/* * UART-LF.c * * Created: 29.01.2017 23:43:39 * Author : Petter */ #define F_CPU 3333333 #define BAUD_9600 4*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. */ #define TX_PORT PORTB #define TX_PIN 0 void uart_init(unsigned long baud){ //From chapter 22.3.1 in datasheet TX_PORT.OUTSET = (1 << TX_PIN); //Setting up TX pin as output TX_PORT.DIRSET = (1 << TX_PIN); //Setting up TX pin as output //Set baud rate register USART3.BAUDL = (uint8_t) baud; //Set baud rate without shifting to get the 8 low bits USART3.BAUDH = (uint8_t)(baud >> 8); //Shift register right by 8 bits to get the 8 high bits //USART.CTRLC CMODE bits default to async, 1 stop bit, 8 bit character size //Since all bits are default 0 we only need to change the character size part USART3.CTRLC = (0x3 << USART_CHSIZE0_bp); //Enable RX and TX USART3.CTRLB = (1 << USART_RXEN_bp) | (1 << USART_TXEN_bp); //Enable interrupts on incoming data USART3.CTRLA |= (1 << USART_RXCIE_bp); } // function to transmit data void uart_transmit(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 (!(USART3.STATUS & (1 << USART_DREIF_bp))){ //wait for previous transmit to finish }; //Put our new data into tx data register USART3.TXDATAL = data; } //To send a string we can do this void uart_transmit_string(char* data) { while (*data != '\0') { uart_transmit(*data); 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. uart_transmit_string("Dette er en test\n"); _delay_ms(200); } } //Interrupt service routine for the receiver. ISR (USART3_RXC_vect) { //In the interrupt we will read the data in the receive buffer //First we should check that new data has arrived the receive buffer while (!(USART3.STATUS & (1 << USART_RXCIF_bp))){ //wait for previous transmit to finish }; //Store the data in a temporarily variable uint8_t tmp = USART3.RXDATAL; }