Friday, May 29, 2015

Timer

We have created the code to display digits, now it is time to create a timer.  We are going to have two main parts, one to select the duration and another to start the count down.


Software

Selection

First of all we are initialize two additional variables, a boolean counting and an int for time.
In our loop we are going to check the value of an analog sensor and map it to our variable time:

int tmp = analogRead(pot);
time = tmp * 30 / 1024;

In this case our analog sensor is a potentiometer which is wired almost identically to an LDR.  The division we do is to map the value of the potentiometer (0-1024] to (0-30] seconds.  If you want a larger range you can increase 30 to the maximum value you need.
We want to display our number though so we will call our previous method:
 
show(time);

This will get called every time the loop runs through.

The last line in our loop will be checking if we should start counting down:
if(digitalRead(button)) countDown(time);

This will call our count down method from a certain time

Countdown

Our countdown method is very straightforward:
void countDown(int counter){
  for(int i=counter;i>0;i--){
    for (int j=0; j<2000; j++) show(i);
  }
  digitalWrite(led,HIGH);
  delay(1000);
  digitalWrite(led,LOW);
}

Recall that the show method took 5ms.  We show the number 2000 times since that will take one second.  In the out of time method we can do more, we trigger an LED on for 1 second then turn it off then back to the main loop.

Hardware

The button is attached to one of the analog inputs.  The LED is attached to a spare output from the multiple segment part.




The LED is connected to pin 1 which means that it needs to be unplugged to send any messages on the serial pin.  When programming the arduino it would be good to unplug this connection.  R6 is the potentiometer, the small blue dial.  Connect pin 1 and 3 (there are small numbers on the pot) to V+ and GND.  Connect pin 2 on the pot to A0.  This lets us read the value of the potentiometer.  If you want to invert the way the dial works just flip the V+ and GND connections.  Wire up another button to A1, digitalWrite can work on analog inputs too!

No comments:

Post a Comment