Advertisement
igendel

TinyTX - ATtiny85 Serial Transmitter Example

Feb 17th, 2015
1,680
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.13 KB | None | 0 0
  1. // Serial Transmission Example for the ATtiny85
  2. // by Ido Gendel, 2015
  3. // Share and enjoy!
  4.  
  5. // Make sure system clock is 16MHz
  6. #define F_CPU 16000000UL
  7.  
  8. #include <avr/io.h>
  9. #include <util/delay.h>
  10. #include <avr/interrupt.h>
  11.  
  12. volatile struct {
  13.   uint8_t dataByte, bitsLeft,
  14.           pin, done;   
  15. } txData = {0, 0, 0, 0};
  16.  
  17. //---------------------------------------------------------
  18. void sendBySerial(const uint8_t data) {
  19.  
  20.   txData.dataByte = data;
  21.   txData.bitsLeft = 10;
  22.   txData.done = 0;
  23.   // Reset counter
  24.   TCNT0 = 0;
  25.   // Activate timer0 A match interrupt
  26.   TIMSK = 1 << OCIE0A;
  27.  
  28. } // sendBySerial
  29.  
  30. //---------------------------------------------------------
  31. // Blocking
  32. void sendStrBySerial(char *p) {
  33.  
  34.   while (*p != '\0') {
  35.     sendBySerial(*p++);
  36.     while (!txData.done);
  37.   } // while
  38.  
  39. } // sendStrBySerial
  40.  
  41. //---------------------------------------------------------
  42. void initSerial(const uint8_t portPin) {
  43.  
  44.   txData.pin = portPin;
  45.   // Define pin as output
  46.   DDRB = 1 << txData.pin;
  47.   // Set it to the default HIGH
  48.   PORTB |= 1 << txData.pin;
  49.   // Set top value for counter 0
  50.   OCR0A = 26;
  51.   // No A/B match output; just CTC mode
  52.   TCCR0A = 1 << WGM01;
  53.   // Set prescaler to clk/64
  54.   TCCR0B = (1 << CS01) | 1 << (CS00);
  55.  
  56. } // initSerial;
  57.  
  58. //---------------------------------------------------------
  59. int main(void) {
  60.    
  61.   char myStr[] = "Hello Tiny Serial!";
  62.    
  63.   initSerial(PB0);
  64.   // Enable interrupts
  65.   sei();
  66.    
  67.   while(1) {
  68.     _delay_ms(5000);
  69.     sendStrBySerial(myStr);  
  70.     sendBySerial(10); // new line
  71.   }
  72.  
  73. } // main
  74.  
  75. //---------------------------------------------------------
  76. // Timer 0 A-match interrupt
  77. ISR(TIMER0_COMPA_vect) {
  78.  
  79.   uint8_t bitVal;
  80.  
  81.   switch (txData.bitsLeft) {
  82.    
  83.     case 10: bitVal = 0; break;
  84.     case  1: bitVal = 1; break;
  85.     case  0: TIMSK &= ~(1 << OCIE0A);
  86.              txData.done = 1;
  87.              return;
  88.  
  89.     default:
  90.       bitVal = txData.dataByte & 1;
  91.       txData.dataByte >>= 1;
  92.        
  93.   } // switch
  94.  
  95.   if (bitVal) PORTB |= (1 << txData.pin);
  96.    else PORTB &= ~(1 << txData.pin);
  97.   --txData.bitsLeft;
  98.  
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement