How to disable then re-enable a watchdog interrupt for Arduino? - arduino

I'm attempting to use a watchdog interrupt as a timer to sleep for a certain period of time with my Arduino. My problem lies in the fact that, on wake-up, I need to conduct operations that will take longer than 8 seconds.
Currently, my Arduino will sleep for 1 minute, using successive interrupts by the watchdog to wake it up and place it back into sleep. After 1 minute, however, I begin to conduct operations that take longer than 8 seconds and the watchdog interrupt times out.
I want to shut off the watchdog timer, conduct operations, then re-enable it and return to sleeping.
Here is my code:
#include "Adafruit_FONA.h"
#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>
#define FONA_RX 10
#define FONA_TX 9
#define FONA_RST 4
#define LED_PIN 8
// this is a large buffer for replies
char replybuffer[255];
char *SMSnumber = "6015962842";
char stack[128] = {'c'};
//Value for watchdog timer interrupt.
volatile int f_wdt = 1;
int seconds = 0;
int minutes = 1;
int hours = 0;
int interval = ((hours*60*60) + (minutes*60) + (seconds))/8;
int timerCounter = 0;
//Setup for pulse sensor.
volatile int Signal; // holds the incoming raw data
int pulsePin = 0; //Pin to read at analog 0 for the pulse.
volatile int IBI = 600; // int that holds the time interval between beats! Must be seeded!
volatile boolean Pulse = false; // "True" when User's live heartbeat is detected. "False" when not a "live beat".
volatile int BPM; // int that holds raw Analog in 0. updated every 2mS
volatile boolean QS = false; // becomes true when Arduoino finds a beat.
unsigned long lastTime; // used to time the Pulse Sensor samples
unsigned long thisTime; // used to time the Pulse Sensor samples
//ISR for watchdog timer.
ISR(WDT_vect)
{
if(f_wdt == 0)
{
f_wdt=1;
timerCounter++;
}
else
{
Serial.println("WDT Overrun!!!");
}
}
// We default to using software serial. If you want to use hardware serial
// (because softserial isnt supported) comment out the following three lines
// and uncomment the HardwareSerial line
#include <SoftwareSerial.h>
SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
SoftwareSerial *fonaSerial = &fonaSS;
// Hardware serial is also possible!
//HardwareSerial *fonaSerial = &Serial;
// Use this for FONA 800 and 808s
Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
void setup() {
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, HIGH);
delay(3000);
digitalWrite(LED_PIN, LOW);
while (!Serial);
Serial.begin(115200);
setupGsm();
setupWdt();
}
void loop()
{
if(f_wdt == 1)
{
if (timerCounter == interval)
{
WDTCSR |= _BV(WDTON);
Serial.println(F("Tried to stop the watchdog."));
delay(20000);
//Reset timer.
timerCounter = 0;
WDTCSR |= _BV(WDIE);
Serial.println(F("Tried to re-enable watchdog."));
}
/* Don't forget to clear the flag. */
f_wdt = 0;
/* Re-enter sleep mode. */
enterSleep();
}
else
{
/* Do nothing. */
}
}
void setupGsm()
{
fonaSerial->begin(4800);
while (! fona.begin(*fonaSerial)) {
Serial.println(F("Couldn't find FONA"));
delay(1000);
}
digitalWrite(LED_PIN, HIGH);
delay(500);
digitalWrite(LED_PIN, LOW);
delay(500);
digitalWrite(LED_PIN, HIGH);
delay(500);
digitalWrite(LED_PIN, LOW);
delay(500);
digitalWrite(LED_PIN, HIGH);
}
void enterSleep(void)
{
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
/* Now enter sleep mode. */
sleep_mode();
/* The program will continue from here after the WDT timeout*/
sleep_disable(); /* First thing to do is disable sleep. */
/* Re-enable the peripherals. */
power_all_enable();
}
void setupWdt()
{
/*** Setup the WDT ***/
/* Clear the reset flag. */
MCUSR &= ~(1<<WDRF);
/* In order to change WDE or the prescaler, we need to
* set WDCE (This will allow updates for 4 clock cycles).
*/
WDTCSR |= (1<<WDCE) | (1<<WDE);
/* set new watchdog timeout prescaler value */
WDTCSR = 1<<WDP0 | 1<<WDP3; /* 8.0 seconds */
/* Enable the WD interrupt (note no reset). */
WDTCSR |= _BV(WDIE);
}
In the void loop() function, I'm attempting to turn off the watchdog using WDTCSR |= _BV(WDTON); however my compiler complains that WDTON is not decalared in its scope.

Rather than directly accessing the controller's registers from your code, use wdt_enable() and wdt_disable() from the avr/wdt.h library to start and stop the watchdog timer.
Also, for the sake of system reliability, it might be better to actually keep the watchdog timer running (not disabling it), and add periodic calls to wdt_reset() inside long loops and functions to prevent inappropriate system resets.
For instance, you can replace the delay(20000); line in your code with a loop that repeats 20 times the statements: delay(1000); wdt_reset();

Related

Arduino send bad signal to interrupt pin

I have connected coin hopper and coin acceptor to one arduino uno, coin acceptor connected to pin 2, coin hopper to pin 3 - sensor and pin 7 - relay. When coin hopper switch relay, it is executing coininterrupt
for coin hopper I am using this script link
coin acceptor script: link
I need this 2 scripts working on 1 arduino
my code:
#define SENSOR 3
#define RELAY 7
#define ACCEPTOR 2
volatile boolean insert = false;
int pulse=0,count;
char sen;
int temp=0;
unsigned long int timer;
void setup()
{
Serial.begin(9600);
pinMode(SENSOR,INPUT_PULLUP);
pinMode(RELAY,OUTPUT);
sen=digitalRead(SENSOR);
digitalWrite(RELAY, HIGH);
attachInterrupt(digitalPinToInterrupt(ACCEPTOR), coinInterrupt, RISING);
}
void loop()
{
if (insert) {
insert = false;
Serial.println("coin");
delay(1000);
}
if(Serial.available())
{
timer=millis();
// temp is amount to dispense send to arduino
temp=Serial.parseInt();
if(temp>0){
digitalWrite(RELAY,LOW);}
}
sen=(sen<<1)|digitalRead(SENSOR);
// if hopper sensor read drop coin
if(sen==1)
{
timer=millis();
pulse++;
sen&=0x03;
Serial.println("out 1");
//if dispensed coins equal with coins to dispense stop engine
if(pulse==temp)
{
digitalWrite(RELAY,HIGH);
pulse=0;
temp=0;
}
}
// if amount dispensed is not equal with amount to dispense and engine running, stop
if((digitalRead(RELAY)==LOW)&(millis()-timer>2000))
{
digitalWrite(RELAY,HIGH);
pulse=0;
temp=0;
}
}
void coinInterrupt() {
insert = true;
}
I was trying to change pins (arduino uno support interrupts on pin 2 and 3 only) but problem still appears so I guess there is issue in the code
your sketch does not run in this state :
first fix errors :
declare insert as volatile
remove cpulse (not used anywhere)
change 'if()' to (I suppose) 'if (insert) ....'
remove stuff with 'sen' var : simply use if(digitalRead(SENSOR)) or if(!digitalRead(SENSOR))
except if you need to store relay state.
use logical operators like || or && unless you really need bitwise operations
example of result sketch :
#define SENSOR 3
#define RELAY 7
volatile boolean insert = false;
byte amountToDispense = 0;
int pulse = 0;
int temp = 0;
unsigned long int timer;
void setup()
{
Serial.begin(9600);
pinMode(SENSOR, INPUT_PULLUP);
pinMode(RELAY, OUTPUT);
digitalWrite(RELAY, HIGH);
attachInterrupt(digitalPinToInterrupt(2), coinInterrupt, RISING);
}
void loop()
{
if (insert ) {
insert = false;
Serial.println("coin");
delay(1000);
}
if (Serial.available())
{
timer = millis();
temp = Serial.parseInt();
if (temp > 0) {
//amountToDispense = Serial.read() - 48;
digitalWrite(RELAY, LOW);
}
}
if (digitalRead(SENSOR))
{
timer = millis();
pulse++;
Serial.println("out 1");
if (pulse >= temp)
{
digitalWrite(RELAY, HIGH);
pulse = 0;
temp = 0;
}
}
if (!digitalRead(RELAY) && (millis() - timer > 2000))
{
digitalWrite(RELAY, HIGH);
pulse = 0;
temp = 0;
}
}
void coinInterrupt() {
insert = true;
}
What is this supposed to do?
sen=(sen<<1)|digitalRead(SENSOR);
You init sen with digitalRead(SENSOR);
Assuming that pin is LOW when you start the sketch and turns HIGH, sen will become 1.
Next you do sen &= 0x03 so sen is still 1.
Again sen=(sen<<1)|digitalRead(SENSOR); , sen will either be 2 or 3.
Next loop run sen=(sen<<1)|digitalRead(SENSOR); sen is now 4 or 6. and so on...
I don't have time to think about what you want to achieve but this is definitely a problem as you'll only enter if (sen == 1) once and never again.
If this is not sufficient you should probably improve your post as it is unclear what arduino sends bad signal to interrup pin is supposed to mean. That doesn't make sense. Explain the expected behaviour of your program and how it behaves instead. add more comments so it becomes clear what you intend to do with each block of code so we don't have to interpret

Arduino IRremote Send and Receive simultaneously

I'm currently working on a lasertag game with several weapons.
I would like to use one arduino nano in each weapon. It should be able to receive the IR-signals of the opponents as well as send IR-signals if a button is triggered.
So now there comes my problem:
I implemented an interrupt for the IR-receiver pin, so that an opponent's shot is always detected even when I'm shooting.
When the button is permanently pressed, the IR LED will shoot every 300 milliseconds (the send-function takes approximately 70ms and I implemented a delay of 230ms).
Unfortunately, the Nano won't detect any signal of the receiver in those 300ms.
However, if I disconnect the IR-LED everything seems to work perfectly.
Now I'm wondering, why the IR-LEDs connection has an effect on the functionality of my code.
Do you know any way I could solve this problem?
Here you can see the entire code I implemented:
#define IR_SEND_PIN 3
#define BUTTON_PIN 10
#define LED_PIN 12
#include <IRremote.hpp>
#include <Arduino.h>
uint8_t sAddress = 0;
uint8_t sCommand = 0x59;
uint8_t sRepeats = 0;
volatile uint8_t hitData;
void setup() {
IrSender.begin();
IrReceiver.begin(IR_RECEIVE_PIN);
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(IR_RECEIVE_PIN), HIT, CHANGE);
}
void HIT() {
if (IrReceiver.decode()) {
hitData = IrReceiver.decodedIRData.command;
}
IrReceiver.resume();
}
void loop() {
if (digitalRead(BUTTON_PIN) == LOW) {
IrSender.sendNEC(sAddress, sCommand, sRepeats);
delay(120);
}
if (hitData == sCommand) { // indicates received signal 0x59
hitData = 0x00;
IrReceiver.resume();
digitalWrite(LED_PIN, HIGH);
delay(8);
digitalWrite(LED_PIN, LOW);
}
}```

How do I have this audio and LED activate ONLY when a button is held using an Arduino?

I have this code that I am using to play a sound effect where I used a program called wav2c to convert a .wav file to number values that I put into a header file that I use in the code to generate the sound. I currently have it programmed to play the audio upon uploading it to the Arduino with an LED being activated along with it and staying lit for just the duration of the sound effect. I am trying to program it so that the sound and LED only activate when I am pressing a button. I have the pin the button is plugged into already programmed in but I'm not sure how to have it control the audio and LED as stated above. I don't have much experience with programming or Arduino so any help is much appreciated! I am using an Arduino Mega 2560.
The code
#include <stdint.h>
#include <avr/interrupt.h>
#include <avr/io.h>
#include <avr/pgmspace.h>
#define SAMPLE_RATE 20000
#include "Test.h"
int ledPin = 2;
int speakerPin = 9; // Can be either 3 or 11, two PWM outputs connected to Timer 2
const byte pinSwitch1 = 3;
volatile uint16_t sample;
byte lastSample;
void stopPlayback()
{
digitalWrite(ledPin, LOW);
// Disable playback per-sample interrupt.
TIMSK1 &= ~_BV(OCIE1A);
// Disable the per-sample timer completely.
TCCR1B &= ~_BV(CS10);
// Disable the PWM timer.
TCCR2B &= ~_BV(CS10);
digitalWrite(speakerPin, LOW);
}
// This is called at 8000 Hz to load the next sample.
ISR(TIMER1_COMPA_vect) {
if (sample >= sounddata_length) {
if (sample == sounddata_length + lastSample) {
stopPlayback();
}
else {
if(speakerPin==11){
// Ramp down to zero to reduce the click at the end of playback.
OCR2A = sounddata_length + lastSample - sample;
} else {
OCR2B = sounddata_length + lastSample - sample;
}
}
}
else {
if(speakerPin==11){
OCR2A = pgm_read_byte(&sounddata_data[sample]);
} else {
OCR2B = pgm_read_byte(&sounddata_data[sample]);
}
}
++sample;
}
void startPlayback()
{
pinMode(speakerPin, OUTPUT);
// Set up Timer 2 to do pulse width modulation on the speaker
// pin.
// Use internal clock (datasheet p.160)
ASSR &= ~(_BV(EXCLK) | _BV(AS2));
// Set fast PWM mode (p.157)
TCCR2A |= _BV(WGM21) | _BV(WGM20);
TCCR2B &= ~_BV(WGM22);
if(speakerPin==11){
// Do non-inverting PWM on pin OC2A (p.155)
// On the Arduino this is pin 11.
TCCR2A = (TCCR2A | _BV(COM2A1)) & ~_BV(COM2A0);
TCCR2A &= ~(_BV(COM2B1) | _BV(COM2B0));
// No prescaler (p.158)
TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);
// Set initial pulse width to the first sample.
OCR2A = pgm_read_byte(&sounddata_data[0]);
} else {
// Do non-inverting PWM on pin OC2B (p.155)
// On the Arduino this is pin 3.
TCCR2A = (TCCR2A | _BV(COM2B1)) & ~_BV(COM2B0);
TCCR2A &= ~(_BV(COM2A1) | _BV(COM2A0));
// No prescaler (p.158)
TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);
// Set initial pulse width to the first sample.
OCR2B = pgm_read_byte(&sounddata_data[0]);
}
// Set up Timer 1 to send a sample every interrupt.
cli();
// Set CTC mode (Clear Timer on Compare Match) (p.133)
// Have to set OCR1A *after*, otherwise it gets reset to 0!
TCCR1B = (TCCR1B & ~_BV(WGM13)) | _BV(WGM12);
TCCR1A = TCCR1A & ~(_BV(WGM11) | _BV(WGM10));
// No prescaler (p.134)
TCCR1B = (TCCR1B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);
// Set the compare register (OCR1A).
// OCR1A is a 16-bit register, so we have to do this with
// interrupts disabled to be safe.
OCR1A = F_CPU / SAMPLE_RATE; // 16e6 / 8000 = 2000
// Enable interrupt when TCNT1 == OCR1A (p.136)
TIMSK1 |= _BV(OCIE1A);
lastSample = pgm_read_byte(&sounddata_data[sounddata_length-1]);
sample = 0;
sei();
}
void setup()
{
pinMode( pinSwitch1, INPUT );
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH);
startPlayback();
}
void loop()
{
while (true);
}
The header file referenced in the code with the numeric values to create the audio.
#ifndef _HEADERFILE_H // Put these two lines at the top of your file.
#define _HEADERFILE_H // (Use a suitable name, usually based on the file name.)
const int sounddata_length=32000;
//const int sounddata_sampleRate=20000;
const unsigned char sounddata_data[] PROGMEM = {
15,1,49,0,150,0,138,0,219,255,133,0,176,0,15,1,210,
//There are many lines of more numbers in between that I cut out to save space
};
#endif // _HEADERFILE_H // Put this line at the end of your file.
The following changes will allow you to start playback whenever there is a falling edge on your switch pin. You may need to tweak to avoid switch 'bouncing'.
Firstly, add a global variable to record the last switch state:
int lastSwitchState;
Change your setup() to
void setup() {
pinMode(pinSwitch1, INPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, HIGH);
lastSwitchState = digitalRead(pinSwitch1);
}
and your loop() function to
void loop() {
delay(50);
int switchState = digitalRead(pinSwitch1);
if (switchState != lastSwitchState) {
lastSwitchState = switchState;
if (switchState == LOW) {
startPlayback();
}
}
}
Interrupts vs polling
Instead of polling the switch pin inside the main loop(), you could use interrupts. You would use attachInterrupt() to do this. Interrupts are only available on certain pins, however, and the above approach is conceptually simpler I think.

Arduino LED control sleep

I want to implement a simple LED controller with an Arduino Uno, that goes to sleep and has different buttons.
Functions of buttons are:
Digital 2: Button for ON OFF
Digital 3: Button for Wake up
Everything works ok, but when it goes to sleep, the LEDs also turn off. I want that after 30 seconds, when Arduino goes to sleep, lights stays on.
Here is my code:
#include <avr/sleep.h>
#define REDPIN 10
#define GREENPIN 11
#define BLUEPIN 9
#define delayTime 20 //za fading cas
unsigned long interval= 30000;
unsigned long previousMillis = 0;
const int ledPin = 12; // the pin that the LED is attached to
const int buttonPin1 = 2; //on off
bool vklop = false;
int bela = 10;
int barva;
int prejsnja_barva = 0;
int buttonPushCounter1 = 0; // counter for the number of button presses
int buttonState1 = 0; // current state of the button
int lastButtonState1 = 0; // previous state of the button
/////////////////////////////////////*SETUP*/////////////////////////////////////////
void setup()
{
pinMode(buttonPin1, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
pinMode(3,INPUT); //because of interrupts PIN digital 3
digitalWrite(3,HIGH);
}
/////////////////////////////////////*LOOP*/////////////////////////////////////////
void loop()
{
unsigned long currentMillis = millis();
if ((currentMillis-previousMillis) > interval) //15s timer
{
previousMillis = currentMillis;
Serial.println("SLEEP!"); // kaj delaj po preteku 5s
delay(50);
sleepSetup(); //sleep mode
}
else
{
buttonState1 = digitalRead(buttonPin1);
/////////////////////////////////////ON/OFF/////////////////////////////////////////
/////////////////////////////////////ON/OFF/////////////////////////////////////////
if (buttonState1 != lastButtonState1) // compare the buttonState to its previous state
{
if (buttonState1 == HIGH) // if the state has changed, increment the counter
{
buttonPushCounter1++; // if the current state is HIGH then the button went from off to on:
Serial.println("on");
Serial.print("number of BUTTON1 pushes: ");
Serial.println(buttonPushCounter1);
digitalWrite(ledPin, HIGH);
if(buttonPushCounter1 % 2 == 0)
{
setColor(bela, bela, bela);
vklop = true;
barva = 13;
}
else
{
setColor(0, 0, 0);
vklop = false;
}
}
else // if the current state is LOW then the button went from on to off:
{
Serial.println("off");
digitalWrite(ledPin, LOW);
}
delay(50); // Delay a little bit to avoid bouncing
}
lastButtonState1 = buttonState1; // save the current state as the last state, for next time through the loop
}
}
/////////////////////////////////functions/////////////////////////////////////////////
/////////////////////////////////functions/////////////////////////////////////////////
/////////////////////////////////functions/////////////////////////////////////////////
void setColor(int red, int green, int blue)
{
analogWrite(REDPIN, red);
analogWrite(GREENPIN, green);
analogWrite(BLUEPIN, blue);
}
void sleepSetup(void)
{
sleep_enable(); // Set sleep enable (SE) bit:
attachInterrupt(1, pinInterrupt, LOW); // Set pin 2 as interrupt and attach handler:
set_sleep_mode(SLEEP_MODE_PWR_DOWN); // define our preferred sleep mode:
digitalWrite(13,LOW);
sleep_cpu();
Serial.println("Just woke up!"); //OD TU SE NADALJUJE PO PRITISKU TIPKE
digitalWrite(13,HIGH);
}
void pinInterrupt() //ISR
{
sleep_disable();
detachInterrupt(0);
}
You're using AVR's Power Down sleep mode. In this mode all timers are turned off to save power.
No timers -> no PWM -> no analogue output -> no PWM driven LEDs
To keep the LED on use another sleep mode.
See
http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf for details.
But to be honest I am not quite sure if this makes any sense. If you're driving an LED through 3 outputs the power you can save by putting the MCU into sleep is maybe a few percent.
And as sleep stops the CPU and hence your program you won't be able to have the LEDs turn off after 30s.
Why not just wait 30s befor going to sleep? The alternative would be some external timing circuitry that would also consume power. So I guess having a few milliamps more for 30 seconds is still a better alternative.

XBee and watchdog timer transmission not working

I've created a sketch that uses a watchdog timer that runs every eight seconds. I've used a counter to wait 64 seconds (about a minute).
In addition, I've used the pin hibernation mode on the XBee. The XBee communication together with the pin hibernation work properly. If I add the watchdog timer it stops working. Is the program restarted from the last row executed before the watchdog interrupt?
#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>
#include <XBee.h>
XBeeAddress64 coordAddr = XBeeAddress64(0x0013a200, 0x4090c5a6);
uint8_t xbeePayload[] = "Hello";
XBee xbee = XBee();
ZBTxRequest zbTx = ZBTxRequest();
ZBTxStatusResponse txStatus = ZBTxStatusResponse();
int XBee_pin = 9; // This pin wakes up the XBee and puts it to sleep.
int counter = 0;
void sendData() {
zbTx.setAddress64(coordAddr);
zbTx.setAddress16(0xFFFE);
zbTx.setPayload(xbeePayload);
zbTx.setPayloadLength(sizeof(xbeePayload));
xbee.send(zbTx);
}
ISR(WDT_vect)
{
counter++;
}
void enterSleep(void)
{
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
/* Now enter sleep mode. */
sleep_mode();
/* The program will continue from here after the WDT timeout */
sleep_disable(); /* First thing to do is disable sleep. */
/* Re-enable the peripherals. */
power_all_enable();
}
void setup()
{
// To reduce power, setup all pins as inputs with without any pullups
/*for(int x = 1 ; x < 18 ; x++){
pinMode(x, INPUT);
digitalWrite(x, LOW);
}*/
pinMode(XBee_pin, OUTPUT);
digitalWrite(XBee_pin, HIGH);
xbee.begin(9600);
delay(5000);
/*** Setup the WDT ***/
/* Clear the reset flag. */
MCUSR &= ~(1 << WDRF);
/* In order to change WDE or the prescaler, we need to
* set WDCE (this will allow updates for 4 clock cycles).
*/
WDTCSR |= (1 << WDCE) | (1 << WDE);
/* Set new watchdog timeout prescaler value */
WDTCSR = 1 << WDP0 | 1 << WDP3; /* 8.0 seconds */
/* Enable the WD interrupt (note no reset). */
WDTCSR |= _BV(WDIE);
//Serial.println("Initialisation complete.");
//delay(100); //Allow for serial print to complete.
ADCSRA &= ~(1 << ADEN); //Disable ADC
ACSR = (1 << ACD); //Disable Analog Comparator
DIDR0 = 0x3E; //Disable digital input buffers on ADC1-ADC5 pins
DIDR1 = (1 << AIN1D)|(1 << AIN0D); //Disable digital input buffer on AIN1/0
power_twi_disable();
power_spi_disable();
power_usart0_disable();
//power_timer0_disable(); //Needed for delay_ms
power_timer1_disable();
power_timer2_disable();
}
void loop()
{
if(counter == 8)
{
counter = 0;
pinMode(XBee_pin, OUTPUT);
digitalWrite(XBee_pin, LOW);
delay(5000);
sendData();
delay(2000);
pinMode(XBee_pin, INPUT);
digitalWrite(XBee_pin, HIGH);
/* Re-enter sleep mode. */
enterSleep();
}
}
enterSleep() needs to be outside the if statement. Your current implementation spins in the loop(), waits for 8 watchdog timeouts, executes the code once, sleeps, wakes up and does the same spin. The code should look like this I believe.
void loop()
{
if(counter == 8)
{
counter = 0;
pinMode(XBee_pin, OUTPUT);
digitalWrite(XBee_pin, LOW);
delay(5000);
sendData();
delay(2000);
pinMode(XBee_pin, INPUT);
digitalWrite(XBee_pin, HIGH);
}
/* Re-enter sleep mode. */
enterSleep();
}
Also, be aware that the watchdog is still running while your delays occur. It may trigger again during your if statement, you should issue a wdt_reset() in a few places like:
void loop()
{
if(counter == 8)
{
counter = 0;
pinMode(XBee_pin, OUTPUT);
digitalWrite(XBee_pin, LOW);
delay(5000);
wdt_reset();
sendData();
wdt_reset();
delay(2000);
pinMode(XBee_pin, INPUT);
digitalWrite(XBee_pin, HIGH);
}
/* Re-enter sleep mode. */
enterSleep();
}

Resources