简体   繁体   中英

I want to read from Arduino using I2C using Raspberry Pi

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.

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);
}

'''

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

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.

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM