Created
May 2, 2014 21:24
-
-
Save ttmarek/3bf7de99ef3b72a73667 to your computer and use it in GitHub Desktop.
Arduino code for generating a sine wave using Pulse Width Modulation.
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
#include "wavetable.h" | |
float seconds = 0; | |
int i = 0; | |
int num_readings = 0; | |
void setup() | |
{ | |
Serial.begin(115200); | |
DDRB = (1<<PB1); // set pin 9 (Arduino UNO) as output | |
// Mode 14: Fast PWM, non-inverted | |
// Prescaler: 1 | |
TCCR1A = (1<<COM1A1) | (0<<COM1A0) | (0<<COM1B1) | (0<<COM1B0) | (1<<WGM11) | (0<<WGM10); | |
TCCR1B = (0<<ICNC1) | (0<<ICES1) | (1<<WGM13) | (1<<WGM12) | (0<<CS12) | (1<<CS11) | (1<<CS10); | |
ICR1 = 249; // TOP | |
OCR1A = 1; // Almost Off | |
// enable timer overflow interrupt for Timer1 | |
// read datasheet p. 127 | |
// "if one of the interrupts are enabled, the interrupt | |
// handler routine can be used for updating the TOP and compare values. | |
TIMSK1 = (0<<ICIE1) | (0<<OCIE1B) | (0<<OCIE1A) | (1<<TOIE1); | |
} | |
void loop() | |
{ | |
//toScope(0); | |
if (seconds > 5 && seconds <= 15) | |
{ | |
takeReading(0); | |
//takeTwoReadings(0,1); | |
} | |
} | |
ISR(TIMER1_OVF_vect) | |
{ | |
seconds += 0.001; | |
if (i > (length-1)) | |
{ | |
i = 0; | |
} | |
OCR1A = pgm_read_byte(&(waveTable[i])); | |
i += 1; | |
} | |
/* takeReading function | |
* takes in an analaog pin number as an integer | |
* sends serial data to PC to be read by Python | |
*/ | |
void takeReading(int pinNum) | |
{ | |
Serial.print(seconds,4); | |
Serial.print(','); | |
Serial.println(analogRead(pinNum)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment