简体   繁体   中英

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). 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. Arduino uses the serial port to transfer the "compiled binary code generated by avr-gcc" to the board. You cannot program an Arduino board by sending commands on the serial port. But you can generate a compiled binary and ship it on the board using 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.

If you only want to write code for Arduino but in python, then check out micropython . This library supports a number of Arduino boards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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