Program does two different things, plse help :(

Dear fellow Arduinists,

I wrote a very simple testprg to activate and de-activate two relays. Two "inPins" and two "outPins", and two conditional statements, see listing below.

  • When I run this prgm, the counter 'countr' value does not toggle between '1'and '0' as it should
  • When I leave out the conditional statements, 'toggle1' does alter between '1'and '0'

What mistake did I make?? Why does 'toggle1' change without the conditional statements, and does it not alter when the conditional statements are in place?

I use the 1.6.4 compiler, I compiled the listing on a W10 platform as well as on a Linux platform. In both cases the results were the same.

Listing:

int stat1 = LOW;
int stat2 = LOW;
int motorPin1=8;
int motorPin2=9;
int switchPin1=2;
int switchPin2=3;
int countr = 0;
int toggle1 = 0;

void setup(){
Serial.begin(115200);
pinMode(motorPin1,OUTPUT);
pinMode(motorPin2,OUTPUT);
pinMode(switchPin1,INPUT);
pinMode(switchPin2,INPUT);
}

void loop(){

while (countr < 7){
Serial.print(" toggle1= ");
Serial.println(toggle1);
Serial.print(" countr= " );
Serial.println(countr);

//------------------------
/*
if (toggle1 = 0){
digitalWrite(motorPin1,HIGH);
delay(30);
digitalWrite(motorPin1,LOW);
}

else {
digitalWrite(motorPin2,HIGH);
delay(30);
digitalWrite(motorPin2,LOW);
}
*/
//------------------------

countr++;
delay(1000);
toggle1=abs(toggle1-1);
}

idle();

}

void idle()
{
int countr = 2;
while (countr > 1){
countr=0;
}
}

Hoping to read from you,

Henk van der Heijden.

  if (toggle1 = 0){oops

void idle()
{
  int countr = 2;
  while (countr > 1){
    countr=0;
  }
}

Since this function declares a local variable called 'countr' it is not doing anything to the global variable of the same name.

Every one, thnx for your fast resopnse. Indeed, a OOPSIE moment, My apologies.

Byte8:

  • When I run this prgm, the counter 'countr' value does not toggle between '1'and '0' as it should
  • When I leave out the conditional statements, 'toggle1' does alter between '1'and '0'

If you want to toggle between 1 and 0 you better use boolean instead of int

int countr = 0;
int toggle1 = 0;

This can be much simplified.

  toggle1=abs(toggle1-1);

into this

toggle1=1-toggle1;

or

toggle1=!toggle1;

Wow, thnx! I will try this