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);
}
}
// *****
1 Answer 1
To answer the posted question literally: Yes, it is the correct way for your circuit, which has the button between the pin and GND, and the LED between VCC and the pin:
schematic
simulate this circuit – Schematic created using CircuitLab
I can understand the confusion. However, the meaning is right, because the level on the button's pin is LOW
if pressed. And the level on the LED's pin needs to be LOW
for current to flow.
You can define your own constants:
// other stuff left out
const int LED_ON = LOW;
const int LED_OFF = HIGH;
const int BUTTON_PRESSED = LOW;
const int BUTTON_RELEASED = HIGH;
void loop()
{
if (digitalRead(button1) == BUTTON_PRESSED) {
digitalWrite(led1, LED_OFF);
}
else {
digitalWrite(led1, LED_ON);
}
}
If you want to keep using HIGH
and LOW
, but interpret them as:
HIGH
= button pressed / LED onLOW
= button released / LED off
Then you need to modify the circuit:
schematic
Unfortunately, there is no pin mode INPUT_PULLDOWN
for the button pin, so you need to provide the pull down resistor externally. Make sure to set the pin to INPUT
, not INPUT_PULLUP
.
A common value for the pull down resistor is 10 kΩ.
int ledState = LOW;
? ... your program does not useledState
const int PRESSED=LOW;
and writeif (digitalRead(button1) == PRESSED) digitalWrite(led1, HIGH);