Hi, i'm quite new with the arduino ide and i'm wondering how i can make a buzzer sound with an attiny45,i've tried:
AnalogWrite on a PWM pin with a duty cicle of 50% and tone function, both didn't work.
then i moved to a more rough slution:
void ttone (int,unsigned long int,int); //pin ,freq-HZ ,duration-mS
const int outpin = 2; //pin for the buzzer
void setup()
{
Serial.begin(9600);
pinMode(outpin,OUTPUT);
}
void loop()
{
ttone(outpin,1000,2000); //pulse 1000HZ on pin 2 for 2000 millis
ttone(outpin,500,2000); //pulse 500HZ on pin 2 for 2000 millis
}
void ttone(int pin,unsigned long int f,int l)
{
unsigned long int t;
unsigned long int idlet;
idlet=millis(); // gets idle time
Serial.print("idle: ");
Serial.println(idlet);
t=((1/f)*1000000)/2; // 1HZ= 1/1s -> t[s]= 1/freq[HZ] -> t[micros]= t[s]*1.000.000 -
// -> /2 because you need 2 delays for the pin to go HIGH and go LOW (do one pulse)
Serial.print("time ");
Serial.println(t);
while((millis()-idlet)<l) //eplased time[millis] since the function was called= current time - idle time < the time[millis] you want the function to run
{
digitalWrite(pin,HIGH);
delayMicroseconds(t);
digitalWrite(pin,LOW);
delayMicroseconds(t);
Serial.print("current: ");
Serial.println(millis()-idlet);
}
}
it didn't work properly.
So is there a more proper way to create a PWM output for the buzzer?
If not can someone see what's wrong in that code i written?
thanks in advantage for the answers.