Arduino Yun是一個非常強大的開發版,人人都會用~!
但是總是透過C#來取得傳出來的資訊就絕對不是人人都曉得囉
這裡要來介紹怎麼樣使用 C# 來取得 Arduino 使用Serial.print() 傳出來的資料
首先!! 先建立一個 主控台應用程式 ConsoleApplication ((這不用教學了吧....直接進入重點..!!
第一步,引用Library
using System.IO.Ports;
接著看入主程式,也才短短幾行而已!!
static void Main(string[] args) { SerialPort myport = new SerialPort(); myport.BaudRate = 9600; //需跟arduno設定的一樣 myport.PortName = "COM5"; //指定PortName myport.Open(); Console.WriteLine("start read"); //在Yun這塊板子中,一定要加上這行來啟用DTR訊號;其他板子不一定需要。 myport.DtrEnable = true; //開始讀值 while (true) { string data = myport.ReadLine(); Console.WriteLine(data); } }
如果跟我一樣是指用ArduinoYun 的話,那只要依據PortName位置做修改就可以動作了
接著再提供稍稍進階一點的做法,在SerialPort 類別裡面還提供事件導向式 (Event Driven)的處理方法,也就是使用委派的方式來協助讀取資料
簡單的說,就是不用為了Arduino特別寫一個while迴圈!!
public event SerialDataReceivedEventHandler DataReceived;
我們在第12行加入DataReceived的委派函式,並將讀取值的工作移到 myport_DataReceived 裡面完成!!
class Program { static SerialPort myport; static void Main(string[] args) { myport = new SerialPort(); myport.BaudRate = 9600; myport.PortName = "COM5"; myport.Open(); Console.WriteLine("start read"); myport.DtrEnable = true; myport.DataReceived += myport_DataReceived; while (true) { //原本讀值的工作交給 myport_DataReceived 去完成 } } static void myport_DataReceived(object sender, SerialDataReceivedEventArgs e) { string data = myport.ReadLine(); Console.WriteLine(data); } }
完成!!
最後再提供Arduino測試用的程式碼,從草稿碼中的Blink 加入兩行 (5,10),讓他會定期輸出Hello World。
// the setup function runs once when you press reset or power the board void setup() { // initialize digital pin 13 as an output. pinMode(13, OUTPUT); Serial.begin(9600); } // the loop function runs over and over again forever void loop() { Serial.println("Hello World"); digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(13, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second }
文章標籤
全站熱搜
留言列表