Some questions about i2c.write

Can someone explain why the I2c.write takes a string for the data?
seems strange to take "string" values.
such as if I wanted to write 3 bytes:
_i2c.write(_addr,"\x02" + "\x00" + "\x00");

Yet using spi.write I dont need to do that. These "writes" should follow the same format.

And since it does take string values then why doesn't this then work;
local value = blob(3);

value.writen("\x02",'b'); // also tried the 'c' parm and still no go.
value.writen("\x00",'b');
value.writen("\x00",'b');

_i2c.write(_addr,value);


I mean it does for the spi write, why not then for the I2c ?

Lastly, how does one take in a value from say a sensor, then pass this value to a I2C device?
The data is going to be raw, and then I need to convert it to a string so I can pass it along using i2c. write.


Comments

  • You're right, i2c.write is a bit inconsistent. In most other places, blobs are coerced to strings when required.

    As for your bit of code, you've found another bug really in that the first parameter of blob.writen should be an integer (or float), not a string, but no error gets reported. Here's a version which should hopefully have those issues fixed:
    local value = blob(3);
    value.writen(0x02, 'b'); // note no quotes around the 2
    value.writen(0x00, 'b');
    value.writen(0x00, 'b');
    _i2c.write(_addr, value.tostring()); // explicit coercion to string
    Peter
  • edited May 2015
    You could also do:

    value.writestring("\x02")

    yes?
  • @peter, thank you. that did work just fine.
  • Would like to add that I saw another way to do it as well.

    _i2c.write(_addr, format("%c%c%c", 0x02, value1, value2));

    saw this from ersatzavian@ github
    https://github.com/electricimp/reference/blob/master/hardware/SX150x/SX150x.device.nut


  • If we're making a complete list:
    _i2c.write(_addr, "\x02" + value1.tochar() + value2.tochar());
    Peter
  • Peter, I believe that is one of the first things I tried and it worked very strangely.

    I have a I2C PCA9555 IC with 16 leds connected to it.
    I did this and the leds did not output correctly using that.

    counts <-0;

    function tick()
    {

    // This works
    _i2c.write(_addr, format("%c%c%c", 0x02, counts, 0x00));

    // This did not, leds acted strangely.
    // _i2c.write(_addr, "\x02" + counts.tochar() + "\x00");

    counts++;

    imp.wakeup(0.5, tick);
    }

  • Update: a task for i2c.write() to support blobs as well as strings is in the impOS backlog
Sign In or Register to comment.