4. An implementation of the system as thread(s) written in protothread style, plus additional code that monitors the serial port and touch sensors, and dispatches them to the threads.
main.cpp
- Committer:
- manujose
- Date:
- 2010-11-30
- Revision:
- 0:3667ad9a98cc
File content as of revision 0:3667ad9a98cc:
#include "mbed.h" #include "pt.h" #include "pt-sem.h" int touchSense1(void); int touchSense2(void); int getTouch(void); void hostError(void); void touchError(void); DigitalOut myled1(LED1); DigitalOut myled2(LED3); AnalogIn input1(p20); AnalogIn input2(p15); DigitalIn charger1(p19); DigitalIn charger2(p16); DigitalOut ground1(p18); DigitalOut ground2(p17); Serial pc(USBTX, USBRX); // tx, rx #define DEBUG 1 static struct pt_sem dataArrived; static char BUF[1024]; static int readFromHost(struct pt *pt) { char c; int i,len,error ; PT_BEGIN(pt); PT_WAIT_UNTIL(pt,pc.readable()); //wait until there is a data in the serial port. i=0; c='k'; error = 0; while (pc.readable() && c!='S') c = pc.getc(); while (pc.readable() && (c != 'E')) { if (c != ' ') { // pc.printf(" READ %c\n",c); BUF[i++] = c; if ((i>1) && (c!='0') &&(c!='1')) { hostError(); error = 1; } } // pc.printf("READING %c \n",c); c = pc.getc(); } BUF[i] = c; BUF[i+1]='\0'; while (pc.readable()) //bufferout rest; c=pc.getc(); len = strlen(BUF)-1; //to make it right offset if ((BUF[0]!='S') || (BUF[len] != 'E')) { if (!error) hostError(); error = 1; } if (!error) PT_SEM_SIGNAL(pt, &dataArrived); PT_END(pt); } static int readFromCapacitor(struct pt *pt) { PT_BEGIN(pt); char mybuf[1024]; int i, len,error; int t_bit, h_bit; PT_SEM_WAIT(pt, &dataArrived); strcpy(mybuf, BUF); #ifdef DEBUG pc.printf(" Data arrived %s \n",mybuf); #endif i = 1; error = 0; len = strlen(mybuf)-1; while (i<len) { t_bit = getTouch(); #ifdef DEBUG pc.printf("\n MY TOKEN IS %c and touch is %d\n",mybuf[i],t_bit); #endif if (mybuf[i] == '0') h_bit = 0; else if (mybuf[i] == '1') h_bit = 1; if (t_bit != h_bit) { touchError(); error = 1; } i++; } if (!error) pc.printf("MATCH\n"); PT_END(pt); } static struct pt pt1, pt2; int main() { PT_SEM_INIT(&dataArrived, 0); PT_INIT(&pt1); PT_INIT(&pt2); while (1) { readFromHost(&pt1); readFromCapacitor(&pt2); wait(0.005); } } int getTouch(void) { int sens; while (1) { sens = 0; if (touchSense1()) { wait_ms(5); while (touchSense1()) { // pc.printf("In touchsense1\n"); sens = 1; wait_ms(100); } if (sens) return 0; } if (touchSense2()) { wait_ms(5); while (touchSense2()) { // pc.printf("In touchsense2\n"); sens = 1; wait_ms(100); } if (sens) return 1; } } } int touchSense1(void) { float sample; ground1 = 0; charger1.mode(PullUp); charger1.mode(PullNone); sample=input1.read(); if (sample < 0.3) { return 1; } else { return 0; } } int touchSense2(void) { float sample; ground2 = 0; charger2.mode(PullUp); charger2.mode(PullNone); sample=input2.read(); if (sample < 0.3) { return 1; } else { return 0; } } void hostError() { pc.printf("HOST ERROR"); } void touchError() { pc.printf("TOUCH ERROR"); }