Arduino UNO Serial.print printing out wrong data

Hello I have posted something similar to this before but I think this is a different issue to my previous post about nothing being printed to the screen

My problem is that the Arduino UNO is printing out data I did not ask it to print
Here is a test program I wrote and my output

int i = 0;
void setup()
{
  Serial.begin(9600);
}
void loop()
{
  Serial.print("Loop: ");
  Serial.println(i);
  i++;
}

And when it runs I get this:

Loop: 9øLoop: 0
Loop: 1
Loop: 2
Loop: 3

Could anyone tell me any possible reason for this, as it is seriously interfering with my project where I need to print AT commands to a shield. I'm wondering is it a problem with the compiler in the IDE or the board itself

I have tried it on Windows 7 with arduino 0021 and arduino 0022 and I get the same response each time.

Oh p.s I tried the loopback test on my board and it worked correctly. So I'm guessing something's happening on the software side.

My guess is that your sketch got as far as pushing "Loop: 8" into the USB input buffers before Serial Monitor connected to it. The sketch then managed to push "Loop: 9" into the USB input buffers before Serial Monitor caused a reset. That caused a single-character glitch followed by the sketch starting over.

If you disable auto-reset then the connection to Serial Monitor won't cause a reset and you will not get repeated data in your output.

Hi johnwasser

Thanks for your reply, unfortunately disabling auto reset did not work my code just doesn't seem to run.

What I have at the moment is this:

#include <stdlib.h>
#include <SoftwareSerial.h>

#define gpsRX 11 //Gps module
#define gpsTX 10

#define ardRX 9 //Other Arduino
#define ardTX 8



//============================VARIABLES====================================

SoftwareSerial gps = SoftwareSerial(gpsRX,gpsTX);
SoftwareSerial ard = SoftwareSerial(ardRX,ardTX);

int led = 13;
int onModulePin = 2;        // the pin to switch on the module (without press on button) 
boolean ini=true;
char mobile[11]="087*******"; //Mobile number to text
int DID = 1;

byte inGPS;
char RMC[500]=""; //Gps NMEA sentence
int rmcCount=0;

float latOne=0; //latitudes and longitudes
float latTwo=0;
float longOne;
float longTwo;

//==============DEBUG=========================
char debug[500]="";
char inet[500]="";
int inetCount =0;
int de = 0;
int hl = 0;
//======================FUNCTIONS=====================================

void initGPRS() //Turn on GPRS module, keep resetting until carrier information is recieved
{
   Serial.println("Beginning initGPRS()");
   int test = 0;
  while(test<1)
 {
    Serial.println("AT+COPS?");//Ask for carrier information
    delay(5000);
    for(int i=0;i<25;i++)
    {  
      inGPS=Serial.read();
      debug[i] = inGPS;
      
      Serial.print(debug[i]);
      if(debug[i]=='+') //Start of carrier info
      {
        test++;
        break;
      }
    }
    Serial.println();
    
   res();//Reset module
 }
    Serial.println("AT+CREG?");//Get signal strength
    delay(1000);
    Serial.println("AT+CSCA?");//Get message service centre address
    delay(1000);
}

void getGPS()//Retrieve GPS sentence
{
    rmcCount = 0;
    inGPS = gps.read();
    while((gps.read()!='G') &&( gps.read()!='G')&& (gps.read()!='A'))//inGPS!='R')
    {
      inGPS = gps.read();
      debug[de] = inGPS;
      Serial.print(debug[de]);
      de++;
    }
    RMC[0]='G';
    RMC[1]='G';
    RMC[2]='A';
    RMC[3]=':';
    rmcCount = 4;
    while(inGPS!='*')
    {
      inGPS=gps.read();
      debug[rmcCount] = inGPS;
      RMC[rmcCount] = inGPS;
      rmcCount++;
      Serial.print(RMC[rmcCount]);
    }
}

//======================GPRS FUNCTIONS===================


void connServer(float lat,float longit,int did,boolean update)//Connect to server, if update is false revtieve info from server
{
   Serial.println("AT&K3");
   delay(1000);
 Serial.println("AT+KCNXCFG=0,\"GPRS\",\"live.vodafone.com\",\"\",\"\",\"0.0.0.0\",\"10.24.59.100\",\"0.0.0.0\"");
   delay(1000);
   Serial.println("AT+KCNXTIMER=0,60,2,70");
   delay(1000);
   Serial.println("AT+KCNXPROFILE=0");
   delay(1000);
   Serial.println("AT+CGATT=1");
   delay(1000);
  if(!update)
  {
    Serial.print("AT+KTCPCFG=0,0,\"www.ca-326.3owl.com/inf.php?DID=");
  }
  else
  {
    Serial.print("AT+KTCPCFG=0,0,\"http://www.ca-326.3owl.com/up_php.php?DID=");
  }
  Serial.print(did);
  if(update)
  {
    Serial.print("&lat=");
    Serial.print(lat);
    Serial.print("&long=");
    Serial.print(longit);
  }
   Serial.print("\",80");
   delay(1000);
   Serial.println("AT+KTCPCNX=1");
   delay(5000);
   Serial.println("AT+KTCPSND=1,18");
   Serial.println("GET / HTTP/1.0");
        Serial.print(char(10));
        Serial.print(char(13));
        Serial.println("--EOF--Pattern--");
       delay(60000);
   Serial.println("AT+KTCPRCV=1,10000");   
   
   while(Serial.available()>0)
   {
     inGPS = Serial.read();
     inet[inetCount] = inGPS;
     inetCount++;
   }
   Serial.println("AT+KTCPCLOSE=1,1");
}


void sendMessage(char* mob,float& lat,float& lon)//Send text message
{
    Serial.print("Going to wait for 1 min");
    delay(60000);
    Serial.println("AT+CMGF=1");         // set the SMS mode to text
    delay(1000);
    Serial.println("AT+CSCS=\"IRA\"");
    delay(1500);
    Serial.print("AT+CMGS=\"");
    Serial.print(mob);
    Serial.print("\"\r");
    delay(5000);
    Serial.print("Your car has moved to: ");     // the SMS body
    Serial.print(lat);
    Serial.print(" , ");
    Serial.print(lon);
    delay(1000);
    Serial.write(char(26));             // end of message command 1A (hex)
}




void switchModule(){
 // Serial.println("Turning on");
  digitalWrite(onModulePin,HIGH);
  delay(2000);
  digitalWrite(onModulePin,LOW);
}

void res()
{
  switchModule();   
delay(3000);  // switch the module ON
  for (int i=0;i<60;i++){ //Wait for one minute for setup to complete
    delay(1000);

  } 
}


float getdir(boolean latitude)//Parse GPS sentence into float of latitude or longitude
{
	char minut[7] = "";
	char deg[4] = "";
	char dir;
	float minA;
	float degA;
	float lat;
	int comCount = 0;
        int check = 4;
	if(latitude)
	{
		check = 2;
	}
	int mm = 0;
	int minus;
	for(int j=0;j<66;j++)
	{
		if(RMC[j] == ',')
			comCount++;
		if(comCount==check)
		{
			minus=j+1;
			deg[0] = RMC[minus];
			minus++;
			deg[1] = RMC[minus];
			minus++;
                        if(latitude)
                          deg[2] = '\0';
                        else
                        {
                          deg[2] = RMC[minus];
                          minus++;
                          deg[3] = '\0';
                        }
			while(RMC[minus]!=',')
			{
				minut[mm] = RMC[minus];
                                mm++;
				minus++;
			}
			minus++;
			dir = RMC[minus];
			break;
		}
			
	}
        Serial.print("Degrees: ");
        for(int degs=0;degs<3;degs++)
        {
          Serial.print(deg[degs]);
        }
        Serial.println();
        Serial.println("Minutes");
        for(int minu =0;minu<mm;minu++)
        {
          Serial.print(minut[minu]);
        }
        Serial.println();
	minA = (float)atof(minut);
	degA = (float)(atoi((deg)));
        Serial.print("Degrees as int: ");
        Serial.println(degA);
	lat = degA + (minA/60);
	if((dir=='S'&&latitude)||(dir=='W'&&!latitude))
		return lat*-1;
	else
		return lat;
}




void setup()
{ 
    pinMode(led,OUTPUT);
    pinMode(onModulePin,OUTPUT);
    pinMode(ardRX,INPUT);
    pinMode(ardTX,OUTPUT);
    pinMode(gpsRX,INPUT);
    pinMode(gpsTX,OUTPUT);
    Serial.begin(9600);
    gps.begin(4800);
    ard.begin(9600);
    delay(2000);
    Serial.println("Setup");
    res();
    initGPRS();  
}

void loop()
{
    if(ini)//If first run, get initial gps info
    {
      getGPS();
      latOne = getdir(true);
      Serial.print("Latitude: ");
      Serial.println(latOne);
      longOne = getdir(false);
    }
   for(int wait=0;wait<3;wait++)//Wait 3 mins
    {
      Serial.print(wait);
      Serial.println(" minutes left");
      delay(60000);
    }
    Serial.println("Getting second GPS"); //Check has position changed
    getGPS();
    latTwo = getdir(true);
    longTwo = getdir(false);
    Serial.println("Got second GPS");
    if((latOne!=latTwo) ||(longTwo!=longOne))
    {
      Serial.println("Entered if statement");
      if(ard.read()!=1)//Check information from other arduino
      {
        Serial.println("About to send text");
        sendMessage(mobile,latTwo,longTwo);//Send text
        Serial.println("Finished sending");
      }
      Serial.println("Updating Server");
     connServer(latOne,longOne,1,true);//Update server
      Serial.println("Updated Server");
      latOne=latTwo;
      longOne=longTwo;
   }
     Serial.println("About to send text");
     sendMessage(mobile,latTwo,longTwo);//Send text (FOR TESTING)
 
    Serial.println("Finished sending");
    Serial.println("Inet Debug: ");//Print debug information (TESTING)
    for(int inetC=0;inetC<inetCount;inetC++)
    {
      Serial.print(inet[inetC]);
    }
    ini = false;
    
    
}

This compiles ok but whenever I run the code I get this

Setup
Beginning initGPRS()
AT+COPS?

AT+CREG?
AT+CSCA?

0.00
Latitude: 0.00
,,0

0.00
0 minutes left
1 minutes left
2 minutes left
Getting second GPS
GGA,003044.040,,,,,0,00,,,M,0.0,M,,0000*

0.00
,,0

0.00
Got second GPS
About to send text

087*******0.000.00Finished sending
Inet Debug:
0 minutes left
1 minutes left
2 minutes left

Most of this is not a problem (at the moment the GPS should return 0 and it does) it is just that sendMessage is not printing out anything to either the GPRS module or the screen, when I remove all the parts involving the GPS module it runs fine and memory is not an issue it's (10k out of 32k max)

I just don't know what's happening with this at all, does anyone have any ideas?

scrineym:
My problem is that the Arduino UNO is printing out data I did not ask it to print

The ATmega8u2 that handles the USB to Serial communication has a buffer. The extra characters you see are from the ATmega8u2. Keep in mind that each time you connect or disconnect to the Arduino (open/close the serial port) the ATmega328 is reset while the ATmega8u2 keeps doing whatever it was doing at that time. So it is normal to see characters from the previous reset or 1-2 corrupted characters still in the buffer.

memory is not an issue it's (10k out of 32k max)

No, you are mixing up the types of memory on the Uno/ATmega328. The 10k out of 32k is for FLASH memory, where code is stored. You only have 2k of RAM and when using big strings like you are doing can exhaust it very quickly.

If you are using 0021/0022 you should read the tutorial on PROGMEM. It allows you to keep strings in FLASH (the 32k memory space) and not consume RAM like your program is doing now.

If you use 1.0 all you need to do is wrap your strings around F():
Serial.println(F("This string stays in PROGMEM..."));

Hi James C4S

Thank you for your reply, I made the changes and put most of the strings into PROGMEM however now there is no output from the program not even the initial Serial.println("Setup"); in setup()

Could there be any other errors I have made in this code ?

I have plenty of experience programming but this is my first Arduino project, I have a lot to learn :stuck_out_tongue:

scrineym:
Could there be any other errors I have made in this code ?

This would be much easier to answer if you posted the code with the changes.

--UPDATE---

After changing ever string in the program to be in flash memory symbols are printing out.
Thank you so much for your help.