作者laevatain103 (RICO)
看板C_Sharp
標題[問題] RS232傳輸與計時
時間Wed Sep 23 19:35:45 2009
我最近在玩8051與PC連線,所以使用到了RS232來進行溝通
← data
┌───┐------------┌─┐
│ 8051 │ │PC│
└───┘------------└─┘
data →
問題一
我使用計時來計算來回的時間差
可是偶爾會有0ms情形發生!!
問題二
我傳一次資料,但是我的接收事件會起2次(我51程式內定只會回傳一次
我的程式
//按下按鈕傳資料 開始計時
private void button1_Click(object sender, EventArgs e){
try
{
//Convert the user's string of hex digits (ex: B4 CA E2)
to a byte array
byte[] data = HexStringToByteArray(textBox1.Text);
// Send the binary data out the port
serialPort1.Write(data, 0, data.Length);
//計時開始
TimeSpan st = new TimeSpan(DateTime.Now.Ticks);
textBox4.Text = st.TotalMilliseconds+"";
global.sendtime = st.TotalMilliseconds;
textBox4.Text = global.sendtime + "";
}
catch (Exception){
MessageBox.Show("非16進制字串");
}
}
//接收資料的事件
private void serialPort1_DataReceived(object sender,
SerialDataReceivedEventArgs e)
{
if (serialPort1.BytesToRead != 0)
{
byte[] data = new byte[serialPort1.BytesToRead];
serialPort1.Read(data, 0, data.Length);
//計時結束
TimeSpan rt = new TimeSpan(DateTime.Now.Ticks);
global.receivetime = rt.TotalMilliseconds;
int i;
string tmp = "";
for (i = 0; i < data.Length; i++)
{
tmp += data[i]+";";
}
this.Invoke((incoming)delegate
{
textBox2.Text = tmp;
textBox3.Text += (global.receivetime-global.sendtime)+
"Milliseconds" + "\n";
textBox5.Text =rt.TotalMilliseconds + "";
});
}
}
謝謝!讓你那麼辛苦看那麼長的程式...
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.128.142.122
※ 編輯: laevatain103 來自: 114.33.51.36 (09/23 22:04)
1F:→ laevatain103:PO錯阪?我真的是用C#寫= = 09/23 22:07
2F:→ EricTsai:StopWatch比較精準 09/24 03:56
3F:→ laevatain103:剛才到的說~~~正在爆肝= = 09/24 05:09
4F:→ laevatain103:3Q 09/24 05:09
5F:推 tomex:資料讀取2次,可能是傳輪delay或資料批量的關係,故要先收集 09/29 16:42
6F:→ laevatain103:感謝~收到了! 09/30 20:55
7F:→ laevatain103:要如何做收集?= = 09/30 21:07