Blog

May 20, 2013 | Circuits |

Serial Communications with the ATmega168

The first thing you do when you learn a new programming language or platform is to write a "hello world" application. This requires something like a "printf" function. That's not so straightforward when it comes to microcontrollers - where will the output of the "printf" go? That's where serial communications come in. Arduino users have it easy - they just need to use Serial.print(). But the situation is not so bad if you are using a standalone microcontroller - just choose a chip like ATmega168 which has USART - hardware support for serial communications.

The code needed to transmit serial data is very simple, and the datasheet has most of what you need:

Here is the schematic of a simple setup that will let you send debug data (strings) from an ATmega168 to your computer. If you are completely new to AVR programming, I recommend that you read Hackaday's tutorial on the subject. Note how the TX/RX lines are flipped when you connect it from the ATmega168 to the FTDI adapter.

A few things to remember in order to for this to work correctly (the Makefile in the GitHub link below takes care of all this):

  • For getting a 9600 baud rate, the chip needs to run at 8 MHz, and for this, you need to unset the  CKDIV8 fuse.
  • For full sprintf formatting support, some additional flags are needed in the linker.

 

 

Here is a photo of the setup that I used:

 

 

Here is what the output looks like on CoolTerm, a serial monitor that I use on my Mac:

 

 

Having a "printf" function is very handy for debugging your projects - so choose a chip that will let you support this functionality without too much pain.

Downloads

Here is all the code used in this project - do pay attention to the flags in the Makefile.

https://github.com/electronut/atmega168-serial-hello

 

 

 


Questions/Comments

We love hearing from our readers. Email us at info@electronut.in for questions or comments on this article. If you found this article useful, please support us by buying some of our Open Source hardware products - like ZeroDriver - an Arduino Zero compatible motor driver for robotics. ZeroDriver is crowdfunding right now. Please click here to support our campaign. and bring this product to market!


Please sign up for updates

Once in a while, we will send you an email update on the latest Electronut Labs projects and products. Your email address will never be shared or abused, ever.

2016 Electronut Labs. All rights reserved.