If you want to get into electronics, one great thing to have is some modules/sensors lying around for fast prototyping. You can buy cheap 'kits' of sensors (Search '37 sensors arduino' on banggood or aliexpress) with tilt, touch, laser, joystick and so on. A good write-up of the common ones can be found here: https://tkkrlab.nl/wiki/Arduino_37_sensors
My loving brother bought me a kit - here's my first useful hack with it as an example of how easy this sort of thing is. I was reminded why so many people choose arduino for prototyping - this whole project took about half an hour. Sure, it's not energy efficient or as cheap as it would otherwise be, but I'll re-use all the components and I didn't even have to solder a single wire.
The goal was to make a box that would play a melody and blink some lights whenever someone recycled a plastic bottle. I thought of having the bottle break a beam, or activate a vibration sensor when it landed, but I decided to go with one of the little mercury tilt switches.
Without further ado, here's the code:
/*
* Sketch modified by Jonathan Whitaker
* Based on example code by by Tom Igoe http://www.arduino.cc/en/Tutorial/Tone
* All code public domain.
*/
#include "pitches.h" // Copy from arduino tone example for this to work
// notes in the melody:
int melody[] = {
NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};
// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
4, 8, 8, 4, 4, 4, 4, 4
};
int tiltPin = 2; // Signal pin of tinlt sensor
int led = 13;
void setup() {
pinMode(tiltPin, INPUT);
pinMode(led, OUTPUT);
digitalWrite(led, LOW);
}
void loop() {
if (digitalRead(tiltPin) == HIGH) { //read tiltPin
digitalWrite(led, HIGH); //turn LED on
play(); //Play a tune
digitalWrite(led, LOW);
}
}
void play(){
// iterate over the notes of the melody:
for (int thisNote = 0; thisNote < 8; thisNote++) {
int noteDuration = 1000 / noteDurations[thisNote];
tone(8, melody[thisNote], noteDuration);
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
noTone(8);
}
}
Simple and easy, especially since I just modified the example tone sketch. SO one wire of the sensor goes to pin 8, the others to power and ground. I also have the option of RGB LED blink patterns, but I'll leave that out of the code for simplicity. Here's a photo of the box (from inside):As a bottle is pushed through the hole it bumps the sensor (which has since been hot-glued in place) and the barbers knock song plays while lights blink. Simple, easy and fun - the perfect beginner project.
Discussions
Become a Hackaday.io Member
Create an account to leave a comment. Already have an account? Log In.