add timer 1 measurement

This commit is contained in:
King Kévin 2015-01-06 17:52:22 +01:00
parent 97f3283118
commit 7b1287afaf
1 changed files with 31 additions and 5 deletions

View File

@ -31,6 +31,10 @@
/* variables */
volatile uint8_t state_portD; // the state of port D
volatile bool scale_on = false; // is the scale on (based on the SCALE_ON PIN)
volatile bool pwm_high = false; // is the PWM for the last weight measurement high
volatile bool measurement_flag = false; // is a PWM measurement value ready
volatile uint16_t measurement_value = 0; // the PWM measurement value from the timer
/* switch off LED */
void led_off(void)
@ -57,8 +61,10 @@ ISR(PCINT2_vect)
{
if ((state_portD&(1<<SCALE_ON))!=(PIND&(1<<SCALE_ON))) { // scale on state changed
if (PIND&(1<<SCALE_ON)) {
scale_on = true;
led_on();
} else {
scale_on = false;
led_off();
}
}
@ -70,10 +76,17 @@ ISR(PCINT2_vect)
*/
ISR(ANALOG_COMP_vect)
{
if (ACSR&(1<<ACO)) { // PWM high
led_on();
} else { // PWM low
led_off();
if (scale_on && !measurement_flag) { // only save value if scale is on and previous value is read
measurement_value = TCNT1; // save value
TCNT1 = 0; // reset timer
if (ACSR&(1<<ACO)) { // PWM raising edge
pwm_high = false;
led_on();
} else { // PWM falling edge
pwm_high = true;
led_off();
}
measurement_flag = true; // signal new value is ready
}
}
@ -114,11 +127,15 @@ void io_init(void)
ACSR &= ~(1<<ACD); // enable analog comparator (should be per default)
ACSR &= ~(1<<ACBG); // use AIN0 as positiv input (should be per default)
ACSR |= (1<<ACI); // clear analog comparator interrup flag
ACSR |= (1<<ACIC); // enable analog comparator input capture (on timer 1)
ACSR &= ~((1<<ACIS1)|(1<<ACIS0)); // comparator interrupt on output toggle
DIDR1 |= ((1<<AIN1D)|(1<<AIN0D)); // disable digital input buffer on AIN0 and AIN1
ACSR |= (1<<ACIE); // enable analog comparator interrupt
/* use timer 1 (with capture unit) to measure PWM */
TCCR1A &= ~((1<<WGM11)|(1<<WGM10)); // mode 0: normal (should be per default)
TCCR1B &= ~((1<<WGM13)|(1<<WGM12)); // mode 0: normal (should be per default)
TCCR1B |= (1<<CS12)|(0<<CS11)|(0<<CS10); // set prescale to 256 for 1.048576s before overflow (PWM should be 3Hz)
sei(); /* enable interrupts */
}
@ -128,6 +145,15 @@ int main(void)
printf(PSTR("welcome to the body scale weight reader\n")); // print welcome message
while (true) { // endless loop for micro-controller
/* display value if available */
if (measurement_flag) {
if (pwm_high) {
printf("high: %u\n",measurement_value);
} else {
printf("low: %u\n",measurement_value);
}
measurement_flag = false;
}
/* go to sleep and wait for next interrupt */
set_sleep_mode(SLEEP_MODE_IDLE);
sleep_mode();