我让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之间的连接:
问题:我已经在用c#编写的Pi代码上部署了Visual的通用windows应用程序,但是代码中出现了异常。异常和错误如下:
引发的'System.Runtime.InteropServices.COMException‘异常:中的
WinRT信息:未能将连接设置应用于设备.
附加信息:附加到系统上的设备无法工作。
要求:我已经在互联网上搜索了关于这个异常的所有信息,但是没有找到任何解决方案,Raspberry Pi 2无法与Arduino or通信,不知道是Arduino侧还是Raspberry Pi侧的问题。
请帮我解决这个问题。
发布于 2016-04-01 09:39:43
看来你的台词错了。通常,SCL引脚连接到SCL,SDA连接到SDA。它不会像UART那样被逆转。
https://stackoverflow.com/questions/36011264
复制相似问题