NODEMCU problem, doesn't run code but examples work fine

Hi everyone and thank you for helping me out. I'm having a problem running code on my nodeMCU v1.0. Basically I'm building a smart greenhouse with for a school project and my professor provided the hardware specs. Basically I have a program that runs on an Arduino UNO where i collect data, print them on a screen, manage irrigation, and last, to send the data to the nodeMCU so that with the second program running on it, i can send the data to Thingspeak. The problem is that the nodeMCU seems like not running, If i upload and example code on it, for instance the blink example, it works perfectly fine, but if I put my own code in, that little bih doesn't even go trought setup.

PS:
Sorry for bad english and the comments on the code but im italian :slight_smile:
These are my two separate programs.
this is the nodeMCU one

/*
CODICE PER IL NODEMCU DELLA SERRA
*/

#include <ESP8266WiFi.h>
#include <ThingSpeak.h>


//variabili per la connessione e la trasmissione dati a thingspeak
unsigned long myChannelNumber =;
const char *ssid = "";
const char* password = "";
const char *myWriteAPIKey = "";

//variabili timer
unsigned long lastTime = 0;
unsigned long timerDelay = 30000;

float terreno, temperatura, umidità, co2;
float valori[4];

WiFiClient client;

void setup(){
  //inizio la comunicazione seriale con arduino
  Serial.begin(115200);
  while(!Serial) {
  ;//aspetto che la porta seriale si connetta
  }

  WiFi.mode(WIFI_STA);

  ThingSpeak.begin(client);
}

void loop(){

  if((millis() - lastTime) > timerDelay){

    //conneto/riconnetto ad internet
    if(WiFi.status() != WL_CONNECTED){
      Serial.print("Attempting to connect");
      while(WiFi.status() != WL_CONNECTED){
        WiFi.begin(ssid, password);
        delay(500);
      }
      Serial.println("\nConnected");
    }

    ricevoValori(); //ricevo i valori da arduino e li invio a thingspeak
    for(int i=0; i < 4; i++){
      int x = ThingSpeak.writeField(myChannelNumber, (i+1), valori[i], myWriteAPIKey);

       //controllo se gli ha inviati fr
       if(x == 200){
        Serial.println("Canale aggiornato correttamente");
       }else {
        Serial.println("errore nell' aggiornamento del canale. errore HTTP: " + String(x));
       }
    }

    lastTime = millis();
  }
}

void ricevoValori(){
  //funzione che separa la stringa ricevuta nelle variabili che servono
  String stringaRicevuta; //leggo la stringa ricevuta dal seriale
  
  if(Serial.available() > 0) {
    stringaRicevuta = Serial.read();
  }

  terreno = splitString(stringaRicevuta, ',', 0).toFloat();
  temperatura = splitString(stringaRicevuta, ',', 1).toFloat();
  umidità = splitString(stringaRicevuta, ',', 2).toFloat();
  co2 = splitString(stringaRicevuta, ',', 3).toFloat();

  //assegno i valori all'array secondo l'ordine che segue thingspeak
  valori[0] = temperatura;
  valori[1] = umidità;
  valori[2] = terreno;
  valori[3] = co2;
}

String splitString(String str, char sep, int index)
{
 int found = 0;
 int strIdx[] = { 0, -1 };
 int maxIdx = str.length() - 1;

 for (int i = 0; i <= maxIdx && found <= index; i++)
 {
    if (str.charAt(i) == sep || i == maxIdx)
    {
      found++;
      strIdx[0] = strIdx[1] + 1;
      strIdx[1] = (i == maxIdx) ? i+1 : i;
    }
 }
 return found > index ? str.substring(strIdx[0], strIdx[1]) : "";
}

and this is the one that runs on the UNO:

/*
-----------------------CHIAVI API THINGSPEAK---------------
CHIAVE SCRITTURA ----> 1Z0VG5H3GCZYYHV3
CHIAVE LETTURA ------> ZEXONIXDAWCI7O84

*/


#include <ArduinoJson.h>
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <DHT.h>
#include <SoftwareSerial.h>

//definisco le variabili globali
#define SCREEN_WIDTH 128 
#define SCREEN_HEIGHT 64

#define OLED_RESET     4 // pin reset lcd
#define SCREEN_ADDRESS 0x3C //dal datasheet
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

#define NUMFLAKES     10 // Number of snowflakes in the animation example

#define LOGO_HEIGHT   16
#define LOGO_WIDTH    16 

static const unsigned char PROGMEM logo_bmp[] =
{ 0b00000000, 0b11000000,
  0b00000001, 0b11000000,
  0b00000001, 0b11000000,
  0b00000011, 0b11100000,
  0b11110011, 0b11100000,
  0b11111110, 0b11111000,
  0b01111110, 0b11111111,
  0b00110011, 0b10011111,
  0b00011111, 0b11111100,
  0b00001101, 0b01110000,
  0b00011011, 0b10100000,
  0b00111111, 0b11100000,
  0b00111111, 0b11110000,
  0b01111100, 0b11110000,
  0b01110000, 0b01110000,
  0b00000000, 0b00110000 };


int soilSensor1 = A3;
#define dhtpin 7
#define dhttype DHT11

#define co2AnalogPin A2
#define co2DigitalPin 2
#define co2Zero 140 //valore da sistemare poi, calibrazione da fare a scuola

DHT dht(dhtpin, dhttype);

//variabili rele pompe
int pompa1 = 7;
int pompa2 = 6;
int pompa3 = 5;

//bottone lcd
int bottone = 10;
int contatore = 1; //massimo 4

//timer per l'invio dati ogni 30 secondi
unsigned long previousMillis = 0;
unsigned long interval = 500;

SoftwareSerial espSerial(5, 6); //5=TX 6=RX

void setup(){
  Serial.begin(9600);
  
  pinMode(soilSensor1, INPUT); //set up del sensore umidità terreno

  // controllo che la corrente venga data correttamente
  if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }

  //-------------------------------------------- OLED SETUP -----------------------------

  //buffer del display e logo(imposto nella libreria)
  display.display();
  delay(1000);
  //pulisco il buffer
  display.clearDisplay();
  // disegno un singolo pixel per controllare il display
  display.drawPixel(10, 10, SSD1306_WHITE);
  // uso display.display per far vedere quello disegnato precedentemente
  display.display();
  delay(1000);

  //--------------------DHT----------------
  dht.begin();

  //--------------------CO2----------------
  pinMode(co2AnalogPin, INPUT);

  //---------------ACQUA-------------
  pinMode(pompa1, OUTPUT);
  pinMode(pompa2, OUTPUT);
  pinMode(pompa3, OUTPUT);

  //-----------NODEMCU---------------
  espSerial.begin(115200); //mando su questo canale le informazioni al seriale del NODEMCU

}

void loop(){
  scritturaLCD(SoilSensor(), temperaturaAria(), umiditaAria(), qualitaAria(), valoreBottone());
  irrigazione();

  //con il timer invio i dati al nodeMCU che poi li invierà a thingspeak
  unsigned long currentMillis = millis();

  if(currentMillis - previousMillis > interval){
    previousMillis = currentMillis;
    inviaDati();
  }
}

float SoilSensor(){
  float percentualeTerreno = ( 100 - ( (analogRead(soilSensor1)/1023.00) * 100 ) ); //calcolo percentuale di umidità
  return(percentualeTerreno);
}

float temperaturaAria(){
  float temperatura = dht.readTemperature();
  return temperatura;
}

float umiditaAria(){
  float umidita = dht.readHumidity();
  return umidita;
}

float qualitaAria(){
  int co2now[10];                               //int array for co2 readings
  int co2raw = 0;                               //int for raw value of co2
  int co2comp = 0;                              //int for compensated co2 
  int co2ppm = 0;                               //int for calculated ppm
  int zzz = 0;                                  //int for averaging

  for (int x = 0;x<10;x++){                   //samplpe co2 10x over 2 seconds
    co2now[x]=analogRead(co2AnalogPin);
    delay(200);
  }

  for (int x = 0;x<10;x++){                     //add samples together
    zzz=zzz + co2now[x];
    
  }
  co2raw = zzz/10;                            //divide samples by 10
  co2comp = co2raw - co2Zero;                 //get compensated value
  co2ppm = map(co2comp,0,1023,400,5000);  
  
  return co2ppm;
}

int valoreBottone(){
  int valore = 1;

  //aumento il valore ogni premuta di tasto
  if(digitalRead(bottone) == 1){
    //premo il bottone
    if(valore == 4) {
      valore = 1;
    }else {
      valore += 1;
    }
  }
  
  return valore;
}

void scritturaLCD(float soilReading, float temperatura, float umidita, float co2, int selezione){ // selezione valore del bottone 
  int grafX = 0;
  display.clearDisplay();

  display.setTextSize(1);      // Normal 1:1 pixel scale
  display.setTextColor(SSD1306_WHITE); // Draw white text
  display.setCursor(0, 0);     // Start at top-left corner
  display.cp437(true);         // Use full 256 char 'Code Page 437' font

  switch(selezione) {
    case 1:
      //temperatura dell'aria
      display.setTextSize(2);
      display.setTextColor(WHITE);
      display.setTextColor(0,0);
      display.println("AIR TEMPERATURE");
      display.println("");
      display.print(temperatura);
      display.print(" C");
      grafX = map(temperatura, 0, 40, 0, 127);
      display.fillRect(0, 52, grafX, 10, WHITE);
      break;
      
    case 2:
      //umidità dell aria
      display.setTextSize(2);
      display.setTextColor(WHITE);
      display.setTextColor(0,0);
      display.println("AIR HUMIDITY");
      display.println("");
      display.print(umidita);
      display.print(" %");
      grafX = map(umidita, 0, 100, 0, 127);
      display.fillRect(0, 52, grafX, 10, WHITE);
      break;
      
    case 3:
      //umidità del terreno
      display.setTextSize(2);
      display.setTextColor(WHITE);
      display.setTextColor(0,0);
      display.println("SOIL HUMIDITY");
      display.println("");
      display.print(soilReading);
      display.print(" %");
      grafX = map(soilReading, 0, 100, 0, 127);
      display.fillRect(0, 52, grafX, 10, WHITE);
      break;
      
    case 4:
      //livelli co2
      display.setTextSize(2);
      display.setTextColor(WHITE);
      display.setTextColor(0,0);
      display.println("AIR TEMP");
      display.println("");
      display.print(co2);
      display.print(" C");
      grafX = map(co2, 0, 1000, 0, 127);
      display.fillRect(0, 52, grafX, 10, WHITE);
      break;
  }
  display.display();
}


//---------------FUNZIONE IRRIGAZIONE-----------------
void irrigazione(){
  float terreno = SoilSensor(); // percentuale umidità terreno

  //se l'umidità è minore del 25 bagno tutto
  if(terreno < 25){
    digitalWrite(pompa1, HIGH);
    digitalWrite(pompa2, HIGH);
    digitalWrite(pompa3, HIGH);
    delay(2000); //da sistemare poi dopo che abbiamo visto quanta acqua esce
    digitalWrite(pompa1, LOW);
    digitalWrite(pompa2, LOW);
    digitalWrite(pompa3, LOW);
  }
}


//---------------------INVIO DATI AL NODEMCU-------------------------------
void inviaDati(){
  float terreno, temperatura, umidita;
  int co2;

  //prendo i dati con le funzioni
  terreno = SoilSensor();
  temperatura = temperaturaAria();
  umidita = umiditaAria();
  co2 = qualitaAria();

  //invio i dati secondo questo ordine
  espSerial.println(String(terreno) + "," + String(temperatura) + "," + String(umidita) + "," + String(co2));
}

Your topic was MOVED to its current forum category as it is more suitable than the original

You might use some serial.print statements. Simply stating in setup that you are starting, your sketch name then the name of each function as you enter it. That will help narrow down the problem for you. Posting schematics, not frizzy pictures helps a lot as do links to technical information of each hardware device.

A good schematic will also form part of the documentation for your project

setting the WiFi-mode and then executing a Thingpeak.begin(client) is wayyyy tooo les to make it work
You should look up by qoogling how establishing a connection to ThingSpeak works.
Your code is missing mutliple steps to establish the connection.
Search with the keywords

nodeMCU tutorial send data to ThingSpeak

To find a demo-code that demonstrates it.
best regards Stefan

Thank you. I'll look it up now

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.