Hello great community of helpers! We new programmers greatly appreciate your continuous help. Thank You!

Can you explain this 1 line of code below... - Or break it down into separate chunks. I read the documentation, and am still a little foggy.

n = struct.unpack('<l', ''.join([chr(i) for i in block[:4]]))[0]

For reference, Here is all the relative code from another working snippet from Here. This is an Arduino sending a long int over i2c to a raspberry pi.
Raspberry Pi Code:

import smbus
import time
import struct
# for RPI version 1, use "bus = smbus.SMBus(0)"
bus = smbus.SMBus(1)

# This is the address we setup in the Arduino Program
address = 0x04

def readLong():
   block = bus.read_i2c_block_data(address, 0) 
   #second arg is 'cmd'. It is mandatory but not used in this case. 
   #It may be used by the higher level protocol
   # block is a list of 32 elements (int)
   #return block
   n = struct.unpack('<l', ''.join([chr(i) for i in block[:4]]))[0]
   return n

while True:
   number = readLong()
   print "[Arduino]", number, "mm"

And Here is the Arduino Code:

    #include <Wire.h>

int SLAVE_ADDRESS = 0x04;
int ledPin = 3;
int analogPin = A0;

boolean ledOn = false;

void setup() 
    pinMode(ledPin, OUTPUT);

void loop()

void requestEvent()
  long d;
  d=300259; // mockup value, in the real script is acquired by the sensor
  Wire.write((const uint8_t*)&d, sizeof(long));

Thanks You!


It's converting the first four bytes received by read_i2c_block_data() to a long assuming the data is stored most significant byte first.

I guess read_i2c_block_data() returns a list rather than a string. If it returned a string I'd use the more natural

n = struct.unpack('I', block[:4])

The ''.join([chr(i) for i in block[:4]]) invocation appears to be a "clever" way (which exponents call Pythonic) of converting a list to the string needed by unpack.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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