Skip to content

Instantly share code, notes, and snippets.

@hdo
Created August 15, 2017 14:27
Show Gist options
  • Save hdo/1404c2ea08c3ffb4a7e4129f79c0770e to your computer and use it in GitHub Desktop.
Save hdo/1404c2ea08c3ffb4a7e4129f79c0770e to your computer and use it in GitHub Desktop.
My halloween project (PIR triggered sounds)
#include "Arduino.h"
#define PIR_INPUT 11
#define DFPLAYER_OUTPUT 10
#define WAIT_TICKS_INTERVAL 1000 // each ticks is about 10ms
int ledPin = 13; // LED connected to digital pin 13
uint8_t state = 0;
volatile uint32_t ticks;
uint32_t lastTrigger;
ISR(TIMER0_COMPA_vect, ISR_BLOCK) {
ticks++;
}
void init_systicks() {
TCCR0B = _BV(CS02) | _BV(CS00);
TCCR0A = _BV(WGM01);
TIMSK0 = _BV(OCIE0A);
// 8000000/1024/78 == 100HZ -> 10 ms
OCR0A = 77; // !!! must me set last or it will not work!
}
uint32_t math_calc_diff(uint32_t value1, uint32_t value2) {
if (value1 == value2) {
return 0;
}
if (value1 > value2) {
return (value1 - value2);
}
else {
// check for overflow
return (0xffffffff - value2 + value1);
}
}
void delay_ticks(uint16_t t) {
uint32_t now_ticks = ticks;
while(math_calc_diff(ticks, now_ticks) < t) {
// do nothing
}
}
// The setup() method runs once, when the sketch starts
void setup() {
init_systicks();
Serial.begin(38400);
// initialize the digital pin as an output:
pinMode(ledPin, OUTPUT);
pinMode(PIR_INPUT, INPUT);
pinMode(DFPLAYER_OUTPUT, OUTPUT);
digitalWrite(DFPLAYER_OUTPUT, HIGH);
}
// the loop() method runs over and over again,
// as long as the Arduino has power
void loop() {
if (digitalRead(PIR_INPUT) == HIGH) {
digitalWrite(ledPin, HIGH);
if (math_calc_diff(ticks, lastTrigger) > WAIT_TICKS_INTERVAL) {
lastTrigger = ticks;
// trigger playback
// NOTE: Due systick arduino 'delay' is not working!
digitalWrite(DFPLAYER_OUTPUT, LOW);
delay_ticks(20);
digitalWrite(DFPLAYER_OUTPUT, HIGH);
Serial.println("trigger");
}
}
else {
digitalWrite(ledPin, LOW);
}
}
int main(void) {
init();
setup();
while (true) {
loop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment