Hi,
Im new in the arduino world, and i have to make a program that print the hour in the Serial monitor and alternate some leds. To make that i have used the timer2 using MsTimer2.
The problem becames when i have to put arduino to sleep if it recives an invalid hour from the Serial, and it's supposed to stop printing on the serial monitor, and keep updating the time using the timer2 interruptions.
Im ussing the library avr/sleep.h and using the SLEEP_MODE_EXT_STANDBY, testing using the standby mode i discovered that in that mode dont print in serial, but I asked to my teacher if its okay and say no.
if someone could help me I would be very grateful I am very stuck.
I let you the code (dont judge im newin this world)
#include<MsTimer2.h>
#include <avr/sleep.h>
volatile bool led;
volatile bool sleep;
const int greenLed = 5;
const int redLed = 10;
const int btnPin = 3;
volatile int second = 0;
volatile int minute = 0;
volatile int hour = 0;
int th;
int tm;
int ts;
volatile bool tup;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(greenLed, OUTPUT);
pinMode(redLed, OUTPUT);
pinMode(btnPin, INPUT);
set_sleep_mode(SLEEP_MODE_STANDBY);
MsTimer2::set(1000,changeTime);
MsTimer2::start();
Serial.println("Clock Started");
}
void loop() {
if(sleep){
sleepNow();
}else{
if(Serial.available() > 0){
th = Serial.parseInt();
tm = Serial.parseInt();
ts = Serial.parseInt();
tup = true;
while (Serial.available()) Serial.read();
}
}
}
void changeTime(){
updateTime();
if(led){ digitalWrite(greenLed,LOW); digitalWrite(redLed,HIGH); }
else{ digitalWrite(redLed,LOW); digitalWrite(greenLed,HIGH);}
led = !led;
printHour();
}
void updateTime(){
if(tup){
updateValues();
}
second++;
if(second>59){
second = 0;
minute++;
}
if(minute>59){
minute = 0;
hour++;
}
if(hour>23){
hour= 0;
}
}
void updateValues(){
if(th > 23 || tm > 59 || ts > 59){
th=0, tm=0, ts=0;
tup = false;
Serial.print("Entering sleep mode\n");
Serial.flush();
sleepNow();
}else{
hour = th;
minute = tm;
second = ts;
th = 0,tm=0,ts=0;
tup = false;
}
}
void wakeUp(){
sleep = false;
detachInterrupt(digitalPinToInterrupt(btnPin));
}
void sleepNow() {
digitalWrite(greenLed,LOW);
digitalWrite(redLed,LOW);
sleep = true;
cli();
sleep_enable();
attachInterrupt(digitalPinToInterrupt(btnPin),wakeUp,FALLING);
sei();
sleep_cpu();
sleep_disable();
}
void printHour(){
Serial.print(hour);
Serial.print(":");
Serial.print(minute);
Serial.print(":");
Serial.print(second);
Serial.print("\n");
Serial.flush();
}