
Varying frequency by potentiometer working.
main.cpp
- Committer:
- gtanvir
- Date:
- 2019-02-14
- Revision:
- 5:0dd98c2ac767
- Parent:
- 4:75ad475aff41
File content as of revision 5:0dd98c2ac767:
// Lab 3 Example Program 2 // ----------------------- // This code uses the Ticker API to create a periodic interrupt // Devices used in this way must not call locks; a variant of // the AnalogOut device w/o locking is created for this. // // Updated for mbed 5 // THIS VERSION HAS NO DEBUGGING CODE #include "mbed.h" #include "sineTable.h" // -------------------------- // This declaration introduces a derived version of the mbed AnalogOut // class with the locking removed. // You do NOT NEED TO UNDERSTAND this class AnalogOut_unsafe : public AnalogOut { public: AnalogOut_unsafe (PinName pin) : AnalogOut (pin) {} protected: virtual void lock() {} virtual void unlock() {} }; // -------------------------- Ticker tick ; // Creates periodic interrupt AnalogOut_unsafe ao(PTE30) ; // Analog output AnalogIn ain(A0) ; // Analog input // Function called periodically // Write new value to AnalogOut volatile int index = 0 ; // index into array of sin values void writeAout() { ao.write_u16(sine[index]) ; index = (index + 1) % 64 ; } EventQueue queue; // creates an event queue, to call read ADC Serial pc(USBTX, USBRX); // tx, rx, for debugging // This thread runs the event queue Thread eventThread ; // Message type typedef struct { uint16_t analog; /* Analog input value */ } message_t; // Mail box Mail<message_t, 3> mailbox; // Function called every 10ms to read ADC // Average using a 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 } samples = 0; } } // Control the frequency of updates // Alternative between two frequencies int main() { int update_us = 1000 ; // 1ms int volts = 0 ; int timeDelay = 0; int frequency = 0; // 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 if (evt.status == osEventMail) { message_t* mess = (message_t*)evt.value.p ; volts = (mess->analog * 330) / 0xffff ; mailbox.free(mess) ; // free the message space } frequency = (1+volts*49/329); // Freq Range: 1~50Hz. V = maximum voltage of ADC timeDelay = 1000000/(frequency*64); // Time is in microseconds update_us = timeDelay ; tick.attach_us(callback(&writeAout), update_us); // setup ticker to write to AnalogOut } }