基于Windows IoT的树莓派3与Arduino I2C写数据实现求助
Hey there! Let's work through this I2C write issue between your Raspberry Pi 3 running Windows IoT and your Arduino slave. Since you've already got reading working, you're halfway there—let's get that write functionality sorted out.
First: Make Sure Your Arduino Slave is Configured to Receive Data
The Arduino needs to listen for incoming I2C writes from the Pi. Use the Wire library's onReceive callback to handle data when it arrives. Here's a minimal working example:
#include <Wire.h> // 🔔 This address MUST match the one you use in your Windows IoT code! #define ARDUINO_SLAVE_ADDRESS 0x08 void setup() { // Initialize I2C as a slave with our chosen address Wire.begin(ARDUINO_SLAVE_ADDRESS); // Register a callback function to run when data is received Wire.onReceive(receivePiData); // Start serial monitor to debug received data Serial.begin(9600); } void loop() { // Nothing needed here—callback handles incoming data delay(100); } // Callback function to process data from the Pi void receivePiData(int byteCount) { while (Wire.available()) { // Read one byte at a time (adjust this based on your data format) char receivedByte = Wire.read(); Serial.print("Received from Pi: "); Serial.println(receivedByte); // Add your logic here—e.g., toggle an LED, store a value, etc. } }
Key notes here:
- Double-check the slave address matches exactly between Arduino and Windows IoT code.
- Use the Arduino Serial Monitor to verify if data is coming in—this is critical for debugging.
Second: Implement I2C Write on Windows IoT (Raspberry Pi)
Since you're using a TextBlock, I assume you're working with a UWP app. Here's how to set up I2C write functionality in C#:
1. Add I2C Permission to Your App Manifest
First, open Package.appxmanifest and add the I2C capability (without this, your app won't have access to the bus):
<Capabilities> <DeviceCapability Name="i2c" /> </Capabilities>
2. Initialize I2C and Write Data
Here's the code to initialize the I2C controller and send data to the Arduino:
using Windows.Devices.I2c; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; public sealed partial class MainPage : Page { private I2cDevice _arduinoI2cDevice; // 🔔 Match this address to the one in your Arduino code! private const int ArduinoSlaveAddress = 0x08; public MainPage() { this.InitializeComponent(); // Initialize I2C when the page loads _ = InitializeI2cAsync(); } private async Task InitializeI2cAsync() { try { // Get the default I2C controller on the Pi var i2cController = await I2cController.GetDefaultAsync(); if (i2cController == null) { StatusTextBlock.Text = "No I2C controller found on the Pi!"; return; } // Configure I2C settings (use StandardMode first for compatibility) var i2cSettings = new I2cConnectionSettings(ArduinoSlaveAddress) { BusSpeed = I2cBusSpeed.StandardMode // 100kHz, matches Arduino's default }; // Connect to the Arduino slave _arduinoI2cDevice = i2cController.GetDevice(i2cSettings); StatusTextBlock.Text = "I2C connection initialized successfully"; } catch (Exception ex) { StatusTextBlock.Text = $"I2C init failed: {ex.Message}"; } } // Example: Trigger write when a button is clicked private async void SendDataButton_Click(object sender, RoutedEventArgs e) { if (_arduinoI2cDevice == null) { StatusTextBlock.Text = "I2C not initialized—check connections!"; return; } try { // Convert your message to a byte array (adjust based on your data needs) string messageToSend = "Hello from Pi!"; byte[] writeBuffer = System.Text.Encoding.ASCII.GetBytes(messageToSend); // Send the data to Arduino await _arduinoI2cDevice.WriteAsync(writeBuffer); StatusTextBlock.Text = $"Sent data: {messageToSend}"; } catch (Exception ex) { StatusTextBlock.Text = $"Write failed: {ex.Message}"; } } }
Key notes for the Windows IoT side:
- Use
StandardMode(100kHz) first—Arduino's default I2C speed is 100kHz, mismatched speeds can cause write failures. - Always wrap I2C operations in try/catch blocks to catch errors like permission issues or loose connections.
Third: Debugging Tips if It Still Fails
If you're still having issues, work through these checks:
- Verify Wiring: Ensure SDA (Pi GPIO2 ↔ Arduino A4), SCL (Pi GPIO3 ↔ Arduino A5), and GND are connected securely. No common ground = no reliable communication.
- Scan for I2C Devices: Run an I2C scanner on the Pi (or Arduino) to confirm the Arduino's slave address is visible. If it's not, your wiring or Arduino setup is wrong.
- Check Serial Monitor: On the Arduino side, open the Serial Monitor (9600 baud) to see if data is being received. If you see nothing, the issue is on the Pi's write side or wiring.
- Check for Address Conflicts: Make sure no other devices on the I2C bus are using the same address as your Arduino.
内容的提问来源于stack exchange,提问作者user6480540

