Taking Input (Part-2)

Let’s do some user input processing now. Let’s say there are some LEDs  connected to your MCU and you want to shift their positions whenever you want. You connect a push button to the controller, change the code and the LEDs begin to shift as you push the button. We will be using blocking I/O and external pull-up to keep it simple.

Parts List :

  1. ATmega 8 – 1 pcs
  2. LED red – 3 pcs
  3. Resistors –
    1. 1K – 3 pcs
    2. 10k – 2 pcs
  4. Capacitors –
    1. 0.1 uF – 1 pcs
    2. 1 uF – 1 pcs

Let’s first create the circuit –

Screenshot from 2016-03-20 12-07-06

Connect the 1uF capacitor between VCC and GND.

Now the code – it’s pretty simple. To initialize a pin as input (external pull-up) you don’t have to configure the DDRx register. When the controller is powered up, all registers are cleared. To configure a pin as input you have to clear the associated bit at DDRx register.

Next thing to do is checking whether the button S1 is pressed or not. It is checked inside the while loop to make sure it checks the button as long as the controller is powered up. To check the button press condition we check PINx register. It reflects the external input. PINx registers are Read-only registers meaning writing to these registers will have no result. Anyway, to check the input at PD3 we can use the following logic –


if( PIND & (1<<PD3) ){
    //button is not pressed
}else {
    //button is pressed
}

We can also use the following for a shortcut –


if( !( PIND & (1<<PD3) ) {
    //button is pressed
}

When the button is pressed we enter into a loop where we stay as long as the button is held down –


if( !( PIND & (1<<PD3) ) {
    //button is pressed

    //stay inside this loop as long as 
    //the button is held down
    while( !( PIND & (1<<PD3) );
}

Whenever the processor gets out of this loop, it means the button is released. Now we can write other logic to process the input.
Was that hard ? Then you should study the bitwise operators of C.

Reader can find the code here. Here’s a little video showing the output –

If you want to use internal pull-up, which is a great feature, all you have to do is setting the associated PORTx bit right after powering up. This will enable the internal pull-up resistor. But you must not clear the PORTx bit if you want to keep this pin as input pin.

This is not everything about taking input. Read some more you will find more techniques to take user input. So keep searching.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s