Infrared sensor to ROS

I have an experimental robot with five old Sharp infrared distance sensors.

I found this code and did some changes in order to add five sensors.

#!/usr/bin/python
import spidev

spi = spidev.SpiDev()
spi.open(0,0)
spi.max_speed_hz=1000000


def readChannel(channel):
  val = spi.xfer2([1,(8+channel)<<4,0])
  data = ((val[1]&3) << 8) + val[2]
  return data

if __name__ == "__main__":
  v1=(readChannel(0)/1023.0)*3.3
  dist1 = 16.2537 * v1**4 - 129.893 * v1**3 + 382.268 * v1**2 - 512.611 * v1 + 301.439
  print "Distance: %.2f cm" % dist1

  v2=(readChannel(1)/1023.0)*3.3
  dist2 = 16.2537 * v2**4 - 129.893 * v2**3 + 382.268 * v2**2 - 512.611 * v2 + 301.439
  print "Distance: %.2f cm" % dist2

  v3=(readChannel(2)/1023.0)*3.3
  dist3 = 16.2537 * v3**4 - 129.893 * v3**3 + 382.268 * v3**2 - 512.611 * v3 + 301.439
  print "Distance: %.2f cm" % dist3

  v4=(readChannel(3)/1023.0)*3.3
  dist4 = 16.2537 * v4**4 - 129.893 * v4**3 + 382.268 * v4**2 - 512.611 * v4 + 301.439
  print "Distance: %.2f cm" % dist4

  v5=(readChannel(4)/1023.0)*3.3
  dist5 = 16.2537 * v5**4 - 129.893 * v5**3 + 382.268 * v5**2 - 512.611 * v5 + 301.439
  print "Distance: %.2f cm" % dist5

Is there a way to do a ROS python script?

You may find this question is better suited for answers.ros.org, or that following some of the python tutorials on the wiki answers this for you.

1 Like