I would love to embed this python program on a c++ one , but I'm kinda struggling there , I never studied python , and even after reading the explanation in others websites about the method I couldn't really apply it , because I don't know what are those python members ,I want to run this program under c++, this code is a good one , but couldn't find it in c++ version , this is why I decided to use the embedded option .
here is the python program
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Le Raspbery Pi envoie des messages à l'Arduino
import serial # bibliothèque permettant la communication série
import time # pour le délai d'attente entre les messages
ser = serial.Serial('/dev/ttyACM0', 9600)
compteur = 0
while True: # boucle répétée jusqu'à l'interruption du programme
if compteur < 6:
compteur = compteur + 1
else:
compteur = 0
ser.write(str(compteur))
time.sleep(1) # on attend pendant 2 secondes
and here is the embedded program that I tried , but I'm pretty sure that its wrong , because there is no call of python object
#include <iostream>
#include <Python.h>
int main(int argc, char **argv) {
Py_Initialize();
return 0;
}
Can anybody help me to do this !? thanks in advance .
-
@PaulWürtz thanks for your proposition , yes I did before this and I did choose this solution because its the more oprtimal for me , and for the example on the website its written on c , I know that we can execute it even in c++ , but in my case , this is not the good one .MadHer– MadHer2018年06月23日 04:23:18 +00:00Commented Jun 23, 2018 at 4:23
-
I'm trying right now to right the same code , using another library in c++ , for exactly those serial communication , will try to post it after , but , I would really love to see the embedded version of the python code , exactly because its a simple oneMadHer– MadHer2018年06月23日 04:29:28 +00:00Commented Jun 23, 2018 at 4:29
1 Answer 1
For simple application as this, I wouldn't link the python headers to your programm, but as a more easy solution I would trigger the system() command of C++ and process the output.
Here a example from this question:
#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <array>
std::string exec() {
std::array<char, 128> buffer;
std::string result;
const char* cmd = "./python script.py";
std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose);
if (!pipe) throw std::runtime_error("popen() failed!");
while (!feof(pipe.get())) {
if (fgets(buffer.data(), 128, pipe.get()) != nullptr)
result += buffer.data();
}
return result;
}
You would then have to change the infinite loop in your python code, so that the python programm terminates and the rest of your C++ code executes, then you could probe the arduino with your python script from you C++ program.
4 Comments
system() in a Qt program does not seem all to wrong for me ;)