Hello friends, I hope you all are doing great. Today, I am going to share the Soil NPK Fertilizer Advisor on Raspberry Pi 5 - Proteus Simulation, the eighty-sixth project of our IoT Projects series. If you have searched for a soil NPK sensor with a Raspberry Pi, how to read an RS485 Modbus sensor in Python, a MAX485 with a Raspberry Pi, or how much fertilizer a garden bed needs, here is a complete one in a Proteus simulation. Plants take three main nutrients from the soil: nitrogen (N) for leaves, phosphorus (P) for roots and flowers, and potassium (K) for fruit and strong stems. Too little and the crop is weak; too much wastes money and washes into rivers.

A soil test tells what is there, but a gardener needs the next step: what to spread, and how much. This Raspberry Pi 5 reads a three-needle RS485 soil NPK probe over Modbus RTU through a MAX485 module, waits for a steady reading, compares the nitrogen, phosphorus and potassium with the ranges the chosen crop needs, and works out the grams of DAP, urea and potash for a 10 square metre bed. It also notices when heavy rain has washed the nitrogen out. A colour TFT shows N, P and K as bars against the crop's range, and a dashboard on the laptop or phone lets you switch between tomato, lettuce, maize and potato. In this tutorial, we will go through the circuit, RS485 and Modbus RTU, the CRC, the direction control of the MAX485, how mg/kg become grams of fertilizer, and why nitrogen leaches while phosphorus stays. Then we put the bed through fertilizer, heavy rain and rich compost in the simulation. At the end, you can download the project with the program and every library file.

NOTICE: Our team has put a lot of effort into this project: the circuit, the code and every part in the simulation are our own work, and you get them all free. Your feedback is the fuel that keeps us going, so please tell us what you think in the comments below. And if our free projects help you, you can buy us a coffee. So, let's get started with the soil NPK fertilizer advisor on Raspberry Pi 5 in Proteus simulation:

Figure: The soil NPK fertilizer advisor in a Proteus simulation.
Figure: The project working in the Proteus simulation (an animation of the main steps).

What Does This Soil NPK Advisor Do?

  • Reads the soil: nitrogen, phosphorus and potassium in mg/kg from an RS485 probe, every 2 seconds.
  • Speaks Modbus RTU: a request with its CRC-16, the MAX485 switched to send and back to listen in time for the answer.
  • Waits for a steady reading: three readings in a row within 3 mg/kg, averaged.
  • Advises: FERTILIZE, ALL GOOD or TOO MUCH for the chosen crop, and the grams of DAP, urea and MOP for the bed.
  • Warns of leaching: nitrogen washed out by rain while phosphorus stayed.
  • Shows and serves it: a TFT with bars and the grams, and a dashboard that switches the crop.

It is a great project for learning industrial RS485 and Modbus with Python, and a bit of soil science on the way. In the simulation, the probe's pop-up holds the bed in a soil and lets us fertilize it, rain on it or move the probe into compost, so we can see every kind of advice in minutes.

Components Used in the Proteus Simulation

All the parts come from our Proteus libraries, each with its own tutorial. The project zip at the end includes every LIB and DLL file and the Python runtime of the simulated Pi.

The parts of the soil NPK advisor and their library posts
PartProteus deviceLibrary postConnection
Raspberry Pi 5RASPBERRY PI 5Raspberry Pi 5 Library for ProteusPI1, soil_advisor.py, Ethernet 192.168.1.51:8000
MAX485 RS-485 moduleMAX485ADVTEPMAX485 RS-485 Module Library for ProteusU1 on the UART; DE / RE on GPIO18
Soil NPK probe (RS485)SOILNPKTEPSoil NPK Sensor Library for ProteusU2, A / B to the MAX485, 12 V
TFT 1.8" ST7735TFT18ST7735ADVTEPTFT ST7735 Library for ProteusTFT1 on SPI0
Laptop WiFi MonitorLAPTOP WIFI MONITORLaptop WiFi MonitorPC1
Mobile WiFi MonitorMOBILE WIFI MONITORMobile WiFi MonitorMOB1

Proteus Simulation of the Soil NPK Advisor: the Circuit

Figure: The complete circuit of the soil NPK advisor on an A3 Proteus sheet.
The connections of the soil NPK advisor
SignalRaspberry Pi 5Goes to
TXDGPIO14 (pin 8)U1 DI: the bytes to send
RXDGPIO15 (pin 10)U1 RO: the bytes received
DIRGPIO18 (pin 12)U1 DE and RE together: HIGH = send, LOW = listen
A / B-U1 A / B to U2 A (yellow) / B (blue): the RS485 pair
+12V-U2 VCC (brown): the probe takes 5 - 30 V
MOSI, SCLK, CE0GPIO10, 11, 8 (pins 19, 23, 24)TFT1 SDA, SCK, CS
A0 / RESETGPIO25 / GPIO24 (pins 22 / 18)TFT1 A0 / RESET

The probe and the MAX485 share the ground. On a real Pi, mind the levels: the usual MAX485 module runs on 5 V, so its RO output should reach the Pi's 3.3 V RXD through a level shifter, or use a 3.3 V transceiver such as the MAX3485.

How the Soil NPK Advisor Works

N, P and K: What Plants Take From the Soil

Nitrogen builds proteins and chlorophyll: without enough of it, leaves turn pale yellow and growth stalls. Phosphorus carries energy inside the plant and feeds roots, flowers and seeds. Potassium controls water and makes fruit sweet and stems strong. Each crop needs a different balance: potatoes are hungry for potassium, leafy lettuce mostly for nitrogen. The probes measure the nutrients the plants can take up, in mg per kg of soil. These probes estimate N, P and K from the soil's conductivity, so they are good for trends and comparisons rather than as a laboratory test, which is how this project uses them.

RS485 and Modbus RTU

RS485 sends each bit as a voltage difference between two wires, A and B: A above B is a 1. Noise picked up on the cable hits both wires equally and cancels, so RS485 runs hundreds of metres across a field or a factory, with many devices on the same pair. Only one may talk at a time, so the transceiver has a driver enable (DE) and a receiver enable (RE): the Pi pulls them HIGH to send and LOW to listen. On top of RS485 runs Modbus RTU, the most common industrial protocol: the master sends the slave's address, a function code, a start register and a count, and a CRC; the slave answers with its address, the function, a byte count, the data and its own CRC. The probe keeps nitrogen in register 0x001E, phosphorus in 0x001F and potassium in 0x0020, so one request reads all three: 01 03 00 1E 00 03 65 CD.

The CRC-16 and the Timing

Modbus protects every frame with a 16-bit CRC: polynomial 0xA001 (the reflected 0x8005), starting at 0xFFFF, sent low byte first. One flipped bit anywhere changes it, so a frame with a wrong CRC is thrown away. The timing matters as much: at 9,600 baud each byte takes 10 bits (a start bit, 8 data bits and a stop bit), so the 8-byte request is on the wire for 8.3 ms. The program keeps DE HIGH for those 8.3 ms plus 1 ms, then drops it. The probe answers 20 ms after the request ends; drop DE too late and the answer collides with our own driver, drop it too early and the last byte of the request is cut off.

Waiting for a Steady Reading

A probe pushed into fresh soil, or soil that has just been watered, takes time to settle, and the readings wander by a mg/kg or two. Advice based on one reading would jump around. So the program keeps the last three readings and calls the soil steady only when all three agree within 3 mg/kg; it then uses their average. When a reading moves more than 6 mg/kg away from the steady value, the program says the soil is changing and waits again.

From mg/kg to Grams of Fertilizer

The roots of vegetables live mostly in the top 15 cm of soil, and a cubic metre of garden soil weighs about 1,300 kg. So each square metre holds 0.15 x 1,300 = 195 kg of root-zone soil, and a 10 square metre bed 1,950 kg. Raising a nutrient by 1 mg/kg in that bed takes 1,950 mg = 1.95 g of the nutrient. Worked example for tomatoes (N at least 120, P 50, K 180 mg/kg) on a poor bed with N 30, P 12 and K 95: the bed is short of (120 - 30) x 1.95 = 175.5 g of nitrogen, (50 - 12) x 1.95 = 74.1 g of phosphorus and (180 - 95) x 1.95 = 165.8 g of potassium.

Choosing the Fertilizers

Fertilizer bags give their grades as N - P2O5 - K2O percentages, so phosphorus and potassium need converting: P2O5 is 43.64 % phosphorus and K2O is 83.01 % potassium. DAP (18-46-0) holds 46 % P2O5, which is 20.1 % P, plus 18 % N. Urea (46-0-0) is 46 % N, and MOP, muriate of potash (0-0-60), is 60 % K2O, which is 49.8 % K. The program covers the phosphorus with DAP first and counts the nitrogen that comes with it, then tops up the nitrogen with urea and the potassium with MOP. For the tomato bed: 74.1 / 0.201 = 369 g of DAP, which also brings 66.4 g of nitrogen; the remaining 109.1 g of nitrogen is 109.1 / 0.46 = 237 g of urea; and 165.8 / 0.498 = 333 g of MOP.

The crop ranges in the program (typical values for learning)
CropN (mg/kg)P (mg/kg)K (mg/kg)
Tomato120 - 20050 - 90180 - 300
Lettuce100 - 16040 - 80150 - 250
Maize130 - 20040 - 70150 - 250
Potato110 - 18055 - 100200 - 320

Leaching: Why Rain Takes the Nitrogen

Most of the nitrogen plants use is nitrate, a negative ion that soil particles do not hold; it moves with the water. Heavy rain carries it down below the roots, into the ground water and the rivers. Phosphate binds tightly to the soil and hardly moves; potassium sits in between. So when a steady reading shows nitrogen down by a third or more while phosphorus held, the program reports LEACHING. The advice then is to put the urea on in smaller, split doses rather than all at once, so less of it is lost in the next downpour.

The Python Code Explained

The program is soil_advisor.py, plain Python for the Raspberry Pi with lgpio, pyserial and spidev. The request, with its CRC computed once:

        req = bytes([ADDR, 0x03, 0x00, 0x1E, 0x00, 0x03])  # read 3 registers from 0x001E: N, P, K
            c = (c >> 1) ^ 0xA001 if c & 1 else c >> 1

Sending it through the MAX485, and letting go of the pair in time:

        lgpio.gpio_write(self.c, DIR, 1)                   # drive the pair
        time.sleep(len(self.frame) * 10 / 9600 + 0.001)    # 8 bytes x 10 bits at 9600 baud = 8.3 ms on the wire

Checking the answer and taking out the three values:

        if crc16(r[:9]) != (r[9] | r[10] << 8) or r[0] != ADDR or r[1] != 0x03 or r[2] != 6:
        return r[3] << 8 | r[4], r[5] << 8 | r[6], r[7] << 8 | r[8]

The soil in the bed and the fertilizers' contents:

G_PER_MGKG = BED_M2 * DEPTH * DENSITY / 1000.0             # 1.95 g of a nutrient in the bed for each mg/kg
DAP_N, DAP_P = 0.18, 0.46 * 0.4364                         # DAP 18-46-0: 46 % P2O5 = 20.1 % P

The advice: DAP for the phosphorus, urea for the rest of the nitrogen, MOP for the potassium:

    urea = max(0.0, need_n - dap * DAP_N) / UREA_N

The steady-reading test and the leaching test:

            if len(recent) == 3 and all(max(x[k] for x in recent) - min(x[k] for x in recent) <= 3 for k in range(3)):
                    if dn <= -last_settled[0] / 3 and abs(dp) <= max(5, last_settled[1] * 0.1):

The TFT is redrawn in bands, so only the part that changed goes over the SPI bus: the crop name, the three bars with the crop's range in dark green, the verdict in its colour and the grams. The dashboard's links pick the crop (/crop/tomato and so on), and /data gives everything as JSON.

How to Run the Proteus Simulation

  1. Download the project zip below and install the library files (the steps are under the download button).
  2. Open Pi-5-Soil-NPK.pdsprj from the Proteus Simulation folder. Keep soil_advisor.py and the DLL files next to it.
  3. Press Play. After about 4 seconds the TFT shows the poor bed and the grams for tomatoes.
  4. Click U2 for the probe's pop-up and change the soil: Fertilise, Rain, Compost.
  5. Open the Laptop WiFi Monitor (press Go) and pick another crop.

Simulation Results: the Garden Bed in Proteus

We started with a poor bed and a tomato crop, then fertilized it, let heavy rain fall on it, switched the crop from the dashboard and finally pushed the probe into rich compost. The times below are the program's clock; the whole run took 87 simulated seconds. Across the run the Pi sent 43 Modbus requests and got 43 answers, with no CRC error, no collision on the pair and no DE dropped early: the MAX485's own pop-up counted every frame.

A Poor Bed for Tomatoes

At 4.0 s the first steady reading came in: N 30, P 12, K 94 mg/kg, far under the tomato ranges, so the verdict was FERTILIZE N P K. The 10 square metre bed was short of 175.5 g of nitrogen, 74.1 g of phosphorus and 167.7 g of potassium, and the advice was DAP 369 g, urea 237 g and MOP 337 g, the same numbers as our worked example (the MOP is 4 g more because the potassium read 94 instead of 95). The TFT showed three short red bars well left of the dark green ranges.

Figure: A poor bed: FERTILIZE N P K, with the grams of DAP, urea and MOP.
Figure: The TFT: the crop, the bars against the crop's range and the advice.
Figure: The probe's pop-up: the soil, and every Modbus frame with its bytes.
Figure: The MAX485's pop-up: the frames on the bus and the DE timing.
Figure: The dashboard: the readings, the crop's ranges and the grams.

After the Fertilizer: ALL GOOD

Then we pressed Fertilise on the probe's pop-up. The readings climbed over a few seconds; at 14.0 s the program noticed the soil changing and stopped advising until it settled. At 28.0 s it reported "N, P and K all rose: +110, +50, +116 mg/kg": N 140, P 62, K 210, all inside the tomato ranges. The verdict turned to ALL GOOD and the advice to no fertilizer needed; the bars went green inside their dark green bands.

Figure: After the fertilizer: ALL GOOD.
Figure: All three nutrients inside the crop's range.
Figure: The probe: the bed fertilised, the grains of all three nutrients.

Heavy Rain: LEACHING

Next came heavy rain. The nitrogen fell fast while the phosphorus did not move. At 44.0 s the program reported LEACHING: nitrogen -94 mg/kg (-67 %) while the phosphorus held (+0) - nitrate washed out. With N at 46 the verdict was FERTILIZE N again: 144.3 g of nitrogen short, urea 314 g and nothing else, since P 62 and K 184 still met the tomato ranges. The TFT added "LEACHING: SPLIT THE UREA DOSES" in blue, and the dashboard said the same.

Figure: After the rain: the nitrogen washed out.
Figure: Only the nitrogen is short: urea, in split doses.
Figure: The probe in the rain: nitrogen down, phosphorus unchanged.
Figure: The dashboard after the rain.

Another Crop From the Dashboard

The same soil means different things to different crops. We clicked POTATO on the dashboard: potatoes want more potassium (200 to 320 mg/kg), so K 185 was now short too, and the advice became FERTILIZE N K: urea 271 g and MOP 59 g. Then LETTUCE, which needs less of everything: only the nitrogen was short, and the advice was urea 233 g. Each change redrew the TFT at once, with the new crop's ranges behind the same readings.

Figure: POTATO: the potassium is short too.
Figure: The potato's ranges behind the same readings.
Figure: LETTUCE: only the nitrogen is short.
Figure: The circuit advising a lettuce bed.
Figure: The TFT for lettuce.

Rich Compost: TOO MUCH

Last, we moved the probe into rich compost. At 74.0 s the soil settled at N 260, P 119, K 418 mg/kg, above every lettuce range, and the verdict was TOO MUCH N P K: no fertilizer needed, the bars orange and running past the dark green bands. Too much nitrogen gives soft, leafy growth and nitrate in the ground water, so knowing when not to fertilize matters as much as knowing how much.

Figure: Rich compost: TOO MUCH, no fertilizer.
Figure: Orange bars past the crop's range.
Figure: The probe in rich compost.
Figure: The MAX485 at the end: every frame answered, no CRC error.
Figure: The dashboard: too much of everything.
Figure: The phone: the same dashboard, with buttons.
Figure: The Pi's terminal: the whole run.
The advice through the simulation
SoilCropN / P / K (mg/kg)VerdictAdvice for 10 m2
Poor bedTomato30 / 12 / 94FERTILIZE N P KDAP 369 g, urea 237 g, MOP 337 g
FertilizedTomato140 / 62 / 210ALL GOODnone
After rainTomato46 / 62 / 184FERTILIZE N (LEACHING)urea 314 g, split
After rainPotato46 / 61 / 185FERTILIZE N Kurea 271 g, MOP 59 g
After rainLettuce45 / 62 / 185FERTILIZE Nurea 233 g
Rich compostLettuce260 / 119 / 418TOO MUCH N P Knone

Every Modbus frame was answered with a good CRC, and the advice followed the soil and the crop at every step, including the leaching after the rain and the warning not to fertilize at all.

Download the Project Files

Click the button below to download Soil-NPK-Fertilizer-Advisor-Raspberry-Pi-5-Proteus-Simulation-v1.0.zip (about 13.7 MB, without the source code of the models):

Soil NPK Fertilizer Advisor on Raspberry Pi 5 - Proteus Simulation V1.0
  • Proteus Simulation: Pi-5-Soil-NPK.pdsprj, soil_advisor.py and copies of the models.
  • Python Code: soil_advisor.py, the program.
  • Proteus Library Files: the LIB files of every part.
  • Proteus Model Files: the DLL models and the TEPPi folder (the Python runtime of the simulated Pi).
  • README.txt: the installation steps, the properties, the test results and the links to every library post.

No Proteus yet? Read How to Download and Install Proteus 7 and 8. New to libraries? Follow How to Install a New Library in Proteus.

How to Install the Project Files

  1. Close Proteus and extract the whole zip file, for example to your Desktop.
  2. Copy the files from Proteus Library Files into the LIBRARY folder of Proteus.
  3. Copy everything from Proteus Model Files, the DLL files and the TEPPi folder, into the MODELS folder.
  4. Start Proteus and open the project from the Proteus Simulation folder.

Changing the Code

soil_advisor.py is plain Python: edit it next to the project and press Play again. The bed's area, the root depth and the soil density, the fertilizers' grades and the crop ranges are near the top. On a real Raspberry Pi the same file runs with python3-lgpio, python3-serial and python3-spidev installed, the serial port enabled (and its console disabled) and SPI enabled in raspi-config.

Ideas to Extend the Project

  • Add a soil moisture and temperature probe on the same RS485 pair, at another Modbus address, and correct the readings for them.
  • Log the readings with the date, and draw how the nitrogen falls between feeds.
  • Let the gardener type the bed's size and the fertilizers they have on the dashboard.
  • Advise organic options too: compost, manure or wood ash, each with its own N - P - K.
  • Add the soil's pH, which decides how much of the phosphorus the plants can actually take up.
  • Put several probes in different beds and give each its own crop and advice.

From Simulation to Real Hardware

  • Levels: use a 3.3 V transceiver (MAX3485) or a level shifter between the 5 V MAX485 module and the Pi.
  • The serial port: enable the UART and disable the serial console in raspi-config, so /dev/serial0 is free.
  • The probe: check the baud rate on its label (some are 4800) and push all three needles fully into moist soil.
  • Long cables: a 120 ohm terminator at each end of a long RS485 run, and A to A, B to B.
  • Calibrate against a lab test: send a soil sample to a laboratory once and scale the probe's readings to it.

Troubleshooting

  • "no answer from the probe": A and B swapped, no 12 V on the probe, a different address, or DE / RE dropped too late.
  • CRC errors: the baud rate or the frame format differ; some probes are set to 4800 baud.
  • The advice keeps saying "waiting": the soil is still changing; three readings within 3 mg/kg are needed.
  • TOO MUCH: the soil already holds more than the crop's range; skip the fertilizer and water the bed.
  • The TFT stays black: CS, RESET, A0, SDA and SCK on pins 24, 18, 22, 19 and 23, VCC and LED on 3.3 V.

Limitations of the Simulation

  • The probe is our library's model: a soil scene with a 1.5 s lag and 1 mg/kg of noise, not a real soil with moisture and temperature effects.
  • The crop ranges, the root depth and the soil density are typical values for learning; follow a local soil laboratory's advice for a real field.
  • The network to the laptop and the phone is simulated inside Proteus.
  • Raspberry Pi is a trademark of Raspberry Pi Ltd and the MAX485 a product of Analog Devices (Maxim Integrated); this project is not made or endorsed by them or by Labcenter.

So, that was all about the Soil NPK Fertilizer Advisor on Raspberry Pi 5 - Proteus Simulation. I hope it helps you understand how RS485 and Modbus RTU work, why the MAX485 must let go of the pair in time, how a soil test in mg/kg becomes grams of DAP, urea and potash, and why rain takes the nitrogen but leaves the phosphorus, all tested in a simulation before you push a probe into a real bed. More projects with the ESP32 and the Raspberry Pi 5 are coming. If you have any questions, ask in the comments and I will help you out. Till the next tutorial, take care and have fun!