Hello all,
My project is about a PIR sensor, an LED and a buzzer. I have a barebone ATMega328p running this code. I am stuck, please see the code below. I am not able to make Tone() work. When the PIR detects nothing the uC sleeps. When movement is detected the uC lights the LED but does not sound the alarm. I am probably missing an elephant here.. suggestions?
Must I take the Tone part out of the ISR? Put it where?
And also: Thank you Nick Gammon!
/* PIR sensor * Sleepy * Interrupt * Buzzer */
#include "Arduino.h"
#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>
const byte ledPin = 13; // choose pin for the LED
const byte inputPin = 2; // choose input pin (for PIR)
const int pitchTone = 3000; // siren frequency
const int speakerPin = 8; // siren pin
void switchPressed() { // Interrupt Service Routine (ISR)
if (digitalRead (inputPin) == HIGH) {
digitalWrite (ledPin, HIGH);
tone(speakerPin, pitchTone);}
else {
digitalWrite (ledPin, LOW);
noTone(speakerPin);}} // end of switchPressed
void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT_PULLUP);} // declare sensor as input
void loop() {
ADCSRA = 0; // disable ADC
set_sleep_mode (SLEEP_MODE_PWR_DOWN); // select sleep mode
noInterrupts (); // timed sequence follows
sleep_enable(); //
attachInterrupt (digitalPinToInterrupt (inputPin), switchPressed, CHANGE); // attach interrupt handler
MCUCR = bit (BODS) | bit (BODSE); // turn on brown-out enable select
MCUCR = bit (BODS); // this must be done within 4 clock cycles of above
interrupts(); // guarantees next instruction executed
sleep_cpu();} // sleep within 3 clock cycles of above