作者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