C# SerialPort 发送接收的问题
usingSystem.IO.Ports;namespacecom{publicpartialclassForm1:Form{SerialPortserialPort1=...
using System.IO.Ports;
namespace com
{
public partial class Form1 : Form
{
SerialPort serialPort1 = new SerialPort();
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
SerialPort serialPort1 = new SerialPort();
serialPort1.PortName = "COM3";
serialPort1.BaudRate = 9600;
try
{
serialPort1.Open();
}
catch (Exception ex)
{
serialPort1 = new SerialPort();
MessageBox.Show(ex.Message);
}
byte[] data = Encoding.Unicode.GetBytes(textBox1.Text);
string str = Convert.ToBase64String(data);
serialPort1.WriteLine(str);
MessageBox.Show("数据发送成功!", "系统提示");
}
private void button2_Click(object sender, EventArgs e)
{
if (!serialPort1.IsOpen)
{
MessageBox.Show("COM异常关闭");
}
serialPort1.ReadLine();
byte[] data = Convert.FromBase64String(serialPort1.ReadLine());
textBox2.Text = Encoding.Unicode.GetString(data);
serialPort1.Close();
MessageBox.Show("数据接收成功!", "系统提示");
}
}
}
button2接收发现com被关闭了,为什么会这样呢?谢谢 展开
namespace com
{
public partial class Form1 : Form
{
SerialPort serialPort1 = new SerialPort();
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
SerialPort serialPort1 = new SerialPort();
serialPort1.PortName = "COM3";
serialPort1.BaudRate = 9600;
try
{
serialPort1.Open();
}
catch (Exception ex)
{
serialPort1 = new SerialPort();
MessageBox.Show(ex.Message);
}
byte[] data = Encoding.Unicode.GetBytes(textBox1.Text);
string str = Convert.ToBase64String(data);
serialPort1.WriteLine(str);
MessageBox.Show("数据发送成功!", "系统提示");
}
private void button2_Click(object sender, EventArgs e)
{
if (!serialPort1.IsOpen)
{
MessageBox.Show("COM异常关闭");
}
serialPort1.ReadLine();
byte[] data = Convert.FromBase64String(serialPort1.ReadLine());
textBox2.Text = Encoding.Unicode.GetString(data);
serialPort1.Close();
MessageBox.Show("数据接收成功!", "系统提示");
}
}
}
button2接收发现com被关闭了,为什么会这样呢?谢谢 展开
1个回答
展开全部
private void button1_Click(object sender, EventArgs e)
{
SerialPort serialPort1 = new SerialPort();
button1_click 中你又定义了一个 私有的serialport1并进行了打开,而全局(即界面上)放置的 serpalPort1并未进行任何操作(如打开),所以在 button2_click操作它时是未打开状态。
删除button1_click中的第一行 SerialPort serialPort1 = new SerialPort(); 编译成功就可以了
{
SerialPort serialPort1 = new SerialPort();
button1_click 中你又定义了一个 私有的serialport1并进行了打开,而全局(即界面上)放置的 serpalPort1并未进行任何操作(如打开),所以在 button2_click操作它时是未打开状态。
删除button1_click中的第一行 SerialPort serialPort1 = new SerialPort(); 编译成功就可以了
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询