-3

My code is taking values from a remote and transmitting the state of it. Right now the states are just 1 and 0, on or off, and is writing over the serial monitor on the transmitting Arduino. On the receiving RF module I can't seem to get my if statements working right

Transmitter code:

const char a[] = "1";
const char b[] = "0";
void loop() {
if (Serial.available ( ) > 0) 
{
char state = Serial.read(); // reading the value from the remote

if (state >= 0)
{
digitalWrite (7, HIGH); //turning LED on transmitting breadboard on to compare to recieving breadboard
radio.write(&a, sizeof(a)); //tell the other arduino that the value is 1
}
if (state < 0)
{
digitalWrite(7,LOW);
radio.write(&b,sizeof(b)); //tell other arduino value is 0
}
}

reciever code:

void loop()
{
if (radio.available())
{
char state[32] = {0};

radio.read(&state, sizeof(state));
Serial.println(state);
int a = state;
if (a = 1);
{
  digitalWrite(7,HIGH);
  Serial.println("do something");
}
if (a = 0);
{
digitalWrite(7,LOW);
Serial.println("do nothing");
}
}

receiving serial monitor

1
do something
do nothing
0
do something
do nothing
0
do something
do nothing

and my light stays off on the receiving Arduino, why does it print both statements? A is 1, but it prints the value that's supposed to be printed when a is 0 also, i'm so confused

6
  • print sizeof(state) also ... is it what you expect?
    – jsotola
    Oct 7, 2023 at 0:15
  • if (a = 1); { ... if (a = 0); { You've got what amounts to four typos there. At minimum two of them will be pointed out to you if you turn up the warning level in the IDE preferences.
    – timemage
    Oct 7, 2023 at 1:00
  • Start with some simple code which is known to work such as: forum.arduino.cc/t/simple-nrf24l01-2-4ghz-transceiver-demo/…. Serial.read() returns a negative value (-1) if no data is available but you already check that data is available before issuing the command. The code you have published is anyway badly formatted and incomplete.
    – 6v6gt
    Oct 7, 2023 at 2:24
  • @timemage Could you please make an answer? A comment is for clarifying the question.
    – Nick Gammon
    Oct 7, 2023 at 6:50
  • 1
    @NickGammon In short: no. You're demonstrating that you don't understand the purpose of my comment.
    – timemage
    Oct 7, 2023 at 17:14

1 Answer 1

0
if (a = 1);
{
  digitalWrite(7,HIGH);
  Serial.println("do something");
}

Two major problems here. In C++ you test for equality for ==, not =.

Second, putting the semicolon after the if terminates the scope of the if.

That should read:

if (a == 1)
{
  digitalWrite(7,HIGH);
  Serial.println("do something");
}

char state[32] = {0};

radio.read(&state, sizeof(state));
Serial.println(state);
int a = state;

state is an array. If you assign that to a you will get the same array, in another variable. That array will not be zero or one.

Maybe you mean:

int a = state [0];

Not the answer you're looking for? Browse other questions tagged or ask your own question.