求c#serialport类实现串口通信的源代码
我想用c#的serialport做一个串口通信的类,向串口发一个AT命令,接受到"OK"并显示出来,谁能提供源代码?我自己做了一个这样的例子,可是在读数据的时候(我是用的同步读)死在那个地方了,怎么也不往下执行了。
下面是我程序的源代码:
using System.IO.Ports
SerialPort sp = new SerialPort("com1");
sp.Open();
sp.Write("at E0\r");
sp.Write("at\r");
char[] buffer = new char[10];
sp.Read(buffer,0,buffer.length);---就到这一句的时候怎么也读不出来了,程序死了。
console.write(buffer);
--------------------编程问答-------------------- 我的邮箱是infobox0532@126.com,infobox0531@163.com,谁有给我发一下吧,谢谢了!! --------------------编程问答-------------------- 转一段代码给你看看
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
namespace TestSerialPort
{
public partial class frmTESTSerialPort : Form
{
public frmTESTSerialPort()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
}
private Button button1;
private TextBox txtSend;
private TextBox txtReceive;
private Label label1;
private Label label2;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.txtSend = new System.Windows.Forms.TextBox();
this.txtReceive = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(440, 379);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "发送";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// txtSend
//
this.txtSend.Location = new System.Drawing.Point(59, 12);
this.txtSend.Multiline = true;
this.txtSend.Name = "txtSend";
this.txtSend.Size = new System.Drawing.Size(456, 164);
this.txtSend.TabIndex = 2;
//
// txtReceive
//
this.txtReceive.Location = new System.Drawing.Point(59, 200);
this.txtReceive.Multiline = true;
this.txtReceive.Name = "txtReceive";
this.txtReceive.Size = new System.Drawing.Size(456, 164);
this.txtReceive.TabIndex = 2;
//
// label1
//
this.label1.Location = new System.Drawing.Point(13, 15);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(41, 12);
this.label1.TabIndex = 0;
this.label1.Text = "发送";
//
// label2
//
this.label2.Location = new System.Drawing.Point(13, 213);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(41, 12);
this.label2.TabIndex = 0;
this.label2.Text = "接收";
//
// frmTESTSerialPort
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(546, 434);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.txtReceive);
this.Controls.Add(this.txtSend);
this.Controls.Add(this.button1);
this.Name = "frmTESTSerialPort";
this.Text = "串口试验";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
--------------------编程问答-------------------- private void button1_Click(object sender, EventArgs e)
{
//实例化串口对象(默认:COMM1,9600,e,8,1)
SerialPort serialPort1 = new SerialPort();
//更改参数
serialPort1.PortName = "COM1";
serialPort1.BaudRate = 19200;
serialPort1.Parity = Parity.Odd;
serialPort1.StopBits = StopBits.Two;
//上述步骤可以用在实例化时调用SerialPort类的重载构造函数
//SerialPort serialPort = new SerialPort("COM1", 19200, Parity.Odd, StopBits.Two);
//打开串口(打开串口后不能修改端口名,波特率等参数,修改参数要在串口关闭后修改)
serialPort1.Open();
//发送数据
SendStringData(serialPort1);
//也可用字节的形式发送数据
//SendBytesData(serialPort1);
//开启接收数据线程
ReceiveData(serialPort1);
}
//发送字符串数据
private void SendStringData(SerialPort serialPort)
{
serialPort.Write(txtSend.Text);
}
/// <summary>
/// 开启接收数据线程
/// </summary>
private void ReceiveData(SerialPort serialPort)
{
//同步阻塞接收数据线程
Thread threadReceive=new Thread(new ParameterizedThreadStart(SynReceiveData));
threadReceive.Start(serialPort);
//也可用异步接收数据线程
//Thread threadReceiveSub = new Thread(new ParameterizedThreadStart(AsyReceiveData));
//threadReceiveSub.Start(serialPort);
}
//发送二进制数据
private void SendBytesData(SerialPort serialPort)
{
byte[] bytesSend=System.Text.Encoding.Default.GetBytes(txtSend.Text );
serialPort.Write(bytesSend, 0, bytesSend.Length);
}
//同步阻塞读取
private void SynReceiveData(object serialPortobj)
{
SerialPort serialPort = (SerialPort)serialPortobj;
System.Threading.Thread.Sleep(0);
serialPort.ReadTimeout = 1000;
try
{
//阻塞到读取数据或超时(这里为2秒)
byte firstByte=Convert.ToByte(serialPort.ReadByte());
int bytesRead=serialPort.BytesToRead ;
byte[] bytesData=new byte[bytesRead+1];
bytesData[0] = firstByte;
for (int i = 1; i <=bytesRead; i++)
bytesData[i] = Convert.ToByte( serialPort.ReadByte());
txtReceive.Text = System.Text.Encoding.Default.GetString(bytesData);
}
catch(Exception e)
{
MessageBox.Show(e.Message);
//处理超时错误
}
serialPort.Close();
}
//异步读取
private void AsyReceiveData(object serialPortobj)
{
SerialPort serialPort = (SerialPort)serialPortobj;
System.Threading.Thread.Sleep(500);
try
{
txtReceive.Text = serialPort.ReadExisting();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
//处理错误
}
serialPort.Close();
}
}
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmTESTSerialPort());
}
}
}
--------------------编程问答-------------------- 顶顶顶,我顶 --------------------编程问答-------------------- Hi,楼主你的问题解决了吗,如果解决了能不能告诉我呢.
我正好现在也在弄这个. 对此不大清楚.
liuyingting110@163.com
thanks --------------------编程问答-------------------- 我也碰到这个问题了.就是readline的时候死在那里了. --------------------编程问答-------------------- 请问你以上的代码在asp.net上能使用吗?serialport类在asp.net中能实现串口通信吗? --------------------编程问答-------------------- 留个记号,备案之 --------------------编程问答-------------------- 楼主,你只需要把DataReceived事件搞清楚就OK了,这是关键. --------------------编程问答-------------------- 感谢分享。学习一下。 --------------------编程问答-------------------- 请确定你的通信参数正确. 波特率之类的. 我记得当初卡在这里卡了N久...... --------------------编程问答-------------------- 谁可以帮忙回答这个问题呀
我感觉SerialPort 控件有问题
http://topic.csdn.net/u/20081231/17/b1e674d6-a0b1-445c-936f-65653022d3a3.html
借楼主的地盘一用
谢谢 --------------------编程问答-------------------- 这个程序也是在readline的时候报错,serialPort捕捉到TimeoutException,操作超时,怎么回事啊,怎么解决啊,谢谢了 --------------------编程问答--------------------
--------------------编程问答-------------------- 串口的参数要设置正确,如波特率,数据位等,
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.IO.Ports;
using System.IO.Compression;
using System.IO.IsolatedStorage;
namespace FortuneWeb.Common.Port
{
/// <summary>
/// 1~9 串口的名称是 "COMx:",>9的以前用\\\\.\\COMx:比较好使,但是在moxa 661设备上却不行,要用如下格式"$device\\COM" + PortNo.ToString() + "\0",也许这是moxa修改了相应的串口驱动。
/// </summary>
public class PortData
{
public event PortDataReceivedEventHandle Received;
public event SerialErrorReceivedEventHandler Error;
public SerialPort port;
public bool ReceiveEventFlag = false; //接收事件是否有效 false表示有效
//public PortData(string sPortName, int baudrate, Parity parity, SerialInte易做图ce.SerialMode mode)
public PortData(string sPortName, int baudrate, Parity parity)
{
port = new SerialPort(sPortName, baudrate, parity, 8, StopBits.One);
port.RtsEnable = true;
port.ReadTimeout = 3000;
port.DataReceived += new SerialDataReceivedEventHandler(DataReceived);
port.ErrorReceived += new SerialErrorReceivedEventHandler(ErrorEvent);
}
~PortData()
{
Close();
}
public void Open()
{
if (!port.IsOpen)
{
port.Open();
}
}
public void Close()
{
if (port.IsOpen)
{
port.Close();
}
}
//数据发送
public void SendData(byte[] data)
{
if (port.IsOpen)
{
port.Write(data, 0, data.Length);
}
}
public void SendData(byte[] data, int offset, int count)
{
if (port.IsOpen)
{
port.Write(data, offset, count);
}
}
//发送命令
public int SendCommand(byte[] SendData, ref byte[] ReceiveData, int Overtime)
{
if (port.IsOpen)
{
ReceiveEventFlag = true; //关闭接收事件
port.DiscardInBuffer(); //清空接收缓冲区
port.Write(SendData, 0, SendData.Length);
int num = 0, ret = 0;
while (num++ < Overtime)
{
if (port.BytesToRead >= ReceiveData.Length) break;
System.Threading.Thread.Sleep(1);
}
if (port.BytesToRead >= ReceiveData.Length)
ret = port.Read(ReceiveData, 0, ReceiveData.Length);
ReceiveEventFlag = false; //打开事件
return ret;
}
return -1;
}
public void ErrorEvent(object sender, SerialErrorReceivedEventArgs e)
{
if (Error != null) Error(sender, e);
}
//数据接收
public void DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//禁止接收事件时直接退出
if (ReceiveEventFlag)
{
return;
}
var data = new byte[port.BytesToRead];
port.Read(data, 0, data.Length);
if (Received != null) Received(sender, new PortDataReciveEventArgs(data));
}
public bool IsOpen()
{
return port.IsOpen;
}
}
public delegate void PortDataReceivedEventHandle(object sender, PortDataReciveEventArgs e);
public class PortDataReciveEventArgs : EventArgs
{
public PortDataReciveEventArgs()
{
this.data = null;
}
public PortDataReciveEventArgs(byte[] data)
{
this.data = data;
}
private byte[] data;
public byte[] Data
{
get { return data; }
set { data = value; }
}
}
}
参考FortuneBase中FortuneWeb\Common\Port
www.cnblogs.com/mail-ricklee
还有 设置下 串口的 writetimeout, readtimeout
同步方法可以用readto(),异步可以用 datareceiving事件 --------------------编程问答-------------------- 我们怎么用上面的那个程序接不到数据呢?是我弄错了了吗?我想用字节来接收,因为用字符是接不到汉字的!你看看是不是有问题呢?
--------------------编程问答--------------------
private void button1_Click(object sender, EventArgs e)
{
serialPort1.PortName = "COM1";
serialPort1.BaudRate = 9600;
serialPort1.Open();
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)
{
byte[] data = Convert.FromBase64String(serialPort1.ReadLine());
textBox2.Text = Encoding.Unicode.GetString(data);
serialPort1.Close();
MessageBox.Show("数据接收成功!","系统提示");
}
一个简单的东西,希望对你有启发! --------------------编程问答-------------------- 首先谢谢你,但是你用的是控件来执行的发送和接收,我是实时的发送和接收,也就是启用委托,和辅助线程!
Datareceive事件 --------------------编程问答-------------------- 大侠!请帮我看看下面的代码:
string AA = txtneirong.Text;
FileStream fs1;
byte[] showarray = new byte[15];
int lstcount = AA.Length, hzcode = 0;
int bb = 0; Int64 offVar = 0;
for (int int1 = 0; int1 <= lstcount - 1; int1++)
{
fs1 = new FileStream(@"ASC16", FileMode.Open, FileAccess.Read);//读取字库
sp.Open();
byte[] showpara = new byte[2];
showpara[0] = 4;//=4 意思是LED显示的模式为固定
showpara[1] = Convert.ToByte(int1 + 1);//表示LED显示的长度
string h = "HellA"; //发送HellA 表示与LED连接通讯信号
sp.Write(h);
sp.Write(showpara, 0, 2);
hzcode = (int)Encoding.ASCII.GetBytes(AA)[bb];
if (hzcode > -1)
{
offVar = hzcode * 16 + 1;
fs1.Seek(offVar, SeekOrigin.Begin);
fs1.Read(showarray, 0, 15);
bb = bb + 1;
}
byte[] aaa=new byte[15] ;
sp.Write(showarray, 0, showarray.Length);
Thread.Sleep(50);
sp.Write(showarray, 0, showarray.Length);
sp.Close();
fs1.Close();
}
意思:假如AA=abc12333 的话
串口发送命令后将abc12333 显示在LED显示屏上面
问题是:abc12333 都是显示在LED显示屏的第一个位置上面 不能按顺序显示出来也就是说显示a之后,再显示b时 b就把a覆盖掉。。。
请大侠们帮我看看!!!谢谢 主要是sp.Write(showarray, 0, showarray.Length);
有误,,不知道要怎么写 --------------------编程问答--------------------
using System;--------------------编程问答-------------------- ReadLine()就死了,是怎么回事儿啊?有人可以解答吗? --------------------编程问答-------------------- 我也是啊。我是多线程做的,每次到这里就操作超时的异常抛出来啊。急啊........ --------------------编程问答-------------------- C# 串口操作系列(4) -- 协议篇,文本协议数据解析(2010-8-20)
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.Ports;
using System.Threading;
namespace 蓝牙
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SerialPort serialPort1 = new SerialPort();
private void Form1_Load(object sender, EventArgs e)
{
string [] str=SerialPort.GetPortNames();
foreach (string Portname in str)
{
this.comboBox1.Items.Add(Portname);
}
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
}
private void ReceiveData()
{
string Message = serialPort1.ReadLine();
}
private void button1_Click(object sender, EventArgs e)
{
serialPort1.PortName = "COM1";
serialPort1.BaudRate = 10000;
serialPort1.Open();
try
{
byte[] data = Encoding.Unicode.GetBytes("你个死串口收到没");
string str = Convert.ToBase64String(data);
serialPort1.WriteLine(str);
MessageBox.Show("数据发送成功!", "系统提示");
}
catch
{
MessageBox.Show("数据发送失败!", "系统提示");
}
}
void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
MessageBox.Show(serialPort1.ReadExisting(),"收到啦");
}
private void button2_Click(object sender, EventArgs e)
{
}
}
}
C# 串口操作系列(3) -- 协议篇,二进制协议数据解析(2010-8-20)
C# 串口操作系列(2) -- 入门篇,为什么我的串口程序在关闭串口时候会死锁 ?(2010-8-20)
C# 串口操作系列(1) -- 入门篇,一个标准的,简陋的串口例子。(2010-8-20)
全部
补充:.NET技术 , C#