Zack Lee's blog

Digital Input and Output with Arduino

Posted at — Sep 27, 2019

Test1: Using a button to light up an LED

digitalInputOutput1&2

Code :

int lastButtonState = LOW;
int buttonInputPin = 2;
int ledOutputPin = 3;

void setup() 
{
    Serial.begin(9600);
    pinMode(buttonInputPin, INPUT);
    pinMode(ledOutputPin, OUTPUT);
}

void loop() 
{
    int buttonState = digitalRead(2);
    if (buttonState != lastButtonState) 
    {
        if (buttonState == HIGH) 
            digitalWrite(ledOutputPin, HIGH);
        else
            digitalWrite(ledOutputPin, LOW);
    }
    lastButtonState = buttonState;
}

Video :

Code :

int buttonInputPin = 2;
int ledOutputPin = 3;

void setup() 
{
    Serial.begin(9600);
    pinMode(buttonInputPin, INPUT);
    pinMode(ledOutputPin, OUTPUT);
}

void loop() 
{
    int buttonState = digitalRead(2);
    if (buttonState == HIGH) 
    {
        digitalWrite(ledOutputPin, HIGH); 
        delay(1000); 
        digitalWrite(ledOutputPin, LOW);
        delay(1000);   
    }  
    else
    {
        digitalWrite(ledOutputPin, LOW);
    }
}

Video :

Test3: Making LEDs light up in sequence and using button to freeze the current state

digitalInputOutput3

Code :

int buttonInputPin = 2;
int led1OutputPin = 3;
int led2OutputPin = 4;
int led3OutputPin = 5;
int led4OutputPin = 6;
int numCurrentOutputPin = 0;
unsigned long lastTime = 0;
int count = 0;

void setup() 
{
    Serial.begin(9600);
    pinMode(buttonInputPin, INPUT);
    pinMode(led1OutputPin, OUTPUT);
    pinMode(led2OutputPin, OUTPUT);
    pinMode(led3OutputPin, OUTPUT);
    pinMode(led4OutputPin, OUTPUT);
    lastTime = millis();
}

void turnLedOn(int numOutputPin)
{
    digitalWrite(led1OutputPin, LOW);
    digitalWrite(led2OutputPin, LOW);
    digitalWrite(led3OutputPin, LOW);
    digitalWrite(led4OutputPin, LOW);
    digitalWrite(numOutputPin, HIGH);
    numCurrentOutputPin = numOutputPin;
}

void loop() 
{
    int buttonState = digitalRead(2);
    if (buttonState == HIGH) 
    {
        turnLedOn(numCurrentOutputPin);
    }
    else
    {
        unsigned long CurrentTime = millis();
        unsigned long ElapsedTime = CurrentTime - lastTime;
        if (ElapsedTime >= 100)
        {
            if (count == 0)
                turnLedOn(led4OutputPin);
            else if (count == 1)
                turnLedOn(led3OutputPin);
            else if (count == 2)
                turnLedOn(led2OutputPin);
            else if (count == 3)
                turnLedOn(led1OutputPin);
            count = (count + 1) % 4;
            lastTime = CurrentTime;
        }
    }
}

Video :

comments powered by Disqus