Attempting to request NPK and ph data from npkph sensor. using a max485 UART to MODBUS connection. the sensor requires a baud rate of 9600. I believe I'm not using UART correctly and I'm not sure how to fix it. I just get back empty squares and zeros when I try to Serial.read Thank you for the help
#define TINY_GSM_MODEM_SIM7000
#define TINY_GSM_RX_BUFFER 1024 // Set RX buffer to 1Kb
#define SerialAT Serial1
//#define Serial2 Serial2
//include libraries
#include <TinyGsmClient.h>
#include <SPI.h>
#include <SD.h>
#include <Ticker.h>
#include <HTTPClient.h>
//Setting up parameters for RS485
const byte ph[]= {0x01,0x03,0x00,0x06,0x00,0x01,0x64,0x0B};
const byte nit[] = {0x01,0x03,0x00,0x1e,0x00,0x01,0xE4,0x0C};
const byte phos[] = {0x01,0x03,0x00,0x1f,0x00,0x01,0xB5,0xCC};
const byte potass[] = {0x01,0x03,0x00,0x20,0x00,0x01,0x85,0xC0};
byte valph,valnit,valpot,valphos;
byte values[11];
//SoftwareSerial mod(2,3);
#define RE 33
#define DE 32
//GPS variables
String coordinates;
String latstring;
String longstring;
// See all AT commands
#define DUMP_AT_COMMANDS
// set GSM PIN
#define GSM_PIN ""
//GPRS id
const char apn[] = "mobile"; //SET TO YOUR APN
const char gprsUser[] = "";
const char gprsPass[] = "";
const char* server = "maker.ifttt.com";
const char* resource = "/trigger/collect_soildata/with/key/c8zYBqZPlu8ltgaK56M8NRXACzViMFOpdl9Ejy-9Eg4";
const int port = 80;
#ifdef DUMP_AT_COMMANDS // if enabled it requires the streamDebugger lib
#include <StreamDebugger.h>
StreamDebugger debugger(SerialAT, Serial);
TinyGsm modem(debugger);
#else
TinyGsm modem(SerialAT);
#endif
// TinyGSM Client for Internet connection
TinyGsmClient client(modem);
#define uS_TO_S_FACTOR 1000000ULL // Conversion factor for micro seconds to seconds
#define TIME_TO_SLEEP 60 // Time ESP32 will go to sleep (in seconds)
#define UART_BAUD 115200
#define PIN_DTR 25
#define PIN_TX 27
#define PIN_RX 26
#define PWR_PIN 4
#define SD_MISO 2
#define SD_MOSI 15
#define SD_SCLK 14
#define SD_CS 13
#define LED_PIN 12
int counter, lastIndex, numberOfPieces = 24;
String pieces[24], input;
void setup(){
// Set console baud rate
Serial.begin(9600);
//mod.begin(9600);
delay(10);
pinMode(RE, OUTPUT);
pinMode(DE, OUTPUT);
digitalWrite(DE, LOW);
digitalWrite(RE, LOW);
// Set LED OFF
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, HIGH);
pinMode(PWR_PIN, OUTPUT);
digitalWrite(PWR_PIN, HIGH);
delay(300);
digitalWrite(PWR_PIN, LOW);
SPI.begin(SD_SCLK, SD_MISO, SD_MOSI, SD_CS);
if (!SD.begin(SD_CS)) {
Serial.println("SDCard MOUNT FAIL");
} else {
uint32_t cardSize = SD.cardSize() / (1024 * 1024);
String str = "SDCard Size: " + String(cardSize) + "MB";
Serial.println(str);
}
Serial.println("\nWait...");
delay(1000);
SerialAT.begin(UART_BAUD, SERIAL_8N1, PIN_RX, PIN_TX);
// Restart takes quite some time
// To skip it, call init() instead of restart()
Serial.println("Initializing modem...");
if (!modem.restart()) {
Serial.println("Failed to restart modem, attempting to continue without restarting");
}
}
void loop(){
// Restart takes quite some time
// To skip it, call init() instead of restart()
Serial.println("Initializing modem...");
if (!modem.init()) {
Serial.println("Failed to restart modem, attempting to continue without restarting");
}
String name = modem.getModemName();
delay(500);
Serial.println("Modem Name: " + name);
String modemInfo = modem.getModemInfo();
delay(500);
Serial.println("Modem Info: " + modemInfo);
// Unlock your SIM card with a PIN if needed
if ( GSM_PIN && modem.getSimStatus() != 3 ) {
modem.simUnlock(GSM_PIN);
}
modem.sendAT("+CFUN=0 ");
if (modem.waitResponse(10000L) != 1) {
DBG(" +CFUN=0 false ");
}
delay(200);
/*
2 Automatic
13 GSM only
38 LTE only
51 GSM and LTE only
* * * */
String res;
// CHANGE NETWORK MODE, IF NEEDED
res = modem.setNetworkMode(2);
if (res != "1") {
DBG("setNetworkMode false ");
return ;
}
delay(200);
/*
1 CAT-M
2 NB-Iot
3 CAT-M and NB-IoT
* * */
// CHANGE PREFERRED MODE, IF NEEDED
res = modem.setPreferredMode(1);
if (res != "1") {
DBG("setPreferredMode false ");
return ;
}
delay(200);
/*AT+CBANDCFG=<mode>,<band>[,<band>…]
* <mode> "CAT-M" "NB-IOT"
* <band> The value of <band> must is in the band list of getting from AT+CBANDCFG=?
* For example, my SIM card carrier "NB-iot" supports B8. I will configure +CBANDCFG= "Nb-iot ",8
*/
/* modem.sendAT("+CBANDCFG=\"NB-IOT\",8 ");*/
/* if (modem.waitResponse(10000L) != 1) {
DBG(" +CBANDCFG=\"NB-IOT\" ");
}*/
delay(200);
modem.sendAT("+CFUN=1 ");
if (modem.waitResponse(10000L) != 1) {
DBG(" +CFUN=1 false ");
}
delay(200);
SerialAT.println("AT+CGDCONT?");
delay(500);
if (SerialAT.available()) {
input = SerialAT.readString();
for (int i = 0; i < input.length(); i++) {
if (input.substring(i, i + 1) == "\n") {
pieces[counter] = input.substring(lastIndex, i);
lastIndex = i + 1;
counter++;
}
if (i == input.length() - 1) {
pieces[counter] = input.substring(lastIndex, i);
}
}
// Reset for reuse
input = "";
counter = 0;
lastIndex = 0;
for ( int y = 0; y < numberOfPieces; y++) {
for ( int x = 0; x < pieces[y].length(); x++) {
char c = pieces[y][x]; //gets one byte from buffer
if (c == ',') {
if (input.indexOf(": ") >= 0) {
String data = input.substring((input.indexOf(": ") + 1));
if ( data.toInt() > 0 && data.toInt() < 25) {
modem.sendAT("+CGDCONT=" + String(data.toInt()) + ",\"IP\",\"" + String(apn) + "\",\"0.0.0.0\",0,0,0,0");
}
input = "";
break;
}
// Reset for reuse
input = "";
} else {
input += c;
}
}
}
} else {
Serial.println("Failed to get PDP!");
}
Serial.println("\n\n\nWaiting for network...");
if (!modem.waitForNetwork()) {
delay(10000);
return;
}
if (modem.isNetworkConnected()) {
Serial.println("Network connected");
}
//Aquire sensor readings
getph();
getnitrogen();
getphosphorus();
getpotassium();
// --------GPS--------
Serial.println("\n---Starting GPS---\n");
getgps();
Serial.println("\n---End of GPS---\n");
// -------GPRS--------
Serial.println("\n---Starting GPRS TEST---\n");
senddata();
Serial.println("\n---End of GPRS TEST---\n");
// --------TESTING POWER DOWN--------
// Try to power-off (modem may decide to restart automatically)
// To turn off modem completely, please use Reset/Enable pins
modem.sendAT("+CPOWD=1");
if (modem.waitResponse(10000L) != 1) {
DBG("+CPOWD=1");
}
// The following command does the same as the previous lines
modem.poweroff();
Serial.println("Poweroff.");
// GO TO SLEEP
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
delay(200);
esp_deep_sleep_start();
// Do nothing forevermore
while (true) {
modem.maintain();
}
}
void getgps(){
// Set SIM7000G GPIO4 HIGH ,turn on GPS power
// CMD:AT+SGPIO=0,4,1,1
// Only in version 20200415 is there a function to control GPS power
modem.sendAT("+SGPIO=0,4,1,1");
if (modem.waitResponse(10000L) != 1) {
DBG(" SGPIO=0,4,1,1 false ");
}
modem.enableGPS();
float lat, lon;
while (1) {
if (modem.getGPS(&lat, &lon)) {
Serial.printf("lat:%f lon:%f\n", lat, lon);
break;
} else {
Serial.print("getGPS ");
Serial.println(millis());
}
delay(2000);
}
modem.disableGPS();
// Set SIM7000G GPIO4 LOW ,turn off GPS power
// CMD:AT+SGPIO=0,4,1,0
// Only in version 20200415 is there a function to control GPS power
modem.sendAT("+SGPIO=0,4,1,0");
if (modem.waitResponse(10000L) != 1) {
DBG(" SGPIO=0,4,1,0 false ");
}
//prep to send coordinates
latstring = String(lat,7);
longstring = String(lon,7);
if (lat>0){
latstring = "0"+String(lat,7);
}
if (lon>0){
longstring = "0"+String(lon,7);
}
coordinates = latstring;
coordinates.concat(longstring);
}
//Connect to GPRS and send JSON data packet
void senddata(){
Serial.println("Connecting to: " + String(apn));
if (!modem.gprsConnect(apn, gprsUser, gprsPass)) {
delay(10000);
return;
}
Serial.print("GPRS status: ");
if (modem.isGprsConnected()) {
Serial.println("connected");
//Client connection
if (!client.connect(server, port)) {
Serial.println(" fail");
}
else {
Serial.println(" OK");
String jsonObject = String("{\"value1\":\"") + "sfsfarm(1)" + "\",\"value2\":\"" + 905591009088955 + "\",\"value3\":\"" + coordinates + "\"}";
client.println(String("POST ") + resource + " HTTP/1.1");
client.println(String("Host: ") + server);
client.println("Connection: close\r\nContent-Type: application/json");
client.print("Content-Length: ");
client.println(jsonObject.length());
client.println();
client.println(jsonObject);
unsigned long timeout = millis();
while (client.connected() && millis() - timeout < 10000L) {
// Print available data (HTTP response from server)
while (client.available()) {
char c = client.read();
Serial.print(c);
timeout = millis();
}
}
Serial.println();
// Close client and disconnect
client.stop();
Serial.println(F("Server disconnected"));
}
}
else {
Serial.println("not connected");
}
modem.gprsDisconnect();
if (!modem.isGprsConnected()) {
Serial.println("GPRS disconnected");
} else {
Serial.println("GPRS disconnect: Failed.");
}
}
void getph(){
Serial.flush();
digitalWrite(DE,HIGH);
digitalWrite(RE,HIGH);
delay(10);
if(Serial.write(ph,sizeof(ph))==8){
digitalWrite(DE,LOW);
digitalWrite(RE,LOW);
delay(200);
for(byte i=0;i<7;i++){
//Serial.print(mod.read(),HEX);
while(Serial.available()){
values[i] = Serial.read();
}
Serial.print(values[i],HEX);
}
Serial.println();
}
valph = values[4];
Serial.println(valph);
}
void getnitrogen(){
Serial.flush();
digitalWrite(DE,HIGH);
digitalWrite(RE,HIGH);
delay(10);
if(Serial.write(nit,sizeof(nit))==8){
digitalWrite(DE,LOW);
digitalWrite(RE,LOW);
delay(200);
for(byte i=0;i<7;i++){
//Serial.print(mod.read(),HEX);
while(Serial.available()){
values[i] = Serial.read();
}
Serial.print(values[i],HEX);
}
Serial.println();
}
valnit = values[4];
Serial.println(valnit);
}
void getphosphorus(){
Serial.flush();
digitalWrite(DE,HIGH);
digitalWrite(RE,HIGH);
delay(10);
if(Serial.write(phos,sizeof(phos))==8){
digitalWrite(DE,LOW);
digitalWrite(RE,LOW);
delay(200);
for(byte i=0;i<7;i++){
//Serial.print(mod.read(),HEX);
while(Serial.available()){
values[i] = Serial.read();
}
Serial.print(values[i],HEX);
}
Serial.println();
}
valphos = values[4];
Serial.println(valphos);
}
void getpotassium(){
Serial.flush();
digitalWrite(DE,HIGH);
digitalWrite(RE,HIGH);
delay(10);
if(Serial.write(potass,sizeof(potass))==8){
digitalWrite(DE,LOW);
digitalWrite(RE,LOW);
delay(200);
for(byte i=0;i<7;i++){
//Serial.print(mod.read(),HEX);
while(Serial.available()){
values[i] = Serial.read();
}
Serial.print(values[i],HEX);
}
Serial.println();
}
valpot = values[4];
Serial.println(valpot);
}