Hi all,
I'm using a ATiny85 to generate 3 different frequencies: 500hz, 1Khz & 2Khz.
I'm using the Fast PWM mode to ahieve this. My problem is the trailing adge of each PWM is moving randomly (as seen on my scope). The fluctuations are as follows for each frequency: 500Hz = 200uS, 1Khz = 100uS & 2Khz =50uS. The datasheet mentions these glitches but I'm not sure how to remedy this problem.
ATtiny85
-------u-------
RST - A0 - (D 5) --| 1 PB5 VCC 8 |-- +5V
| |
500Hz SW I/P A3 - (D 3) --| 2 PB3 PB2 7 |-- (D 2) - A1 --> 10K Potentiometer
| |
1kHZ SW I/P A2 - (D 4) --| 3 PB4 PB1 6 |-- (D 1) - PWM --> Damper Circuitry
| |
Gnd ---| 4 GND PB0 5 |-- (D 0) - PWM --> 2Khz SW I/P
-----------------
*/
// normal delay() won't work anymore because we are changing Timer1 behavior
// Adds delay_ms and delay_us functions
#include <util/delay.h>
// Clock at 8mHz
#define F_CPU 8000000 //F_CPU 8000000 (8Mhz). This is used by delay.h library
const int PWMPin = 1; // Only works with Pin 1(PB1)
const int PotPin = A1;
const int fivehundredhertz_select = 3;
const int onekilohertz_select = 4;
const int twokilohertz_select = 0;
// variables will change:
int selectionState1 = 0;// variable for reading the 500Hz selection
int selectionState2 = 0;// variable for reading the 1KHz selection
int selectionState3 = 0;// variable for reading the 2KHz selection
void setup()
{
pinMode(PWMPin, OUTPUT);
pinMode(fivehundredhertz_select, INPUT);
pinMode(onekilohertz_select, INPUT);
pinMode(twokilohertz_select, INPUT);
//Use FAST PWM
TCCR0A = 1 << COM0B1 | 0 << COM0B0 | 1 << WGM01 | 1 << WGM00;
TCCR0B = 1 << WGM02;
/*
8 000 000 / 64 = 125 kHz
64 - pre-scaler
125 kHz / 63 ~ 2000 Hz
63 - OCR0A
*/
// disable interrupts
TIMSK = 0;
// set TOP to generate ~2 kHz
OCR0A = 63;// 63=2Khz, 127=1Khz, 500hz=255
// 50% duty cycle
OCR0B = 31;//31
// start timer at 125 kHz (8 MHz / 64)
TCCR0B = 1 << WGM02 | 0 << CS02 | 1 << CS01 | 1 << CS00;
}
void loop()
{
int in, out;
in = analogRead(PotPin);
// out = map(in, 0, 1023, 0, 63);//(in, 0, 1023, 0, 1023) LINE ADDED
// read the state of the input selections:
selectionState1 = digitalRead(fivehundredhertz_select);
selectionState2 = digitalRead(onekilohertz_select);
selectionState3 = digitalRead(twokilohertz_select);
if (selectionState1 == HIGH)
{
OCR0A = 255;//500 hz
out = map(in, 0, 1023, 0, 255);//(in, 0, 1023, 0, 255)
}
else
{
;//Do nothing
}
if (selectionState2 == HIGH)
{
OCR0A = 127;//1Khz(127)
out = map(in, 0, 1023, 0, 127);//(in, 0, 1023, 0, 127)
}
else
{
;//Do nothing
}
if (selectionState3 == HIGH)
{
OCR0A = 63;//2Khz 63
out = map(in, 0, 1023, 0, 63);//(in, 0, 1023, 0, 1023)
}
else
{
;//Do nothing
}
if ( out < 0.5 ) pinMode(PWMPin, INPUT); // This was added due to duty cycle only reaching as low as 1% min.
else pinMode(PWMPin, OUTPUT);
OCR0B = out;
_delay_ms(200);
}
Any help would be most appreciated!
Thanks
