Nicholas Outram / Mbed OS Task443Solution
Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 
00003 //Function prototype
00004 void doSample1Hz();
00005 void printBinary12(unsigned short u16);
00006 
00007 //Global objects
00008 Serial pc(USBTX, USBRX);
00009 AnalogIn POT_ADC_In(A0);
00010 DigitalOut led(LED1);
00011 
00012 //Shared variables
00013 volatile static unsigned short sample16 = 0;
00014 
00015 //The ticker, used to sample data at a fixed rate
00016 Ticker t;
00017 
00018 //Main function
00019 int main()
00020 {
00021     //Set baud rate to 115200
00022     pc.baud(115200);
00023 
00024     //Set up the ticker - 100Hz
00025     t.attach(doSample1Hz, 1.0);
00026 
00027     while(1) {
00028 
00029         //Sleep
00030         sleep();
00031 
00032         //Displauy the sample in HEX
00033         printBinary12(sample16);
00034  
00035     } //end while(1)
00036 } //end main
00037 
00038 //ISR for the ticker - simply there to perform sampling
00039 void doSample1Hz()
00040 {
00041     //Toggle on board led
00042     led = !led;
00043 
00044     //READ ADC as an unsigned integer.
00045     //Shift right 4 bits (this is a 12bit ADC) & store in static global variable
00046     sample16 = POT_ADC_In.read_u16() >> 4;
00047 }
00048 
00049 //Function to print a 12-bit number in the binary format
00050 //(I've kept this simple to avoid confusion)
00051 void printBinary12(unsigned short u16)
00052 {
00053     unsigned int mask = 0x800; //Binary 1000000000000000
00054     for (unsigned int n=0; n<12; n++) {
00055         //Test to see if the bit is set
00056         if (u16 & mask) {
00057             pc.printf("1");
00058         } else {
00059             pc.printf("0");   
00060         }
00061         //Shift mask 1 bit right
00062         mask >>= 1;
00063     }
00064     pc.printf("\n"); 
00065 }