我想使用Raspberry Pi使用I2C从Arduino阅读 [英] I want to read from Arduino using I2C using Raspberry Pi

查看:109
本文介绍了我想使用Raspberry Pi使用I2C从Arduino阅读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过Raspberry Pi使用c ++代码从Arduino阅读. 但是,我在寻找解决方案时遇到了一些困难.

I want to read from Arduino using c++ code via Raspberry Pi. However, I am facing some difficulty in finding solution.

是否可以找到有关此问题的良好信息来源?

Is there any good source of information I can find for this problem?

到目前为止,我已经能够写出这么多了,但是我知道它绝对行不通.

So far I've been able to write upto this much, but I know it definitely does not work.

网络上的许多资源似乎都集中在python上,而不是从arduino接收数据,而是将数据发送到arduino.

Many sources on the web seems to focus on the python, and sending data to arduino rather than receiving data from 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

'''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

So what I want is when C++ program is executed, Arduino will send "Hi Raspberry Pi" to terminal, but it gives me weird number of 4.2039e-45

推荐答案

float char_ar[16];
read(file,char_ar,16);
cout<<char_ar[16];

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

This doesn't look right. You are trying to read an array of floats instead of chars, then printing element 16, which is one past the end of the array since indexing is zero based.

尝试一下:

char char_ar[16];
read(file,char_ar,16);
cout << char_ar;

这篇关于我想使用Raspberry Pi使用I2C从Arduino阅读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆