Skip to content

Instantly share code, notes, and snippets.

@guigaoliveira
Last active October 24, 2019 14:04
Show Gist options
  • Save guigaoliveira/74580d14b33c1ec2b6ae852651098e35 to your computer and use it in GitHub Desktop.
Save guigaoliveira/74580d14b33c1ec2b6ae852651098e35 to your computer and use it in GitHub Desktop.
#include <avr/io.h>
#include <util/delay.h>
#define F_CPU 16000000UL
void mySerialBegin(int baudRate) {
UCSR0B |= (1 << RXEN0) | (1 << TXEN0); // Turn on the transmission and reception circuitry
UCSR0C |= (1 << UCSZ00) | (1 << UCSZ01); // Use 8-bit character sizes
UBRR0H = (baudRate >> 8); // Load upper 8-bits of the baud rate value into the high byte of the UBRR register
UBRR0L = (((F_CPU / (baudRate * 16UL))) - 1); // Load lower 8-bits of the baud rate value into the low byte of the UBRR register
}
char mySerialRead() {
char ReceivedByte;
while ((UCSR0A & (1 << RXC0)) == 0) {}; // Do nothing until data have been received and is ready to be read from UDR
ReceivedByte = UDR0; // Fetch the received byte value into the variable "ByteReceived"
return ReceivedByte;
}
void mySerialPrint(char data) {
while ((UCSR0A & (1 << UDRE0)) == 0) {}; // Do nothing until UDR is ready for more data to be written to it
UDR0 = data; // Echo back the byte back to the computer
}
void mySerialPrintln(char data) {
mySerialPrint(data);
mySerialPrint('\n');
}
int main(void)
{
char ReceivedByte;
mySerialBegin(9600);
for (;;) // Loop forever
{
ReceivedByte = mySerialRead();
mySerialPrintln(ReceivedByte);
}
}
@alexandrelourival
Copy link

#include <avr/io.h>
#include <util/delay.h>
#define BAUD_RATE 9600
#define BAUD_PRESCALE (((F_CPU / (BAUD_RATE * 16UL))) - 1)

void mySerialBegin(int baudRate) {
UCSR0B |= (1 << RXEN0) | (1 << TXEN0); // Turn on the transmission and reception circuitry
UCSR0C |= (1 << UCSZ00) | (1 << UCSZ01); // Use 8-bit character sizes

UBRR0H = (BAUD_PRESCALE >> 8); // Load upper 8-bits of the baud rate value into the high byte of the UBRR register
UBRR0L = BAUD_PRESCALE; // Load lower 8-bits of the baud rate value into the low byte of the UBRR register
}

char* mySerialRead() {
loop_until_bit_is_set(UCSR0A, RXC0); /* Wait until data exists. */
return UDR0;
}

void mySerialPrint(char* data) {
for (int i = 0; i < strlen(data); i++){
UDR0 = data[i];
loop_until_bit_is_set(UCSR0A, TXC0); /* Wait until transmission ready. */
}
}

void mySerialPrintln(char data) {
mySerialPrint(data);
mySerialPrint('\n');
}

int main(void)
{
char* ReceivedByte;
mySerialBegin(9600);
for (;;) // Loop forever
{
ReceivedByte = mySerialRead();
mySerialPrint(ReceivedByte);
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment