Shop OBEX P1 Docs P2 Docs Learn Events
Simple Object to Test SF02 Laser Rangefinder's Serial Interface — Parallax Forums

Simple Object to Test SF02 Laser Rangefinder's Serial Interface

Duane DegnDuane Degn Posts: 10,588
edited 2015-03-10 11:28 in Propeller 1
28043a.png?itok=vx9ebDDY

I'm using a SF02 Laser Rangefinder with my latest robot.

attachment.php?attachmentid=112500&d=1419657908

In order to test the serial interface of the SF02, I wrote a very simple test program.

I've been very impressed with the SF02. I made a short video comparing it with Joe Grand's Laser Rangefinder (not really a fair comparison). Joe Grand's rangefinder (which I also like) does not work well in the daylight but the SF02 didn't have any trouble with daylight or any other lighting conditions I tried.

One feature Joe Grand's rangefinder has which the SF02 doesn't is the ability to capture images. IMO, both of these rangefinders are great devices.

Apparently Parallax will soon be selling Lightware's SF10 laser rangefinder. Laser Developer made a very interesting post about developing the SF10.

The interface object is available from my GitHub account.

Here's the main section of the code.
CON

  _clkmode = xtal1 + pll16x                           
  _xinfreq = 5_000_000

  SR02_RX_PIN = 11 
  SR02_TX_PIN = 10
  
  DEBUG_BAUD = 115_200
  SR02_BAUD = 9_600 
  
OBJ

  Pst[2] : "Parallax Serial Terminal"

PUB Main

  Pst[0].Start(DEBUG_BAUD)
  Pst[1].StartRxTx(SR02_RX_PIN, SR02_TX_PIN, 0, SR02_BAUD)
  
  repeat
    Pst[1].Char("D")
    Pst[0].Home
    repeat
      result := Pst[1].CharIn
      if result <> Pst#LF ' skip linefeed
        Pst[0].Char(result)
    while result <> 13
    Pst[0].ClearEnd
    Pst[0].ClearBelow

As I previously said, it's very simple.

It just sends the character "D" to the SF02 RX line and receives and displays the returning data.

Here's some sample output:
1.45

I know it's practically trivial code but I thought it might be useful to someone new to Spin who wanted to use the SF02 with the Propeller.

The value isn't saved as a variable. If anyone needs help converting the ASCII characters to a variable, let me know and I could add some code to make the conversion.

Comments

  • Laser DeveloperLaser Developer Posts: 140
    edited 2015-01-06 01:43
    Great stuff Duane!

    For the last year we've concentrated on LRF applications that are related to UAVs where size and weight are the defining requirements. However, we want to put more effort into education and robotics during 2015.

    From feedback received so far, we have made a revision update to the SF02 and added a few things that we regularly get asked for:

    1. An analog port that outputs the laser signals - this is for educational purposes and for people who want to develop their own DSP algorithms.
    2. A digital expansion port on an unpopulated, 0.1" pitch header - this is for add-on boards or for people wanting to use different connectors.
    3. Multiple alarms on the digital port - this is to allow for "take evasive action", "slow down" and "stop" conditions that can be easily connected to IO pins on the host controller.
    4. A faster update rate to increase the resolution in scanning applications (SLAM) - 32 readings per second.
    5. Additional buffers on all IOs - to make the unit more robust when used in +5V systems.
    6. Lights and a buzzer - to make the unit more interesting to younger students.

    Of course, the idea of a complete laser scanning system is always a possibility, but we have looked at the economics of this and for educational robotic applications it doesn't make a lot of sense. The reason is that with the addition of a servo or stepper motor and maybe slip rings, you already have most of what's needed. If we were to supply these in a complete scanning system, we would need to markup the price of these readily available components making it much more expensive. I'd like to see an open source kit as an add-on to the SF02 instead.

    So now that you have experience in the practical application of LRF technology, what do you think should be the next cool capability to incorporate into a robot specific LRF design?
  • Duane DegnDuane Degn Posts: 10,588
    edited 2015-01-06 02:24
    For the last year we've concentrated on LRF applications that are related to UAVs where size and weight are the defining requirements.

    I think your rangefinders are a great match for UAVs. I have radio controlled airplanes, helicopters, quadcopters and a hexacopter. My airplanes all have holes in the bottom for camera lenses, like the one shown in the photo you shared in your development thread. I'll save my thoughts about using the rangefinder in UAVs for another time.
    However, we want to put more effort into education and robotics during 2015.

    From feedback received so far, we have made a revision update to the SF02 and added a few things that we regularly get asked for:

    To be honest only of few of these updates are very interesting to me.
    1. An analog port that outputs the laser signals - this is for educational purposes and for people who want to develop their own DSP algorithms.

    This sounds very interesting. I don't know enough about DSP algorithms to make use of this sort of feature but I'd like it as an option.
    2. A digital expansion port on an unpopulated, 0.1" pitch header - this is for add-on boards or for people wanting to use different connectors.

    I suppose this could be convenient. I think I feel comfortable adding whatever connectors I wanted anyway but I think I would prefer 0.1" headers over the the screw terminals but I'm not sure about this. I don't mind the connectors as they are now.
    3. Multiple alarms on the digital port - this is to allow for "take evasive action", "slow down" and "stop" conditions that can be easily connected to IO pins on the host controller.

    I think these sorts of alarms could be important to microcontrollers using interrupts but I don't think I see a big advantage to having these when using the SF02 with the Propeller. I'll just have the program make these sorts of decisions. It may be I haven't used the SF02 enough to realize how useful alarms could be.
    4. A faster update rate to increase the resolution in scanning applications (SLAM) - 32 readings per second.

    Yes. This is something I think would be very useful.
    5. Additional buffers on all IOs - to make the unit more robust when used in +5V systems.

    Again, I don't think this is very important when using the SF02 with the Propeller.
    6. Lights and a buzzer - to make the unit more interesting to younger students.

    I'm not sure about this myself. I think I'd rather add my own lights and buzzers.

    I know from my days of being a high school chemistry and physics teacher, teachers love having things already done. The less preparation time they need to spend on some aspect of a lesson the better. I think much of this is understandable but I was also horrified to see how often teachers relied on the "teacher edition" of a book without working through any of the problems themselves (the main problem with this approach was the teacher editions often had many mistakes (this was the "horrifying part")) (sorry for the rant).

    While I may not be very interested in having lights and buzzes added, I think many teachers would welcome such additions.
    Of course, the idea of a complete laser scanning system is always a possibility, but we have looked at the economics of this and for educational robotic applications it doesn't make a lot of sense. The reason is that with the addition of a servo or stepper motor and maybe slip rings, you already have most of what's needed. If we were to supply these in a complete scanning system, we would need to markup the price of these readily available components making it much more expensive. I'd like to see an open source kit as an add-on to the SF02 instead.

    Yes, I very much like the idea of an open source kit. I'll take some photos of the pan and tilt mechanism I'm using. I'm using the one I am, mainly because I had it on hand and it was really inexpensive (about $3 without the servos). I'm not sure if it's really strong enough to point the SF02 consistently. I had planned to test the precision in the next few days.
    So now that you have experience in the practical application of LRF technology, what do you think should be the next cool capability to incorporate into a robot specific LRF design?

    To be honest, my experience is still very limited but even with my limited experience I do have several ideas about possible LRF applications. It will take a bit of time to explain these ideas so I'll need to wait until another time to go into detail about them (it's 3:15 am here in Idaho). I'll make sure and get back to this topic soon. I'm very glad you asked about this.
  • Duane DegnDuane Degn Posts: 10,588
    edited 2015-01-09 02:52
    I'm still trying to figure out if my inexpensive pan and tilt mechanism will work well enough to identify obstacles in the robot's path.

    ICStationPanTilt0_11.PNG

    These pan and tilt mechanisms are availble through a lot of sources for about $3. The HXT900 servos are less than $3 each. I posted a couple of video of how to assemble them in this thread.

    I'm not sure how much effort I want to put into getting this inexpensive mechanism to work. Part of me thinks the SF02 deserves better than this inexpensive pan and tilt gadget but then I also like how easy these devices are to use and how inexpensive they are.

    My initial tests using this mechanism with the SF02 were inconclusive. I'm not sure if I can control the angle where the SF02 is pointed well enough to calculate the x, y and z coordinates of the target location. I think the SF02 combined with the pan/tilt mechanism would need to be able to detect obstacles a couple of centimeters high in order to use it as a primary obstacle avoiding tool for the the robot. I'm confident the SF02 is capable of this sort of precision but it's not clear if the pan/tilt mechanism's precision is good enough to detect small obstacles.

    I did find once the tilt angle had been set, panning the mechanism resulted in a relatively consistent "z" component to the calculated target positions. Perhaps the robot could perform some sort of calibration routine while the robot is positioned on a flat, obstacle free surface? This is one of several actions I will likely try as I attempt to make some sort of pointing device for the rangefinder.

    I have some ideas about how to make a better pan and tilt mechanism. I'll take some photos of the parts I'm considering using for this alternate mechanism and try to get them posted tomorrow.

    I added another file to my GitHub account. This version uses a method to return a numeric value of the distance reading. In order to represent the distance as an integer, the returned value is in units of centimeters rather than meters.

    Here's most of the code:
    CON
    
      _clkmode = xtal1 + pll16x                           
      _xinfreq = 5_000_000
    
      SR02_RX_PIN = 11 
      SR02_TX_PIN = 10
      
      DEBUG_BAUD = 115_200
      SR02_BAUD = 9_600 
    
      INVALID_READING = -999
      
    VAR
    
      long rangeInCentimeters
      
    OBJ
    
      Pst[2] : "Parallax Serial Terminal"
    
    PUB Setup
    
      Pst[0].Start(DEBUG_BAUD)
      Pst[1].StartRxTx(SR02_RX_PIN, SR02_TX_PIN, 0, SR02_BAUD)
    
      MainLoop
      
    PUB MainLoop | inputCharacter
    
      repeat  
        rangeInCentimeters := ReadLrf
        Pst[0].Home
        if rangeInCentimeters == INVALID_READING
          Pst[0].Str(string("Not Valid", 11, 13))
        else
          Pst[0].Dec(rangeInCentimeters)
          Pst[0].Str(string(" cm", 11, 13))
        Pst[0].ClearEnd
        Pst[0].ClearBelow
      
    PUB ReadLrf | validFlag, inputCharacter
    
      Pst[1].Char("D")
      validFlag := 0  
      repeat
        inputCharacter := Pst[1].CharIn
        case inputCharacter
          "0".."9":
            result := (result * 10) + (inputCharacter - "0")
            validFlag := 1
      while inputCharacter <> 13
          
      if validFlag == 0
        result := INVALID_READING
          
    


    The variable "rangeInCentimeters" can be used in comparisons allowing appropriate actions may be taken based on the measured distances.
  • Duane DegnDuane Degn Posts: 10,588
    edited 2015-01-12 20:12
    I wanted to add some additional filtering to the code reading the SF02. Initially I had hoped to use Phil's QuickMedian object but I found there were some data sets which caused the algorithm to endlessly loop.

    I wrote a very simple median finding algorithm which takes advantage of the likelihood of receiving multiple identical readings from the sensor.

    The code with the median algorithm is titled "Sf02LrfWithMedianFilter.spin" and is available from my GitHub repository.

    I'm not so sure how my inexpensive gimbal is going to work. I'm still hoping I can gather data from a calibration run in order to identify obstacles or drop offs.
  • Laser DeveloperLaser Developer Posts: 140
    edited 2015-01-12 20:36
    Another late night Duane? In our experience you are on the right track with a relatively low cost gimbal. To identify major features and obstacles, it doesn't matter too much if there is some angular distortion in the data, although you can improve repeatability by making sure that the scanning pattern is run in the same direction each time. To get an accurate, reversible system is very difficult, and even high end systems use feedback from angle sensors to correct for backlash or non-linear motions.
    The reason why top end LIDARs use such expensive and accurate aiming technology is because they are used more for mapping, not obstacle detection. To get optimal mapping information, the angular errors in the data should be of the same order of magnitude as the distance errors, so the accuracy of LRF technology has forced the designers into creating high precision systems.
    On the other hand, I think that obstacle avoidance will more closely mimic biological systems - avoid the obstacle at all costs, don't worry about the accuracy. Animals don't map their environment in the same sense that a SLAM system might. Instead they make a decision using high level logic as to which general direction to go in, then spend the rest of the journey using reflexive course adjustments based on lower level data to prevent walking into things.
  • Duane DegnDuane Degn Posts: 10,588
    edited 2015-01-14 21:21
    I took some photos of the $10 (including servos) gimbal I'm using with the SF02/F.

    When positioning the LRF for a measurement, I have the servos always move from the same direction. I found these cheap servos would whine a lot as they struggled to move to the final destination. To preserve my sanity I added some code which would relieve some of the strain on the servos by driving the servos 20us past the destination and then "backing up" to the final position (the tilt servo was driven 60us past it's intended position and then reversed to the final position). The servos don't actually move while backing up, the motors just release some of the strain inside the gearbox. I was concerned this noise reducing technique would cause an increase in the angular error of the servos. Fortunately for my nerves, the noise reducing code didn't cause an increase in measured errors. If anything, the the errors were reduced with this code in place (though the error reduction may have been caused by other improvements to the control algorithm).

    Here's some output with the robot on the bench. The robot is elevated above the floor so the distance measurements are about 1 meter larger than they would be when at ground level.
    [165] -7, [187] 7, [187] 0, [187] 7, [187] 7
    [151] 0, [175] 0, [174] -12, [191] 6, [218] 6
    [141] 5, [174] 0, [201] 0, [194] 10, [280] 20
    
    Over All Average = 3
    Over All Minimum = -12, # 7, pan = 1530, tilt 1443
    Over All Maximum = 20, # 14, pan = 1330, tilt 1360
    

    The 15 sets of data include the distance inside the [] brackets followed by the calculated distance above the ground based on the angle of the servos and adding a correction factor from a previous calibration run.

    The bracketed distance measurements are in units of centimeters but the distance above ground values are in units of millimeters.

    I'm pleasantly surprised how well this inexpensive pan/tilt mechanism is working. In the above example, the worst error in the computed ground level was 2 centimeters (20mm).

    I've run a similar test on level ground with similar results.

    The 15 measurements were taken with three different tilt settings and five pan positions (5 columns and 3 rows). The pan servo would return to the same side to start each row of samples. The pan servo would turn 200us past the start position in order to keep the backlash state of the gearbox identical (as practical) between samples. I only used 15 sample positions to speed up the debugging process. I didn't want to wait for long calibration runs to complete before I could see what the error amounts were.

    As I previously mentioned, this pan/tilt mechanism is a very inexpensive device. While I wasn't opposed to modifying the mechanism, the structure of the device was not conducive to having the SF02 pointed in a similar manner as a small camera which is commonly used with these gimbals.

    I decided to sacrifice some range of motion in order to make it easier to mount the SF02 to the gimbals. When the tilt portion of the gimbals was in it's full upward position, the mounting surface provided a nice level attachment point for the SF02.

    attachment.php?attachmentid=112826&d=1421296598

    Normally, with the gimbal in the above position, an attached camera would be pointing straight up. I didn't need to point the SF02 straight up but I did want to be able to point the LRF higher than the horizon. I gave the SF02 some vertical elevation by using an extra set of standoff on the front pair of mounting holes.

    attachment.php?attachmentid=112824&d=1421296598

    By measuring the height of the standoff and using the distance between the mounting holes, I was able to calculate the offset from horizontal caused by the standoffs. I didn't really need to calculate this value since I ended up just adjusting the position of the servo until the SF02 was level with the horizon and recorded the pulse length required to achieve this position (1030us for my setup). The servos moved pretty close to 45 degrees with a change in pulse length of 500us. I used this conversion factor to compute the servo angles. I also measured the height of the SF02 above the ground to use when calculating the XYZ coordinates of the LRF target locations.

    While the tilt mechanism had a limited vertical range, it could point the SF02 straight down if desired.

    attachment.php?attachmentid=112827&d=1421296598

    Here's a photo with the top piece of expanded PVC removed.

    attachment.php?attachmentid=112825&d=1421296598

    I hope to make a video of the pan/tilt device in action soon. While this mechanism certainly isn't appropriate for creating 3D maps, I think it will probably be accurate enough to help the robot avoid obstacles and drop offs.

    I still intend to post some ideas on alternate pan/tilt devices which will hopefully offer greater accuracy. I'll save these musing for another time.
    568 x 541 - 149K
    578 x 631 - 167K
    781 x 613 - 194K
    774 x 671 - 253K
  • Duane DegnDuane Degn Posts: 10,588
    edited 2015-01-15 20:40
    Here's a video showing the gimbal in "action" (there's not a lot of action in the video).

    For now, I just had the robot take 15 readings per scan. It starts out making a calibration scan and asks if the calibration data should be saved or not. If the calibration data is saved, it will then make another scan using the calibration readings to determine where ground level is located.

    I added a box to the scan area and then had the robot point to the largest deviation from level ground it had found in its scan. It could easily find the box but smaller obstacles weren't always found.

    I have a lot of work to do before being able to use the laser rangefinder (LRF) while the robot is in motion. The code used in this demo had lots of debug statements inline with the code moving the servos and making the measurements. There are several ways, besides removing these debug statements, the scan rate of the LRF could be increased. I think the scan rate shown in the video is much slower than is possible with the hardware I'm using.

    I'm not sure if I should continue with this particular hardware setup of if I should pause from the software side of the project to build a better gimbal to point the LRF. Besides making an improved gimbal, the accuracy of object detection could be increased by elevating the position of the LRF on the robot. Having the LRF pointing ahead with very shallow angles make it very difficult to detect the height of an obstacle. The closer the LRF can be to pointing straight down, the better the accuracy of the height calculations.

    While I'm seriously considering making a better gimbal for the LRF, I still think this inexpensive gimbal has the potential of allowing the LRF to successfully detect obstacles.

    I may switch projects for a little while and work on improving the Eddie firmware a bit more before continuing my efforts of using the LRF for obstacle detection. I was hoping to have my robot able to perform some interesting tasks while at the same time testing the Eddie firmware. Watching for obstacles with the LRF is one such task I think would be both interesting and very useful.
  • ercoerco Posts: 20,256
    edited 2015-01-23 16:30
    Cool setup. Looks like a lot of weight for that poor little pan/tilt bracket to schlep around!
  • Duane DegnDuane Degn Posts: 10,588
    edited 2015-01-23 17:28
    erco wrote: »
    Cool setup. Looks like a lot of weight for that poor little pan/tilt bracket to schlep around!

    I kind of agree. These are the mighty HXT900 servos and they don't appear to complain about the weight. The servos don't even whine (anymore) while holding the rangefinder in position.

    The servos used to whine a lot but I gave the servos instructions to move slightly past the target and then move back to the target. This removes most of the strain on the servos once they reach their final destination. As I'm sure you're aware, analog servos exert a force proportional to the distance from the target position. With this extra weight, the servo's firmware didn't drive the motors hard enough to reach the target position. Since the actual position of the servo was so close to the target position only a small amount of force was exerted. This small force wasn't enough to overcome the static friction of the gearbox especially when attempting to move the weight of the LRF. My trick of commanding the servos to move past the target and then return to the target allowed the static friction of the gearbox to work in the servos favor. By moving a little past the target first, once the servos reached their target destinations, they drew very little current.

    I'm inclined to think the SF02/F deserves a better pan/tilt mechanism but I have too many other projects vying for my attention. My large hexapod is practically screaming for me to code some proper eye animations and to tame the bucking motion of its gait. I also need/want to polish the Eddie firmware a bit more.

    I have some very fine resolution encoder disks I removed from a printer. I think it would be really interesting to see if they could be used with a DC motor to accurately point the LRF. In a way this would overlap with the Eddie firmware project since I'm trying to improve the quadrature encoder based position control algorithm of the Eddie firmware. It would be nice if the same code used to control the Eddie's position could also be used to control the angular position of a LRF gimbal.

    Another idea is to use the 12-bit magnetic encoders I've played with as a way of pointing the LRF. My attempt to use the magnetic encoders inside a servo didn't work very well, but if I were to mount the magnet and encoder chip precisely, I think I'd have a much better chance of precisely aiming the LRF. I have a small hobby lathe and I'd think I could probably use it to machine a proper magnet holder.

    Of course a stepper motor is another very appealing method of pointing the LRF. Laser Developer mentioned using stepper motors in the scanner he developed for a client. Stepper motors may end up being the best option but these other options would be interesting to try.

    You've just about got me talked into making a better gimbal. If only I didn't also have to make a [url="http://forums.parallax.com/showthread.php/159729]single motor robot[/url], I may have time to work on this project some more.
  • ercoerco Posts: 20,256
    edited 2015-01-23 20:26
    I love those pan/tilts you found for $3. Two of them might make a cool biped! There's a whole other challenge, a 4-servo walker.

    But yes, we also need a bigger pan/tilt for standard servos.
  • KDBrownKDBrown Posts: 13
    edited 2015-02-04 09:02
    From feedback received so far, we have made a revision update to the SF02 and added a few things that we regularly get asked for:

    1. An analog port that outputs the laser signals - this is for educational purposes and for people who want to develop their own DSP algorithms.
    2. A digital expansion port on an unpopulated, 0.1" pitch header - this is for add-on boards or for people wanting to use different connectors.
    3. Multiple alarms on the digital port - this is to allow for "take evasive action", "slow down" and "stop" conditions that can be easily connected to IO pins on the host controller.
    4. A faster update rate to increase the resolution in scanning applications (SLAM) - 32 readings per second.
    5. Additional buffers on all IOs - to make the unit more robust when used in +5V systems.
    6. Lights and a buzzer - to make the unit more interesting to younger students.
    I have an SF02 on order, does this list mean that there should be a new version of the manual...and when is the new version available?
  • PublisonPublison Posts: 12,366
    edited 2015-02-04 10:28
    KDBrown wrote: »
    I have an SF02 on order, does this list mean that there should be a new version of the manual...and when is the new version available?

    Welcome to the forums!

    Your other post was deleted because it was a double post, and not allowed in the forums:

    http://forums.parallax.com/showthread.php/134682-Forum-Guidelines

    As far as the SF02, where did you back order it from, Parallax or Lightware? I guess it doesn't matter since both are out of stock. I would think Lightware is ramping up the new revision.

    I guess we will all have to wait and see.
  • KDBrownKDBrown Posts: 13
    edited 2015-02-04 15:28
    Sorry, I didn't consider that the posts would be taken as the same. One was (intended) to be just about the revision level of the unit and the docs. I did not order it, my customer did, and from Parallax. I was hoping that I'd get a response from "Laser Developer" himself...

    Actually the other post was intended to discern whether the SF02's settings (as established via the USB link) would go away when power did. In no way should that have been seen as a redundant post (unless I forgot to ask the question...can't tell 'cause its gone).

    So let's be clear:
    * Is the SF02 expected to be in stock any time soon? Is the 17th of Feb date on the unit's sale page accurate?
    * Is what will be delivered different from what the present documentation says? (I'm laying out a PCB here so need to know what I'll be talking to!)
    * Is the set-up maintained when power goes away?

    Thanks to any and all!
  • KDBrownKDBrown Posts: 13
    edited 2015-03-10 11:28
    OK, I have an SF02, Rev 3 PCB. I don't know how many Parallax took in but they flew off the shelves: all gone already.
    There are advances and differences, the newest manual is on the Lightware site, not on the Parallax product page.
    And the answer to my #3 is yes, the settings are kept.
Sign In or Register to comment.