c# 串口数据获取、发送,解决乱码
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
namespace CYSY.Simulation
{
public partial class Serial : Form
{
public Serial()
{
InitializeComponent();
settextevent += set;
}
private SerialPort device = new SerialPort();
StringBuilder builder = new StringBuilder();
private void button1_Click(object sender, EventArgs e)
{
if (device.IsOpen)
{
if (!string.IsNullOrEmpty(this.textBox1.Text))
{
//(this. + "\r\n");//发送的数据有乱码问题
string cmd = this.textBox1.Text;
byte[] SendBytes = null;
Encoding chs = Encoding.GetEncoding("utf-8");
byte[] bytes = chs.GetBytes(cmd);
string str = "";
for (int i = 0; i < bytes.Length; i++)
{
str += string.Format("{0:X2}", bytes[i]);
}
List<string> SendDataList = new List<string>();
for (int i = 0; i < str.Length; i = i + 2)
{
SendDataList.Add(str.Substring(i, 2));
}
SendDataList.Add("0D");
SendBytes = new byte[SendDataList.Count];
for (int j = 0; j < SendBytes.Length; j++)
{
SendBytes[j] = (byte)(Convert.ToInt32(SendDataList[j], 16));
}
device.Write(SendBytes, 0, SendBytes.Length);//发送数据
}
else
{
MessageBox.Show("数据为空");
}
}
else
{
MessageBox.Show("COM1未打开!");
}
}
public delegate void settext(string text);
public event settext settextevent;
public void set(string text)
{
this.textBox2.Text = text;
}
//在接收到了ReceivedBytesThreshold设置的字符个数或接收到了文件结束字符并将其放入了输入缓冲区时被触发
public void device_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Console.WriteLine("接收中...");
int n = device.BytesToRead;
byte[] buf = new byte[n]; //声明临时数组存储串口数据
device.Read(buf, 0, n); //读取缓冲数据
builder.Remove(0, builder.Length); //清除字符串构造器的内容
builder.Append(Encoding.Default.GetString(buf));
string comdata = builder.ToString();
Console.WriteLine("data:" + comdata);
if(!string.IsNullOrEmpty(comdata)) this.Invoke(settextevent, comdata);
}
private void button2_Click(object sender, EventArgs e)
{
if (!device.IsOpen)
{
try
{
//串口号
device.PortName = "COM1";
//波特率
device.BaudRate = 115200;
//数据位
device.DataBits = 8;
//停止位
device.StopBits = StopBits.One;
//奇偶校验位
device.Parity = Parity.Even;
//DataReceived事件发送前,内部缓冲区里的字符数
device.ReceivedBytesThreshold = 1;
device.RtsEnable = true; device.DtrEnable = true; device.ReadTimeout = 3000;
// = false;
//表示将处理 对象的数据接收事件的方法。
device.DataReceived += new SerialDataReceivedEventHandler(device_DataReceived);
//打开
device.Open();
MessageBox.Show("COM1打开成功!");
}
catch (Exception ex)
{
MessageBox.Show("COM1打开失败!");
}
}
else
{
MessageBox.Show("COM1打开成功!");
}
}
private void button3_Click(object sender, EventArgs e)
{
if (device.IsOpen)
{
device.Close();
MessageBox.Show("COM1关闭成功!");
}
}
}
}