malcolm lear / Mbed 2 deprecated labmbedV31

Dependencies:   mbed HTTPServer EthernetNetIf TextLCD

Fork of HTTPServerHelloWorld by Robert Gutknecht

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 // Device Drivers for Labmbed Board
00002 
00003 #include "mbed.h"
00004 #include "TextLCD.h"
00005 #include "EthernetNetIf.h"
00006 #include "HTTPServer.h"
00007 
00008 TextLCD lcd(p15, p16, p17, p18, p19, p20);            // LCD: RS, E, D4-D7
00009 SPI spi(p5, p6, p7);                                  // SPI: MOSI, MISO, SCLK (MISO not used with LCD)
00010 DigitalOut lat(p8);                                   // data latch for LED driver TLC59281
00011 DigitalOut Sel0(p26);                                 // input select bits:
00012 DigitalOut Sel1(p25);                                 //  "
00013 DigitalOut Sel2(p24);                                 //  "
00014 DigitalIn In0(p14);                                   // input from switches, keypad etc
00015 DigitalIn In1(p13);                                   //  "
00016 DigitalIn In2(p12);                                   //  "
00017 DigitalIn In3(p11);                                   //  "
00018 I2C i2c(p9, p10);                                     // I2C: SDA, SCL pins
00019 PwmOut servo1(p21);                                   // servo 1 PWM pin
00020 PwmOut servo2(p22);                                   // servo 2 PWM pin
00021 DigitalOut Trigger(p28);                              // ultrasonic rangefinder trigger pin
00022 DigitalIn  Echo(p27);                                 // ultrasonic rangefinder echo pin
00023 Timer Sonar;                                          // ultrasonic timer
00024 DigitalOut led1(LED1);                                // web server stay alive indication
00025 Serial out(USBTX, USBRX);                             // used for wev server
00026 LocalFileSystem fs("webfs");                          // web server local file system
00027 EthernetNetIf eth;                                    //
00028 HTTPServer svr;                                       //
00029 Ticker WebUpdate;                                     // interrupt timer to service web page requests
00030 
00031 // global variables
00032 short LEDbits = 0;                                    // global led status used for readback
00033 const int TMP102Addr = 0x92;                          // TMP102 temperature I2C address
00034 const int MPU6050Addr = 0xd0;                         // MPU-6050 accelerometer and Gyro I2C address
00035 float Acceleration[3];                                // MPU-6050 x,y,z acceleration values in 1G floating point
00036 float GyroRate[3];                                    // MPU-6050 x,y,z gyrorates in degrees per second
00037 float GyroOffset[3];                                  // MPU-6050 x,y,z gyrorates compensation
00038 char AReg[] = { 0x3b, 0x3d, 0x3f };                   // MPU-6050 I2C x,y,z accelerometer data registers
00039 char GReg[] = { 0x43, 0x45, 0x47 };                   // MPU-6050 I2C x,y,z gyro data registers
00040 extern "C" void mbed_mac_address(char *mac);          //
00041 
00042 void WebServerPoll () {
00043     Net::poll();                                      // bump web server into action
00044     led1=!led1;                                       // show that web server polling is alive
00045 }
00046 
00047 int InitWebServer() {
00048   EthernetErr ethErr = eth.setup();
00049   if(ethErr) {
00050     return -1;                                        // ethernet setup error
00051   }
00052   FILE *fp = fopen("/webfs/index.htm", "w");          // open "out.txt" on the local file system for writing
00053   fprintf(fp, "<html><head><title>Hello World online</title></head><body><h1>Hello World from Mbed NXP LPC1768!</h1></body></html>");
00054   fclose(fp);                                         // close file
00055   FSHandler::mount("/webfs", "/files");               // mount /webfs path on /files web path
00056   FSHandler::mount("/webfs", "/");                    // mount /webfs path on web root path
00057   svr.addHandler<SimpleHandler>("/hello");
00058   svr.addHandler<RPCHandler>("/rpc");
00059   svr.addHandler<FSHandler>("/files");
00060   svr.addHandler<FSHandler>("/");                     // default handler
00061   svr.bind(80);                                       // example : http://155.245.21.144
00062   WebUpdate.attach(&WebServerPoll, 0.1);              // update webserver every 100ms
00063   return 0;                                           // return without error
00064 }
00065 
00066 void HTTPText(char t[100]) {
00067   FILE *fp = fopen("/webfs/index.htm", "w");          // open "index.htm" on the local file system for writing
00068   fprintf(fp, t);                                     // print to file
00069   fclose(fp);                                         // close file
00070 }
00071 
00072 void Servo1(float s) {                                // range +-1
00073     s=s+1;
00074     if (s>=0 && s<=2) {
00075         servo1.pulsewidth(s/2000+0.001);              // pulse 1 - 2 ms
00076     }
00077 }
00078 
00079 void Servo2(float s) {                                // range +-1
00080     s=s+1;
00081     if (s>=0 && s<=2) {
00082         servo2.pulsewidth(s/2000+0.001);              // pulse 1 - 2 ms
00083     }
00084 }
00085 
00086 void InitServos() {
00087     servo1.period(0.02);                              //
00088     servo2.period(0.02);                              //
00089     Servo1(0);                                        // initiate servo 1 to centre position
00090     Servo2(0);                                        // initiate servo 1 to centre position
00091 }
00092 
00093 int ReadSonar() {
00094     Trigger = 1;                                      // set sonar trigger pulse high
00095     Sonar.reset();                                    // reset sonar timer
00096     wait_us(10.0);                                    // 10 us pulse
00097     Trigger = 0;                                      // set sonar trigger pulse low
00098     while (Echo == 0) {};                             // wait for echo high (8 cycles have been transmitted)
00099     Sonar.start();                                    // echo high so start timer
00100     while (Echo == 1) {};                             // wait for echo low
00101     Sonar.stop();                                     // echo low so stop timer
00102     return (Sonar.read_us()*10)/58;                   // read timer and scale to mm
00103 }
00104 
00105 void InitLEDs() {
00106     lat = 0;                                          // latch must start low
00107     spi.format(16,0);                                 // SPI 16 bit data, low state, high going clock
00108     spi.frequency(1000000);                           // 1MHz clock rate
00109 }
00110 
00111 void SetLEDs(short ledall) {
00112     LEDbits = ledall;                                 // update global led status
00113     spi.write((LEDbits & 0x03ff) | ((LEDbits & 0xa800) >> 1) | ((LEDbits & 0x5400) << 1));
00114     lat = 1;                                          // latch pulse start 
00115     lat = 0;                                          // latch pulse end
00116 }
00117 
00118 void SetLED(short LEDNo, short LEDState) {
00119     LEDNo = ((LEDNo - 1) & 0x0007) + 1;               // limit led number
00120     LEDState = LEDState & 0x0003;                     // limit led state
00121     LEDNo = (8 - LEDNo) * 2;                          // offset of led state in 'LEDbits'
00122     LEDState = LEDState << LEDNo;
00123     short statemask = ((0x0003 << LEDNo) ^ 0xffff);   // mask used to clear led state
00124     LEDbits = ((LEDbits & statemask) | LEDState);     // clear and set led state
00125     SetLEDs(LEDbits);
00126 }
00127 
00128 short ReadLED(short LEDNo) {
00129     LEDNo = ((LEDNo - 1) & 0x0007) + 1;               // limit led number
00130     LEDNo = (8 - LEDNo) * 2;                          // offset of led state in 'LEDbits'
00131     short LEDState = (LEDbits >> LEDNo) & 0x0003;     // shift selected led state into ls 2 bits
00132     return LEDState;                                  // return led state
00133 }
00134 
00135 short ReadLEDs() {
00136     return LEDbits;                                   // return led status
00137 }
00138 
00139 void SelInput(short Input) {
00140     Sel0 = Input & 0x0001;                            // set sel[0:2] pins
00141     Sel1 = (Input >> 1) & 0x0001;                     //
00142     Sel2 = (Input >> 2) & 0x0001;                     //
00143 }
00144 
00145 short ReadSwitches() {
00146     SelInput(5);                                      // select least significant 4 switches in[3:0]
00147     short Switches = In0 + (In1 << 1) + (In2 << 2) + (In3 << 3);
00148     SelInput(4);                                      // select most significant 4 switches in[3:0]
00149     return (Switches + (In0 << 4) + (In1 << 5) + (In2 << 6) + (In3 << 7));
00150 }
00151 
00152 short ReadSwitch(short SwitchNo) {
00153     SwitchNo = ((SwitchNo - 1) & 0x0007) + 1;         // limit switch number
00154     SwitchNo = 8 - SwitchNo;                          // offset of switch state in ReadSwitches()
00155     short SwitchState = ReadSwitches();               // read switch states
00156     SwitchState = SwitchState >> SwitchNo;            // shift selected switch state into ls bit
00157     return (SwitchState & 0x0001);                    // mask out and return switch state 
00158 }
00159 
00160 short ReadKeys() {
00161     SelInput(0);                                      // select Keypad top row 
00162     short Keys = (In0 << 15) + (In1 << 14) + (In2 << 13) + (In3 << 12);
00163     SelInput(1);                                      // select Keypad second row
00164     Keys += (In0 << 3) + (In1 << 6) + (In2 << 9) + (In3 << 11);   
00165     SelInput(2);                                      // select Keypad third row
00166     Keys += (In0 << 2) + (In1 << 5) + (In2 << 8) + In3;  
00167     SelInput(3);                                      // select Keypad forth row
00168     Keys += (In0 << 1) + (In1 << 4) + (In2 << 7) + (In3 << 10);
00169     return (Keys ^ 0xffff);                           // return inverted (Key press active high)
00170 }
00171 
00172 short ReadKey(short KeyNo) {
00173     KeyNo = KeyNo & 0x000f;                           // limit key number 0 to 15 (0 to F)
00174     short KeyState = ReadKeys();                      // read key states
00175     KeyState = KeyState >> KeyNo;                     // shift selected key state into ls bit
00176     return (KeyState & 0x0001);                       // mask out and return key state     
00177 }
00178 
00179 int FindKeyNo() {
00180     short KeyNo;
00181     short KeyPressed = -1;                            // set KeyPressed to -1 (no key pressed)
00182     short KeyState = ReadKeys();                      // read key states
00183     for (KeyNo= 0; KeyNo < 16; KeyNo++ ) {            // check all 16 Keys
00184         if (KeyState & 0x0001) {                      // check key state
00185             if (KeyPressed == -1) {                   // check if key already found
00186                 KeyPressed = KeyNo;                   // update KeyPressed
00187             }
00188             else {
00189                 return -1;                            // 2 or more keys pressed
00190             }
00191         }
00192         KeyState = KeyState >> 1;                     // shift to check next key
00193     }
00194     return KeyPressed;                                // return KeyPressed
00195 }
00196 
00197 char FindKeyChar() {
00198     short KeyNo;
00199     char KeyChar = ' ';                               // set KeyChar to ' ' (no key pressed)
00200     KeyNo = FindKeyNo();                              // find key pressed
00201     if (KeyNo < 10 && KeyNo >= 0) {
00202         KeyChar = (char) KeyNo + 0x30;                // convert char 0-9 to ascii string '0'-'9'
00203     }
00204     if (KeyNo > 9 && KeyNo < 16) {
00205         KeyChar = (char) KeyNo + 0x37;                // convert char 10-15 to ascii string 'A'-'F'
00206     }
00207     return KeyChar;                                   // return key pressed
00208 }
00209 
00210 float ReadTemp() {
00211     char Cmd[3];
00212     Cmd[0] = 0x01;                                    // pointer register value
00213     Cmd[1] = 0x60;                                    // byte 1 of the configuration register
00214     Cmd[2] = 0xa0;                                    // byte 2 of the configuration register
00215     i2c.write(TMP102Addr, Cmd, 3);                    // select configuration register and write 0x60a0 to it
00216     wait(0.5);                                        // ensure conversion time
00217     Cmd[0] = 0x00;                                    // pointer register value
00218     i2c.write(TMP102Addr, Cmd, 1);                    // select temperature register
00219     i2c.read(TMP102Addr, Cmd, 2);                     // read 16-bit temperature register 
00220     return (float((Cmd[0] << 8) | Cmd[1]) / 256);     // divide by 256 and return temperature
00221 }
00222 
00223 signed short ReadMPU6050(int RegAddr) {
00224     char Cmd[3];
00225     Cmd[0] = RegAddr;                                 // register address
00226     i2c.write(MPU6050Addr, Cmd, 1);                   // select register to read
00227     i2c.read(MPU6050Addr, Cmd, 2);                    // read 2 bytes from register
00228     return ((Cmd[0] << 8) | Cmd[1]);                  // return signed 16 bit value
00229 }
00230 
00231 void CalibrateGyros() {
00232     short a,b;
00233     for(a=0; a<3; a++) {
00234         GyroOffset[a] = 0;                            // clear gyro calibration offsets
00235         for(b=0; b<1000; b++) {
00236             GyroOffset[a] = GyroOffset[a] + (float)ReadMPU6050(GReg[a]);
00237             wait_ms(1);                               // wait for next sample
00238         }  
00239         GyroOffset[a] = GyroOffset[a]/1000;           // find average over 1000 samples
00240     }
00241 }
00242    
00243 void InitMotion() {
00244     char Cmd[3];
00245     Cmd[0] = 0xa1;                                    // config register address
00246     Cmd[1] = 0x06;                                    // accelerometer and gyro bandwidth = 5Hz
00247     i2c.write(MPU6050Addr, Cmd, 2);                   // write data to config register      
00248     Cmd[0] = 0x6b;                                    // power management register address
00249     Cmd[1] = 0x00;                                    // data
00250     i2c.write(MPU6050Addr, Cmd, 2);                   // write data to power management register   
00251     Cmd[0] = 0x1b;                                    // gyro configuration register address
00252     Cmd[1] = 0x08;                                    // no gyro self test, +-500 full scale
00253     i2c.write(MPU6050Addr, Cmd, 2);                   // write data to gyro configuration register
00254     Cmd[0] = 0x19;                                    // sample rate register address
00255     Cmd[1] = 0x07;                                    // sample rate = gyro output rate / 8
00256     i2c.write(MPU6050Addr, Cmd, 2);                   // write data to sample rate register    
00257     CalibrateGyros();           
00258 }
00259 
00260 void ReadMotion() {
00261     short a;                                          // Acceleration is in G where 1G = 9.81 ms/s
00262     for(a=0; a<3; a++) {                              // GyroRate is in degrees per second
00263         Acceleration[a] =  (float)ReadMPU6050(AReg[a]) / 16384;      
00264         GyroRate[a] = ((float)ReadMPU6050(GReg[a]) - GyroOffset[a]) / 66.5;
00265     }
00266 } 
00267 
00268 int main() {
00269     
00270     float spos = 0;                                   // Test servo position
00271     char mac[6];                                      // MAC address
00272     InitLEDs();                                       //
00273     InitMotion();                                     //
00274     InitServos();                                     //
00275     InitWebServer();                                  //
00276   
00277     while(1) {
00278         int a,b;
00279         for (b = 0; b < 4; b++ ) {                    // select all 4 led states
00280             for (a = 1; a < 9; a++ ) {                // set all 8 leds to selected state
00281                 SetLED (a,b);                         // set led 'a' to state 'b'
00282                 wait(.05);                            // wait 0.05 second
00283             }
00284         }
00285         for (a= 1; a < 9; a++ ) {                     // map Switch states to led's
00286             SetLED (a,(ReadSwitch(a) + 1));           //
00287             wait(.05);                                // wait 0.05 second
00288         }
00289         float temp = ReadTemp();                      // get temperature
00290         lcd.cls();                                    // clear lcd
00291         lcd.printf("Temp = %f\n", temp);              // print temperature
00292         wait(1);                                      // wait 1 second
00293         lcd.cls();                                    // clear lcd
00294         int swch = ReadSwitches();                    // look at Switch states   
00295         lcd.printf("Switches = %d\n", swch);          // print result
00296         char Key = FindKeyChar();                     // look for Key pressed
00297         lcd.printf("Key = %c\n", Key);                // print result
00298         wait(1);                                      // wait 1 second
00299         lcd.cls();                                    // clear lcd
00300 //        int dist = ReadSonar();                       // get distance
00301 //        lcd.printf("Distance = %d\n", dist);          // print result
00302         lcd.printf("Servo = %f\n", spos);             // print servo pos
00303         wait(1);                                      // wait 1 second
00304         ReadMotion();                                 // read new data in from the MPU-6050
00305         lcd.cls();                                    // clear lcd
00306         lcd.locate(0,0);                              // print at start of first line
00307         lcd.printf("x%.1f y%.1f z%.1f", Acceleration[0], Acceleration[1], Acceleration[2]);
00308         lcd.locate(0,1);                              // print at start of second line
00309         lcd.printf("x%.1f y%.1f z%.1f", GyroRate[0], GyroRate[1], GyroRate[2]);   
00310         wait(1);                                      // wait 1 second
00311         lcd.cls();                                    // clear lcd
00312         lcd.printf("MAC Address = ");                 // print to LCD
00313         mbed_mac_address(mac);                        // get MAC address
00314         for(int i=0; i<6;i++) {                       // step through MAC address characters
00315             lcd.printf("%02X ", mac[i]);              // print MAC address
00316         }
00317         printf("\n");                                 //
00318         wait(.4);                                     // wait 0.4 second
00319         if (spos < 1) {                               // is servo at upper limit of 1
00320           spos += .1;                                 // increment servo position
00321         }                                             //
00322         else {                                        // was at upper limit so
00323           spos = -1;                                  // reset servo position
00324         }                                             //
00325         Servo1(spos);                                 // update servo
00326         // HTTPText("<html><head><title>Hello World online</title></head><body><h1>New Message !!!!</h1></body></html>");
00327         char Buffer[200];
00328         sprintf(Buffer, "%s %.3f %s %1.1f %s", "<html><head><title>Hello World online</title></head><body><h1> Temperature = ", temp, "<br/>Servo = ", spos, "</h1></body></html>");
00329         HTTPText(Buffer);                             // ouput temperature on web page 
00330     }
00331 }