1

I'm measuring voltage between button's ground and input pole on the following sketch. When button is on off state, there's 5V there, when it's switched on and led turs on, there's 0. Is this a correct way, and also how do I make it easier to write code and have LOW represent led being off. In this sketch, digitalWrite(led1, LOW); means the LED is actually turned on, so how do I tweak this to be representative of actual state, high=led on.

#include <ezButton.h>

// -----
// Declaration
// -----
   
const int button1  = 9;   
const int led1     = 4;    
int ledState = LOW;
  
ezButton button(button1);
    
// -----
// Setup
// -----

void setup()
{
   
  pinMode(led1, OUTPUT);      
  pinMode(button1, INPUT_PULLUP);    
  button.setDebounceTime(50);
    
}
    
// *****
// Main Loop
// *****

void loop()
{

  if( digitalRead(button1) == LOW ) {
    digitalWrite(led1, HIGH);
  }
  else  {
    digitalWrite(led1, LOW);
  }      

}
 
// *****
6
  • @Juraj but doesn't the "int ledState = LOW;" mandate that when starting up the Arduino with this sketch led is off? – Varonne Apr 18 at 17:22
  • what is the purpose of int ledState = LOW;? ... your program does not use ledState – jsotola Apr 18 at 17:45
  • 1
    So, if I correctly understand, you are getting confused, because turning the LED on means writing LOW to it. And you want to change that to not be confused anymore. Is that correct? – chrisl Apr 18 at 19:51
  • 2
    To answer your question, Is this a correct way, yes, it is one correct way. There's nothing incorrect about an LED circuit that turns the LED on when the voltage is low, and off when the voltage is high. If you want to change that fundamental property, you have to change the circuit. – lurker Apr 19 at 1:29
  • 1
    If I correctly understand, you're rather confused by the inverse logic of a PULLUP button. Alternatively to @Abel's comment you might define const int PRESSED=LOW; and write if (digitalRead(button1) == PRESSED) digitalWrite(led1, HIGH); – DataFiddler Apr 19 at 13:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.