Simple Electronic Angle Meter and Spirit Level.

Dependencies:   MMA8452 mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

Go to the documentation of this file.
00001 /**
00002 @file main.cpp
00003 @brief Electronic Angle Meter and Spirit Level.
00004 @brief Revision 1.0.
00005 @author Shengyuan Chu
00006 @date May 2015
00007 */
00008 
00009 #include "mbed.h"
00010 #include "main.h"
00011 #include "MMA8452.h"
00012 #include "PowerControl/PowerControl.h"
00013 #include "PowerControl/EthernetPowerControl.h"
00014 
00015 /**
00016 @brief Connect all components to mbed LPC1768.
00017 @brief Connect LCD to pin 7,8,9,10,11,13,26.
00018 @brief Connect Accelerometer to pin 27,28.
00019 @brief Connect buzzer to pin 21.
00020 @brief Connect button to pin 17.
00021 @brief Connect LEDs to pin 22,23,24,25.
00022 */
00023 N5110 lcd(p7,p8,p9,p10,p11,p13,p26);
00024 MMA8452 mma8452(p28,p27);
00025 PwmOut buzzer(p21);
00026 DigitalIn pb(p17);                
00027 DigitalOut ledA(p25);
00028 DigitalOut ledB(p23);
00029 DigitalOut ledC(p22);
00030 DigitalOut ledD(p24);
00031 
00032 Serial serial(USBTX,USBRX);
00033 Timeout flipper;
00034 
00035 /**
00036 @brief Function prototypes.
00037 */
00038 void Switch (int functoion);           
00039 void AngleMeter();
00040 void SpiritLevel();
00041 void fun1();
00042 void fun2();
00043 
00044 /**
00045 @brief Different frequencies of buzzer.
00046 */
00047 float frequency1 = 1046.5;
00048 float frequency2 = 1174.7;
00049 float frequency3 = 1318.5;
00050 
00051 /**
00052 @brief Main function.
00053 @brief Call function of Angle Meter without pushing 
00054 @brief button when power is initally turned on.
00055 */
00056 int main() {
00057     
00058     /**Power down Ethernet interface to save power.*/    
00059     PHY_PowerDown();
00060     
00061     /**Initialise LCD and set brightness to 0.8.*/ 
00062     lcd.init();
00063     lcd.normalMode();    
00064     lcd.setBrightness(0.8);
00065     
00066     /**Display the name of Angle Meter function after the initialization of LCD.*/ 
00067     lcd.printString("Electronic",12,2);
00068     lcd.printString("Angle Meter",10,3);
00069     
00070     /**Call function of Angle Meter after 2 seconds' delay.*/ 
00071     flipper.attach(&AngleMeter, 2.0);
00072         
00073     /**Turn all the LEDs on when the power is initially turned on.*/ 
00074     ledA=1;
00075     ledB=1;
00076     ledC=1;
00077     ledD=1;
00078     
00079     /**Set button to PullDown mode.*/           
00080     pb.mode(PullDown);           
00081  
00082     /**Change the integer between 1 and 2 when button is pressed and send it to Switch function.*/
00083     int function = 1;        
00084     
00085     while(1) {
00086         if (pb){                 
00087             Switch(function); 
00088             
00089             /**Allow 0.2 second for button debounce.*/          
00090             wait(0.2);             
00091             while (pb);          
00092             {if (function == 2) function = 1; else function++;} 
00093         }        
00094     }   
00095 }
00096 
00097 /**
00098 @brief Switch functions between Angle Meter and Spirit Level.
00099 @param function - integer to change between 1 and 2.
00100 @return Call fun1() when function=2, call fun2() when function=1.
00101 */   
00102 void Switch (int function) 
00103 {         
00104     
00105     switch (function) {
00106         case 1 : fun2(); 
00107         break;
00108         case 2 : fun1(); 
00109         break;
00110     }
00111     
00112 }
00113 
00114  /**
00115  @brief Display angles in two dimensions and indicate directions using arrows.
00116  */
00117 void AngleMeter() 
00118 {    
00119     /**Initialise the accelerometer.*/       
00120     mma8452.init();
00121     Acceleration acceleration; 
00122     
00123     /**Lower down the brightness of LCD to 0.5.*/ 
00124     lcd.clear();
00125     lcd.setBrightness(0.5); 
00126     
00127     /**When button is not pushed, main features of Angle Meter will be run.*/ 
00128     while(!pb) {
00129         
00130         /**Display 'degree' in the last line of LCD.*/      
00131         lcd.printString("degree",3,5);
00132         lcd.printString("degree",46,5);
00133         
00134         /**Read value of acceleration.*/
00135         acceleration = mma8452.readValues();
00136     
00137         float X=acceleration.x;
00138         float Y=acceleration.y;
00139         float Z=acceleration.z;
00140         
00141         /**Calculate the angles in X and Y dimensions.*/
00142         float Ax=atan(X/sqrt(pow(Y,2)+pow(Z,2)))/3.14159265358979323846*180;
00143         float Ay=atan(Y/sqrt(pow(X,2)+pow(Z,2)))/3.14159265358979323846*180;
00144         
00145         /**Print formatted data to buffer.*/
00146         char buffer1[14]; 
00147         int length = sprintf(buffer1,"%.0f",abs(Ax));
00148         char buffer2[14]; 
00149         length = sprintf(buffer2,"%.0f",abs(Ay)); 
00150    
00151         /**Display values if string will fit on display.*/
00152         if (length <= 14)  // 
00153             lcd.printString(buffer1,20,3); 
00154             lcd.printString(buffer2,55,3);      
00155         
00156         /**LED C will be turned on if the angle in X dimension is larger than 20 degree.*/
00157         if (Ax>20)
00158             ledC=1;
00159         else
00160             ledC=0;
00161         
00162         /**LED A will be turned on if the angle in X dimension is smaller than -20 degree.*/
00163         if (Ax<-20)
00164             ledA=1;
00165         else
00166             ledA=0;
00167         
00168         /**LED D will be turned on if the angle in Y dimension is larger than 20 degree.*/ 
00169         if (Ay>20)
00170             ledD=1;
00171         else
00172             ledD=0;
00173         
00174         /**LED B will be turned on if the angle in Y dimension is smaller than -20 degree.*/
00175         if (Ay<-20)
00176             ledB=1;
00177         else
00178             ledB=0;
00179          
00180         /**Draw lines of the body of arrows.*/ 
00181         lcd.drawLine(58,6,58,16,1);
00182         lcd.drawLine(17,11,29,11,1);
00183         lcd.refresh();     
00184         
00185         /**Pixes will be set if the angle in Y dimension is larger than 0 degree.*/             
00186         if (Ay>=0){
00187             lcd.setPixel(60,5);
00188             lcd.setPixel(59,5);
00189             lcd.setPixel(58,5);
00190             lcd.setPixel(57,5);
00191             lcd.setPixel(56,5);
00192             lcd.setPixel(59,4);
00193             lcd.setPixel(58,4);
00194             lcd.setPixel(57,4);
00195             lcd.setPixel(58,3);
00196             lcd.refresh(); 
00197         }
00198         
00199         /**Pixes will be set if the angle in Y dimension is smaller than 0 degree.*/     
00200         else if (Ay<=0) {
00201             lcd.setPixel(60,17);
00202             lcd.setPixel(59,17);
00203             lcd.setPixel(58,17);
00204             lcd.setPixel(57,17);
00205             lcd.setPixel(56,17);
00206             lcd.setPixel(59,18);
00207             lcd.setPixel(58,18);
00208             lcd.setPixel(57,18);
00209             lcd.setPixel(58,19);
00210             lcd.refresh(); 
00211         }
00212         
00213         /**Pixes will be set if the angle in X dimension is larger than 0 degree.*/ 
00214         if (Ax>=0) {
00215             lcd.setPixel(30,13);
00216             lcd.setPixel(30,12);
00217             lcd.setPixel(30,11);
00218             lcd.setPixel(30,10);
00219             lcd.setPixel(30,9);
00220             lcd.setPixel(31,12);
00221             lcd.setPixel(31,11);
00222             lcd.setPixel(31,10);
00223             lcd.setPixel(32,11);
00224             lcd.refresh(); 
00225         }
00226         
00227         /**Pixes will be set if the angle in X dimension is smaller than 0 degree.*/     
00228         else if (Ax<=0) {
00229             lcd.setPixel(16,13);
00230             lcd.setPixel(16,12);
00231             lcd.setPixel(16,11);
00232             lcd.setPixel(16,10);
00233             lcd.setPixel(16,9);
00234             lcd.setPixel(15,12);
00235             lcd.setPixel(15,11);
00236             lcd.setPixel(15,10);
00237             lcd.setPixel(14,11);
00238             lcd.refresh(); 
00239         }
00240         
00241         /**Decrease the fluctuation of values.*/     
00242         wait(0.3);
00243         lcd.clear();
00244         
00245         /**Buzzer will beep in frequency 2 if the angle is between 50 and 75 degree.*/ 
00246         if ((abs(Ax) >= 50 && abs(Ax) < 75)||(abs(Ay) >= 50 && abs(Ay) < 75)) {
00247             buzzer.period(1/frequency2);
00248             buzzer=0.1;
00249         }  
00250         
00251         /**Buzzer will beep in frequency 3 if the angle is beyond 75 degree.*/            
00252         else if ((abs(Ax) >= 75)||(abs(Ay) >= 75)) {
00253             buzzer.period(1/frequency3);
00254             buzzer=0.1;
00255         }  
00256         
00257         /**Buzzer will not beep.*/
00258         else {
00259             buzzer.period(1/frequency1);
00260             buzzer=0;
00261         }         
00262     }     
00263     
00264     /**When button is pushed, main features will stop.*/
00265     while(pb) {
00266         break;
00267     }    
00268 }
00269      
00270 /**
00271 @brief Indicate the gradient in all directions by showing
00272 @brief the position of a group of pixes.
00273 */
00274 void SpiritLevel()
00275 {
00276     /**Initialise all the LEDs to be off.*/  
00277     ledA=0;
00278     ledB=0;
00279     ledC=0;
00280     ledD=0; 
00281 
00282     /**Set the LCD to inverse mode and lower down the brightness to 0.5.*/     
00283     lcd.clear();
00284     lcd.inverseMode(); 
00285     lcd.setBrightness(0.5);
00286     
00287     /**Initialise the accelerometer.*/      
00288     mma8452.init();    
00289     Acceleration acceleration; 
00290 
00291     /**When button is not pushed, main features of Spirit Level will be run.*/       
00292     while(!pb) {        
00293         
00294         /**Read value of acceleration.*/
00295         acceleration = mma8452.readValues();//read value of acceleration
00296         
00297         float Ax=acceleration.x;
00298         float Ay=acceleration.y;
00299 
00300         /**Draw three circles and two lines.*/
00301         lcd.drawCircle(41,24,23,0);
00302         lcd.drawCircle(41,24,4,0);
00303         lcd.drawCircle(41,24,13,0);
00304         lcd.drawLine(41,3,41,45,1);
00305         lcd.drawLine(20,24,62,24,1);       
00306         lcd.refresh();
00307     
00308         /**Pixes will be displayed if acceleration values are within -0.4 and 0.4.*/
00309         if (abs(Ax)<=0.4&&abs(Ay)<=0.4) {
00310      
00311             float X=Ax/0.018;
00312             float Y=Ay/0.018;
00313             
00314             lcd.setPixel(42+X, 26-Y);
00315             lcd.setPixel(41+X, 26-Y);
00316             lcd.setPixel(40+X, 26-Y);
00317             lcd.setPixel(43+X, 25-Y);
00318             lcd.setPixel(42+X, 25-Y);
00319             lcd.setPixel(41+X, 25-Y);
00320             lcd.setPixel(40+X, 25-Y);
00321             lcd.setPixel(39+X, 25-Y);
00322             lcd.setPixel(43+X, 24-Y);
00323             lcd.setPixel(42+X, 24-Y);
00324             lcd.setPixel(41+X, 24-Y);
00325             lcd.setPixel(40+X, 24-Y);
00326             lcd.setPixel(39+X, 24-Y);
00327             lcd.setPixel(43+X, 23-Y);
00328             lcd.setPixel(42+X, 23-Y);
00329             lcd.setPixel(41+X, 23-Y);
00330             lcd.setPixel(40+X, 23-Y);
00331             lcd.setPixel(39+X, 23-Y);
00332             lcd.setPixel(42+X, 22-Y);
00333             lcd.setPixel(41+X, 22-Y);
00334             lcd.setPixel(40+X, 22-Y);
00335             lcd.refresh();
00336             
00337             /**Displayed pixes will be cleared after 0.2 second.*/
00338             wait(0.2);
00339  
00340             lcd.clearPixel(42+X, 26-Y);
00341             lcd.clearPixel(41+X, 26-Y);
00342             lcd.clearPixel(40+X, 26-Y);    
00343             lcd.clearPixel(43+X, 25-Y);    
00344             lcd.clearPixel(42+X, 25-Y);
00345             lcd.clearPixel(41+X, 25-Y);
00346             lcd.clearPixel(40+X, 25-Y);
00347             lcd.clearPixel(39+X, 25-Y);
00348             lcd.clearPixel(43+X, 24-Y);    
00349             lcd.clearPixel(42+X, 24-Y);
00350             lcd.clearPixel(41+X, 24-Y);
00351             lcd.clearPixel(40+X, 24-Y);
00352             lcd.clearPixel(39+X, 24-Y);
00353             lcd.clearPixel(43+X, 23-Y);    
00354             lcd.clearPixel(42+X, 23-Y);
00355             lcd.clearPixel(41+X, 23-Y);
00356             lcd.clearPixel(40+X, 23-Y);
00357             lcd.clearPixel(39+X, 23-Y);
00358             lcd.clearPixel(42+X, 22-Y);
00359             lcd.clearPixel(41+X, 22-Y);
00360             lcd.clearPixel(40+X, 22-Y);
00361             lcd.refresh();    
00362         }
00363      
00364         /**All LEDs will be turned on if acceleration values are within -0.05 and 0.05.*/
00365         if (abs(Ax)<=0.05&&abs(Ay)<=0.05) {   
00366             ledA=1;
00367             ledB=1;
00368             ledC=1;
00369             ledD=1; 
00370         }
00371       
00372         /**All LEDs will be turned off if acceleration values go beyond this range.*/
00373         else {
00374             ledA=0;
00375             ledB=0;
00376             ledC=0;
00377             ledD=0; 
00378         }
00379     }
00380 }
00381         
00382 /**
00383 @brief Display the function name of Angle Meter for 1 second before calling it.
00384 */     
00385 void fun1() 
00386 {   
00387     /**Initialise the LCD and set brightness to 0.8.*/   
00388     lcd.init();
00389     lcd.normalMode();   
00390     lcd.setBrightness(0.8);
00391     lcd.clear();
00392     
00393     /**Display the function name of Angle Meter.*/   
00394     lcd.printString("Electronic",12,2);
00395     lcd.printString("Angle Meter",10,3);
00396     
00397     /**Turn LED A and LED C on.*/   
00398     ledA=1;
00399     ledB=0;
00400     ledC=1;
00401     ledD=0;
00402      
00403     /**Call function of Angle Meter after 1 second delay.*/      
00404     flipper.attach(&AngleMeter, 1.0);      
00405 }
00406 
00407 /**
00408 @brief Display the function name of Spirit Level for 1 second before calling it.
00409 */          
00410 void fun2()
00411 {
00412     /**Turn off the buzzer.*/   
00413     buzzer = 0;
00414     
00415     /**Initialise the LCD and set brightness to 0.8.*/   
00416     lcd.init();
00417     lcd.normalMode();    
00418     lcd.setBrightness(0.8);
00419     lcd.clear();
00420     
00421     /**Display the function name of Spirit Level.*/     
00422     lcd.printString("Electronic",12,2);
00423     lcd.printString("Spirit Level",7,3);
00424 
00425     /**Turn LED B and LED D on.*/                 
00426     ledA=0;
00427     ledB=1;
00428     ledC=0;
00429     ledD=1;
00430 
00431     /**Call function of Spirit Level after 1 second delay.*/           
00432     flipper.attach(&SpiritLevel, 1.0);       
00433 }
00434 
00435 /**
00436 @brief Power down the Ethernet interface to save power.
00437 @brief Acknowledgements to Michael Wei's code.
00438 */
00439 void PHY_PowerDown()
00440 {
00441     if (!Peripheral_GetStatus(LPC1768_PCONP_PCENET))
00442         EMAC_Init(); //init EMAC if it is not already init'd
00443     
00444     unsigned int regv;
00445     regv = read_PHY(PHY_REG_BMCR);
00446     write_PHY(PHY_REG_BMCR, regv | (1 << PHY_REG_BMCR_POWERDOWN));
00447     regv = read_PHY(PHY_REG_BMCR);
00448     
00449     //shouldn't need the EMAC now.
00450     Peripheral_PowerDown(LPC1768_PCONP_PCENET);
00451     
00452     //and turn off the PHY OSC
00453      LPC_GPIO1->FIODIR |= 0x8000000;
00454      LPC_GPIO1->FIOCLR = 0x8000000;
00455 }
00456 
00457 static void write_PHY (unsigned int PhyReg, unsigned short Value) {
00458     /* Write a data 'Value' to PHY register 'PhyReg'. */
00459     unsigned int tout;
00460     /* Hardware MII Management for LPC176x devices. */
00461     LPC_EMAC->MADR = DP83848C_DEF_ADR | PhyReg;
00462     LPC_EMAC->MWTD = Value;
00463  
00464     /* Wait utill operation completed */
00465     for (tout = 0; tout < MII_WR_TOUT; tout++) {
00466         if ((LPC_EMAC->MIND & MIND_BUSY) == 0) {
00467             break;
00468         }
00469     }
00470 }
00471  
00472 static unsigned short read_PHY (unsigned int PhyReg) {
00473    /* Read a PHY register 'PhyReg'. */
00474    unsigned int tout, val;
00475  
00476    LPC_EMAC->MADR = DP83848C_DEF_ADR | PhyReg;
00477    LPC_EMAC->MCMD = MCMD_READ;
00478  
00479    /* Wait until operation completed */
00480    for (tout = 0; tout < MII_RD_TOUT; tout++) {
00481       if ((LPC_EMAC->MIND & MIND_BUSY) == 0) {
00482          break;
00483       }
00484    }
00485    LPC_EMAC->MCMD = 0;
00486    val = LPC_EMAC->MRDD;
00487    
00488    return (val);
00489 }
00490 
00491 void EMAC_Init()
00492 {
00493     unsigned int tout,regv;
00494     /* Power Up the EMAC controller. */
00495     Peripheral_PowerUp(LPC1768_PCONP_PCENET);
00496   
00497     LPC_PINCON->PINSEL2 = 0x50150105;
00498     LPC_PINCON->PINSEL3 &= ~0x0000000F;
00499     LPC_PINCON->PINSEL3 |= 0x00000005;
00500  
00501     /* Reset all EMAC internal modules. */
00502     LPC_EMAC->MAC1 = MAC1_RES_TX | MAC1_RES_MCS_TX | MAC1_RES_RX | MAC1_RES_MCS_RX |
00503              MAC1_SIM_RES | MAC1_SOFT_RES;
00504     LPC_EMAC->Command = CR_REG_RES | CR_TX_RES | CR_RX_RES;
00505  
00506     /* A short delay after reset. */
00507     for (tout = 100; tout; tout--);
00508  
00509     /* Initialize MAC control registers. */
00510     LPC_EMAC->MAC1 = MAC1_PASS_ALL;
00511     LPC_EMAC->MAC2 = MAC2_CRC_EN | MAC2_PAD_EN;
00512     LPC_EMAC->MAXF = ETH_MAX_FLEN;
00513     LPC_EMAC->CLRT = CLRT_DEF;
00514     LPC_EMAC->IPGR = IPGR_DEF;
00515  
00516     /* Enable Reduced MII interface. */
00517     LPC_EMAC->Command = CR_RMII | CR_PASS_RUNT_FRM;
00518  
00519     /* Reset Reduced MII Logic. */
00520     LPC_EMAC->SUPP = SUPP_RES_RMII;
00521     for (tout = 100; tout; tout--);
00522     LPC_EMAC->SUPP = 0;
00523  
00524     /* Put the DP83848C in reset mode */
00525     write_PHY (PHY_REG_BMCR, 0x8000);
00526  
00527     /* Wait for hardware reset to end. */
00528     for (tout = 0; tout < 0x100000; tout++) {
00529         regv = read_PHY (PHY_REG_BMCR);
00530         if (!(regv & 0x8000)) {
00531             /* Reset complete */
00532             break;
00533         }
00534     }
00535 }
00536   
00537 /**
00538 @brief Functions used to display characters and shapes.
00539 @brief Acknowledgements to Dr.Craig A. Evans's code.
00540 */
00541 N5110::N5110(PinName pwrPin, PinName scePin, PinName rstPin, PinName dcPin, PinName mosiPin, PinName sclkPin, PinName ledPin)
00542 {
00543 
00544     spi = new SPI(mosiPin,NC,sclkPin); // create new SPI instance and initialise
00545     initSPI();
00546 
00547     // set up pins as required
00548     led = new PwmOut(ledPin);
00549     pwr = new DigitalOut(pwrPin);
00550     sce = new DigitalOut(scePin);
00551     rst = new DigitalOut(rstPin);
00552     dc = new DigitalOut(dcPin);
00553 
00554 }
00555 
00556 // initialise function - powers up and sends the initialisation commands
00557 void N5110::init()
00558 {
00559     turnOn();     // power up
00560     wait_ms(10);  // small delay seems to prevent spurious pixels during mbed reset
00561     reset();      // reset LCD - must be done within 100 ms
00562 
00563     // function set - extended
00564     sendCommand(0x20 | CMD_FS_ACTIVE_MODE | CMD_FS_HORIZONTAL_MODE | CMD_FS_EXTENDED_MODE);
00565     // Don't completely understand these parameters - they seem to work as they are
00566     // Consult the datasheet if you need to change them
00567     sendCommand(CMD_VOP_7V38);    // operating voltage - these values are from Chris Yan's Library
00568     sendCommand(CMD_TC_TEMP_2);   // temperature control
00569     sendCommand(CMD_BI_MUX_48);   // bias
00570 
00571     // function set - basic
00572     sendCommand(0x20 | CMD_FS_ACTIVE_MODE | CMD_FS_HORIZONTAL_MODE | CMD_FS_BASIC_MODE);
00573     normalMode();  // normal video mode by default
00574     sendCommand(CMD_DC_NORMAL_MODE);  // black on white
00575 
00576     // RAM is undefined at power-up so clear
00577     clearRAM();
00578 
00579 }
00580 
00581 // sets normal video mode (black on white)
00582 void N5110::normalMode()
00583 {
00584     sendCommand(CMD_DC_NORMAL_MODE);
00585 
00586 }
00587 
00588 // sets normal video mode (white on black)
00589 void N5110::inverseMode()
00590 {
00591     sendCommand(CMD_DC_INVERT_VIDEO);
00592 }
00593 
00594 // function to power up the LCD and backlight
00595 void N5110::turnOn()
00596 {
00597     // set brightness of LED - 0.0 to 1.0 - default is 50%
00598     setBrightness(0.5);
00599     pwr->write(1);  // apply power
00600 }
00601 
00602 // function to power down LCD
00603 void N5110::turnOff()
00604 {
00605     setBrightness(0.0);  // turn backlight off
00606     clearRAM();   // clear RAM to ensure specified current consumption
00607     // send command to ensure we are in basic mode
00608     sendCommand(0x20 | CMD_FS_ACTIVE_MODE | CMD_FS_HORIZONTAL_MODE | CMD_FS_BASIC_MODE);
00609     // clear the display
00610     sendCommand(CMD_DC_CLEAR_DISPLAY);
00611     // enter the extended mode and power down
00612     sendCommand(0x20 | CMD_FS_POWER_DOWN_MODE | CMD_FS_HORIZONTAL_MODE | CMD_FS_EXTENDED_MODE);
00613     // small delay and then turn off the power pin
00614     wait_ms(10);
00615     pwr->write(0);
00616 
00617 }
00618 
00619 // function to change LED backlight brightness
00620 void N5110::setBrightness(float brightness)
00621 {
00622     // check whether brightness is within range
00623     if (brightness < 0.0)
00624         brightness = 0.0;
00625     if (brightness > 1.0)
00626         brightness = 1.0;
00627     // set PWM duty cycle
00628     led->write(brightness);
00629 }
00630 
00631 // pulse the active low reset line
00632 void N5110::reset()
00633 {
00634     rst->write(0);  // reset the LCD
00635     rst->write(1);
00636 }
00637 
00638 // function to initialise SPI peripheral
00639 void N5110::initSPI()
00640 {
00641     spi->format(8,1);    // 8 bits, Mode 1 - polarity 0, phase 1 - base value of clock is 0, data captured on falling edge/propagated on rising edge
00642     spi->frequency(4000000);  // maximum of screen is 4 MHz
00643 }
00644 
00645 // send a command to the display
00646 void N5110::sendCommand(unsigned char command)
00647 {
00648     dc->write(0);  // set DC low for command
00649     sce->write(0); // set CE low to begin frame
00650     spi->write(command);  // send command
00651     dc->write(1);  // turn back to data by default
00652     sce->write(1); // set CE high to end frame (expected for transmission of single byte)
00653 
00654 }
00655 
00656 // this function writes 0 to the 504 bytes to clear the RAM
00657 void N5110::clearRAM()
00658 {
00659     int i;
00660     sce->write(0);  //set CE low to begin frame
00661     for(i = 0; i < WIDTH * HEIGHT; i++) { // 48 x 84 bits = 504 bytes
00662         spi->write(0x00);  // send 0's
00663     }
00664     sce->write(1); // set CE high to end frame
00665 
00666 }
00667 
00668 // function to set the XY address in RAM for subsequenct data write
00669 void N5110::setXYAddress(int x, int y)
00670 {
00671     if (x>=0 && x<WIDTH && y>=0 && y<HEIGHT) {  // check within range
00672         sendCommand(0x80 | x);  // send addresses to display with relevant mask
00673         sendCommand(0x40 | y);
00674     }
00675 }
00676 
00677 // These functions are used to set, clear and get the value of pixels in the display
00678 // Pixels are addressed in the range of 0 to 47 (y) and 0 to 83 (x).  The refresh()
00679 // function must be called after set and clear in order to update the display
00680 void N5110::setPixel(int x, int y)
00681 {
00682     if (x>=0 && x<WIDTH && y>=0 && y<HEIGHT) {  // check within range
00683         // calculate bank and shift 1 to required position in the data byte
00684         buffer[x][y/8] |= (1 << y%8);
00685     }
00686 }
00687 
00688 void N5110::clearPixel(int x, int y)
00689 {
00690     if (x>=0 && x<WIDTH && y>=0 && y<HEIGHT) {  // check within range
00691         // calculate bank and shift 1 to required position (using bit clear)
00692         buffer[x][y/8] &= ~(1 << y%8);
00693     }
00694 }
00695 
00696 // function to refresh the display
00697 void N5110::refresh()
00698 {
00699     int i,j;
00700 
00701     setXYAddress(0,0);  // important to set address back to 0,0 before refreshing display
00702     // address auto increments after printing string, so buffer[0][0] will not coincide
00703     // with top-left pixel after priting string
00704 
00705     sce->write(0);  //set CE low to begin frame
00706 
00707     for(j = 0; j < BANKS; j++) {  // be careful to use correct order (j,i) for horizontal addressing
00708         for(i = 0; i < WIDTH; i++) {
00709             spi->write(buffer[i][j]);  // send buffer
00710         }
00711     }
00712     sce->write(1); // set CE high to end frame
00713 
00714 }
00715 
00716 // function to print string at specified position
00717 void N5110::printString(const char * str,int x,int y)
00718 {
00719     if (y>=0 && y<BANKS) {  // check if printing in range of y banks
00720 
00721         int n = 0 ; // counter for number of characters in string
00722         // loop through string and print character
00723         while(*str) {
00724 
00725             // writes the character bitmap data to the buffer, so that
00726             // text and pixels can be displayed at the same time
00727             for (int i = 0; i < 5 ; i++ ) {
00728                 int pixel_x = x+i+n*6;
00729                 if (pixel_x > WIDTH-1) // ensure pixel isn't outside the buffer size (0 - 83)
00730                     break;
00731                 buffer[pixel_x][y] = font5x7[(*str - 32)*5 + i];
00732             }
00733 
00734             str++;  // go to next character in string
00735 
00736             n++;    // increment index
00737 
00738         }
00739 
00740         refresh();  // this sends the buffer to the display and sets address (cursor) back to 0,0
00741     }
00742 }
00743 
00744 // function to clear the screen
00745 void N5110::clear()
00746 {
00747     clearBuffer();  // clear the buffer then call the refresh function
00748     refresh();
00749 }
00750 
00751 // function to clear the buffer
00752 void N5110::clearBuffer()
00753 {
00754     int i,j;
00755     for (i=0; i<WIDTH; i++) {  // loop through the banks and set the buffer to 0
00756         for (j=0; j<BANKS; j++) {
00757             buffer[i][j]=0;
00758         }
00759     }
00760 }
00761 
00762 // function to draw circle
00763 void N5110:: drawCircle(int x0,int y0,int radius,int fill)
00764 {
00765     // from http://en.wikipedia.org/wiki/Midpoint_circle_algorithm
00766     int x = radius;
00767     int y = 0;
00768     int radiusError = 1-x;
00769 
00770     while(x >= y) {
00771 
00772         // if transparent, just draw outline
00773         if (fill == 0) {
00774             setPixel( x + x0,  y + y0);
00775             setPixel(-x + x0,  y + y0);
00776             setPixel( y + x0,  x + y0);
00777             setPixel(-y + x0,  x + y0);
00778             setPixel(-y + x0, -x + y0);
00779             setPixel( y + x0, -x + y0);
00780             setPixel( x + x0, -y + y0);
00781             setPixel(-x + x0, -y + y0);
00782         } else {  // drawing filled circle, so draw lines between points at same y value
00783 
00784             int type = (fill==1) ? 1:0;  // black or white fill
00785 
00786             drawLine(x+x0,y+y0,-x+x0,y+y0,type);
00787             drawLine(y+x0,x+y0,-y+x0,x+y0,type);
00788             drawLine(y+x0,-x+y0,-y+x0,-x+y0,type);
00789             drawLine(x+x0,-y+y0,-x+x0,-y+y0,type);
00790         }
00791 
00792 
00793         y++;
00794         if (radiusError<0) {
00795             radiusError += 2 * y + 1;
00796         } else {
00797             x--;
00798             radiusError += 2 * (y - x) + 1;
00799         }
00800     }
00801 
00802 }
00803 
00804 void N5110::drawLine(int x0,int y0,int x1,int y1,int type)
00805 {
00806     int y_range = y1-y0;  // calc range of y and x
00807     int x_range = x1-x0;
00808     int start,stop,step;
00809 
00810     // if dotted line, set step to 2, else step is 1
00811     step = (type==2) ? 2:1;
00812 
00813     // make sure we loop over the largest range to get the most pixels on the display
00814     // for instance, if drawing a vertical line (x_range = 0), we need to loop down the y pixels
00815     // or else we'll only end up with 1 pixel in the x column
00816     if ( abs(x_range) > abs(y_range) ) {
00817 
00818         // ensure we loop from smallest to largest or else for-loop won't run as expected
00819         start = x1>x0 ? x0:x1;
00820         stop =  x1>x0 ? x1:x0;
00821 
00822         // loop between x pixels
00823         for (int x = start; x<= stop ; x+=step) {
00824             // do linear interpolation
00825             int y = y0 + (y1-y0)*(x-x0)/(x1-x0);
00826 
00827             if (type == 0)   // if 'white' line, turn off pixel
00828                 clearPixel(x,y);
00829             else
00830                 setPixel(x,y);  // else if 'black' or 'dotted' turn on pixel
00831         }
00832     } else {
00833 
00834         // ensure we loop from smallest to largest or else for-loop won't run as expected
00835         start = y1>y0 ? y0:y1;
00836         stop =  y1>y0 ? y1:y0;
00837 
00838         for (int y = start; y<= stop ; y+=step) {
00839             // do linear interpolation
00840             int x = x0 + (x1-x0)*(y-y0)/(y1-y0);
00841 
00842             if (type == 0)   // if 'white' line, turn off pixel
00843                 clearPixel(x,y);
00844             else
00845                 setPixel(x,y);  // else if 'black' or 'dotted' turn on pixel
00846 
00847         }
00848     }
00849 
00850 }
00851 
00852 MMA8452:: MMA8452(PinName sdaPin, PinName sclPin)
00853 {
00854     i2c = new I2C(sdaPin,sclPin); // create new I2C instance and initialise
00855     i2c->frequency(400000);       // I2C Fast Mode - 400kHz
00856     leds = new BusOut(LED4,LED3,LED2,LED1);  // for debug
00857 }
00858 
00859 void MMA8452::init()
00860 {
00861 
00862     i2c->frequency(400000); // set Fast Mode I2C frequency (5.10 datasheet)
00863 
00864     char data = readByteFromRegister(WHO_AM_I);  // p18 datasheet
00865     if (data != 0x2A) { // if correct ID not found, hand and flash error message
00866         error();
00867     }
00868 
00869     // put into STANDBY while configuring
00870     data = readByteFromRegister(CTRL_REG1); // get current value of register
00871     data &= ~(1<<0); // clear bit 0 (p37 datasheet)
00872     sendByteToRegister(data,CTRL_REG1);
00873 
00874     // Set output data rate, default is 800 Hz, will set to 100 Hz (clear b5, set b4/b3 - p37 datasheet)
00875     data = readByteFromRegister(CTRL_REG1);
00876     data &= ~(1<<5);
00877     data |=  (1<<4);
00878     data |=  (1<<3);
00879     sendByteToRegister(data,CTRL_REG1);
00880 
00881     //// Can also change default 2g range to 4g or 8g (p22 datasheet)
00882     data = readByteFromRegister(XYZ_DATA_CFG);
00883     data |=  (1<<0); // set bit 0 - 4g range
00884     sendByteToRegister(data,XYZ_DATA_CFG);
00885 
00886     // set ACTIVE
00887     data = readByteFromRegister(CTRL_REG1);
00888     data |= (1<<0);   // set bit 0 in CTRL_REG1
00889     sendByteToRegister(data,CTRL_REG1);
00890 
00891 }
00892 
00893 // read acceleration data from device
00894 Acceleration MMA8452::readValues()
00895 {
00896     // acceleration data stored in 6 registers (0x01 to 0x06)
00897     // device automatically increments register, so can read 6 bytes starting from OUT_X_MSB
00898     char data[6];
00899     readBytesFromRegister(OUT_X_MSB,6,data);
00900 
00901     char x_MSB = data[0];  // extract MSB and LSBs for x,y,z values
00902     char x_LSB = data[1];
00903     char y_MSB = data[2];
00904     char y_LSB = data[3];
00905     char z_MSB = data[4];
00906     char z_LSB = data[5];
00907 
00908     // [0:7] of MSB are 8 MSB of 12-bit value , [7:4] of LSB are 4 LSB's of 12-bit value
00909     // need to type-cast as numbers are in signed (2's complement) form (p20 datasheet)
00910     int x = (int16_t) (x_MSB << 8) | x_LSB;  // combine bytes
00911     x >>= 4;  // are left-aligned, so shift 4 places right to right-align
00912     int y = (int16_t) (y_MSB << 8) | y_LSB;
00913     y >>= 4;
00914     int z = (int16_t) (z_MSB << 8) | z_LSB;
00915     z >>= 4;
00916 
00917     // sensitivity is 1024 counts/g in 2g mode (pg 9 datasheet)
00918     //  "   "          512      "      4g     "
00919     //  "   "          256      "      8g     "
00920     Acceleration acc;
00921     
00922     acc.x = x/512.0;
00923     acc.y = y/512.0;
00924     acc.z = z/512.0;
00925     
00926     return acc;
00927 }
00928 
00929 // reads a byte from a specific register
00930 char MMA8452::readByteFromRegister(char reg)
00931 {
00932     int nack = i2c->write(MMA8452_W_ADDRESS,&reg,1,true);  // send the register address to the slave
00933     // true as need to send repeated start condition (5.10.1 datasheet)
00934     // http://www.i2c-bus.org/repeated-start-condition/
00935     if (nack)
00936         error();  // if we don't receive acknowledgement, flash error message
00937 
00938     char rx;
00939     nack = i2c->read(MMA8452_R_ADDRESS,&rx,1);  // read a byte from the register and store in buffer
00940     if (nack)
00941         error();  // if we don't receive acknowledgement, flash error message
00942 
00943     return rx;
00944 }
00945 
00946 // reads a series of bytes, starting from a specific register
00947 void MMA8452::readBytesFromRegister(char reg,int numberOfBytes,char bytes[])
00948 {
00949 
00950     int nack = i2c->write(MMA8452_W_ADDRESS,&reg,1,true);  // send the slave write address and the configuration register address
00951     // true as need to send repeated start condition (5.10.1 datasheet)
00952     // http://www.i2c-bus.org/repeated-start-condition/
00953 
00954     if (nack)
00955         error();  // if we don't receive acknowledgement, flash error message
00956 
00957     nack = i2c->read(MMA8452_R_ADDRESS,bytes,numberOfBytes);  // read bytes
00958     if (nack)
00959         error();  // if we don't receive acknowledgement, flash error message
00960 
00961 }
00962 
00963 // sends a byte to a specific register
00964 void MMA8452::sendByteToRegister(char byte,char reg)
00965 {
00966     char data[2];
00967     data[0] = reg;
00968     data[1] = byte;
00969     // send the register address, followed by the data
00970     int nack = i2c->write(MMA8452_W_ADDRESS,data,2);
00971     if (nack)
00972         error();  // if we don't receive acknowledgement, flash error message
00973 
00974 }
00975 
00976 void MMA8452::error()
00977 {
00978     while(1) {
00979         leds->write(15);
00980         wait(0.1);
00981         leds->write(0);
00982         wait(0.1);
00983     }
00984 }
00985 
00986 
00987 
00988