转:C#串口编程
本文用來(lái)簡(jiǎn)單介紹一下C#串口編程的知識(shí),主要以實(shí)例為內(nèi)容。
凡是串口設(shè)備和計(jì)算機(jī)交互的時(shí)候都用到串口,在C#中我們?nèi)绾蝸?lái)操作串口呢?
大話串口工作原理
實(shí)際串口是用來(lái)和外部設(shè)備進(jìn)行交換數(shù)據(jù)的,我抽象出下面一個(gè)圖形,來(lái)簡(jiǎn)單解釋一下串口的原理。
上圖表示一個(gè)COM口,可以往外傳輸數(shù)據(jù)流,也可以往里傳輸數(shù)據(jù)流,我們?nèi)绻氆@得傳入的數(shù)據(jù)流只需要監(jiān)聽往計(jì)算機(jī)的數(shù)據(jù)流即可。
虛擬串口軟件
當(dāng)我們沒有設(shè)備時(shí)我們可以用虛擬串口軟件來(lái)模擬串口操作。下面我來(lái)介紹一款軟件?VSPM 虛擬串口軟件。大家可以去天空軟件站下載,地址請(qǐng)點(diǎn)擊我。
下載下來(lái)安裝成功后如下圖所示:
然后你就點(diǎn)擊添加端口,我上圖中的COM2和COM3就是VSDM添加的,這個(gè)時(shí)候你把COM2和Com3看做是一個(gè)真實(shí)的串口,然后用兩個(gè)軟件連接,就相當(dāng)于一個(gè)串口了,我用一個(gè)串口測(cè)試器和我們自己編寫的軟件進(jìn)行測(cè)試:
如下圖所示,我們的串口測(cè)試器已經(jīng)連接到COM3上了,
監(jiān)聽串口程序
直接上代碼,在控制臺(tái)程序中添加如下源碼就可以直接運(yùn)行了:
using System; using System.IO.Ports; using System.Text; namespace PortDataReceived {class PortDataReceived{public static void Main(){SerialPort mySerialPort = new SerialPort("COM2");mySerialPort.BaudRate = 9600;mySerialPort.Parity = Parity.None;mySerialPort.StopBits = StopBits.One;mySerialPort.DataBits = 8;mySerialPort.Handshake = Handshake.None;mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); mySerialPort.Open(); Console.WriteLine("Press any key to continue..."); Console.WriteLine(); Console.ReadKey(); mySerialPort.Close();}private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e){SerialPort sp = (SerialPort)sender; string indata = sp.ReadExisting(); Console.WriteLine("Data Received:"); Console.Write(StrToHex(indata));}public static string StrToHex(string mStr) //返回處理后的十六進(jìn)制字符串 {return BitConverter.ToString(ASCIIEncoding.Default.GetBytes(mStr)).Replace("-", " ");}} }運(yùn)行結(jié)果如下圖:
數(shù)據(jù)完全正確,發(fā)出的數(shù)據(jù)和接受的數(shù)據(jù)都一樣,而且此時(shí)VSDM的界面有簡(jiǎn)單變化:
總結(jié):本文寫了一個(gè)用虛擬串口軟件編寫的C#串口編程實(shí)例。希望對(duì)大家有幫助。
除非注明,木杉博客文章均為原創(chuàng)并采用BY-NC-SA協(xié)議進(jìn)行授權(quán)原創(chuàng)文章,轉(zhuǎn)載請(qǐng)注明: 轉(zhuǎn)載自木杉博客
轉(zhuǎn)載于:https://www.cnblogs.com/lusunqing/p/3449594.html
總結(jié)
- 上一篇: oracle数据库常用的函数总结
- 下一篇: c# char unsigned_dll