My ATtiny85 circuit generates signals like this one on PB1 (OC0B) using fast PWM (preamble, 16 bit data, stop pulse):
I have trouble with the leftmost longer pulse. At the moment i use simple _delay_us statements to generate it, but it sometimes introduces glitches later near the end of the PWM (orange and yellow) parts.
It seemed smart to switch to using timers for this part but I can't get it to work correctly. This is my code:
const uint8_t JVC_MUTE = 0x71;
const uint8_t JVC_ADDRESS = 0xF1;
void setupPWM () {
//enables fast pwm, non inverting,TOP=OCR0A, prescaler 8
TCCR0A = (1<<WGM01)| (1<<WGM00)|(1<<COM0B1);
TCCR0B = (1<<WGM02)|( 1<<CS01);
}
void stopPWM () {
TCCR0A = 0;
}
/*emits a long preamble pulse
*/
void preamble(){
//enables fast pwm, non inverting, prescaler 64
TCCR0A = (1<<WGM01)| (1<<WGM00)|(1<<COM0B1);
TCCR0B = (1<<WGM02)|( 1<<CS01)|(1<<CS00);
TCNT0=0;
OCR0A=255;
OCR0B=80;
do ; while ((TIFR & 1<<OCF0B) == 0);
TIFR = 1<<OCF0B;
TCCR0A = 0;
}
/*emits 16 bit of data using fast PWM
code:16 bit data value to be send (address + command)
*/
void sendCode (uint16_t code) {
TCNT0=0;
//padding instructions 1
OCR0A=0;
OCR0B=0;
do ; while ((TIFR & 1<<OCF0B) == 0);
TIFR = 1<<OCF0B;
//padding instructions 2
OCR0A=0;
OCR0B=0;
//waits while polling the OCF0B bit signaling a compare match with OCR0B
do ; while ((TIFR & 1<<OCF0B) == 0);
TIFR = 1<<OCF0B;
//loops through each bit in the 'code' variable
//and emits a long or short pulse depending on value
for (uint16_t Bit=0x8000;Bit;Bit=Bit>>1){
//if 1
if (code & Bit) {
OCR0A=255;
OCR0B=80;
}
//if 0
else {
OCR0A=130;
OCR0B=80;
};
do ; while ((TIFR & 1<<OCF0B) == 0);
TIFR = 1<<OCF0B;
}
//emits a short pulse signaling the end of the transmission
OCR0A=130;
OCR0B=80;
do ; while ((TIFR & 1<<OCF0B) == 0);
TIFR = 1<<OCF0B;
}
/*
*emits a transmission (preamble pulse, 16 bit of data + end pulse)
*/
void transmit(uint8_t address,uint8_t code){
preamble();
setupPWM();//PWM settings in TCCR0A and TCCR0B
sendCode((JVC_ADDRESS<<8)+JVC_MUTE);
stopPWM();//disables PWM (TCCR0A=0)
}
There are two issues:
- This code will generate the preamble pulse the first time, followed
by glitched data, and then only the glitchy data when called
consecutively. - It needs the padding instructions I added in sendCode(), otherwise the 2 first bits of the transmission are always cut.
edit: the actual data part (orange and yellow parts), as well as the stop pulse at the end work fine when the call to preamble() is commented out. The only issue is with the preamble() part.
I'd appreciate any help, especially with point 1.