Sebastian Barrera
/
Lab3_ADC
Proposed solution to lab 3
Diff: main.cpp
- Revision:
- 3:f5d7fddeef39
- Parent:
- 1:126dd2f5fc2d
- Child:
- 4:ebd00f94455a
diff -r dad9e6e165e7 -r f5d7fddeef39 main.cpp --- a/main.cpp Wed Jan 23 17:05:06 2019 +0000 +++ b/main.cpp Thu Jan 31 11:10:30 2019 +0000 @@ -1,6 +1,6 @@ // LAB 3 SAMPLE PROGRAM 1 -// Revised for mbed 5 +// Revised for mbed 5 #include "mbed.h" @@ -8,9 +8,13 @@ Ticker tick; // Ticker for reading analog AnalogIn ain(A0) ; // Analog input DigitalOut led1(LED_RED); // Red LED +DigitalOut led2(LED_BLUE); // BLUE LED Serial pc(USBTX, USBRX); // tx, rx, for debugging +// Variable for a second thread +Thread ADCthread; + // Message type typedef struct { uint16_t analog; /* Analog input value */ @@ -22,19 +26,23 @@ // Function called every 10ms to read ADC // Low pass filter // Every 10th value is sent to mailbox -volatile int samples = 0 ; -volatile uint16_t smoothed = 0 ; void readA0() { - smoothed = (smoothed >> 1) + (ain.read_u16() >> 1) ; - samples++ ; - if (samples == 10) { - // send to thread - message_t *mess = mailbox.alloc() ; // may fail but does not block - if (mess) { - mess->analog = smoothed ; - mailbox.put(mess); // fails but does not block if full + int samples = 0 ; + uint16_t smoothed = 0 ; + while (true) { + wait(0.01) ; // every 10 ms + led2 = 1 ; + smoothed = (smoothed >> 1) + (ain.read_u16() >> 1) ; + samples++ ; + if (samples == 10) { + // send to thread + message_t *mess = mailbox.alloc() ; // may fail but does not block + if (mess) { + mess->analog = smoothed ; + mailbox.put(mess); // fails but does not block if full + } + samples = 0; } - samples = 0; } } @@ -58,8 +66,10 @@ const int threshold = 100 ; int counter = 0 ; char vstring[] = "X.XX\r\n" ; + + // start the ADC reading thread + ADCthread.start(callback(readA0)); - tick.attach_us(callback(&readA0), 10000); // ticks every 10ms while (true) { osEvent evt = mailbox.get(); // wait for mail if (evt.status == osEventMail) {