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

查看:22
本文介绍了我想使用 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

#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];

这看起来不对.您正在尝试读取浮点数而不是字符数组,然后打印元素 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天全站免登陆