Operácie

Serial.c

Zo stránky SensorWiki

Verzia z 14:38, 24. január 2013, ktorú vytvoril StudentDVPS (diskusia | príspevky) (Vytvorená stránka „→‎*************************************************************************: : /* Descri...“)
(rozdiel) ← Staršia verzia | Aktuálna úprava (rozdiel) | Novšia verzia → (rozdiel)

/* ************************************************************************* */ /* */ /* Description  : UART communication routines */ /* Based on AppNote AVR109 - Self-programming */ /* */ /* FileName  : serial.c */ /* */ /* ************************************************************************* */

  1. include <avr\io.h>

// Following calculation assumes that F_CPU is assigned in 'Project/Options'

  1. define BAUDRATE 4800
  2. define BAUD_PRESCALE (((F_CPU / (BAUDRATE * 16UL))) - 1)


/* definitions for UART control */

                                       // Valid for ATmega328
  1. define BAUD_RATE_REG UBRR0 //
  2. define UART_STATUS_REG UCSR0A // OK, checked (but also control reg.)
  3. define UART_CONTROL_REG_B UCSR0B // OK, checked
  4. define UART_CONTROL_REG_C UCSR0C // Added for mode setting
  5. define ENABLE_TRANSMITTER_BIT TXEN0 // OK, checked
  6. define ENABLE_RECEIVER_BIT RXEN0 // OK, checked
  7. define DATA_REGISTER_EMPTY_BIT UDRE0 // Added, for possible speed-up
  8. define TRANSMIT_COMPLETE_BIT TXC0 // OK, checked
  9. define RECEIVE_COMPLETE_BIT RXC0 // OK, checked
  10. define UART_DATA_REG UDR0 // OK, checked


void inituart(void) {

BAUD_RATE_REG = (unsigned char)BAUD_PRESCALE;    // Set baud rate: Load the UBRR register
UART_CONTROL_REG_B = (1 << ENABLE_RECEIVER_BIT)|
                   (1 << ENABLE_TRANSMITTER_BIT); // Enable receive + transmit 
UART_CONTROL_REG_C = (3<<UCSZ00);                 // Added: Async. UART, None 
                                                  // Parity, 8-data, 1 stopbit
                                                  

}


void sendchar(unsigned char c) {

 UART_DATA_REG = c;                                   // prepare transmission
 while (!(UART_STATUS_REG & (1 << TRANSMIT_COMPLETE_BIT)));// wait until byte sendt
 UART_STATUS_REG |= (1 << TRANSMIT_COMPLETE_BIT);          // delete TXCflag

}


unsigned char recchar(void) {

 while( !(UART_STATUS_REG & (1 << RECEIVE_COMPLETE_BIT)) );  // wait for data
 return UART_DATA_REG;

}