Thursday, December 4, 2014

Arduino GPS

UPDATE: Complete source code is now available at:
http://kamoly.space/projects/gps/


Background

My wife and I have been making an annual summer trip to Colorado to get out of the Texas heat. On some of the hikes we get a bit adventurous (and the trails are poorly marked), so I wanted to have a GPS receiver on hand just in case. There are maps, but they're horrible - my wife and I are convinced its Coloradans sick joke to get Texans lost in the mountains. They have so many visitors in Pagosa Springs from Texas, the gas station actually stocks Big Red! Sure there are a wide variety of GPS receivers on the market,  but why buy one of them when I could make my own with an Arduino! (Also I've used some of the other GPS receivers, and their user interfaces are awful.)

This is a project I completed earlier this year, so I don't have good step by step instructions. However, the source code may be very beneficial to you if you're working on your own GPS project.

Hardware for the Project

Arduino Mega 2560
Seeedstudio 2.8" TFT Touch Shield (v1.0, but they have newer versions now)
Adafruit Ultimate GPS Breakout
Wire
Prototype Board
Battery Holder
4 AA 1.2V Rechargeable NiMH Batteries
Fiberglass & Epoxy



Design

At a minimum, I wanted to see my current location and be able to log waypoint locations at major turns along the hike. The display should show the total distance back to home (accumulated from the current location through each previous location). Then based on my speed, I could show how much time it will take to get back home. The user interface should allow me to set waypoints, navigate between waypoints, and clear all waypoints.

I haven't done this yet, but long term I'd like to save and load collections of waypoints as routes. I could use the internal EEPROM or add a SD card interface

I'm using the Arduino's USB connection for two purposes: For development, it delivers power and is the communication link with the computer. For portable use, it delivers power from a battery pack.

Build Process

1. Plug the TFT Touch Shield directly into the Arduino.
2. Mount a prototype board over the remaining part of the Arduino. Mount the GPS Breakout to the prototype board.
3. Jump wires soldered from the GPS Breakout to appropriate pins on the Arduino.
4. Write code to display the GPS position and keep track of waypoints.
5. Cut an A/B USB cable in half and strip the wires. Connect red wire to + of battery holder and black wire to - of battery holder. White and green wires are data and are not connected.
6. The Arduino USB connection takes a 5V power input. Use 4x 1.2V NiMH batteries to get 4.8V nominal. It is VERY important to not use 1.5V alkaline batteries - otherwise the pack will deliver 6.0V which is too high for the Arduino.
7. Layer several sheets of fiberglass together and epoxy them to make a fairly thick plate. Cut the plate to shape each side of the case then use additional epoxy to hold it all together.

User Interface

The first block is just for the number of satellites detected and the current time.
The second block is for maintaining the routes. For now it doesn't support saving and loading routes, so the only option is New.
The third block displays the current location, speed, and heading.
The fourth block displays information to the currently selected waypoint.
The fifth block includes options to navigate between waypoints, create new waypoints, and delete existing waypoints.
The sixth block shows the accumulated distance to home and time to home. The distance home is the accumulation from the current position to the currently selected waypoint and through every preceding waypoint. Time home is the the distance home divided by the current speed.
The last block is a confirmation block which asks the user to confirm adding waypoints, deleting waypoints, and creating new routes. The confirmation is important so inadvertent contact with the GPS screen does not cause unwanted actions.

When the GPS starts, it shows the current location.


Pushing the Add button results in a confirmation selection as the bottom of the screen.


If the Add Waypoint is confirmed, a waypoint is added.


Additional waypoints can be added. Pushing Prev and Next cycles between the waypoints. Del deletes the currently selected waypoint.


New clears all waypoints (creates a new Route). The empty space to the right of New is for future expansion for saving and loading routes.

Other Notes

The distances are calculated and displayed using the WGS-84 Round Earth model. The functions below may be very useful for other purposes in which round Earth distances or headings are desired.

If the display is currently on waypoint 3 of 5 and add is selected, then the current location is added as waypoint 4 and the existing waypoints 4 and 5 are shifted to 5 and 6 respectively.

The touch screen takes a while to refresh. I was originally clearing and refreshing the entire screen with each update - it would take a long time (longer than a second). And during the redraw, the user interface would be unresponsive. The code below only clears out and redraws the values that change in normal operation. This allowed me to update the GPS values on the screen far more frequently while making the GPS still responsive to user input.

Lessons Learned / Future Changes

1. The Touch Screen is a bit hard to read in direct sunlight and I'm sure it's drawing a lot of power. Maybe use an e-ink display instead with a different input device?
2. The USB cable for portable power works, but it sticks out quite a bit and it's a little unwieldy getting everything in the backpack (without putting extra stress on the power connection). I may rewire how the battery pack is connected so it doesn't use the USB port.
3. Still need to add code to save / load routes to EEPROM or a SD card.

Source Code

// ClintK
// Adapted from "parsing" GPS example.

// Create / clear new route. Then confirm at bottom.
// Create waypoint. Then confirm at bottom.
// Select which waypoint to go to. Then confirm at bottom.
// Delete waypoint. Then confirm at bottom.
// Cancel button at bottom.

// GPS Headers
#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>

// EEPROM is for reading/writing the onboard Arduino memory.
//#include <EEPROM.h>

// TFT is for manipulating the TFT display.
#include <stdint.h>
#include <TouchScreen.h>
#include <TFT.h>

// GPS Setup
// Connect VIN to +5V
// Connect GND to Ground
// Connect GPS RX (data into GPS) to Digital 0 (or RX1 pin 19)
// Connect GPS TX (data out from GPS) to Digital 1 (or TX1 pin 18)

// Necessary???
SoftwareSerial mySerial(3, 2);

// Using Hardware Serial / Arduino Mega
Adafruit_GPS GPS(&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  false

// this keeps track of whether we're using the interrupt
// off by default!
boolean usingInterrupt = false;
void useInterrupt(boolean); // Func prototype keeps Arduino 0023 happy

// TFT Setup
#define YP A2   // must be an analog pin, use "An" notation!
#define XM A1   // must be an analog pin, use "An" notation!
#define YM 54   // can be a digital pin, this is A0
#define XP 57   // can be a digital pin, this is A3
#define TS_MINX 140
#define TS_MAXX 900
#define TS_MINY 120
#define TS_MAXY 940
// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int builtInLED = 13;

int selectedScreen = 0;
int selectedConfirmation = 0;

#define EQUATORIAL_RADIUS_IN_NAUTICAL_MILES 3443.918 // Radius of Earth in nm, WGS-84

#define MAX_NUMBER_OF_WAYPOINTS 100

double getRadiansFromDegrees(double value_degrees)
{
  return (value_degrees * 3.1415926535897932384626433832795 / 180.0);
}

double getDecimalDegreesFromDegreeDecimalMinutes(double value_degreeDecimalMinutes)
{
  double shiftedValue = value_degreeDecimalMinutes / 100;
  double wholeDegreeComponent = (int) shiftedValue;
  double fractionalDegreeComponent = (shiftedValue - wholeDegreeComponent) * 100 / 60.0;
  return (wholeDegreeComponent + fractionalDegreeComponent);
}

class WaypointModel
{
  public:
  double latitude_degreeDecimalMinutes;
  double longitude_degreeDecimalMinutes;
  double latitude_decimalDegrees;
  double longitude_decimalDegrees;

  boolean clear()
  {
    latitude_degreeDecimalMinutes = 0.0;
    longitude_degreeDecimalMinutes = 0.0;
    latitude_decimalDegrees = 0.0;
    longitude_decimalDegrees = 0.0;
    return true;
  }

  boolean setLocation(double newLatitude_degreeDecimalMinutes, double newLongitude_degreeDecimalMinutes)
  {
    latitude_degreeDecimalMinutes = newLatitude_degreeDecimalMinutes;
    longitude_degreeDecimalMinutes = newLongitude_degreeDecimalMinutes;
    latitude_decimalDegrees = getDecimalDegreesFromDegreeDecimalMinutes(latitude_degreeDecimalMinutes);
    longitude_decimalDegrees = getDecimalDegreesFromDegreeDecimalMinutes(longitude_degreeDecimalMinutes);
    return true;
  }
};

class RouteModel
{
  public:
  WaypointModel waypoints[MAX_NUMBER_OF_WAYPOINTS];
  int currentWaypoint;
  int totalWaypoints;

  boolean clearRoute()
  {
    for (int waypointIndex = 0; waypointIndex < MAX_NUMBER_OF_WAYPOINTS; waypointIndex++)
    {
      waypoints[waypointIndex].clear();
    }
    currentWaypoint = 0;
    totalWaypoints = 0;
    return true;
  }

  boolean addWaypoint(double newLatitude_degreeDecimalMinutes, double newLongitude_degreeDecimalMinutes)
  {
    if (totalWaypoints >= (MAX_NUMBER_OF_WAYPOINTS - 1))
    {
      return false;
    }
    for (int waypointIndex = totalWaypoints; waypointIndex > (currentWaypoint + 1) ; waypointIndex--)
    {
      waypoints[waypointIndex].setLocation(waypoints[waypointIndex-1].latitude_degreeDecimalMinutes,
                                           waypoints[waypointIndex-1].longitude_degreeDecimalMinutes);
    }
    totalWaypoints += 1;
    if (totalWaypoints == 1)
    {
      currentWaypoint = 0;
    }
    else
    {
      currentWaypoint += 1;
    }
    waypoints[currentWaypoint].setLocation(newLatitude_degreeDecimalMinutes, newLongitude_degreeDecimalMinutes);
    return true;
  }

  double getDistanceToWaypoint_nauticalMiles(int waypointIndex, double currentLatitude_degreeDecimalMinutes, double currentLongitude_degreeDecimalMinutes)
  {
    if (totalWaypoints <= 0)
    {
      return 0.0;
    }
 
    // WGS-84 Round Earth
    double currentLatitude_radians = getRadiansFromDegrees(getDecimalDegreesFromDegreeDecimalMinutes(currentLatitude_degreeDecimalMinutes));
    double currentLongitude_radians = getRadiansFromDegrees(getDecimalDegreesFromDegreeDecimalMinutes(currentLongitude_degreeDecimalMinutes));

    double currentWaypointLatitude_radians = getRadiansFromDegrees(waypoints[waypointIndex].latitude_decimalDegrees);
    double currentWaypointLongitude_radians = getRadiansFromDegrees(waypoints[waypointIndex].longitude_decimalDegrees);

    double distanceCalc_haversine = sqrt( sin((currentLatitude_radians - currentWaypointLatitude_radians) / 2) * sin((currentLatitude_radians - currentWaypointLatitude_radians) / 2) +
                                          cos(currentLatitude_radians) * cos(currentWaypointLatitude_radians) *
                                          sin((currentLongitude_radians - currentWaypointLongitude_radians) / 2) * sin((currentLongitude_radians - currentWaypointLongitude_radians) / 2));

    return (2 * asin(distanceCalc_haversine) * EQUATORIAL_RADIUS_IN_NAUTICAL_MILES);
  }

  double getDistanceToHome_nauticalMiles(double currentLatitude_degreeDecimalMinutes, double currentLongitude_degreeDecimalMinutes)
  {
    double totalDistance_nauticalMiles = 0.0;  
    if (totalWaypoints > 0)
    {
      // Loop through the current waypoint back to the first. Add the accumulated
      // distance between each waypoints to get a total travel time to return home.
      for (int waypointIndex = currentWaypoint; waypointIndex >= 0; waypointIndex--)
      {
        totalDistance_nauticalMiles += getDistanceToWaypoint_nauticalMiles(waypointIndex, currentLatitude_degreeDecimalMinutes, currentLongitude_degreeDecimalMinutes);
        currentLatitude_degreeDecimalMinutes = waypoints[waypointIndex].latitude_degreeDecimalMinutes;
        currentLongitude_degreeDecimalMinutes = waypoints[waypointIndex].longitude_degreeDecimalMinutes;
      }
    }
    return totalDistance_nauticalMiles;
  }

  double getHeadingToCurrentWaypoint_degrees(double currentLatitude_degreeDecimalMinutes, double currentLongitude_degreeDecimalMinutes)
  {
    if (totalWaypoints <= 0)
    {
      return -1.0;
    }

    // WGS-84 Round Earth
    double currentLatitude_radians = getRadiansFromDegrees(getDecimalDegreesFromDegreeDecimalMinutes(currentLatitude_degreeDecimalMinutes));
    double currentLongitude_radians = getRadiansFromDegrees(getDecimalDegreesFromDegreeDecimalMinutes(currentLongitude_degreeDecimalMinutes));

    double currentWaypointLatitude_radians = getRadiansFromDegrees(waypoints[currentWaypoint].latitude_decimalDegrees);
    double currentWaypointLongitude_radians = getRadiansFromDegrees(waypoints[currentWaypoint].longitude_decimalDegrees);

    double deltaLongitude_radians = (currentWaypointLongitude_radians - currentLongitude_radians);
    double y = sin(deltaLongitude_radians) * cos(currentWaypointLatitude_radians);
    double x = cos(currentLatitude_radians) * sin(currentWaypointLatitude_radians) - sin(currentLatitude_radians) * cos(currentWaypointLatitude_radians) * cos(deltaLongitude_radians);
    double heading_radians = atan2(y, x);
    if (heading_radians < 0.0)
    {
      heading_radians += (2 * PI);
    }
    return (heading_radians * 180.0 / PI);
  }

  double currentWaypointLatitude_degreeDecimalMinutes()
  {
    if (totalWaypoints <= 0)
    {
      return 0.0;
    }
    return waypoints[currentWaypoint].latitude_degreeDecimalMinutes;
  }

  double currentWaypointLongitude_degreeDecimalMinutes()
  {
    if (totalWaypoints <= 0)
    {
      return 0.0;
    }
    return waypoints[currentWaypoint].longitude_degreeDecimalMinutes;
  }

  boolean deleteWaypoint()
  {
    if (totalWaypoints == 0)
    {
      return false;
    }
    for (int waypointIndex = currentWaypoint; waypointIndex < (totalWaypoints - 1) ; waypointIndex++)
    {
      waypoints[waypointIndex].setLocation(waypoints[waypointIndex+1].latitude_degreeDecimalMinutes,
                                           waypoints[waypointIndex+1].longitude_degreeDecimalMinutes);
    }
    totalWaypoints -= 1;
    if (currentWaypoint > 0)
    {
      currentWaypoint -= 1;
    }
    return true;
  }

  boolean proceedToPreviousWaypoint()
  {
    if (totalWaypoints <= 0)
    {
      return false;
    }
    currentWaypoint -= 1;
    if (currentWaypoint < 0)
    {
      currentWaypoint = totalWaypoints - 1;
    }
    return true;
  }

  boolean proceedToNextWaypoint()
  {
    if (totalWaypoints <= 0)
    {
      return false;
    }
    currentWaypoint += 1;
    if (currentWaypoint >= totalWaypoints)
    {
      currentWaypoint = 0;
    }
    return true;
  }
};

RouteModel currentRoute;

double getRelativeBearing_degrees(double currentHeading_degrees, double destinationHeading_degrees)
{
  double relativeBearing_degrees = destinationHeading_degrees - currentHeading_degrees;
  if (relativeBearing_degrees < -180.0)
  {
    relativeBearing_degrees += 360.0;
  }
  else if (relativeBearing_degrees > 180.0)
  {
    relativeBearing_degrees -= 360.0;
  }
  return relativeBearing_degrees;
}

// For better pressure precision, we need to know the resistance
// between X+ and X- Use any multimeter to read it
// The 2.8" TFT Touch shield has 300 ohms across the X plate
TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300); //init TouchScreen port pins

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);
  Serial.println("Program start!");

  currentRoute.clearRoute();

  // TFT
  // Initialize the digital pin as an output.
  pinMode(builtInLED, OUTPUT);
  Tft.init();

  // 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);

  // the nice thing about this code is you can have a timer0 interrupt go off
  // every 1 millisecond, and read data from the GPS for you. that makes the
  // loop code a heck of a lot easier!
  useInterrupt(true);

  delay(1000);
  // Ask for firmware version
  mySerial.println(PMTK_Q_RELEASE);

  drawMainScreenLabels();
  drawMainScreenValues();
  drawMainScreenMenu();
}

// Interrupt is called once a millisecond, looks for any new GPS data, and stores it
SIGNAL(TIMER0_COMPA_vect)
{
  char c = GPS.read();
  // if you want to debug, this is a good time to do it!
#ifdef UDR0
  if (GPSECHO)
    if (c) UDR0 = c;
    // writing direct to UDR0 is much much faster than Serial.print
    // but only one character can be written at a time.
#endif
}

void useInterrupt(boolean v)
{
  if (v)
  {
    // Timer0 is already used for millis() - we'll just interrupt somewhere
    // in the middle and call the "Compare A" function above
    OCR0A = 0xAF;
    TIMSK0 |= _BV(OCIE0A);
    usingInterrupt = true;
  }
  else
  {
    // do not call the interrupt function COMPA anymore
    TIMSK0 &= ~_BV(OCIE0A);
    usingInterrupt = false;
  }
}

uint32_t timer = millis();
void loop()                     // run over and over again
{
  // in case you are not using the interrupt above, you'll
  // need to 'hand query' the GPS, not suggested :(
  if (! usingInterrupt)
  {
    // read data from the GPS in the 'main loop'
    char c = GPS.read();
    // if you want to debug, this is a good time to do it!
    if (GPSECHO)
      if (c) Serial.print(c);
  }

  // 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
  }

  Point touchPoint = ts.getPoint();
  touchPoint.x = map(touchPoint.x, TS_MINX, TS_MAXX, 240, 0);
  touchPoint.y = map(touchPoint.y, TS_MINY, TS_MAXY, 320, 0);

  bool userTriggeredEvent = false;

  if (touchPoint.z > ts.pressureThreshhold)
  {
    switch (selectedScreen)
    {
      case 0:
        // Main
        switch (selectedConfirmation)
        {
          case 0:
            if (touchPoint.y > 190 && touchPoint.y < 220)
            {
              if (touchPoint.x < 70)
              {
                // Previous
                userTriggeredEvent = true;
                currentRoute.proceedToPreviousWaypoint();
              }
              else if (touchPoint.x > 75 && touchPoint.x < 125)
              {
                // Add
                selectedConfirmation = 1;
                userTriggeredEvent = true;
              }
              else if (touchPoint.x > 130 && touchPoint.x < 175)
              {
                // Delete
                selectedConfirmation = 2;
                userTriggeredEvent = true;
              }
              else if (touchPoint.x > 180)
              {
                // Next
                userTriggeredEvent = true;
                currentRoute.proceedToNextWaypoint();
              }
            }
            else if (touchPoint.y > 50 && touchPoint.y < 80 )
            {
              if (touchPoint.x > 10 && touchPoint.x < 50)
              {
                // New Route
                selectedConfirmation = 3;
                userTriggeredEvent = true;
              }
            }
            break;
          case 1:
            // Confirm Add Waypoint
            if (touchPoint.y > 290 && touchPoint.y < 320)
            {
              if (touchPoint.x < 125)
              {
                // Yes
                currentRoute.addWaypoint(GPS.latitude, GPS.longitude);
                selectedConfirmation = 0;
                userTriggeredEvent = true;
              }
              else if (touchPoint.x > 130)
              {
                // No
                selectedConfirmation = 0;
                userTriggeredEvent = true;
              }
            }
            break;
          case 2:
            // Confirm Delete Waypoint
            if (touchPoint.y > 290 && touchPoint.y < 320)
            {
              if (touchPoint.x < 125)
              {
                // Yes
                selectedConfirmation = 0;
                userTriggeredEvent = true;
                currentRoute.deleteWaypoint();
              }
              else if (touchPoint.x > 130)
              {
                // No
                selectedConfirmation = 0;
                userTriggeredEvent = true;
              }
            }
            break;
          case 3:
            // Confirm New Route
            if (touchPoint.y > 290 && touchPoint.y < 320)
            {
              if (touchPoint.x < 125)
              {
                // Yes
                currentRoute.clearRoute();
                selectedConfirmation = 0;
                userTriggeredEvent = true;
              }
              else if (touchPoint.x > 130)
              {
                // No
                selectedConfirmation = 0;
                userTriggeredEvent = true;
              }
            }
            break;
        } // (selectedConfirmation)
    } // (selectedScreen)
  } // (touchPoint.z > ts.pressureThreshhold)

  // if millis() or timer wraps around, we'll just reset it
  if (timer > millis())
  {
    timer = millis();
  }

  // approximately every 3 seconds or so, print out the current stats
  if (userTriggeredEvent || (millis() - timer > 3000))
  {
     drawMainScreenValues();
     // Reset the Timer
     timer = millis();
  }
  if (userTriggeredEvent)
  {
    // Redraw the menu as some choices may need to be drawn
    // while other choices may need to be removed.
    drawMainScreenMenu();
  }
}

bool drawMainScreenLabels()
{
  Tft.paintScreenBlack();

  // GPS Label
  Tft.drawString("GPS", 45, 10, 1, WHITE);

  // Time Label
  Tft.drawString("Time (UTC):", 5, 20, 1, WHITE);

  // Route Label
  Tft.drawString("Route", 5, 40, 1, WHITE);

  Tft.drawString("Current", 80, 80, 1, WHITE);

  Tft.drawString("Loc:", 5, 90, 1, WHITE);

  Tft.drawString("Spd (kts):", 5, 100, 1, WHITE);

  Tft.drawString("Hdg (deg):", 5, 110, 1, WHITE);

  Tft.drawString("To Waypoint:", 40, 130, 1, WHITE);

  Tft.drawString("Loc:", 5, 140, 1, WHITE);

  Tft.drawString("Dist (ft):", 5, 150, 1, WHITE);

  Tft.drawString("Hdg (deg):", 5, 160, 1, WHITE);

  Tft.drawString("Brg (deg):", 5, 170, 1, WHITE);

  Tft.drawString("Time to Arrive (min):", 5, 180, 1, WHITE);

  Tft.drawString("Dist to Home (ft):", 5, 220, 1, WHITE);

  Tft.drawString("Time to Home (min):", 5, 230, 1, WHITE);

  return true;
}

bool drawMainScreenMenu()
{
  // Clear out menu choices that may not longer be available.
  Tft.fillRectangle(0, 60, 239, 10, BLACK);
  Tft.fillRectangle(0, 200, 239, 10, BLACK);
  Tft.fillRectangle(0, 280, 239, 10, BLACK);
  Tft.fillRectangle(0, 300, 239, 10, BLACK);

  // Draw the available menu choices.
  switch (selectedConfirmation)
  {
    case 0:
      Tft.drawString("New", 20, 60, 1, CYAN);
      //Tft.drawString("Save", 70, 60, 1, GREEN);
      //Tft.drawString("Del", 135, 60, 1, RED);
      //Tft.drawString("Open", 180, 60, 1, YELLOW);
 
      Tft.drawString("Prev", 20, 200, 1, YELLOW);
      Tft.drawString("Add", 80, 200, 1, GREEN);
      Tft.drawString("Del", 135, 200, 1, RED);
      Tft.drawString("Next", 185, 200, 1, YELLOW);
      break;
    case 1:
      Tft.drawString("Confirm Add Waypoint", 38, 280, 1, WHITE);
      Tft.drawString("Yes", 50, 300, 1, GREEN);
      Tft.drawString("No", 150, 300, 1, RED);
      break;
    case 2:
      Tft.drawString("Confirm Delete Waypoint", 20, 280, 1, WHITE);
      Tft.drawString("Yes", 50, 300, 1, GREEN);
      Tft.drawString("No", 150, 300, 1, RED);
      break;
    case 3:
      Tft.drawString("Confirm New Route", 42, 280, 1, WHITE);
      Tft.drawString("Yes", 50, 300, 1, GREEN);
      Tft.drawString("No", 150, 300, 1, RED);
      break;
    default:
        break;
  }
}

bool drawMainScreenValues()
{
  //Tft.paintScreenBlack();

  // Number of Satellites
  String titleString = "(";
  titleString += String(GPS.satellites);
  titleString += " satellites)";
  char titleCharArray[40];
  titleString.toCharArray(titleCharArray, 40);
  Tft.fillRectangle(80, 10, 169, 10, BLACK);
  Tft.drawString(titleCharArray, 80, 10, 1, WHITE);

  String timeString = "";
  timeString += String(GPS.hour);
  timeString += ":";
  timeString += String(GPS.minute);
  if (GPS.minute < 10)
  {
    timeString += "0";
  }
  timeString += ":";
  timeString += String(GPS.seconds);
  if (GPS.seconds < 10)
  {
    timeString += "0";
  }
  char timeCharArray[40];
  timeString.toCharArray(timeCharArray, 40);
  Tft.fillRectangle(100, 20, 139, 10, BLACK);
  Tft.drawString(timeCharArray, 100, 20, 1, WHITE);

  // Current

  // Loc:
  String currentLocationString = "";
  char latitudeCharArray[10];
  String latitudeString = dtostrf(GPS.latitude, 1, 4, latitudeCharArray);
  currentLocationString += latitudeString;
  currentLocationString += " ";
  char longitudeCharArray[11];
  String longitudeString = dtostrf(GPS.longitude, 1, 4, longitudeCharArray);
  currentLocationString += longitudeString;
  char currentLocationCharArray[40];
  currentLocationString.toCharArray(currentLocationCharArray, 40);
  Tft.fillRectangle(42, 90, 197, 10, BLACK);
  Tft.drawString(currentLocationCharArray, 42, 90, 1, WHITE);

  // Spd (kts):
  String currentSpeedString = "";
  double currentSpeed_knots = GPS.speed;
  char speedCharArray[7];
  String speedString = dtostrf(currentSpeed_knots, 1, 1, speedCharArray);
  currentSpeedString += speedString;
  char currentSpeedCharArray[40];
  currentSpeedString.toCharArray(currentSpeedCharArray, 40);
  Tft.fillRectangle(90, 100, 149, 10, BLACK);
  Tft.drawString(currentSpeedCharArray, 90, 100, 1, WHITE);

  // Hdg (deg):
  String currentHeadingString = "";
  char headingCharArray[7];
  String headingString = dtostrf(GPS.angle, 1, 0, headingCharArray);
  currentHeadingString += headingString;
  char currentHeadingCharArray[40];
  currentHeadingString.toCharArray(currentHeadingCharArray, 40);
  Tft.fillRectangle(90, 110, 149, 10, BLACK);
  Tft.drawString(currentHeadingCharArray, 90, 110, 1, WHITE);

  // Altitude
  // gps.altitude ( in centimeters)
//  char fixQualityCharArray[20];
//  String fixQualityString = dtostrf(GPS.fixquality, 3, 0, fixQualityCharArray);
//  Tft.drawString(fixQualityCharArray, 5, 120, 1, WHITE);

  if (currentRoute.totalWaypoints > 0)
  {
    // To Waypoint:
    String toWaypointString = "";
    toWaypointString += (currentRoute.currentWaypoint + 1);
    toWaypointString += " of ";
    toWaypointString += currentRoute.totalWaypoints;
    char toWaypointCharArray[30];
    toWaypointString.toCharArray(toWaypointCharArray, 30);
    Tft.fillRectangle(140, 130, 99, 10, BLACK);
    Tft.drawString(toWaypointCharArray, 140, 130, 1, WHITE);

    // Loc:
    String currentWaypointLocationString = "";
    char waypointLatitudeCharArray[10];
    //String waypointLatitudeString = dtostrf(currentRoute.waypoints[currentRoute.currentWaypoint].latitude_decimalDegrees, 9, 4, waypointLatitudeCharArray);
    String waypointLatitudeString = dtostrf(currentRoute.currentWaypointLatitude_degreeDecimalMinutes(), 1, 4, waypointLatitudeCharArray);
    currentWaypointLocationString += waypointLatitudeString;
    currentWaypointLocationString += " ";
    char waypointLongitudeCharArray[11];
    //String waypointLongitudeString = dtostrf(currentRoute.waypoints[currentRoute.currentWaypoint].longitude_decimalDegrees, 10, 4, waypointLongitudeCharArray);
    String waypointLongitudeString = dtostrf(currentRoute.currentWaypointLongitude_degreeDecimalMinutes(), 1, 4, waypointLongitudeCharArray);
    currentWaypointLocationString += waypointLongitudeString;
    char currentWaypointLocationCharArray[40];
    currentWaypointLocationString.toCharArray(currentWaypointLocationCharArray, 40);
    Tft.fillRectangle(42, 140, 197, 10, BLACK);
    Tft.drawString(currentWaypointLocationCharArray, 42, 140, 1, WHITE);

    // Dist (ft):
    double distanceFromCurrentWaypoint_nauticalMiles = currentRoute.getDistanceToWaypoint_nauticalMiles(currentRoute.currentWaypoint, GPS.latitude, GPS.longitude);
    String distanceToWaypointString = "";
    char distanceToWaypointCharArray[20];
    String distanceValueToWaypointString = dtostrf((distanceFromCurrentWaypoint_nauticalMiles * 6076.12), 1, 0, distanceToWaypointCharArray);
    distanceToWaypointString += distanceValueToWaypointString;
    char currentDistanceToWaypointCharArray[40];
    distanceToWaypointString.toCharArray(distanceToWaypointCharArray, 40);
    Tft.fillRectangle(90, 150, 149, 10, BLACK);
    Tft.drawString(distanceToWaypointCharArray, 90, 150, 1, WHITE);

    // Hdg (deg):
    double headingToCurrentWaypoint_degrees = currentRoute.getHeadingToCurrentWaypoint_degrees(GPS.latitude, GPS.longitude);
    String headingToWaypointString = "";
    char headingToWaypointCharArray[20];
    String headingValueToWaypointString = dtostrf(headingToCurrentWaypoint_degrees, 1, 0, headingToWaypointCharArray);
    headingToWaypointString += headingValueToWaypointString;
    char currentHeadingToWaypointCharArray[40];
    headingToWaypointString.toCharArray(headingToWaypointCharArray, 40);
    Tft.fillRectangle(90, 160, 149, 10, BLACK);
    Tft.drawString(headingToWaypointCharArray, 90, 160, 1, WHITE);

    // Brg (deg):
    double relativeBearingToCurrentWaypoint_degrees = getRelativeBearing_degrees(GPS.angle, headingToCurrentWaypoint_degrees);
    String bearingToWaypointString = "";
    char bearingToWaypointCharArray[20];
    String bearingValueToWaypointString = dtostrf(relativeBearingToCurrentWaypoint_degrees, 1, 0, bearingToWaypointCharArray);
    bearingToWaypointString += bearingValueToWaypointString;
    char currentBearingToWaypointCharArray[40];
    bearingToWaypointString.toCharArray(currentBearingToWaypointCharArray, 40);
    Tft.fillRectangle(90, 170, 149, 10, BLACK);
    Tft.drawString(currentBearingToWaypointCharArray, 90, 170, 1, WHITE);

    // Time to Arrive (min):
    String timeToArriveString = "";
    if (currentSpeed_knots > 0.0)
    {
      double timeToArrive_minutes = distanceFromCurrentWaypoint_nauticalMiles / currentSpeed_knots * 60.0;
      if (timeToArrive_minutes < 9999)
      {
        // If stopped (or ridiculously far away), then show nothing.
        char timeToArriveCharArray_minutes[20];
        String timeToArriveString_minutes = dtostrf(timeToArrive_minutes, 1, 0, timeToArriveCharArray_minutes);
        timeToArriveString += timeToArriveString_minutes;
      }
    }
    char timeToArriveCharArray[40];
    timeToArriveString.toCharArray(timeToArriveCharArray, 40);
    Tft.fillRectangle(178, 180, 61, 10, BLACK);
    Tft.drawString(timeToArriveCharArray, 178, 180, 1, WHITE);

    // Dist to Home (ft):
    double distanceToHome_nauticalMiles = currentRoute.getDistanceToHome_nauticalMiles(GPS.latitude, GPS.longitude);
    String distanceToHomeString = "";
    char distanceToHomeCharArray[20];
    String distanceValueToHomeString = dtostrf((distanceToHome_nauticalMiles * 6076.12), 1, 0, distanceToHomeCharArray);
    distanceToHomeString += distanceValueToHomeString;
    char currentDistanceToHomeCharArray[40];
    distanceToHomeString.toCharArray(distanceToHomeCharArray, 40);
    Tft.fillRectangle(165, 220, 74, 10, BLACK);
    Tft.drawString(distanceToHomeCharArray, 165, 220, 1, WHITE);

    // Time to Home (min):
    String timeToHomeString = "";
    if (currentSpeed_knots > 0.0)
    {
      double timeToHome_minutes = distanceToHome_nauticalMiles / currentSpeed_knots * 60.0;
      if (timeToHome_minutes < 9999)
      {
        // If stopped (or ridiculously far away), then show nothing.
        char timeToHomeCharArray_minutes[20];
        String timeToHomeString_minutes = dtostrf(timeToHome_minutes, 1, 0, timeToHomeCharArray_minutes);
        timeToHomeString += timeToHomeString_minutes;
      }
    }
    char timeToHomeCharArray[40];
    timeToHomeString.toCharArray(timeToHomeCharArray, 40);
    Tft.fillRectangle(165, 230, 74, 10, BLACK);
    Tft.drawString(timeToHomeCharArray, 165, 230, 1, WHITE);
  }
  else
  {
    // To Waypoint:  
    Tft.fillRectangle(140, 130, 99, 10, BLACK);
    // Loc:
    Tft.fillRectangle(42, 140, 197, 10, BLACK);
    // Dist (ft):
    Tft.fillRectangle(90, 150, 149, 10, BLACK);
    // Hdg (deg):
    Tft.fillRectangle(90, 160, 149, 10, BLACK);
    // Brg (deg):
    Tft.fillRectangle(90, 170, 149, 10, BLACK);
    // Time to Arrive (min):
    Tft.fillRectangle(178, 180, 61, 10, BLACK);
 
    // Dist to Home (ft):
    Tft.fillRectangle(165, 220, 74, 10, BLACK);
    // Time to Home (min):
    Tft.fillRectangle(165, 230, 74, 10, BLACK);
  }

  return true;
}



The code within this post is released into the public domain. You're free to use it however you wish, but it is provided "as-is" without warranty of any kind. In no event shall the author be liable for any claims or damages in connection with this software.

No comments:

Post a Comment