Skip to content

Instantly share code, notes, and snippets.

@brightcloudy
Created April 10, 2014 03:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brightcloudy/10339595 to your computer and use it in GitHub Desktop.
Save brightcloudy/10339595 to your computer and use it in GitHub Desktop.
#include <avr/io.h>
#include <avr/interrupt.h>
volatile uint8_t rwflags = 0b00000001;
volatile uint8_t bit = 0;
int main(void)
{
volatile uint8_t byte = 0b10101010;
DDRD |= (1 << 0) | (1 << 1); //portd0 portd1 output
PORTD |= (1 << 0); //portd0 high
PORTD &= ~(1 << 1); //ensure portd1 low
DDRB &= ~(1 << 0); //ensure portb0 (pcint0) input
PORTB |= (1 << 0); //portb0 (pcint0) pull-up resistor
cli(); // disable interrupts for prescaler set
CLKPR = (1 << CLKPCE); // set prescaler 1x
CLKPR = 0;
sei();
TCCR0A |= (1 << WGM01); // timer0 ctc ocr0a
OCR0A = 157; //5 ms
//TCCR0B |= (1 << CS02); // /256 timer prescale
PCMSK0 = (1 << PCINT0); //set pcint mask to pin pcint0 only (db0)
PCICR |= (1 << PCIE0); //enable pcint0 interrupts
TCCR1B |= (1 << WGM12); // timer1 ctc ocr1a
OCR1A = 62500; // 0.5 seconds
TCCR1B |= (1 << CS11) | (1 << CS10); // /64 timer prescale
for (;;) {
if (TIFR1 & (1 << OCF1A)) {
if (rwflags & (1 << 0)) {
if (byte & (1 << bit)) { PORTD |= (1 << 1); } else { PORTD &= ~(1 << 1); };
// set portd1 to bit in byte
if (bit == 7) {
rwflags &= ~(1 << 0); //stop writing
} else { bit++; }; //next bit
}
PORTD ^= (1 << 0); //flip portd0
if (!(rwflags & (1 << 0))) { DDRD &= ~(1 << 0); }; //disable clock
TIFR1 = (1 << OCF1A);
}
}
}
ISR(PCINT0_vect) {
// use timer0 to see if pin state is same after 5 ms
uint8_t state = (PINB & (1 << 0));
PCIFR |= (1 << PCIF0); //clear interrupt flag
TIFR0 |= (1 << OCF0A); //clear ctc match flag
TCNT0 = 0;
TCCR0B |= (1 << CS02); // /256 clock prescale
while (!(TIFR0 & (1 << OCF0A))) {};
if ((PINB & (1 << 0)) == (state & (1 << 0))) { //if still same state
rwflags |= (1 << 0); //enable another round
PORTD &= ~(1 << 1); //reset data pin
DDRD |= (1 << 0); //enable clock pin
bit = 0; //reset data bit
TCCR0B &= ~(1 << CS02); //stop timer0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment