pip install Serial
pip install pyautogui
pip install time
2、代码示例
目标:每当有物体在超声波模块上方1cm—25cm时,电脑自动按下右键,即"right"键.
First,我们先要打开 Arduino IDE 拷入以下代码进入nano板:
/* * gesture control program for controlling certain functions in windows pc * Code by BalaAppu * Website: www.electronicshub.org */constint trigPin =11; constint echoPin =10; long duration; int distance; float r;////////////////////////////////voidfind_distance (void) { digitalWrite(trigPin, LOW);delayMicroseconds(2);digitalWrite(trigPin, HIGH);delayMicroseconds(10);digitalWrite(trigPin, LOW); duration =pulseIn(echoPin, HIGH,5000); r =3.4* duration /2; distance = r /100.00;delay(50);}voidsetup() {Serial.begin(9600);pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT);delay (1000);}voidloop(){ distance =0;find_distance(); if(distance <=25&& distance >=1){ Serial.write("right");Serial.print("\n"); } Serial.print(distance);Serial.print("\n");delay(250);}
然后,需要在arduino界面找到你连接的端口号,这里我们示例的端口号为COM5.
接着,我们打开任意的 Python IDE 在电脑上运行如下python程序:
from serial import Serial import pyautogui import timeArduino_Serial =Serial('COM5', 9600)//这里的COM请在while1: incoming_data =str(Arduino_Serial.readline())# read the serial data and print it as lineprint(incoming_data)# print the incoming Serial dataif'left'in incoming_data: pyautogui.keyDown('left') time.sleep(0.1) pyautogui.keyUp('left')elif'right'in incoming_data: pyautogui.keyDown('right') time.sleep(0.1) pyautogui.keyUp('right') incoming_data =""# clears the data