lesson 01 interlude - CircuitPython versus C
posted: Thu, Jun 15, 2023 | tagged: projects dev electronics fec
return to project home | resources
By way of a counter point, below is code for a typical LED blink program. One is built in low level C, the other is built in CircuityPython. Note, the C version takes advantage of a number of helper libraries as well.
blink in CircuitPython
# Import libraries
import board
import digitalio
import time
# Initialize variables
sleepTime = 0.75 # controls duration of sleep between blinks
# Initialize LED (connected to GP20) object and set direction
led = digitalio.DigitalInOut(board.GP20)
led.direction = digitalio.Direction.OUTPUT
# Loop infinitely and alter LED state with sleep between state changes
while True:
led.value = True
time.sleep(sleepTime)
led.value = False
time.sleep(sleepTime)blink in C
#include "stm32f0xx.h"
#include "stm32f0xx_nucleo.h"
int main(void)
{
HAL_Init();
// LED clock initialization
LED2_GPIO_CLK_ENABLE();
//Initialize LED
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.Pin = LED2_PIN;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(LED2_GPIO_PORT, &GPIO_InitStruct);
for(;;) {
// Toggle LED2
HAL_GPIO_TogglePin(LED2_GPIO_PORT, LED2_PIN);
HAL_Delay(400); // Delay 400 ms
}
}Which looks easier to write and recall syntactically?
Also of note, the toolchain for CircuitPython is significantly easier to support than that of C.
toolchain in CircuitPython
Full details of the setup can be reviewed here.
- Flash the microcontroller with CircuitPython
- Install Mu
- Write some CircuitPython code and save the file to the board
- Add some libraries from circuitpython.org for optional components
toolchain in C
- Pick up a development board for testing code
- Includes a separate toolchain to support
- Find a compiler for the processor instruction set
- Use Eclipse or some other IDE that supports the board and its libraries
- Write the C code and compile for processor instruction set then flash the board
- Add various C libraries to support optional components
a quick note on C on a microcontroller
It is damn fast. The CircuitPython-based board will have to load its firmware then interpret your code.py file in order to execute. This can take 10-15 seconds.
Conversely, the C-based board has code compiled directly for the board and the custom instruction set you developed so it starts executing in microseconds.
Like I said, damn fast.