Arduino Uno | Hardware Bug? | Compiles OK

Hello!

Im experiencing a wierd bug. Basically, i have a code that compiles and works properly, but, if I introduce in some functions "if", "for" or "while", compiles fine, but arduino freezes...

The function below analyzes RGB values stored in Colorsensor[] variable, (there are two RGB values sets), and prints a percentage of how far away values are from values stored in ColorEnd[]. This part works fine, and compiles fine, but if I include the code that is commented, which it is a simple "if", program compiles but arduino crashes, i mean, it crashes even function has not been called.

This function is called from a menu on an lcd screen, so it has no sense that it affects the whole program when it is even not executed...

Any ideas? Could be an error of the compilator, writting code in wrong place? Anyone with a similar experience?

Thank you in advance

void checkproximity(){
 int resta[6];
 int porcentaje[6];

for (int i=0;i<6;i++){
	resta[i]=(ColorEnd[i] - ColorSensor[i]);
	resta[i]=abs(resta[i]);
	
	porcentaje[i]=(resta[i]*100/255);
	
/*	if (porcentaje[i]<threshold){
	UnderThresold[i] = 1;
	}*/
	
		
	Serial.print(ColorEnd[i]);
	Serial.print("       ");
	Serial.print(ColorSensor[i]);
	Serial.print("       ");
	Serial.print(resta[i]);
	Serial.print("       ");
	Serial.print(porcentaje[i]);
	Serial.println(" %");

}


}

It's hard to tell without seeing the complete sketch, but my guess is that you are running out of RAM. One way to reduce RAM usage is to move string literals used in print statements into program memory. To do this:

  1. Add the following code you your sketch:
#include <avr/pgmspace.h>

void print_P(Print& device, const PROGMEM char* s)
{
  for (size_t i = 0; i < strlen_P(s); ++i)
  {
    device.print(pgm_read_byte_near(s + i));
  }
}

void println_P(Print& device, const PROGMEM char* s)
{
  print_P(device, s);
  device.println();
}
  1. Instead of e.g. "Serial.print("some string")" use "print_P(Serial, PSTR("some string"))". Similarly for println. The effect is that the text "some string" no longer takes up RAM.

Hello dc42:

Thank you very much for your answer. Even without taking a look to the whole sketch, you solved my problem! Great!

As you said, it is a lack of RAM. I have been reading around and it seems that Serial, newsoftserial, lcd,... all these libraries stores the chars in the RAM instead than in flash...

With your code, of also with the Flash.h library, problem has gone away!

Thank you again!

Glad I was able to help. It's a real nuisance that the Print class doesn't already provide methods to print strings stored in program memory. I hope this is added in the Arduino 1.0 software release.