close
(1) RJ45轉RS232
(2) RS232轉USB
(3) 電子鐘<->RJ45轉RS232轉換器接線 如下
(4)電子鐘電源接上後, 預設0:00.00
系統接線圖如下
新增一個Windows Form應用程式
GUI介面設計如下
電子鐘RS232通訊協定
1: Byte0 Byte1 Byte2 Byte3 Byte4 Byte5 Byte6 Byte7 Byte8 Byte9
2: --------------------------------------------------------------------
3: 0xFF 0xFF 0xFF 0x00 0x00 <--倒數剩餘秒數---> 0xFE 0xFE
4:
5: 倒數剩餘秒數=Byte5*65536 + Byte6*256 + Byte7
6:
7: 例如 1小時10分10秒(倒數剩餘秒數=4210秒)===>Byte5=0x00, Byte6=0x10, Byte7=0x72
使用命名空間
1: using System.Threading;
2: using System.IO.Ports;
變數宣告
1: enum ProcStatus { Running, Pause, Stop };
2:
3: // 變數宣告
4: Thread gProcThread; // 通訊執行緒
5: ProcStatus gProcThreadStatus;
6: SerialPort comport; // 串列通訊物件
7: bool _shouldStop = false; // 是否停止執行
開始按鈕
1: private void InputProcControlStartBtn_Click(object sender, EventArgs e)
2: {
3: ProcControlPauseBtn.Enabled = true;
4: ProcControlStopBtn.Enabled = true;
5:
6: string com = comboBox1.Text;
7: int baudrate = int.Parse(comboBox2.Text);
8: int parity = comboBox3.SelectedIndex;
9: int databits = int.Parse(comboBox4.Text);
10: int stopbits = int.Parse(comboBox5.Text);
11: comport = new SerialPort(com, baudrate, (Parity)parity, databits, (StopBits)stopbits);
12: try
13: {
14: if (!comport.IsOpen)
15: comport.Open();
16: _shouldStop = false;
17: gProcThread = new Thread(new ThreadStart(ProcControl));
18: gProcThread.Start();
19: }
20: catch
21: {
22: serialPort1.Close();
23: }
24: }
其中ProcControl定義如下:
1: private void ProcControl()
2: {
3: uint Start = 3600;
4: uint i=Start;
5: uint hour;
6: uint min;
7: uint sec;
8: gProcThreadStatus = ProcStatus.Running;
9: byte[] data = new byte[10]{ 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xfe };
10: while(!_shouldStop){
11: hour = i/65536;
12: min = i/256;
13: sec = i - hour*65536 - min*256;
14: data[5] = (byte) hour;
15: data[6] = (byte) min;
16: data[7] = (byte) sec;
17: comport.Write(data, 0, data.Length);
18: Thread.Sleep(1000);
19: i--;
20: if(i<=0) i=Start;
21: }
22: }
暫停按鈕
1: private void InputProcControlPauseBtn_Click(object sender, EventArgs e)
2: {
3: if (ProcControlPauseBtn.Text == "暫停")
4: {
5: ProcControlPauseBtn.Text = "繼續";
6: gProcThread.Suspend();
7: gProcThreadStatus = ProcStatus.Pause; // 更新執行狀態: 暫停
8: ProcControlStopBtn.Enabled = false;
9: }
10: else
11: {
12: ProcControlPauseBtn.Text = "暫停";
13: gProcThreadStatus = ProcStatus.Running; // 更新執行狀態: 繼續Running
14: gProcThread.Resume();
15: ProcControlStopBtn.Enabled = true;
16: }
17: }
停止按鈕
1: private void InputProcControlStopBtn_Click(object sender, EventArgs e)
2: {
3: if (gProcThread.IsAlive)
4: {
5: try
6: {
7: gProcThread.Abort();
8: comport.Close();
9: _shouldStop = true;
10: gProcThread = null;
11: //gProcThread.Join();
12: gProcThreadStatus = ProcStatus.Stop;
13: }
14: catch (ThreadStateException)
15: {
16: //gProcThread.Resume();
17: }
18: ProcControlStartBtn.Enabled = true;
19: ProcControlPauseBtn.Enabled = false;
20: ProcControlStopBtn.Enabled = false;
21: }
22: }
測試結果
全站熱搜
留言列表