将整数传递给Arduino [英] Pass an integer to an Arduino
问题描述
我在将整数传递给非1或0的Arduino时遇到了一些麻烦.在此示例中,我希望能够传递3.原因是我很快将拥有更多控制按钮的不同部分的按钮. Arduino,并且将需要不同的整数值来执行此操作.
I am having some trouble passing over integers to the Arduino that is not a 1 or a 0. In this example I want to be able to pass a 3. The reason is that I will soon have more buttons controlling different parts of the Arduino and will need different integer values to do this.
这是Arduino代码.
Here is Arduino code..
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来存储为整数值.
I have two different ways of sending data through the serialport, but they both work in the same way. My question is how do I know what values are coming out of the Serial.read() at the Arduino side. When I choose any value that is not a 1 or a 0 in my C# program to send, such as a 3, the program does not work. Clearly 3 is not being sent over as 3 to the Arduino to be stored into an integer value.
推荐答案
我略微修改了您的代码-int b作为顶部的声明被拉出, 我改变了你的行b = Serial.read();到b = Serial.read()-'0';
I modified your code slightly - int b is pulled out as a declaration at the top, and I changed your line b = Serial.read(); to b = Serial.read() - '0';
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();
} }
这篇关于将整数传递给Arduino的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!