Tutorial: State Machines with C Callbacks

State machine

Many electronics projects involve the device transitioning from one state to another. On a high level, it could be that your project is initially in a state where it awaits input, and once it receives it, it goes to another state where it performs a series of actions, eventually returning back to the initial state. On a lower level, many communications protocols are often simple or increasingly complex state machines. In many cases, an elegantly implemented state machine can simplify your code and make it easier to manage.

There are several methods to implement state machines programmatically starting from simple if-conditions to state variables and switch structures. In this tutorial I’ll cover a slightly more advanced method of using callbacks or “function pointers” as they are implemented in C. This has some performance benefits, makes up for some clean code, and you’ll learn a bit on the way!

State Machines with Conditionals

First, to introduce the idea of a state machine, lets take a simple example: Blinking LEDs. Imagine you want the LED to turn on for a second, and then turn off. We could do it with a simple 2-state machine:

enum states { 

enum states state = LED_OFF;

while(1) {
  if(state == LED_OFF) {
    state = LED_ON;
  } else {
    state = LED_OFF;
  sleep(1); // sleep for a second

If you can understand the code above, you have pretty much grasped the fundamentals of state machines. We have some processing specific to given state, and when we want to go to another state, we use a variable (in this example it’s called state) to do that. And by the way, if you haven’t encountered enum before, you should check out Enumerated type in Wikipedia. It’s a very handful tool to add to your C coding arsenal.
Continue reading Tutorial: State Machines with C Callbacks

Using WinAVR and Command Line for AVR Development


Since my V-USB tutorials became popular, a recurring theme in the comments section have been people who are obviously motivated to try out the tutorial, but due to limited exposure to C language and command-line are either having trouble following my short instructions to compile the example .hex files, or being scared of the command-line, have tried to use AVR Studio instead, and fail.

I have to admit that first I was a bit annoyed by these people – why are they trying to follow a challenging project, when they seemingly have no understanding of how command line, makefiles, C compiler and linking process works? Then, comment by comment, I finally realized that not everyone started coding in the nineties where you launched Windows 3.11 mostly to play Solitaire, and biggest thing in coding productivity was 80×50 text mode which allowed you to have 16-color hacking bliss in your Borland Turbo C++ 3.0 IDE (or RHIDE, after DJGPP came around).

So, instead of either ignoring these people, or spending any more hours answering the same questions, I decided to start a new series of tutorials to cover really basics of getting into AVR development the way I like to do it: Old skool.

Navigating the command line

The bar for command-line wizardry in AVR development is low. There are four levels in it:

  1. Firing up command prompt
  2. Navigating to a directory and viewings its contents
  3. Running commands

The first one is really easy. In Windows 7 you can just click the start button, type “cmd”, and you’re there. Or type “command”, as the Command Prompt is usually the first search hit displayed. More hardcore persons use Win+R (that key with flag symbol finally does something useful!) and type “cmd” into the Run dialog as shown in title image of this post.

Windows Explorer

Once you’ve bitten the blue pill, commanding #2 is also quite easy. First, you need to understand that command prompt is very much like Windows explorer (shown in the above screenshot) – you are always in some directory, and the commands you enter usually work within that directory. In the example above, we are in directory E:\Koodi\AVR\usb_tutorial – let’s try if we can replicate that in command line:
Continue reading Using WinAVR and Command Line for AVR Development

Stellaris Launchpad PWM Tutorial

After receiving my Stellaris Launchpad, I decided to browse the little amount of tutorials there was available on the subject. I was really impressed by the Getting Started hands-on workshop offered in TI’s wiki. After watching the first few tutorials, I had a somewhat firmer grasp on how this little puppy was supposed to be programmed, and the capabilities of the Code Composer Studio IDE.

I got as far as Chapter 4: Interrupts until I hit the first snag: After the Lab4 assignment, the friendly instructor told that as a home assignment, one could try out the PWM (pulse-width modulation) capabilities of the Launchpad before proceeding further. Little did I know how many hours I would spend on that topic! After a solid 8 hours of banging my head against the documentation, Launchpad and CCS (which is prone to hanging at least on my PC), I finally got it working, and decided this would be a great place for a tutorial.

Rule 1 of PWM on Launchpad: There are no PWM units

The initial four hours of my PWM efforts were spent on the StellarisWare Driverlib documentation concerning PWM. In case you haven’t yet watched the tutorials, the Driverlib is essentially a bundle of code that takes away the burden of writing into dozens of control registers, and instead presents the programmer with a couple of hundred API calls to enable a higher-level approach.

It wasn’t until the third hour of googling around that I discovered, that while the timer functionality of the Launchpad includes a PWM mode, there are no actual PWM units on board! So if you’re looking at the PWM functions in Chapter 21 of Stellaris Peripheral Driver Library User’s Guide – stop it and get back to the Chapter 27: Timer functions.

Step 1: Setting up the timer0 PWM mode

So the only PWM functionality the Launchpad supports is the “PWM mode” of the six hardware timers. Thankfully, that’s already quite nice (if I ever find out how to use interrupts with PWM, even better). So unless you already know how the timer system works, now’s a good time to watch the Chapter 4 video which explains it quite nicely. Based on that tutorial, we learn that the following piece of code should initialize the timer for us:


ulPeriod = (SysCtlClockGet() / 10) / 2;
TimerLoadSet(TIMER0_BASE, TIMER_A, ulPeriod - 1);

TimerEnable(TIMER0_BASE, TIMER_A);

Continue reading Stellaris Launchpad PWM Tutorial

DipTrace and PCB manufacture with Olimex

It’s time to wrap up my DipTrace tutorial series with a brief look at how to do Design Rule Check (DRC) with the PCB layout tool, and generate gerber files for board manufacture. Take a look at the previous part on how the board was done.

I chose Olimex PCB prototype service because it’s very inexpensive by itself: 30€ for a two-side 160x100mm euroboard plus 5.50€ for shipping. They also can panel your designs and I counted that 16 ATtiny2313 headers would fit into a single board while still leaving room to cut them apart. Read on what was needed to make sure my PCB design was ready for manufacturing!

Design Rule Check (DRC)

The first thing before ordering was to investigate Olimex requirements for the boards. I knew I had no overlapping drill holes and had taken care to use only drill sizes supported by them (35 and 39 mils), so the most important ones for me were:

  1. At least 8 mils spacing between tracks/pads
  2. At least 8 mils for pads (i.e. 16 mils larger pad than drill hole)
  3. Less than 20 % of area without solder mask
  4. Over 500 drill holes costs a bit extra

Continue reading DipTrace and PCB manufacture with Olimex

Raspberry Pi Serial Console With MAX3232CPE

In addition to the audio, video, network and USB connectors, the Raspberry Pi also has 26 GPIO pins. These pins also include an UART serial console, which can be used to log in to the Pi, and many other things. However, normal UART device communicate with -12V (logical “1”) and +12V (logical “0”), which may just fry something in the 3.3V Pi. Even “TTL level” serial at 5V runs the same risk.

So in this short tutorial, I’ll show you how to use a MAX3232CPE transceiver to safely convert the normal UART voltage levels to 3.3V accepted by Raspberry Pi, and connect to the Pi using Putty. This is what you’ll need:

  • Raspberry Pi unit
  • Serial port in your PC or USB to serial -adapter
  • MAX3232CPE or similar RS-232 to 3.3V logic level transceiver
  • 5 x 0.1 uF capacitors (I used plastic ones)
  • Jumper wires and breadboard
  • Some type of female-female adapter

The last item is needed to connect male-male jumper wires to RaspPi GPIO pins. I had a short 2×6 pin extension cable available and used that, but an IDE cable and other types ribbon cable work fine as well. Just make sure it doesn’t internally short any of the connections – use a multimeter if in doubt!

The connections on Pi side are rather straightforward. We’ll use the 3.3V pin for power – the draw should not exceed 50 mA, but this should not be an issue, since MAX3232CPE draws less than 1 mA and the capacitors are rather small. GND is also needed, and the two UART pins, TXD and RXD.
Continue reading Raspberry Pi Serial Console With MAX3232CPE

USB HID keyboard with V-USB

There still seems to be a lot of traffic to my V-USB tutorials, so I thought I’d write a short follow-up post on USB keyboards. I already did a USB HID mouse post earlier, so you might want to check that out to understand a bit about HID descriptors and associated V-USB settings (in short, human interface devices send a binary descriptor to PC telling what kind of “reports” they send to the host on user activities).

As a basic setup, you’ll need a working V-USB circuit with one switch and one LED attached. Here, I’m using ATtiny2313 with the LED wired to PB0 and switch to PB1. The ATtiny is using 20 MHz crystal, so if you’re following my USB tutorial series and have that circuit at hand, remember to change that frequency in usbconfig.c before trying this out. Note the cool breadboard header I have, there will be more posts about that one to follow soon!
Continue reading USB HID keyboard with V-USB

PCB design with DipTrace

Continuing from part 1 of this ATtiny2313 breadboard header with DipTrace -tutorial, I’ll now go through the PCB design. In DipTrace Schematic Editor, I used File->Convert to PCB (CTRL-B) to get the components and connections exported to PCB Layout tool. Like it’s schematic counterpart, also this tool is quite easy to use.

First I change the grid to 5 mil so each step is half of the 10 mil breadboard hole spacing. I then proceed arrange the components roughly to final layout, and add two 10-pin headers which will plug into breadboard. I then remove some component names which are not sorely needed, and change the location for the remaining ones to the center of the component.

Continue reading PCB design with DipTrace

Simple FAT and SD Tutorial Part 4

In the previous parts of this tutorial, we have built both an FAT library as well as a test program to communicate with the SD card. Now it’s time to wrap it up with final parts of code to read a file from SD card and print it out.

This part will utilize the previously made FAT library with a few tweaks – it turned out that some byte and word-sized values needed explicit casting to unsigned long so that the calculations worked as they should. The new library and all code shown here can be found from the updated project zip.

Initializing the SD card automatically

Instead of manually pressing 1, 2, and 3, we’ll now write a single function to initialize the SD card to SPI mode. For standard SD (not high capacity SDHC) cards, it’s enough to:

  1. Send clock pulses for 80 cycles (“read” 10 bytes)
  2. Send command 0x40 (it should return 1)
  3. Send command 0x41 until it returns 0 (it returns 1 while the card is busy)
  4. Send command 0x50 to set read block size (as well as write block size)

Here’s the code to do just that (sd_sector and sd_pos will be used shortly):
Continue reading Simple FAT and SD Tutorial Part 4

Simple FAT and SD Tutorial Part 3

Finally back! Sorry for taking a while, but getting the SD cards to work required quite a bit of research! In this part of the tutorial, we’ll start talking with the SD card. Once you get that working, adding the FAT library developed in the previous part will be easy.

This tutorial will most likely be the most challenging covered in my blog so far, so beware: You may need to do some troubleshooting on this one! If you encounter problems, I recommend you to ask any questions at the AVR Freaks tutorial forum topic, so more people might be able to help you than just me!

Basic hardware setup: ATmega88 with UART console

The 3.3V UART I covered just a while ago will form the basis for this project. Only change we will be doing is to replace ATtiny2313 with ATmega88. This is because SPI, SD and FAT code will eat up almost 3 kB of program memory, and the ATtiny chips with that much program memory and separate RX/TX and SPI pins are not that common, while ATmega88 is readily available (48 and 168 work as well, of course). To accommodate the new chip, the following hardware changes are made to the ATtiny2313 version:

  • ATmega88 will require two ground connections
  • In addition to VCC, also AVCC for analog circuitry needs to be wired to VCC
  • Additional capacitor between AVCC and GND is recommended (I used 10 uF)
  • Programming header MOSI/MISO/SCK are also in different place

Continue reading Simple FAT and SD Tutorial Part 3

Simple FAT and SD Tutorial Part 2

In the last week’s part 1 of my FAT and SD tutorial, we got as far as reading the file entries in root directory, and peeking into a file with hex editor. Now we’ll cover the file allocation table itself to enable reading longer files, and adapt the code into a small footprint FAT16 library!

File allocation table in FAT16

In the previous part, we learned that the data on a FAT-formatted disk is stored in clusters. In our test image, the cluster size was 32 sectors, i.e. 16 kiB (16 384 bytes). Let’s imagine a newly formatted disk with 100 free clusters, with the clusters numbered from 2 (the first cluster at the beginning of data area) to 101 (the very last cluster). Now let’s copy some files there:

File operation File allocation
Copy HAMLET.TXT (193 082 bytes) to disk Clusters 2-13 allocated for the file (196 608 bytes)
Copy README.TXT (353 bytes) to disk Cluster 14 allocated for the file
Create SUBDIR on disk Cluster 15 allocated for the directory file entries
Create 1.TXT in SUBDIR Cluster 16 allocated for the file, a new file entry written to SUBDIR (beginning of cluster 15)

Continue reading Simple FAT and SD Tutorial Part 2