Learn how to connect to a PoKeys device and control digital outputs
This example demonstrates the fundamental operations of the PoKeys Core Library:
use pokeys_lib::*;
use std::{thread, time::Duration};
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("🚀 PoKeys Basic Device Control Example");
println!("=====================================");
// Step 1: Enumerate connected devices
println!("📡 Scanning for PoKeys devices...");
let device_count = enumerate_usb_devices()?;
println!("✅ Found {} device(s)", device_count);
if device_count == 0 {
println!("❌ No PoKeys devices found!");
println!("💡 Please check:");
println!(" - Device is connected via USB");
println!(" - USB drivers are installed");
println!(" - Device has power");
return Ok(());
}
// Step 2: Connect to the first device
println!("🔌 Connecting to device...");
let mut device = connect_to_device(0)?;
// Get device information
let device_name = device.get_device_name()?;
println!("✅ Connected to: {}", device_name);
// Step 3: Configure pin 1 as digital output
println!("⚙️ Configuring pin 1 as digital output...");
device.set_pin_function(1, PinFunction::DigitalOutput)?;
println!("✅ Pin 1 configured successfully");
// Step 4: Blink the LED 10 times
println!("💡 Starting LED blink sequence...");
for i in 1..=10 {
println!(" Blink {}/10 - LED ON", i);
device.set_digital_output(1, true)?;
thread::sleep(Duration::from_millis(500));
println!(" Blink {}/10 - LED OFF", i);
device.set_digital_output(1, false)?;
thread::sleep(Duration::from_millis(500));
}
println!("🎉 Example completed successfully!");
println!("💡 The LED should have blinked 10 times");
Ok(())
} let device_count = enumerate_usb_devices()?; This function scans all USB ports for connected PoKeys devices. It returns the number of devices found. Always check this count before attempting to connect.
let mut device = connect_to_device(0)?;
Connects to the device at index 0 (the first device found). The device object provides all control functions.
The mut keyword is required because we'll be modifying device state.
device.set_pin_function(1, PinFunction::DigitalOutput)?; Configures pin 1 as a digital output. PoKeys pins are versatile and can serve different functions. Always configure the pin function before using it.
device.set_digital_output(1, true)?; // Turn ON (HIGH)
device.set_digital_output(1, false)?; // Turn OFF (LOW)
Controls the digital output state. true sets the pin to HIGH (typically 3.3V),
false sets it to LOW (0V).
The example uses Rust's ? operator for error handling.
Here's how to handle specific errors:
// More detailed error handling
match enumerate_usb_devices() {
Ok(count) if count == 0 => {
eprintln!("No devices found. Check connections.");
return Ok(());
},
Ok(count) => println!("Found {} devices", count),
Err(e) => {
eprintln!("Failed to enumerate devices: {}", e);
return Err(e.into());
}
}