Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import serial
- import time
- def test_serial_loopback(port, baudrate=9600):
- """
- Test FT232RL adapter using loopback at specified baud rate.
- Args:
- port (str): Serial port name (e.g., 'COM7')
- baudrate (int): Baud rate for testing
- Returns:
- bool: True if test passed, False otherwise
- """
- try:
- # Open serial port
- ser = serial.Serial(
- port=port,
- baudrate=baudrate,
- bytesize=serial.EIGHTBITS,
- parity=serial.PARITY_NONE,
- stopbits=serial.STOPBITS_ONE,
- timeout=1
- )
- print(f"\nTesting at {baudrate} baud...")
- # Test string
- test_string = f"FT232RL TEST at {baudrate} baud!"
- print(f"Sending: {test_string}")
- # Clear any existing data
- ser.reset_input_buffer()
- ser.reset_output_buffer()
- # Send data
- ser.write(test_string.encode())
- time.sleep(0.2) # Longer wait for higher baud rates
- # Read data
- received = ser.read(len(test_string))
- received_string = received.decode()
- print(f"Received: {received_string}")
- # Check if received data matches sent data
- if received_string == test_string:
- print(f"✓ TEST PASSED at {baudrate} baud")
- result = True
- else:
- print(f"✗ TEST FAILED at {baudrate} baud")
- print(f"Expected: {test_string}")
- print(f"Got: {received_string}")
- result = False
- # Close the port
- ser.close()
- return result
- except serial.SerialException as e:
- print(f"Error: Could not open port {port}")
- print(f"Details: {str(e)}")
- return False
- except Exception as e:
- print(f"Error during testing: {str(e)}")
- return False
- def run_multi_baud_test(port):
- """
- Test multiple common baud rates
- """
- # Common baud rates to test
- baud_rates = [
- 300, # Very slow, legacy
- 1200, # Slow, legacy
- 2400, # Legacy
- 4800, # Legacy
- 9600, # Common default
- 19200, # Medium speed
- 38400, # Medium-high speed
- 57600, # High speed
- 115200, # Very high speed, common for modern devices
- 230400, # Super high speed
- 460800, # Ultra high speed
- 921600 # Maximum common rate
- ]
- print(f"Starting multi-baud rate test on port {port}")
- print("Make sure TX and RX pins are connected for loopback test")
- print("-" * 50)
- results = []
- for rate in baud_rates:
- success = test_serial_loopback(port, rate)
- results.append((rate, success))
- time.sleep(0.5) # Wait between tests
- print("\nTest Summary:")
- print("-" * 50)
- print("Baud Rate\tResult")
- print("-" * 50)
- for rate, success in results:
- status = "✓ PASS" if success else "✗ FAIL"
- print(f"{rate:,}\t\t{status}")
- # Calculate success rate
- success_count = sum(1 for _, success in results if success)
- success_rate = (success_count / len(baud_rates)) * 100
- print("-" * 50)
- print(f"Overall Success Rate: {success_rate:.1f}%")
- print(f"Passed: {success_count}/{len(baud_rates)} baud rates")
- if __name__ == "__main__":
- # Replace 'COM7' with your port if different
- PORT = 'COM8'
- run_multi_baud_test(PORT)
Advertisement
Add Comment
Please, Sign In to add comment