Overview
In this article, we will learn about the interfacing of Soil NPK Sensor with Arduino & make our own Arduino Soil NPK Meter. The soil nutrient content can be easily measured using NPK Soil Sensor & Arduino. Measurement of soil content N (nitrogen), P (phosphorus), and K (potassium) is necessary to determine how much additional nutrient content is to be added to soil to increase crop fertility.
The soil fertility is detected using NPK sensors. A major component of soil fertilizer is nitrogen, phosphorus, and potassium. The knowledge of the soil nutrient concentration can help us to learn about nutritional deficiency or abundance in soils used to endorse plant production.
There are multiple methods of measuring the soil nutrient content like using some optical sensors or using the spectrometer. But the spectral analysis method is not convenient and the drawback is the data are only 60-70% correct. While comparing the spectral analysis method with traditional wet chemistry methods, the accuracy of the products is yet to be fully resolved, given the paucity of data in that regard.
So, here we will use a JXCT Soil NPK Sensor to detect the soil nitrogen, phosphorous & Potassium in a soil. The JXCT Soil NPK sensor is a low cost, quick responsive, high precision & portable Sensor that works with Modbus RS485. The advantage of this sensor over a traditional detection method is that it gives very fast measurement & data are highly accurate. All you need is to insert its probe in soil and get the reading using Arduino. So, let’s learn in detail about the interfacing of Soil NPK Sensor with Arduino.
Bill of Materials
The components required for making a device that can help you in studying the Soil Nutrient Content is given below. You can purchase almost all the components from Amazon.
S.N. | Components Name | Quantity | Purchase Link |
---|---|---|---|
1 | Arduino Nano Board | 1 | Amazon | AliExpress |
2 | NPK Sensor | 1 | Amazon | AliExpress |
3 | 0.96" OLED Display | 1 | Amazon | AliExpress |
4 | MAX485 Modbus Module | 1 | Amazon | AliExpress |
5 | 9-12V DC Power Supply | 1 | Amazon | AliExpress |
6 | Connecting Wires | 10 | Amazon | AliExpress |
7 | Breadboard | 1 | Amazon | AliExpress |
Soil NPK Sensor
The soil NPK sensor is suitable for detecting the content of nitrogen, phosphorus, and potassium in the soil. It helps in determining the fertility of the soil thereby facilitating the systematic assessment of the soil condition. The sensor can be buried in the soil for a long time. It has a High-quality probe, rust resistance, electrolytic resistance, salt & alkali corrosion resistance, to ensure the long-term operation of the probe part. Therefore, it is suitable for all kinds of soil. It is suitable for the detection of alkaline soil, acid soil, substrate soil, seedling bed soil & coconut bran soil.
The sensor doesn’t require any chemical reagent. Since it has High measurement accuracy, fast response speed, and good interchangeability, it can be used with any microcontroller. You cannot use the sensor directly with the microcontroller as it has a Modbus Communication port. Hence you need any Modbus Module like RS485/MAX485 and connect the sensor to the microcontroller.
The sensor operates on 9-24V & power consumption is very low. While talking about the accuracy of the sensor, it is up to within 2%. The nitrogen, phosphorous & potassium measuring resolution is up to 1mg/kg (mg/l).
Using this Soil NPK Sensor, you can make your own Arduino Soil NPK Meter or any Cloud IoT Based Soil Nutrient Content Monitoring System.
Specifications
1. Power: 9V-24V
2. Measuring Range: 0-1999 mg/kg (mg/l)
3. Operating Temperature: 5-45 °C
4. Resolution: 1mg/kg
5. Precision: ±2% F.S.
6. Output Signal: RS485
7. Baud Rate: 2400/4800/9600
8. Protection Class: IP68
MAX485 TTL to RS-485 Interface Module
The MAX485 TTL to RS-485 Interface Module allows us to use the RS-485 differential signaling for robust long-distance serial communications up to 1200 meters or in electrically noisy environments and is commonly used in industrial environments. It supports up to 2.5MBit/Sec data rates, but as distance goes up, the maximum data rate that can be supported comes down.
The data starts out as a typical TTL level serial as far as the microcontroller is concerned while the RS-485 module takes care of converting the electrical signals between TTL and the differential signaling used by RS-485. A significant benefit of RS-485 is that it supports multiple devices (up to 32) on the same cable, commonly referred to as ‘multi-drop’.
Specifications
1. Use MAX485 Interface chip
2. Uses differential signaling for noise immunity
3. Distances up to 1200 meters
4. Speeds up to 2.5Mbit/Sec
5. Multi-drop supports up to 32 devices on same bus
6. Red power LED
7. 5V operation
Pinout & Module Connection
The module has two 4-pin headers on the assembly.
1 x 4 Header (Data side)
RO = Receiver Output. Connects to a serial RX pin on the microcontroller
RE = Receiver Enable. Active LOW. Connects to a digital output pin on a microcontroller. Drive LOW to enable receiver, HIGH to enable Driver
DE = Driver Enable. Active HIGH. Typically jumpered to RE Pin.
DI = Driver Input. Connects to serial TX pin on the microcontroller
1 x 4 Header (Output side)
VCC = 5V
B = Data ‘B’ Inverted Line. Common with the B
A = Data ‘A’ Non-Inverted Line. Connects to A on far end module
GND = Ground
1 x 2 Screw Terminal Block (Output side)
B = Data ‘B’ Inverted Line. Connects to B on far end module
A = Data ‘A’ Non-Inverted Line. Connects to A on far end module
Interfacing Soil NPK Sensor with Arduino
Now, let us interface the Soil NPK Sensor with the Arduino Nano Board using the MAX485 Modbus Module. Check the connection diagram below.
Connect the R0 & DI pin of from the Modbus to D2 & D3 Arduino using Software Serial. Similarly, we have to enable DE & RE high. To do this connect the DE & RE Pins to the D7 & D8 pin of Arduino. The NPK Sensor has 4 wires. The brown one is VCC which needs a 9V-24V Power Supply. The GND pin which is black in color. So connect it to the GND of Arduino. The Blue wire which is the B pin is connected to the B pin of MAX485 & the Yellow Wire which is the A pin is connected to the A pin of MAX485.
The 0.96″ SSD1306 OLED Display is an I2C Module. Connect the OLED Display VCC & GND pins to 3.3V & GND of Arduino. Similarly, connect its SDA & SCL pins to the A4 & A5 of Arduino. You can follow the circuit diagram & assemble the circuit on a breadboard or make a custom PCB.
Modbus Command for NPK Sensor
Modbus commands can instruct a Modbus Device to:
1. change the value in one of its registers, which is written to Coil and Holding registers
2. read an I/O port: Read data from Discrete and Coil ports,
3. command the device to send back one or more values contained in its Coil and Holding register
A Modbus command contains the Modbus address of the device it is intended for (1 to 247). The Modbus address is also called an inquiry frame. Only the addressed device will respond and act on the command, even though other devices might receive it.
The NPK Sensor has 3 different inquiry frame for reading the value of Nitrogen (N), Phosphorous (P) & Potassium (K). The inquiry frame is provided along with the instruction manual. For the NPK data the following individual inquiry frameworks:
1. Nitrogen: {0x01,0x03, 0x00, 0x1e, 0x00, 0x01, 0xe4, 0x0c}
The inquiry frame for getting Soil Nitrogen Value is:
You will get the following as a response:
You can calculate the Soil Nitrogen from the Response you receive. For example, if you get 0030 as a response then Soil Nitrogen Value will be:
0020 H(hexadecimal) = 32 (Decimal) => Nitrogen = 32mg/kg
2. Phosphorous:{0x01,0x03, 0x00, 0x1f, 0x00, 0x01, 0xb5, 0xcc}
The inquiry frame for getting Soil Phosphorous Value is:
You will get the following as a response:
You can calculate the Soil Phosphorous from the Response you receive. For example, if you get 0030 as a response then Soil Nitrogen Value will be:
0025 H(hexadecimal) = 37 (Decimal) => Phosphorous = 37/kg
3. Potassium:{0x01,0x03, 0x00, 0x20, 0x00, 0x01, 0x85, 0xc0}
The inquiry frame for getting Soil Potassium Value is:
You will get the following as a response:
You can calculate the Soil Potassium from the Response you receive. For example, if you get 0030 as a response then Soil Potassium Value will be:
0030 H(hexadecimal) =48 (Decimal) => Potassium = 48mg/kg
Source Code/Program
The source code for interfacing Soil NPK Sensor with Arduino & retrieving Soil Nutrient value from the Sensor via Modbus command is given below. You can send the command and retrieve the value in HEX Code. The HEX code needs to be converted into Decimal to get the Measured Soil Nutrient content data.
Since we are using OLED Display to display the Soil Nutrient values (Nitrogen, Phosphorous & Potassium) in mg/kg, you will need OLED Library. Download the following OLED Library and add it to the Arduino IDE.
1. Adafruit SSD1306 Library: Download
2. Adafruit GFX Library: Download
Here is the complete source code. Compile the code & upload it to the Arduino Nano Board.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 |
#include <SoftwareSerial.h> #include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> #define SCREEN_WIDTH 128 // OLED display width, in pixels #define SCREEN_HEIGHT 64 // OLED display height, in pixels #define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin) Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); #define RE 8 #define DE 7 //const byte code[]= {0x01, 0x03, 0x00, 0x1e, 0x00, 0x03, 0x65, 0xCD}; const byte nitro[] = {0x01,0x03, 0x00, 0x1e, 0x00, 0x01, 0xe4, 0x0c}; const byte phos[] = {0x01,0x03, 0x00, 0x1f, 0x00, 0x01, 0xb5, 0xcc}; const byte pota[] = {0x01,0x03, 0x00, 0x20, 0x00, 0x01, 0x85, 0xc0}; byte values[11]; SoftwareSerial mod(2,3); void setup() { Serial.begin(9600); mod.begin(9600); pinMode(RE, OUTPUT); pinMode(DE, OUTPUT); display.begin(SSD1306_SWITCHCAPVCC, 0x3C); //initialize with the I2C addr 0x3C (128x64) delay(500); display.clearDisplay(); display.setCursor(25, 15); display.setTextSize(1); display.setTextColor(WHITE); display.println(" NPK Sensor"); display.setCursor(25, 35); display.setTextSize(1); display.print("Initializing"); display.display(); delay(3000); } void loop() { byte val1,val2,val3; val1 = nitrogen(); delay(250); val2 = phosphorous(); delay(250); val3 = potassium(); delay(250); Serial.print("Nitrogen: "); Serial.print(val1); Serial.println(" mg/kg"); Serial.print("Phosphorous: "); Serial.print(val2); Serial.println(" mg/kg"); Serial.print("Potassium: "); Serial.print(val3); Serial.println(" mg/kg"); delay(2000); display.clearDisplay(); display.setTextSize(2); display.setCursor(0, 5); display.print("N: "); display.print(val1); display.setTextSize(1); display.print(" mg/kg"); display.setTextSize(2); display.setCursor(0, 25); display.print("P: "); display.print(val2); display.setTextSize(1); display.print(" mg/kg"); display.setTextSize(2); display.setCursor(0, 45); display.print("K: "); display.print(val3); display.setTextSize(1); display.print(" mg/kg"); display.display(); } byte nitrogen(){ digitalWrite(DE,HIGH); digitalWrite(RE,HIGH); delay(10); if(mod.write(nitro,sizeof(nitro))==8){ digitalWrite(DE,LOW); digitalWrite(RE,LOW); for(byte i=0;i<7;i++){ //Serial.print(mod.read(),HEX); values[i] = mod.read(); Serial.print(values[i],HEX); } Serial.println(); } return values[4]; } byte phosphorous(){ digitalWrite(DE,HIGH); digitalWrite(RE,HIGH); delay(10); if(mod.write(phos,sizeof(phos))==8){ digitalWrite(DE,LOW); digitalWrite(RE,LOW); for(byte i=0;i<7;i++){ //Serial.print(mod.read(),HEX); values[i] = mod.read(); Serial.print(values[i],HEX); } Serial.println(); } return values[4]; } byte potassium(){ digitalWrite(DE,HIGH); digitalWrite(RE,HIGH); delay(10); if(mod.write(pota,sizeof(pota))==8){ digitalWrite(DE,LOW); digitalWrite(RE,LOW); for(byte i=0;i<7;i++){ //Serial.print(mod.read(),HEX); values[i] = mod.read(); Serial.print(values[i],HEX); } Serial.println(); } return values[4]; } |
Code Explanation
This Arduino code is designed to interact with an NPK (Nitrogen, Phosphorus, and Potassium) sensor, which are typically used to measure the levels of these nutrients in soil. This information is then displayed on an OLED screen.
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <SoftwareSerial.h> #include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> #define SCREEN_WIDTH 128 // OLED display width, in pixels #define SCREEN_HEIGHT 64 // OLED display height, in pixels #define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin) Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); #define RE 8 #define DE 7 |
This section includes necessary libraries for serial communication, I2C communication, and functionality for the OLED display. It also defines certain parameters such as screen width and height for the OLED display, pin number for reset, and pin numbers for the RE (Receive Enable) and DE (Driver Enable) pins used in RS485 communication.
1 2 3 4 5 6 |
const byte nitro[] = {0x01,0x03, 0x00, 0x1e, 0x00, 0x01, 0xe4, 0x0c}; const byte phos[] = {0x01,0x03, 0x00, 0x1f, 0x00, 0x01, 0xb5, 0xcc}; const byte pota[] = {0x01,0x03, 0x00, 0x20, 0x00, 0x01, 0x85, 0xc0}; byte values[11]; SoftwareSerial mod(2,3); |
This part of the code declares and initializes arrays to contain byte sequences for requesting Nitrogen, Phosphorous, and Potassium readings from the sensor. It also initializes a byte array to hold response values, and a software serial interface on pins 2 and 3.
1 2 3 4 5 6 7 8 |
void setup() { Serial.begin(9600); mod.begin(9600); pinMode(RE, OUTPUT); pinMode(DE, OUTPUT); //... OLED display initialization and message... } |
The setup function initializes the hardware serial port and software serial port at a baud rate of 9600. It also sets the RE and DE pins as outputs. It initializes the OLED display and shows a message.
1 2 3 4 5 6 7 |
void loop() { byte val1,val2,val3; val1 = nitrogen(); val2 = phosphorous(); val3 = potassium(); //... Print values to the serial monitor and OLED display... } |
This is the main loop where it continually requests and retrieves Nitrogen, Phosphorous, and Potassium values from the sensor using the respective functions. It then prints these values to the serial monitor and updates the OLED display with these values.
1 2 3 4 5 6 7 8 9 |
byte nitrogen(){ //... Send request, read response, return value... } byte phosphorous(){ //... Send request, read response, return value... } byte potassium(){ //... Send request, read response, return value... } |
These are the functions that handle sending the request byte sequences to the sensor and reading the response. They return the sensor reading values. In each function, it first sets the DE and RE pins high, indicating that it wants to write to the bus. Then it sends the request byte sequence for the respective nutrient. After sending, it sets DE and RE low, indicating that it wants to read from the bus. It then reads the response from the sensor into the ‘values’ array and returns the value of interest.
Note: The code is the only capable of measuring the Soil NPK values up to 255mg/kg. This is because we are only reading 8bit value. According to the datasheet of the Sensor, you can measure the value up to 1999mg/kg. To read such value we have to read 16bit data. Refer to the Soil EC Sensor Code to read such high values.
Monitoring Soil NPK Data on OLED Display
Once you upload the code to Arduino Nano Board, the OLED will initialize along with the sensor. The sensor will take some time for stability and the reading may be incorrect initially.
Once the sensor gets becomes stable, you can dip the sensor in the soil to get the NPK Reading. The volume of Nitrogen, Phosphorous & Potassium which are the Ammonium content in the soil will be displayed as mg/Kg.
So this is how you interface Soil Nutrient Sensor Arduino & get the NPK Readings. Similarly, put the sensor in different samples of soil. You will see a variation in the volume of NPK depending upon the type of soil.
Video Tutorial & Guide
Follow the following video to learn about the entire project & code information.
Apart from measuring Soil NPK, you can also measure Soil Moisture Content using Soil Moisture Sensor, Soil Ph using Soil Ph Sensor & Soil EC & Salinity using Soil EC Sensor, which is explained in my one the previous post.
Thus, you can make your own Arduino Soil NPK Meter using the above guide & determine the fertility of the soil. You can also check the advanced version of this project. In the advance version, you can combine Soil NPK Sensor, Temperature Sensor & Soil Moisture Sensor with Arduino: IoT Based Soil Nutrient Monitoring.
136 Comments
can u read the npk modbus sepcification on the modbus scanner
Maybe.
I haven’t tried it. You can try and let us know.
Thanks.
Yeah i can but i cant even know what the values are and there is some chinese words.I used CAS modbus scanner. Does the npk values show on serail montior coz i cant read the values thanks
i created this same project a year ago. this sensor has pc software where you can configure everything of modbus. even address of you sensor and baund rate also.
This sensor can be use to detect NPK in water?
Nop. This sensor is designed for soil only.
thx for your answer. Do you know if there is an NPK sensor for water?
Have you compared its results with soil analysis of lab. I couldn’t find any research material related to testing of soil with this method.
can upgrade this project like soil npk recommendation with esp32 or something u could.
Based on the result of the sensor, what it would be if it is converted on percentage?
You can convert mg/kg into percentage. For example 130mg/1kg= 0.13gm/1000gm which is equivalent to 0.013%.
Respected Mr. Alam,
I am an computer science engineering student from Bangalore. I am in need of this sensor for my final year project and on searching for it, it doesn’t seem to be available anywhere and it is also very expensive. Is there anyway you could help us in this regard. I could return it right after the project is done. This is the most important component of the project and without it i won’t be able to do my project. I request you to help me out in this regard.
You can get these sensors on aliexpress.
Hi I tried to this but I only get 255, what could be the problem?
By the way i’m using uno.
Have you resolved the issue?
Have you resolved the issue? I am also getting the same output
The reason that most of the people are getting 255 or 0 as output for all N, P & K values:
1. Wrong connection of DI, DE, RE, RO with respect to code
2. MAX485 Module should be powered via 5V & should have common GND
3. The NPK Sensor needs 9V or 12V or more. Supply appropriate voltage to its VCC pin. The sensor won’t operate at 5V or anything lesser than 9V.
4. Check the Slave address of NPK Sensor with respect to the datasheet or manual provided by manufacturer. The sensor will only give correct output if the address is correct. You can also contact the manufacturer for support.
How long will the sensor stabilized? The nitrogen is now reading properly. but the P and K is not reading yet.
I need this sensor I,m from Bangladesh please help me
Have you solve this problem yet?
Have you resolve this issue. Cause i have the same problem tnx for answering
someone has tested it and confirms that it gives the data well?. thanks
Hi, is it possible to set up the NPK sensor with NodeMCU?
Hi mr Alam, can I use this sensor with NodeMCU?
You can try. I was unable to get the result.
Hi great job, it gives me an error while compiling.
Usando librería SPI con versión 1.0 en la carpeta: C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SPI
exit status 1
Error compilando para la tarjeta Arduino Nano.
i have questions. 1. should i purchase the npk sensor shown on the blog which is now 285 usd on amazon.
. the same kind of npk sensors are sold in ebay for 90 usd. WHY it is so much different in price. are they same!
2. i am learning hydroponics. why Mr. Alam said it can’t be used in fluid and only in soil. although its designed to use in soil the readings must be slightly offset. in otherwords there must be an approximate value shown which has somewhat direct relation to the npk content in hydroponic solution. this will be more than satisfactory for optimizing. further optimization may be dealt with ion specific electrodes.
also, how is the working principle. is it using same principle as EC.
in the diagram, the OLED vcc IS IT connected to ardrino pin and not main power supply of 5+v
thanks
You can buy this sensor from eBay if the sensor is the same. The price in Amazon is just so high. You can get the sensor at around 60$ from Chinese sites like aliexpress or Alibaba.
The sensor is designed for measuring soil NPK value, not the water. I already checked with water, the result is not so good as expected. The working principle is based on ionization same as Electrical Conductivity.
The OLED works at 3.3V and 5V too. It’s better to connect the OLED to 3.3V to reduce power.
Can anyone confirm the +/- 2% accuracy? As well can the probes be bent and still be functional or will they be off. Thanks
Thanks Alam,
const byte nitro[] = {0x01,0x03, 0x00, 0x1e, 0x00, 0x01, 0xe4, 0x0c};
const byte phos[] = {0x01,0x03, 0x00, 0x1f, 0x00, 0x01, 0xb5, 0xcc};
const byte pota[] = {0x01,0x03, 0x00, 0x20, 0x00, 0x01, 0x85, 0xc0};
are these inquiries standard. or do we need to modify according to the sensor.
Modify the inquiry bit according to your sensor manufacturer. These are standard for most of the sensors. But it may vary for some sensors.
if(mod.write(nitro,sizeof(nitro))==8){
does it mean if we get a reply from the modbus rs485 for our inquiry frame nitro, meaning mod.write if its true does it mean we are receiving a response frame. are the receiving pins standard. the rest i understand it as if the size is 8 bit then so and so.
for(byte i=0;i<7;i++){
which location the response value is received or saved.
is it here.
and where is it getting converted from hex to readable format.
}
return values[4];
one more thing Alam the receiving info is stored under 4th place. i want to know how the response info is saved and is it replacing the inquiry frame.
How do you power up the npk sensor. Can you please help me for that ? Thank you
Power it using external 9V supply. You can use a 12V battery or a 9-12v DC Adapter
I’m sorry, I have tried 9v and 12v and I’m still getting a 255 value. I believe I’m correct in steps 1-2 as well.
I have looked into “Soil EC Sensor Code” but remain unclear for me how do I read 16bit data.
Additionally, what do you mean by “Slave address” in step 4 ?
Mr. Alarm can you respond?
Hi Carson,
I am unsure about this products specificity. The sensor is not accurate . I have experimented with some potting soil and the results are way off. The potting soil bag sais that nutrient levels are as follows N= 160-300 mg/kg ; P = 80-140 mg/kg ; K = 160- 260 mg/l.
The result from the sensor without adding water: N: 26-27 mg/kg ; P: 10-11 mg/kg; K: 9- 10 mg/kg .
The result from the sensor water (added 100 ml to 166 g of soil): N: 133-134 mg/kg ; P: 54 mg/kg; K: 50 mg/kg .
Hi,
I do not understand the section of the wiring explaining :
Does it mean we should connect DE with RE ? this is not shown on the diagram image.
Additionally, I’m trying to figure out as well why I’m getting a fixed value of 255.
I’m using your code and an Arduino Uno board.
Please could you clarify as you obviously know the caveats and did not give enougt details.
Not everything works the same. I used an Arduino Nano and to get it to read the values of NKP I connected the D2 pin to the RX, the D3 to TX and removed the wired from D8 leaving the wire from RE on the RS485 adapter board attached to D7. I powered my unit from a lithium 12 battery to make it mobile by using that input on vin.
Well, that was wrong. That change got it to always read ~51 on all 3. On my Arduino Nano, when I put an LED and resistor between D2 and ground the LED will always be on but with some flashing. With the LED plus resistor I get zero’s on all 3 parts of the display but it won’t read the values.
You can either enable it HIGH using the Arduino Digital Pin via Code. Or you can simply Short the DE & RE Together. In my case I enabled it high using the Arduino Digital Pin
Which “it” do you enable high?
same problem here (only 0xFF)… using mega 2650.
Did you get it solved?
BTW i sniffed the rs485 and after sending a 0D 0A (CR and LF) are send out by the arduino and sensor.
0xFF problem Solved…
https://www.arduino.cc/en/Reference/softwareSerial
Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).
Pins used to transmit must be of the type PCINT. very very annoying
Very right. Those pins which accept interrupt can only be used for Software Serial.
Garfield = Piet Moenen
Elaboration: I used a 2560 and connected the DI and RO to pin 3 and 2. All i received was FF. The data transmitted was correct. (sniffed with PC (accessPort.. hence the CR and LF))
After connecting DI and RO to pin 11 and 10 on the Mega 2560 and changing the code to
SoftwareSerial mod(10,11);
all was well.
Although… after wattering the soil, the values change… so the question is… are NPK sensors any good? Do they measure the NPK values accurately?
Hello,
It seems I’m having the same “FFFF” or 255 value. I’m using an Arduino Uno, are there any restrictions ?
I have tested both : pins 3, 2 and pins 11, 10 (and updating code accordingly). According to my documentation, pins 3&2 should be compatible with interrupt.
Any idea ?
Soldering the connections to the Arduino Uno seems to have solved the 255 problem for me. I must have been having connection problems with the breadboard. I have it wired exactly as the diagram shows for the Arduino Nano but with the Uno..
You could connect a PC to the RS485 wires and sniffer the data… is that data also FF?
You can also inject data from the PC in the RS285.
Hi, I have the same problem, were you able to solve?
I can confirm that the above tutorial is correct but the sensor does not measure directly the NPK content of the soil. By using benchmarking solutions of 50ppm N-NO3, 7ppm N-Nh4 and a few others + 2 samples of soil whose NPK content was determined using spectrophotometry, i have determined that this sensor is nothing more than an Ec sensor. If you wish to measure such thing, you can find way cheaper solutions out there and can infer the NPK content ( just like this sensor does) of the soil.
When I made solder connections I started getting reasonable readings but only when the soil was wet.
I have had success with measuring the NPK levels in my field by taking multiple samples at different locations. The OLED was nearly impossible to read in the sunlight so I brought the samples into my house in ziplock bags. The soil was dry so I used distilled water to wet it well. Inserting the probe and waiting until the reading quit changing gave me believable if not totally accurate numbers. I tried using tap water for the samples also and got wildly varying numbers depending on the type of soil. This will now give me a good basis for ordering fertilizer for my fields, making the project worth far more than its cost.
Next to attempt is to use a Lilygo e ink display mounted to an ESP32 so I can just go around the fields and measure.
Nice to know you are satisfied and worked fine for you. God bless you. Do let us know the result, in future with ur fertiliser.
did you solve the problem in the end?
I do not know what I have done wrong, I only get:
nitrogen value 255 mg / kg
Phosphoro Value 255 mg / Kg
Potassium Value: 255 mg / kg
I returned the sensor and bought a new one. Now everything works
Congratulations. Glad to know it worked for you.
I am trying to find ways to make the sensor more space efficient. Would it damage the sensor if you cut/sharpen the prongs. Also, would it be possible to remove the casing of the sensor and stripping it down to just the prongs and connections?
I would advise you to compare your readings to a lab analysis. Maybe reach out to a nearby university of agronomy or agrochemistry and ask for their help. That’s what i did and found out that this sensor just infers the quantity of N P K in the soil and it has really unreliable results ( it probably just measures the electrical conductivity of the soil).
Thank you so much for the clear explanation and letting us know about the results given out by this sensor. We will compare the results of this sensor with the chemistry lab result and share the results here.
I totally agree with MihneaStoica. I have compared the readings from potting soil and sand and the results do not look promising. Sand: N: 71mg/kg ; P: 29mg/kg ; K: 26 mg/kg. If I am to believe these results, then I could harvest 5 t/ha of wheat from sand, which is impossible because of sands low CEC
Hi Carson,
I am unsure about this products specificity. The sensor is not accurate . I have experimented with some potting soil and the results are way off. The potting soil bag sais that nutrient levels are as follows N= 160-300 mg/kg ; P = 80-140 mg/kg ; K = 160- 260 mg/l.
The result from the sensor without adding water: N: 26-27 mg/kg ; P: 10-11 mg/kg; K: 9- 10 mg/kg .
The result from the sensor water (added 100 ml to 166 g of soil): N: 133-134 mg/kg ; P: 54 mg/kg; K: 50 mg/kg .
Hi Mr. Alam, thank you for answering my question.
May I have a request? Can you give me a pseudo code of the NPK sensor?
Hi,
How to wire multiple RS485? I heard it can support up to 32 devices. But do we need separate MAX485 for each devices and how the wiring will work and how about the code?
Thanks;
I do not know what I have done wrong, I only get:
nitrogen value 255 mg / kg
Phosphoro Value 255 mg / Kg
Potassium Value: 255 mg / kg
please help me
Hi, some great work by you Alex/Alam. I also found that the registry codes given in the manual of JXCT NPK sensor I purchased via AliExpress from JXCT shop was incorrect. I tried your codes and it works. However I found the results somewhat confusing. In a pure soil the values of N=84 P=26 K=36. I added a dilute solution of Ammonium Nitrate and the values moved to 189/59/81. Next I added a garden food chemical that says its N/P/K is 20/20/20 percent and the values moved to 138/121/168. I again added Ammonium Nitrate and the values moved to 170/52/74 . So the addition of AmNit causes N/P/K to rise to nearly double. the addition of garden food chemical causes N to fall but P/K rise a lot. But the addition of AmNit again causes the N to rise but P/K to fall to nearly half….Are we really measuring NPK or just Electrical Conductivity. Can you answer.
The device is internally programmed in such a way that the NPK represents the electrical conductivity of particular sample. And moreover the sensor can only give the accuracy of around 70%.
How internally programmed?
And also, is this the concept on which the JCXT NPK sensor is based? https://aip.scitation.org/doi/abs/10.1063/1.5142147
Please let me advice , can i check liquid fertilizer npk.
Finally I tested through various chemical and conductivity tests and have come to the conclusion that these JXCT type NPK sensors are actually not measuring NPK but they measure soil electrical conductivity and this is then taken as a measure of Nitrogen. Next the so called microcontroller inside does is to use a straight line equation that uses solpe and intercept of Nitrogen vs EC plot and predicts Phosphorus and Potassium. No matter what you add the sensor will always give Nitrogen>Potassium >Phosphorus. If your soil has 46‰ urea and zero percent P and K the JXCT type will show Nitrogen as 200 and K nad P as 60 and 80. That is with no K and P the sensor will show they are! The 8 bit output means after N going over 255 the K nad P will be 90 and 120 but N will show 30, that means its the residual of the 8 bits appearing to show less N. If you use the K data and plot it against N then you get a straight line equation which can then be used to Predict N and then you can calculate N as 330 where K and P are 90 and 120. In short, buy a $12 at https://www.dfrobot.com/product-1662.html and $7 at
https://a.aliexpress.com/_m0s5yU7 . Do not waste $70-90 on these duped JCXT sensors when you can yourself use EC as a measure of N. However no sensor based on EC can give you K and P because thats a myth.
Thanks for all these tests and information and for letting us know about the capability of this sensor.
Instead of spending $70 use dfrobot TDS sensor and board for $7 at Aliexpress and measure electrical conductivity, EC, as a measure of Nitrogen. This JXCT type sensors are fraud, they actually are cheap EC sensors build as if they measure NPK. Instead these use EC to approximate Nitrogen and then calculate Pand K from Nitrogen! Your solution may have no P or K but these will always show them. If you add say 400ppm of N then the JXCT type will show K as 200 and P as 180 even though your solution will have zero P nad K. So dont be fooled, buy cheap TDS sensor!
FOR ESP32
#include <LiquidCrystal.h>
#include <WiFi.h>
#include <EEPROM.h>
////////////////////////////////////////////////////////////////////////
// Definimos las constantes
#define COLS 20 // Columnas del LCD
#define ROWS 4 // Filas del LCD
#define RS 13
#define EN 12
#define D4 14
#define D5 27
#define D6 26
#define D7 25
LiquidCrystal lcd(RS ,EN,D4,D5,D6,D7);
////////////////////////////////////////////////////////////////////////
TaskHandle_t Task1;
TaskHandle_t Task2;
TaskHandle_t Task3;
WiFiServer *Servidor;
WiFiClient client;
String cadena;
boolean cliente=false;
const byte NITROGENO[]={0x01,0x03,0x00,0x01e,0x00,0x01,0xb5,0xcc};
const byte FOSFORO[]= {0x01,0x03,0x00,0x01f,0x00,0x01,0xe4,0x0c};
const byte POTASIO[]= {0x01,0x03,0x00,0x020,0x00,0x01,0x85,0xc0};
////////////////////////////////////////////////////////////////////////
void MENU(void *pvParameter);
void SERVIDOR(void *pvParameter);
void LECTURAS(void *pvParameter);
int lectura(const byte trama[]);
/////////////////////////////////////////////////////////////////////////
// Create An LCD Object. Signals: [ RS, EN, D4, D5, D6, D7 ]
void setup()
{
Servidor=new WiFiServer(25);
Serial.begin(9600);
WiFi.mode(WIFI_AP);
WiFi.softAP(String(“AGROLINK”).c_str(),String(“12345678”).c_str());
Servidor[0].begin();
lcd.begin(20,4);
lcd.clear();
lcd.setCursor(1,0);
lcd.printf(“BIENVENIDO AL NPK”);
lcd.setCursor(1,1);
lcd.printf(” SCOPE”);
IPAddress IP = WiFi.softAPIP();
xTaskCreate(MENU,”MENU”,5024,NULL,2,&Task1);
xTaskCreate(SERVIDOR,”SERVIDOR”,5024,NULL,2,&Task2);
}
void loop()
{
}
///////////////////////////////////////////////////////////////////////////
void MENU(void *pvParameter)
{
while(true)
{
}
}
///////////////////////////////////////////////////////////////////////////
void SERVIDOR(void *pvParameter)
{
while(true)
{
client = Servidor[0].available();
if(client)
{
Serial.println(“New Client.”);
while (client.connected())
{
if (client.available())
{
cadena=client.readStringUntil(‘\n’);
if(cadena.equals(“ESCANEAR”))
{
cliente=true;
if(Task3==NULL)xTaskCreate(LECTURAS,”LECTURAS”,5024,NULL,2,&Task3);
}
else if(cadena.equals(“STOP”))
{
cliente=false;
lcd.clear();
lcd.setCursor(1,0);
lcd.printf(“BIENVENIDO A AGROLINK”);
lcd.setCursor(1,1);
lcd.printf(” SCOPE”);
}
client.flush();
cadena=””;
}
}
}
delay(1);
}
}
///////////////////////////////////////////////////////////////////////////////////
void LECTURAS(void *pvParameter)
{
while(true)
{
if(cliente)
{
// client.println(“ENCENDIDO”);
client.println(“N: 0p/m,K: 0p/m,P:0p/m,PH:0,T:0″);
lcd.clear();
lcd.setCursor(0,0);
lcd.printf(” OBTENIENDO”);
lcd.setCursor(0,1);
lcd.printf(“PARAMETROS DE SUELO”);
lcd.setCursor(0,2);
lcd.printf(“N:0p/m,K:0p/m,P:0p/m”);
lcd.setCursor(0,3);
lcd.printf(“PH:0,Temp:0”);
delay(500);
}
delay(1);
}
}
That is what i am getting as well….did your fix the problem?
Thank you for this information, I’ve implemented parts of it in a project that uses a simimlar unit, but has 5 spikes rather than 3.
I’m wondering if you know the polynomial used to compute the CRC bytes, (high and low), since they need to be incorporated into the inqury frame – the unit you’re using here has the CRC byes explicitly detailed in the documentation so the way they’re calculated isnt revealed, but in the documentation for the 5 – spike unit, there is no information on how the CRC bytes are computed.
In your case, requesting from register 1e uses CRC bytes e40c – how are those CRC bytes determined?
get only 0xFF as response … wiring checked. using arduino nano. Voltage also checked at 12.5V.
Good day. Please can anyone explain what this means please?
Arduino: 1.8.15 (Windows 10), Board: “Arduino Nano, ATmega328P”
Sketch uses 16592 bytes (54%) of program storage space. Maximum is 30720 bytes.
Global variables use 755 bytes (36%) of dynamic memory, leaving 1293 bytes for local variables. Maximum is 2048 bytes.
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00
An error occurred while uploading the sketch
This report would have more information with
“Show verbose output during compilation”
option enabled in File -> Preferences.
Can I ask sir If we can used it in determining the npk content in plant leaves? This will be a great help if you reponse. Thank you
Not at all. The sensor is only designed for soil. You spectral sensor like AS7265x to measure the NPK content in leaves or something else.
Thank you so much sir. Can I ask again sir if How much is the expected price of the spectral sensor like AS7265x
Sir do you have any reference that spectral sensor like AS7265x can measure the NPK content of leaves?. Thank you so much sir for your responce
Sir do you have any reference regarding that spectral sensor like AS7265x can detect the NPK content of plant leaves? Hope you consider my question. Thank you so much in advance
ify, tienes que seleccionar la opcion ATmega 328 (Old Bootloader) para poder cargar el programa en el nano. Otra opcion es que estes utilizando el puerto serial (pines 0 y 1) conectados a algun dispositivo y estes tratando de cargar el programa por el puerto USB, lo cual entraria en conflicto ya que son el mismo puerto y por eso no te deja cargar el programa, tendrias que desconectar el dispositivo de comunicacion provisionalmente mientras descargas el programa y despues conectarlo nuevamente.
any one able to send the soil npk sensor library for proteus
I also had a problem with communication not working properly.
As a result of testing for several days, when I change the baud rate of Software Serial to 4800, the data comes in normally.
mod.begin(9600); —> mod.begin(4800);
i have had success using esp8266 to connect to rs485 and display on screen (including web server/blynk). And it is working perfectly. The power supply for it is only 5v (using the same 5v power supply for both npk sensor and esp8266). I have some pictures
Can you share your code and pictures along with some documentation to our mail address: [email protected]. We will like to publish your work on our website with your name.
Hi, does anyone have a pdf of that npk soil sensor? tnx
Hi TNKHOA,
Can you share your code to me ([email protected])?
Thanks!
Hi, I purchased SEM225 6in1 sensor. It works fine with UART Assistant and gives proper values. However when using ESP32 or Atmega328P and your program here it gives wrong values. If temp and moisture only are sought the values are something, when nitrogen or ph is added to be sought the values of temp and moisture change. Any idea why this is happening?
The baud rate is 4800, the serial works at 9600.
Even i tested the same sensor in the past and got the same result what you are telling. The reason is signal isolation, one sensor is disturbing the other one.
Hello Sir , I have tried NPK sensor with Arduino UNO and it’s working correctly. But when I am using NPK sensor with Arduino UNO along with LoraShield module , I am not getting the result ; it’s showing 255 only. Could Anyone Help me with this?
Amigo quando você fala “onde você pode configurar tudo em Modbus. A pergunta é ? tem como configurar para os outros nutrientes como: Cálcio , Magnésio , Enxofre , Boro , Zinco , Ferro , Manganês , Molibidênio , Níquel e Cobalto.
Your LORA shield needs digital pin 8 on your Arduino Uno. That pin is also needed for the NPK sensor. See line Line 11 in your Arduino IDE where it says, “#define RE 8” You could try changing that from 8 to 9 and see if that works.
please drop your email address, i want to contact you urgently regarding ion selective electrodes. [email protected]
please, kindly drop your email address for me. I want to contact you regarding ion selective electrodes. thanks. Mine: [email protected]
I am working on this project but using MSP430 board and getting few errors.Can you help me with that sir?
Hello guys, I’m a big fan of your projects. A massive thank you.
In this precise project, in my case the measurment has significant changes almost every 5 seconds. I don’t know if this sensor need a little time gap to stablish. Could be a baud rate problem, maybe the sensor is damaged…
Good Day Mr. ALam I have problem running npk sensor in ttgo t-call esp32 sim800l the problem is that no pinout no tag given in the code can you help me
No accuracy at all. It’s based on EC and using mathematical conversion to N,PK. Even their own manufacturer also said like this. You can try to put Urea fertilizer(Pure nitrogen) and you will see that the N is still the same while PK increase instead.
No accuracy at all. It’s based on EC and using mathematical conversion to NPK. Even their own manufacturer also said like this. It’s waste of time and money with this one and can have a dangerous consequence if you follow its result.
I even buy these Chinese made N/P/K tube(3 separate tubes) sensor with LCD. But the result are just the same as this 3 in 1. So the bottom line is they are all scam.
No accuracy at all. It’s based on EC and using mathematical conversion to NPK. Even their own manufacturer also said like this. It’s waste of time and money with this one and can have a dangerous consequence if you follow its result.
@Riaz Ahmed,
How sure are you that JCXT uses this concept? I tested several of this sensors and all of them give very inaccurate result. I use Urea fertiliizer on the soil but the sensor read high value of K instead of N. I think it’s based on EC and convert the result to NPK.
Can someone please guide why i am getting 255 for all values? i have rechecked my connections as per directions several time. Also i am using the inquiry frame from the manufacturer still i am having this issue. Please guide
Do you remember the name of the software?
I performed 10 laboratory tests and compared the same samples with the sensor. The values delivered by the sensor are not even close to the laboratory values. Also, the values vary a lot with the soil moisture.
Hello. I had a question, what kind of soil does the soil npk sensor read better? Dry soil? Or wet soil? What percentage should the soil moisture be?
hi, thanks for your heads up. it worked for me, but i have a quick question. why dont it work with arduino mega hardware serial communication.
Can someone help me with the code to read values greater than 255, how can I read up to 1999 mg/kg as indicated in the sensor datasheet?
Read the article properly. A method is already mentioned and a link is already attached on reading the value upto 1999.
Did you fix it? I’m having the same issue, getting only 255. I’m using esp8266.
Hey! Did you fix it? I’m also getting 255 and have been stuck here for some days!!
Hi Admin, is there a solution to getting only 255 values? I’ve been stuck here for a couple of days unfortunately and followed all the steps in the guide and in the comment. I’m using Nodemcu with 8266. Thank you!
Hi Guys, I have the same problem — getting 255. I have purchased the 3.3V version of this device.
I am using an Arduino WAN 1310 and a MAX3485 with the NPK sensor and getting 255.
If someone has fixed the 255 error, please could they share the details.
Thanks
I am facing the same problem with getting 255.
I am using a 3.3V version of the NPK sensor with an Arduino WAN 1310 and a MAX3485 transceiver.
Any help would be appreciated, thanks.
hlo sir i had request/question if i could use this sensor with arduino mega
Does JXCT 7 in 1 sensor detects EC and then mathematically converts to nitrogen? How accurate are pH and EC data? Kindly respond.
How does this sensor differentiate between the 3 ions in soil? Normally done via ISFETS or Ion selective electrodes, this just looks like an EC probe? thanks
Dear Sir.
If i have 4 Soil NPK Sensor, how do i read the individual sensor using the Arduino code. Could you please advice?
Ask the seller you bought it from. It should give you the codes for each query.
Did you solve the output? please share the details with me, that will be appreciated
Twitter @HasnaiNabeel
I downloaded the libraries and I copied the code, but for some reason I’m getting a compilation error related to the libraries. Could you add the download link to the file, rather than the github repository link? For some reason, the library isn’t getting called by the code.
Error:In file included from /Users/namanmutalikdesai/Documents/Arduino/NPK_Sensor_Program_2/NPK_Sensor_Program_2.ino:1:0:
/Users/namanmutalikdesai/Documents/Arduino/libraries/Adafruit-GFX-Library-master/Adafruit_GFX.h:12:10: fatal error: Adafruit_I2CDevice.h: No such file or directory
#include
^~~~~~~~~~~~~~~~~~~~~~
compilation terminated.
exit status 1
Error compiling for board Arduino Uno.
I am using Arduino Uno with RS485 NPK sensor. But I am getting 255 for all NPK values not even dipping the sensor inside the soil and when i dip it into the soil same 255 mg/kg is showing. I have seen all the solutions provided for this problem like changing the baud rate, checking the connections, checking if 12V supply is being provided to the NPK sensor but did not work for me. I am unable to figure out the problem. If anyone could come up with a solution ,it would be of great help.
Makes sure the soil is wet.
Did you get solution to your problem as i am facing the same error.
Anyone can help me? I am getting an output
N: 10mg/kg
P: 111mg/kg
K: 48mg/kg
even the NPK sensor is off I am getting this ouput. Someone help me thank you
I followed the code and diagram and I am getting an ouput just like this even the modbus and npk even it’s not plugged in and turned on.
Nitrogen: 10 mg/kg
Phosphorus: 111 mg/kg
Potassium: 48 mg/kg
Someone help me with this problem. Thank you in advance
Those kind of displays are caused by noise on the input lines. If you restart the Arduino you are likely to get different values each time.
Hi
Can someone help me with a system for measuring npk, ph, ec, moisture, temperature in the root of some blueberry plants? The system will consist of 6 sensors that must wirelessly transmit the data measured and visualized on the phone with the help of an application.
Thank you
[email protected]
Hai Mr Alam. What is your tool? If yes can i get your email
Hi, I have used the same code. But it is showing same values for all N=255 mg/kg, P=255 mg/kg, K=255 mg/kg. I am unable to figure out the problem. If anyone could come up with a solution ,it would be of great help.
hi Mr.Alam, im doing the same project with ESP32 but with TTL to RS485 converter not MAX 485 .i should use only RX and TX pin can you help me to do this
Hello did you get done with your final project? Does it have any papers for research?