http://blog.sina.com.cn/s/blog_9faf08510101dhk0.html
2013
private void serialPort1_DataReceived(objectsender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
//先讀取下位機(jī)發(fā)來的數(shù)據(jù),然后就比較
//如果是呼叫我,則回復(fù)他
//下位機(jī)接到回復(fù)后就發(fā)數(shù)據(jù)過來,這邊要接收
//吧接受的數(shù)據(jù)與該用戶的之前的數(shù)據(jù)進(jìn)行比較
//如果是減肥成功了,就form5,否則就form4
//最后就插入該用戶剛剛測試的數(shù)據(jù)
if (serialPort1.IsOpen == false)
{
return;
}
Thread.Sleep(2000);
int c = serialPort1.BytesToRead; //獲取緩沖區(qū)中的字節(jié)數(shù)
//int n = serialPort1.ReadBufferSize;
byte[] buf = new byte[c];//聲明一個(gè)臨時(shí)數(shù)組存儲(chǔ)當(dāng)前來的串口數(shù)據(jù)
StringBuilder strbuilder = new StringBuilder(buf.Length);
serialPort1.Read(buf, 0, c);//讀取緩沖數(shù)
//data =System.Text.Encoding.ASCII.GetString(buf);//將RevData中的數(shù)據(jù)轉(zhuǎn)換成字符串
string str2="";
int data = 0;
if (c == 1)
{
foreach (byte b in buf)
{
strbuilder.Append(b.ToString("X2"));//如果兩個(gè)數(shù)10和26,正常情況十六進(jìn)制顯示0xA、0x1A,這樣看起來不整齊,為了好看,我們可以指定X2,這樣顯示出來就是:0x0A、0x1A。
}
data = 0;