Lab3-task2
Fork of ADCandticker_sample by
Embed:
(wiki syntax)
Show/hide line numbers
main.cpp
00001 00002 // LAB 3 SAMPLE PROGRAM 1 00003 // Revised for mbed 5 00004 00005 #include "mbed.h" 00006 #include "sinTable.h" 00007 00008 Ticker tickout ; // Creates periodic interrupt 00009 AnalogOut ao(PTE30) ; // Analog output 00010 00011 Ticker tick; // Ticker for reading analog 00012 AnalogIn ain(A0) ; // Analog input 00013 DigitalOut led1(LED_RED); 00014 00015 00016 Serial pc(USBTX, USBRX); // tx, rx, for debugging 00017 00018 // Message type 00019 typedef struct { 00020 uint16_t analog; /* Analog input value */ 00021 } message_t; 00022 00023 // Mail box 00024 Mail<message_t, 2> mailbox; 00025 00026 // Function called every 10ms to read ADC 00027 // Low pass filter 00028 // Every 10th value is sent to mailbox 00029 volatile int samples = 0 ; 00030 volatile uint16_t smoothed = 0 ; 00031 void readA0() { 00032 smoothed = (smoothed >> 1) + (ain.read_u16() >> 1) ; 00033 samples++ ; 00034 if (samples == 10) { 00035 // send to thread 00036 message_t *mess = mailbox.alloc() ; // may fail but does not block 00037 if (mess) { 00038 mess->analog = smoothed ; 00039 mailbox.put(mess); // fails but does not block if full 00040 } 00041 samples = 0; 00042 } 00043 } 00044 00045 // Write voltage digits 00046 // v Voltage as scale int, e.g. 3.30 is 330 00047 void vToString(int v, char* s) { 00048 s[3] = '0' + (v % 10) ; 00049 v = v / 10 ; 00050 s[2] = '0' + (v % 10) ; 00051 v = v / 10 ; 00052 s[0] = '0' + (v % 10) ; 00053 } 00054 00055 volatile int index = 0 ; // index into array of sin values 00056 void writeAout() { 00057 ao.write_u16(sine[index]) ; 00058 index = (index + 1) % 64 ; 00059 } 00060 00061 // Main program 00062 // Initialise variables 00063 // Attach ISR for ticker 00064 // Procss messages from mailbox 00065 int main() { 00066 00067 int update_us = 1000 ; 00068 float tempupdate = 0.0; 00069 int volts = 0; 00070 led1 = 1 ; // turn off 00071 int counter = 0 ; 00072 char vstring[] = "X.XX\r\n" ; 00073 00074 tick.attach_us(callback(&readA0), 10000); // ticks every 10ms 00075 00076 00077 while (true) 00078 { 00079 osEvent evt = mailbox.get(); // wait for mail 00080 if (evt.status == osEventMail) 00081 { 00082 message_t* mess = (message_t*)evt.value.p ; 00083 volts = (mess->analog * 330) / 0xffff ; 00084 mailbox.free(mess) ; // free the message space 00085 00086 update_us = 1000000/((1+(49*volts/330))*64) ; 00087 tickout.detach() ; 00088 tickout.attach_us(callback(&writeAout), update_us); 00089 00090 // vToString(volts, vstring) ; 00091 00092 /* counter++ ; 00093 if (counter == 10) { // limit bandwidth of 00094 pc.printf(vstring); 00095 pc.printf("%d\n",update_us); 00096 counter = 0 ; 00097 } 00098 */ 00099 } 00100 00101 } 00102 }
Generated on Sat Jul 23 2022 02:46:12 by
1.7.2
