In the previous tutorial, we have deployed our model on the STM32. We successfully run inference to predict the output of the NAND gate, and the output was sent to serial terminal.

In this tutorial, we are going to add an LED and two buttons. We are going to use the LED for NAND’s output and buttons for NAND’s inputs.

LED and Button Circuit

The circuit for LED and buttons is very simple. The following schematic shows the circuit.

Firstly, the LED circuit is an active high circuit. Therefore, a logic high from the STM32’s GPIO turns the LED on, and vice versa. Secondly, the buttons circuit is an active low circuit. It uses internal pull-up resistors. Therefore, the STM32’s GPIO receives a logic high, when the button is not pressed.

I use prototype shield stacked on top of the NUCLEO-F446RE board. I use a 5 mm orange diffused LED and two DPDT switches.

Modifying the Project

We need three GPIO pins, one as output for LED, and the others as input for buttons. We are going to use the project file created in the previous tutorial.

Open the previous STM32CubeMX project. On the Pinout view tab, firstly, right click on PA0, and set it as GPIO_Output. Secondly, right click on PA8 and PB10, and set them as GPIO_Input.

After that, click on the System view tab.

On the System view tab, click the GPIO button, and then enable pull-up resistors for PA8 and PB10.

Finally, click the GENERATE CODE button to generate the code.

Writing Code for LED and Buttons

Now, we have the code generated. Let’s start writing the code for LED and buttons!

We just need to modify the code within the MX_X_CUBE_AI_Process() function. The rest of the functions are remain the same. The following listing shows the MX_X_CUBE_AI_Process() function:

Let’s take it one step at a time.

Firstly, in line 10-11, they read the buttons state. When the button is pressed, the state will be zero or GPIO_PIN_RESET. Subsequently, we set the in_data value to be one, and vice versa.

Secondly, in line 12, we run the inference process by calling the aiRun() function.

Thirdly, in line 13-16, they round the prediction output. Subsequently, they turn on or off the LED. If the prediction output is equal to one the the LED will be on, and vice versa.

Finally, in line 25, we add a delay of one second. The rest of the codes are remain the same as in the previous project.


Build the project, and then download it into the STM32. The end result looks like this:


This tutorial was meant to give you a hands-on course on how to build a simple neural network model using keras, deploy it on STM32, and add several peripherals. Although neural network is not necessarily required for implementing a logic gates, the point is that you know how to use the tools and frameworks, such as Keras, STM32Cube.AI, STM32CubeMX, and STM32CubeIDE.

Leave a Reply

Close Menu