using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.IO.Ports; namespace _2 { public partial class Form1 : Form { SerialPort spReceive = new SerialPort (); delegate void UpdateTextEventHandler(string text); UpdateTextEventHandler updateText; public Form1() { InitializeComponent(); updateText = new UpdateTextEventHandler(UpdateTextBox); spReceive.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(spReceive_DataReceived ); } private void Form1_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { spReceive.PortName = "COM1"; spReceive.BaudRate = 2400; spReceive.DataBits = 8; spReceive.StopBits = StopBits .One ; spReceive.Parity = Parity .Even ; spReceive.Open(); spReceive.Write("FE FE FE 68 AA AA AA AA AA AA 68 13 00"); string data = spReceive.ReadExisting(); textBox1.Text =data ; spReceive.Close(); } public void spReceive_DataReceived(object sender,System .IO .Ports .SerialDataReceivedEventArgs e) { byte[]readBuffer = new byte[spReceive .ReadBufferSize]; spReceive.Read(readBuffer,0,readBuffer.Length); this.Invoke(updateText ,new string []{Encoding .Unicode .GetString (readBuffer )}); string readString = spReceive.ReadExisting(); this.Invoke(updateText ,new string []{readString }); } private void UpdateTextBox(string text) { textBox1.Text =text; } } }
为什么接收不到数据.哪位高人帮看看上面代码有什么问题啊.向串口发送一串16进制数字,然后接收串口返回的数据.
你串口设置的和硬件的一致不?先用串口调试软件发帧看看能不能正常接收。
一段代码什么意思?没有问题???
先定义一个串口类,往串口中写数据,然后发送命令,当接收到数据时,就将收到的数据字节对应的Unicode码数据显示在textBox1文本框中