Sep 2014
This project utilzed the Adafruit Ultimate GPS Logger Shield to read the GPS location and then send them over a Seeedstudio CAN bus shield. The code below solves the problem of creating an accurate CAN bus message that contains both the latitude and longitude values.
See my section on Arduino SeeedStudio CAN-BUS shield for details on how I programmed the microcontroller to send the CAN messages.
See my section on the Adafruit Ultimate GPS Shield on how to convert the gps coordinates that are output by the GPS shield into a form that is useful.
If no GPS fix is available, then a CAN bus message is sent that contains the fix value (zero), the fix quality, and the number of satellites. If the GPS fix is available, then the sketch alternates between sending a CAN bus message with either the latitude and longitude, or a message with the GPS speed, angle, altitude, and the number of satellites.
The posting interval is every 59 seconds. This corresponds to how long it takes for the boat to travel 500' at 8 knots.
The CAN data is read by another Arduino that transmits the data via Wi-Fi to a custom web page where the data is collected and displayed. I plan to implement a map that shows the position and prior path of the boat over the past week. &nbap;
/* Send GPS data out over CAN bus Adafruit Ultimate GPS Logger Shield Seeduino CAN-BUS Shield Resources: DIO4 Red LED DIO5 Green LED DIO7 SoftwareSerial GPS DIO8 SoftwareSerial GPS DO10 SPI (SS) CAN DO11 SPI (MOSI) CAN DO12 SPI (MISO) CAN Note that tests indicate you may be able to use DIO10. DIO 2 to 6 and 9 may be used without any effect on the GPS. LEDs Red blinking, Green off CAN init failure Red on, Green on CAN ok; GPS has no fix. Red off, Green on CAN ok, GPS fix ok. Red off, Green blinking CAN ok, GPS ok, sending CAN msg Interval calculation: One reading every 500' at 8 knots v = s/t; t = s/v = 500' / 8 kn * (1 kn/1.15 mph) * (1 mi/5208') * (3600s / hr) = 59.3 sec */ // Test code for Adafruit GPS modules using MTK3329/MTK3339 driver // // This code shows how to listen to the GPS module in an interrupt // which allows the program to have more 'freedom' - just parse // when a new NMEA sentence is available! Then access data when // desired. // // Tested and works great with the Adafruit Ultimate GPS module // using MTK33x9 chipset // ------> http://www.adafruit.com/products/746 // Pick one up today at the Adafruit electronics shop // and help support open source hardware & software! -ada //This code is intended for use with Arduino Leonardo and other ATmega32U4-based Arduinos #include "Adafruit_GPS.h" #include "SoftwareSerial.h" // Connect the GPS Power pin to 5V // Connect the GPS Ground pin to ground // If using software serial (sketch example default): // Connect the GPS TX (transmit) pin to Digital 8 // Connect the GPS RX (receive) pin to Digital 7 // If using hardware serial: // Connect the GPS TX (transmit) pin to Arduino RX1 (Digital 0) // Connect the GPS RX (receive) pin to matching TX1 (Digital 1) // If using software serial, keep these lines enabled // (you can change the pin numbers to match your wiring): SoftwareSerial mySerial(8, 7); Adafruit_GPS GPS(&mySerial); // If using hardware serial, comment // out the above two lines and enable these two lines instead: //Adafruit_GPS GPS(&Serial1); //HardwareSerial mySerial = Serial1; // Set GPSECHO to 'false' to turn off echoing the GPS data to the Serial console // Set to 'true' if you want to debug and listen to the raw GPS sentences #define GPSECHO true ///////////////////////////////////////////////////////////////////////// #include "mcp_can.h" #include "SPI.h" unsigned long CANmsgId; unsigned char CANmsg[8]; ///////////////////////////////////////////////////////////////////////// // set 'true' to see all details, false for the parsed GPS data only #define DEBUG false boolean lastCanMsgWasLatLong = false; byte pinRedLED = 5; byte pinGreenLED = 4; void setup() { // connect at 115200 so we can read the GPS fast enough and echo without dropping chars // also spit it out Serial.begin(115200); delay(5000); pinMode(pinRedLED, OUTPUT); delay(1); pinMode(pinGreenLED, OUTPUT); delay(1); Serial.println("Seeduino CAN-BUS Shield"); // CAN_5KBPS, CAN_10KBPS, CAN_20KBPS, CAN_40KBPS, CAN_50KBPS, CAN_80KBPS, CAN_100KBPS, CAN_125KBPS, CAN_200KBPS, CAN_250KBPS and CAN_500KBPS. if(CAN.begin(CAN_250KBPS) == CAN_OK) { Serial.println ("CAN bus init ok"); } else { Serial.println("CAN bus init fail!!"); while (1) { blinkLED(pinRedLED); } } Serial.println(" "); Serial.println("Adafruit ultimate GPS shield!"); // 9600 NMEA is the default baud rate for Adafruit MTK GPS's- some use 4800 GPS.begin(9600); // uncomment this line to turn on RMC (recommended minimum) and GGA (fix data) including altitude GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA); // uncomment this line to turn on only the "minimum recommended" data //GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCONLY); // For parsing data, we don't suggest using anything but either RMC only or RMC+GGA since // the parser doesn't care about other sentences at this time // Set the update rate GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ); // 1 Hz update rate // For the parsing code to work nicely and have time to sort thru the data, and // print it out we don't suggest using anything higher than 1 Hz // Request updates on antenna status, comment out to keep quiet GPS.sendCommand(PGCMD_ANTENNA); delay(1000); // Ask for firmware version mySerial.println(PMTK_Q_RELEASE); } uint32_t timer = millis(); void loop() { char c = GPS.read(); // if you want to debug, this is a good time to do it! if ((c) && (GPSECHO)) #if DEBUG Serial.write(c); #endif // if a sentence is received, we can check the checksum, parse it... if (GPS.newNMEAreceived()) { // a tricky thing here is if we print the NMEA sentence, or data // we end up not listening and catching other sentences! // so be very wary if using OUTPUT_ALLDATA and trytng to print out data //Serial.println(GPS.lastNMEA()); // this also sets the newNMEAreceived() flag to false if (!GPS.parse(GPS.lastNMEA())) // this also sets the newNMEAreceived() flag to false return; // we can fail to parse a sentence in which case we should just wait for another } // if millis() or timer wraps around, we'll just reset it if (timer > millis()) timer = millis(); // approximately every 59 seconds or so, send out the GPS data over CAN bus if (millis() - timer > 59000) { timer = millis(); // reset the timer Serial.print("\nTime: "); Serial.print(GPS.hour, DEC); Serial.print(':'); Serial.print(GPS.minute, DEC); Serial.print(':'); Serial.print(GPS.seconds, DEC); Serial.print('.'); Serial.println(GPS.milliseconds); //Time: 13:6:37.0 Serial.print("Date: "); Serial.print(GPS.month, DEC); Serial.print('/'); Serial.print(GPS.day, DEC); Serial.print("/20"); Serial.println(GPS.year, DEC); //Date: 3/8/2014 Serial.print("Fix: "); Serial.print((int)GPS.fix); Serial.print(" quality: "); Serial.println((int)GPS.fixquality); //Fix: 1 quality: 2 if (GPS.fix) { // GPS.fix = 1 when there is a fix (location verification). digitalWrite(pinRedLED, LOW); digitalWrite(pinGreenLED, HIGH); if (! lastCanMsgWasLatLong) { // send lat & long msg //Serial.print("Location: "); //Serial.print(GPS.latitude, 4); Serial.print(GPS.lat); //Serial.print(", "); //Serial.print(GPS.longitude, 4); Serial.println(GPS.lon); //Location: 4026.4370N, 7607.3613W // 4026.4370 = Latitude 40 deg, 26.4370 minutes // 4026.4370 = 40 deg 26 min 26 sec // the .lat and .lon are the N and W characters float latDecDeg = gpsGetDecimalDegFromUltGPS_LatLong(GPS.latitude, GPS.lat); Serial.print("Lat in decimal degrees: "); printFloat(latDecDeg, 4); Serial.println(" "); // 40.4478 float longDecDeg = gpsGetDecimalDegFromUltGPS_LatLong(GPS.longitude, GPS.lon); Serial.print("Long in decimal degrees: "); printFloat(longDecDeg, 4); // -76.1287 Serial.println(" "); Serial.println("Sending CAN msg with GPS lat & long.."); updateCanMsgFromGPS_LatLong(latDecDeg, longDecDeg); CANmsgId = 0xF80060; CAN.sendMsgBuf(CANmsgId, 1, 8, CANmsg); blinkLED(pinGreenLED); digitalWrite(pinGreenLED, HIGH); /* /////////////////////////////////////////////////////////////////////////////////////// // Convert CAN msg back to lat and long coordinates in decimal degrees Serial.println("Convert CAN msg back to lat and long coordinates in decimal degrees:"); Serial.print("CAN msg = "); for (int i=0; i<7; i++) { Serial.print(CANmsg[i]); Serial.print(", "); } Serial.println(CANmsg[7]); Serial.print("Latitude from the CAN msg: "); float fLat = GPS_LatFromCANmsg(); printFloat(fLat, 4); Serial.println(" "); Serial.print("Longitude from the CAN msg: "); float fLong = GPS_LongFromCANmsg(); printFloat(fLong, 4); Serial.println(" "); /////////////////////////////////////////////////////////////////////////////////////// */ lastCanMsgWasLatLong = true; } else { // send CAN msg with speed, angle, altitude, satellites Serial.print("Speed (knots): "); Serial.println(GPS.speed); //Speed (knots): 0.31 Serial.print("Angle(deg): "); Serial.println(GPS.angle); //Angle: 59.69 Serial.print("Altitude(m): "); Serial.println(GPS.altitude); //Altitude: 109.70 Serial.print("Satellites: "); Serial.println((int)GPS.satellites); //Satellites: 8 // send out the GPS speed (knots), altitude, satellites, fix, quality // (only gets sent if GPS fix issue) Serial.println("Sending CAN msg with GPS speed, angle, altitude, satellites"); CANmsgId = 0xF80160; // clear out CANmsg[] for (int i=0; i<8; i++) { CANmsg[i] = 0; } int msgOffset = 0; float msgFactor = 0.01; // updateCanMsgFromFloat(float floatVal, int startBit, int Length, int offset, float factor) // updateCanMsgFromFloat(GPS.speed, 0, 16, msgOffset, msgFactor); updateCanMsgFromFloat(GPS.angle, 16, 16, msgOffset, msgFactor); updateCanMsgFromFloat(GPS.altitude, 32, 16, msgOffset, msgFactor); updateCanMsgFromFloat((float)GPS.satellites, 48, 16, msgOffset, msgFactor); CAN.sendMsgBuf(CANmsgId, 1, 8, CANmsg); blinkLED(pinGreenLED); digitalWrite(pinGreenLED, HIGH); lastCanMsgWasLatLong = false; } // (! lastCanMsgWasLatLong) } else { // GPS.fix = 0, therefore NO fix (location verification). digitalWrite(pinRedLED, HIGH); digitalWrite(pinGreenLED, HIGH); // // send out the GPS speed (knots), altitude, satellites, fix, quality // (only gets sent if GPS fix issue) Serial.println(" "); Serial.println("NO fix. "); Serial.println("Sending GPS fix, fix quality, # satellites over CAN bus.."); Serial.println(" "); CANmsgId = 0xF80260; // clear out CANmsg[] for (int i=0; i<8; i++) { CANmsg[i] = 0; } int msgOffset = 0; float msgFactor = 0.01; // updateCanMsgFromFloat(float floatVal, int startBit, int Length, int offset, float factor) // updateCanMsgFromFloat((float)GPS.fix, 0, 16, msgOffset, msgFactor); updateCanMsgFromFloat((float)GPS.fixquality, 16, 16, msgOffset, msgFactor); updateCanMsgFromFloat(0.0, 32, 16, msgOffset, msgFactor); updateCanMsgFromFloat((float)GPS.satellites, 48, 16, msgOffset, msgFactor); CAN.sendMsgBuf(CANmsgId, 1, 8, CANmsg); blinkLED(pinGreenLED); digitalWrite(pinRedLED, HIGH); digitalWrite(pinGreenLED, HIGH); } Serial.println(" "); } } /////////////////////////////////////////////////////////////////////////// // gps functions float gpsGetDecimalDegFromUltGPS_LatLong(float in_coords, char NSEW) { // Convert the latitude or longitude float value from the // Ultimate GPS (GPS.latitude or GPS.longitude) to GPS // decimal degrees format. // For the location: 4026.4370N, 7607.3613W // in_coords holds the lat or long (4026.437 or 7607.3613). // NSEW hold the lat or long direction North, South, East, West (NSEW) // N & E are positive, S & W are negative // Lat values vary from 90° N to 90° S. // Long values vary from 180° W to 180° E. // Get the first two digits by turning f into an integer, then doing an integer divide by 100; // firsttowdigits should be 77 at this point. int firsttwodigits = ((int)in_coords)/100; //This assumes that f < 10000. float nexttwodigits = in_coords - (float)(firsttwodigits*100); int left_part = intOfFloat(in_coords); int right_part = fractionOfFloat(in_coords, 4, left_part); float fRightPart = (float)right_part / 10000.0; float theFinalAnswer = (float)(firsttwodigits + (nexttwodigits + fRightPart)/60.0); if (NSEW == 'S' || NSEW == 'W') { // S & E are negative theFinalAnswer = theFinalAnswer * (-1.0); } return theFinalAnswer; } int intOfFloat(float f) { // intOfFloat(4026.4370) = 4026 int left_part; left_part = floor(f); return left_part; } int fractionOfFloat(float f, byte numDecPlaces, int left_part) { // fractionOfFloat(4026.4370, 4, 4026) = 4370 int right_part; right_part = f * pow(10, numDecPlaces) - left_part * pow(10, numDecPlaces); return right_part; } /////////////////////////////////////////////////////////////////////////// void printFloat(float value, int places) { // printFloat prints out the float 'value' rounded to 'places' places after the decimal point // Follow with println as needed. // this is used to cast digits int digit; float tens = 0.1; int tenscount = 0; int i; float tempfloat = value; // make sure we round properly. this could use pow from, but doesn't seem worth the import // if this rounding step isn't here, the value 54.321 prints as 54.3209 // calculate rounding term d: 0.5/pow(10,places) float d = 0.5; if (value < 0) d *= -1.0; // divide by ten for each decimal place for (i = 0; i < places; i++) d/= 10.0; // this small addition, combined with truncation will round our values properly tempfloat += d; // first get value tens to be the large power of ten less than value // tenscount isn't necessary but it would be useful if you wanted to know after this how many chars the number will take if (value < 0) tempfloat *= -1.0; while ((tens * 10.0) <= tempfloat) { tens *= 10.0; tenscount += 1; } // write out the negative if needed if (value < 0) Serial.print('-'); if (tenscount == 0) Serial.print(0, DEC); for (i=0; i< tenscount; i++) { digit = (int) (tempfloat/tens); Serial.print(digit, DEC); tempfloat = tempfloat - ((float)digit * tens); tens /= 10.0; } // if no places after decimal, stop now and return if (places <= 0) return; // otherwise, write the point and continue on Serial.print('.'); // now write out each decimal place by shifting digits one by one into the ones place and writing the truncated value for (i = 0; i < places; i++) { tempfloat *= 10.0; digit = (int) tempfloat; Serial.print(digit,DEC); // once written, subtract off that digit tempfloat = tempfloat - (float) digit; } } byte countDigits(int num){ byte count=0; while(num){ num=num/10; count++; } return count; } int getDigitRightToLeft(unsigned int number, int digit) { // gets the digit specified, counting from the left of the // decimal point and moving to the left. for (int i=0; i = 0) { fLat = fLeft + fRight; } else { fLat = fLeft - fRight; } return fLat; } float GPS_LongFromCANmsg(){ // float getFloatFromCanMsg(int startBit, int msgLen, int offset, float factor) float fLeft = getFloatFromCanMsg(32, 16, -180, 1.0); float fRight = getFloatFromCanMsg(48, 16, 0, 0.0001); float fLong; if (fLeft >= 0) { fLong = fLeft + fRight; } else { fLong = fLeft - fRight; } return fLong; } /////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////// float getFloatFromCanMsg(int startBit, int msgLen, int offset, float factor) { // Read the data from msg[8] within CANmsg[] // convert it with the passed parameters, and return a float value. // Assumes msgLen = 16 byte msb; byte lsb; switch (startBit) { case 0: msb = CANmsg[0]; lsb = CANmsg[1]; break; case 16: msb = CANmsg[2]; lsb = CANmsg[3]; break; case 32: msb = CANmsg[4]; lsb = CANmsg[5]; break; case 48: msb = CANmsg[6]; lsb = CANmsg[7]; break; } int myInt = (lsb << 8) | msb; #if DEBUG Serial.print("getFloatFromCanMsg myInt = "); Serial.println(myInt); #endif // float CANbusIntToFloat(unsigned int myInt, int offset, float factor) { float myFloat = CANbusIntToFloat(myInt, offset, factor); return myFloat; } void updateCanMsgFromFloat(float floatVal, int startBit, int msgLen, int offset, float factor) { // Update msg[8] within CANmsg[] with the passed parameters // Assumes msgLen = 16; // unsigned int floatToIntCANbus(float myFloat, int offset, float factor) { unsigned int myInt = floatToIntCANbus(floatVal, offset, factor); byte msb = getMsbFromInt(myInt); byte lsb = getLsbFromInt(myInt); switch (startBit) { case 0: CANmsg[0] = msb; CANmsg[1] = lsb; break; case 16: CANmsg[2] = msb; CANmsg[3] = lsb; break; case 32: CANmsg[4] = msb; CANmsg[5] = lsb; break; case 48: CANmsg[6] = msb; CANmsg[7] = lsb; break; } } unsigned int floatToIntCANbus(float myFloat, int offset, float factor) { // float myFloat = 2128.5; // unsigned int myInt = floatToIntCANbus(myFloat, 0, 0.125); // // Beginning with float of 2128.5, convert to CAN signal // values. // (int val) = ((float val) - offset) / factor; // (int val) = ((2128.5) - 0.0) / 0.125; // (int val) = 17028 // Common offset & factor values for msgLen = 16 (two bytes): // Temperature in C: offset=-273; factor=0.03125 // Percent (0 to 100%): offset=-125; factor=1 // speed (0 to 5000 rpm): offset=0; factor=0.125 // torque (Nm): offset=0; factor=1 // mass flow (kg/h): offset=0; factor=0.2 // pressure (kPa): offset=0; factor=4; // Boolean (0/1): offset=0; factor=1; myFloat = myFloat - (float)offset; myFloat = myFloat / factor; unsigned int myInt = (unsigned int) myFloat; return myInt; } float CANbusIntToFloat(unsigned int myInt, int offset, float factor) { // value in decimal = (CAN DEC value) * factor + offset // 17500 * 0.125 + 0 = 2187.5 rpm float myFloat = (float) myInt * factor + (float) offset; return myFloat; } byte getMsbFromInt(int myInt) { // int myInt = 17028; // byte msb = getMsbFromInt(myInt); byte msb = myInt & 0xff; return msb; } byte getLsbFromInt(int myInt) { // int myInt = 17028; // byte lsb = getLsbFromInt(myInt); byte lsb = (myInt >>8) & 0xff; return lsb; } /////////////////////////////////////////////////////////////////////////// void blinkLED(byte ledPIN){ // consumes 300 ms. for(int i = 5; i>0; i--){ digitalWrite(ledPIN, HIGH); delay(30); digitalWrite(ledPIN, LOW); delay(30); } }
Do you need help developing or customizing a IoT product for your needs? Send me an email requesting a free one hour phone / web share consultation.
The information presented on this website is for the author's use only. Use of this information by anyone other than the author is offered as guidelines and non-professional advice only. No liability is assumed by the author or this web site.