My GPS won't work with other modules

when I checked my GPS sensor with Arduino Mega independently, It works properly.
but, when i add GPS sensor codes into my overall codes, it doesn't work properly and keep says GPS value(lat,long) is 0.0000. I want to fix this problem. how do I fix this? GPS sensor got its power and I can see the red light on GPS Sensor. It is not because cold start. please help me.
here's my code.


#include <SoftwareSerial.h>
SoftwareSerial esp8266(2, 3); //esp8266 시리얼 통신 설정
#define esp8266 Serial3   //esp8266선을 RX,TX3으로 수정
#define BAUDRATE 9600


#include <TinyGPS.h>
#include <Wire.h>           //BH1750 조도센서 라이브러리 포함
#include <BH1750FVI.h>
#include <DHT.h>            //DHT22 라이브러리 포함

// 핀 설정 및 센서 기본 변수 설정
#define DEBUG   true        //esp 설정
#define DHTPIN A0           //DHT22 온습도 센서 핀 설정
#define DHTTYPE DHT22
#define MG_PIN A1           //MG811 CO2센서 핀 설정
#define VltS A2
#define BOOL_PIN 2
#define DC_GAIN 8.5
#define READ_SAMPLE_INTERVAL 5
#define READ_SAMPLE_TIMES 5
#define ZERO_POINT_VOLTAGE 0.220
#define REACTION_VOLTAGE 0.030
#define RCPin1 3
#define RCPin2 4


//라이브러리별 설정
DHT dht(DHTPIN, DHTTYPE);
BH1750FVI::eDeviceMode_t DEVICEMODE = BH1750FVI::k_DevModeContHighRes;
BH1750FVI LightSensor(DEVICEMODE);
SoftwareSerial uart_gps(5, 4);
#define uart_gps Serial2
TinyGPS gps;

//전역변수 설정
float hum;
float temp;
float CO2Curve[3]  =  {2.602, ZERO_POINT_VOLTAGE, (REACTION_VOLTAGE / (2.602 - 3))};
float volts;
float vout = 0.0;
float vin = 0.0;
float R1 = 30000.0;
float R2 = 7500.0;
float Latitude, Longitude;
int Vval = 0;
int RCValue1;
int RCValue2;
int Angle;
int Spd_rpm;
int Spd_rps;


//String형태로 입출력 변수 설정
String AP =     "bime0304_2.5G";        //Wifi설정
String PASS =   "bime0304";
String WApiKey = "CU8634SH66Q1MLO9";    //ThingSpeak 내 Write API
String RApiKey = "XMP6OYHXR8RYX55A";    //ThingSpeak 내 Read API
String HOST = "api.thingspeak.com";
String PORT = "80";
String fieldTemp = "field1";            //Air Temperature 필드1 설정(최대 8)
String fieldHum  = "field2";            //Air humidity 필드2 설정
String fieldLight = "field3";           //Light Intensity 필드3 설정
String fieldCO2 = "field4";             //CO2 센서 필드 4 설정
String fieldlat = "field5";             //GPS 위도
String fieldlon = "field6";             //GPS 경도
String fieldangle = "field7";
String fieldspeed = "field8";


int countTrueCommand;                   //ESP8266 커맨드 카운트 함수
int countTimeCommand;
boolean found = false;
int percentage;                         //CO2센서 전역변수 설정

//CO2 계산 함수
int  MGGetPercentage(float volts, float * pcurve) //MGGetPercentage 변수
{
  if ((volts / DC_GAIN ) >= ZERO_POINT_VOLTAGE) {
    return -1;
  } else {
    return pow(10, ((volts / DC_GAIN) - pcurve[1]) / pcurve[2] + pcurve[0]);
  }
}

float MGRead(int mg_pin) //MGRead변수
{
  int i;
  float v = 0;
  for (i = 0; i < READ_SAMPLE_TIMES; i++) {
    v += analogRead(mg_pin);
    delay(READ_SAMPLE_INTERVAL);
  }
  v = (v / READ_SAMPLE_TIMES) * 5 / 1024 ;
  return v;
}


void getgps(TinyGPS&gps) {

  gps.f_get_position(&Latitude, &Longitude);
  int year;
  byte month, day, hour, minute, second, hundredths;
  gps.crack_datetime(&year, &month, &day, &hour, &second, &hundredths);
  unsigned long chars;
  unsigned short sentences, failed_checksum;
  gps.stats(&chars, &sentences, &failed_checksum);



}



void setup()
{
  unsigned int i = 0;
  // Open Serial1 communications and wait for port to open:
  // 시리얼 1 통신 시작 및 열릴때까지 대기
  esp8266.begin(BAUDRATE);            //ESP8266 보드레이트 설정
  esp8266.setTimeout(5000);
  uart_gps.begin(9600);
  dht.begin();                        //온습도 시작
  LightSensor.begin();                //조도 센서 시작
  Serial.begin(9600);                 //시리얼 통신 시작
  pinMode(RCPin1, INPUT);
  pinMode(RCPin2, INPUT);
  pinMode(BOOL_PIN, INPUT);
  pinMode(VltS, INPUT);
  digitalWrite(BOOL_PIN, HIGH);

  Serial.println("Thingspeak with ESP-01");
  //ESPWiFi 셋팅
  sendCommand("AT", 5, "OK");
  sendCommand("AT+CWMODE=1", 5, "OK");
  sendCommand("AT+CWJAP=\"" + AP + "\",\"" + PASS + "\"", 20, "OK");

  //IP획득 및 표시
  sendCommand("AT+CIFSR", 2, "OK");
  delay(2000);
}

//반복 조건
void loop()
{

  hum = dht.readHumidity();                             //습도 읽는 함수
  temp = dht.readTemperature();                         //온도 읽는 함수
  uint16_t lux = LightSensor.GetLightIntensity();       //조도 읽는 함수
  Vval = analogRead(VltS);
  vout = (Vval * 5.0) / 1024.0;
  vin = vout / (R2 / (R1 + R2));                        //전압 센서
  volts = MGRead(MG_PIN);                             //CO2내 전압
  percentage = MGGetPercentage(volts, CO2Curve);
  RCValue1 = pulseIn(RCPin1, HIGH);
  RCValue2 = pulseIn(RCPin2, HIGH);
  Angle = map(RCValue2, 1000, 1900, -45, 45);
  Spd_rpm = map(RCValue1, 1000, 1900, -15080, 15080);
  Spd_rps = Spd_rpm / 60;
  while (uart_gps.available()) {
    int c = uart_gps.read();
    if (gps.encode(c)) {
      getgps(gps);
    }
  }
  //시리얼 표시
  Serial.print(" lat: ");
  Serial.print(Latitude, 5);      //GPS 위도
  Serial.print(" lon: ");
  Serial.print(Longitude, 5);     //GPS 경도
  Serial.print(" alt: ");
  Serial.print(gps.f_altitude());//GPS 고도
  Serial.print(" Spd: ");
  Serial.print(Spd_rpm);
  Serial.print(" Angle: ");
  Serial.print(Angle);
  Serial.print("Humidity: ");
  Serial.print(hum, 1);           //습도 소수점 첫째 표시
  Serial.print(" %, Temp: ");
  Serial.print(temp, 1);          //온도 소수점 첫째 표시
  Serial.print(" Celsius, ");
  Serial.print(lux);              //조도 표시
  Serial.print(" lux, ");
  Serial.print(volts);            //CO2볼트 표시
  Serial.print("V, ");
  if (percentage == -1) {         //CO2 값 표시
    Serial.print( "<400" );
  }
  else {
    Serial.print(percentage);
  }
  Serial.print( "ppm, " );
  if (digitalRead(BOOL_PIN))    //CO2 BoolPin 상태 보고
  {
    Serial.println( "HIGH" );
  }
  else
  {
    Serial.println( "LOW" );
  }

  //Thing Speak 서버에 업로드

  //통합 시도
  sendCommand("AT+CIPMUX=1", 5, "OK");
  String getData = "GET /update?api_key=" + WApiKey + "&" + fieldTemp + "=" + String(temp) + "&" + fieldHum + "=" + String(hum) + "&" + fieldLight + "=" + String(lux) + "&" + fieldCO2 + "=" + String(percentage) + "&" + fieldlat + "=" + String(Latitude) + "&" + fieldlon + "=" + String(Longitude) + "&" + fieldangle + "=" + String(Angle) + "&" + fieldspeed + "=" + String(Spd_rpm);
  sendCommand("AT+CIPSTART=0,\"TCP\",\"" + HOST + "\"," + PORT, 15, "OK");
  sendCommand("AT+CIPSEND=0," + String(getData.length() + 4), 4, ">");
  esp8266.println(getData); countTrueCommand++;
  sendCommand("AT+CIPCLOSE=0", 5, "OK");

}

// ESP 커맨드 입력 및 전송상태 수신
void sendCommand(String command, int maxTime, char readReplay[]) {
  Serial.print(countTrueCommand);
  Serial.print(". at command => ");
  Serial.print(command);
  Serial.print(" ");
  while (countTimeCommand < (maxTime * 1))
  {
    esp8266.println(command);//at+cipsend
    if (esp8266.find(readReplay)) //ok
    {
      found = true;
      break;
    }

    countTimeCommand++;
  }

  if (found == true)
  {
    Serial.println("OYI");
    countTrueCommand++;
    countTimeCommand = 0;
  }

  if (found == false)
  {
    Serial.println("Fail");
    countTrueCommand = 0;
    countTimeCommand = 0;
  }

  found = false;
}


+this is my serial monitor

A Mega has several hardware ports, any reason to use a software port on a Mega?

Multiple software serials does not work very well. A Mega has several hardware ports, any reason to use a software port on a Mega?

Why does the code have 8266 thingies in it?

Only one instance of software serial can be listening at a time.

Use the hardware serial ports instead.

How do you imagine that this can work?

SoftwareSerial esp8266(2, 3); //esp8266 시리얼 통신 설정
#define esp8266 Serial3   //esp8266선을 RX,TX3으로 수정
...
SoftwareSerial uart_gps(5, 4);
#define uart_gps Serial2

Finally, use of String objects on the Arduino Mega will cause memory problems and program crashes.

Thanks for your reply.
We recognize that we need to use hardware serial, so we redesignated Serial2 and Serial3 after software serial. It seems that the SoftwareSerial part at the top is like that because it uses the existing example code.
Communication of ESP8266 is possible, but GPS signal is not received. Is there any way to receive the signal from Serial2?

Thanks for your reply.
The reason for using the code of 8266 seems to be that UNO tests first and the code modification is not suitable for Mega.
The 8266 is currently using serial 3, and gps is accepting data as serial 2.
However, it was confirmed that the 8266 works normally in the Wi-Fi environment, but the GPS does not output normally. If you know a way to solve it, I'd appreciate it if you let me know.

well here is a code I used on a MEGA several years ago. Perhaps it will give a clue or 2?

// Test code for Ultimate GPS Using Hardware Serial (e.g. GPS Flora or FeatherWing)
//
// This code shows how to listen to the GPS module via polling. Best used with
// Feathers or Flora where you have hardware Serial and no interrupt
//
// Tested and works great with the Adafruit GPS FeatherWing
// ------> https://www.adafruit.com/products/3133
// or Flora GPS
// ------> https://www.adafruit.com/products/1059
// but also works with the shield, breakout
// ------> https://www.adafruit.com/products/1272
// ------> https://www.adafruit.com/products/746
// 
// Pick one up today at the Adafruit electronics shop
// and help support open source hardware & software! -ada
     
#include <Adafruit_GPS.h>

// what's the name of the hardware serial port?
#define GPSSerial Serial1

// Connect to the GPS on the hardware port
Adafruit_GPS GPS(&GPSSerial);
     
// 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

uint32_t timer = millis();


void setup()
{
  //while (!Serial);  // uncomment to have the sketch wait until Serial is ready
  
  // 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("Adafruit GPS library basic test!");
     
  // 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
  GPSSerial.println(PMTK_Q_RELEASE);
}

void loop() // run over and over again
{
  // 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
  }
  // if millis() or timer wraps around, we'll just reset it
  if (timer > millis()) timer = millis();
     
  // approximately every 2 seconds or so, print out the current stats
  if (millis() - timer > 2000) {
    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);
    Serial.print("Date: ");
    Serial.print(GPS.day, DEC); Serial.print('/');
    Serial.print(GPS.month, DEC); Serial.print("/20");
    Serial.println(GPS.year, DEC);
    Serial.print("Fix: "); Serial.print((int)GPS.fix);
    Serial.print(" quality: "); Serial.println((int)GPS.fixquality);
    if (GPS.fix) {
      Serial.print("Location: ");
      Serial.print(GPS.latitude, 4); Serial.print(GPS.lat);
      Serial.print(", ");
      Serial.print(GPS.longitude, 4); Serial.println(GPS.lon);
      Serial.print("Speed (knots): "); Serial.println(GPS.speed);
      Serial.print("Angle: "); Serial.println(GPS.angle);
      Serial.print("Altitude: "); Serial.println(GPS.altitude);
      Serial.print("Satellites: "); Serial.println((int)GPS.satellites);
    }
  }
}

that may help you get started.

Please rewrite your code, get rid all SoftwareSerials and test your sketch without it.. Asking for help with code that you yourself think is wrong is impolite....
Do not force the others dig to this:

Please forgive me if my answer was rude.
It was because I was afraid that the results I had accidentally deleted from my code would be erased. We will delete the Software Serial code. I'll attach the modified code accordingly. Thanks for pointing out what to watch out for.

#define esp8266 Serial3   //esp8266선을 RX,TX3으로 수정
#define uart_gps Serial2  //gps 선 RX,TX2
#define BAUDRATE 9600

#include <TinyGPS.h>
#include <Wire.h>           //BH1750 조도센서 라이브러리 포함
#include <BH1750FVI.h>
#include <DHT.h>            //DHT22 라이브러리 포함

// 핀 설정 및 센서 기본 변수 설정
#define DEBUG   true        //esp 설정
#define DHTPIN A0           //DHT22 온습도 센서 핀 설정
#define DHTTYPE DHT22
#define MG_PIN A1           //MG811 CO2센서 핀 설정
#define VltS A2
#define BOOL_PIN 2
#define DC_GAIN 8.5
#define READ_SAMPLE_INTERVAL 5
#define READ_SAMPLE_TIMES 5
#define ZERO_POINT_VOLTAGE 0.220
#define REACTION_VOLTAGE 0.030
#define RCPin1 3
#define RCPin2 4


//라이브러리별 설정
DHT dht(DHTPIN, DHTTYPE);
BH1750FVI::eDeviceMode_t DEVICEMODE = BH1750FVI::k_DevModeContHighRes;
BH1750FVI LightSensor(DEVICEMODE);
TinyGPS gps;

//전역변수 설정
float hum;
float temp;
float CO2Curve[3]  =  {2.602, ZERO_POINT_VOLTAGE, (REACTION_VOLTAGE / (2.602 - 3))};
float volts;
float vout = 0.0;
float vin = 0.0;
float R1 = 30000.0;
float R2 = 7500.0;
float Latitude, Longitude;
int Vval = 0;
int RCValue1;
int RCValue2;
int Angle;
int Spd_rpm;
int Spd_rps;


//String형태로 입출력 변수 설정
String AP =     "bime0304_2.5G";        //Wifi설정
String PASS =   "bime0304";
String WApiKey = "CU8634SH66Q1MLO9";    //ThingSpeak 내 Write API
String RApiKey = "XMP6OYHXR8RYX55A";    //ThingSpeak 내 Read API
String HOST = "api.thingspeak.com";
String PORT = "80";
String fieldTemp = "field1";            //Air Temperature 필드1 설정(최대 8)
String fieldHum  = "field2";            //Air humidity 필드2 설정
String fieldLight = "field3";           //Light Intensity 필드3 설정
String fieldCO2 = "field4";             //CO2 센서 필드 4 설정
String fieldlat = "field5";             //GPS 위도
String fieldlon = "field6";             //GPS 경도
String fieldangle = "field7";
String fieldspeed = "field8";


int countTrueCommand;                   //ESP8266 커맨드 카운트 함수
int countTimeCommand;
boolean found = false;
int percentage;                         //CO2센서 전역변수 설정

//CO2 계산 함수
int  MGGetPercentage(float volts, float * pcurve) //MGGetPercentage 변수
{
  if ((volts / DC_GAIN ) >= ZERO_POINT_VOLTAGE) {
    return -1;
  } else {
    return pow(10, ((volts / DC_GAIN) - pcurve[1]) / pcurve[2] + pcurve[0]);
  }
}

float MGRead(int mg_pin) //MGRead변수
{
  int i;
  float v = 0;
  for (i = 0; i < READ_SAMPLE_TIMES; i++) {
    v += analogRead(mg_pin);
    delay(READ_SAMPLE_INTERVAL);
  }
  v = (v / READ_SAMPLE_TIMES) * 5 / 1024 ;
  return v;
}


void getgps(TinyGPS&gps) {

  gps.f_get_position(&Latitude, &Longitude);
  int year;
  byte month, day, hour, minute, second, hundredths;
  gps.crack_datetime(&year, &month, &day, &hour, &second, &hundredths);
  unsigned long chars;
  unsigned short sentences, failed_checksum;
  gps.stats(&chars, &sentences, &failed_checksum);



}



void setup()
{
  unsigned int i = 0;
  // Open Serial1 communications and wait for port to open:
  // 시리얼 1 통신 시작 및 열릴때까지 대기
  esp8266.begin(BAUDRATE);            //ESP8266 보드레이트 설정
  esp8266.setTimeout(5000);
  uart_gps.begin(9600);
  dht.begin();                        //온습도 시작
  LightSensor.begin();                //조도 센서 시작
  Serial.begin(9600);                 //시리얼 통신 시작
  pinMode(RCPin1, INPUT);
  pinMode(RCPin2, INPUT);
  pinMode(BOOL_PIN, INPUT);
  pinMode(VltS, INPUT);
  digitalWrite(BOOL_PIN, HIGH);

  Serial.println("Thingspeak with ESP-01");
  //ESPWiFi 셋팅
  sendCommand("AT", 5, "OK");
  sendCommand("AT+CWMODE=1", 5, "OK");
  sendCommand("AT+CWJAP=\"" + AP + "\",\"" + PASS + "\"", 20, "OK");

  //IP획득 및 표시
  sendCommand("AT+CIFSR", 2, "OK");
  delay(2000);
}

//반복 조건
void loop()
{

  hum = dht.readHumidity();                             //습도 읽는 함수
  temp = dht.readTemperature();                         //온도 읽는 함수
  uint16_t lux = LightSensor.GetLightIntensity();       //조도 읽는 함수
  Vval = analogRead(VltS);
  vout = (Vval * 5.0) / 1024.0;
  vin = vout / (R2 / (R1 + R2));                        //전압 센서
  volts = MGRead(MG_PIN);                             //CO2내 전압
  percentage = MGGetPercentage(volts, CO2Curve);
  RCValue1 = pulseIn(RCPin1, HIGH);
  RCValue2 = pulseIn(RCPin2, HIGH);
  Angle = map(RCValue2, 1000, 1900, -45, 45);
  Spd_rpm = map(RCValue1, 1000, 1900, -15080, 15080);
  Spd_rps = Spd_rpm / 60;
  while (uart_gps.available()) {
    int c = uart_gps.read();
    if (gps.encode(c)) {
      getgps(gps);
    }
  }
  //시리얼 표시
  Serial.print(" lat: ");
  Serial.print(Latitude, 5);      //GPS 위도
  Serial.print(" lon: ");
  Serial.print(Longitude, 5);     //GPS 경도
  Serial.print(" alt: ");
  Serial.print(gps.f_altitude());//GPS 고도
  Serial.print(" Spd: ");
  Serial.print(Spd_rpm);
  Serial.print(" Angle: ");
  Serial.print(Angle);
  Serial.print("Humidity: ");
  Serial.print(hum, 1);           //습도 소수점 첫째 표시
  Serial.print(" %, Temp: ");
  Serial.print(temp, 1);          //온도 소수점 첫째 표시
  Serial.print(" Celsius, ");
  Serial.print(lux);              //조도 표시
  Serial.print(" lux, ");
  Serial.print(volts);            //CO2볼트 표시
  Serial.print("V, ");
  if (percentage == -1) {         //CO2 값 표시
    Serial.print( "<400" );
  }
  else {
    Serial.print(percentage);
  }
  Serial.print( "ppm, " );
  if (digitalRead(BOOL_PIN))    //CO2 BoolPin 상태 보고
  {
    Serial.println( "HIGH" );
  }
  else
  {
    Serial.println( "LOW" );
  }

  //Thing Speak 서버에 업로드

  //통합 시도
  sendCommand("AT+CIPMUX=1", 5, "OK");
  String getData = "GET /update?api_key=" + WApiKey + "&" + fieldTemp + "=" + String(temp) + "&" + fieldHum + "=" + String(hum) + "&" + fieldLight + "=" + String(lux) + "&" + fieldCO2 + "=" + String(percentage) + "&" + fieldlat + "=" + String(Latitude) + "&" + fieldlon + "=" + String(Longitude) + "&" + fieldangle + "=" + String(Angle) + "&" + fieldspeed + "=" + String(Spd_rpm);
  sendCommand("AT+CIPSTART=0,\"TCP\",\"" + HOST + "\"," + PORT, 15, "OK");
  sendCommand("AT+CIPSEND=0," + String(getData.length() + 4), 4, ">");
  esp8266.println(getData); countTrueCommand++;
  sendCommand("AT+CIPCLOSE=0", 5, "OK");

}

// ESP 커맨드 입력 및 전송상태 수신
void sendCommand(String command, int maxTime, char readReplay[]) {
  Serial.print(countTrueCommand);
  Serial.print(". at command => ");
  Serial.print(command);
  Serial.print(" ");
  while (countTimeCommand < (maxTime * 1))
  {
    esp8266.println(command);//at+cipsend
    if (esp8266.find(readReplay)) //ok
    {
      found = true;
      break;
    }

    countTimeCommand++;
  }

  if (found == true)
  {
    Serial.println("OYI");
    countTrueCommand++;
    countTimeCommand = 0;
  }

  if (found == false)
  {
    Serial.println("Fail");
    countTrueCommand = 0;
    countTimeCommand = 0;
  }

  found = false;
}

Thanks for sharing your code. I will try it with my GPS sensor. It is very different from the existing code of mine, so I will test it separately and then apply it.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.