C#实现串口通讯




        .NET提供了SerialPort类进行串口通信。

串口主要有以下几个参数: 

1.串口名称(PortName) 

2.波特率(BaudRate)

3.数据位(DataBits)

4.奇偶效应(Parity) 

5.停止位(StopBits)

        使用很简单,连我这个.NET新手也能很快上手.以下是从网上找到并自己修改后的参考代码:

[csharp]  view plain  copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Windows;  
  6. using System.Windows.Controls;  
  7. using System.Windows.Data;  
  8. using System.Windows.Documents;  
  9. using System.Windows.Input;  
  10. using System.Windows.Media;  
  11. using System.Windows.Media.Imaging;  
  12. using System.Windows.Navigation;  
  13. using System.Windows.Shapes;  
  14. using System.IO.Ports;  
  15.   
  16. namespace CsharpComm  
  17.   {  
  18.       /// <summary>  
  19.  /// Window1.xaml 的交互逻辑  
  20.  /// </summary>  
  21.       public partial class Window1 : Window  
  22.       {  
  23.           public Window1()  
  24.           {  
  25.               InitializeComponent();  
  26.           }  
  27.     
  28.           //定义 SerialPort对象  
  29.           SerialPort port1;  
  30.     
  31.           //初始化SerialPort对象方法.PortName为COM口名称,例如"COM1","COM2"等,注意是string类型  
  32.           public void InitCOM(string PortName)  
  33.           {  
  34.               port1 = new SerialPort(PortName);  
  35.               port1.BaudRate = 9600;//波特率  
  36.               port1.Parity  = Parity.None;//无奇偶校验位  
  37.               port1.StopBits = StopBits.Two;//两个停止位  
  38.               port1.Handshake = Handshake.RequestToSend;//控制协议  
  39.               port1.ReceivedBytesThreshold = 4;//设置 DataReceived 事件发生前内部输入缓冲区中的字节数  
  40.               port1.DataReceived += new SerialDataReceivedEventHandler(port1_DataReceived);//DataReceived事件委托  
  41.           }  
  42.     
  43.           //DataReceived事件委托方法  
  44.           private void port1_DataReceived(object sender, SerialDataReceivedEventArgs e)  
  45.           {  
  46.               try  
  47.               {  
  48.                   StringBuilder currentline = new StringBuilder();  
  49.                   //循环接收数据  
  50.                   while (port1.BytesToRead > 0)  
  51.                   {  
  52.                      char ch = (char)port1.ReadByte();  
  53.                       currentline.Append(ch);  
  54.                   }  
  55.                   //在这里对接收到的数据进行处理  
  56.                   //  
  57.                   currentline = new StringBuilder();  
  58.               }  
  59.               catch(Exception ex)  
  60.               {  
  61.                   Console.WriteLine(ex.Message.ToString());  
  62.               }  
  63.     
  64.           }  
  65.     
  66.           //打开串口的方法  
  67.           public void OpenPort()  
  68.           {  
  69.               try  
  70.               {  
  71.                   port1.Open();  
  72.               }  
  73.               catch { }  
  74.               if (port1.IsOpen)  
  75.               {  
  76.                  Console.WriteLine("the port is opened!");  
  77.              }  
  78.              else  
  79.              {  
  80.                  Console.WriteLine("failure to open the port!");  
  81.              }  
  82.          }  
  83.    
  84.          //关闭串口的方法  
  85.          public void ClosePort()  
  86.          {  
  87.              port1.Close();  
  88.              if (!port1.IsOpen)  
  89.              {  
  90.                  Console.WriteLine("the port is already closed!");  
  91.              }  
  92.          }  
  93.    
  94.          //向串口发送数据  
  95.          public void SendCommand(string CommandString)  
  96.          {  
  97.              byte[] WriteBuffer = Encoding.ASCII.GetBytes(CommandString);  
  98.              port1.Write(WriteBuffer, 0, WriteBuffer.Length);  
  99.          }  
  100.            
  101.          //调用实例  
  102.          private void btnOpen_Click(object sender, RoutedEventArgs e)  
  103.          {  
  104.              //我现在用的COM1端口,按需要可改成COM2,COM3  
  105.              InitCOM("COM1");  
  106.              OpenPort();  
  107.          }  
  108.      }  
  109.  }    

        值得注意的是:

1. port1.ReceivedBytesThreshold = 4; ReceivedBytesThreshold属性设置触发一次DataReceived事件时将接收到的数据字节数.由于我的硬件是一次发上来4个字节估设置为4.如果不能正确设置这个属性的话,在SerialPort对象第一次触发DataReceived事件时还是正确的(4个字节),但是从第二次触发之后都是一个字节触发一次DataReceived事件...为什么这样搞不清楚...

2.如果在 DataReceived 委托事件中使用了不是DataReceived委托事件所在线程创建的UI控件,函数等,需要使用到Dispatcher 类来达到线程安全,不然会报错.以下是MSDN中Dispatcher类的例子(XAML),简单明了:

[csharp]  view plain  copy
  1. private delegate void AddTextDelegate(Panel p, String text);  
  2.    
  3.  private void AddText(Panel p, String text)  
  4.  {  
  5.      p.Children.Clear();  
  6.      p.Children.Add(new TextBlock { Text = text });  
  7.  }  
  8.    
  9.  private void TestBeginInvokeWithParameters(Panel p)  
  10.  {  
  11.      if (p.Dispatcher.CheckAccess()) AddText(p, "Added directly.");  
  12.      else p.Dispatcher.BeginInvoke(  
  13.          new AddTextDelegate(AddText), p, "Added by Dispatcher.");  
  14.  }  

        还有一个比较简单的方法。

[csharp]  view plain  copy
  1.   //create a serialport object,with COM1,baudrate 57600,parity bit:none,data bit:8  
  2.             //stopbits:one  
  3. SerialPort sport = new SerialPort("COM1",57600,Parity.None,8,StopBits.One);        
  4.  private void seriallistenfun()  
  5.         {  
  6.  try  
  7.             {  
  8.                       
  9.                     if (sport.IsOpen)  
  10.                     {  
  11.                         sport.Close();  
  12.                         sport.Open(); //open com  
  13.                     }  
  14.                     else  
  15.                     {  
  16.                         sport.Open();//open com  
  17.                     }  
  18.   
  19.                     String data;  
  20.                     string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase); //得到当前路径  
  21.                     path = path+@"/newfile.txt";  
  22.                     FileStream TextFile = File.Open(path, FileMode.Create, FileAccess.Write,FileShare.Read);//创建文件  
  23.                    byte [] Info ;  
  24.                      
  25.                       
  26.                     while (true)  
  27.                     {  
  28.   
  29.   
  30.                         if (sport.BytesToRead != 0)  
  31.                         {  
  32.                             data = sport.ReadExisting().ToString();//读取串口数据  
  33.                             this.BeginInvoke(dfun, new object[] { data });  
  34.                             data += "/r/n";  
  35.                             Info = new UTF8Encoding(true).GetBytes(data);//转换成字节流  
  36.                               
  37.                             TextFile.Write(Info,0,Info.Length);//写入文件  
  38.                             Thread.Sleep(10);  
  39.                         }  
  40.                         else  
  41.                         {  
  42.                             //this.BeginInvoke(dfun, new object[] { "Serialrev:NULL" });  
  43.                             Thread.Sleep(50);  
  44.                         }  
  45.                     }  
  46.             }  
  47.             catch(SystemException e)  
  48.             {  
  49.                 this.BeginInvoke(dfun, new object[] { e.ToString() });  
  50.             }  
  51.               
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#串口介绍以及简单串口通信程序设计实现 源代码和串口程序介绍连接:https://www.cnblogs.com/JiYF/p/6618696.html 本站积分太贵,自己变得。。直接到连接地址下载代码 周末,没事干,写个简单的串口通信工具,也算是本周末曾来过,废话不多,直接到主题 串口介绍   串行接口简称串口,也称串行通信接口或串行通讯接口(通常指COM接口),是采用串行通信方式的扩展接口。(至于再详细,自己百度) 串口应用:   工业领域使用较多,比如:数据采集,设备控制等等,好多都是用串口通信来实现!你要是细心的话,你会发现,目前家用国网智能电能表就具备RS485通信总线(串行总线的一种)与RS232可以相互转化(当然一般,非专业的谁也不会闲的蛋疼,趴电表上瞎看,最多也就看看走了多少度电) RS232 DB9介绍: 1.示意图 2.针脚介绍: 载波检测(DCD) 接受数据(RXD) 发出数据(TXD) 数据终端准备好(DTR) 信号地线(SG) 数据准备好(DSR) 请求发送(RTS) 清除发送(CTS) 振铃指示(RI) 3.实物图: 以下是我购买XX公司的一个usb转串口线:这个头就是一个公头,另一端是一个usb口 笨小孩串口工具运行图: 1.开启程序 2.发送一行字符串HelloBenXH,直接将针脚的发送和接收链接起来就可以测试了(针脚2 接受数据(RXD) 和3 发出数据(TXD))直接链接, C#代码实现:采用SerialPort 1.实例化一个SerialPort [csharp] view plain copy 在CODE上查看代码片派生到我的代码片 private SerialPort ComDevice = new SerialPort(); 2.初始化参数绑定接收数据事件 [csharp] view plain copy 在CODE上查看代码片派生到我的代码片 public void init() { btnSend.Enabled = false; cbbComList.Items.AddRange(SerialPort.GetPortNames()); if (cbbComList.Items.Count > 0) { cbbComList.SelectedIndex = 0; } cbbBaudRate.SelectedIndex = 5; cbbDataBits.SelectedIndex = 0; cbbParity.SelectedIndex = 0; cbbStopBits.SelectedIndex = 0; pictureBox1.BackgroundImage = Properties.Resources.red; ComDevice.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived);//绑定事件 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值