
timer0 stopwatch
Diff: main.cpp
- Revision:
- 0:ec69a5b677ed
diff -r 000000000000 -r ec69a5b677ed main.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/main.cpp Fri Oct 03 17:47:43 2014 +0000 @@ -0,0 +1,128 @@ +#include "mbed.h" +#include "TextLCD.h" +#include <stdio.h> +#include <stdlib.h> + +TextLCD lcd(p15, p16, p17, p18, p19, p20, TextLCD::LCD16x2); +Serial pc (USBTX, USBRX); +DigitalOut myled(LED1); + +// global vars +int t [6]; +int run_status = -1; + +// functions +void update_display(); +void update_timer(); +void init_timer0(); + +int main() { + + // init timer and display + for (int i=0;i<6;i++) t[i]=0; + update_display(); + + // init timer + init_timer0(); + char input = 'z'; + + while(1) { + + if ( input == 's') { + run_status = 1; + LPC_TIM0->TCR |= 1; + } + if ( input == 'p') { + run_status = 2; + LPC_TIM0->TCR &= ~1; + } + if ( input == 'r') { + if (run_status == 2) { + for (int i=0; i<6; i++) t[i]=0; + update_display(); + } + } + + input = pc.getc(); + + } +} + +void update_display() { + lcd.printf("%d%d:%d%d:%d%d\n\n",t[5],t[4],t[3],t[2],t[1],t[0]); +} + +void update_timer() { +// signal = 1 : start +// signal = 2 : stop + + if (run_status == 1) { + + // update m0 + t[0]++; + + // update m1 + if (t[0] >= 10) { + t[0] = 0; + t[1]++; + + // update S0 + if (t[1] >= 10) { + t[1] = 0; + t[2]++; + + // update S1 + if (t[2] >= 10) { + t[2] = 0; + t[3]++; + + // update M0 + if (t[3] >= 6) { + t[3]=0; + t[4]++; + + // update M1 + if (t[4] >= 10) { + t[4]=0; + t[5]++; + } + } + } + } + } + + // update display + update_display(); + } + + // reset interrupt + LPC_TIM0->IR |= 1 << 0; +} + +void init_timer0() { + + //power up TIMER0 (PCONP[1]) + LPC_SC->PCONP |= 1 << 1; + + // reset and set TIMER0 to timer mode + LPC_TIM0->TCR = 0x2; + LPC_TIM0->CTCR = 0x0; + + // set no prescaler + LPC_TIM0->PR = 0; + + // calculate period (1 interrupt every 1/100 second) + uint32_t period = 240000; + + // set match register and enable interrupt + LPC_TIM0->MR0 = period; + LPC_TIM0->MCR |= 1 << 0; // interrupt on match + LPC_TIM0->MCR |= 1 << 1; // reset on match + + // enable the vector in the interrupt controller + NVIC_SetVector(TIMER0_IRQn, (uint32_t)&update_timer); + NVIC_EnableIRQ(TIMER0_IRQn); + + // start the timer + LPC_TIM0->TCR = 1; +} \ No newline at end of file