Sending 4 empty bits

Posted on
  • Is there a way to directly represent 4 empty bits in JS? To send 0000 over I2C, it seems I have to use an array of 0's.

  • I see that espruino supports the binary prefix, 0b, so 0b0000 should work, and appears to work, but reading the empty byte and printing it out ('0000') seems to take a lot of effort in C++ (my slave device for testing use is an arduino uno).

  • I2C is sending by specification always 8 bits - the 8 lower bits of the bytes (or values in an array) you provide. Easiest is a plain integer number that you mask with & 15. Bits 5 through 7 (counting from 0 and LSB) get nulled. If you need to pack four booleans into 4 bit, you can do that by addition of the mapping values of 1, 2, 4, and 8. Unpacking can be done in a similar way... and the fun part is that JavaScript looks at any number that is not 0 as true in a logical statement, so receiving r = 6 can be masked out in to var bool0 = r & 1, bool1 = r & 2, bool2 = r & 4, bool3 = r & 8;, and the code logic (in JavaScript) is if (bool2) { // is true for r = 6... or you simply say if (r & 2) { .... That's one of the beauties of JS (and of course also a trap if you are not familiar with...). Bit masking/testing is not much different in Arduino world.

    To actually answer your question literally: just send 0 ( ....writeTo(..., 0, ...) ).

  • As @allObjects says, it's not possible to send just 4 bits via I2C on any platform, it's just the way I2C works - you have to send a byte at a time.

    Your best bet is to send a whole byte and only use the bottom 4 bits - so sending 0b0000 like you're doing with Espruino is fine.

    but reading the empty byte and printing it out seems to take a lot of effort in C++

    Welcome to embedded software! :)

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Sending 4 empty bits

Posted by Avatar for CriscoCrusader @CriscoCrusader

Actions