Serial.print loop


evening, i'm total noob arduino , have quite ambitious long term goal, totally have start @ begginning , such don't want scour web chunks of code lift; want learn go. means starting scratch. i've written basic code turn pin 13 led on when button pressed pull input low, , while doing so, want serial.print state of button once each change of state, while keeping led lit. i've searched forum , found helpful post pointing me in right direction, need second half of "if" statement. code started with, output serial print text (and understand why doing this)

code: [select]
const int ledpin = 13;
const int sw = 4;

int buttonstate =0;

void setup()

{
 
    serial.begin(9600);
   
    pinmode(ledpin, output);
   
    pinmode(sw, input);
   
    digitalwrite(sw, high);
   
}

void loop()

{
  buttonstate = digitalread(sw);
    if (buttonstate == low) {
        digitalwrite(ledpin, high);
        serial.println("button pressed");
               
    }
    else if (buttonstate == high) {
      digitalwrite(ledpin, low);
      serial.println("button released");
    }
    delay(1000);


i put delay in stop serial monitor going nuts, while i'm trying sort out error.

this code i've got to, prints "button pressed" once while pressed, can't see how same on opposite side of if argument.

code: [select]
const int ledpin = 13;
const int sw = 4;

int buttonstate =0;
int old_buttonstate;

void setup()

{
 
    serial.begin(9600);
   
    pinmode(ledpin, output);
   
    pinmode(sw, input);
   
    digitalwrite(sw, high);
   
}

void loop()

{
  int buttonstate = digitalread(sw);
    if (buttonstate != old_buttonstate) {
        digitalwrite(ledpin, high);
        serial.println("button pressed");
       old_buttonstate = buttonstate;         
    }
     else if (buttonstate == high) {
      digitalwrite(ledpin, low);
      serial.println("button released");
    }
    delay(1000);
   
}


 any awesome.

your first "if":

code: [select]
if (buttonstate != old_buttonstate) {
        digitalwrite(ledpin, high);
        serial.println("button pressed");
       old_buttonstate = buttonstate;         
}


does not @ whether buttonstate low , has gone high, or high, , went low.  print "button pressed, whether button pressed or released.

your "else":

code: [select]
else if (buttonstate == high) {
      digitalwrite(ledpin, low);
      serial.println("button released");
}


does not see if button has gone high, or of it's been high last week.  print "button released" whenever buttonstate high, except first time goes high after having been low.

regards,
ray l.


Arduino Forum > Using Arduino > Programming Questions > Serial.print loop


arduino

Comments

Popular posts from this blog

invalid use of void expresion in FlexiTimer2 library

error: a function-definition is not allowed here before '{' token

LED Strip Code