pyftdi synchronous fifo example
- User
pyftdi synchronous fifo example
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
pyftdi synchronous fifo example
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's a comprehensive example of using PyFtdi for synchronous FIFO mode:
from pyftdi.ftdi import Ftdi, FtdiError
import time
import struct
def synchronous_fifo_example():
"""Example of using FTDI device in synchronous FIFO mode.
This example demonstrates how to configure an FTDI device (like FT2232H, FT232H)
for synchronous FIFO mode, which provides high-speed parallel data transfer.
"""
# Device URL - adjust for your specific FTDI device
# FT2232H: VID=0403, PID=6010
# FT232H: VID=0403, PID=6014
# FT245R: VID=0403, PID=6001 (supports synchronous bit-bang, not full sync FIFO)
device_url = 'ftdi://0403:6014/0' # Example for FT232H, interface 0
try:
# Create FTDI instance
ftdi = Ftdi()
# Open the device
ftdi.open_from_url(device_url)
print(f"Successfully opened FTDI device: {device_url}")
# Get device information
device_info = ftdi.device
print(f"Device: {device_info}")
# Configure for synchronous FIFO mode
# Note: Synchronous FIFO mode is primarily supported on FT2232H and FT232H
# Set synchronous FIFO mode
# The exact method depends on the FTDI chip and PyFtdi version
# For FT232H/FT2232H, you typically need to:
# 1. Reset the device
# 2. Set the mode to synchronous FIFO
# Reset the device
ftdi.reset()
# Set latency timer (lower values for better real-time performance)
ftdi.set_latency_timer(2) # 2ms latency
# Configure for synchronous FIFO mode
# Note: PyFtdi's direct support for sync FIFO mode may be limited
# You might need to use lower-level commands
# For FT232H/FT2232H in sync FIFO mode:
# - Data is transferred on D0-D7 pins
# - RD# and WR# control read/write operations
# - RXF# indicates data available to read
# - TXE# indicates space available to write
# Example: Configure as synchronous bit-bang mode (similar to sync FIFO)
# This is more commonly supported in PyFtdi
ftdi.set_bitmode(0xFF, Ftdi.BitMode.SYNCBB) # All pins as outputs initially
print("Configured for synchronous bit-bang mode")
# Set clock divisor for synchronous mode
# The actual clock frequency depends on the device
# For FT232H: base clock is 60MHz
# Clock = 60MHz / ((1 + divisor) * 2)
divisor = 5 # Results in 5MHz clock for FT232H
ftdi.set_frequency(60000000 / ((1 + divisor) * 2))
# Example data operations
print("\n--- Writing Data ---")
# Generate some test data
test_data = bytearray()
for i in range(256):
test_data.append(i & 0xFF)
# Write data in chunks
chunk_size = 64 # Typical USB packet size
bytes_written = 0
start_time = time.time()
for i in range(0, len(test_data), chunk_size):
chunk = test_data[i:i+chunk_size]
written = ftdi.write_data(chunk)
bytes_written += written
print(f"Wrote {written} bytes (chunk {i//chunk_size + 1})")
elapsed_time = time.time() - start_time
throughput = bytes_written / elapsed_time / 1024 / 1024 # MB/s
print(f"Total written: {bytes_written} bytes in {elapsed_time:.3f} seconds")
print(f"Write throughput: {throughput:.2f} MB/s")
# For reading data in sync FIFO mode
print("\n--- Reading Data ---")
# In a real application, you would check RXF# pin to see if data is available
# Here we'll attempt to read with a timeout
# Attempt to read data
read_buffer = bytearray()
bytes_to_read = 256
chunk_size = 64
start_time = time.time()
while len(read_buffer) < bytes_to_read:
try:
# Read with timeout
data = ftdi.read_data(chunk_size)
if data:
read_buffer.extend(data)
print(f"Read {len(data)} bytes")
else:
# No data available
time.sleep(0.001) # Small delay
# Timeout check
if time.time() - start_time > 1.0: # 1 second timeout
print("Read timeout")
break
except FtdiError as e:
print(f"Read error: {e}")
break
if read_buffer:
print(f"Total read: {len(read_buffer)} bytes")
print(f"First 16 bytes: {read_buffer[:16].hex()}")
# Example: Using synchronous bit-bang for parallel I/O
print("\n--- Synchronous Bit-Bang Example ---")
# Set pin directions (1 = output, 0 = input)
# Lower 4 bits as outputs, upper 4 bits as inputs
pin_direction = 0x0F
ftdi.set_bitmode(pin_direction, Ftdi.BitMode.SYNCBB)
# Write pattern to output pins
patterns = [0x00, 0x05, 0x0A, 0x0F, 0x0A, 0x05, 0x00]
for pattern in patterns:
ftdi.write_data(bytes([pattern]))
time.sleep(0.1)
# Read back the pin states
pin_states = ftdi.read_pins()
print(f"Wrote: 0x{pattern:02X}, Read pins: 0x{pin_states:02X}")
# Advanced: Bulk transfer for maximum performance
print("\n--- Bulk Transfer Example ---")
# Generate larger test data
large_data = bytearray(range(256)) * 16 # 4KB of data
# Write in one large chunk
start_time = time.time()
bytes_written = ftdi.write_data(large_data)
elapsed_time = time.time() - start_time
throughput = bytes_written / elapsed_time / 1024 / 1024 # MB/s
print(f"Bulk write: {bytes_written} bytes in {elapsed_time:.3f} seconds")
print(f"Bulk throughput: {throughput:.2f} MB/s")
# Reset to normal mode before closing
ftdi.set_bitmode(0x00, Ftdi.BitMode.RESET)
# Close the device
ftdi.close()
print("\nFTDI device closed.")
except FtdiError as e:
print(f"FTDI Error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
def synchronous_fifo_loopback_test():
"""Example of a loopback test in synchronous FIFO mode.
This requires external loopback connection (connect TXE# to RXF#, and data pins D0-D7 together).
"""
device_url = 'ftdi://0403:6014/0' # FT232H example
try:
ftdi = Ftdi()
ftdi.open_from_url(device_url)
# Configure for synchronous bit-bang mode
ftdi.set_bitmode(0xFF, Ftdi.BitMode.SYNCBB) # All pins as outputs
ftdi.set_frequency(1000000) # 1MHz clock
print("Loopback test started (requires external loopback connection)")
# Test patterns
test_patterns = [
b'\x00\xFF\x00\xFF', # Alternating
b'\x55\xAA\x55\xAA', # Alternating bits
b'\x01\x02\x04\x08\x10\x20\x40\x80', # Walking bit
bytes(range(256)) # Sequential
]
for i, pattern in enumerate(test_patterns):
print(f"\nTest pattern {i+1}: {pattern[:8].hex()}...")
# Write pattern
written = ftdi.write_data(pattern)
print(f"Wrote {written} bytes")
# Small delay for data to propagate
time.sleep(0.001)
# Read back
read_data = ftdi.read_data(len(pattern))
if read_data == pattern:
print("✓ Loopback test PASSED")
else:
print("✗ Loopback test FAILED")
print(f"Expected: {pattern[:16].hex()}...")
print(f"Received: {read_data[:16].hex()}...")
ftdi.set_bitmode(0x00, Ftdi.BitMode.RESET)
ftdi.close()
except FtdiError as e:
print(f"FTDI Error: {e}")
def synchronous_fifo_performance_test():
"""Performance benchmark for synchronous FIFO mode."""
device_url = 'ftdi://0403:6014/0' # FT232H example
try:
ftdi = Ftdi()
ftdi.open_from_url(device_url)
# Configure for maximum performance
ftdi.set_bitmode(0xFF, Ftdi.BitMode.SYNCBB)
ftdi.set_latency_timer(1) # Minimum latency
# Test different clock frequencies
frequencies = [1000000, 5000000, 10000000, 30000000] # 1MHz to 30MHz
for freq in frequencies:
try:
ftdi.set_frequency(freq)
print(f"\n--- Testing at {freq/1000000:.1f} MHz ---")
# Generate test data (1MB)
test_size = 1024 * 1024
test_data = bytearray(range(256)) * (test_size // 256)
# Write test
start_time = time.time()
bytes_written = 0
chunk_size = 65536 # 64KB chunks
for i in range(0, len(test_data), chunk_size):
chunk = test_data[i:i+chunk_size]
bytes_written += ftdi.write_data(chunk)
elapsed_time = time.time() - start_time
throughput = bytes_written / elapsed_time / 1024 / 1024
print(f"Write throughput: {throughput:.2f} MB/s")
print(f"Effective data rate: {throughput * 8:.2f} Mbps")
except FtdiError as e:
print(f"Cannot set frequency {freq/1000000:.1f} MHz: {e}")
ftdi.set_bitmode(0x00, Ftdi.BitMode.RESET)
ftdi.close()
except FtdiError as e:
print(f"FTDI Error: {e}")
if __name__ == '__main__':
print("=== FTDI Synchronous FIFO Example ===\n")
# Run the main example
synchronous_fifo_example()
# Uncomment to run additional tests:
# print("\n\n=== Loopback Test ===")
# synchronous_fifo_loopback_test()
# print("\n\n=== Performance Test ===")
# synchronous_fifo_performance_test()
Key Points about Synchronous FIFO Mode:
Hardware Requirements:
Pin Configuration in Sync FIFO Mode:
PyFtdi Limitations:
Performance Considerations:
Common Use Cases:
Before Running:
Install PyFtdi:
pip install pyftdi
Identify your FTDI device and update the device_url with correct VID/PID
For loopback testing, connect:
Ensure your FTDI device supports synchronous modes (FT232H, FT2232H recommended)
Note: For production applications requiring true synchronous FIFO mode with maximum performance, you might need to use FTDI's D2XX drivers directly or libftdi with lower-level access. PyFtdi is excellent for many use cases but has some limitations for the most advanced FTDI features.