使用 C# 來操作 Arduino
C# 與 Arduino 相互溝通
整個概念就是依靠 Serial Port 來溝通,讓電腦端可以控制 Arduino 的 LED 燈
要讓 C# 可以控制 Serial Port,必須要引入 using System.IO.Ports
這個東西才行,安裝方式我是直接用 Nuget 去裝,不知為何我沒有內建這個東西。
相關介紹可以去看微軟的技術文件
C# 程式
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO.Ports; namespace App1 { public partial class Form1 : Form { private SerialPort serialPort1 = new SerialPort(); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { serialPort1.BaudRate = 9600; serialPort1.Parity = Parity.None; serialPort1.DataBits = 8; serialPort1.StopBits = StopBits.One; btnDisconnect.Enabled = false; btnLedOpen.Enabled = false; btnLedClose.Enabled = false; cbPortNumber.Items.AddRange(SerialPort.GetPortNames()); label1.Text = "PC狀態:尚未連線"; } private void cbPortNumber_SelectedIndexChanged(object sender, EventArgs e) { serialPort1.PortName = cbPortNumber.Text; } private void btnConnect_Click(object sender, EventArgs e) { serialPort1.Open(); btnConnect.Enabled = false; btnDisconnect.Enabled = true; btnLedOpen.Enabled = true; btnLedClose.Enabled = true; label1.Text = "PC狀態:連線中"; } private void btnDisconnect_Click(object sender, EventArgs e) { serialPort1.Write("0"); serialPort1.Close(); btnConnect.Enabled = true; btnDisconnect.Enabled = false; btnLedOpen.Enabled = false; btnLedClose.Enabled = false; label1.Text = "PC狀態:斷線中"; label2.Text = "Arduino回傳:"; } private void btnLedOpen_Click(object sender, EventArgs e) { serialPort1.Write("1"); btnLedClose.Enabled = true; btnLedOpen.Enabled = false; label1.Text = "送出指令:LED ON"; label2.Text = "Arduino回傳:" + serialPort1.ReadLine(); } private void btnLedClose_Click(object sender, EventArgs e) { serialPort1.Write("0"); btnLedOpen.Enabled = true; btnLedClose.Enabled = false; label1.Text = "送出指令:LED OFF"; label2.Text = "Arduino回傳:" + serialPort1.ReadLine(); } } }
Arduino 程式
void setup() { Serial.begin(9600); // 開啟 Serial port, 通訊速率為 9600 bps // 初始化 LED 接腳 pinMode(13, OUTPUT); } void loop() { // 檢查是否有資料可供讀取 if (Serial.available() > 0) { // 讀取進來的 byte char inByte = Serial.read(); // 根據收到的字元決定要打開或關掉 LED switch (inByte) { case '0': digitalWrite(13, LOW); delay(1); Serial.println("LED OFF"); break; case '1': digitalWrite(13, HIGH); delay(1); Serial.println("LED ON"); break; default: // 關掉所有的 LED digitalWrite(13, LOW); } } }