4

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));
}
6
  • 1
    Check the wiring; there's no particular reason this would be an issue specifically with that pin unless there's a wiring or electrical issue (which can be internal). Note that digitalRead returns an int, not a bool, and IMO should be coded as such to avoid breaking changes or cross-architecture issues. – Dave Newton Jun 21 at 15:53
  • Aha okay, the Arduino I'm using has been through alot so I will verify this with a new one soon. It could be faulty. But what exactly do you mean that "it should be coded as such"? Should I explicitly cast it to a bool? Or write it the "long way", checking if digitalRead==0 or ==1? – Jurc192 Jun 21 at 17:13
  • 1
    Re: the latter; it's (incrementally) safer to check against HIGH (or LOW) 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 at 17:17
  • 1
    Got cranky and found it: forum.arduino.cc/t/… – Dave Newton Jun 21 at 17:26
  • 3
    It's safer for your class to have an internal record of the LED state instead of relying on digitalRead() to give you the right result. – Majenko Jun 21 at 18:05
2

It seems to be a hardware fault, as others have suggested: I connected the LED to another pin(8) and it works perfectly, everytime. Looks like something got fried internally on that specific pin

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.