I connected three LEDs to an Arduino Uno and wrote a simple LED class. I toggle all the leds the main loop, but for some reason one led (connected to pin7) always misbehaves, skips one toggle or stays on all the time. Initially all leds are off (in begin() function). What could cause this problem?
main.cpp
#include "led.h"
#include <Arduino.h>
Led leds[] = {
Led(2),
Led(3),
Led(7)
};
void setup()
{
Serial.begin(9600);
for (Led& l : leds) l.begin();
}
void loop()
{
for (Led &l : leds) l.toggle();
delay(500);
}
Led.h
class Led {
public:
Led(int pin);
void begin();
void toggle();
private:
const int _pin;
};
Led.cpp
#include "led.h"
#include "Arduino.h"
Led::Led(int pin) : _pin(pin)
{}
void Led::begin()
{
pinMode(_pin, OUTPUT);
digitalWrite(_pin, LOW);
}
void Led::toggle()
{
digitalWrite(_pin, !digitalRead(_pin));
}
digitalReadreturns an int, not a bool, and IMO should be coded as such to avoid breaking changes or cross-architecture issues. – Dave Newton Jun 21 '21 at 15:53HIGH(orLOW) and use a conditional op. I forget the thread that led me to think this could be a potential issue moving forward--something on the Arduino forums. Sorry--it's probably not a big deal, either. – Dave Newton Jun 21 '21 at 17:17digitalRead()to give you the right result. – Majenko Jun 21 '21 at 18:05