UNO - Program compiled, uploaded, but not running

Hi everyone!

//Background
I’m doing a new project - sunrise alarm clock. It’s an early version not including all hardware it suppose to have.
I’m in the middle of developing a program - all basic functions are already coded, some will be coded (LEDs disabling after some time). I decided, it’s a time for first check with simple hardware analogs of my target setup - plain red LED’s instead of MOSFET driven LED modules, serial USB terminal instead of 7-segment modules display, but RTC on it’s place.

//Actual problem
Compiling and uploading a sketch into my UNO clone is fine. It reports 5734 bytes (17%) of flash used, and 431 bytes (21%) of SRAM used by global variables.
Although, the sketch is not running. And I don’t even need to bother about theoretical problems with my functions, buttons debouncing or any other stuff, because even the code in setup function is not being executed. I get nothing in terminal (baud rate configured, example sketches using serial work fine). Builtin LED doesn’t perform 3 blinks (it blinks like it used to when restarted, but not the programmed-3-blinks-800ms-delay-way). Everything seems to be working when using other sketches, so it has to be a programming problem.

I tried to eliminate any memory waste - this version does not include LiquidCrystal_I2C library, every variable that can be local - has been made local, every printed string is wrapped in F(). I still have no idea what other problem can it be besides full SRAM. Maybe mistake is very simple, but I can’t see it.

// RTClib - Version: 1.2.0
#include <RTClib.h>

// Wire - Version: Latest 
#include <Wire.h>

//pins
#define ABUTTON 4
#define LBUTTON 5
#define ASWITCH 6
#define LSWITCH 7
#define WARMLIGHT 9
#define COLDLIGHT 10

RTC_DS1307 rtc;
DateTime now = rtc.now();

const byte alarmTimeSet[2] = {6, 0};
byte sunriseTime[2];
const byte sunriseTimeAdvance = 20;
bool sunriseActive = false;
bool prevactivated = false;
const byte warmLEDboundaries[2] = {25, 255};
const byte coldLEDboundaries[2] = {25, 200};
int warmStep, coldStep;
byte currentWarm = 0;
byte currentCold = 0;
byte lampStatus = 0;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW); //initialization LED blinking
  delay(800);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(800);
  digitalWrite(LED_BUILTIN, LOW);
  delay(800);
  digitalWrite(LED_BUILTIN, HIGH);
  Serial.begin(9600);
    while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.println("Hello, World");

  pinMode(ABUTTON, INPUT_PULLUP);
  pinMode(LBUTTON, INPUT_PULLUP);
  pinMode(ASWITCH, INPUT_PULLUP);
  pinMode(LSWITCH, INPUT_PULLUP);
  pinMode(WARMLIGHT, OUTPUT);
  pinMode(COLDLIGHT, OUTPUT);
  
  if (! rtc.begin()) {
    Serial.println(F("Couldn't find RTC"));
    while (1);
  }

  if (! rtc.isrunning()) {
    Serial.println(F("RTC is NOT running!"));
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }
  
  if(calculateSunriseTime() == true){
    Serial.print(F("Calculated sunrise time start: "));
    Serial.print(sunriseTime[0]);
    Serial.print(F(":"));
    Serial.println(sunriseTime[1]);
  }
  else{
    Serial.println(F("ERROR: Sunrise time start in previous day than its finish"));
  }
  
  calculateSunriseParameters();
}


void loop() {
  if(aktualizujWyswietlacz() == true){
//    if(alarmTrigger() == true && digitalRead(ASWITCH) == HIGH){
//      alarmActive = true;
//    }
    if(sunriseTrigger() == true && digitalRead(ASWITCH) == HIGH){
      sunriseActive = true;
    }
  }
  
  if(digitalRead(ABUTTON) == LOW && digitalRead(ASWITCH) == HIGH){
    sunriseActive = false;
//    alarmActive = false;
  }
}

bool calculateSunriseTime(){
  int sunriseMinOfDay = (alarmTimeSet[0] * 60 + alarmTimeSet[1]) - sunriseTimeAdvance;
  if(sunriseMinOfDay < 0){
    return false; //error
  }
  else{
    sunriseTime[1] = sunriseMinOfDay % 60;
    sunriseTime[0] = (sunriseMinOfDay - sunriseTime[1])/60;
    return true;
  }
}

void calculateSunriseParameters(){
  warmStep = sunriseTimeAdvance * 36 / (warmLEDboundaries[1]-warmLEDboundaries[0]); 
  coldStep = sunriseTimeAdvance * 24 / (coldLEDboundaries[1]-coldLEDboundaries[0]);
  Serial.print(F("Calculated time step [warm/cold][s]: "));
  Serial.print(warmStep);
  Serial.print(F(":"));
  Serial.println(coldStep);
}

bool aktualizujWyswietlacz(){ //actualise display
  byte prevmin;
  byte aktmin = now.minute();
  if(prevmin != aktmin){
    int czas = (now.hour() * 100) + aktmin; // czas(PL) = time(EN)
    Serial.println(czas);
    prevmin = aktmin;
    return true;
  }
  else{
    return false;
  }
}


bool sunriseTrigger(){
  byte dzisiaj = now.dayOfTheWeek();  //dzisiaj(PL) = today(EN)
  const bool alarmDayOfWeekSet[7] = {0,1,1,1,1,1,0}; //nastawienie alarmu w kolejne dni tygodnia liczac od niedzieli (1-wl, 0-wyl)
  unsigned long prevAlarmLaunchTimestamp = 0;
  if(alarmDayOfWeekSet[dzisiaj] == 1 &&
      sunriseTime[0] == now.hour() &&
      sunriseTime[1] == now.minute() && 
      now.unixtime() > (prevAlarmLaunchTimestamp + 60)){
    prevAlarmLaunchTimestamp = now.unixtime();
    return true;
  }
  else{
  return false;
  }
}

bool sunriseProcedure(bool activated){  //procedure returns true when finished
  unsigned long sunriseLastStep = 0;
  if(activated == false){
    prevactivated = activated; //false
    return false;
  }
    if(activated == true && prevactivated == false){  //initialisation
    prevactivated = activated;  //true
    sunriseLastStep = millis();
    byte currentWarm = warmLEDboundaries[0];
    byte currentCold = 0;
    analogWrite(WARMLIGHT,currentWarm);
    return false;
  }
  if(activated == true && prevactivated == true && currentWarm < warmLEDboundaries[1] &&
  (millis() - sunriseLastStep) > warmStep){  //warm LED brightening
    currentWarm++;
    analogWrite(WARMLIGHT,currentWarm);
    sunriseLastStep = millis();
    return false;
  }
  if(activated == true && prevactivated == true && currentWarm == warmLEDboundaries[1] &&
  (millis() - sunriseLastStep) > warmStep && currentCold == 0){  //cold LED brightening initialisation
    currentCold = coldLEDboundaries[0];
    analogWrite(COLDLIGHT,currentCold);
    sunriseLastStep = millis();
    return false;
  }
  if(activated == true && prevactivated == true && currentCold < coldLEDboundaries[1] &&
  (millis() - sunriseLastStep) > coldStep && currentCold > 0){  //cold LED brightening
    currentCold++;
    analogWrite(COLDLIGHT,currentCold);
    sunriseLastStep = millis();
    return false;
  } 
  if(activated == true && prevactivated == true && currentCold == coldLEDboundaries[1]){  //brightening finished
    return true;
  } 
  else{
    Serial.println(F("Sunrise procedure error. Unexpected set of values:"));
    Serial.print(F("activated: "));
    Serial.println(activated);
    Serial.print(F("prevactivated: "));
    Serial.println(prevactivated);
    Serial.print(F("currentWarm: "));
    Serial.println(currentWarm);
    Serial.print(F("currentCold: "));
    Serial.println(currentCold);
  }
}

void toggleLamp(){
  const int lampToggleTimeThr = 3000;
  const byte lampPower[6][2] = {{0,0},
                             {50,0},
                             {255,0},
                             {0,100},
                             {0,255},
                             {255,255}};
  unsigned long prevLampToggle;
  if((millis() - prevLampToggle) > lampToggleTimeThr && lampStatus > 0){
    lampStatus = 0;
  }
  if(lampStatus = 0){
    lampStatus++;
    prevLampToggle = millis();
  }
  if((millis() - prevLampToggle) < lampToggleTimeThr && lampStatus > 0 && lampStatus < 5){
    lampStatus++;
    prevLampToggle = millis();
  }
  if((millis() - prevLampToggle) < lampToggleTimeThr && lampStatus > 0 && lampStatus >= 5){
    lampStatus = 0;
  }
  else{
    Serial.println(F("Toggle lamp function error. Conditions not met."));
    return;
  }
  analogWrite(WARMLIGHT,lampPower[lampStatus][0]);
  analogWrite(COLDLIGHT,lampPower[lampStatus][1]);
  return;
}

What happens if you move this line:

DateTime now = rtc.now();

to setup()?

Your program is likely running, it's just not doing what you expected it to do.

lefstin:
What happens if you move this line:

DateTime now = rtc.now();

to setup()?

It causes compilation error “‘now’ was not declared in this scope”. Now has to be declared globally.

ChrisTenone:
Your program is likely running, it’s just not doing what you expected it to do.

In the beginning (first lines of setup) I expect it to blink the LED and print message to serial monitor. Neither is working.

MasterYoda95:
It causes compilation error "'now' was not declared in this scope". Now has to be declared globally.

Then leave the definition global, move the initialization to setup, after rtc.begin().

Whandall:
Then leave the definition global, move the initialization to setup, after rtc.begin().

But I did it in the way leftsin told me: just moved this line to setup

DateTime now = rtc.now();

leaving

RTC_DS1307 rtc;

definition global.
Any other ideas?
Do you think it may be memory problem? It looks like that, by at this point, when I optimised code and limited libraries usage to neccesary minimum, it's much less probable than I thought in the beginning, when I dealt with a larger code.

Put serial begin a bit higher up and add a few print statements here and there to help find where the program is
“ starting up”
“ setup complete”

Whandall:
Then leave the definition global, move the initialization to setup, after rtc.begin().

MasterYoda95:
But I did it in the way leftsin told me: just moved this line to setup

DateTime now = rtc.now();

leaving

RTC_DS1307 rtc;

definition global.
Any other ideas?
Do you think it may be memory problem? It looks like that, by at this point, when I optimised code and limited libraries usage to neccesary minimum, it’s much less probable than I thought in the beginning, when I dealt with a larger code.

I think that what was meant was

// RTClib - Version: 1.2.0
#include <RTClib.h>

.....

RTC_DS1307 rtc;
DateTime now;
.....

void setup() {
  ....

  if (! rtc.begin()) {
    Serial.println(F("Couldn't find RTC"));
    while (1);
  }

  now = rtc.now();

  ......
}

I tried to compile your program. Once I replaced dayOfTheWeek with dayOfWeek it compiles - different library versions perhaps. There are a number of warnings that look important but I ignored them for now.

I moved the serial begin and initial print to the top of setup & got them working after I commented out the initialization of now.

I have no RTC attached to my uno and the program hangs when I call rtc.now(), which appears to be your symptom too. I'd suggest checking the wiring for your clock.

darrob:
I think that what was meant was

// RTClib - Version: 1.2.0

#include <RTClib.h>

RTC_DS1307 rtc;
DateTime now;

void setup() {

if (! rtc.begin()) {
Serial.println(F(“Couldn’t find RTC”));
while (1);
}

now = rtc.now();


}

Dude, works like a charm!


Thank You all very much!

As pointed out by wildbill, your code does have a couple of mistakes.

C:\Users\sterretje\AppData\Local\Temp\untitled363953553.tmp\sketch_sep19a\sketch_sep19a.ino: In function 'aktualizujWyswietlacz()':

C:\Users\sterretje\AppData\Local\Temp\untitled363953553.tmp\sketch_sep19a\sketch_sep19a.ino:121:3: warning: 'prevmin' is used uninitialized in this function [-Wuninitialized]

   if (prevmin != aktmin) {

   ^

C:\Users\sterretje\AppData\Local\Temp\untitled363953553.tmp\sketch_sep19a\sketch_sep19a.ino: In function 'toggleLamp()':

C:\Users\sterretje\AppData\Local\Temp\untitled363953553.tmp\sketch_sep19a\sketch_sep19a.ino:210:17: warning: 'prevLampToggle' is used uninitialized in this function [-Wuninitialized]

   if ((millis() - prevLampToggle) > lampToggleTimeThr && lampStatus > 0) {

                 ^

prevmin and prevLampToggle should be declared as static.

C:\Users\sterretje\AppData\Local\Temp\untitled363953553.tmp\sketch_sep19a\sketch_sep19a.ino: In function 'void toggleLamp()':

C:\Users\sterretje\AppData\Local\Temp\untitled363953553.tmp\sketch_sep19a\sketch_sep19a.ino:213:21: warning: suggest parentheses around assignment used as truth value [-Wparentheses]

   if (lampStatus = 0) {

                     ^

Mistake should be obvious :wink:

C:\Users\sterretje\AppData\Local\Temp\untitled363953553.tmp\sketch_sep19a\sketch_sep19a.ino: In function 'bool sunriseProcedure(bool)':

C:\Users\sterretje\AppData\Local\Temp\untitled363953553.tmp\sketch_sep19a\sketch_sep19a.ino:198:1: warning: control reaches end of non-void function [-Wreturn-type]

 }

 ^

Might result in unexpected behaviour (not the one that was your problem).

Oh, problem was calling now() before begin().

Now that's solved, I'd suggest you turn up the warning level in the IDE. Some of the warnings are just annoying, but there are a number that you should address, e.g. this one:

test.ino:215:21: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
   if (lampStatus = 0) {

sterretje was faster on the keys :slight_smile:

wildbill:
Oh, problem was calling now() before begin().

Now that's solved, I'd suggest you turn up the warning level in the IDE. Some of the warnings are just annoying, but there are a number that you should address, e.g. this one:

test.ino:215:21: warning: suggest parentheses around assignment used as truth value [-Wparentheses]

if (lampStatus = 0) {



sterretje was faster on the keys :)

I haven't been aware of this option in IDE. I turned on detailed output, and didn't get any warnings. Now I can see it.
It will reduce chances that I'll be asking more questions on forum during further code development and save Arduino's precious servers space :smiley:

@OP

With reference to the following excerpt taken from the RTClib.CPP file of RTClib.h library, I would like to make few remarks on your original sketch.
rtclibcpp.png

1. now() method returns the whole structure via an user defined variable (say, nowTime) of type DateTime which has been declared in the RTClib.h file. So, the rational declaration should be:

DateTime nowTime = rtc.now();

and not DateTime now = rtc.now();; where, now and now() may appear illiterate though they might work.

2. DatetTime nowTime = rtc.now(); is an executable code; can we perform it in the global space? I think that (it is seen true in my case and also in your case) this is the reason for which the setup() function is not being executed.

3. I would suggest to remove the method (now()) from the global space and invoke it whenever you need it, and it is like --

bool aktualizujWyswietlacz() 
{ //actualise display
  DateTime nowTime = rtc.now();
  byte prevmin;
  byte aktmin = nowTime.minute();
  if (prevmin != aktmin) {
    int czas = (nowTime.hour() * 100) + aktmin; // czas(PL) = time(EN)
    Serial.println(czas);
    prevmin = aktmin;
    return true;
  }
  else {
    return false;
  }
}

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

bool sunriseTrigger() 
{
  DateTime nowTime = rtc.now();
  byte dzisiaj = nowTime.dayOfTheWeek();  //dzisiaj(PL) = today(EN)
  const bool alarmDayOfWeekSet[7] = {0, 1, 1, 1, 1, 1, 0}; //nastawienie alarmu w kolejne dni tygodnia liczac od niedzieli (1-wl, 0-wyl)
  unsigned long prevAlarmLaunchTimestamp = 0;
  if (alarmDayOfWeekSet[dzisiaj] == 1 &&
      sunriseTime[0] == nowTime.hour() &&
      sunriseTime[1] == nowTime.minute() &&
      nowTime.unixtime() > (prevAlarmLaunchTimestamp + 60)) {
    prevAlarmLaunchTimestamp = nowTime.unixtime();
    return true;
  }
  else {
    return false;
  }
}

rtclibcpp.png

@GolamMostafa
I realised the neccesity of point 3. application after I've seen that the clock isn't updating - i just put the DateTime now = rtc.now(); in the very beginning of loop. Now, any functions called later use updated time values.

Ad 1 I was confused by the number of "now(s)" in code, but I'm not experienced C programmer, so I just copy-pasted initialization method from library's example. It works with simple now instead of (sticking to your example) nowTime, but now I see, it's more rational to change it like you suggested.

Ad 2 And this looks like good explanation why my program couldn't start properly.

Thank you for additional tips and explanation!