2

Expected Behavior:

I am attempting to use && or nested if statements to achieve the effect of two switches being required to close prior to an LED light (i.e., flip both switches), the LED turns on for 1 second, and then turns off.

Encountered Behavior:

It appears that no matter how I write the statement, if the SECOND if is true, the LED lights up.

Additional information:

The switches connect directly to ground when closed.

I have tried multiple conditional statements:

  1. using &&: if (switch1 == LOW && switch2 == LOW) {LED code}
  2. Nested if: if (switch1 == LOW) { if (switch2 == LOW) {LED code} }

I have tried multiple variable declarations:

  1. int switch1 = 0; int switch2 = 1; (using integer representation of digispark pinout)
  2. #define switch1 PB1
#define switch1 PB1
#define switch2 PB0

void setup() { pinMode(2, OUTPUT); pinMode(switch1, INPUT_PULLUP); pinMode(switch2, INPUT_PULLUP); }

void loop() { if (!digitalRead(switch1)) { if (!digitalRead(switch2)) { digitalWrite(2, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(2, LOW); } }

else { digitalWrite(2, LOW); delay(1); } }

My Digispark Attiny85 is attached to a breadboard, where it receives power through the 5V and ground pins on the Digispark board. PB0 and PB1 connect directly to ground when closed, otherwise I count on the pull-up resistors. PB2 is connected to an LED -> resistor -> ground. All components share the same 5V power supply and ground.

enter image description here

the busybee
  • 2,408
  • 9
  • 18
jmarywien
  • 51
  • 6

2 Answers2

3

I am confident I solved the problem and think I know why it occurs.

PB1 on the digispark Attiny85 has a built in LED. This LED is still active when I run my code. The LED is dim, but consuming power. My hypothesis is that is is consuming enough current to drive that pin low when digital_read is called on PB1. Therefore, PB1 always evaluates to true, because of the internal LED (despite the fact that input_pullup should drive it false by default).

Here is how I tested this hypothesis:

  1. If I plug PB1 into 5v+, the internal LED gets brighter, and my project LED never lights up. i.e., my first if is now !true, so the conditional fails to execute.
  2. If I recode to exclude PB1 and instead map to PB3, my code runs as intended.

All of this is to say, I think that even when you specify PB1 as input_pullup, it does not behave as expected because of the internal LED.

@jsotola, thank you for your kindness and patience. What do you think?

jmarywien
  • 51
  • 6
1

You would appear to have the incorrect physical pins connected to the switches:

Pins 0 and 1 connect directly to ground when closed, otherwise I count on the pull-up resistors.

However:

  • PB0 is physical pin 5
  • PB1 is physical pin 6

ATTiny85 pinout

Greenonline
  • 3,152
  • 7
  • 36
  • 48