Posted on  Updated on 

基于树莓派上位机与arduino下位机实现键盘控制

实现键盘控制小车行驶

下位机代码,Arduino的5号引脚为电机引脚,9号引脚为舵机引脚

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <Servo.h> 

Servo myservo;
String str;
int pos = 92; //舵机角度
int motor_pwm = 100; //电机数值0 ~255
int pos_mid = 92; // 储存舵机中值角度
int motorPin = 5; // 确定motor控制引脚
int servoPin = 9; //确定servo控制引脚

void setup() {
Serial.begin(115200);
myservo.attach(servoPin); // 该舵机由arduino第9脚控制
pinMode(motorPin, OUTPUT); // 将电机引脚设为输出模式
myservo.write(pos_mid); // 舵机复位
analogWrite(motorPin,0); // 电机初始转动
delay(1000);
}

void loop() {
if (Serial.available() >= 2) {
int servoValue = Serial.read();
int motorValue = Serial.read();

// 控制舵机
myservo.write(servoValue);
if (servoValue <40) servoValue=40;
else if(servoValue > 140) servoValue=140;

Serial.print("servo: ");
Serial.println(servoValue);
// 控制电机

if (motorValue <0) motorValue=0;
else if(motorValue > 255) motorValue=255;
analogWrite(motorPin, motorValue);

Serial.print("motor: ");
Serial.println(motorValue);
}
}

上位机代码
文件名 key_control.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# Author: 无忧
# Date: 2023-12-02
# Description: 这是一个键盘控制的简单代码
# 请调节键盘状态为英语小写状态
# --------------------

import keyboard
import time
# 要下包keyboard
from send_M_S import *

speed = 0
speed_max = 60 # 速度的最大值
turn = 92 # 舵机中值
turn_l = 60 # 舵机打角最左
turn_r = 120 # 舵机打角最右

if __name__ == "__main__":
ser = init_send()
while True:
try:
if keyboard.is_pressed('w'):
speed += 5
if speed >= speed_max:
speed = speed_max
elif keyboard.is_pressed('a'):
turn -= 8
if turn <= turn_l:
turn = turn_l
elif keyboard.is_pressed('d'):
turn += 8
if turn >= turn_r:
turn = turn_r
elif keyboard.is_pressed('s'):
speed -= 5
if speed <= 0:
speed = 0
time.sleep(0.1) # 系统响应速度
send_values(ser, turn, speed)
except KeyboardInterrupt:
break

上位机串口代码
文件名send_M_S

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Author:
# Date: 2023-12-02
# Description: This script does XYZ.
import serial
import time
import sys

# 设置串口参数
def init_send():
ser = serial.Serial('COM4', 115200, timeout=1)
return ser

def send_values(ser, servo_value, motor_value):
# 向串口发送舵机值和电机值
time.sleep(0.1)
ser.write(bytes([servo_value, motor_value]))
while ser.in_waiting:
arduino_feedback = ser.readline().decode()
print("Arduino:", arduino_feedback)

if __name__ == '__main__':
# 初始化串口
ser = init_send()
try:
while True:
for i in range(60, 120, 1):
send_values(ser, i, 50)
for i in range(120, 60, -1):
send_values(ser, i, 50)
except KeyboardInterrupt:
# 在用户按下 Ctrl+C 时,关闭串口并退出程序
ser.close()
sys.exit()