Karimhamdy1
Published

Python and C Blended Programming on ESP32 using Zerynth

This tutorial illustrates the use of Python/C hybrid programming environment in Zerynth Studio.

EasyProtip1 hour304
Python and C Blended Programming on ESP32 using Zerynth

Things used in this project

Hardware components

DIOT ESP32 devkit V1
×1

Software apps and online services

Zerynth Studio
Zerynth Studio

Story

Read more

Code

main.py

Python
# C-python Exmaple
# Created at 2018-12-20 22:04:51.001903

import streams

streams.serial()

# define a Python function decorated with c_native.
# This function has no body and will instead call
# the C function specified in the decorator.
# The source file(s) where to find the C function must be given (cdiv.c)

def blink_led():
    pinToggle(LED0)

@c_native("init_interrupt_c",["cdiv.c"],[]) #we use @c_native to tell the compiler that we are calling a c function in another file.
def init_interrupt():
    pass

init_interrupt()                            #init. of the interrupt in the C function in "cdic.c" file
pinMode(LED0,OUTPUT_PUSHPULL)               #defining the pin of the LED to be output

while True:
    try:
        print("Blinking LED")
        blink_led()
        
    except Exception as e:
        print(e)
    sleep(500)

cdiv.c

C/C++
#define ZERYNTH_PRINTF                  //we define this macro to use "printf"function

#include "zerynth.h"                    //this is mandatory

void btn_press_callback(int slot, int dir)             //this header and the paramters of the function mmust be defined like that according to the docs.
{                                       				//https://docs.zerynth.com/latest/official/core.zerynth.stdlib/docs/official_core.zerynth.stdlib___common_vhal_h.html?highlight=vhalpinattachinterrupt#c.vhalPinAttachInterrupt

   printf("interrupt triggered\n");        //just a print to know when the interrupt is triggered.

}

C_NATIVE(init_interrupt_c){

       C_NATIVE_UNWARN();              //must be included at the start of a called c function.

vhalPinAttachInterrupt(BTN0,PINMODE_EXT_BOTH,btn_press_callback,TIME_U(0,MILLIS));     //enabling the interrupt for BTN0 on both rising and falling edge, a

       printf("Interrupt initialized on BTN0\n");                              // the service routine is the function btn_press_callback defined above.

       return ERR_OK; //<-- execution ok                                       //the timeout is given as 0 millis.
}

Credits

Karimhamdy1

Karimhamdy1

2 projects • 2 followers

Comments