2

Im trying to send string data from arduino to raspberry pi via i2c. Raspberry pi can receive the data of particular length(probably32 bytes) of string since bus.read_i2c_block_data(address,0) read 32bytes only. But the string send from arduino to raspberry pi has length exceed 32bytes. Below code is arduino code.

#include <Wire.h>
#define SLAVE_ADDRESS 0x04
int sensorPin = A3;
int sensorValue;
String str;
String stringOne = "ldr";
//char data[50];
int index = 0;
void setup()
{
Wire.begin(SLAVE_ADDRESS); // join i2c bus (address optional for master)
Serial.begin(9600);
Wire.onRequest(sendData);
}

void sendData() {
sensorValue = analogRead(sensorPin);
String tagvalue = String("ldr=") + sensorValue;
//Serial.println(tagvalue);
tagvalue = String(tagvalue);
//String tagvalue1;
//tagvalue1 = String(",led=off");
tagvalue = String(tagvalue) + String(",streamkey=98081d09-4359-4b8b-8ba5-f265430155ff");
Serial.println(tagvalue);
//Wire.write('c');
//Serial.println("hi");
Wire.write(tagvalue.c_str());
//delay(1000);
//nWire.write(String("hi").c_str());
//Wire.write(tagvalue1.c_str());


}

void loop()
{
sendData();
delay(5000);
}

Raspberry pi code:

import smbus
import time
bus = smbus.SMBus(1)
address=0x04
data=""
value=""
while True:
  #print 'reading'
  value = bus.read_i2c_block_data(address,0)
  for i in range(len(value)):
      data+=chr(value[i])
  print data
  time.sleep(2)
  data=""
  value=""

This is the string im trying to receiving...

"ldr=254,led=on,stream=98081d09-4359-4b8b-8ba5-f265430155ff"

Im getting this error in raspberry pi when i try to receiving the above string.

Traceback (most recent call last):
File "i2cstr.py", line 8, in <module>
character = bus.read_i2c_block_data(address,0)
IOError: [Errno 5] Input/output error

How to solve this problem?

1 Answer 1

1

The Python smbus module limits itself to SMBus commands which have a 32 byte limit.

You could bit bang or you could use the underlying /dev/i2c-1 device from Python. You should be able to find examples of both on the www.

My pigpio Python module implements I2C as well as SMBus commands.

#!/usr/bin/env python

import time

import pigpio

pi = pigpio.pi()

handle = pi.i2c_open(1, 0x04)

start = time.time()

while (time.time() - start) < 60:

   (length, bytes) = pi.i2c_read_device(handle, 46)

   print(length, bytes)

   time.sleep(2)

pi.i2c_close(handle)

pi.stop()

You shouldn't really use address 0x04, it's meant to be a reserved address.

I2C doesn't really lend itself to messages of varying length. It's probably best to use messages with a fixed size.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.