You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python与Arduino串口通信:Arduino向Python传红外数值的代码问题

Arduino-Python Serial Communication: Completing IR Distance Logic

Hey Daniel, let's work through finishing your IR sensor distance logic and getting that data sent to Python smoothly. Here's a step-by-step breakdown tailored to your setup:

1. First, Ensure the Distance Conversion Function is Complete

I notice you're using gp2y0a21yk() to convert the analog sensor reading to centimeters—if you haven't already defined this function, here's a tested implementation for the GP2Y0A21YK sensor (adjust based on your actual sensor calibration):

long gp2y0a21yk(long analogValue) {
    // Avoid division by zero if sensor reads 0
    if (analogValue <= 27) return 100; // Max range for this sensor is ~80-100cm
    // Formula derived from typical sensor datasheet characteristics
    return (long)(10650.08 / (analogValue - 27.728)) - 1;
}

2. Finish the <50cm Logic & Send Data to Python

Your goal is to transmit the distance value to Python when an object is within 50cm. Update your loop() function to send consistent, parseable data over serial:

void loop() {
    // Optional: Average multiple readings for stability
    long total = 0;
    for(int i = 0; i < 5; i++){
        total += analogRead(IR_sensor);
        delay(10); // Small delay between samples
    }
    long IR_value = total / 5;
    long IR_range = gp2y0a21yk(IR_value);

    // Send data to Python with a clear format
    if (IR_range < 50) {
        // Send distance with a prefix to make parsing easier in Python
        Serial.print("distance:");
        Serial.println(IR_range);
    } else {
        // Optional: Notify Python when object is out of range
        Serial.println("out_of_range");
    }
    delay(100); // Adjust delay based on how often you need updates
}

3. Python Code to Receive & Parse Serial Data

Use the pyserial library to read the data from Arduino. First install it with pip install pyserial, then use this example script:

import serial
import time

# Initialize serial port (replace 'COM3' with your Arduino's port, e.g., /dev/ttyUSB0 on Linux)
ser = serial.Serial('COM3', 9600, timeout=1)
time.sleep(2)  # Give Arduino time to initialize

try:
    while True:
        # Read and clean up the incoming line
        raw_data = ser.readline().decode('utf-8').strip()
        if raw_data:
            if raw_data.startswith('distance:'):
                # Extract the numeric value
                distance_cm = int(raw_data.split(':')[1])
                print(f"Object detected at: {distance_cm} cm")
                # Add your custom logic here (e.g., store data, trigger actions)
            elif raw_data == 'out_of_range':
                print("No object within 50cm range")
except KeyboardInterrupt:
    # Close the serial port gracefully when stopping the script
    ser.close()
    print("\nSerial connection closed")

Key Notes to Avoid Issues

  • Baud Rate Match: Make sure both Arduino (Serial.begin(9600)) and Python (serial.Serial(..., 9600)) use the same baud rate.
  • Port Identification: Find your Arduino's port in the Arduino IDE (Tools > Port).
  • Sensor Calibration: If distance readings are off, adjust the formula in gp2y0a21yk() by testing known distances and recording their analog values.
  • Serial Stability: Adding small delays and averaging readings helps reduce noise from the sensor.

内容的提问来源于stack exchange,提问作者Daniel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:37:10