app4

Dependencies:   mbed-rtos mbed CRC16

Fork of S5info_APP2 by Éric Bisson

main.cpp

Committer:
ericbisson
Date:
2017-03-07
Revision:
14:bd909277eb13
Parent:
11:b27d1a83f688
Child:
15:7c2e70c36b98

File content as of revision 14:bd909277eb13:

#include "read.h"

Serial pc(USBTX, USBRX);
DigitalOut out(p8);

void initTimers()
{
    //Timer 1 (match)
    LPC_SC->PCLKSEL0 |= (1 << 4);           // pclk = cclk timer1
    LPC_SC->PCONP |= (1 << 2);              // timer1 power on
    LPC_TIM1->MR0 = CLOCKS_TO_SECOND / 100; // 100 ms
    LPC_TIM1->MCR = 3;                      // interrupt and reset control
    LPC_TIM1->EMR = (3 << 4);               // Interrupt & reset timer on match
    NVIC_EnableIRQ(TIMER1_IRQn);            // enable timer interrupt
    LPC_TIM1->TCR = 1;                      // enable Timer
 
    //Timer 2 (cap)
    LPC_SC->PCLKSEL1 |= (1 << 12);          // pclk = cclk timer2
    LPC_SC->PCONP |= (1 << 22);             // timer2 power on
    LPC_TIM2->TC = 0;                       // clear timer counter
    LPC_TIM2->PC = 0;                       // clear prescale counter
    LPC_TIM2->PR = 0;                       // clear prescale register
    LPC_TIM2->TCR |= (1 << 1);              // reset timer
    LPC_TIM2->TCR &= ~(1 << 1);             // release reset
    LPC_TIM2->IR = 0xFFFFFFFF;              // clear interrupt register
    LPC_TIM2->CCR |= 0x0000007;             // enable rising-edge and falling-edge capture
    NVIC_EnableIRQ(TIMER2_IRQn);            // enable timer interrupt
    LPC_TIM2->TCR = 1;                      // start Timer
}

bool bTimer1 = false;
extern "C" void TIMER1_IRQHandler()
{
    if ((LPC_TIM1->IR & 0x01) == 0x01)
    {
        bTimer1 = !bTimer1;
        
        LPC_TIM1->IR |= 1 << 0; // clear
    }
}

int sumClocks = 0;
int PeriodLength = 0;
bool bReceivedFirstBit = false;
extern "C" void TIMER2_IRQHandler()
{
    if (PeriodLength > 0)
    {
        if (LPC_TIM2->CR0 >= PeriodLength*1.5 || (sumClocks + clocks) >= PeriodLength*1.5)
        {
            sumClocks = 0;
            
            ThreadLecture.signal_set(1);
        }
        else
        {
            sumClocks += LPC_TIM2->CR0;
        }
    }
    else if (bReceivedFirstBit)
    {
        PeriodLength = LPC_TIM2->CR0 / 2;
        ThreadLecture.signal_set(1);
    }
    else
    {
        bReceivedFirstBit = true;
        ThreadLecture.signal_set(1);
    }
 
    LPC_TIM2->TC = 0;
    LPC_TIM2->IR |= 0xFFFFFFFF; // clear
}

int main() {
    LPC_PINCON->PINSEL0 |= (3 << 8); // pin30
    initTimers();
    ThreadLecture.attach(read);
    ThreadLecture.start();
    
    while(true) {
    }
};