[問題] RS232傳輸與計時
我最近在玩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)
→
09/23 22:07, , 1F
09/23 22:07, 1F
→
09/24 03:56, , 2F
09/24 03:56, 2F
→
09/24 05:09, , 3F
09/24 05:09, 3F
→
09/24 05:09, , 4F
09/24 05:09, 4F
推
09/29 16:42, , 5F
09/29 16:42, 5F
→
09/30 20:55, , 6F
09/30 20:55, 6F
→
09/30 21:07, , 7F
09/30 21:07, 7F