Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Serial.c
- *
- * Created: 18/10/2019 18:14:50
- * Author : Leonardo Lisa
- */
- #define F_CPU 16000000UL
- #define BAUD 9600
- #define MAX_BUFFER_LENGTH 64
- #define USART_RX_MAX_BUFFER_LENGTH 20
- #define BRC ((F_CPU/16/BAUD) - 1)
- #include <avr/io.h>
- #include <stdlib.h>
- #include <avr/eeprom.h>
- void USART_Begin(unsigned int brc)
- {
- // Set baud rate.
- UBRR0H = (brc >> 8);
- UBRR0L = brc;
- // Enable receiver and transmitter with their interrupt.
- UCSR0B |= (1 << TXEN0) | (1 << TXCIE0) | (1 << RXEN0) | (1 << RXCIE0);
- // Set frame format yo 8bit data.
- UCSR0C = (1 << UCSZ01) | (1 << UCSZ00);
- }
- // Send one byte.
- void USART_Transmit(unsigned char data)
- {
- /* Wait for empty transmit buffer */
- while (!(UCSR0A & (1<<UDRE0)));
- /* Put data into buffer, sends the data */
- UDR0 = data;
- }
- // Receive one byte.
- unsigned char USART_Receive(void)
- {
- /* Wait for data to be received */
- while (!(UCSR0A & (1<<RXC0)));
- /* Get and return received data from buffer */
- return UDR0;
- }
- void USART_Transmit_Buffer(char *buffer)
- {
- char error_message[] = "ERROR: Empty message or null pointer\n";
- // Get message length.
- if (buffer == NULL)
- {
- buffer = error_message;
- }
- // Print buffer message.
- for (uint8_t size = 1; *buffer != '\0' && size != MAX_BUFFER_LENGTH; size++, buffer++)
- {
- USART_Transmit(*buffer);
- }
- }
- void *USART_Receive_Buffer(void)
- {
- // Allocate n. byte for the message buffer + one byte for '\0' termination character.
- char *buffer = calloc((USART_RX_MAX_BUFFER_LENGTH + 1), 8);
- char *tmp_buffer = buffer;
- if (buffer == NULL)
- {
- return NULL;
- }
- for (uint8_t size = 1; size < USART_RX_MAX_BUFFER_LENGTH; size++, buffer++)
- {
- *buffer = USART_Receive();
- if (*buffer == '\0')
- {
- if (size == 1)
- {
- free(buffer);
- return NULL;
- }
- return realloc(tmp_buffer, size);
- }
- }
- // buffer++;
- // *buffer = '\0'; (remember that '\0' == 0).
- // Not necessary because calloc have already cleared the allocated memory to zero.
- return tmp_buffer;
- }
- int main(void)
- {
- // Same as write: char message[]{'S','e','r','i','a','l',' ','O','N','\n'};
- // Compiler place '\0' at the end of the string.
- char message[] = "Serial On\n";
- // No '\0' character at the end of the string. DANGEROUS!
- char message2[] = {'1','2','3','4','5'};
- char *temp;
- USART_Begin(BRC);
- USART_Transmit_Buffer(message);
- USART_Transmit_Buffer(message2);
- while (1)
- {
- temp = USART_Receive_Buffer();
- USART_Transmit_Buffer(temp);
- // IMPORTANT! Clean your memory.
- free(temp);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement