Salutations all!
I've been messing around with audio on an Arduino Uno. My code is below. I tried to generate a sine wave alternating from 220 and 440 Hz. I'm getting some of the ugliest sounds back. I'd appreciate any ideas.
Hardware: I have a passive piezo buzzer on pin 11 of my Uno R3. I know it can't really do sine waves, but I'm in the back yard and just using it to get an idea of my progress. Yes, I'm very sure it's passive, supplying direct dc voltage produces no tone, and square waves can be heard without problem.
I'd appreciate any ideas and guidance. I'm new to Arduino, but have 35 years programming experience. Apple Basic counts, right? ![]()
I know reading and answering my question is voluntary, so thank you in advance for taking time for it, I'm grateful.
#include <math.h>
//sample rate = 16000 / (8*256), 8 is OCR1A.
#define SAMPRATE 7812.5
//I multiplied by 256 because I wanted 8bit resolution. is this correct?
float f = 440; //frequency in Hz.
byte pinState = LOW; //only change the pin if its different from last time.
unsigned int samples = 0; //how many samples have been played.
int counter = 0; //duty cycle for current sample.
byte curSamp = 0; //the currently playing sample.
//I stole some of this, still trying to wrap my head around registers and flags for AVR timers. If I went astray, please let me know.
void setup() {
DDRB |= B00001000; // set pin11 to output without affecting other pins
cli();
TCCR1A = 0;
TCCR1B = 0;
OCR1A = 8;
TCCR1B |= (1 << WGM12); // CTC mode on
TCCR1B |= (1 << CS10);// Set CS10 bit for 1 prescaler.
TIMSK1 |= (1 << OCIE1A);// timer compare intrupt
sei();
}
void loop() {
//generate warble, 440 - 220, swaping every 1/2 second.
delay(500);
if (f == 440) {
f = 220;
} else {
f=220;
} //if
} //loop
ISR(TIMER1_COMPA_vect) {
counter++; //tracks duty cycle.
byte dstate = (counter <= curSamp);
if (dstate != pinState) {
pinState = dstate;
PORTB ^= B00001000; // toggles bit which affects pin11.
} //if samp bounds
if (counter >= 256) {
counter = 0;
samples++;
curSamp = ((byte)(sin((2 * PI * samples * f) / SAMPRATE) * 127) + 128); //should generate <F> sine wave at <SAMPRATE> samples per second.
//Something is wrong here, even if I replace (127) with 1, the tone doesn't change frequency, but does have less distortion. It doesn't sound like 440Hz either.
} //if time
} //timer
Thanks again for your time.