Hi,
I'm doing my very first arduino experiment (after blinking a led) with a buzzer and the CapacitiveSernsor library. Basically, as long as I touch an aluminium foil, the buzzer plays a tone and stops as I move my finger away.
The code I used is:
#include <CapacitiveSensor.h>
CapacitiveSensor csensor = CapacitiveSensor (4,2);
int buzzPin = 9; // use an analog Pin
void setup () {
Serial.begin (9600);
pinMode (buzzPin, OUTPUT);
}
void loop () {
long start = millis();
long sensor = csensor.capacitiveSensor (30);
Serial.print ("Reading");
Serial.println (sensor);
if (sensor > 100) {
playTone ();
}
else {
mute ();
}
delay (50);
}
void playTone () {
analogWrite (buzzPin, 20);
}
void mute () {
analogWrite (buzzPin, 0);
}
This works but the buzzer plays a 490Hz tone, according to the analogWrite() reference on the site. I'd like the buzzer play an higer tone so I found on the internet another snippet for my playTone() function that uses a digital pin instead of an analog one.
#include <CapacitiveSensor.h>
CapacitiveSensor csensor = CapacitiveSensor (4,2);
int buzzPin = 7;
void setup () {
Serial.begin (9600);
pinMode (buzzPin, OUTPUT);
}
void loop () {
long start = millis();
long sensor = csensor.capacitiveSensor (30);
Serial.print ("Reading");
Serial.println (sensor);
if (sensor > 100) {
playTone ();
}
else {
mute ();
}
delay (50);
}
void playTone () {
for (long i = 0; i < 2048; i++ )
// 1 / 2048Hz = 488uS, or 244uS high and 244uS low to create 50% duty cycle
{
digitalWrite(buzzPin, HIGH);
delayMicroseconds(244);
digitalWrite(buzzPin, LOW);
delayMicroseconds(244);
}
}
void mute () {
digitalWrite (buzzPin, LOW);
}
In this case the buzzer plays only a 1 second tone so it does not play as long as I touch the aluminium foil sensor. What I miss is the logic behind the loop. My understanding is that it sends 2048 HIGH / LOW messages to the buzzer to create a 2048Hz tone. But what the delayMicrosecond() functions are used for? and how to change the code to achieve my goal?
Thank you very much!
P.S. I use an Arduino Duemilanove and not an Uno.