PlatformIO Community

How to include some python code in my C/C++ arduino sketch

My Environment:

1- MacOs catalina.

2- VScode “Visual Studio Code”

3- PlatformIO extension (for Arduino Development in C/C++)

4- Python3 and Python2 are both installed on my mac.

The Problem:

I was trying to embed a python application called “sr1.py” into my C/C++ application but I’m getting this error when hovering on the #inclde <python.h> squiggly red line:

#include errors detected. Please update your includePath. Squiggles are disabled for this translation unit (/Users/ImCodeName7/Documents/PlatformIO/Projects/speech_recognision/src/main.cpp).C/C++(1696) cannot open source file "python.h"C/C++(1696)

CODE:

#include <Arduino.h>
#include <python.h>


int main()
{
    char filename[] = "sr1.py";
    FILE* fp;

    Py_Initialize();

    fp = _Py_fopen(filename, "r");
    PyRun_SimpleFile(fp, filename);

    Py_Finalize();
    return 0;
}

Please note I am still learning how to configure my environment so please bear with me. Thank you!

Are you trying to write software for an embedded system like an Arduino Uno?

If so, you would need a Python version specifically built for the Arduino Uno. But I doubt that it exists at all. I’ve never heard of such Python versions.

There are boards supporting MicroPython. But then you wouldn’t combine it with C++ code for the Arduino framework.

So generally I doubt very much that your approach is possible.

I am trying to compile a C/C++ arduino code where I need to integrate a python code which will allow me to use speech recognizing functions to control arduino, the python part will convert my speech into a text where I can use this text as a variable and compare it to conditionals to allow a certain operation executed be an arduino.

What kind of board are you using? Do you expect the voice recognition to run on that board or on your computer?

arduino nano, the app is going to run on my computer and will control the arduino pins by getting instructions from the voice recognition library which is made for python. my code is written in arduino C but I need this small python code embedded into my application.

With the Arduino Uno’s hardware capabilities of just 2KB of RAM and 32kB of Flash, running python on it is impossible.

Do the voice-recognition on your computer and send pin toggle commands (e.g. via serial) to the Uno.

Only bigger microcontrollers such as an ESP32 (4MB flash, 512kB RAM, …) have a chance at running python, e.g. using Micropython (https://docs.micropython.org/en/latest/esp32/tutorial/intro.html)

You need two programs:

  • One running on the Arduino Nano
  • One running on your computer

The Python code with voice recognition runs on your computer, a C/C++ program runs on your Arduino Nano.

They can communicate with each other via a serial communication, either using a custom protocol you design yourself or a standard protocol like Firmata. The later setup is describe on this web page: