title: Parsing float from i2c with ruby on raspberry pi
body: <p>this is mostly a ruby question.</p>
  
  <p>I'm stuck trying to parse some bytes from an i2c device to a float value on ruby.</p>
  
  <p>Long story:</p>
  
  <p>I'm trying to read a float value from an i2c device with raspberry pi and an AtTiny85 (the device). i'm able to read its value from console through i2ctools</p>
  
  <p>Example:</p>
  
  <pre><code>i2cset -y 0 0x25 0x00; sleep 1; i2cget -y 0 0x25 0x00; i2cget -y 0 0x25 0x00; i2cget -y 0 0x25 0x00; i2cget -y 0 0x25 0x00
  </code></pre>
  
  <p>Gives me:</p>
  
  <pre><code>0x3e
  0x00
  0x80
  0x92
  </code></pre>
  
  <p>that means 0.12549046, which is a value in volts that i'm able to check with my multimeter and is ok. (the order of the bytes is 0x3e008092)</p>
  
  <p>Now i need to get this float value from a ruby script, I'm using the <a href="http://www.rubydoc.info/gems/i2c/0.4.0/I2C/Dev" rel="nofollow">i2c gem</a>.</p>
  
  <p>A comment on <a href="http://www.dsprobotics.com/support/viewtopic.php?f=2&amp;t=1602" rel="nofollow">this site</a> suggest the following conversion method:</p>
  
  <pre><code>hex_string = '42880000'
  float = [hex_string.to_i(16)].pack('L').unpack('F')[0]
  # =&gt; 68.0
  
  float = 66.2
  hex_string  = [float].pack('F').unpack('L')[0].to_s(16)
  # =&gt; 42846666
  </code></pre>
  
  <p>But i haven't been able to get this string of hex values. This fraction of code:</p>
  
  <pre><code>require "i2c/i2c"
  require "i2c/backends/i2c-dev"
  
  @i2c = ::I2C.create("/dev/i2c-0")
  sharp = 0x25
  
  @i2c.write(sharp, 0)
  
  sleep 1
  
  puts @i2c.read(sharp, 4).inspect
  </code></pre>
  
  <p>Puts on screen</p>
  
  <pre><code>"&gt;\x00\x00P"
  </code></pre>
  
  <p>Where the characters '>' and 'P' are the ASCII values of the byte in that position, but then i cannot know where/how to split the string and clean it up to at least try the method showed above.</p>
  
  <p>I could write a C program to read the value and printf it to console or something and run it from ruby, but i think that would be an awful solution.</p>
  
  <p>Some ideas on how can this be done would be very helpful!</p>
  
  <p>Greetings.</p>