简体   繁体   English

如何将 arduino 代码从 c++ 转换为 python?

[英]how to translate arduino code from c++ to python?

I'm new to Arduino. I have this code written in c++ that I can understand but I don't know how to translate it to python using pyserial or other python libraries (for a school project).我是 Arduino 的新手。我在 c++ 中编写了这段代码,我可以理解,但我不知道如何使用 pyserial 或其他 python 库(用于学校项目)将其翻译成 python。 can u help me please.你能帮帮我吗I'm completely lost.我完全迷路了。

#include <Servo.h>

//Threshold for servo motor control with muscle sensor. 
//You can set a threshold according to the maximum and minimum values of the muscle sensor.
#define THRESHOLD 250

//Pin number where the sensor is connected. (Analog 0)
#define EMG_PIN 0

//Pin number where the servo motor is connected. (Digital PWM 3)
#define SERVO_PIN 3

//Define Servo motor
Servo SERVO_1;

/-------------------------------- void setup ------------------------------------------------/

void setup(){
  
  //BAUDRATE set to 115200, remember it to set monitor serial properly. 
  //Used this Baud Rate and "NL&CR" option to visualize the values correctly.
  Serial.begin(115200);
  
  //Set servo motor to digital pin 3
  SERVO_1.attach(SERVO_PIN);
}

/--------------------------------  void loop  ------------------------------------------------/

void loop(){

  //The "Value" variable reads the value from the analog pin to which the sensor is connected.
  int value = analogRead(EMG_PIN);

  //If the sensor value is GREATER than the THRESHOLD, the servo motor will turn to 170 degrees.
  if(value > THRESHOLD){
    SERVO_1.write(170);
  }

  //If the sensor is LESS than the THRESHOLD, the servo motor will turn to 10 degrees.
  else{
    SERVO_1.write(10);
  }

  //You can use serial monitor to set THRESHOLD properly, comparing the values shown when you open and close your hand.
  Serial.println(value);
}

pyserial is a serial communication library. pyserial 是一个串行通信库。 Arduino uses the serial port to transfer the "compiled binary code generated by avr-gcc" to the board. Arduino使用串口将“avr-gcc生成的编译后的二进制代码”传给板子。 You cannot program an Arduino board by sending commands on the serial port.您不能通过在串行端口上发送命令来对 Arduino 板进行编程。 But you can generate a compiled binary and ship it on the board using pyserial.但是您可以生成编译后的二进制文件并使用 pyserial 将其发送到板上。

If you really wanna do it in python from scratch then go Google the instruction set of the MCU that Arduino uses and start writing your own compiler.如果你真的想在 python 中从头开始,那么 go Google Arduino 使用的 MCU 指令集并开始编写你自己的编译器。

If you only want to write code for Arduino but in python, then check out micropython .如果您只想为 Arduino 而在 python 中编写代码,请查看micropython This library supports a number of Arduino boards.该库支持多个 Arduino 板。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM