Yet Another Garden Waterer

Like many other people with an arduino and a garden, I was irresistably drawn to spending a lot of time making a thing that would save me having to water the veggie patches. My requirements are little more constraining than some, perhaps…

There’s a veg plot at the end of the garden. It’s a fairly long garden. No chance of mains water down there, but that’s ok, I can have a diverter at the top of the house’s downpipe and that gives enough pressure head to get to the veg patch. No chance of mains power, so this needs to be off grid. That also pretty much rules out anything but the smallest pumps, so something gravity fed ideally.
I’ll only have stored water, so don’t want to waste it on rainy days, so we’ll need some smarts. And I quite like to know what’s going on, so may as well thrown in some data collection too.

So like any reasonable person would I grabbed an ESP32 from the drawer and set to…

Valves

First problem to solve was how to let the water out when I want to and not when I don’t. Solenoid valves draw way too much current, for the whole time they’re open, and need 12v. No way that was going to work. So it was accomplished at first using a hacked watering timer of the green, circular kind that you’ll find on the usual tat emporium. I won’t link it because the link will just expire but they’re a motorised pilot valve in a convenient housing. Remove the timer and drive the motor yourself and you’re away. It sucked though. Just not enough flow. Problem was that a) there wasn’t really enough pressure for it in my gravity fed system, and b) it needed a motor driver board (I used a TB6612FNG) to run it, which made it awkward to have more than 2 of them, and with my watering pipes split into only 2 zones there was really not enough flow to get them all dripping. So I’ll fast forward year 1 and just show you what I built for year 2.
There are 6 raised beds to water, and we buried individual hose runs under the paths to each of them when we put them in, so 6 valves for 6 zones made the most sense.

Back to those solenoid valves…. if only there was a way to hold them open without the current being on…
Well, turns out you can rip the solenoid off and a permanent magnet works just as well. With an adaptor to hold a magnet on a servo arm we only need to use power to open and close them. I kept the motor controller in place to gate the servos’ power. So they’re only drawing while they need to be. A microswitch on top allows for position feedback.

Permanent magnet valves

They’re housed in a food container and power and control goes through a chopped up cat5e cable back to the ESP. Water supply is through an ‘it’ll do’ combination of hose fittings.

Valve box and manifold. The messy coil in the background is not involved.

Power

It’s a solar panel in an old CD jewel case. Iteration 1 struggled a bit in the autumn on cloudy days, so I built in a hinged mount with another sg90 servo buried inside. It doesn’t track the sun as such because it turns out going too far down that rabbit hole can waste more power than it gains, but every hour it gets nudged around to point vaguely the right way. Works pretty well.
The 2000 mAh Li battery is taken from a cheap tablet, having replaced it with a better one as soon as I bought the tablet.
TP4056 handles charging. 2W solar panel, 110×136 mm, fits very neatly in a CD jewel case making weatherproofing trivial. The case does go yellow over the course of a summer, but the world isn’t exactly short of jewel cases these days so it can be replaced.
It’s massive overkill most of the time. I did not need this much power or storage. It barely gets down to 4V overnight and is back up to 4.2 as soon as the sun fully hits it. The sun ‘tracking’ just means I get a bit further into October, or get through almost an entire fortnight without a sunny day in summer, before it starts to struggle.

Barrel depth gauge

The water from the house runs down 19mm hose into a barrel, which is balanced via a 12mm hose with a IBC, so between them there’s 1200 and some litres there. That’s a good start.

It was quickly clear though that the flow rate drops off massively as the barrel empties. This meant a level sensor (or flow rate sensor) was essential, not just the nice-to-have I thought it would be.
First effort was a simple one. A laser rangefinder, VL53L0X, pointed at the water surface worked fine in testing, so I quickly moved on to deployment. There were a few issues to work out, mostly related to I2C over 5 m of wire, but that one was solved with stronger pullups. Power use was a concern too but again easily solved by switching the GND pin of the VL530LX using a GPIO so it’s only powered when needed.

The laser was always flaky, and readings jump around a lot. Averaging helped, so into the barrel it went.


The morning after I went out to check on it and as expected it was covered in condensation. It was still working (I guess rainwater isn’t that conductive) but the droplets caused all kinds of bad readings. That aside, it’s rubbish at measuring close-up things anyway so a full barrel is hard to get a handle on.
After about a week it started throwing more and more errors. Clearly it’s not going to last in a wet environment. Need a plan B that’s more reliable and robust.

This.

Barrel gauge mk2

It’s a roll of string jammed on the axle of a 10-turn potentiometer. It’s spring-loaded by one of those retractable badge holder things wound around the smaller diameter side. On the end is a water-filled bottle as a weight/float that will sit on the water surface.

Coming up to 2 summers of use now and still trucking.

Sensing

There’s a soil moisture probe stuck in the ground, ubiquitous capacitive type. It’s ok. Does seem to vary output a lot with temperature changes though. I’ve tried to calibrate it out without much success.
There’s also a Dallas type temperature probe in a screen in the shade, just for interest. It gets reported but doesn’t influence decisions.

Packaging

Is not pretty.

The ESP (on DOIT Devkit board) is connected to what it needs to be on a stripboard in a super simple 3d printed case, shoved in a food container screwed to a fence post. Not much to look at. Interesting thing to note here though, it’s on the hairy edge of the wifi reach from the house. I was having real issues with it, and it was reporting really flaky RSSI of like -90dB. But then I lined the food container with aluminium tape and now it’s more like -65 to -80 and pretty reliably connects.
Everything is hooked up via superseal connectors which are awesome but you have to print your own strain reliefs, and then those connectors are still stuffed inside the food tub anyway. It works. Don’t judge.

Behaviour

The esp wakes up every 5 mins. It checks battery voltage, soil moisture, tank level. It checks whether all the valves are in the closed position (and sends a message via callmebot if they’re not where they’re meant to be). It connects to wi-fi and gets NTP time and a weather forecast and parses it (omg that was a lot of code), then checks for any changes to parameters or commands on a local server (the overworked household pi, obviously). It decides whether to water and how much based on predicted temperature, rainfall, tank level (hence flow rate) and time of day. The multipliers and constants are pulled from the local server each wake cycle, so parameters can be updated easily. They include things like how long to water each bed for before adjustment, how much extra for dry soil, how much extra for barrel depth, what the min/max ADC readings are for the barrel gauge and moisture probe, that sort of stuff. All stored in the ESP’s EEPROM and updated if changed.
It should only water twice a day, once early and once late, so if it’s not time or too wet or about to rain the info just gets posted to iotplotter, and with some additional verbosity and debug info into a Google sheet. Then it’s esp deep sleep until the next wake up. If it is time to water the valves get opened in sequence for however long each needs with a deep sleep in between.

There’s an override mode, accessible by a switch on the case or by a command in the file it checks for locally on wake up, which causes it to stay awake and serve a webpage with manual controls. Mostly for testing and to allow me to balance all the drippers.

So far, most of the way into its second summer now, it’s been working. Really well actually. Overall I’m pretty happy. We can go away and leave it in charge, and find the plants mostly still alive when we get back. Well, the ones that the drippers reach at least.

Issues/upgrades

When the tank level is low the pressure is low. This means a lot of the outlets run dry. I had planned to add a header tank with a solar powered lift pump to keep a constant head. However the new plan after this year’s epic drought is just to get another IBC for more storage. May as well stack that on top of the existing and just let it be the header tank.

The weather API I’m using, openweathermap, has a habit of reporting an anomalous rain prediction every now and then, so that when it’s definitely going to rain, and it’s been telling you for hours it’s going to rain, you’ll get a one-off forecast of zero rain. This screws things up because we’ll be very much not intending or needing to water, but then get tricked into watering by that one-off forecast. Not sure whether to try to code around it or just get the forecast somewhere else.

Arduino Ignition

The why

For a while now I’ve been running a megajolt v3 ignition system. You can read about what it is and what it does for yourself: https://wiki.autosportlabs.com/MJLJ_V3_vehicle_installation_guide
Important terms to take from that are:
EDIS – Ford’s coil driver and toothed wheel interpreter black box thing
PIP – signal sent from the EDIS when it wants a SAW
SAW – signal communicating how much advance to give

More info on this super-useful page: http://www.megamanual.com/ms2/EDIS.htm

The megajolt has been great, and there’s nothing really wrong with it, but lately I’ve been wanting to tweak the maps a little. That would be trivial if I still had a windows laptop to run the windows only bespoke tuning software, but I don’t any more. I tried using a VM on my linux machine with the MJ powered up on the desk, but couldn’t get it to communicate through the infamously flaky ‘Prolific’ serial/USB adapter thing and it was proving a hassle to work out what was at fault. Was it the VM not having the right drivers? The host machine not having the right drivers? The USB-serial thing being flaky and crap? The VM not seeing the COM port? The MJ not being powered up properly? Too much to troubleshoot all at once.

Anyway, after being loyal to the PIC uc for a number of years, I have recently discovered the fun you can have with arduinos and WS2812 LED strips, so at the same time I had a solution looking for a problem.
I figured it’d be nice to have a system that I can tweak and map and look after from my phone, so set about throwing something together. If you want to do something similar, don’t copy this but do learn from the mistakes. If you really want to copy it… I guess… creative commons non-commercial.

The hardware

Obviously, the first thing to do was to get one of them pretending to be the EDIS system, so I wrote some code for that, and then set about hooking up a second one and getting it to respond appropriately.
IMG_20180704_163616_HDR
In the photo the arduino on the left is sending out PIP pulses, slowly ramping up and down between RPM values, and reporting what SAW width it’s receiving and therefore the advance value the EDIS would provide.
The one on the right is receiving the PIP, calculating RPM, measuring throttle position (the pot on my kiddies’ electronics kit is playing the part of the throttle position sensor here), looking up the advance value from a table, sending a SAW pulse, and driving a strip of RGB LEDs (not shown) using FastLED. There are option switches to flick between 2 maps, and also to change the function of the LED strip from regular shift lights to showing TPS position and other diagnostic info.
In the code there is provision for a rev limiter; a pin is driven low when a set limit is exceeded. (The EDIS doesn’t do that so we need some more circuitry. For the megajolt I made a close copy (with permission) of this: https://wiki.autosportlabs.com/Hard_rev_limiter_1.2.0 and will include something functionally similar on this project. More on this later.)

A lot of coding went by with more than a few facepalms before I got to what I would call working code. Pretty much the usual development process that takes the bulk of the work but isn’t very interesting and so is glossed over here. Imagine a long montage of coding errors and successes. That got me as far as this example output from the simulator/monitor shown here:
Screenshot_20180704_163856

This is showing RPM being ramped up and down, corresponding width of PIP pulse, Advance degrees corresponding to the received SAW pulse, delay between PIP edge and SAW edge (μs), rev lim status (1 => coil power is on) and a few other obscure debug diagnostics.

The main program gives output like this:

Screenshot_20180722-155742.png

Getting ahead of the story a little here; this is captured on my phone from the running engine but it illustrates the point.

There are diagnostics in there telling me how long (in μS) it’s spending sending the LEDs data and writing to the serial port. I was a little concerned at first that it wouldn’t have the clock cycles spare between PIP events to do all that, but it seems fine. I put the important job in an ISR so, notwithstanding the secrets of FastLED library, it should always do the #1 job. Even if it misses a few events it’s no big deal since the EDIS “remembers” the last SAW width for some time.

All seemed ok so I moved on to hardware.

I decided early on to stay compatible with the megajolt so I can freely swap between the two (in case the smoke gets out of mine or whatever, not that I don’t have confidence…). This put some awkward constraints on pinouts etc, but I worked around that to produce the circuit diagram and board layout below. I used Fritzing because it looked like it’d be easy to learn. It’s easy to learn but a giant pain in the arse to use. Stuff just won’t stay where you left it and anything it doesn’t have a footprint for (like the molex connector the MJ uses) causes no end of grief. Anyway, I battled through and got this:

ignition_for_shematic_schem

 

ignition3_pcb3(The 10v zener D5 is an afterthought. So are R16 and R17. More on those later too.)

There’s some extra copper where the coil pack current needs to flow, or big thick wire leading to the off-board power resistor. Making copper flood work properly is another thing that turned out to be impossible in fritzing. It just did random shit and made me angry so I drew a copper rectangle. Shoulda learned kicad. Wide tracks are also impossible so I kept them short and laid some thick solder down over the very-slightly-wider ones that it calls extra-wide.

The big 10W resistor might be overkill but the rev limiter works by placing a resistor in series with the coil pack power feed, so it could see most of 12 V for a few seconds. In normal operation it’s shorted out by the FETs, but when activated they turn off and the coil doesn’t get enough current to fire. Importantly it isn’t abruptly open-circuited since that could cause a spark at a bad time. FETs is plural there for no great reason. Just seemed safer to run 2 in parallel even though each is good for a lot of current (75 A). Only ever need ~10 but we don’t want anything getting warm.

This board has many bodges on it. Do not copy this board.

I made up the board and quickly discovered I’d made the molex connector’s footprint wrong. Predictable, since fritzing’s part editor is such a PoS and you have to make everything by hand as SVG. But it’s only the mounting holes so we’ll just not use those.
With everything populated I connected to the car and switched the LEDs to TPS mode. After calibrating the max/min values given over serial, I got to here:

Next I tried firing it up. Nothing. No power to the coil. (No 10 V zener at this point). After metering everything I pulled the arduino out in desperation and got power. I tried 5v and 0v on the rev lim pin and nothing. Floating, fine, works. It took some headscratching to remember that the MJ switched everything with 12 V, so 5 V was keeping the 2907A conducting and I could never un-limit the rpms. Very annoyed that I overlooked that. A colleague suggested the remarkably simple workaround of putting a zener in series, so I pulled the 100 k resistor and made a 100 k/10 V “zenristor” (just visible in photo) to go in its place. Now the base of the 2907 can cope with the line voltage as high as 15V before it will start to conduct against our wishes, and the arduino can drop it to 10 V to activate the limiter. I might change this for an 11 V zener at some point, just in case the alternator ever decides to put out >15 V (Edit: I did).

After thinking about what comes next I threw in some code to read a toggle switch input pin and add some advance, just to make the mapping and tweaking an experimenting a little easier. Then I figured 2 is better than 1, so now I have +2° and +5° switches available. Being able to add 2, 5 or 7 degrees should help in the tweaking phase. I can change those values, or even the function of those switches, in software later if needed.
At this point it was time to think about a case, so I designed this:

boardcase2
This is the easy part when you have a 3D printer and some experience using it.
The USB port is accessible through a little flap, and there’s a switch panel I can mount by the gearstick with the Map select, LED function, +2° and +5° switches.
IMG_20180707_113104_HDR

IMG_20180707_113134_HDR

IMG_20180707_141635_HDR

I printed that switch panel in 2 pieces. The first 2mm, with the lettering on, is a separate piece. Not only did that mean that all the failed prints where the lettering came out crap went by a lot quicker, but also that if I ever decide to change what the switches are for I only need to reprint the faceplate. It’s just held on by the nuts that retain the switches.
I used some fancy switches that need to be pulled out to toggle. Makes sure I can’t knock them by accident and cause engine destruction.

IMG_20180722_151930_HDR

It’s at this point that feature creep set in and I decided having a voltmeter might be quite nice. It’s really as simple as 2 resistors dividing onto one of the ADC pins, so would be silly not to have it. I drilled a few extra holes in the board and added 10k and 30k resistors dividing the 12V input by 4. When in TPS/diagnostic mode the reading is displayed as a single yellow LED, mapped to read from 10-18 V. With my 20 LEDs that should give a good enough indication of whether everything’s nominal.
Also in this mode, the current advance in degrees is displayed as a single blue dot, mapped to read from 5 to 45. Just for interest. These are superposed on a background of throttle position shown as green-red fill.

Results

The boring code bit can wait until later. It’s down the bottom if you’re interested. Here’s the (not quite) red-line clip you’ve all been waiting for:

 

The code

So first, a quick explanation of what it needs to do.

Priority #1, most important job, is to get a SAW pulse out as soon as PIP transitions low. For this reason all that business happens in an ISR, with the PIP pin set to interrupt on change. The first thing that happens if it’s gone low is the SAW pin immediately goes high. Thenwe use a delay, inside an ISR, despite all the documentation saying not to, because I don’t care about the timing of anything but this, so this needs to be accurate and it needs to happen NOW and nothing else really matters so everything else can wait.
Just after the SAW pulse we know we have a bit of time to work out vital parameters before the next one, so some of the timing values needed to work out RPM are stored then too. (RPM is PIPs/minute divided by 2).

After PIP goes high, we know we have a half PIP cycle before the action starts, so this is a good time to get the ADC to read throttle position.

Everything else can sort of happen any time. The main loop calculates the SAW width and keeps it stored ready, and does the maths to work out the RPM.
It checks positions of the add advance and map select switches, and checks we’re not above the rev limit. Those are fairly important jobs not to get behind on.

The rest is just calling stuff once in a while. Those things are:

Serial output – send diagnostics down the serial line. Once a second is plenty.

Get battery voltage – This is a mixed bag. It happens when PIP is high because that means there’s a bit of free time, but only if it’s not been done in a while. No need to check on that too often.

Update LEDs – send data to the WS2812, whatsoever that data may be. This happens every 64ms so it’s nice and smooth to the eye. 16 fps is plenty when you should have your eyes on the road. In the routine for that is a check to see where the option switch is. If it’s set to RPM the LEDs work as shift lights, left to right lighting green to red as revs close in to the limit.
If set to TPS the LEDs fill L-R green to red to show throttle position, and superposed on that is a static blue LED showing advance in degrees and a yellow one showing current battery voltage.

 

 

lightss2

In “TPS” mode, throttle closed.

The only significant other stuff is the part that triggers the ADC reads when the engine’s not running (they happen on PIP going high normally, remember), and some panic lights in case everything goes wrong.

That’s basically it. It could be tidier, but it works. More tweaks will probably follow as I play with it and do some mapping.

Oh, and my LEDs are numbered backwards – it’s just the way they have to sit in my car. The wire needs to come out on the right. Sorry if that’s confusing.

Here’s the code, formatting probably screwed up by wordpress:

#include “FastLED.h”

#define SAW_PIN 2
#define PIP_PIN 3
#define REV_LIM_PIN 5
#define ADD_2_DEG_PIN 9 //add 2 degrees if low
#define ADD_5_DEG_PIN 10 //add 5 degrees if low
#define map_select_pin 7 //==1 (pullup) for map 1, 0 for map 2
#define TPS_PIN A3 //needs to be an analog pin. check this.
#define BATTV_PIN A6 //needs to be an analog pin. check this.
#define LED_FUNC_PIN 11 //==1 for rev counter, ==0 for TPS display
#define LED_PIN 8
#define NUM_LEDS 20
#define BRIGHTNESS 230
#define LED_TYPE WS2811
#define COLOR_ORDER GRB
CRGB leds[NUM_LEDS];

#define NUM_REDS 3 //how many are solid red at the top end

const byte greenhue=90;
const int redhue=0;
const byte hue_increment=(greenhue-redhue)/(NUM_LEDS-NUM_REDS);
//const int hue_increment=(greenhue-redhue)/num_rpm_bins-1;
volatile byte ledhue[NUM_LEDS];
//volatile byte ledhue2[NUM_LEDS];
const byte num_rpms_to_average = 5; //average 5 timings to get rpm
int pipcount; //how many pips have passed
const byte pips_per_led_update=10;

//const int rev_limit=3000;
//const int rev_firstlight=800;
const int rev_limit=5800;
const int rev_firstlight=3000;
const int tps_minv=110;
const int tps_maxv=780;

const byte adv_offset=5; //add a fixed offset

bool rl_active=false,add2deg=false,add5deg=false,errormode=false;
byte active_map=1; //==1 (pullup) for map 1, 0 for map 2
byte adv_led,batt_led; //led that’s lit to indicate advance, voltage
volatile int rpms_index=0;

volatile unsigned long lag,rpm, rpm_micros_total, half_rev_time_usec,previous_half_rev, interrupttime, lasttime, rpmarray[num_rpms_to_average];
volatile int tps_volts, throttle_pos, saw_width_usec,tps_volts_constrained, missedpulses=0, batt_volts;
float floatvolts;

int advance; //current advance in deg
byte idx_j,idx_k; //index of tps,rpm bins

unsigned long ledtime,serialtime,serialstart;
volatile unsigned long nextTPSupdate=64,nextBattupdate=512,nextLEDupdate=92,nextSerialupdate=1024;

const int num_rpm_bins=15;
int leds_lit;
const byte tpsbins[20]={5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,101};

const String serialheader=”RPM\tT(%,V)\tADV\tlost\tt_led\tt_ser\t12V:”;
byte seriallines=0;

const int rpmbins[num_rpm_bins]={
600,800,1200,1500,1900,2300,2700,3100,3500,4000,4500,5000,5500,6000,6500};

const byte ignition_map_one [20] [15] = {
//Pinto 3D base 6k
{5,15,13,20,32,33,35,37,39,41,43,44,44,44,44},
{5,15,14,24,32,33,35,37,39,41,43,44,44,44,44},
{5,15,17,27,32,33,35,36,39,40,43,44,44,44,44},
{5,15,19,29,31,32,34,35,38,39,42,43,43,43,43},
{5,15,19,29,30,31,32,33,36,37,40,41,41,41,41},
{5,15,19,28,28,29,30,31,34,34,38,39,39,39,39},
{5,15,19,27,27,28,29,30,32,32,38,39,39,39,39},
{5,15,19,25,26,27,28,28,30,30,38,38,38,38,38},
{5,15,19,25,26,27,27,28,30,30,38,38,38,38,38},
{5,15,19,24,25,26,26,27,29,29,37,37,37,37,37},
{5,15,19,23,25,26,26,27,29,29,36,36,36,36,36},
{5,15,19,21,24,25,26,27,28,29,35,35,35,35,35},
{5,15,18,21,24,25,26,27,28,29,34,34,34,34,34},
{5,15,17,20,24,25,25,26,28,28,33,33,33,33,33},
{5,15,16,19,24,25,25,26,28,28,32,32,32,32,32},
{5,15,15,18,24,24,25,25,27,28,30,30,30,30,30},
{5,15,15,18,24,24,25,25,27,28,30,30,30,30,30},
{5,15,15,17,24,24,24,25,27,28,30,30,30,30,30},
{5,15,15,17,24,24,24,25,27,28,30,30,30,30,30},
{5,15,15,17,24,24,24,25,27,28,29,29,29,29,29},
};

const byte ignition_map_two [20] [15] = {
//tiger2lt Pinto 6k-dyno3D
{5,12,13,14,20,22,24,26,29,32,34,35,36,37,38},
{5,12,21,27,29,30,29,32,36,37,40,41,42,43,44},
{5,12,21,26,27,28,28,30,34,35,38,39,40,41,42},
{5,12,20,26,26,26,27,29,32,32,36,37,38,39,40},
{5,12,20,25,25,25,26,28,30,30,36,36,37,38,39},
{5,12,19,24,24,24,25,27,28,29,36,36,37,38,39},
{5,12,19,23,23,24,24,26,28,28,35,36,37,38,39},
{5,12,18,22,22,23,24,25,27,28,35,35,36,37,38},
{5,12,18,22,22,23,24,25,27,27,35,35,36,37,38},
{5,12,17,20,22,24,24,25,26,27,34,34,35,36,37},
{5,12,17,19,22,25,24,25,26,27,33,33,34,35,36},
{5,12,16,18,22,24,24,25,25,26,32,32,33,34,35},
{5,12,16,18,22,24,24,25,25,26,31,31,32,33,34},
{5,12,16,17,22,23,24,25,26,26,31,31,32,33,34},
{5,12,15,16,21,22,24,25,26,26,31,31,32,33,34},
{5,12,15,14,21,22,24,25,27,26,31,31,32,33,34},
{5,12,15,14,21,23,24,25,27,27,31,31,31,32,33},
{5,12,15,13,21,24,25,26,28,29,31,31,30,30,30},
{5,12,15,13,21,23,23,25,26,27,29,29,30,30,30},
{5,12,15,13,21,22,22,23,25,26,27,27,29,29,29},
};
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(SAW_PIN, OUTPUT);
pinMode(13, OUTPUT);
pinMode(REV_LIM_PIN, OUTPUT);
pinMode(PIP_PIN, INPUT_PULLUP);
pinMode(LED_FUNC_PIN, INPUT_PULLUP);
pinMode(map_select_pin, INPUT_PULLUP);
pinMode(ADD_2_DEG_PIN, INPUT_PULLUP);
pinMode(ADD_5_DEG_PIN, INPUT_PULLUP);
attachInterrupt (digitalPinToInterrupt(PIP_PIN), pip_ISR, CHANGE);
digitalWrite(REV_LIM_PIN,HIGH);
for (int i = 0; i < num_rpms_to_average; i++){
rpmarray[i]=500000; //initialise at 60 rpm for cranking
rpm_micros_total = rpm_micros_total + rpmarray[i];
}

//work out a SAW to start off
calculate_saw();

FastLED.addLeds<NEOPIXEL, LED_PIN>(leds, NUM_LEDS);
FastLED.setBrightness( BRIGHTNESS );
for(int b=0;b<NUM_LEDS;b++) { //power up chase light
leds[b] = CHSV(20*b,255,255);
FastLED.show();
delay(10);
}
for(int b=0;b<NUM_LEDS;b++) { //power up chase light
leds[b] = CRGB::Black;
FastLED.show();
delay(10);
}
Serial.println(“RESET”);
//set up all the hues and stuff here
for(int b=0;b<NUM_LEDS;b++) {
ledhue[b] = greenhue-hue_increment*b;
// ledhue2[b] = -100+(120/(NUM_LEDS-NUM_REDS))*b;
}
ledhue[NUM_LEDS-1]=redhue;
ledhue[NUM_LEDS-2]=redhue;
ledhue[NUM_LEDS-3]=redhue;
}

void loop() {
// put your main code here, to run repeatedly:

//important stuff we can do any time:

calc_rpm();
calculate_saw();

if (rpm == 60 && millis() > nextTPSupdate){ //haven’t started yet
get_throttle_pos();
nextTPSupdate=millis()+72;
}

if (rpm == 60 && millis() > nextBattupdate){ //haven’t started yet
get_batt_volts();
nextBattupdate=millis()+1024;
}
if (rpm > rev_limit){
digitalWrite(REV_LIM_PIN,LOW);
rl_active=true;
} else {
digitalWrite(REV_LIM_PIN,HIGH);
rl_active=false;
};

if (digitalRead(map_select_pin)==1){
active_map=1; // map1
} else {
active_map=0; //map2
}

// if (millis() % 64 == 0){ //16 times a sec should be enough
if (millis() > nextLEDupdate){
unsigned long ledstart=micros();
set_LED_params();
unsigned long ledend=micros();
ledtime=ledend-ledstart;
nextLEDupdate=millis()+64;
}

if (digitalRead(ADD_2_DEG_PIN)==0){
add2deg=true;
} else {
add2deg=false;
}

if (digitalRead(ADD_5_DEG_PIN)==0){
add5deg=true;
} else {
add5deg=false;
}
if (millis() > nextSerialupdate) { //once per sec but try not to clash with LEDs
sendserial();
}
//ERROR MODE STUFF
unsigned long lasttimestable=lasttime;
unsigned long now=micros();
lag=now-lasttimestable;
if (lag > 1000000 && rpm > 650){ //not seen a PIP for >1 sec and didn’t spin down

//missing a lot of PIPs now
//go into error mode
errormode=true;
rpm=800;
rpm_micros_total = 0;
for (int i = 0; i < num_rpms_to_average; i++){
rpmarray[i]=40000; //initialise at 800 rpm for safety
rpm_micros_total = rpm_micros_total + rpmarray[i];
}

}

}//end loop()
void pip_ISR () {
if (digitalRead(PIP_PIN) == LOW){ //replace with a PORT read when pins known!!!!!
//PIP has just fallen
//get numbers we need to work out rpm first
interrupttime = micros();

// need to get the SAW pulse out ASAP
//digitalWrite(SAW_PIN, HIGH); //replace with a PORT write when pins known!!!!!
PORTD = PORTD | B00000100; //set pin 2 high
delayMicroseconds(saw_width_usec);
//digitalWrite(SAW_PIN, LOW); //replace with a PORT write when pins known!!!!!
PORTD = PORTD & B11111011; //set pin 2 low

//now carry on with the rpm timing
previous_half_rev=half_rev_time_usec;
half_rev_time_usec=interrupttime-lasttime;

//check we haven’t missed one
//if time is bigger than 1.5 * last, or smaller by 0.5, probably missed some events
if (half_rev_time_usec > 3 * previous_half_rev/2 ||half_rev_time_usec < previous_half_rev/2){
missedpulses++;
} else {

//update the historic rpm averager array
rpm_micros_total=rpm_micros_total-rpmarray[rpms_index];
rpmarray[rpms_index]=half_rev_time_usec;
rpm_micros_total=rpm_micros_total+rpmarray[rpms_index];
rpms_index++;
if (rpms_index >= num_rpms_to_average) {rpms_index=0;};
}

lasttime=interrupttime;
errormode=false; //got a PIP so clear error flag
} else {
//PIP has just risen
//got some time to spare now
//do the adc reads while we have time
get_throttle_pos();

if (millis() > nextBattupdate){
get_batt_volts();
nextBattupdate=millis()+1024;
}

pipcount++;
}
}

void get_throttle_pos() {

//get a throttle position
tps_volts = analogRead(TPS_PIN);
tps_volts_constrained=constrain(tps_volts,tps_minv+1,tps_maxv-1);
throttle_pos = map(tps_volts_constrained,tps_minv,tps_maxv,0,100);

}

void get_batt_volts() {

//get a line voltage
//divided 12V line by 10k/10+30k, so x4 for true voltage
//but here just treat it as 1023 on the ADC =20V so it can stay an int
//0.01953125 volts per ADC unit
//51.2 ADC units per volt
batt_volts = analogRead(BATTV_PIN);
floatvolts=batt_volts*20.0/1024.0;
batt_led=map(constrain(batt_volts,512,920),512,920,0,NUM_LEDS-1);
//this in theory gives 10V to 18V
//good enough to monitor it and spot radical changes

}

void calculate_saw() {

byte j=0; //index of throttle pos
byte k=0; //index of rpm
while (throttle_pos > tpsbins[j]){
j++;
}
while (rpm > rpmbins[k] && k <= num_rpm_bins-1){
k++;
}
if (k>num_rpm_bins-1){k=num_rpm_bins-1;};
idx_j=j;
idx_k=k;

if (active_map==1){
advance=ignition_map_one[j][k];
} else {
advance=ignition_map_two[j][k];
}

advance=advance+adv_offset;
if (add2deg==true){
advance=advance+2;
}
if (add5deg==true){
advance=advance+5;
}
if (rpm > rev_limit – 200) {advance=adv_offset;};//set advance to 0 approaching rev lim
saw_width_usec= constrain(1536 – (25.6 * advance),64,1792);

}

void calc_rpm(){
//work out rpm (rolling average of last few)
unsigned long avg=0;
avg = rpm_micros_total/num_rpms_to_average;
//remember time is for half a revolution
rpm = 30000000/avg;
// rpm = 30000000/half_rev_time_usec;
// return(rpm);
}
void set_LED_params(){

for(int c=0;c<NUM_LEDS;c++){
leds[c]=CRGB(0,0,0);
}

// if (PINB & B00001000){
if (digitalRead(LED_FUNC_PIN) == HIGH) {
digitalWrite(13,LOW);
int rpm_constrained=constrain(rpm,rev_firstlight,rev_limit-200);
leds_lit=map(rpm_constrained,rev_firstlight,rev_limit-200,0,NUM_LEDS-1);

for(int c=0;c<leds_lit;c++) {
leds[NUM_LEDS-1-c]= CHSV(ledhue[c],255,255);

}
} else { // —–comment to force TPS mode for debug
digitalWrite(13,HIGH);
leds_lit=map(throttle_pos,0,100,0,NUM_LEDS);

for(int c=0;c<leds_lit;c++) {

// leds[c]= CHSV(ledhue[c],255,255);
leds[NUM_LEDS-1-c]= CHSV(ledhue[c],255,255);

}

leds[NUM_LEDS-1-batt_led]= CRGB::Yellow;

adv_led=map(constrain(advance,5,45),5,50,0,NUM_LEDS-1);
leds[NUM_LEDS-1-adv_led]= CRGB::Blue;
}
if (rl_active){
leds[NUM_LEDS-1]= CRGB::Red;
leds[NUM_LEDS-2]= CRGB::Red;
leds[NUM_LEDS-3]= CRGB::Red;

}
if (errormode==true){
for(int c=0;c<NUM_LEDS-1;c++) {
if(c%2){
leds[c]= CRGB::Black;
} else {
leds[c]= CRGB::DarkOrange;
}

}
}

// leds[0]= CRGB::Yellow;
// leds[NUM_LEDS]= CRGB::Red;
//
FastLED.show();
// Serial.println(“LED set”);
}
void sendserial(){
serialstart=micros();

//const String serialheader=”RPM\tT(%,V)\tADV\tlost\tt_led\tt_ser\t12V:”;
String data=””;
data+=rpm;
data+=”\t”;
data+=throttle_pos;
data+=”,”;
data+=tps_volts;
data+=”\t”;
data+=advance-adv_offset;
data+=”\t”;
data+=missedpulses-2;
data+=”\t”;
data+=ledtime;
data+=”\t”;
data+=serialtime;
data+=”\t”;
data+=floatvolts;
data+=”,”;
data+=batt_volts;
if (seriallines %10==0){
Serial.println(serialheader);
}
Serial.println(data);

serialtime=micros()-serialstart;
nextSerialupdate=millis()+1024;
seriallines=seriallines+1;
}

And for anyone trying to replicate this project, (maybe this will save somebody some time someday) here’s my code for the EDIS simulator:

#define PIP_OUT_PIN 3
#define SAW_IN_PIN 2
#define TPS_OUT_PIN 10
#define REV_LIM_SENSE 5
#define LED_PIN 13

const int max_rpm = 6500;
int lasttime;

bool rev_lim;
byte throttle_pos = 0; //runs from 0 to 100
byte tps_DC; //from 0 to 255
int rpm=5000;
int rpm_increment=500;

String data_return,newdata;
unsigned long time1,pips_sent=0,pip_time_us;
volatile unsigned long num_saws,advance_deg,pipdroptime,sawuptime,sawdowntime,saw_width_manual,saw_delay,saw_width_duino;

void setup() {
// put your setup code here, to run once:
pinMode(SAW_IN_PIN, INPUT);
attachInterrupt (digitalPinToInterrupt(SAW_IN_PIN), saw_ISR, CHANGE);
pinMode(REV_LIM_SENSE, INPUT);
pinMode(PIP_OUT_PIN, OUTPUT);
pinMode(TPS_OUT_PIN, OUTPUT);
Serial.begin(115200);
lasttime=micros();
}

void loop() {

// put your main code here, to run repeatedly:
pip_time_us=30000000/rpm; //full cycle of PIP pulse |^|_
tps_DC=map(throttle_pos,0,100,0,255);
//analogWrite(TPS_OUT_PIN,tps_DC); //set the voltage on TPS

//send a PIP
PORTD = PORTD | B00001000; //set pin 3 high
delayMicroseconds(pip_time_us/2);
PORTD = PORTD & B11110111; //set pin 3 low
pipdroptime=micros();
rev_lim=digitalRead(REV_LIM_SENSE);
//if (rev_lim==0) {rpm_increment=-20;}

pips_sent++;

data_return+=”RPM: “;
data_return+=rpm;
data_return+=” PIP wid: “;
data_return+=pip_time_us;
// data_return+=” Tpos: “;
// data_return+=throttle_pos;
data_return+=” Adeg: “;
data_return+=advance_deg;
data_return+=” Sdelay: “;
data_return+=saw_delay;
data_return+=” SW m,d: “;
data_return+=saw_width_manual;
data_return+=”,”;
data_return+=saw_width_duino;
data_return+=” rlim: “;
data_return+=rev_lim;
data_return+=” PIPs: “;
data_return+=pips_sent;
data_return+=” SAWs: “;
data_return+=num_saws;
data_return+=” missed SAWs: “;
data_return+=pips_sent-(num_saws-1);

if (pips_sent % 15==0){
Serial.print(data_return);
Serial.print(“\r\n”);
}
data_return=””;

if (pips_sent % 30==0){
rpm=rpm+rpm_increment;
}

// if (micros() – lasttime > 2000){
// rpm=rpm+rpm_increment;
// lasttime=micros();
// }

if (rpm>max_rpm){
rpm_increment=-110;
}

if (rpm<2000){
rpm_increment=110;
}

if (throttle_pos > 100){
throttle_pos=0;
}
while(micros() < pipdroptime + pip_time_us/2){digitalWrite(LED_PIN,HIGH);}
digitalWrite(LED_PIN,LOW);

}
void saw_ISR() {
unsigned long interrupttime=micros();
if (PIND & B00000100){
// if (PIND & B01000000){
// if(digitalRead(SAW_IN_PIN)==HIGH){
sawuptime=interrupttime;
// saw_width_duino=pulseIn(SAW_IN_PIN,HIGH);
saw_delay=sawuptime-pipdroptime;
num_saws++;
} else {
sawdowntime=interrupttime;
saw_width_manual=sawdowntime-sawuptime;
advance_deg=(1536-saw_width_manual)/25.6;
}
}

 

PIC strobe tuner

I decided pretty much all bought guitar tuners are crap. They’re never accurate and they’re useless if there’s any other noise going on. I set out to make something better, and here it is.

Someone did make something like this commercially, but it’s not as cool as mine. I forget what it was.
Edit: Planet Waves CT06

I figured the easiest and best way to accomplish the task of tuning a string is with a strobe light flashing at the right frequency.  What we set out to achieve is some arrangement of flashing LEDs that throws bands of light onto guitar strings. When the string oscillates at the same frequency as the flashing of the light we won’t see any movement because the string is in the same place each time the light flashes. If the string is out of tune the bands of light will appear to wobble. Read about strobe tuners if you’re not keeping up so far.

The easiest way to make lights flash at an accurate but switchable frequency has to be the venerable PIC running off a crystal oscillator. So let’s start there.
I had a PIC 16f819 sitting in my parts bin, and it’s perfect for the job for many reasons. The best part is one of its 3 timers is 16-bit, so we should be able to get super accurate timings with it. It seems a shame to waste the other 2 so I figured why not use 3 LEDs that can be for tuning half-step down or whatever.
A 4 MHz crystal makes the PIC run at an incredibly convenient 1 microsecond instruction cycle, so if we know the frequencies of all our notes it’s trivial to work out how to set the timers. Similarly wiring 3 LEDs to pins on a PIC is about as easy as it gets, so the only hard part is the code…

I won’t go too much into the details, but I can tell you it was a faff getting the 3 timers to interrupt (many “enable” bits need to be set and they’re scattered all through the datasheet). Once they do we just need code to figure out which timer tripped, code to switch strings on a button push, and a bit of magic to compensate for the time spent turning lights on and off.

Our magic numbers are 82.4, 110, 146.8, 196, 246.9 and 329.6 Hz for a guitar. I wasn’t sure at first how I was going to keep track of which note the strobes were flashing at as we cycle through the strings, but then I reasoned that with 3 LEDs we can count to 6 in binary, so when the button is pushed to change we go to a delay loop (that also serves to debounce the button) that lights up LEDs showing the number of the string, from 1-6, that we’re moving to.
I set up the 3 LEDs so that the green runs off the 16-bit timer and always strobes at standard tuning, i.e. EADGBE. The red is always 1/2 step down in case I ever lend this thing to some scruffy guy with long hair from the 1990s, and blue is a little different.

The disadvantage of this strobe setup is it’s impossible to tell if you’re too high or too low without adjusting, so I set the blue LED to flash a little fast, meaning that if blue is the most stationary band don’t go any higher. This should prevent string snappage. The exception is on the E string (string 1), where blue is set a full step down to make drop D quick and easy.

The rest is simple maths, not so simple code and masses and masses of debugging [Thanks Adam!!]. Once it was working I measured the frequencies accurately and tweaked the timer loadings a little. Now it’s probably the most accurate tuner I’ll ever see.

BOM:
3 super-mega-uberbright LEDs + resistors of your choice
1 PIC
1 4 MHz crystal (+small caps per PIC datasheet)
1 offcut of stripboard
1 power switch
1 push button

+ batteries + case = Done.
DSC_0162DSC_0165
The case is some junk, I don’t remember from what. It’s a little bigger than I needed, but that leaves room to store some picks. No puns please.

Solar powered automated plant waterer

My plants are unhappy. I go away a lot and they don’t get looked after. I figured I could do something about this.
First off, I should own up to having solved this problem before. Mk1 used one of these commercially available things

41rfZkmnj5L._SY300_

and a water pump smashed out of a battery powered kids water pistol, a bit of hose and a phone charger. It was plugged into the wall via a timer plug so it was only powered for 15 minutes a day, but the probes still corrode way too fast to be useful long term and the pump draws a lot of electrics (800mA for up to a minute at a time) so it’s constrained to live near a socket. In light of this first success my requirements have been refined. Mk2 must:

1. Water plants when they need it (see how that one’s top of the list)
2. Be able to run from (cheap!) solar power
3. Not electrolyse the soil probes away
4. Cost less than a commercially available alternative

Now, I’ve seen this kind of thing done loads on hackaday. People just grab an arduino/pi/whatever and buy a solenoid valve and call it good. Well requirement 2 kinda dumps on the pi, probably the arduino too, and 2 and 4 both rule out the 12/24V solenoid valve. But we still need some kind of intelligence to meet #3 by limiting the time we run current through wet dirt.
Enter the PIC. It draws like 20 microAmps or something in sleep mode, and even with everything running it’s hardly what you’d call thirsty. These things are ideal for solar power. I went for the 12f683 because it’s small and cheap, but almost any would do.

We also need a bespoke power supply. This part was fairly easy. It’s 4 solar garden lights, costing £1 each, with the guts removed. Maplin part# N08FX to be precise.

solar-powered-stainless-steel-post-light

Each contains a AAA NiMH cell and a crap solar panel (and a white LED and switch, together worth about 80p, that I get to keep). The solar cells are connected in series, the AAAs are connected in series, and the solar cells charge the batteries through a diode so they can’t drain at night. I added a USB connector to make wiring easy and universal.
I figured a custom stand would be a nice touch, so I drew and printed this too.

legs1 post stand

DSC_0155 DSC_0156

Now we’re going to need a valve that can control water with 5 Volts and, to be sensible, not draw much more than an Amp. I searched extensively and found, never mind requirement #4, you just can’t buy that. This is where the project hit its first wall. I’d have to invent a valve.
I played with coils of wire wound on steel bolts lifting steel ball bearings. The results were encouraging, so I started trying to design a valve seat that a ball bearing would seal against. I tried moulding stuff out of silicone sealant but the results were too grabby for the solenoid to pull against. I tried drilling very very neat holes in all sorts of things but nothing was perfectly round enough to seal. I tried 3d printing parts but they all leaked, no matter what I tried. I tried 3d printing something that would take an o-ring that would seat a ball bearing. No joy – the o-ring always distorted just enough to leak.

Then, one day, as I was washing the dishes and ran out of detergent I spotted something. The cap on the bottle had a perfectly made toroidal hole that would work perfectly. A quick bit of drawing and I had a valve assembly that would open and close and control water with electricity. This felt like a hell of an achievement. I’m still quite proud of it.

valve1 DSC_0153
DSC_0151

I left it for a while to see that it held water long term, and realised the ball bearing I’d used wasn’t going to work. It had rusted badly in a week. A quick search threw up a ball that is stainless but still magnetic, (that’d be 420 stainless), so I ordered a pack of 10. It worked, but not as well. Anything over an inch or two of water and the attraction was too weak to pull against the pressure. So I unwound half of the coil, snipped it and re wound it in parallel with other half to give some more Amp-turns. I don’t know how many turns it is but now the coil draws about 650mA and can open the valve under 4 inches of water, which is enough.
The coil is wound on a screw between two 3d-printed plastic discs. This screw is threaded into a little cylindrical thingy that sits in the neck of a regular cut down drinks bottle. With the dish soap bottle cap screwed on, turning the coil assembly with a screwdriver adjusts the clearance between the armature and the ball bearing so I don’t need to worry about the tolerances on those plastic parts. Simple, right?

Now that all works, it was time to figure out the logic. I wanted to be able to adjust the dryness of soil at which we decide to water, so I’d need some kind of trim pot, but how big? I stuck some screws in plant pots a few cm apart and found as expected wet soil is low resistance and drying soil can be anywhere up to 200k, but is usually about 50k at the point when you’d start to feel sorry for the plant. I went for a 100k because I had that in the parts bin. Ideally would be twice that but meh. It’ll work.
Still the PIC leaves many choices of implementation because it has so many peripherals to choose from. Do I use an ADC with the pot providing a reference voltage? Or a comparator? Or some other weird exotic with the analog inputs? In the end I chose the comparator because I understood that part of the datsheet after only 4 read throughs. That’s simpler than anything else in there…

I set about writing some code to set up all the peripherals on the pic (most of the code) and then the actual working bit (not so much). The plan is for the PIC to wake up from sleep, apply power to the probes, wait half a second for the potentials to settle down (I’d noticed drift when using a meter), then if soil resistance > pot resistance open the valve for 2 seconds. Then power off the probe voltage and comparator (important!) and sleep again.
2 seconds is enough – that lets about a teaspoon of water out, so it won’t take many cycles to saturate even the driest of pots.
The pic is clocked internally and wakes from sleep using the watchdog timer interrupt. The longest that can run is 272 seconds – about 5 mins. There’s no need to wake up that often, so I just made it sleep twice. This means it wakes and runs the test every 9 minutes.

I also wanted some kind of “calibration mode” so that I could set the pot to a sensible value without waiting 9 minutes after every tweak to see if it was right. So on waking up (or on power on) the PIC checks an input for the presence of a jumper link that sets “calibration mode”. If this is present the sleep cycle is swapped for a 2 second delay loop, meaning the test gets run every 2-ish seconds. Combined with a LED in parallel with the coil this should let me set up the device in a sensible amount of time, with or without the valve connected.

I wrote all the code while my PIC programmer was on order. I’d always borrowed one before but figured it was time.
When it arrived I breadboarded up a test circuit and was amazed to find the code was really nearly right. All I’d done was forget to put the correct delay value back in the delay loops after simulating with an artificially shortened one. One small change and it was working! When has PIC assembly EVER worked second time?! I’m super proud of that too!

So to stripboard.

DSC_0144_labels

I threw this together with a micro USB socket for power (see what I did there? So you can use a phone charger instead of solar if you want…) and remembered to add a diode so the flyback from the valve doesn’t toast the PIC. I knew to do that because I remember feeling the shocks when playing around testing the valve with wet hands. It tingles…

The PIC drives a MOSFET to switch the high current to the valve. The probe and valve connect on pin headers for convenience.
The soil resistance probe is just a pair of stainless screws through a bit of PLA. Nothing to see there.

DCIM100GOPRO

I knocked up a little bottle stand and channel for the water out of PLA also, and set it in place. It works, as designed, amazingly. Its legs are the stands recycled from the garden lights I used in the power supply. The board hangs off the side of the stand and some ugly trailing wires lead off via strain reliefs to the solenoid and probes.

trough ring

DCIM100GOPRO

In the video below the part of the plant is being played by a glass, because it’s winter and there are no plants really left to water. You’ll have to take my word about the soil probe working properly. This is with the test jumper installed, so cycling constantly. In run mode there’s a 9 minute wait, but that doesn’t make good tv.

The solar cells have no trouble keeping the batteries topped up, and they in turn have no trouble feeding 600mA for 2 seconds every now and then. I think they’d struggle with anything more hungry than a PIC, though. It’s been fine looking after my chili plant for 2 months now 🙂