Project Predator, part three – Code

So let me just say right up front that I basically don’t code and I have never in my life looked at a Python script before this project.  If anyone happens to know of better approaches for anything I’ve done here, I’d sure like to know.

I wanted a few changes in the functionality of the Rainbow Hat.  Since reloading was intended to be automatic (driven by a state change from magazine not inserted to magazine inserted), I didn’t need one of the Hat’s three buttons for that purpose.  I also didn’t want a power-down button since I intended to just pull the battery and 1500 mAh of juice will run a Pi for a long time.  I decided to set the possible options of magazine size in code, and use the A button to switch to the next smaller size, use the B button to show the current magazine size, and use C to switch to the next larger size.  But I wanted feedback on magazine size changes in real time, and since the number of darts available doesn’t change until a magazine is ejected and replaced, I had the idea to use the alphanumeric display on the Hat.

BUT, given that the Hat is generally displaying distance from the range sensor, I had to determine a way to free up the display at the time of magazine size change and then hand it back to the rangefinder.  I’m sure there’s a far better way but since I’m new to coding, I decided to have the ammunition script call the rangefinder script as a subprocess, and kill that process whenever a button is pressed which requires the display.  The main ammo loop queries as to whether the range subprocess is running, and if not, starts it again.  Because of that, the ammo script is the only script that autoruns at startup – follow the instructions here to get autorun working.

I also wanted a nice, easy to recognize alert when the mag is either empty or removed.  Luckily the Hat has a piezo buzzer, so it will alert for either shots = 0 or magazine not inserted with a series of 0.3-second beeps.

Here is the code for the primary script

And here’s the code for the rangefinder subroutine:


Leave a Reply

Your email address will not be published. Required fields are marked *