0

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

1

1 Answer 1

0
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;
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, looks like it works, but somehow, it doesnt give me Hi Raspberry Pi but gives me weird 0 0 0 3 inside of square as response. Do you know anything about this?
Why memsetting an array that you are going to overwrite anyway? That's just pointless...
@JasonJu Now the error is more likely to be on the Arduino side. Have you set the baud rate correctly? e.g. Serial.begin(9600);
@jignatius I²C; transmission speed is defined by clock signal only, generated by master (well, OK, clock-stretching by slave not considered). Serial is UART interface.
I have this issue as well, stackoverflow.com/questions/58255579/… Can't seem to solve the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.