C#
加入
using System.IO.Ports;
程式碼
private void button1_Click(object sender, EventArgs e)
{
serialPort1.Open();
button1.Enabled = false;
button2.Enabled =true;
button3.Enabled = true;
button4.Enabled = false;
label1.Text = "連線中";
}
private void Form1_Load(object sender, EventArgs e)
{
serialPort1.PortName = "COM14";
serialPort1.BaudRate = 9600;
serialPort1.Parity = Parity.None;
serialPort1.DataBits = 8;
serialPort1.StopBits = StopBits.One;
button2.Enabled = false;
button3.Enabled = false;
button4.Enabled = false;
label1.Text = "尚未連線";
}
private void button2_Click(object sender, EventArgs e)
{
serialPort1.Write("0");
serialPort1.Close();
button1.Enabled = true;
button2.Enabled = false;
button3.Enabled = false;
button4.Enabled = false;
label1.Text = "斷線中";
}
private void button3_Click(object sender, EventArgs e)
{
serialPort1.Write("1");
button4.Enabled = true;
button3.Enabled = false;
label1.Text = "LED ON";
}
private void button4_Click(object sender, EventArgs e)
{
serialPort1.Write("0");
button3.Enabled = true;
button4.Enabled = false;
label1.Text = "LED OFF";
}
Arduino程式
// 結合 switch case 的 Serial port 讀取範例 V1
void setup() {
Serial.begin(9600); // 開啟 Serial port, 通訊速率為 9600 bps
// 初始化 LED 接腳
pinMode(13, OUTPUT);
}
void loop() {
// 檢查是否有資料可供讀取
if (Serial.available() > 0) {
// 讀取進來的 byte
int inByte = Serial.read();
// 根據收到的字元決定要打開或關掉 LED
switch (inByte) {
case '0':
digitalWrite(13, LOW);
break;
case '1':
digitalWrite(13, HIGH);
break;
default:
// 關掉所有的 LED
digitalWrite(13, LOW);
}
}
}
沒有留言:
張貼留言