首页 > 解决方案 > 通过python代码的串行监视器(arduino)不起作用

问题描述

我为连接到 arduino 的 A4998 驱动器的步进电机编写了代码:

// defines pins numbers
const int stepPin = 3; 
const int dirPin = 4; 
const int cycle = 200*8;

void setup() {
  // Sets the two pins as Outputs
  pinMode(stepPin,OUTPUT); 
  pinMode(dirPin,OUTPUT);
  Serial.begin(9600);
}
void loop() {
  if (Serial.available()) {
    
    char val = Serial.read();
    
    if (val == '1') {
      digitalWrite(dirPin,HIGH); // Enables the motor to move in a particular direction
      // Makes 200 pulses for making one full cycle rotation
      for(int i=0; i<=cycle/10; i++){
         digitalWrite(stepPin,HIGH); 
         delayMicroseconds(1000); 
         digitalWrite(stepPin,LOW); 
         delayMicroseconds(1000);
        } 
      // delay(2000);
      }
    
    if (val == '0') {
      digitalWrite(dirPin,LOW); // Enables the motor to move in a particular direction
      // Makes 200 pulses for making one full cycle rotation
      for(int i=0; i<=cycle/10; i++){
         digitalWrite(stepPin,HIGH); 
         delayMicroseconds(1000); 
         digitalWrite(stepPin,LOW); 
         delayMicroseconds(1000);
        } 
      // delay(2000);
      }
  }
}

当我在 arduino 程序中使用串行监视器时,这运行良好,但是当我试图从我的 python 代码启动电机时:

import serial

ser = serial.Serial('COM8', baudrate=9600, timeout=1)

ser.write(b'1')

ser.close()

它不起作用,什么也没有发生。

我错过了什么?

谢谢你。

标签: pythonarduinoserial-portpyserial

解决方案


推荐阅读