Monday, April 25, 2011

Using a switch with a Microcontroller

, w
Suppose you want to use a switch with a microcontroller. 

Please go through this article on ' Pull Ups and Pull Downs ' before starting.



We'll assume that the switch will give a 0 when it is pressed and that the switch is connected at PB.0 .


Thus, the pin of the Microcontroller at which the switch is connected will get a 0 when the switch is pressed.

If that pin is already at 0, in this case the microcontroller will not be able to detect that a switch is pressed as there will be no change on the status of the pin.

So, to positively detect a switch press at PB.0 we need to set it to 1, i.e pull-it-up.




Since, we have to check/detect/receive an input on PB.0, we need to make that as an input port, i.e 
DDRB=0b00000000;   
Since I am not using the other pins of PortB, it does not matter whether I write 1 or 0 to them. If the other pins are being used as output, then we should set PB.0 as input using the unary OR, denoted by ' | ', operator.

after DDRB, we need to give the PORT command,

PORTB=0b00000001;   // make PB.0 as 1.

The following picture shows, what happens when we give a 1 to a pin, declared as output, to which LED are connected. Notice the intensity of the LED.




In the next picture we declared the pins connected to the LED as input and then set the pins to 1.


Notice the change in intensity?
In the case when the port is declared as input and we still try to give an output to it, a small amount of current is provided on those pins as compared to when the port has been declared as output.


Now, using the same logic in case of switches.
We'll declare the pin to which the switch is connected as input and give an output on it, so that a small current is provided on it. Thus, every time the switch is pressed, the pin receives a definite 0.


#include<avr/io.h>
#include<util/delay.h>
void main()

   DDRC=0b11111111;        // assuming that LED's are connected at PortC.
   DDRB=0x00;   
// making PB.0 as input (here, other pins will also become input, but since we // are not using them, it doesn't matter)


  PORTB=0b00000001;   // give a 1 on PB.0 to provide a small current on it.


  while(1)
  {  if(PINB==0b00000000)   // 'PIN' is used for checking input
     {                                  // when switch is pressed, entire port becomes 0
         PORTC=0xff;             // we could also have written if(PINB==0)
     }                         
     else
     PORTC=0x00;
  }
}


In the above program, LED glow only when the switch is pressed.






No comments:

Post a Comment