SinelaboreRT Header Logo


As simple as possible, but not any simpler!

User Tools

Site Tools


Getting started with the PIC16F18446 and State Machines

This tutorial explains the use of state machines with the PIC16F18446 Curiosity Nano board. It provides 2k of RAM and 16k program memory. More than enought for this small tutorial.

(Source: Microchip)

Install the required software if you want to follow all steps yourself. Otherwise just go on reading.

For this tutorial we will use just the push botton and the LED on the board. So you can follow it without any additional hardware required. The LED shall blink all the time. The frequency can be changed from slow to fast by pressing the button. Simple enough but sufficient to show all the key concepts we are going to use.

The PINs are allocated using the MPLAP X IDE Resource Manager as well as the 4MHz system clock and the 10ms Timer0. I've not used this configurator before. But have to say that it is a very convinient way to setup the hardware. I would wish to have the same for the MSP430 μCs I also often use.

Step 1 - Deciding the system architecture

For small systems e.g. sensor nodes it is usually sufficient use a main loop design. The main loop cycles endlessly and waits for events. Events are benefitially stored in an event queue. The queue is filled from timer events, other state machines (cooperating machines) or interrupt handlers. If events are available the state machine(s) are called from the main loop to process them.

In our little example events are sent from the keyboad interrupt and from a software timer module which is called regulary from the cyclic hardware timer. The following figure shows the system architecture.

The below code snippets show the irq handlers and the main loop processing the evens.

// cyclic timer interrupt
void TMR0_IRQHandler(void){
    tick(); // if a timer has fired this function stores a timer event in the message queue
// keyboard interrupt
void SW0_IRQHandler(void){
void main(void){
    while (1)
        do {
            // check if there are one or more events in the queue.
            // if yes, process all events in the state machine
            retVal = fifoGet(&fifo, &bufVal);
            if (retVal != QUEUE_EMPTY) {
                sm(&instData, bufVal);
        } while (retVal != QUEUE_EMPTY);

In the library folder (see project tree below) the required timer and fifo files are provided. They can easily reused also with other Controller types. I used them in several MSP430 projects before.

Step 2 - Realizing the state machine

So far we have not seen how the state machine looks like. To realize this simple job just two evens are reqired. - evKey: Indicates that the user pressed the switch - evTimeout: Indicating that it is time to toggle the LED

For this simpel state machine the editor which is built into the code generator is sufficient. For more complex machines is is recommended to use an advanced UML modelling tool of your choice. See the list of supported tools here. The next figure shows the complete state machine:

Initally the state machine enters the state Slow. The initial transition triggers the start of the timer with timeout time 10U (10U represents 10 times the base clock of the hardware interrupt (i.e. 100ms)). Then the machine waits for further events. Every time event evTimeout occures there is a self transition and as action the LED is toggeled.

In case evKey occures a state transitions from state Slow to state Fast and vice versa is triggered and the timeout time is updated.

Example action code for the transition going from state Slow to state Fast.

timerStart(timer_id, 10U);

Step 3 - Integrating the state machine in MPLAB X

The generated state machine code files can be easily added to the PIC project. It is recommended to create a new folder e.g. called state_machine_generated_files. All state machine related files go in there. sm.scc contains the state machine model. sm.c/h contains the generated state machine code.

The following figure shows the project tree with all generated files.

To convienently edit the state machine model and generate code from it two batch files were created. Call edit.bat to start up the editor. And call gen.bat to generate the code. The generated files start all with the prefix sm_ (see command line). The output when calling gen.bat is shown below.

C:\Users\PM\develop\microchip\blink.X\state_machine_generated_files>java -Djava.ext.dirs=C:\Users\PM\Desktop\sinelaborert\bin\ -jar C:\Users\PM\Desktop\sinelaborert\bin\codegen.jar -p ssc -l cx -o sm sm.scc
Starting robustness tests of state machine ...
State names: ..............
Machine hierarchy: ........
Machine height = 1
Transitions: ..............
Default states: ...........
Final states: .............
Choices: ..................
No. of children in composites: ...
Connectivity of states: ...

The code generator needs a configuration file to set basic parameters. Take a look into the configuration file and read the Manual if the meaning of the parameters is not clear.


The chosen system architecture with state machines, an event queue and software timers is very powerful. It is proven in praxis since many years and used sucessfully in many projects. Quite complex systems can be built this way and no RTOS is requrid. It can be expaned easily by adding additional state machines and by using more than one software timer.

Use the example and expand it to learn. To receive a copy just send a mail.

Hope you like the tutorial

Have fun


This website uses cookies. By using the website, you agree with storing cookies on your computer. Also you acknowledge that you have read and understand our Privacy Policy. If you do not agree leave the website.More information about cookies

Leave your comments

, 2022/03/24 19:01, 2022/03/24 19:05
Hello Jonathan,

There are different possibilities. The most flexible is probably that you use a simple event queue per state machine. Then you check for each queue in the main loop if there is an event and then call the corresponding state machine.

An example of this approach is shown here:
The code example starts at "Weaving the state machines and the library part together”.

A simple implementation of a queue is also available on this page further down in the “lib” folder of the download. Or alternatively here:

If your machine has only view events (e.g. an irq handler implemented as SM) you can also instruct the code generator to generate the events represented as bits in a bitfield. Then a simple variable can store the events (bit set) for your state machine. But I think the queue based design is much more flexible. The relevant configuration parameter in the config file is: EventsAreBitCoded=yes

I send you the MPLAB files by separate mail.

Best regards,
, 2022/03/24 19:01, 2022/03/24 19:02
I am evaluating your code generator for use with PIC24 controllers. I saw in Getting started with the PIC16F18446 and State Machines that you said "Use the example and expand it to learn. To receive a copy just send a mail."

Would it be possible to send me the MPLAB project for an example?

Also, I have a question about having several State Machines in the main loop. Do I have to worry about events being consumed by the wrong SM? How do I handle passing events to the correct SM?

Best Regards,
Jonathan Baize
wiki/examples/pic_tutorial.txt · Last modified: 2022/08/17 17:43 by pmueller

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki