Hi, I am currently trying to use the USART to communicate with my linux machine (for now just debugging messages, later for sending instructions to the arduino) in c without the abstraction of the arduino IDE (for learning purposes). This is my code so far, trying to get some communication going:
#include "registers.h"
#define Biton(reg, bit) *reg |= (1 << bit)
#define Bitoff(reg, bit) *reg &= ~(1 << bit)
#define Readbit(reg, bit) (*reg & (1 << bit))
#define BAUD 9600
void
initSerial ()
{
// set baud rate to 9600
*UBRR0L = (F_CPU / 8 / BAUD - 1) / 2;
*UBRR0H = ((F_CPU / 8 / BAUD - 1) / 2) >> 8;
// enable transmission and reception
Biton (UCSR0B, RXEN0);
Biton (UCSR0B, TXEN0);
// enable interrupt on RX complete
//Biton (UCSR0B, RXCIE0);
// enable interrupt on Data register empty
//Biton (UCSR0B, UDRIE0);
// enable asynchonus mode
Bitoff (UCSR0C, UMSEL00);
Bitoff (UCSR0C, UMSEL01);
// disable parity mode
Bitoff (UCSR0C, UPM00);
Bitoff (UCSR0C, UPM01);
// diable 2 stop bits
Bitoff (UCSR0C, USBS0);
// set data length to 8 bits
Bitoff (UCSR0B, UCSZ02);
Biton (UCSR0C, UCSZ00);
Biton (UCSR0C, UCSZ01);
// double transmission speed
Biton (UCSR0A, U2X0);
}
unsigned char
serialRead ()
{
volatile char cStopCompilerFromOptimizing;
while (!Readbit (UCSR0A, RXC0))
{
cStopCompilerFromOptimizing++;
}
return *UDR0;
}
void
serialWrite (unsigned char c)
{
volatile char cStopCompilerFromOptimizing;
while (!Readbit (UCSR0A, UDRE0)) // flag that is set when transmit buffer is
// empty and ready for new
{
cStopCompilerFromOptimizing++;
}
*UDR0 = c;
}
void setup() {
initSerial();
}
void loop() {
serialWrite('H');
serialWrite('e');
serialWrite('l');
serialWrite('l');
serialWrite('o');
serialWrite('!');
serialWrite('\n');
}
registers.h contains only define statements for register and byte names like this:
#define PORTB ((volatile unsigned char *)0x25)
I wrote it before I discovered avr/io.h.
Then I use to arduino cli (arduino-cli monitor -p /dev/ttyACM0)to get a serial monitor, so i can first can focus on the arduino side and then implement something on my computer, but i get only unprintable chars like this:
}�R�yv(2RPZ_�D�"RPZ]�D�:#4:��@c<#���
When i try to use my serialRead() it weirdly only works when i remove the NOT in the while loop(and use Serial.begin(9600)).
I am using a arduino uno.
Thanks for any help getting this to work.