我目前正在进行一个项目,该项目使用情绪检测来根据接收到的情绪转动两个电机中的一个。我遇到的问题是,每当我输入“快乐”或“悲伤”时,相应的电机根本不会移动。在我遇到这个问题之前,电机会稍微抽动一下,仅此而已。我所有的代码都编译正确,并且我仔细检查了所有连接是否正确,并且实际上有电源通过系统运行并到达电机。我使用的电机是 PWM 电机,MG995 与 Aduino Uno 和 Adafruit 16x12 位 PWM 和伺服屏蔽。
这是 Arduino 代码:
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
#include <Servo.h>
#include <SoftwareSerial.h>
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();// Create an instance of the Adafruit PWM Servo Driver
// Create two instances of the Servo library
Servo servo1;
Servo servo2;
// Software serial instance to receive serial communication from Python
SoftwareSerial serial(2, 3);
void setup() {
// Start the serial communication with the Python script
serial.begin(9600);
Serial.println("Setup Complete");
// Initialize the PWM driver
pwm.begin();
pwm.setPWMFreq(50);
// Attach the two motors to the Servo library
servo1.attach(0, 500, 2500);
servo2.attach(1, 500, 2500);
// Set servo1 and servo2 to center position
servo1.write(90);
servo2.write(90);
}
String input = "";
void loop() {
// Check if there is serial data available
if (Serial.available() > 0) {
// Read the serial data as a string
char input [10];
Serial.readBytesUntil('\n' , input , sizeof(input));
// Check if the input is "happy"
if (strcmp(input, "happy") == 0 ) {
// Move servo1 to 0 degrees
servo1.write(0);
delay(1000);
// Move servo1 to 180 degrees
servo1.write(180);
}
// Check if the input is "sad"
else if (strcmp(input, "sad") == 0) {
// Move servo2 to 0 degrees
servo2.write(0);
delay(1000);
// Move servo2 to 180 degrees
servo2.write(180);
}
}
}
这是 python 代码:
from pyfirmata import Arduino
import serial
import time
ser = serial.Serial('COM4', 9600)
while True:
input_str = input("Enter 'happy' or 'sad': ")
if input_str == 'happy':
#print(input_str)
ser.write(input_str.encode())
time.sleep(2)
ser.flushInput()
elif input_str == 'sad':
#print(input_str)
ser.write(input_str.encode())
time.sleep(2)
ser.flushInput()
else:
print("Invalid input. Try again.")
ser.close()
我仔细检查了 arduino 和 python 中的波特率和端口是否相同,我知道你不能同时激活两个串行终端。
当我使用 python 发送输入时,代码按预期运行,要求用户输入“快乐”或“悲伤”,等待几秒钟让电机转动,然后再次询问“输入'快乐'或'悲伤'” .唯一的问题是没有一个电机转动,所以我目前不确定这是通信问题还是其他原因。
这是输入后 python 的输出:
Enter 'happy' or 'sad': happy
Enter 'happy' or 'sad': sad
Enter 'happy' or 'sad': angry
Invalid input. Try again.
Enter 'happy' or 'sad':
我曾尝试使用不同的输出类型并重写代码但无济于事。我还注意到在 Void setup 中写的一些输出也不起作用。