Alexandre Lemay / Mbed 2 deprecated APP4_FunTimes

Dependencies:   mbed mbed-rtos

Receiver.cpp

Committer:
ThierryLeonard
Date:
2017-10-23
Revision:
4:a3c4a43f94f8
Child:
6:ac7c0ccf9b5d

File content as of revision 4:a3c4a43f94f8:

#include <Receiver.h>


InterruptIn DO(p21);

const int us_period = 10000;

void ReceiverData::setTime()
{
    lastTime = time.read_us();
}

void ReceiverData::addBit(unsigned char bit)
{
    setTime();
    if(bit != 0)
    {
        // MSB First
        temp = temp | 1 << (7-currentBit);
    }
    
    currentBit++;

    // If filled  a whole byte, send it to the data
    if(currentBit == 8) {
        data.push_back(temp);        
        temp = 0;
        currentBit = 0;
    }
}

void ReceiverData::clear()
{
    currentBit =0;
    lastTime =0;
    temp =0;
    data.clear();
    time.stop();    
}


void ReceiverData::fall()
{
    if(!ready){
        return;
    }
    
    if(waiting()) {
        //First data is a 0 (rising edge)
        return;
    }
    if(time.read_us() - lastTime < us_period/2) {
        // This transition is not real data.
        return;
    } else {
        addBit(1);
    }
}

void ReceiverData::rise()
{
    if(!ready){
        return;
    }
    
    if(waiting()) {
        // Should be the first 0 in the first byte
        receiving = true;
        addBit(0);
        return;
    }

    if(time.read_us() - lastTime < us_period/2) {
        // This transition is not real data.
        return;
    } else {
        addBit(0);
    }
}

void ReceiverData::waitData()
{
    dataSemaphore.wait();
}

void ReceiverData::timeout()
{
    if(!receiving){
        return;
    }
    if(time.read_us() - lastTime > 3/2 * us_period )
    {   // Finished
        dataSemaphore.release();
        
        watchDog.detach();
        ready = false;
    }
}

void ReceiverData::start()
{
    clear();
    DO.fall(this,&ReceiverData::fall);
    DO.rise(this, &ReceiverData::rise);
    watchDog.attach(this, &ReceiverData::timeout,us_period);
    ready = true;
}