I am building a timer circuit using Arduino Pro Mini Atmega168p 5v 16MHz (which later supposed to be become to adjustable one).
Here is the current breadboard view.
(I am supposed to use SS relay at place of that green thing. I am not sure if that item is correct SS relay in Fritzing)
Here is the program code I wrote.
#include <PinChangeInterrupt.h>
#include <PinChangeInterruptBoards.h>
#include <PinChangeInterruptPins.h>
#include <PinChangeInterruptSettings.h>
#include <avr/sleep.h>
// LED to indicate timer is active.
const int ON_LED = 5;
// It should be high when timer is active.
// Connect to relay.
const int PUMP_SWITCH = 6;
// Button to start timer running.
const int START_BUTTON = 8;
// Button to stop timer forcefully.
const int STOP_BUTTON = 9;
volatile boolean timer_running;
volatile int timer_start_time;
// TODO: Make it volatile once timer has mdified as configurable.
volatile unsigned long timer_time = 0;
void enter_sleep_mode() {
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
sei();
sleep_mode();
}
/**
* Activate timer.
*/
void start_timer() {
if (!timer_running) {
// Time period in milliseconds.
timer_time = 30000ul; // 30 seconds
timer_running = true;
timer_start_time = millis();
}
}
/**
* Stop timer.
*/
void stop_timer() {
timer_running = false;
timer_start_time = 0;
}
void setup() {
timer_running = false;
timer_start_time = 0;
// Configure output pins.
pinMode(ON_LED, OUTPUT);
pinMode(PUMP_SWITCH, OUTPUT);
// Configure pins for input push buttons.
pinMode(START_BUTTON, INPUT_PULLUP);
pinMode(STOP_BUTTON, INPUT_PULLUP);
// Attach interrupt handlers
// Buttons are with pull up resistors so listening for 'falling' (voltage).
attachPCINT(digitalPinToPCINT(START_BUTTON), start_timer, FALLING);
attachPCINT(digitalPinToPCINT(STOP_BUTTON), stop_timer, FALLING);
}
void loop() {
if (timer_running) {
digitalWrite(ON_LED, HIGH);
digitalWrite(PUMP_SWITCH, HIGH);
// TODO: Handle the case when return value of millis() goes back to start from zero
if ( (millis() - timer_start_time) >= timer_time ) {
// Timer elapsed the required time period.
// So, stop the timer.
stop_timer();
}
}
else {
digitalWrite(ON_LED, LOW);
digitalWrite(PUMP_SWITCH, LOW);
// Nothing to do If timer is not running.
// Save power!!
enter_sleep_mode();
sleep_disable();
}
}
The problem is timer does not work when pressing START button starting from third click. Two initial clicks works OK and timer functions as it should be. I think it does not wake up properly from sleep mode. However, wondering why it works for two initial clicks??
Please help me to identify the problem. I don't have much experience in writing Arduino code.
Thanks
volatile int timer_start_time;
wheretimer_start_time
variable is supposed to hold return value frommillis()
Now I declared it asvolatile unsigned long timer_start_time;
and it worked! :) Could you please make it an answer so I can select? Thanks