我将 Arduino UNO 设为奴隶,将 Raspberry Pi 2 设为主人。在 Arduino UNO 上运行的代码如下:
#include "DHT.h"
#include<Wire.h>
#define DHTPIN 4 // what digital pin we're connected to
#define DHTTYPE DHT11 // DHT 11
#define SLAVE_ADDRESS 0x29
DHT dht(DHTPIN, DHTTYPE);
int t;
void setup() {
Serial.begin(9600); //setting baud rate for communication
Wire.begin(SLAVE_ADDRESS); //assigning slave with i2c at defined slave address
Wire.onRequest(sendData); //Event for sending the data through i2c
dht.begin();
}
void loop() {
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
t = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print("\n");
Wire.onRequest(sendData); // asked to send the data
delay(1000);
}
void sendData(){
Wire.write(t);
Serial.print("in send data:"+t);
}
Raspberry Pi 2 代码是用 c# 编写的。如下:
using System;
using Windows.UI.Xaml.Controls;
using Windows.Devices.Enumeration;
using Windows.Devices.I2c;
using System.Diagnostics;
using System.Threading;
namespace App2
{
public sealed partial class MainPage : Page
{
private I2cDevice Device;
private Timer periodicTimer;
public MainPage()
{
this.InitializeComponent();
initcomunica();
}
private async void initcomunica()
{
var settings = new I2cConnectionSettings(0x29); // Arduino address
Debug.WriteLine(settings);
settings.BusSpeed = I2cBusSpeed.StandardMode;
Debug.WriteLine(settings.BusSpeed);
string aqs = I2cDevice.GetDeviceSelector("I2C1");
Debug.WriteLine(aqs);
var dis = await DeviceInformation.FindAllAsync(aqs);
Debug.WriteLine(dis);
Debug.WriteLine(dis[0].Id);
Device = await I2cDevice.FromIdAsync(dis[0].Id,settings );
periodicTimer = new Timer(this.TimerCallback, null, 0, 1000); // Create a timmer
}
private void TimerCallback(object state)
{
byte[] RegAddrBuf = new byte[] { 0x08 };
byte[] ReadBuf = new byte[5];
try
{
Device.Read(ReadBuf); // read the data
Debug.WriteLine(ReadBuf);
}
catch (Exception f)
{
Debug.WriteLine("error in reading from buffer"+f.Message);
}
// Converte Byte to CharArray
char[] cArray = System.Text.Encoding.UTF8.GetString(ReadBuf, 0,5).ToCharArray();
String c = new String(cArray);
Debug.WriteLine(c);
}
}
}
Raspberry Pi 2 和 Arduino UNO 之间的连接:
- Arduino UNO (A4-SDA) 的模拟引脚连接到 Raspberry Pi 2 的引脚 5(SCL)
- Arduino UNO (A5-SCL) 的模拟引脚连接到 Raspberry Pi 2 的引脚 3(SDA)
使用电阻为 1K ohm 和 2k ohm 的分压器电路为 Pi 提供 3.3V 而不是 5V。
DHT11 传感器与 Arduino UNO 的连接。
问题:我已经在用 c# 编写的 Pi 代码上从 Visual Studio 部署了通用 Windows 应用程序,但我在代码中遇到异常。异常和错误如下:
抛出异常: mscorlib.ni.dll 中的“System.Runtime.InteropServices.COMException”
WinRT 信息:无法将连接设置应用到设备。
附加信息:连接到系统的设备无法运行。
要求:我在互联网上搜索了有关此异常的所有内容,但没有找到任何解决方案,Raspberry Pi 2 无法与 Arduino UNO 通信。不知道是 Arduino 方面的问题还是 Raspberry Pi 方面的问题。
请帮我解决这个问题。