...

Arduino Basics

This week’s assignment is to create a circuit and Arduino code that does the following:

Circuit

  • Connect two LEDs to your Arduino using a breadboard
  • Connect one switch to your Arduino using a breadboard

Code

  1. Read a momentary switch being pressed
  2. When the program starts, both LEDs are off
  3. When the switch is pressed once, the first LED turns on
  4. When the switch is pressed the second time, the second LED turns on (the first one should also still be on)
  5. When the switch is pressed the third time, both LEDs turn off
  6. Repeat this same cycle of LEDs turning on and off in sequence (off, one LED, two LEDs, off…)

Simulator Draft

The first step for me to achieve it this was to use WOKWI Arduino Simulator to help me build a virtual circuit that looks like this:

Detail image

You can also see my code and circuit here.

Code

int count=0;
int button;

void setup() {
   pinMode(2, INPUT);
   pinMode(8, OUTPUT);
   pinMode(13, OUTPUT);
   button=digitalRead(2);
}

void loop() {
  int read=digitalRead(2);//use this to avoid using too much 'digitalRead' later
  if(button!=read){
     count+=read;
     if(count>=3){
       count=0;
     }
   button=read;
  }
  if(count==0){
    digitalWrite(13, LOW);
    digitalWrite(8, LOW);
  }
   if(count==1){
    digitalWrite(13, HIGH);
  }
   if(count==2){
    digitalWrite(8, HIGH);
  }
  delay(10);
}

Circuit

This is my circuit based on my simulation, and it worked out quite well.

1st press: Detail image

2nd press: Detail image

3rd press: Detail image

again and again and again…