我在将整数传递给不是1或0的Arduino时遇到了一些麻烦。在这个例子中我希望能够传递3.原因是我很快会有更多的按钮来控制不同的部分Arduino将需要不同的整数值来执行此操作。
这是Arduino代码..
void setup()
{
Serial.begin(9600);
// Define the led pin as output
pinMode(13, OUTPUT);
}
void loop()
{
// Read data from serial communication
if (Serial.available() > 0) {
int b = Serial.read();
// Note, I made it so that it's more sensitive to 0-40% load.
// Since thats where it's usually at when using the computer as normal.
if (b == 3)
{
digitalWrite(13, HIGH);
}
else if (b == 0)
{
digitalWrite(13, LOW);
}
Serial.flush();
}
}
这是我的C#代码。
int MyInt = 3;
byte[] b = BitConverter.GetBytes(MyInt);
private void OnButton_Click(object sender, EventArgs e)
{
serialPort1.Write(b, 0, 4);
}
private void OffButton_Click(object sender, EventArgs e)
{
serialPort1.Write(new byte[] { Convert.ToByte("0") }, 0, 1);
}
我有两种不同的方式通过串口发送数据,但它们都以相同的方式工作。我的问题是如何知道Arduino端Serial.read()的值是什么。当我在我的C#程序中选择任何不是1或0的值来发送时,例如3,程序不起作用。显然,3不会被发送为3到Arduino以存储为整数值。
答案 0 :(得分:0)
我稍微修改了你的代码 - int b被拉出作为顶部的声明, 我改变了你的行b = Serial.read();到b = Serial.read() - ' 0&#39 ;;
int b;
void setup()
{
Serial.begin(9600);
// Define the led pin as output
pinMode(13, OUTPUT);
}
void loop()
{
// Read data from serial communication
if (Serial.available() > 0) {
b = Serial.read() - '0';
// Note, I made it so that it's more sensitive to 0-40% load.
// Since thats where it's usually at when using the computer as normal.
if (b == 3)
{
digitalWrite(13, HIGH);
}
else if (b == 0)
{
digitalWrite(13, LOW);
}
Serial.flush();
} }