Pass an integer to an Arduino

て烟熏妆下的殇ゞ 提交于 2019-12-11 11:46:56

问题


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.

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();
}
}

Here is my C# code.

    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);
    }

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.


回答1:


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();

} }



来源:https://stackoverflow.com/questions/23727033/pass-an-integer-to-an-arduino

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!