How to optimize Memory usage

Hi

I am having problems, because my sketch is simply too big. I am fully aware that I have not done anything to optimize my memory usage, so what are some general things I could do to reduce the size of the sketch?

//SD///////
#include <SPI.h>
#include <SD.h>

//TEMPERATURE N HUMIDITY//////////////
#include <SparkFunHTU21D.h>

//BMP180////////////////////////////////////////
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP085_U.h>
/////////////////////////// 

//GPS STUFF////////////////
#include <SoftwareSerial.h>
SoftwareSerial GPS(3, 5);
byte gps_set_sucess = 0 ; 
char gpssentence[66];
//////////////////////////

//BMP180//////////
Adafruit_BMP085_Unified bmp = Adafruit_BMP085_Unified(10085);
float pressure;
float inTemp;
///////////////////////

//Ozone//////////////
int OZval;
/////////////////////

//UV/////
float uvIntensity;
/////////

/////Temp +Hum///////
HTU21D myHumidity;
float humidity;
float temp;
////////////////////

//SD//////
const int chipSelect = 4;
/////////
void setup() {
   pinMode(A0, INPUT);
  
  //GPS STUF/////////////////////////
  GPS.begin(9600); 
  // START OUR SERIAL DEBUG PORT
  Serial.begin(9600);
  Serial.println("GPS Level Convertor Board Test Script");
  Serial.println("03/06/2012 2E0UPU");
  Serial.println("Initialising....");
  //
  // THE FOLLOWING COMMAND SWITCHES MODULE TO 4800 BAUD
  // THEN SWITCHES THE SOFTWARE SERIAL TO 4,800 BAUD
  //
  GPS.print("$PUBX,41,1,0007,0003,4800,0*13\r\n"); 
  GPS.begin(4800);
  GPS.flush();
 
  //  THIS COMMAND SETS FLIGHT MODE AND CONFIRMS IT 
  Serial.println("Setting uBlox nav mode: ");
  uint8_t setNav[] = {
    0xB5, 0x62, 0x06, 0x24, 0x24, 0x00, 0xFF, 0xFF, 0x06, 0x03, 0x00, 0x00, 0x00, 0x00, 0x10, 0x27, 0x00, 0x00, 
    0x05, 0x00, 0xFA, 0x00, 0xFA, 0x00, 0x64, 0x00, 0x2C, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0xDC };
  while(!gps_set_sucess)
  {
    sendUBX(setNav, sizeof(setNav)/sizeof(uint8_t));
    gps_set_sucess=getUBX_ACK(setNav);
  }
  gps_set_sucess=0;
 

GPS.println("$PUBX,40,GLL,0,0,0,0*5C");
GPS.println("$PUBX,40,GGA,0,0,0,0*5A");
GPS.println("$PUBX,40,GSA,0,0,0,0*4E");
GPS.println("$PUBX,40,RMC,0,0,0,0*47");
GPS.println("$PUBX,40,GSV,0,0,0,0*59");
GPS.println("$PUBX,40,VTG,0,0,0,0*5E");
////////////////////////////////////////////////////////////////////////////////////////////////////

//BMP180////////////////////
  if(!bmp.begin())
  {
    /* There was a problem detecting the BMP085 ... check your connections */
    Serial.print("Ooops, no BMP085 detected ... Check your wiring or I2C ADDR!");
    while(1);
  }
  ////////////////////////////////////

  //Temp + Humidity///////
  myHumidity.begin();
  ////////////////

  //SD////////
  Serial.print("Initializing SD card...");

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    return;
  }
  Serial.println("card initialized.");


}

void loop() {
  getgps();
  readsensors();
  logdata();
  senddata();
}


void getgps(){

   GPS.println("$PUBX,00*33");
   
   unsigned long previousMillis = millis();
   unsigned long currentMillis = millis(); 
  while (currentMillis - previousMillis <= 2000) {
    // save the last time you blinked the LED
     currentMillis = millis();
  }


  while (GPS.available())
{
    for (int i=0; i <66 ; i++)
    {
        gpssentence[i] = GPS.read();
    }
}
  
}
void readsensors(){
  getBarTemp();
  getOZ();
  getUV();
  getTempHum();
  
  
}

void logdata(){
  File dataFile = SD.open("theData.txt", FILE_WRITE);

  // if the file is available, write to it:
  if (dataFile) {
    for (int i=0; i <66 ; i++)
    {
        dataFile.print(gpssentence[i]);
    }
    dataFile.print(", pressure: ");
    dataFile.print(pressure);
    dataFile.print(", InTemp: ");
    dataFile.print(inTemp);
    dataFile.print(", OZ:");
    dataFile.print(OZval);
    dataFile.print(", UV:");
    dataFile.print(uvIntensity);
    dataFile.print(", outTemp:");
    dataFile.print(temp);
    dataFile.print(", Humidity:");
    dataFile.println(humidity); 
    dataFile.close();


for (int i=0; i <66 ; i++)
    {
        Serial.print(gpssentence[i]);
    }
    Serial.print(", pressure: ");
    Serial.print(pressure);
    Serial.print(", InTemp: ");
    Serial.print(inTemp);
    Serial.print(", OZ:");
    Serial.print(OZval);
    Serial.print(", UV:");
    Serial.print(uvIntensity);
    Serial.print(", outTemp:");
    Serial.print(temp);
    Serial.print(", Humidity:");
    Serial.println(humidity); 
    
   
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.println("error opening datalog.txt");
  }
  
  
}

void senddata(){
  
}


void getBarTemp(){
 /* Get a new sensor event */ 
  sensors_event_t event;
  bmp.getEvent(&event);

  if (event.pressure)
  {
    pressure = event.pressure;
   
    bmp.getTemperature(&inTemp);
  }
  else
  {
    Serial.println("Sensor error");
  }
}

void getOZ(){
  OZval = analogRead(1);
}

void getUV(){
  int uvLevel = averageAnalogRead(A0);
  
  float outputVoltage = uvLevel * (5.0 / 1023.0);
  uvIntensity = mapfloat(outputVoltage, 0.99, 2.8, 0.0, 15.0);
}

void getTempHum(){
  humidity = myHumidity.readHumidity();
  temp = myHumidity.readTemperature();
  
}









int averageAnalogRead(int pinToRead)
{
  byte numberOfReadings = 8;
  unsigned int runningValue = 0; 

  for(int x = 0 ; x < numberOfReadings ; x++)
    runningValue += analogRead(pinToRead);
  runningValue /= numberOfReadings;

  return(runningValue);  
}

//The Arduino Map function but for floats
//From: http://forum.arduino.cc/index.php?topic=3922.0
float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}


// Send a byte array of UBX protocol to the GPS
void sendUBX(uint8_t *MSG, uint8_t len) {
  for(int i=0; i<len; i++) {
    GPS.write(MSG[i]);
    Serial.print(MSG[i], HEX);
  }
  GPS.println();
}
 
 
// Calculate expected UBX ACK packet and parse UBX response from GPS
boolean getUBX_ACK(uint8_t *MSG) {
  uint8_t b;
  uint8_t ackByteID = 0;
  uint8_t ackPacket[10];
  unsigned long startTime = millis();
  Serial.print(" * Reading ACK response: ");
 
  // Construct the expected ACK packet    
  ackPacket[0] = 0xB5;  // header
  ackPacket[1] = 0x62;  // header
  ackPacket[2] = 0x05;  // class
  ackPacket[3] = 0x01;  // id
  ackPacket[4] = 0x02;  // length
  ackPacket[5] = 0x00;
  ackPacket[6] = MSG[2];  // ACK class
  ackPacket[7] = MSG[3];  // ACK id
  ackPacket[8] = 0;   // CK_A
  ackPacket[9] = 0;   // CK_B
 
  // Calculate the checksums
  for (uint8_t i=2; i<8; i++) {
    ackPacket[8] = ackPacket[8] + ackPacket[i];
    ackPacket[9] = ackPacket[9] + ackPacket[8];
  }
 
  while (1) {
 
    // Test for success
    if (ackByteID > 9) {
      // All packets in order!
      Serial.println(" (SUCCESS!)");
      return true;
    }
 
    // Timeout if no valid response in 3 seconds
    if (millis() - startTime > 3000) { 
      Serial.println(" (FAILED!)");
      return false;
    }
 
    // Make sure data is available to read
    if (GPS.available()) {
      b = GPS.read();
 
      // Check that bytes arrive in sequence as per expected ACK packet
      if (b == ackPacket[ackByteID]) { 
        ackByteID++;
        Serial.print(b, HEX);
      } 
      else {
        ackByteID = 0;  // Reset and look again, invalid order
      }
 
    }
  }
}

Try remove some parts of the code to see which one eats most of memory.

Do you need to use the software serial? You should be able to use all devices with one serial interface.

Are your concerns with program memory (Flash) or SRAM?

see Optimizing SRAM | Memories of an Arduino | Adafruit Learning System

From the original sketch
Sketch uses 20250 bytes (62%) of program storage space. Maximum is 32256 bytes.
Global variables use 1955 bytes (95%) of dynamic memory, leaving 93 bytes for local variables.
Maximum is 2048 bytes.
Low memory available, stability problems may occur.

just using the F( macro for the strings the memory usage dropped...
Sketch uses 20380 bytes (63%) of program storage space. Maximum is 32256 bytes.
Global variables use 1393 bytes (68%) of dynamic memory, leaving 655 bytes for local variables.
Maximum is 2048 bytes.

//SD///////
#include <SPI.h>
#include <SD.h>

//TEMPERATURE N HUMIDITY//////////////
#include <SparkFunHTU21D.h>

//BMP180////////////////////////////////////////
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP085_U.h>
/////////////////////////// 

//GPS STUFF////////////////
#include <SoftwareSerial.h>
SoftwareSerial GPS(3, 5);
byte gps_set_sucess = 0 ; 
char gpssentence[66];
//////////////////////////

//BMP180//////////
Adafruit_BMP085_Unified bmp = Adafruit_BMP085_Unified(10085);
float pressure;
float inTemp;
///////////////////////

//Ozone//////////////
int OZval;
/////////////////////

//UV/////
float uvIntensity;
/////////

/////Temp +Hum///////
HTU21D myHumidity;
float humidity;
float temp;
////////////////////

//SD//////
const int chipSelect = 4;
/////////
void setup() {
   pinMode(A0, INPUT);
  
  //GPS STUF/////////////////////////
  GPS.begin(9600); 
  // START OUR SERIAL DEBUG PORT
  Serial.begin(9600);
  Serial.println(F("GPS Level Convertor Board Test Script"));
  Serial.println(F("03/06/2012 2E0UPU"));
  Serial.println(F("Initialising...."));
  //
  // THE FOLLOWING COMMAND SWITCHES MODULE TO 4800 BAUD
  // THEN SWITCHES THE SOFTWARE SERIAL TO 4,800 BAUD
  //
  GPS.print(F("$PUBX,41,1,0007,0003,4800,0*13\r\n")); 
  GPS.begin(4800);
  GPS.flush();
 
  //  THIS COMMAND SETS FLIGHT MODE AND CONFIRMS IT 
  Serial.println(F("Setting uBlox nav mode: "));
  uint8_t setNav[] = {
    0xB5, 0x62, 0x06, 0x24, 0x24, 0x00, 0xFF, 0xFF, 0x06, 0x03, 0x00, 0x00, 0x00, 0x00, 0x10, 0x27, 0x00, 0x00, 
    0x05, 0x00, 0xFA, 0x00, 0xFA, 0x00, 0x64, 0x00, 0x2C, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0xDC };
  while(!gps_set_sucess)
  {
    sendUBX(setNav, sizeof(setNav)/sizeof(uint8_t));
    gps_set_sucess=getUBX_ACK(setNav);
  }
  gps_set_sucess=0;
 

GPS.println(F("$PUBX,40,GLL,0,0,0,0*5C"));
GPS.println(F("$PUBX,40,GGA,0,0,0,0*5A"));
GPS.println(F("$PUBX,40,GSA,0,0,0,0*4E"));
GPS.println(F("$PUBX,40,RMC,0,0,0,0*47"));
GPS.println(F("$PUBX,40,GSV,0,0,0,0*59"));
GPS.println(F("$PUBX,40,VTG,0,0,0,0*5E"));
////////////////////////////////////////////////////////////////////////////////////////////////////

//BMP180////////////////////
  if(!bmp.begin())
  {
    /* There was a problem detecting the BMP085 ... check your connections */
    Serial.print(F("Ooops, no BMP085 detected ... Check your wiring or I2C ADDR!"));
    while(1);
  }
  ////////////////////////////////////

  //Temp + Humidity///////
  myHumidity.begin();
  ////////////////

  //SD////////
  Serial.print(F("Initializing SD card..."));

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println(F("Card failed, or not present"));
    // don't do anything more:
    return;
  }
  Serial.println(F("card initialized."));


}

void loop() {
  getgps();
  readsensors();
  logdata();
  senddata();
}


void getgps(){

   GPS.println(F("$PUBX,00*33"));
   
   unsigned long previousMillis = millis();
   unsigned long currentMillis = millis(); 
  while (currentMillis - previousMillis <= 2000) {
    // save the last time you blinked the LED
     currentMillis = millis();
  }


  while (GPS.available())
{
    for (int i=0; i <66 ; i++)
    {
        gpssentence[i] = GPS.read();
    }
}
  
}
void readsensors(){
  getBarTemp();
  getOZ();
  getUV();
  getTempHum();
  
  
}

void logdata(){
  File dataFile = SD.open("theData.txt", FILE_WRITE);

  // if the file is available, write to it:
  if (dataFile) {
    for (int i=0; i <66 ; i++)
    {
        dataFile.print(gpssentence[i]);
    }
    dataFile.print(F(", pressure: "));
    dataFile.print(pressure);
    dataFile.print(F(", InTemp: "));
    dataFile.print(inTemp);
    dataFile.print(F(", OZ:"));
    dataFile.print(OZval);
    dataFile.print(F(", UV:"));
    dataFile.print(uvIntensity);
    dataFile.print(F(", outTemp:"));
    dataFile.print(temp);
    dataFile.print(F(", Humidity:"));
    dataFile.println(humidity); 
    dataFile.close();


for (int i=0; i <66 ; i++)
    {
        Serial.print(gpssentence[i]);
    }
    Serial.print(F(", pressure: "));
    Serial.print(pressure);
    Serial.print(F(", InTemp: "));
    Serial.print(inTemp);
    Serial.print(F(", OZ:"));
    Serial.print(OZval);
    Serial.print(F(", UV:"));
    Serial.print(uvIntensity);
    Serial.print(F(", outTemp:"));
    Serial.print(temp);
    Serial.print(F(", Humidity:"));
    Serial.println(humidity); 
    
   
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.println(F("error opening datalog.txt"));
  }
  
  
}

void senddata(){
  
}


void getBarTemp(){
 /* Get a new sensor event */ 
  sensors_event_t event;
  bmp.getEvent(&event);

  if (event.pressure)
  {
    pressure = event.pressure;
   
    bmp.getTemperature(&inTemp);
  }
  else
  {
    Serial.println(F("Sensor error"));
  }
}

void getOZ(){
  OZval = analogRead(1);
}

void getUV(){
  int uvLevel = averageAnalogRead(A0);
  
  float outputVoltage = uvLevel * (5.0 / 1023.0);
  uvIntensity = mapfloat(outputVoltage, 0.99, 2.8, 0.0, 15.0);
}

void getTempHum(){
  humidity = myHumidity.readHumidity();
  temp = myHumidity.readTemperature();
  
}









int averageAnalogRead(int pinToRead)
{
  byte numberOfReadings = 8;
  unsigned int runningValue = 0; 

  for(int x = 0 ; x < numberOfReadings ; x++)
    runningValue += analogRead(pinToRead);
  runningValue /= numberOfReadings;

  return(runningValue);  
}

//The Arduino Map function but for floats
//From: http://forum.arduino.cc/index.php?topic=3922.0
float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}


// Send a byte array of UBX protocol to the GPS
void sendUBX(uint8_t *MSG, uint8_t len) {
  for(int i=0; i<len; i++) {
    GPS.write(MSG[i]);
    Serial.print(MSG[i], HEX);
  }
  GPS.println();
}
 
 
// Calculate expected UBX ACK packet and parse UBX response from GPS
boolean getUBX_ACK(uint8_t *MSG) {
  uint8_t b;
  uint8_t ackByteID = 0;
  uint8_t ackPacket[10];
  unsigned long startTime = millis();
  Serial.print(F(" * Reading ACK response: "));
 
  // Construct the expected ACK packet    
  ackPacket[0] = 0xB5;  // header
  ackPacket[1] = 0x62;  // header
  ackPacket[2] = 0x05;  // class
  ackPacket[3] = 0x01;  // id
  ackPacket[4] = 0x02;  // length
  ackPacket[5] = 0x00;
  ackPacket[6] = MSG[2];  // ACK class
  ackPacket[7] = MSG[3];  // ACK id
  ackPacket[8] = 0;   // CK_A
  ackPacket[9] = 0;   // CK_B
 
  // Calculate the checksums
  for (uint8_t i=2; i<8; i++) {
    ackPacket[8] = ackPacket[8] + ackPacket[i];
    ackPacket[9] = ackPacket[9] + ackPacket[8];
  }
 
  while (1) {
 
    // Test for success
    if (ackByteID > 9) {
      // All packets in order!
      Serial.println(F(" (SUCCESS!)"));
      return true;
    }
 
    // Timeout if no valid response in 3 seconds
    if (millis() - startTime > 3000) { 
      Serial.println(F(" (FAILED!)"));
      return false;
    }
 
    // Make sure data is available to read
    if (GPS.available()) {
      b = GPS.read();
 
      // Check that bytes arrive in sequence as per expected ACK packet
      if (b == ackPacket[ackByteID]) { 
        ackByteID++;
        Serial.print(b, HEX);
      } 
      else {
        ackByteID = 0;  // Reset and look again, invalid order
      }
 
    }
  }
}

Thanks for the great answer, MarshaJ847 ! The solution I was looking for !

The link to adafruit is not working anymore, but can be found here:https://cdn-learn.adafruit.com/downloads/pdf/memories-of-an-arduino.pdf

Besides moving strings to PROGMEM consider minimizing strings to their essence.
This often saves 50% of the tekst.

some constructions can be done with less variables

   unsigned long previousMillis = millis();
   unsigned long currentMillis = millis(); 
  while (currentMillis - previousMillis <= 2000) {
    // save the last time you blinked the LED
     currentMillis = millis();
  }

==>

   unsigned long previousMillis = millis();
   while (millis() - previousMillis <= 2000);   // save the last time you blinked the LED

Use smallest possible variables reduces memory also a bit.

    for (int i=0; i <66 ; i++)
    {
        gpssentence[i] = GPS.read();
    }

==>

    for (uint8_t i=0; i <66 ; i++)
    {
        gpssentence[i] = GPS.read();
    }

updated, added code tags

Quote from: robtillart


---

Use smallest possible variables reduces memory also a bit.

for (int i=0; i <66 ; i++)
{
gpssentence = GPS.read();
** }**[/td][/tr][/table]:o

Oops, no code tags :frowning: updated my post to fix it.