本文主要是介绍C#实现串口通信(自身留稿方便以后查看),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
连接串口程序,发起握手,传递参数和接收参数的代码
SerialPort serialPort = new SerialPort();
private void button1_Click(object sender, EventArgs e)
{
try
{
string[] portName = SerialPort.GetPortNames();
serialPort.PortName = "COM3";
serialPort.BaudRate = 115200;
serialPort.DataBits = 8;
serialPort.Parity = Parity.None;
serialPort.StopBits = StopBits.One;
serialPort.Open();
Control.CheckForIllegalCrossThreadCalls = false; //强制不检查跨线程的调用是否合法,为了能在订阅返回时修改label的Text
serialPort.DataReceived += serialPort_DataReceived;
//adjustScreenBrightness(30);
label1.Text = "串口打开成功";
label1.Text = "开始建立握手";
handshake();
//serialPort.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
serialPort.Close();
}
}
private void handshake()//建立握手
{
try
{
if (serialPort.IsOpen)
{
byte[] data1 = new byte[6];
data1[0] = 0xAA;
data1[1] = 0x00;
data1[2] = 0xCC;
data1[3] = 0x33;
data1[4] = 0xC3;
data1[5] = 0x3C;
serialPort.Write(data1, 0, 6);
}
else
{
label1.Text = "串口在发送握手时被关闭";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
serialPort.Close();
}
}
private void adjustScreenBrightness(Int32 brightness)//调节屏幕亮度
{
if (serialPort.IsOpen)
{
byte[] data1 = new byte[7];
data1[0] = 0xAA;
data1[1] = 0x5F;
data1[2] = Convert.ToByte(brightness);
data1[3] = 0xCC;
data1[4] = 0x33;
data1[5] = 0xC3;
data1[6] = 0x3C;
serialPort.Write(data1, 0, 7);
}
else
{
label1.Text = "串口在调节亮度时发现被关闭";
}
}
void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
serialPort.DataReceived -= serialPort_DataReceived;
if (serialPort.IsOpen)
{
try
{
Byte[] receivedData = new Byte[serialPort.BytesToRead]; //创建接收字节数组
serialPort.Read(receivedData, 0, receivedData.Length); //读取数据
serialPort.DiscardInBuffer(); //清空SerialPort控件的Buffer
string strRcv = null;
for (int i = 0; i < receivedData.Length; i++) //窗体显示
{
strRcv += receivedData[i].ToString("X2"); //16进制显示
}
if (strRcv == "AA004F4B35020101CC33C33C")
label1.Text = "握手建立成功";
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "出错提示");
serialPort.Close();
}
}
else
{
label1.Text = "串口在握手返回时被关闭";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
serialPort.Close();
}
}
这篇关于C#实现串口通信(自身留稿方便以后查看)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!