Archive for the ‘code’ Category

AVR, UART C++ example…

02-03-2007

Some people came here from Google, looking for “avr example”. I’m playing with Atmega88 for a few days, because I’m thinking about simple motorcycle alarm.

Normally when I get new microcontroller I’m programming UART to get some readable debug output. It (probably) won’t be needed in final version of device – I don’t want MAX232 to consume power and I may have not enough memory to append extra debug code. (situation with not enough memory would be a nightmare, but it’s still possible – UART and Debug classes aren’t very big, but const strings with debug output may consume a lot) Anyway it’s good idea to get UART working at the very beginning.

Of course you know that you may set your house on fire or brake your leg because of my ideas or software I developed. I’ve got both legs straight and they seem to be all right, but it doesn’t prove anything. I’ve heard that probability of train appearing over your head (3..2..1..now) doesn’t equal zero. So, you’ve been warned.

I’ve written a post about avr and interrupts in c++ about three weeks ago. There was an example of defining interrupt routine as a friend of class. I’ve implemented C_UART class methods and added C_Debug class.

You can get sources here.

Directories and files:

  • Devs
    • debug.h, debug.cpp – debug device, defines operator <<
    • devs.h, devs.cpp – devices namespace
  • Periphs
    • uart.h, uart.cpp – uart peripheral class and interrupt routines
    • periphs.h, periphs.cpp – peripherals namespace

After including files with namespaces in main.cpp:
Debug<<"Hello World!\n"<<"uiTest = "<<123<<"\n";

Remember that there is no memory copying, so there is no hidden buffers – when you’re using this debug output microcontroller waits until all data is sent.
You have to change UBRR0H/L definitions in uart.h. They’re correct for baud rate 9600 when clock is ~8.8MHz. You may find proper values in ATmega88 datasheet.

Makefile is based on some example from AVRFreaks, I’ve just modified it to compile C++ code, added some dependencies and run statement. You may compile this project using WinAVR under Windows or anyhow under Linux.

After “$ make all” and “$ make run” you should get something like this (terminal – 9600/8/1):

Hello World!
uiTest = 123

That’s all folks :-).

Thanks to Patrys for hosting my files.