Monthly Archives: October 2026

Porting LIDAR-based ‘Find Best Direction’ to Vision-Enhanced Robot

Posted 13 October 2026

While working on my new ‘vision-enhanced’ robot project, it became apparent the the OAK-D Lite camera was not the best tool for handling a ‘stuck’ condition where the robot has nosed into something and needs to find a better movement direction. The camera After some experimentation, I found that by moving the rear-facing VL53L1X LIDAR distance sensor to the front of the robot, I could turn the robot under manual (‘C’) control and watch the reported LIDAR distances change. Since I had already solved the ‘Find Best Direction’ problem on my older robot, I decided to port the code into the new vision-enhanced robot.

Looking back through my old code in C:\Users\Frank\Documents\Arduino\WallE3_Git\WallE3_Git\WallE3_Git.ino, I found a reference to this post. It wasn’t directly relevant as it discussed the problem of sorting multiple arrays in a synchronized fashion so as to arrive at a situation where all the distance and heading sensor arrays are sorted in lockstep with a ‘master’ array containing front distance readings. Then the ‘dependent’ array readings associated with the maximum front distance reading can be easily read off.

This isn’t really necessary for the vision-enhanced robot, as there are only two sensors of interest – the front distances and the associated headings. I believe I should be able to set up two small lists (say 10 elements; front distance readings and associated headings. As the robot rotates, each new distance reading is compared to the stored ones, and replaces the largest value that is smaller than it. The headings array value associated with the replaced heading value gets replaced by the heading value associated with the new distance value. At the end of the rotation, the distance array should contain the 10 highest distance readings, sorted in descending order, and the heading array should be synchronized to their associated distances. Then an ‘appropriate’ heading can be selected from the data (‘appropriate’ to be defined later).

It turns out UpdateIMUHdgValDeg() already manages a HEADING_HISTORY_ARRAY_SIZE array of heading values, where earlier values are bumped up (down in index) and the latest value is stored at gl_HdgHistoryArray[HEADING_HISTORY_ARRAY_SIZE – 1]. If I also have a HEADING_HISTORY_ARRAY_SIZE array of distance values that are handled in the same manner, that should be all I need. I’m pretty sure I already have that array, as that is what is used to calculate variances needed to detect ‘stuck’ conditions. Yep – its there but named ‘aRearDistCM’ instead of ‘aFrontDistCM’. I’ll let that ride until everything is working and then change ‘Rear’ to ‘Front’ everywhere. CalcBruteRearDistArrayVariance() is also there for stuck detection. bool IsStuckBehind() is missing so copied it from WallE3_Git.ino to VisionEnhancedRobot…’. ino (into MISCELLANEOUS section).

Looking back through the code and previous posts, I built up the ‘QuickSort’ algorithms to handle just this situation, so abandoning them for something simpler does not seem real smart; it’s already there, and it works.

Well, maybe not. Looking at WallE3_Git.ino, I see that the RunToDaylight() code does not appear to use QuickSort at all – it does the ‘simpler’ idea of rotating 10 deg at a time, recording both heading and distance. After the rotation I see:

which is pretty much exactly the ‘simpler’ idea I was thinking about.

Well, I may have spoken too soon. WallE3_Git.ino has *two* ‘RunToDaylight()’ functions, ‘RunToDaylight()’ and ‘RunToDaylightV2()’, and ‘RunToDaylight()’ is apparently never called and was replaced by ‘RunToDaylightV2()’ which incorporates the QuickSort algorithms. However, only RunToDaylightV2() Step5:

applies to this situation – all the other code is aimed at finding a trackable wall. Step5 is basically ‘RunToDaylight()’ with the distance and heading arrays presorted by decreasing distance with

I made the decision to port all the ‘RunToDaylightV2()’ and supporting code to the new ‘stuck-recovery’ branch, trimmed down to just the ‘Hdg’ and ‘FrontD’ arrays for now (may later want to add RearD, but not now). This is basically just the ‘Step5’ portion of ‘RunToDaylightV2()’, with the addition of all the supporting code for QuickSort operations.

I have the ‘stuck ahead’ detection running now. Here’s a sample output:

The next step is to use the ‘RunToDaylightV2()’ function and supporting QuickSort code to determine the best direction to travel *after* IsStuck() returns TRUE.

18 October 2026 Update:

After getting the stuck-recovery code working, I created a new C++ project on my PC to parse through the output generated by the 360 degree scans from ‘stuck-recovery’. Here’s the final code:

Including both 36-point (10 deg steps) and a 72-point (5 deg steps) datasets from the ‘stuck-recovery’ code. With the 72-point (5 deg steps) scan data active, the .cpp program produces the following output.

The above plot was generated using a small Python program generated by Grok, as shown below:

19 October 2026 Update:

Grok modified the ‘polar_scan.py’ script to pull the required ‘bestStart’ and ‘bestEnd’ values directly out of the raw data from the robot. With the following data

The polar_scan.py program produced the following plot:

This is a bit of an unrealistic scenario, as I deliberately started the robot scan with its front toward the open doorway, in order to excite the edge case where the ‘best direction’ lobe crosses over the +/- 0 deg boundary. In reality the ‘best direction scan will almost certainly start with the robot pointed away from the ‘best’ direction, as that condition is what triggers the ‘run to daylight’

It is also unrealistic in another way, in that this data was collected with my robot sitting on my bench, with the robot’s VL53L1X distance sensor about 90cm off the ground. In reality it will be more like 17cm off the floor in real operation.

Here is the scan from the robot sitting on the floor, starting with its nose just a few centimeters away from a simulated wall, with the open area behind it.

As the plot shows, there is a fairly wide of headings from about -135 to +135 deg, with the peak at about -170 or so. This corresponds very to the actual layout of my lab.

I attached my iPhone to the robot in the same place as the VL53L1X sensor and ran another 360 scan. The result was this video:

261019 360 deg scan in 5-deg steps, starting with the robot’s nose just a few cm from a simulated wall

The far doorway can be seen in the video at about the 8 second mark.

20 October 2026 Update:

The ‘Find Best Direction’ study is complete. the ‘polar_scan.py’ script takes the scan data from the robot and produces the polar plot shown below:

Now it’s time to integrate all this back into the mainline repo. I had a conversation with Grok about this, and I believe I am coming around to his/its way of thinking. Have the teensy handle initial ‘stuck’ detection using a variance threshold on the front-facing VL53L1X. If a stuck condition is detected, notify the Pi5. The Pi5 tells the teensy to back up 1 sec & perform a 360 deg scan and report distances and headings. The Pi5 will then run the above ‘polar_scan’ script to determine the best escape direction and tell the teensy to turn to that heading. After that the Pi5 uses the camera to validate the escape direction, and if it agrees, normal travel/navigation is resumed.

21 October 2026 Update:

I committed/pushed the ‘stuck-recovery’ branch from my PC – this is all the stuck-recovery scan code, but minus all the required integration code.

So, what to do about the big switch statement in CheckForUserInput? Right now it switches on the first character of the string. Some commands are truly single-character (C, H, U…) but some are single-alpha + numeric (Txx, Lxx, Rxx), where the ‘xx’ are arbitrary numeric characters. Now I want to add full-string commands like ‘STUCK_SCAN’, but this results in “Unknown top-level character”. I could add a ‘S’ case, but I might eventually run out of single-character commands. Maybe the way to handle this is with a ‘!’ (bang) prefix, which says “look at the full string”. A case statement like “case ‘!’: would handle all multi-alpha characters commands and would then use internal ‘if’ statements to accommodate an arbitrary number of commands

So, I started with “!STUCK_SCAN”. When this string is entered at the serial port, CheckForUserInput() runs this code:

It stops the motors and then calls RunToDaylightV2():

which repeatedly calls SpinTurn(true, 5) to scan 360 degrees.

This all works great – except – – – when RunToDaylightV2 is running a scan, it can’t be stopped – oops! The reason it can’t be stopped is because it isn’t calling CheckForUserInput() inside the ‘for’ loop. The obvious answer is to place a call to CheckForUserInput() inside the loop and then send a ‘C’ character to the teensy, which will stop the motors ….. except that it doesn’t; it stops the motors, but then the next call to SpinTurn() starts them up again – rats!

So, next we try using the bool return from CFUI() to guard the SpinTurn() calls, like so:

But, this doesn’t work either, because the call to CFUI here doesn’t have anything to do with the part of CFUID that called RunToDaylightV2 – completely separate. So, I finally decided that the only way to reliably handle this (and other similar) issues is to establish a global ‘status’ variable ‘gl_AnomalyCode’ that can be set in CFUID and read anywhere. I actually had this in my previous WallE3_git project, and even had a separate ‘enum.h’ file to house the anomaly codes and other enums. I copied just the AnomalyCode section from enum.h, as shown below:

Then I added the global variable ‘uint8_t gl_AnomalyCode = ANOMALY_NONE;’ to hold the current anomaly code, and set it to ‘ANOMALY_STUCK_AHEAD’ in the ‘!STUCK_AHEAD’ CFUI section, and back to ‘ANOMALY_NONE’ in the ‘C’ CFUI section. This fixed the problem entirely (but not necessarily elegantly). RunToDaylightV2 checks the value of gl_AnomalyCode each time through the scan loop, and terminates if it isn’t ANOMALY_STUCK_AHEAD.

After sleeping on this, I started thinking that what I really want instead of (or maybe in addition to ANOMALY_CODES is a SYSTEM_STATUS enum, with STATUS_MANUAL_CONTROL set system-wide whenever the user inputs ‘C’.

enum SystemStatus {   STATUS_MANUAL_CONTROL = 0,   STATUS_AUTO_NAV }; SystemStatus gl_SystemStatus = SystemStatus::STATUS_AUTO_NAV;

Then, in RunToDaylightV2():

    if (gl_SystemStatus == STATUS_MANUAL_CONTROL)     {       return;     }

And in CheckForUserInput() -> ‘C’ case:

gl_SystemStatus = SystemStatus::STATUS_MANUAL_CONTROL

And in CheckForUserInput() -> ‘C’ case:

And in RunToDaylightV2():

I will keep the AnomalyCode stuff around as well, but just not for this purpose:

After making these changes, I ran the Teensy program and simulated a Pi5 command to perform a stuck scan by sending “!STUCK_SCAN’ at the PC serial port, and then sent ‘C’ after the scan actually started, with the following output:

23 October 2026 Update:

So now I have the teensy RunToDaylightV2() and CheckForUserInput() code modified to handle ‘!STUCK_AHEAD’, ‘STATUS_MANUAL_CONTROL’ and ‘!STUCK_SCAN’ situations, it’s time to make the associated changes/additions to the Pi5 code.

In a ‘stuck_ahead’ situation, the teensy sends ‘!STUCK_AHEAD’ to the Pi5 via Serial1, and it is captured by the ‘telemetry_loop()’ function.

As shown in the code above, any line from the teensy of the form “[timestamp]: [body]” where ‘body’ is “DONE [cmd]”, “ACK [cmd]”, or “BUSY [cmd]” has the [body] extracted and placed in the ‘teensy_events’ queue. This queue is examined in ‘wait_for_done’ and if one of the above strings is present, does the right thing. This isn’t directly applicable to the ‘stuck’ situation, but something similar will be necessary. ‘telemetry_loop’ will have to recognize the anomaly flag from the teensy and pass it along to the main nav function

25 October 2026 Update:

I’m getting closer to the complete ‘stuck ahead’ interaction between the teensy and the pi5, but still having problems.

In order to allow the ‘manual control’ command (now ‘M’) to abort a 360-degree scan, I added

which skips all the remaining SpinTurn() invocations.

26 October 2026 Update:

I’m running into some conceptual (or maybe semantics) issues with the robot project. The Pi5 recognizes two different modes; ‘Auto’ where the Pi5 drives by sending commands to the robot via Serial1, and ‘Manual’ where the user drives by sending commands to the robot via either a direct USB cable connection (Serial) or by way of the wireless SSH connection to the robot (relayed by the Pi5 over Serial1). In ‘auto’ mode, only the Pi5 talks to the robot.

09 November 2026 Update:

The ‘stuck_ahead’ recovery project is pretty much complete. The robot will now recognize the situation, perform a ‘stuck_recovery’ process that includes using the front-facing LIDAR to measure the available ‘straight ahead’ distance every 5 degrees around a complete rotation, then turning to the ‘best’ direction and proceeding. Here’s a short video showing the recovery operation:

Once we got ‘stuck-recovery’ going, it became apparent that we had somehow managed to kill the ‘rolling turn’ behavior of the normal auto-nav mode. We finally figured out that we needed a new ‘!TWEAK command and another default argument to the SpinTurn(). function, and this got us back to the original ‘rolling turn’ behavior, as shown in the following short video:

At this point the ‘stuck-recovery’ project is pretty much complete, so I decided to merge the ‘stuck-recovery Github branch back into the ‘main’ branch. This turned out to be *much* more complicated than I thought, and I would never have gotten it done without Grok’s help. I am learning a lot about git version control and ‘history’ vs ‘code’, so that’s a win at least.

Next up ‘Too Close’ recovery: This should be identical to the ‘stuck_ahead’ case, differing (I think) only in the triggering condition.

26 November 2026

Well, as usual I spoke too soon about “the ‘stuck-recovery’ project is pretty much complete“. Grok and I kept running into additional issues, but most of them, at least, have been addressed successfully. I took the robot with me to St. Louis for Thanksgiving dinner with family, and the robot got a chance to strut its stuff. It actually did very well until it ran out of battery (and unfortunately, I forgot an essential cable for recharging the battery), so I counted that as a plus.

At this point, the ‘obstacle_ahead’ and ‘stuck_ahead’ actions are working pretty well, and so I no longer need the ‘too close’ action.

Vision-enhanced Robot ‘Find Best Direction’ Issue

Posted 14 October 2026

WallE, my autonomous wall-following robot had a nominal capability called “run to daylight”. The idea was to use this as a last resort when all the other ‘find a wall and follow it’ tricks failed. Unfortunately, I never could get this to work and never figured out why. Fast forward to the present, and Grok and I were trying to implement the same kind of capability into the new vision-enhanced version, to address the issue of what to do when the robot gets stuck.

Basically, the algorithm is the same as it was for the wall-following version; back up, look around and turn to the heading that provides the most freedom (‘largest depth’ in vision processing language). We (Grok and I) implemented the “back up and look around” operations using the new ‘L/Rxxx’ (where ‘xxx’ is in degrees), and then the ‘turn to the best heading’ utilizes a new ‘Txx’ command which is implemented via the already-existing ‘TurnToHdgDeg()’ function.

Unfortunately, although the ‘back up and look around’ part worked almost immediately, the ‘turn to the best heading’ part failed miserably, with the end result consistently going off in a completely different direction. I was somewhat mystified by this, as I was suffering from the (soon-to-be-debunked) belief that my MPU6050 IMU/DMP was actually delivering accurate heading measurements, and the problem must be in the ‘TurnToHdgDeg()’ function. However, data beats belief, so I decided to go back to basic ‘show me’ experiments.

To validate the MPU6050 IMU function operation, I set up an experiment where I manually rotated the robot on a printed compass rose, and measured the output of the IMU at each point, as shown in the following Excel table and resulting plot:

The above plot looks ugly, but a lot of the ugliness is due to the way IMU heading output jumps from +180 to -179; this is normal. What isn’t normal is the way the IMU reported heading diverges from the actual heading – the +180 to -179 transition occurs between 150 and 160 degrees rather than 180, and the -179 to +180 transition occurs between -140 and -150 degrees on the other side.

At first I thought this must be due to a bad IMU module, but changing out the module for a brand-new one produced the same results – so not that (further validation of my “hardware never fails – its ALWAYS the software” mantra).

So, I made another plot, this time manually changing the ‘opposite sign’ measurements back into the proper range by adding/subtracting 360 degrees. This produced the following plot:

Just looking at the ‘positive’ half from 0 to 180 deg, it is clear that the measured values are consistently higher than the actual physical headings. Looking at the first five values (before the first breakpoint in the plot) we see the differential goes from zero to about 156.8-120 = 36.8 deg over a 150 deg range, or about 36.8/150 = 0.25 deg/deg. Assuming the difference is linear, then the required multiplication factor should be 156.8X = 120 –> X = 120/156.8 = 0.769. For example, a multiplicative factor of 0.787 yielded the following plot:

Good enough for government work ;).

This factor can’t be applied directly to the IMU yaw output, as that value has already been corrected for the +/- 180 arrangement, so Grok suggested an algorithm to hold a ‘running total’ heading that uses IMU heading changes to produce a separate heading value that is corrected for the slope error and only afterwards applies the +/- 360 adjustment for the +/-180 scheme, as follows:

18 October 2026 Update:

Since the last post I have been working hard on the ‘Find Best Direction’ problem, and now I (with lots of help from Grok Code) have it pretty much licked. Rather than continue to mess up my robot Arduino code, I created a small C++ console project to study the process of converting the raw Heading/Front Distance values from a robot 360-degree scan into one or more ‘runs’ of distance/heading pairs where the distance part is greater than some threshold (currently set at 200cm).

Originally I thought that the way to go was to first reverse-sort the timestamp, heading and distance data fields with ‘distance’ as the master field. This would give me all the distances in descending order, with the associated heading and timestamp values listed with them. To do this I ported the ‘QuickSort’ machinery from my May 2024 ‘Wall3_Git’ project into my ‘stuck_recovery’ branch of my current ‘VisionEnhanced4WheelRobot’ Github repo, and then onward to my little ‘RobotBestDistV2.cpp’ exploratory project, shown below:

Almost half of the actual code above is dedicated to QuickSort-related code, and as I have now found out – none of it is actually necessary – elegant, pretty – and useless. Once I took all that out, the RobotBestDistV2.cpp test program shrank down to something much smaller, as shown below:

The above is about 360 lines long, and well over half of it is copy/pasted test data from the robot scans.

After figuring that out, I used the robot code to actually do the 360 scan to collect the heading/distance data and then copy/pasted the data in text form into my RobotBestDistV2.cpp test program. This allowed me to iterate pretty quickly through different techniques while keeping the two programs isolated from each other.

The first set of data (commented out in the above code) was from a 360 scan in 10 deg steps for a total of 36 steps. This was nice, but I wanted to see what would happen with 5 deg steps – and that is the second set of data. I also wanted to verify if this test program would handle the (highly improbable, but not impossible) case where the best ‘far’ lobe spanned the +/- 0 deg split (it does – yay!). Here’s the printout from the last run:

Looking at the raw data, you can see that one section of the ‘far’ lobe goes from ‘samples[0]’ through ‘samples[12]’ and the other section goes from ‘samples[69]’ through ‘samples[71]’, for a combined ‘far’ lob of about 78.6 deg. Cool!