2017-09-25 23:35:01 +02:00

126 lines
2.5 KiB
C

/*
* uart.c
*
*/
#include "uart.h"
char uartReceiveBuffer[UART_RECV_BUFFER_SIZE];
void uart_init() {
#if defined (__AVR_ATmega8__)
// enable receive and transmit
UCSRB |= (1 << RXEN) | (1 << TXEN);
// set frame format
//Set data frame format: asynchronous mode,no parity, 1 stop bit, 8 bit size
UCSRC=(1<<URSEL)|(0<<UMSEL)|(0<<UPM1)|(0<<UPM0)|(0<<USBS)|(0<<UCSZ2)|(1<<UCSZ1)|(1<<UCSZ0);
//UCSRC |= (1<<URSEL)|(3<<UCSZ0); // async 8n1
// set baud rate
UBRRH = UBRR_VAL >> 8;
UBRRL = UBRR_VAL & 0xFF;
#elif defined (__AVR_ATmega168P__)
// enable receive and transmit
UCSR0B = (1<<RXEN0)|(1<<TXEN0);
// set frame format
// UCSR0C = ((1<<UCSZ01)|(1<<UCSZ00))&(0<<USBS0); // 8n1
UCSR0C = (1<<UCSZ01)|(1<<UCSZ00); // 8n2
// set baud rate
UBRR0H = UBRR_VAL >> 8;
UBRR0L = UBRR_VAL;
#else
# if !defined(__COMPILING_AVR_LIBC__)
# warning "device type not defined"
# endif
#endif
}
// ======================= SEND =======================
void uart_sendChar(char c) {
#if defined (__AVR_ATmega8__)
while (!(UCSRA & (1<<UDRE)));
UDR = c;
#elif defined (__AVR_ATmega168P__)
while (!(UCSR0A & (1<<UDRE0))) {}
UDR0 = c;
#else
# if !defined(__COMPILING_AVR_LIBC__)
# warning "device type not defined"
# endif
#endif
}
void uart_sendInt(int c) {
char m[7];
itoa(c,m,10);
uart_sendString(m);
}
void uart_sendBinary(int c) {
char m[7];
itoa(c,m,2);
uart_sendString(m);
}
void uart_sendHex(int c) {
char m[7];
itoa(c,m,16);
uart_sendString(m);
}
void uart_sendString(char *s) {
while (*s != '\0') {
uart_sendChar(*s);
s++;
}
}
void uart_sendLF() {
uart_sendChar('\n');
}
// ======================= RECEIVE =======================
char uart_receiveChar() {
#if defined (__AVR_ATmega8__)
while (!(UCSRA & (1<<RXC)));
return UDR;
#elif defined (__AVR_ATmega168P__)
while ( !(UCSR0A & (1<<RXC0)) );
return UDR0;
#else
# if !defined(__COMPILING_AVR_LIBC__)
# warning "device type not defined"
# endif
#endif
}
char* uart_receiveString() {
char nextChar;
char stringLen = 0;
char *startPtr = uartReceiveBuffer;
char *bufferPtr = uartReceiveBuffer;
nextChar = uart_receiveChar();
while( nextChar != '\n' && nextChar != '\0' && stringLen < UART_RECV_BUFFER_SIZE - 1 ) {
*(bufferPtr++) = nextChar;
stringLen++;
nextChar = uart_receiveChar();
}
*bufferPtr = '\0';
return startPtr;
}