Andrew Mkpanam
/
ADCandticker
final
Diff: main.cpp
- Revision:
- 4:ebd00f94455a
- Parent:
- 3:f5d7fddeef39
- Child:
- 6:28a86a76010b
--- a/main.cpp Thu Jan 31 11:10:30 2019 +0000 +++ b/main.cpp Thu Jan 31 13:53:15 2019 +0000 @@ -1,19 +1,19 @@ // LAB 3 SAMPLE PROGRAM 1 // Revised for mbed 5 +// Revised to replace Ticker with event queue and thread #include "mbed.h" -Ticker tick; // Ticker for reading analog AnalogIn ain(A0) ; // Analog input DigitalOut led1(LED_RED); // Red LED -DigitalOut led2(LED_BLUE); // BLUE LED +EventQueue queue; // creates an event queue, to call read ADC Serial pc(USBTX, USBRX); // tx, rx, for debugging -// Variable for a second thread -Thread ADCthread; +// This thread runs the event queue +Thread eventThread ; // Message type typedef struct { @@ -24,26 +24,23 @@ Mail<message_t, 2> mailbox; // Function called every 10ms to read ADC -// Low pass filter +// Average using a low pass filter // Every 10th value is sent to mailbox +volatile int samples = 0 ; +volatile uint16_t smoothed = 0 ; + void readA0() { - 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; + 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; + } } // Write voltage digits @@ -67,8 +64,11 @@ int counter = 0 ; char vstring[] = "X.XX\r\n" ; - // start the ADC reading thread - ADCthread.start(callback(readA0)); + // Start the event queue + eventThread.start(callback(&queue, &EventQueue::dispatch_forever)); + + // call the readA0 function every 10ms + queue.call_every(10, readA0) ; while (true) { osEvent evt = mailbox.get(); // wait for mail @@ -84,6 +84,5 @@ counter = 0 ; } } - } }