我的项目是用我制作的Visual程序来控制LED灯。
在我的项目中我有一个小问题,我如何从我的PC发送更多的命令到arduino?
例如,
这是我上传的Arduino代码:
{int ledPin = 13; // the number of the LED pin
void setup() {
Serial.begin(9600); // set serial speed
pinMode(ledPin, OUTPUT); // set LED as output
digitalWrite(ledPin, LOW); //turn off LED
}
}
{void loop(){
while (Serial.available() == 0); // do nothing if nothing sent
int val = Serial.read() - '0'; // deduct ascii value of '0' to find numeric value of sent number
if (val == 1) { // test for command 1 then turn on LED
Serial.println("LED on");
digitalWrite(ledPin, HIGH); // turn on LED
}
}
if (val == 0) // test for command 0 then turn off LED
{
Serial.println("LED OFF");
digitalWrite(ledPin, LOW); // turn off LED
}如你所见,(val =1)将LED 1打开,( Val = 2)将LED 1关闭,我还在同一arduino草图中增加了2盏LED灯,所以现在( Val =3)将LED 2打开,( val =4)将LED 2关闭,与另一个LED的进程相同。
但是,当我再加一个LED,当我输入( val = 10 ) LED 1就会打开,
我不知道当我指定val = 10.时为什么要打开LED 1
下面是如何从我在vb中创建的程序中发送(Val):
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click
SerialPort1.Open()
SerialPort1.Write("1") 'this will turn LED 1 On
SerialPort1.Close()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button2.Click
SerialPort1.Open()
SerialPort1.Write("0") 'this will turn LED 1 off
SerialPort1.Close()
End Sub 其他LED也是如此,这取决于它们的Val。

如何解决这个问题?
发布于 2014-06-02 19:27:07
一个野蛮的快速修复将不是使用数字来打开/关闭灯,而是将单个字符传递给arduino并将其定义为on和off (例如A->打开1,B->关闭1),至少您将有26/2 = 13 (对于大写字母)灯可以单独打开/关闭。
使用serialEvent,在arduino中转换数据和使用开关;
void serialEvent() {
while (Serial.available() > 0) {
// get the new byte:
inChar = (char)Serial.read();
switch(inChar){
case 'A':
digitalWrite(ledPin, HIGH); //turn ON
break;
case 'B':
digitalWrite(ledPin, LOW); //turn OFF
break;
//add more lights here
}
}
}用你的代码触发;
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click
With SerialPort1
If Not .IsOpen Then
.Open()
End If
.Write("A") 'this will turn LED 1 On
.Close()
End Sub
End With希望能帮上忙。
https://stackoverflow.com/questions/22288065
复制相似问题