I need help .... I need to send a certain number (example '1') via serial, it will turn on a certain port, and that when sending that same number again that same port will be turned off and that this inversion between on and off Is done whenever the same number is sent ... Could anyone help me with this code?
'1' is not a number. Well, ok, it is, but ist value isn't one, it's 49. 1 is a number. '1' is a character and the ASCII value of '1' is 49.
We can help you with your code. Post it and we'd be happy to take a look.
This is my code:
int led = 7;
int receiver;
void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);
digitalWrite(led, LOW);
}
void loop() {
receiver = Serial.read();
if (receiver == '1'){
digitalWrite(led, HIGH);
}
else if (receiver == '1'){
digitalWrite(led, HIGH);
}
}
I need the same number sent via serial to activate a certain port and when it is sent again disable the same port...it's possible?
You need to remember the state of the port - enabled or disabled.
Then when you detect a '1' you can flip the state.
Note that the bare Serial.read() you have there will return -1 (the number, not the character) when there's nothing to read. You might wrap this with a if(Serial.available){} or you might just leave it alone the way it is.
Comparing an int to a char (the single character '1' is char datatype) is not always going to give you the answer you expect.
Most of the time, just reading the serial port without checking there's something to read will return -1.
Checking to see if something is '1' or else is '1' . . .
Thanks for the help, friends, Solved!