/* * UART-LF.c * * Created: 29.01.2017 23:43:39 * Author : Petter */ #define F_CPU 3333333UL #define BAUD_9600 ((4UL*F_CPU)/9600) #include #include #include /* In this exercise we will set up and use UART communication. The embedded debugger has a virtual com port that we will use to communicate with the computer. */ void uart_init(unsigned long baud){ //From chapter 24.3 in datasheet PORTB.DIRSET = (1 << PIN2_bp); //Setting up TX pin as output PORTB.OUTSET = (1 << PIN2_bp); //Setting the TX pin high USART0.BAUDH = (baud >> 8); //Shift register right by 8 bits to get the 8 high bits USART0.BAUDL = baud; //Set baud rate without shifting to get the 8 low bits //It turns out the compiler can handle this automatically, meaning this works just as well: //USART0.BAUD = baud; //USART.CTRLC CMODE bits default to async, 1 stop bit, 8 bit character size USART0.CTRLB |= (1 << USART_RXEN_bp) | (1 << USART_TXEN_bp); //Enable RX and TX USART0.CTRLA |= (1 << USART_RXCIE_bp); //Enable interrupts on incoming data } // function to transmit data void uart_transmit(unsigned char data){ //In this function we will be send data. //First we should check that there isn't already data being sent // if there is, we should probably wait for it to finish first while (!(USART0.STATUS & (1 << USART_DREIF_bp))){ //wait for previous transmit to finish }; //Put our new data into se sending register USART0.TXDATAL = data; } int main(void) { //Initialize the UART with our function. //We will be using a baudrate of 9600 (defined as BAUD_9600 at the top of the file) uart_init(BAUD_9600); sei(); //Enable inerrupt, important for anything here to work while (1) { //We don't really need to do anything here. //the ISR will handle receiving. } } //Interrupt service routine for the receiver. ISR(USART0_RXC_vect){ //Read out the received data to a variable uint8_t data = USART0_RXDATAL; //Do things with data: uart_transmit(data + 1); //Example: Shift all characters by one step A -> B, B -> C etc. }