如何通过Python的PySerial调用Arduino中超声波传感器的函数?
Got it, let's get this sorted out for you! Here's a straightforward way to call your Arduino ultrasonic sensor function from Python whenever you need it:
First, you need to modify your existing Arduino code to respond to a specific trigger command from Python. Let's use the character 'r' (short for "read") to kick off the sensor reading. Here's how to wrap your existing sensor function:
// Your existing ultrasonic sensor read function (keep this as-is!) long readUltrasonic() { // Replace this with your actual sensor logic const int trigPin = 9; const int echoPin = 10; long duration, distance; pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); distance = duration * 0.034 / 2; // Convert to centimeters return distance; } void setup() { Serial.begin(9600); // Match this baud rate in your Python script later } void loop() { // Listen for commands from Python if (Serial.available() > 0) { char cmd = Serial.read(); if (cmd == 'r') { // Call your sensor function and send the result back to Python long sensorReading = readUltrasonic(); Serial.println(sensorReading); } } }
Upload this updated code to your Arduino, and leave it connected to your computer via USB.
You'll use the pyserial library to talk to the Arduino over USB. Install it first if you haven't:
pip install pyserial
Then create a Python script that sends the 'r' command and captures the sensor response:
import serial import time def fetch_ultrasonic_reading(port='COM3', baud_rate=9600): try: # Open the serial port (adjust the port to match your Arduino's) ser = serial.Serial(port, baud_rate, timeout=1) time.sleep(2) # Give the Arduino time to initialize the connection # Send the trigger command to start reading ser.write(b'r') # Read the response from Arduino and clean it up raw_reading = ser.readline().decode('utf-8').strip() ser.close() return float(raw_reading) if raw_reading else None except Exception as e: print(f"Oops, something went wrong: {e}") return None # Example: Call this function whenever you need a sensor reading if __name__ == "__main__": distance = fetch_ultrasonic_reading(port='COM3') # Update port for your system if distance is not None: print(f"Ultrasonic Sensor Reading: {distance} cm") else: print("Failed to retrieve sensor data")
- Find Your Serial Port: On Windows, check Arduino IDE > Tools > Port for something like
COM3. On macOS/Linux, it'll look like/dev/tty.usbmodemXXXXor/dev/ttyACM0. - Match Baud Rates: Double-check that
Serial.begin(9600)in Arduino andbaud_rate=9600in Python are the same. - Permissions: On Linux/macOS, you might need to add your user to the
dialout(Linux) oruucp(macOS) group to access the serial port without sudo. - Stability: The 2-second sleep in Python is important—Arduino resets when you open the serial connection, so it needs a moment to get ready.
内容的提问来源于stack exchange,提问作者Amal Baby

