HW2 implemented using busy loop

main.cpp

Committer:
the729
Date:
2010-12-01
Revision:
0:9db2667ac0d3

File content as of revision 0:9db2667ac0d3:

#include "mbed.h"

//DigitalOut led1(LED1);
//DigitalOut led2(LED2);

Serial pc(USBTX, USBRX);

#define BTN0 p15
#define BTN1 p20
#define MAX_LENGTH 32

typedef unsigned int uint32_t;
typedef unsigned char uint8_t;

void precharge(PinName p) 
{
    DigitalIn prec(p);
    prec.mode(PullUp);
    prec.mode(PullNone);
}

uint8_t read_cap() 
{
    precharge(BTN0);
    precharge(BTN1);
    wait_ms(5);
    float s0 = AnalogIn(BTN0);
    float s1 = AnalogIn(BTN1);
    //pc.printf("%f \r", s0);
    return ((s0>0.5)?0:1) + ((s1>0.5)?0:2);
}

int main() 
{
    enum {
        IDLE=0, 
        HOST_INPUT,
        USER_INPUT
    } state;
    uint8_t c = 0;
    uint32_t data = 0;
    uint8_t datalength = 0;
    
    state = IDLE;
    while (1) {
        switch(state) {
            case IDLE:
                pc.putc(c = pc.getc());
                if (c == 'S') {
                    datalength = 0;
                    state = HOST_INPUT;
                } else {
                    pc.printf("HOST ERROR. You are supposed to input S. Try again. \r\n");
                }
                break;
            case HOST_INPUT:
                pc.putc(c = pc.getc());
                if (c == '0' || c == '1') {
                    datalength ++;
                    if (datalength > MAX_LENGTH) {
                        pc.printf("\r\nLength execeeds maximum. \r\n");
                    } else {
                        data = (data << 1) | (c-'0');
                    }
                } else if (c == 'E') {
                    pc.printf("\r\nInput End. Tap the caps now. \r\n");
                    if (!datalength) {
                        pc.printf("Zero length. Try again. \r\n");
                        state = IDLE;
                        break;
                    }
                    data <<= (32-datalength);
                    state = USER_INPUT;
                } else {
                    pc.printf("\r\nHOST ERROR. \r\n");
                }
                break;
            case USER_INPUT:
                c = read_cap();
                if (!c) break;
                wait_ms(10);
                if (c != read_cap()) break;
                while(read_cap()); 
                if (c == 3) {
                    pc.printf("\r\nTOUCH ERROR. Touch only one. \r\n");
                    break;
                }
                c -= 1;
                pc.putc(c + '0');
                if (c == (data >> 31)) {
                    datalength--;
                    if (!datalength) {
                        pc.printf("\r\nMATCH! \r\n");
                        state = IDLE;
                    }
                    data <<= 1;
                } else {
                    pc.printf("\r\nTOUCH ERROR. \r\n");
                }
                break;
        }
    }
}