Advertisement
Simonik

I2C

Feb 7th, 2016
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.22 KB | None | 0 0
  1. Arduino
  2.  
  3. void requestEvent() {
  4.   byte DEV_CNT =4;
  5.   float hodnoty[DEV_CNT];
  6.   hodnoty[0]=10000;
  7.   hodnoty[1]=20;
  8.   hodnoty[2]=1029.50;
  9.   hodnoty[3]=3333.123456789;
  10.  
  11.  // Buffer to hold temp data, 4 bytes for each device
  12.  
  13.   byte buffer[DEV_CNT*4];
  14.  
  15.  
  16.   // Populate buffer with temp. data
  17.   for(int a = 0; a < DEV_CNT; a++) {
  18.     byte* b = (byte*) &hodnoty[a];
  19.     // 4 bytes for each float
  20.     for(int i = 0; i < 4; i++) {
  21.       buffer[a*4+i] = b[i];
  22.     }
  23.   }
  24.   // Send data over i2c connection
  25.   Wire.write(buffer, DEV_CNT*4);
  26. }
  27.  
  28. Raspberry
  29. #!/usr/bin/python
  30. import smbus
  31. import time
  32. import struct
  33.  
  34. bus = smbus.SMBus(1)
  35. address = 0x03
  36.  
  37. while True:
  38.     try:
  39.         data = bus.read_i2c_block_data(address, 0);
  40.     except:
  41.         print "Error getting data\n"
  42.         continue
  43.     # Example uses 4 sensors.
  44.     # Each float from the Arduino is 4 bytes long.
  45.     print len(data)
  46.     print data
  47.     for i in range(0, 4):
  48.         bytes = data[4*i:4*i+4]
  49.         # Python 2 struct.unpack takes the data to be unpacked
  50.         # in string format, so the bytes need to be joined
  51.         # together first
  52.         print struct.unpack('f', "".join(map(chr, bytes)))[0]
  53.     print
  54.     time.sleep(5);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement