AVR Menu Over Serial

Have you ever wanted to have a “menu” in your AVR that you can interact with over a serial connection? This guide show you exactly how to do it.

STK500 Setup

You should leave your STK500 setup exactly the same as it was setup for the previous guide, AVR USART Serial Communications.

Required Functions

You should already have all of the functions that you need from the previous guide:

  • usart_init()
  • usart_getchar()
  • usart_purchar()
  • usart_pstr()
  • usart_kbhit()

We are going to use these functions to make a menu that processes keyboard hits, and continues to do normal processing in a way that appears to multitask.

All of the work is in our main loop. Here is a psuedocode representation of what this program does:

Putting it All Together

Here is the program listing that accomplishes the above psuedocode. Notice that the only changes from the previous guide are in the main loop.

You can download the complete source code here.

It should compile down to 712 bytes and be ready to download in to your chip.

Once it is downloaded, every time you reset your AVR you should see Ready to rock and roll! printed on screen. If you do not see that, then something is not quite right.

A Note about USART Speed

You might notice that when you hold down SW0 the lights update pretty slowly. This is because each time the lights are updated, the AVR has to send a long string out the USART. Think about how usart_pstr() works. It transmits a single character, then waits for the USART to be ready. This effectively blocks the rest of the program from running until the entire string is printed.

Try a few modifications to this program to see how big of a difference this can make.

  1. Try initializing the USART at 9600 baud instead of 19200 baud. The lights will update much slower. Don’t forget to change the settings in your terminal program or you will get garbage on screen.
  2. Try making your strings that you print to the screen much shorter. Each character that you trim off the string will make the program loop faster.
  3. Try commenting out the usart_pstr() lines for the switches and you should see the loop run at it’s maximum speed. In fact, it runs so fast that you can’t see the lights update at all, they just get a little dimmer. Then when you let go of SW0 there is a random bit pattern displayed. That USART is REALLY slowing us down.

Up Next, printf

In C, there is a function called printf() that is heavily used on computers. Continue on to our next guide to see how to use printf() on your AVR microcontroller.

Or head back to our index of AVR Guides here.

One comment

  • Hi,
    Thanks for this amazing tutorial.

    How can I modify this code to print on lcd and also do you know the ascii code for left,up,right and down arrow key?
    Thank.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.