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

Jason Ju
  • 25
  • 1
  • 7
  • You probably haven't configured the Raspberry Pi correctly for I2c communication. Check out this link: https://www.raspberrypi-spy.co.uk/2018/02/change-raspberry-pi-i2c-bus-speed/ – jignatius Oct 07 '19 at 05:13

1 Answers1

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;
jignatius
  • 6,304
  • 2
  • 15
  • 30
  • 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? – Jason Ju Oct 06 '19 at 06:38
  • Why memsetting an array that you are going to overwrite anyway? That's just pointless... – Aconcagua Oct 06 '19 at 07:40
  • @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 Oct 06 '19 at 07:46
  • @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. – Aconcagua Oct 06 '19 at 08:48
  • I have this issue as well, https://stackoverflow.com/questions/58255579/raspberry-pis-terminal-response-has-weird-font-that-cannot-be-recognized Can't seem to solve the problem. – Jason Ju Oct 07 '19 at 03:21