串口通讯
请问串口通讯的方法有哪些?哪种效果会更好? --------------------编程问答-------------------- 用mscomm 在232口,容易吧 --------------------编程问答-------------------- vs自带的serialportbar --------------------编程问答-------------------- C#中有mscomm.ocx控件吗?--------------------编程问答-------------------- 先对seriport控件进行初始化:
serialPort1.Close();
serialPort1 .PortName ="COM1";
serialPort1.BaudRate = 4800;
serialPort1.Parity = Parity.Odd;
serialPort1.RtsEnable = true;
serialPort1.DataBits = 8;
serialPort1.ReceivedBytesThreshold = 1;
serialPort1.StopBits = StopBits.One;
serialPort1.Open();
再对sriport的DataReceived进行读取数据格式进行设置:
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
intBytes = serialPort1.BytesToRead;
byte[] bytes = new byte[intBytes];
serialPort1.Read(bytes, 0, intBytes);
StringBuilder sb = new StringBuilder(bytes.Length * 3);
foreach (byte b in bytes )
{
sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
}
str = sb.ToString().ToUpper() ;
dspy_count += 1;
if (dspy_count ==15)
{
dspy_count = 0;
this.Invoke(new EventHandler(delegate { ClearText(); }));
}
this.Invoke(new EventHandler(delegate { SetText(); }));
}
最后还有两个函数用来清楚文本内容和写入文本内容:
private void SetText()
{
seriport.Text += str;
}
private void ClearText()
{
seriport.Text = "";
}
是serialport,不好意思,打错了. --------------------编程问答-------------------- 没有数据的发送吗? --------------------编程问答-------------------- 在工具栏,或添加引用using System.IO.Ports;
主要方法,属性参考:
http://topic.csdn.net/u/20080613/21/99cb7a0f-b535-4e5d-b2fb-1eb771e2f61c.html --------------------编程问答-------------------- serialPort1.PortName = "COM1";//串口名
serialPort1.BaudRate = 4800;//波特率
serialPort1.Parity = Parity.Odd;//校验方式
serialPort1.RtsEnable = true;
serialPort1.DataBits = 8;//数据位
serialPort1.StopBits = StopBits.One;//停止位
serialPort1.ReceivedBytesThreshold = 1;//接收数据时缓冲区的字节数
串口打开
serialPort1.Open();
发送数据:
serialPort1.Write(string text);
serialPort1.Write(byte[] buffer,int offset,int count);
serialPort1.Write(char[] buffer,int offset,int count);
serialPort1.WriteLine(string text);
接收数据:在DataReceived 事件中:
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
while (serialPort1.BytesToRead != 0)
{
int serialPort1.ReadByte();
int serialPort1.Read(byte[] buffer,int offset,int count);
int serialPort1.Read(char[] buffer,int offset,int count);
int serialPort1.ReadChar();
string serialPort1.ReadExisting();
string serialPort1.ReadLine();
string serialPort1.ReadTo(string value);//一直读到指定value字符串;
.........
}
}
--------------------编程问答-------------------- 已经很详细了 --------------------编程问答-------------------- 够用了 --------------------编程问答-------------------- 恩,刚接触.看看.. ... . --------------------编程问答-------------------- 4楼写的非常好,顶一下!哈哈
补充:.NET技术 , C#