我想使用Raspberry Pi使用I2C从Arduino读取

问题描述 投票:0回答:1

我想通过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

c++ arduino i2c
1个回答
0
投票
float char_ar[16];
read(file,char_ar,16);
cout<<char_ar[16];

这看起来不正确。您正在尝试读取一个浮点数组而不是char数组,然后打印元素16,该元素比数组末尾晚一个,因为索引是从零开始的。]

尝试一下:

char char_ar[16];
read(file,char_ar,16);
cout << char_ar;
© www.soinside.com 2019 - 2024. All rights reserved.