2013年6月14日 星期五

DIY - 智能小車:用 Microsoft Visual C++/CLI 編寫 Timer 程式 (三十八)

DIY - 智能小車:用 Microsoft Visual C++/CLI 編寫 Timer 程式 (三十八) 

在編寫雷達Radar)程式時,需要每隔一段時間讀取從智能小車上的超聲波測距模塊 US-020發出的距離資料,所以要利 Timer 控制時間,當 Timer 開始後,便會按照設定的時間去執行事件EvnetHandler),這就是筆者要使用的方法去讀取距離資料。

Microsoft Visual C++/CLI 編寫 Timer 程式
.NET Framework 裏面提供了三種 Timer
    System::Windows::Forms::Timer
    System::Timers::Timer
    System::Threading::Timer
 
System::Windows::Forms::Timer Timer
一般的 Timer 控制會選用 System::Windows::Forms::Timer 控制項,因為添加和編寫程式相對簡單,Timer Start 之後定時(按設定的 Interval)調用掛接在Tick事件上的 EvnetHandler,由於System::Windows::Forms::Timer EventHandler 中可 以直接獲取和修改 UI 元素而不會出現問題,因為這種 Timer 實際上就是在 UI 線程自身上進行調用的,會導致了在 Timer EventHandler 裏面進行長時間的阻塞調用。

Timer程式:
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;

private : int timeValue;
private: System::Void timer1_Tick(System::Object^  sender, System::EventArgs^  e)
             {
                 this->timer1->Enabled=false;
                 timeValue +=1;
                 this->label1->Text=timeValue.ToString();
                 this->textBox1->Text=timeValue.ToString();
                 this->timer1->Enabled=true;
             }

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e)
             {
                 button1->Enabled=false;
                 timeValue =1;

                 if (!this->timer1)
                 {
                     this->timer1=gcnew Timer();
                     this->timer1->Enabled=true;
                     this->timer1->Interval=200;
                     timer1->Tick += gcnew EventHandler(this, &Form1::timer1_Tick);
                 }
                     this->timer1->Start();
             }

private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e)
         {
             this->timer1->Stop();
             delete this->timer1;
         }

2013614 天氣報告
氣溫:26.0 @ 21:30
相對濕度:百分之98%
天氣:大雨

沒有留言:

張貼留言