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

运行Windows 10 IoT的树莓派与Arduino通信及考勤设备数据传输问题

Hey there, let's work through this problem together—using an Arduino as a middleman for your R305 fingerprint sensor is a smart workaround since there's no native C# library, so let's get that communication with your Windows 10 IoT Raspberry Pi sorted out.

Troubleshooting Communication Issues & Reliable Methods

First, let's eliminate the most common quick fixes before diving into specific communication protocols:

Basic Pre-Checks

  • Level Shifting is NON-NEGOTIABLE for UART/GPIO: Raspberry Pi GPIO pins run on 3.3V, while Arduino uses 5V. Directly connecting them will damage the Pi's pins and cause garbage data (like 255, 0/1). Use a 3.3V ↔ 5V level converter (e.g., TXB0108) for any GPIO-based communication.
  • Always Ground Together: The Pi and Arduino must share a common ground pin—without this, signals will be unstable and unreadable.
  • Windows IoT Permissions: In your UWP app's Package.appxmanifest, add the required capabilities for whichever protocol you're using:
    • Serial: <DeviceCapability Name="serialcommunication"><Device Id="any"><Function Type="name:serialPort" /></Device></DeviceCapability>
    • I2C: <DeviceCapability Name="lowLevelDevices"><Device Id="any"><Function Type="name:i2c" /></Device></DeviceCapability>

Fixes for Each Communication Method

1. USB Serial (Simplest & Most Reliable)

This is the easiest path since USB handles level conversion and device detection automatically.

Arduino Side (Test Code)

#include <Adafruit_Fingerprint.h>

// Use hardware Serial1 for fingerprint sensor, USB Serial for Pi communication
Adafruit_Fingerprint finger = Adafruit_Fingerprint(&Serial1); 

void setup() {
  // USB Serial to Pi (9600 baud)
  Serial.begin(9600);
  // Serial1 to fingerprint sensor (match your sensor's baud rate—often 57600)
  Serial1.begin(57600);
  finger.begin(57600);

  if (finger.verifyPassword()) {
    Serial.println("Sensor connected successfully!");
  } else {
    Serial.println("Failed to connect to sensor—check wiring!");
    while (1); // Halt if sensor isn't detected
  }
}

void loop() {
  // Attempt to read a fingerprint
  int result = finger.getImage();
  if (result == FINGERPRINT_OK) {
    result = finger.image2Tz();
    if (result == FINGERPRINT_OK) {
      result = finger.fingerSearch();
      if (result == FINGERPRINT_OK) {
        // Send structured data to Pi (easy to parse)
        Serial.print("{\"fingerID\":");
        Serial.print(finger.fingerID);
        Serial.println(",\"status\":\"matched\"}");
      }
    }
  }
  delay(1000);
}

Raspberry Pi UWP Side (C#)

using Windows.Devices.SerialCommunication;
using Windows.Storage.Streams;
using Newtonsoft.Json; // Add via NuGet for JSON parsing

public class FingerprintData
{
    public int fingerID { get; set; }
    public string status { get; set; }
}

async void InitializeUsbSerial()
{
    // Enumerate available serial devices
    string selector = SerialDevice.GetDeviceSelector();
    var devices = await DeviceInformation.FindAllAsync(selector);
    
    if (devices.Count == 0)
    {
        Debug.WriteLine("No serial devices found—check USB connection!");
        return;
    }

    // Connect to the first detected device (adjust if needed)
    SerialDevice serialPort = await SerialDevice.FromIdAsync(devices[0].Id);
    serialPort.BaudRate = 9600;
    serialPort.DataBits = 8;
    serialPort.StopBits = SerialStopBitCount.One;
    serialPort.Parity = SerialParity.None;

    // Set up continuous reading
    DataReader reader = new DataReader(serialPort.InputStream);
    reader.InputStreamOptions = InputStreamOptions.Partial;

    while (true)
    {
        uint bytesRead = await reader.LoadAsync(1024);
        if (bytesRead > 0)
        {
            string rawData = reader.ReadString(bytesRead).Trim();
            // Parse structured JSON to avoid messy string handling
            FingerprintData data = JsonConvert.DeserializeObject<FingerprintData>(rawData);
            Debug.WriteLine($"Matched Finger ID: {data.fingerID}, Status: {data.status}");
        }
        await Task.Delay(500);
    }
}

2. UART (GPIO Pins)

Use this only if USB isn't an option. Remember the level converter!

  • Wiring: Arduino TX → Level Converter 5V IN → Level Converter 3.3V OUT → Pi GPIO15 (RX); Arduino RX → Level Converter 3.3V IN → Level Converter 5V OUT → Pi GPIO14 (TX); Common Ground.
  • Enable UART on Pi: Go to the Windows IoT Device Portal → Devices → Serial Ports, and enable UART0.
  • Pi Code Adjustment: Change the device selector to SerialDevice.GetDeviceSelector("UART0") instead of enumerating all serial devices.

3. I2C

Great for low-power, multi-device setups, but requires stricter address management.

Arduino Side

#include <Wire.h>
#include <Adafruit_Fingerprint.h>

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&Serial1);
const int I2C_ADDRESS = 0x08; // Choose a unique address (0x08-0x77)

void setup() {
  Wire.begin(I2C_ADDRESS);
  Wire.onRequest(SendFingerprintData); // Triggered when Pi requests data
  Serial1.begin(57600);
  finger.begin(57600);
}

void loop() {
  // Fingerprint detection logic remains the same as USB example
  delay(1000);
}

void SendFingerprintData() {
  // Send a byte array or structured string to Pi
  int currentID = GetCurrentFingerID(); // Implement your fingerprint match logic here
  char buffer[20];
  sprintf(buffer, "{\"id\":%d}", currentID);
  Wire.write(buffer);
}

int GetCurrentFingerID() {
  // Reuse the fingerprint detection code from the USB example
  int result = finger.getImage();
  if (result == FINGERPRINT_OK) {
    result = finger.image2Tz();
    if (result == FINGERPRINT_OK) {
      result = finger.fingerSearch();
      if (result == FINGERPRINT_OK) {
        return finger.fingerID;
      }
    }
  }
  return -1; // Return -1 if no match
}

Raspberry Pi UWP Side

using Windows.Devices.I2c;
using Newtonsoft.Json;

public class I2cFingerprintData
{
    public int id { get; set; }
}

async void InitializeI2c()
{
    var i2cSettings = new I2cConnectionSettings(0x08); // Match Arduino's I2C address
    i2cSettings.BusSpeed = I2cBusSpeed.StandardMode;

    var controller = await I2cController.GetDefaultAsync();
    if (controller == null)
    {
        Debug.WriteLine("No I2C controller found!");
        return;
    }

    using (I2cDevice device = controller.GetDevice(i2cSettings))
    {
        byte[] readBuffer = new byte[20];
        while (true)
        {
            // Request data from Arduino
            device.Read(readBuffer);
            string rawData = System.Text.Encoding.ASCII.GetString(readBuffer).Trim('\0');
            
            if (!string.IsNullOrEmpty(rawData))
            {
                I2cFingerprintData data = JsonConvert.DeserializeObject<I2cFingerprintData>(rawData);
                Debug.WriteLine($"Finger ID from I2C: {data.id}");
            }
            await Task.Delay(1000);
        }
    }
}

Pro Tips for Reliable Communication

  • Use Structured Data: JSON or CSV makes parsing on the Pi side way easier than raw numbers/strings—no guessing where one value ends and another begins.
  • Add Checksum Validation: For critical data, calculate a simple checksum (e.g., sum of all bytes) on the Arduino, send it with the data, and verify it on the Pi to catch corrupted packets.
  • Debug with Serial Monitors: Use the Arduino IDE's Serial Monitor to confirm the Arduino is sending the right data. On the Pi, use the Windows IoT Device Portal's Serial Monitor to check incoming data.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:01:10