Exercise 5 - Connecting a switch

1.      INTRODUCTION


There are too many types of switch, but in this exercise you will use three terminal switch which has two positions and with common middle terminal.


2.      HOW TO CONNECT?

Materials:

·         Arduino UNO board

·         Protoboard

·         Some wire Jumpers

·         LED

·         220 ohms resistor

·         2x 10K ohms resistors

·         switch

To profit Arduino digitalRead(). The lateral terminal of the switch will be connected to digital pins on Arduino board (2 y 4), which can read drop voltage (0V or 5V). However, to avoid short circuit in Arduino board, it is necessary, add a 10k resistor in each lateral terminal. It is Similar to CONNECTING_A_BUTTON.


As in a button Contact bounce, which can be fixed by anti-bouncing function, is a common problem with mechanical switches.


EXERCISE_A (Change between blink and fade)


 


3.      PROGRAMMING

EXERCISE_A (Change between blink and fade)

In the first part of code pins 2 and 4 are associate to channelA and channel.

int channelA=2;
int channelB=4;
int led=9;
int i=0;
void setup(){
  pinMode(channelA,INPUT);
  pinMode(channelB,INPUT);
  pinMode(led,OUTPUT);
  Serial.begin(9600);
}
 
 

In loop two states are read by digitalWrite(), then if state1 and state2 are HIGH and LOW level respectively, blink mode is on. On the other hand, if state2 and state1 are HIGH and LOW level respectively, fade mode is on. It’s better to put two condition to avoid bad reads in switch (like two states are in HIGH level).

 
 
void loop(){
  int state1=digitalRead(channelA);//Read channelA state
  int state2=digitalRead(channelB);//Read channelB state
  Serial.print("canalA: ");Serial.print(state1);
  Serial.print("canalB: ");Serial.println(state2);
  //If Button state is in HIGH level led blinking,
  //Unless led will be in fade mode.
  if(state1==HIGH||state2==LOW){
    digitalWrite(led,HIGH);//Write HIGH voltage level in led pin
    delay(500);//Stop program 500 miliseconds
    digitalWrite(led,LOW);//Write LOW voltage level in led pin
    delay(500);
  }
  else if(state2==HIGH||state1==LOW){
    //for increments i , one on one
    for(i=0;i<=255;i++){
      analogWrite(led,i);
      delay(5);
    }
    //for decrements i , one on one
    for(i=255;i>=0;i--){
      analogWrite(led,i);
      delay(5);
    }
  }
}

Última modificación: Tuesday, 21 de January de 2020, 10:28