我想使用 Raspberry Pi 使用 I2C 从 Arduino 读取
I want to read from Arduino using I2C using Raspberry Pi
我想通过 Raspberry Pi 使用 c++ 代码从 Arduino 读取数据。
但是,我在寻找解决方案时遇到了一些困难。
对于这个问题,我可以找到任何好的信息来源吗?
到目前为止我已经能写这么多了,但我知道这肯定行不通。
网络上的许多资源似乎都集中在 python 和向 arduino 发送数据而不是从 arduino 接收数据。
'''C++
#include <iostream>
#include <stdio.h>
#include <string>
#include <sstream>
#include <linux/i2c-dev.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#define MicroControlAdr 0x8;
static const char* devName="/dev/i2c-1";
using namespace std;
int main(int argc, char **argv)
{
cout<<"Hello, World!\n";
cout<<"I2C connection..."<<endl;
int file;
if ((file=open(devName, O_RDWR))<0)
{
cout<<"I2C: Failed to Access "<< devName<< endl;
return -1;
}
ioctl (file, I2C_SLAVE, 0x8);
float char_ar[16];
read(file,char_ar,16);
cout<<char_ar[16];
return 0;
}
'''
'''Arduino
#include <Wire.h>
void setup()
{
//Join Arduino I2C bus as slave with address 8
Wire.begin(0x8);
Wire.onRequest(requestEvent);
}
void loop()
{
delay(100);
}
void requestEvent()
{
unsigned char char_ar[16]="Hi Raspberry Pi";
Wire.write(char_ar,16);
}
'''
所以我想要的是当 C++ 程序执行时,Arduino 会发送 "Hi Raspberry Pi" 到终端,但它给了我奇怪的数字 4.2039e-45
float char_ar[16];
read(file,char_ar,16);
cout<<char_ar[16];
这看起来不对。您正在尝试读取浮点数组而不是字符数组,然后打印元素 16,这是数组末尾之后的元素,因为索引是从零开始的。
试试这个:
char char_ar[16];
read(file,char_ar,16);
cout << char_ar;
我想通过 Raspberry Pi 使用 c++ 代码从 Arduino 读取数据。 但是,我在寻找解决方案时遇到了一些困难。
对于这个问题,我可以找到任何好的信息来源吗?
到目前为止我已经能写这么多了,但我知道这肯定行不通。
网络上的许多资源似乎都集中在 python 和向 arduino 发送数据而不是从 arduino 接收数据。
'''C++
#include <iostream>
#include <stdio.h>
#include <string>
#include <sstream>
#include <linux/i2c-dev.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#define MicroControlAdr 0x8;
static const char* devName="/dev/i2c-1";
using namespace std;
int main(int argc, char **argv)
{
cout<<"Hello, World!\n";
cout<<"I2C connection..."<<endl;
int file;
if ((file=open(devName, O_RDWR))<0)
{
cout<<"I2C: Failed to Access "<< devName<< endl;
return -1;
}
ioctl (file, I2C_SLAVE, 0x8);
float char_ar[16];
read(file,char_ar,16);
cout<<char_ar[16];
return 0;
}
'''
'''Arduino
#include <Wire.h>
void setup()
{
//Join Arduino I2C bus as slave with address 8
Wire.begin(0x8);
Wire.onRequest(requestEvent);
}
void loop()
{
delay(100);
}
void requestEvent()
{
unsigned char char_ar[16]="Hi Raspberry Pi";
Wire.write(char_ar,16);
}
'''
所以我想要的是当 C++ 程序执行时,Arduino 会发送 "Hi Raspberry Pi" 到终端,但它给了我奇怪的数字 4.2039e-45
float char_ar[16]; read(file,char_ar,16); cout<<char_ar[16];
这看起来不对。您正在尝试读取浮点数组而不是字符数组,然后打印元素 16,这是数组末尾之后的元素,因为索引是从零开始的。
试试这个:
char char_ar[16];
read(file,char_ar,16);
cout << char_ar;