View previous topic :: View next topic |
Author |
Message |
nina
Joined: 20 Apr 2007 Posts: 111
|
Timer0 and button |
Posted: Thu Jan 19, 2012 11:42 am |
|
|
When button pressed it should start time count and when button is released, display total time display at LCD.
If user press button again, time should start where stopped previously and when released, display the total time button was kept pressed.
What is happening ? When press button for the second time it starts counting after 10 or 11 seconds.
Many thanks
Code: |
#include <16F628A.h>
#use delay(clock=4000000)
#fuses NOWDT,INTRC_IO, PUT, NOPROTECT, NOBROWNOUT, MCLR, NOLVP, NOCPD
#include <mod_lcd.c>
#define button PIN_A1
int cont,sec;
#INT_timer0
void timer ()
{
set_timer0 (0);
cont++;
}
void main()
{
delay_ms(1000);
lcd_ini();
lcd_escreve('\f');
setup_timer_0(RTCC_INTERNAL | RTCC_DIV_256);
enable_interrupts(GLOBAL | INT_TIMER0);
set_timer0 (0);
cont = 0;
sec = 0;
while(TRUE)
{
if (input(button) == 0)
{
do{
if(cont==16)
{
lcd_escreve('\f');
sec = sec + 1;
cont=0;
}
} while (!input(button));
printf(lcd_escreve, "%u",sec);
}
}
|
|
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Thu Jan 19, 2012 4:07 pm |
|
|
You need to put a limit on how high the count can go. Don't let it count
higher than the amount you are testing for (16). Add the line shown
in bold below.
Quote: |
void timer ()
{
set_timer0 (0);
if(cont < 16)
cont++;
} |
|
|
|
nina
Joined: 20 Apr 2007 Posts: 111
|
Timer0 button |
Posted: Thu Jan 19, 2012 7:39 pm |
|
|
Thank you in advance PCM...but when when i use cont=0 it means I'll never exceed 16 (count always lower than 16). It should work? Am i right?
I was thinking use set_rtcc (0) that means make timer0 zero again and starts from zero.
Thank you
Nina |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Thu Jan 19, 2012 9:43 pm |
|
|
Quote: | it means I'll never exceed 16 |
Your code that resets the count only executes if your loop catches the
count at exactly when it's equal to 16.
Your Timer0 interrupt occurs at a rate of about 15 per second.
What if you wait 3 seconds after the program starts, before you press
the button ? The count will already have increased to 45 (3 x 15 = 45).
But because your loop is waiting for the exact count of 16, this
means you have missed the count of 16. You now have to wait until the
counter goes up to 255 and rolls over to 0 and then goes up to 16.
This will take about 15 seconds.
There are many ways to fix the problem. I gave you one quick way. |
|
|
|