can't increment int value inside if() statement....

Hi all,

Can someone please explain this to me. I am trying to increment the "SendMessage" (which is an int variable) value to "2", inside an "if()" statement, but it doesn't increment.

Here's the sketch:

int Sensor1 = A8; //Optocoupler input
int Sensor2 = 37; //Optocoupler input2 (Digital 37, mapped to DB0 on Gboard PRO
int SensorState = 0;
int SendMessage = 0;

void setup()  
{

  Serial.begin(115200);
  pinMode(Sensor1, INPUT);
  pinMode(Sensor2, INPUT);
  digitalWrite(Sensor1, HIGH);
  digitalWrite(Sensor2, HIGH);  
} // end setup()


void loop()                     // run over and over again
{
  CheckSignal(); 
} // End loop


void CheckSignal()
{
   if(digitalRead(Sensor1) == LOW || digitalRead(Sensor2) == LOW) // See if either sensors are active
  {
    SensorState = 1;
    SendMessage = 1;
    if (SendMessage == 1)
    {
      Serial.println("Message Sent");
      Serial.print("SensorState: ");
      Serial.println(SensorState);
      Serial.print("SendMessage: ");
      Serial.println(SendMessage);
      SendMessage = 2;
    }
  } else { 
  SensorState = 2;
  SendMessage = 2;
  } // end ditigalRead(Sensor1) or digitalRead(Sensor2)
   
  
} // end CheckSignal()

And here's the sample output:

SendMessage: 1
Message Sent
SensorState: 1
SendMessage: 1
Message Sent
SensorState: 1
SendMessage: 1
Message Sent
SensorState: 1
SendMessage: 1
Message Sent
SensorState: 1
SendMessage: 1
Message Sent
SensorState: 1
SendMessage: 1

In theory, each of those lines should be printed once only, and the "SendMessage" int variable should increase to "2", but it doesn't. Why would that be?

You did not see this?

    // set SendMessage to 1
    SendMessage = 1;

    // now check SendMessage. It will always be 1
    if (SendMessage == 1)
    {
      Serial.println("Message Sent");

Question:

  • what do you (wnat to ) do if both sensors are low.
    SendMessage = 1;
    if (SendMessage == 1)

Why bother checking if it's 1? You just set it to 1; you know it is 1.