Lcd anologread problem {{SOLVED}}

i have a lcd displaying and anolog read and it currently buggy. Some time the lcd starts reading gibberish. I'm a new comer so im kind lost here. Im using a uno with an sd shield,a bare lcd, and a RTC. Im assuming that there is a flaw in new code creating this issue. Any help would be greatly appreciated.

#include <LiquidCrystal.h>
LiquidCrystal lcd(4, 5, 6, 7, 8, 9);
int LDR = A0;                  //analog pin to which LDR is connected, here we set it to 0 so it means A0
int LDRValue = 0;             //that’s a variable to store LDR values
int light_sensitivity = 650;  //This is the approx value of light surrounding your LDR


#include <SdFat.h>
#include <SdFatUtil.h>  // define FreeRam()

#define SD_CHIP_SELECT  SS  // SD chip select pin
#define USE_DS1307       1  // set nonzero to use DS1307 RTC
#define LOG_INTERVAL  1000  // mills between entries
#define SENSOR_COUNT     1  // number of analog pins to log
#define ECHO_TO_SERIAL   1  // echo data to serial port if nonzero
#define WAIT_TO_START    0  // Wait for serial input in setup()
#define ADC_DELAY       10  // ADC delay for high impedence sensors

// file system object
SdFat sd;

// text file for logging
ofstream logfile;

// Serial print stream
ArduinoOutStream cout(Serial);

// buffer to format data - makes it eaiser to echo to Serial
char buf[80];
//------------------------------------------------------------------------------
#if SENSOR_COUNT > 6
#error SENSOR_COUNT too large
#endif  // SENSOR_COUNT
//------------------------------------------------------------------------------
// store error strings in flash to save RAM
#define error(s) sd.errorHalt_P(PSTR(s))
//------------------------------------------------------------------------------
#if USE_DS1307
// use RTClib from Adafruit
// https://github.com/adafruit/RTClib

// The Arduino IDE has a bug that causes Wire and RTClib to be loaded even
// if USE_DS1307 is false.


#include <Wire.h>
#include <RTClib.h>
RTC_DS1307 RTC;  // define the Real Time Clock object


//------------------------------------------------------------------------------
// call back for file timestamps
void dateTime(uint16_t* date, uint16_t* time) {
    DateTime now = RTC.now();

  // return date using FAT_DATE macro to format fields
  *date = FAT_DATE(now.year(), now.month(), now.day());

  // return time using FAT_TIME macro to format fields
  *time = FAT_TIME(now.hour(), now.minute(), now.second());
}
//------------------------------------------------------------------------------
// format date/time
ostream& operator << (ostream& os, DateTime& dt) {
  os << dt.year() << '/' << int(dt.month()) << '/' << int(dt.day()) << ',';
  os << int(dt.hour()) << ':' << setfill('0') << setw(2) << int(dt.minute());
  os << ':' << setw(2) << int(dt.second()) << setfill(' ');
  return os;
}
#endif  // USE_DS1307
//------------------------------------------------------------------------------
void setup() {
  {lcd.begin(16,2);
  lcd.clear();
  lcd.print("LDR");}
  
  pinMode(3, OUTPUT);
  Serial.begin(9600);
  while (!Serial){}  // wait for Leonardo
  
  // pstr stores strings in flash to save RAM
  cout << endl << pstr("FreeRam: ") << FreeRam() << endl;

#if WAIT_TO_START
  cout << pstr("Type any character to start\n");
  while (Serial.read() <= 0) {}
  delay(400);  // catch Due reset problem
#endif  // WAIT_TO_START

#if USE_DS1307
  // connect to RTC
  Wire.begin();
  if (!RTC.begin()) error("RTC failed");
  // set date time callback function
  SdFile::dateTimeCallback(dateTime);
  DateTime now = RTC.now();
  cout  << now << endl;

#endif  // USE_DS1307

  // initialize the SD card at SPI_HALF_SPEED to avoid bus errors with
  if (!sd.begin(SD_CHIP_SELECT, SPI_HALF_SPEED)) sd.initErrorHalt();

  // create a new file in root, the current working directory
  char name[] = "LOGGER00.CSV";

  for (uint8_t i = 0; i < 100; i++) {
    name[6] = i/10 + '0';
    name[7] = i%10 + '0';
    if (sd.exists(name)) continue;
    logfile.open(name);
    break;
  }
  if (!logfile.is_open()) error("file.open");

  cout << pstr("Logging to: ") << name << endl;
  cout << pstr("Type any character to stop\n\n");
  
  // format header in buffer
  obufstream bout(buf, sizeof(buf));

  bout << pstr("millis");

#if USE_DS1307
  bout << pstr(",date,time");
#endif  // USE_DS1307

  for (uint8_t i = 0; i < SENSOR_COUNT; i++) {
    bout << pstr(",sens") << int(i);
  }
  logfile << buf << endl;

#if ECHO_TO_SERIAL
  cout << buf << endl;
#endif  // ECHO_TO_SERIAL
}
//------------------------------------------------------------------------------
void loop() {

  {lcd.clear();
  lcd.setCursor(0,0);
  lcd.print(analogRead (A0));}
  delay(200);
  
  LDRValue = analogRead(LDR);          //reads the ldr’s value through LDR which we have set to Analog input 0 “A0?
    Serial.println(LDRValue);                  //prints the LDR values to serial monitor
 
    if (LDRValue > light_sensitivity) 
      {
  digitalWrite(3, HIGH);
  delay(180000); 
  digitalWrite(3, LOW);
  delay(1620000);
        }
    if (LDRValue < light_sensitivity) 
      {
  digitalWrite(3, LOW);
  delay(900000); 

        }
  
  uint32_t m;

  // wait for time to be a multiple of interval
  do {
    m = millis();
  } while (m % LOG_INTERVAL);

  // use buffer stream to format line
  obufstream bout(buf, sizeof(buf));

  // start with time in millis
  bout << m;

#if USE_DS1307
  DateTime now = RTC.now();
  bout << ',' << now;
#endif  // USE_DS1307

  // read analog pins and format data
  for (uint8_t ia = 0; ia < SENSOR_COUNT; ia++) {
#if ADC_DELAY
    analogRead(ia);
    delay(ADC_DELAY);
#endif  // ADC_DELAY
    bout << ',' << analogRead(ia);
  }
  bout << endl;

  // log data and flush to SD
  logfile << buf << flush;

  // check for error
  if (!logfile) error("write data failed");

#if ECHO_TO_SERIAL
  cout << buf;
#endif  // ECHO_TO_SERIAL

  // don't log two points in the same millis
  if (m == millis()) delay(1);
  
  if (!Serial.available()) return;
  logfile.close();
  cout << pstr("Done!");
  while (1);



}
  {lcd.clear();
  lcd.setCursor(0,0);
  lcd.print(analogRead (A0));}

Whatarethecurlybracesfor? Is your space key broken?

Does the strange behavior occur in a SIMPLE sketch?

i added them to see if it would fix the problem

no it doesn't

Does the strange behavior occur in a SIMPLE sketch?

Well, does it?

PaulS:

Does the strange behavior occur in a SIMPLE sketch?

Well, does it?

No it works fine

No it works fine

So, we've ruled out hardware issues. The LCD works. The analogRead() of the sensor works.

The next thing to check is how much memory you are using.
playground.arduino.cc/Code/AvailableMemory

My sketch is 24kb and since I upgraded to a mega, because I need more pins :smiley:

OK still getting the problem i'm thinking it could be hardware, several different sketches latter and i'm intermittently getting the problem still. Instead of gibberish the screen goes blank. It always seems to happen after the lcd prints and the relay turns on. Could be my code I'm not gonna lie its sloppy, and and bunch of different stuff hacked together, but still I'm getting frustrated.

Here's my latest code.

#include <LiquidCrystal.h>
LiquidCrystal lcd(4, 5, 6, 7, 8, 9);


// degree fahrenheit
byte newChar[8]= {
        B01100,
        B10010,
        B10010,
        B01100,
        B00000,
        B00000,
        B00000,
        B00000
};


#include <SD.h>
#include <Wire.h>
#include "RTClib.h"
#include "DHT.h"

/* 
 A simple data logger for the Arduino analog pins.  This one is simplifed by taking away the 
 calculation that determined file flush interval.  Since the readings are far enought apart,
 the file is flushed for every reading.
 */

#define ECHO_TO_SERIAL 1 // echo data to serial port

// The analog pins that connect to the sensors
#define PHOTOCELLPIN A0           // analog 0
#define chipSelect 53            // for the data logging shield, we use digital pin 10 for the SD cs line

#define DHTTYPE DHT11            // DHT 11  
#define DHTPIN_outside 12
#define DHTPIN_attic 11
#define DHTPIN 2  // The DHT output is connected to digital pin 7.
DHT dht(DHTPIN, DHTTYPE); //define the DHT object
DHT dht_attic(DHTPIN_attic, DHTTYPE);
DHT dht_outside(DHTPIN_outside, DHTTYPE);

//------------------------------

const int relay =  13;      // the number of the LED pin

int swState =0;
// Variables will change:
int relayState = HIGH;             // ledState used to set the LED
long previousMillis = 0;        // will store last time LED was updated

// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long interval = 210000; 




//------------------------------

RTC_DS1307 RTC; // define the Real Time Clock object

File fileData;                          // the logging file on the SD card
unsigned long ulintMillis = 0;              // milliseconds since start
int Relay = 3;

int intPhotocellreading = 0;
int light_sensitivity = 850;
int humidity_sensitivity = 49;
float atticHumidity = 0;
float atticTemp = 0;
float outsideHumidity = 0;
float outsideTemp = 0;
float fHumidity = 0;
float fTemp = 0;

const unsigned long ulintLoginterval = 10000;       // mills between entries (reduce to take more/faster data)



void error(char *str)
{
  Serial.print("error: ");
  Serial.println(str);
        
}


void setup()
{
  pinMode(Relay, OUTPUT);  //Relay 
  
  Serial.begin(9600);
  //Serial.println();
  Serial.println("Millis, Date , Time , Light , Humidity , Roof Temp, Humidity Attic , Attic Temp,Outside Humidity,Outside Temp");
  
lcd.createChar(1, newChar);
lcd.begin(16,2);
lcd.clear();
lcd.setCursor(6,0);
lcd.print("TEMP");
lcd.setCursor(4,1);
lcd.print("HUMIDITY");
  pinMode(DHTPIN, INPUT);
  pinMode(PHOTOCELLPIN, INPUT);

  // make sure that the default chip select pin is set to
  // output, even if you don't use it:
  pinMode(chipSelect, OUTPUT);

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


  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    error("Card failed, or not present, or datalog.csv file not present");
  }
  //Serial.println("card initialized.");


  

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  fileData = SD.open("datalog.csv", FILE_WRITE);



  // connect to RTC
  Wire.begin();  
  if (!RTC.begin()) {
    fileData.println("RTC failed");
#if ECHO_TO_SERIAL
    error ("RTC failed");
#endif  //ECHO_TO_SERIAL
  }

  dht.begin();    // Start reading from the  temperature and humidity sensor

  if (fileData){
    fileData.println("Millis , Date , Time, Light, Roof Humidity ,Roof Temp, Attic Humidity,Attic Temp,Outside Humidity,Outside Temp");
  }
  else{
    error("Could not write to file.");
  }

}

void loop(void)
{
  DateTime now; 

  // delay for the amount of time we want between readings
  delay((ulintLoginterval -1) - (millis() % ulintLoginterval));



  // log milliseconds since starting
  ulintMillis = millis();
  fileData.print(ulintMillis);           // milliseconds since start
  fileData.print(", ");

#if ECHO_TO_SERIAL
  Serial.print(ulintMillis);         // milliseconds since start
  Serial.print(", ");  
#endif

  // fetch the time
  now = RTC.now();
  // log time
  fileData.print(now.year(), DEC);
  fileData.print("/");
  fileData.print(now.month(), DEC);
  fileData.print("/");
  fileData.print(now.day(), DEC);
  fileData.print(",");
  fileData.print(now.hour(), DEC);
  fileData.print(":");
  fileData.print(now.minute(), DEC);
  fileData.print(":");
  fileData.print(now.second(), DEC);

#if ECHO_TO_SERIAL
  Serial.print(now.year(), DEC);
  Serial.print("/");
  Serial.print(now.month(), DEC);
  Serial.print("/");
  Serial.print(now.day(), DEC);
  Serial.print(",");
  Serial.print(now.hour(), DEC);
  Serial.print(":");
  Serial.print(now.minute(), DEC);
  Serial.print(":");
  Serial.print(now.second(), DEC);
#endif //ECHO_TO_SERIAL

  intPhotocellreading = analogRead(PHOTOCELLPIN);  

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  fHumidity = dht.readHumidity();
  fTemp = dht.readTemperature(true);
  atticHumidity = dht_attic.readHumidity();
  atticTemp = dht_attic.readTemperature(true);
  outsideHumidity = dht_outside.readHumidity();
  outsideTemp = dht_outside.readTemperature(true);

  // check if returns are valid, if they are NaN (not a number) then something went wrong!
  if (isnan(fHumidity) || isnan(fTemp)) {
    Serial.println("Failed to read from DHT");
  }

  fileData.print(", ");    
  fileData.print(intPhotocellreading);

#if ECHO_TO_SERIAL
  Serial.print(", ");   
  Serial.print(intPhotocellreading);      //
#endif //ECHO_TO_SERIAL

  fileData.print(", ");    
  fileData.print(fHumidity);

#if ECHO_TO_SERIAL
  Serial.print(", ");   
  Serial.print(fHumidity);
#endif //ECHO_TO_SERIAL

  fileData.print(", ");    
  fileData.print(fTemp);

#if ECHO_TO_SERIAL
  Serial.print(", ");   
  Serial.print(fTemp);
#endif //ECHO_TO_SERIAL

//------------------------------------------temp 2

  fileData.print(", ");    
  fileData.print(atticHumidity);

#if ECHO_TO_SERIAL
  Serial.print(", ");   
  Serial.print(atticHumidity);
#endif //ECHO_TO_SERIAL

  fileData.print(", ");    
  fileData.print(atticTemp);

#if ECHO_TO_SERIAL
  Serial.print(", ");   
  Serial.print(atticTemp);
#endif //ECHO_TO_SERIAL

//---------------------------------------

  fileData.print(", ");    
  fileData.print(outsideHumidity);

#if ECHO_TO_SERIAL
  Serial.print(", ");   
  Serial.print(outsideHumidity);
#endif //ECHO_TO_SERIAL

  fileData.print(", ");    
  fileData.print(outsideTemp);

#if ECHO_TO_SERIAL
  Serial.print(", ");   
  Serial.print(outsideTemp);
#endif //ECHO_TO_SERIAL
//-----------------------------------------
fileData.println();

#if ECHO_TO_SERIAL
  Serial.println();
#endif // ECHO_TO_SERIAL

lcd.clear();
lcd.setCursor(0,0);
lcd.print("R ");
lcd.print(fTemp);
lcd.write(1);
lcd.setCursor(0,1);
lcd.print("R ");
lcd.print(fHumidity);
lcd.print("%");
lcd.setCursor(9,0);
lcd.print ("O ");
lcd.print(outsideTemp);
lcd.setCursor(9,1);
lcd.print("A ");
lcd.print(atticTemp);





 
   if ((intPhotocellreading > light_sensitivity)&&(fHumidity < humidity_sensitivity))
     {
  digitalWrite(Relay, relayState);
     }

  unsigned long currentMillis = millis();
 
  if(currentMillis - previousMillis > interval) {
    // save the last time you blinked the LED 
    previousMillis = currentMillis;   
    interval = 2160000 - interval;
    // if the LED is off turn it on and vice-versa:
    if (relayState == LOW)
      relayState = HIGH;
    else
      relayState = LOW;

     if(swState == LOW){
    digitalWrite(relay, LOW);
  }
  }

  fileData.flush();
}

It always seems to happen after the lcd prints and the relay turns on.

If the problem occurs only after toggling the relay on, then it is almost certainly a hardware issue. You may need decoupling caps and/or diodes across the relay poles. Noise is not a good thing around the Arduino.

Here is how i have the relay wired up. What should i add to make this better.

BAD LCD tried a different one no problem.

After swapping the LCD it was fine until i made more modification. Then the same problem occurred. I finally realized the problem was noise. I had my LCD data lines running parallel with some 24 VAC power line. :roll_eyes:

I had my LCD data lines running parallel with some 24 VAC power line.

That will do it.