从 Python 调用 Arduino C/C++ 库函数

问题描述

我正在尝试从 python3 调用 Arduino C++ 库 Adafruit-Motor-Shield-library

我尝试了几种解决方法。例如,Arduino-Python3 Command API , pyserial ,pyFirmata 但他们的支持有限,我想致电 Adafruit-Motor-Shield-library 来自python3函数

另外,我已经尝试使用 python 子进程,但我不想使用 .ino/C++ 文件

例如这里是 python 脚本,它使用子进程调用 .ino C++ 文件

# Todo: Testing
if __name__ == "__main__":
    import subprocess
    import sys

    # next line must be edited to be appropriate for your PC
    arduinoprog = "/home/arslan/Downloads/arduino-1.8.13/arduino"

    # projectFile = sys.argv[1]
    projectFile = "DCM2.ino"
    codeFile = open(projectFile,'r')
    startLine = codeFile.readline()[3:].strip()
    actionLine = codeFile.readline()[3:].strip()
    boardLine = codeFile.readline()[3:].strip()
    portLine = codeFile.readline()[3:].strip()
    endLine = codeFile.readline()[3:].strip()
    codeFile.close()

    if startLine != "python-build-start" or endLine != "python-build-end":
        print("Sorry,can't process file")
        sys.exit()

    arduinoCommand = arduinoprog + " --" + actionLine + " --board " + boardLine + " --port " + portLine + " " + projectFile

    print("\n\n -- Arduino Command --")
    print(arduinoCommand)

    print("-- Starting %s --\n" % (actionLine))

    presult = subprocess.call(arduinoCommand,shell=True)

    if presult != 0:
        print("\n Failed - result code = %s --" % (presult))
    else:
        print("\n-- Success --")

最后,python Boost.Python library解决这个问题吗?有什么方法可以从 python3Adafruit-Motor-Shield-library 生成 shared dll,然后从 python3 调用,而无需在 Adafruit-Motor-Shield-library.

的 src/include 中进行大量手动更改

例如,我想将这个简单的 Arduino 代码转换python3

// Arduino code
#include <AFMotor.h>
#include <SoftwareSerial.h>

void setup() {
  // put your setup code here,to run once:
AF_DCMotor Leftmotor1(1);  
AF_DCMotor Rightmotor2(2);  
AF_DCMotor Rightmotor3(3); 
AF_DCMotor Leftmotor4(4); 


}

void loop() {
  // put your main code here,to run repeatedly:
 Leftmotor1.setSpeed(SpeedL1);
  Leftmotor1.run(RELEASE);
  Leftmotor1.run(FORWARD);
  Rightmotor2.setSpeed(SpeedR2);
 }

我将感谢您的任何评论,并在此表示感谢。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)