Last active
November 27, 2024 23:06
-
-
Save stonehippo/c23bad2c6b854317d20d76e4753419b5 to your computer and use it in GitHub Desktop.
A simple Arduino piezo knock sensor that cycles through a series of RGB LED patterns
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// define pins for the RGB LED | |
byte led_red_pin = 3; | |
byte led_green_pin = 5; | |
byte led_blue_pin = 6; | |
int piezo_pin = A0; | |
int piezo_threshold = 250; // This may have to be tuned for your piezo | |
int wait = 10000; // the time before the last night and the cycle resets | |
int debounce = 200; // the number of milliseconds we'll wait to reject bad input | |
// used to handle the picking the pattern/behavior to respond to a knock | |
long knock_count = 0; | |
void config_rgb_led() { | |
pinMode(led_red_pin, OUTPUT); | |
pinMode(led_green_pin, OUTPUT); | |
pinMode(led_blue_pin, OUTPUT); | |
} | |
byte invert_color(byte color) { | |
// uncomment this if LOW == ON for your LED | |
return 255 - color; | |
// uncomment this if HIGH == ON for your LED | |
// return color; | |
} | |
void set_led_color(byte red, byte green, byte blue) { | |
analogWrite(led_red_pin, invert_color(red)); | |
analogWrite(led_green_pin, invert_color(green)); | |
analogWrite(led_blue_pin, invert_color(blue)); | |
} | |
void setup() { | |
config_rgb_led(); | |
set_led_color(0,0,0); | |
} | |
int read_piezo() { | |
return analogRead(piezo_pin); | |
} | |
void loop() { | |
// detect a knock | |
if (read_piezo() >= piezo_threshold) { | |
// figure out which pattern we should use | |
int pattern = (knock_count + 1) % 3; | |
switch (pattern) { | |
case 1: // this is the first pattern | |
set_led_color(255, 0, 0); // set the LED to green | |
delay(debounce); | |
break; | |
case 2: // this is the second pattern | |
set_led_color(0, 255, 0); // set the LED to green | |
delay(debounce); | |
break; | |
case 0: // this is the third pattern | |
set_led_color(0, 0, 255); // set the LED to blue | |
delay(debounce); | |
delay(wait - debounce); | |
set_led_color(0,0,0); | |
break; | |
default: | |
break; | |
} | |
knock_count += 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment