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.
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';
} }