《Arduino從基礎到實踐》第三章項目十,因為沒有買藍燈,我用的黃色的LED燈代替,代碼如下: char buffer[18]; int red, green, yellow;
int redPin = 9; int greenPin = 10; int yellowPin = 11;
void setup() { // put your setup code here, to run once: Serial.begin(9600); Serial.flush(); pinMode(redPin, OUTPUT); pinMode(greenPin, OUTPUT); pinMode(yellowPin, OUTPUT); }
void loop() { // put your main code here, to run repeatedly: if (Serial.available() > 0) { int index = 0; delay(100); int numChar = Serial.available();
Serial.print("Received bytes:"); Serial.println(numChar);
if (numChar > 15) { numChar = 15; }
while (numChar--) { buffer[index++] = Serial.read(); }
splitString(buffer); } }
void splitString(char*data) { Serial.print("Data entered: "); Serial.println(data);
char*parameter; parameter = strtok(data, " ,");
while (parameter != NULL) { setLED(parameter); parameter = strtok(NULL, " ,"); }
for (int x = 0; x < 16; x++) { buffer[x] = '\0'; }
Serial.flush(); }
void setLED(char*data) { if ((data[0] == 'r') || (data[0] == 'R')) { int ans = strtol(data + 1, NULL, 10); ans = constrain(ans, 0, 255); analogWrite(redPin, ans); Serial.print("Red is set to: "); Serial.println(ans); }
if ((data[0] == 'g') || (data[0] == 'G')) { int ans = strtol(data + 1, NULL, 10); ans = constrain(ans, 0, 255); analogWrite(greenPin, ans); Serial.print("Green is set to: "); Serial.println(ans); }
if ((data[0] == 'y') || (data[0] == 'Y')) { int ans = strtol(data + 1, NULL, 10); ans = constrain(ans, 0, 255); analogWrite(yellowPin, ans); Serial.print("Yellow is set to: "); Serial.println(ans); } } 一開始用Arduino的序列槽通信視窗做實驗,後來自己在C#裡面寫了一個序列槽通信的控制台程式,也可以與之通信, 控制燈的亮度,代碼如下: SerialPort sp = null; string inputStr = string.Empty; Console.WriteLine("input cmd to port,input exit to exit"); inputStr = Console.ReadLine(); try { sp = new SerialPort("COM3", 9600); sp.Open();
while (!string.Equals(inputStr.ToUpper(), "EXIT")) { sp.WriteLine(inputStr); Console.WriteLine("input cmd to port,input exit to exit"); inputStr = Console.ReadLine(); } } catch (Exception ex) { Console.WriteLine(ex); } finally { if (sp != null) { sp.Close(); sp.Dispose(); } }
Console.WriteLine("Press any key to exit..."); Console.ReadKey();
需要注意的是,同一個序列槽隻能同時被一個程式使用,如果Arduino序列槽視窗打開,則C#程式就會運作出錯