Shengyuan Chu
/
AngleMeter
Simple Electronic Angle Meter and Spirit Level.
Diff: main.cpp
- Revision:
- 0:2885d4453e88
- Child:
- 1:f167423f6f0c
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/main.cpp Mon May 11 12:24:48 2015 +0000 @@ -0,0 +1,988 @@ +/** +@file main.cpp +@brief Electronic Angle Meter and Gradienter. +@brief Revision 1.0. +@author Shengyuan Chu +@date May 2015 +*/ + +#include "mbed.h" +#include "main.h" +#include "MMA8452.h" +#include "PowerControl/PowerControl.h" +#include "PowerControl/EthernetPowerControl.h" + +/** +@brief Connect all components to mbed LPC1768. +@brief Connect LCD to pin 7,8,9,10,11,13,26. +@brief Connect Accelerometer to pin 27,28. +@brief Connect buzzer to pin 21. +@brief Connect button to pin 17. +@brief Connect LEDs to pin 22,23,24,25. +*/ +N5110 lcd(p7,p8,p9,p10,p11,p13,p26); +MMA8452 mma8452(p28,p27); +PwmOut buzzer(p21); +DigitalIn pb(p17); +DigitalOut ledA(p25); +DigitalOut ledB(p23); +DigitalOut ledC(p22); +DigitalOut ledD(p24); + +Serial serial(USBTX,USBRX); +Timeout flipper; + +/** +@brief Function prototypes. +*/ +void Switch (int functoion); +void AngleMeter(); +void Gradienter(); +void fun1(); +void fun2(); + +/** +@brief Different frequencies of buzzer. +*/ +float frequency1 = 440; +float frequency2 = 554; +float frequency3 = 659; + +/** +@brief Main function. +@brief Call function of Angle Meter without pushing +@brief button when power is initally turned on. +*/ +int main() { + + /**Power down Ethernet interface to save power.*/ + PHY_PowerDown(); + + /**Initialise LCD and set brightness to 0.8.*/ + lcd.init(); + lcd.normalMode(); + lcd.setBrightness(0.8); + + /**Display the name of Angle Meter function after the initialization of LCD.*/ + lcd.printString("Electronic",12,2); + lcd.printString("Angle Meter",10,3); + + /**Call function of Angle Meter after 2 seconds' delay.*/ + flipper.attach(&AngleMeter, 2.0); + + /**Turn all the LEDs on when the power is initially turned on.*/ + ledA=1; + ledB=1; + ledC=1; + ledD=1; + + /**Set button to PullDown mode.*/ + pb.mode(PullDown); + + /**Change the integer between 1 and 2 when button is pressed and send it to Switch function.*/ + int function = 1; + + while(1) { + if (pb){ + Switch(function); + + /**Allow 0.2 second for button debounce.*/ + wait(0.2); + while (pb); + {if (function == 2) function = 1; else function++;} + } + } +} + +/** +@brief Switch functions between Angle Meter and Gradienter. +@param function - integer to change between 1 and 2. +@return Call fun1() when function=2, call fun2() when function=1. +*/ +void Switch (int function) +{ + + switch (function) { + case 1 : fun2(); + break; + case 2 : fun1(); + break; + } + +} + + /** + @brief Display angles in two dimensions and indicate directions using arrows. + */ +void AngleMeter() +{ + /**Initialise the accelerometer.*/ + mma8452.init(); + Acceleration acceleration; + + /**Lower down the brightness of LCD to 0.5.*/ + lcd.clear(); + lcd.setBrightness(0.5); + + /**When button is not pushed, main features of Angle Meter will be run.*/ + while(!pb) { + + /**Display 'degree' in the last line of LCD.*/ + lcd.printString("degree",3,5); + lcd.printString("degree",46,5); + + /**Read value of acceleration.*/ + acceleration = mma8452.readValues(); + + float X=acceleration.x; + float Y=acceleration.y; + float Z=acceleration.z; + + /**Calculate the angles in X and Y dimensions.*/ + float Ax=atan(X/sqrt(pow(Y,2)+pow(Z,2)))/3.14159265358979323846*180; + float Ay=atan(Y/sqrt(pow(X,2)+pow(Z,2)))/3.14159265358979323846*180; + + /**Print formatted data to buffer.*/ + char buffer1[14]; + int length = sprintf(buffer1,"%.0f",abs(Ax)); + char buffer2[14]; + length = sprintf(buffer2,"%.0f",abs(Ay)); + + /**Display values if string will fit on display.*/ + if (length <= 14) // + lcd.printString(buffer1,20,3); + lcd.printString(buffer2,55,3); + + /**LED C will be turned on if the angle in X dimension is larger than 20 degree.*/ + if (Ax>20) + ledC=1; + else + ledC=0; + + /**LED A will be turned on if the angle in X dimension is smaller than -20 degree.*/ + if (Ax<-20) + ledA=1; + else + ledA=0; + + /**LED D will be turned on if the angle in Y dimension is larger than 20 degree.*/ + if (Ay>20) + ledD=1; + else + ledD=0; + + /**LED B will be turned on if the angle in Y dimension is smaller than -20 degree.*/ + if (Ay<-20) + ledB=1; + else + ledB=0; + + /**Draw lines of the body of arrows.*/ + lcd.drawLine(58,6,58,16,1); + lcd.drawLine(17,11,29,11,1); + lcd.refresh(); + + /**Pixes will be set if the angle in Y dimension is larger than 0 degree.*/ + if (Ay>=0){ + lcd.setPixel(60,5); + lcd.setPixel(59,5); + lcd.setPixel(58,5); + lcd.setPixel(57,5); + lcd.setPixel(56,5); + lcd.setPixel(59,4); + lcd.setPixel(58,4); + lcd.setPixel(57,4); + lcd.setPixel(58,3); + lcd.refresh(); + } + + /**Pixes will be set if the angle in Y dimension is smaller than 0 degree.*/ + else if (Ay<=0) { + lcd.setPixel(60,17); + lcd.setPixel(59,17); + lcd.setPixel(58,17); + lcd.setPixel(57,17); + lcd.setPixel(56,17); + lcd.setPixel(59,18); + lcd.setPixel(58,18); + lcd.setPixel(57,18); + lcd.setPixel(58,19); + lcd.refresh(); + } + + /**Pixes will be set if the angle in X dimension is larger than 0 degree.*/ + if (Ax>=0) { + lcd.setPixel(30,13); + lcd.setPixel(30,12); + lcd.setPixel(30,11); + lcd.setPixel(30,10); + lcd.setPixel(30,9); + lcd.setPixel(31,12); + lcd.setPixel(31,11); + lcd.setPixel(31,10); + lcd.setPixel(32,11); + lcd.refresh(); + } + + /**Pixes will be set if the angle in X dimension is smaller than 0 degree.*/ + else if (Ax<=0) { + lcd.setPixel(16,13); + lcd.setPixel(16,12); + lcd.setPixel(16,11); + lcd.setPixel(16,10); + lcd.setPixel(16,9); + lcd.setPixel(15,12); + lcd.setPixel(15,11); + lcd.setPixel(15,10); + lcd.setPixel(14,11); + lcd.refresh(); + } + + /**Decrease the fluctuation of values.*/ + wait(0.3); + lcd.clear(); + + /**Buzzer will beep in frequency 2 if the angle is between 50 and 75 degree.*/ + if ((abs(Ax) >= 50 && abs(Ax) < 75)||(abs(Ay) >= 50 && abs(Ay) < 75)) { + buzzer.period(1/frequency2); + buzzer=0.1; + } + + /**Buzzer will beep in frequency 3 if the angle is beyond 75 degree.*/ + else if ((abs(Ax) >= 75)||(abs(Ay) >= 75)) { + buzzer.period(1/frequency3); + buzzer=0.1; + } + + /**Buzzer will not beep.*/ + else { + buzzer.period(1/frequency1); + buzzer=0; + } + } + + /**When button is pushed, main features will stop.*/ + while(pb) { + break; + } +} + +/** +@brief Indicate the gradient in all directions by showing +@brief the position of a group of pixes. +*/ +void Gradienter() +{ + /**Initialise all the LEDs to be off.*/ + ledA=0; + ledB=0; + ledC=0; + ledD=0; + + /**Set the LCD to inverse mode and lower down the brightness to 0.5.*/ + lcd.clear(); + lcd.inverseMode(); + lcd.setBrightness(0.5); + + /**Initialise the accelerometer.*/ + mma8452.init(); + Acceleration acceleration; + + /**When button is not pushed, main features of Gradienter will be run.*/ + while(!pb) { + + /**Read value of acceleration.*/ + acceleration = mma8452.readValues();//read value of acceleration + + float Ax=acceleration.x; + float Ay=acceleration.y; + + /**Draw three circles and two lines.*/ + lcd.drawCircle(41,24,23,0); + lcd.drawCircle(41,24,4,0); + lcd.drawCircle(41,24,13,0); + lcd.drawLine(41,3,41,45,1); + lcd.drawLine(20,24,62,24,1); + lcd.refresh(); + + /**Pixes will be displayed if acceleration values are within -0.4 and 0.4.*/ + if (abs(Ax)<=0.4&&abs(Ay)<=0.4) { + + float X=Ax/0.018; + float Y=Ay/0.018; + + lcd.setPixel(42+X, 26-Y); + lcd.setPixel(41+X, 26-Y); + lcd.setPixel(40+X, 26-Y); + lcd.setPixel(43+X, 25-Y); + lcd.setPixel(42+X, 25-Y); + lcd.setPixel(41+X, 25-Y); + lcd.setPixel(40+X, 25-Y); + lcd.setPixel(39+X, 25-Y); + lcd.setPixel(43+X, 24-Y); + lcd.setPixel(42+X, 24-Y); + lcd.setPixel(41+X, 24-Y); + lcd.setPixel(40+X, 24-Y); + lcd.setPixel(39+X, 24-Y); + lcd.setPixel(43+X, 23-Y); + lcd.setPixel(42+X, 23-Y); + lcd.setPixel(41+X, 23-Y); + lcd.setPixel(40+X, 23-Y); + lcd.setPixel(39+X, 23-Y); + lcd.setPixel(42+X, 22-Y); + lcd.setPixel(41+X, 22-Y); + lcd.setPixel(40+X, 22-Y); + lcd.refresh(); + + /**Displayed pixes will be cleared after 0.2 second.*/ + wait(0.2); + + lcd.clearPixel(42+X, 26-Y); + lcd.clearPixel(41+X, 26-Y); + lcd.clearPixel(40+X, 26-Y); + lcd.clearPixel(43+X, 25-Y); + lcd.clearPixel(42+X, 25-Y); + lcd.clearPixel(41+X, 25-Y); + lcd.clearPixel(40+X, 25-Y); + lcd.clearPixel(39+X, 25-Y); + lcd.clearPixel(43+X, 24-Y); + lcd.clearPixel(42+X, 24-Y); + lcd.clearPixel(41+X, 24-Y); + lcd.clearPixel(40+X, 24-Y); + lcd.clearPixel(39+X, 24-Y); + lcd.clearPixel(43+X, 23-Y); + lcd.clearPixel(42+X, 23-Y); + lcd.clearPixel(41+X, 23-Y); + lcd.clearPixel(40+X, 23-Y); + lcd.clearPixel(39+X, 23-Y); + lcd.clearPixel(42+X, 22-Y); + lcd.clearPixel(41+X, 22-Y); + lcd.clearPixel(40+X, 22-Y); + lcd.refresh(); + } + + /**All LEDs will be turned on if acceleration values are within -0.05 and 0.05.*/ + if (abs(Ax)<=0.05&&abs(Ay)<=0.05) { + ledA=1; + ledB=1; + ledC=1; + ledD=1; + } + + /**All LEDs will be turned off if acceleration values go beyond this range.*/ + else { + ledA=0; + ledB=0; + ledC=0; + ledD=0; + } + } +} + +/** +@brief Display the function name of Angle Meter for 1 second before calling it. +*/ +void fun1() +{ + /**Initialise the LCD and set brightness to 0.8.*/ + lcd.init(); + lcd.normalMode(); + lcd.setBrightness(0.8); + lcd.clear(); + + /**Display the function name of Angle Meter.*/ + lcd.printString("Electronic",12,2); + lcd.printString("Angle Meter",10,3); + + /**Turn LED A and LED C on.*/ + ledA=1; + ledB=0; + ledC=1; + ledD=0; + + /**Call function of Angle Meter after 1 second delay.*/ + flipper.attach(&AngleMeter, 1.0); +} + +/** +@brief Display the function name of Gradienter for 1 second before calling it. +*/ +void fun2() +{ + /**Turn off the buzzer.*/ + buzzer = 0; + + /**Initialise the LCD and set brightness to 0.8.*/ + lcd.init(); + lcd.normalMode(); + lcd.setBrightness(0.8); + lcd.clear(); + + /**Display the function name of Gradienter.*/ + lcd.printString("Electronic",12,2); + lcd.printString("Gradienter",12,3); + + /**Turn LED B and LED D on.*/ + ledA=0; + ledB=1; + ledC=0; + ledD=1; + + /**Call function of Gradienter after 1 second delay.*/ + flipper.attach(&Gradienter, 1.0); +} + +/** +@brief Power down the Ethernet interface to save power. +@brief Acknowledgements to Michael Wei's code. +*/ +void PHY_PowerDown() +{ + if (!Peripheral_GetStatus(LPC1768_PCONP_PCENET)) + EMAC_Init(); //init EMAC if it is not already init'd + + unsigned int regv; + regv = read_PHY(PHY_REG_BMCR); + write_PHY(PHY_REG_BMCR, regv | (1 << PHY_REG_BMCR_POWERDOWN)); + regv = read_PHY(PHY_REG_BMCR); + + //shouldn't need the EMAC now. + Peripheral_PowerDown(LPC1768_PCONP_PCENET); + + //and turn off the PHY OSC + LPC_GPIO1->FIODIR |= 0x8000000; + LPC_GPIO1->FIOCLR = 0x8000000; +} + +static void write_PHY (unsigned int PhyReg, unsigned short Value) { + /* Write a data 'Value' to PHY register 'PhyReg'. */ + unsigned int tout; + /* Hardware MII Management for LPC176x devices. */ + LPC_EMAC->MADR = DP83848C_DEF_ADR | PhyReg; + LPC_EMAC->MWTD = Value; + + /* Wait utill operation completed */ + for (tout = 0; tout < MII_WR_TOUT; tout++) { + if ((LPC_EMAC->MIND & MIND_BUSY) == 0) { + break; + } + } +} + +static unsigned short read_PHY (unsigned int PhyReg) { + /* Read a PHY register 'PhyReg'. */ + unsigned int tout, val; + + LPC_EMAC->MADR = DP83848C_DEF_ADR | PhyReg; + LPC_EMAC->MCMD = MCMD_READ; + + /* Wait until operation completed */ + for (tout = 0; tout < MII_RD_TOUT; tout++) { + if ((LPC_EMAC->MIND & MIND_BUSY) == 0) { + break; + } + } + LPC_EMAC->MCMD = 0; + val = LPC_EMAC->MRDD; + + return (val); +} + +void EMAC_Init() +{ + unsigned int tout,regv; + /* Power Up the EMAC controller. */ + Peripheral_PowerUp(LPC1768_PCONP_PCENET); + + LPC_PINCON->PINSEL2 = 0x50150105; + LPC_PINCON->PINSEL3 &= ~0x0000000F; + LPC_PINCON->PINSEL3 |= 0x00000005; + + /* Reset all EMAC internal modules. */ + LPC_EMAC->MAC1 = MAC1_RES_TX | MAC1_RES_MCS_TX | MAC1_RES_RX | MAC1_RES_MCS_RX | + MAC1_SIM_RES | MAC1_SOFT_RES; + LPC_EMAC->Command = CR_REG_RES | CR_TX_RES | CR_RX_RES; + + /* A short delay after reset. */ + for (tout = 100; tout; tout--); + + /* Initialize MAC control registers. */ + LPC_EMAC->MAC1 = MAC1_PASS_ALL; + LPC_EMAC->MAC2 = MAC2_CRC_EN | MAC2_PAD_EN; + LPC_EMAC->MAXF = ETH_MAX_FLEN; + LPC_EMAC->CLRT = CLRT_DEF; + LPC_EMAC->IPGR = IPGR_DEF; + + /* Enable Reduced MII interface. */ + LPC_EMAC->Command = CR_RMII | CR_PASS_RUNT_FRM; + + /* Reset Reduced MII Logic. */ + LPC_EMAC->SUPP = SUPP_RES_RMII; + for (tout = 100; tout; tout--); + LPC_EMAC->SUPP = 0; + + /* Put the DP83848C in reset mode */ + write_PHY (PHY_REG_BMCR, 0x8000); + + /* Wait for hardware reset to end. */ + for (tout = 0; tout < 0x100000; tout++) { + regv = read_PHY (PHY_REG_BMCR); + if (!(regv & 0x8000)) { + /* Reset complete */ + break; + } + } +} + +/** +@brief Functions used to display characters and shapes. +@brief Acknowledgements to Dr.Craig A. Evans's code. +*/ +N5110::N5110(PinName pwrPin, PinName scePin, PinName rstPin, PinName dcPin, PinName mosiPin, PinName sclkPin, PinName ledPin) +{ + + spi = new SPI(mosiPin,NC,sclkPin); // create new SPI instance and initialise + initSPI(); + + // set up pins as required + led = new PwmOut(ledPin); + pwr = new DigitalOut(pwrPin); + sce = new DigitalOut(scePin); + rst = new DigitalOut(rstPin); + dc = new DigitalOut(dcPin); + +} + +// initialise function - powers up and sends the initialisation commands +void N5110::init() +{ + turnOn(); // power up + wait_ms(10); // small delay seems to prevent spurious pixels during mbed reset + reset(); // reset LCD - must be done within 100 ms + + // function set - extended + sendCommand(0x20 | CMD_FS_ACTIVE_MODE | CMD_FS_HORIZONTAL_MODE | CMD_FS_EXTENDED_MODE); + // Don't completely understand these parameters - they seem to work as they are + // Consult the datasheet if you need to change them + sendCommand(CMD_VOP_7V38); // operating voltage - these values are from Chris Yan's Library + sendCommand(CMD_TC_TEMP_2); // temperature control + sendCommand(CMD_BI_MUX_48); // bias + + // function set - basic + sendCommand(0x20 | CMD_FS_ACTIVE_MODE | CMD_FS_HORIZONTAL_MODE | CMD_FS_BASIC_MODE); + normalMode(); // normal video mode by default + sendCommand(CMD_DC_NORMAL_MODE); // black on white + + // RAM is undefined at power-up so clear + clearRAM(); + +} + +// sets normal video mode (black on white) +void N5110::normalMode() +{ + sendCommand(CMD_DC_NORMAL_MODE); + +} + +// sets normal video mode (white on black) +void N5110::inverseMode() +{ + sendCommand(CMD_DC_INVERT_VIDEO); +} + +// function to power up the LCD and backlight +void N5110::turnOn() +{ + // set brightness of LED - 0.0 to 1.0 - default is 50% + setBrightness(0.5); + pwr->write(1); // apply power +} + +// function to power down LCD +void N5110::turnOff() +{ + setBrightness(0.0); // turn backlight off + clearRAM(); // clear RAM to ensure specified current consumption + // send command to ensure we are in basic mode + sendCommand(0x20 | CMD_FS_ACTIVE_MODE | CMD_FS_HORIZONTAL_MODE | CMD_FS_BASIC_MODE); + // clear the display + sendCommand(CMD_DC_CLEAR_DISPLAY); + // enter the extended mode and power down + sendCommand(0x20 | CMD_FS_POWER_DOWN_MODE | CMD_FS_HORIZONTAL_MODE | CMD_FS_EXTENDED_MODE); + // small delay and then turn off the power pin + wait_ms(10); + pwr->write(0); + +} + +// function to change LED backlight brightness +void N5110::setBrightness(float brightness) +{ + // check whether brightness is within range + if (brightness < 0.0) + brightness = 0.0; + if (brightness > 1.0) + brightness = 1.0; + // set PWM duty cycle + led->write(brightness); +} + +// pulse the active low reset line +void N5110::reset() +{ + rst->write(0); // reset the LCD + rst->write(1); +} + +// function to initialise SPI peripheral +void N5110::initSPI() +{ + 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 + spi->frequency(4000000); // maximum of screen is 4 MHz +} + +// send a command to the display +void N5110::sendCommand(unsigned char command) +{ + dc->write(0); // set DC low for command + sce->write(0); // set CE low to begin frame + spi->write(command); // send command + dc->write(1); // turn back to data by default + sce->write(1); // set CE high to end frame (expected for transmission of single byte) + +} + +// this function writes 0 to the 504 bytes to clear the RAM +void N5110::clearRAM() +{ + int i; + sce->write(0); //set CE low to begin frame + for(i = 0; i < WIDTH * HEIGHT; i++) { // 48 x 84 bits = 504 bytes + spi->write(0x00); // send 0's + } + sce->write(1); // set CE high to end frame + +} + +// function to set the XY address in RAM for subsequenct data write +void N5110::setXYAddress(int x, int y) +{ + if (x>=0 && x<WIDTH && y>=0 && y<HEIGHT) { // check within range + sendCommand(0x80 | x); // send addresses to display with relevant mask + sendCommand(0x40 | y); + } +} + +// These functions are used to set, clear and get the value of pixels in the display +// Pixels are addressed in the range of 0 to 47 (y) and 0 to 83 (x). The refresh() +// function must be called after set and clear in order to update the display +void N5110::setPixel(int x, int y) +{ + if (x>=0 && x<WIDTH && y>=0 && y<HEIGHT) { // check within range + // calculate bank and shift 1 to required position in the data byte + buffer[x][y/8] |= (1 << y%8); + } +} + +void N5110::clearPixel(int x, int y) +{ + if (x>=0 && x<WIDTH && y>=0 && y<HEIGHT) { // check within range + // calculate bank and shift 1 to required position (using bit clear) + buffer[x][y/8] &= ~(1 << y%8); + } +} + +// function to refresh the display +void N5110::refresh() +{ + int i,j; + + setXYAddress(0,0); // important to set address back to 0,0 before refreshing display + // address auto increments after printing string, so buffer[0][0] will not coincide + // with top-left pixel after priting string + + sce->write(0); //set CE low to begin frame + + for(j = 0; j < BANKS; j++) { // be careful to use correct order (j,i) for horizontal addressing + for(i = 0; i < WIDTH; i++) { + spi->write(buffer[i][j]); // send buffer + } + } + sce->write(1); // set CE high to end frame + +} + +// function to print string at specified position +void N5110::printString(const char * str,int x,int y) +{ + if (y>=0 && y<BANKS) { // check if printing in range of y banks + + int n = 0 ; // counter for number of characters in string + // loop through string and print character + while(*str) { + + // writes the character bitmap data to the buffer, so that + // text and pixels can be displayed at the same time + for (int i = 0; i < 5 ; i++ ) { + int pixel_x = x+i+n*6; + if (pixel_x > WIDTH-1) // ensure pixel isn't outside the buffer size (0 - 83) + break; + buffer[pixel_x][y] = font5x7[(*str - 32)*5 + i]; + } + + str++; // go to next character in string + + n++; // increment index + + } + + refresh(); // this sends the buffer to the display and sets address (cursor) back to 0,0 + } +} + +// function to clear the screen +void N5110::clear() +{ + clearBuffer(); // clear the buffer then call the refresh function + refresh(); +} + +// function to clear the buffer +void N5110::clearBuffer() +{ + int i,j; + for (i=0; i<WIDTH; i++) { // loop through the banks and set the buffer to 0 + for (j=0; j<BANKS; j++) { + buffer[i][j]=0; + } + } +} + +// function to draw circle +void N5110:: drawCircle(int x0,int y0,int radius,int fill) +{ + // from http://en.wikipedia.org/wiki/Midpoint_circle_algorithm + int x = radius; + int y = 0; + int radiusError = 1-x; + + while(x >= y) { + + // if transparent, just draw outline + if (fill == 0) { + setPixel( x + x0, y + y0); + setPixel(-x + x0, y + y0); + setPixel( y + x0, x + y0); + setPixel(-y + x0, x + y0); + setPixel(-y + x0, -x + y0); + setPixel( y + x0, -x + y0); + setPixel( x + x0, -y + y0); + setPixel(-x + x0, -y + y0); + } else { // drawing filled circle, so draw lines between points at same y value + + int type = (fill==1) ? 1:0; // black or white fill + + drawLine(x+x0,y+y0,-x+x0,y+y0,type); + drawLine(y+x0,x+y0,-y+x0,x+y0,type); + drawLine(y+x0,-x+y0,-y+x0,-x+y0,type); + drawLine(x+x0,-y+y0,-x+x0,-y+y0,type); + } + + + y++; + if (radiusError<0) { + radiusError += 2 * y + 1; + } else { + x--; + radiusError += 2 * (y - x) + 1; + } + } + +} + +void N5110::drawLine(int x0,int y0,int x1,int y1,int type) +{ + int y_range = y1-y0; // calc range of y and x + int x_range = x1-x0; + int start,stop,step; + + // if dotted line, set step to 2, else step is 1 + step = (type==2) ? 2:1; + + // make sure we loop over the largest range to get the most pixels on the display + // for instance, if drawing a vertical line (x_range = 0), we need to loop down the y pixels + // or else we'll only end up with 1 pixel in the x column + if ( abs(x_range) > abs(y_range) ) { + + // ensure we loop from smallest to largest or else for-loop won't run as expected + start = x1>x0 ? x0:x1; + stop = x1>x0 ? x1:x0; + + // loop between x pixels + for (int x = start; x<= stop ; x+=step) { + // do linear interpolation + int y = y0 + (y1-y0)*(x-x0)/(x1-x0); + + if (type == 0) // if 'white' line, turn off pixel + clearPixel(x,y); + else + setPixel(x,y); // else if 'black' or 'dotted' turn on pixel + } + } else { + + // ensure we loop from smallest to largest or else for-loop won't run as expected + start = y1>y0 ? y0:y1; + stop = y1>y0 ? y1:y0; + + for (int y = start; y<= stop ; y+=step) { + // do linear interpolation + int x = x0 + (x1-x0)*(y-y0)/(y1-y0); + + if (type == 0) // if 'white' line, turn off pixel + clearPixel(x,y); + else + setPixel(x,y); // else if 'black' or 'dotted' turn on pixel + + } + } + +} + +MMA8452:: MMA8452(PinName sdaPin, PinName sclPin) +{ + i2c = new I2C(sdaPin,sclPin); // create new I2C instance and initialise + i2c->frequency(400000); // I2C Fast Mode - 400kHz + leds = new BusOut(LED4,LED3,LED2,LED1); // for debug +} + +void MMA8452::init() +{ + + i2c->frequency(400000); // set Fast Mode I2C frequency (5.10 datasheet) + + char data = readByteFromRegister(WHO_AM_I); // p18 datasheet + if (data != 0x2A) { // if correct ID not found, hand and flash error message + error(); + } + + // put into STANDBY while configuring + data = readByteFromRegister(CTRL_REG1); // get current value of register + data &= ~(1<<0); // clear bit 0 (p37 datasheet) + sendByteToRegister(data,CTRL_REG1); + + // Set output data rate, default is 800 Hz, will set to 100 Hz (clear b5, set b4/b3 - p37 datasheet) + data = readByteFromRegister(CTRL_REG1); + data &= ~(1<<5); + data |= (1<<4); + data |= (1<<3); + sendByteToRegister(data,CTRL_REG1); + + //// Can also change default 2g range to 4g or 8g (p22 datasheet) + data = readByteFromRegister(XYZ_DATA_CFG); + data |= (1<<0); // set bit 0 - 4g range + sendByteToRegister(data,XYZ_DATA_CFG); + + // set ACTIVE + data = readByteFromRegister(CTRL_REG1); + data |= (1<<0); // set bit 0 in CTRL_REG1 + sendByteToRegister(data,CTRL_REG1); + +} + +// read acceleration data from device +Acceleration MMA8452::readValues() +{ + // acceleration data stored in 6 registers (0x01 to 0x06) + // device automatically increments register, so can read 6 bytes starting from OUT_X_MSB + char data[6]; + readBytesFromRegister(OUT_X_MSB,6,data); + + char x_MSB = data[0]; // extract MSB and LSBs for x,y,z values + char x_LSB = data[1]; + char y_MSB = data[2]; + char y_LSB = data[3]; + char z_MSB = data[4]; + char z_LSB = data[5]; + + // [0:7] of MSB are 8 MSB of 12-bit value , [7:4] of LSB are 4 LSB's of 12-bit value + // need to type-cast as numbers are in signed (2's complement) form (p20 datasheet) + int x = (int16_t) (x_MSB << 8) | x_LSB; // combine bytes + x >>= 4; // are left-aligned, so shift 4 places right to right-align + int y = (int16_t) (y_MSB << 8) | y_LSB; + y >>= 4; + int z = (int16_t) (z_MSB << 8) | z_LSB; + z >>= 4; + + // sensitivity is 1024 counts/g in 2g mode (pg 9 datasheet) + // " " 512 " 4g " + // " " 256 " 8g " + Acceleration acc; + + acc.x = x/512.0; + acc.y = y/512.0; + acc.z = z/512.0; + + return acc; +} + +// reads a byte from a specific register +char MMA8452::readByteFromRegister(char reg) +{ + int nack = i2c->write(MMA8452_W_ADDRESS,®,1,true); // send the register address to the slave + // true as need to send repeated start condition (5.10.1 datasheet) + // http://www.i2c-bus.org/repeated-start-condition/ + if (nack) + error(); // if we don't receive acknowledgement, flash error message + + char rx; + nack = i2c->read(MMA8452_R_ADDRESS,&rx,1); // read a byte from the register and store in buffer + if (nack) + error(); // if we don't receive acknowledgement, flash error message + + return rx; +} + +// reads a series of bytes, starting from a specific register +void MMA8452::readBytesFromRegister(char reg,int numberOfBytes,char bytes[]) +{ + + int nack = i2c->write(MMA8452_W_ADDRESS,®,1,true); // send the slave write address and the configuration register address + // true as need to send repeated start condition (5.10.1 datasheet) + // http://www.i2c-bus.org/repeated-start-condition/ + + if (nack) + error(); // if we don't receive acknowledgement, flash error message + + nack = i2c->read(MMA8452_R_ADDRESS,bytes,numberOfBytes); // read bytes + if (nack) + error(); // if we don't receive acknowledgement, flash error message + +} + +// sends a byte to a specific register +void MMA8452::sendByteToRegister(char byte,char reg) +{ + char data[2]; + data[0] = reg; + data[1] = byte; + // send the register address, followed by the data + int nack = i2c->write(MMA8452_W_ADDRESS,data,2); + if (nack) + error(); // if we don't receive acknowledgement, flash error message + +} + +void MMA8452::error() +{ + while(1) { + leds->write(15); + wait(0.1); + leds->write(0); + wait(0.1); + } +} + + + +