Skip to content

Instantly share code, notes, and snippets.

@ricardas
Created December 24, 2012 01:15
Show Gist options
  • Save ricardas/4367002 to your computer and use it in GitHub Desktop.
Save ricardas/4367002 to your computer and use it in GitHub Desktop.
Atmega16: USART
// chip: atmega16
#ifndef F_CPU
#define F_CPU 16000000
#endif
#include <avr/io.h>
#include <util/delay.h>
#define BAUD 9600
#define MYUBRR F_CPU/16/BAUD-1
void USART_init(unsigned int ubrr) {
UBRRH = (unsigned char)(ubrr >> 8);
UBRRL = (unsigned char)ubrr;
UCSRB = 1 << RXEN | 1 << TXEN;
UCSRC = 1 << URSEL | 1 << USBS | 3 << UCSZ0;
}
void USART_transmit( unsigned char data ) {
while(!(UCSRA & (1 << UDRE)));
UDR = data;
}
void USART_transmit_string(const char *data) {
unsigned char c;
while(( c = *data++ )) {
USART_transmit(c);
_delay_ms(10);
}
}
@unis178
Copy link

unis178 commented Nov 6, 2023

#ifndef F_CPU
#define F_CPU 1843200
#endif

#include <avr/io.h>
#include <util/delay.h>

#define BAUD 9600
//#define MYUBRR F_CPU/16/BAUD-1

#define MYUBRR ((F_CPU) / (16 * BAUD)) - 1
//#define MYUBRR (F_CPU) / (16 * BAUD) - 1
//#define MYUBRR F_CPU/16/BAUD-1

// Function to initialize USART0 for 9600 baud rate
void USART0_Init(unsigned int ubrr)
{
// Set baud rate
UBRR0H = (unsigned char)(ubrr >> 8);
UBRR0L = (unsigned char)ubrr;

// Enable transmitter
UCSR0B = (1 << TXEN0);

// Setting frame format (according to data sheet): 8 data bits, 2 stop bit
UCSR0C = (1 << USBS0) | (1 << UCSZ01) | (1 << UCSZ00);

}

// Function to transmit a character over USART0
void USART0_Transmit(unsigned char data)
{
// Wait for the transmit buffer to be empty
while (!(UCSR0A & (1 << UDRE0)));

// Put the data into the transmit buffer
UDR0 = data;

}

// Function to transmit a string over USART0
void USART0_TransmitString(const char* str)
{
while (*str)
{
USART0_Transmit(*str);
_delay_ms(10);
str++;
}
}

/* Function to clear the USART0 transmit buffer
void USART0_ClearTransmitBuffer()
{
while (!(UCSR0A & (1 << UDRE0)))
{
// Read the UDR0 register to clear the buffer
volatile unsigned char dummy = UDR0;
}
}
*/

int main()
{
// Initialize USART0 with a baud rate of 9600
USART0_Init(MYUBRR);

// Transmit the string "Hello, World!"
USART0_TransmitString("Hello, World\r\n");

while (1)
{
	;
}

return 0;

}

this is my code i want to print string on a terminal, but i am getting this o/p
i am getting string along with the some gv values

<00><00><00><00><J€H@�� <00>�a�ƒ�<00><00>����<00>à<00>„À 0!<00><00<00>Hello, World

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