Programming: Creating a Function from Existing Code (Specifically for Initializing UART/USART)
Share
A function can be created from existing code, as seen in this example. Surround the code with {} braces. Above the braces, add the function return type (if no return type, use void) followed by the function name and then add parameters within the parentheses(). The code may need to change is there are parameters and there may need to be a return if there is a return type included in the function declaration.
#ifndef UARTInit #define UARTInit #define EVEN 0 #define ODD 1 #include #include void InitializeUART0(int baud, char AsyncDoubleSpeed, char DataSizeInBits, char ParityEVENorODD, char StopBits) { uint16_t UBBRValue = lrint(( F_CPU / (16L * baud) ) - 1); //setting the U2X bit to 1 for double speed asynchronous if (AsyncDoubleSpeed == 1) UCSR0A = (1 << U2X0); //Put the upper part of the baud number here (bits 8 to 11) UBRR0H = (unsigned char) (UBBRValue >> 8); //Put the remaining part of the baud number here UBRR0L = (unsigned char) UBBRValue; //Enable the receiver and transmitter UCSR0B = (1 << RXEN0) | (1 << TXEN0); //Set 2 stop bits if (StopBits == 2) UCSR0C = (1 << USBS0); if (ParityEVENorODD == EVEN) UCSR0C |= (1 << UPM01); //Sets parity to EVEN if (ParityEVENorODD == ODD) UCSR0C |= (3 << UPM00); //Alternative way to set parity to ODD if (DataSizeInBits == 6) UCSR0C |= (1 << UCSZ00); //6-bit data length if (DataSizeInBits == 7) UCSR0C |= (2 << UCSZ00); //7-bit data length if (DataSizeInBits == 8) UCSR0C |= (3 << UCSZ00); //8-bit data length if (DataSizeInBits == 9) UCSR0C |= (7 << UCSZ00); //9-bit data length }