Variables resting after a loop?


#include "DHT.h"
#define DHTPIN 8
#define DHTTYPE DHT11
int t;
int t2;
DHT dht(DHTPIN, DHTTYPE);
void setup() {
  Serial.begin(9600);
  dht.begin();
}

void loop() {
 int t2 = t;
 int t = dht.readTemperature();
                     if(t != t2)
                     {
                     Serial.print(t);
                     }
                     delay(3000);
                     
}

I want to compare the old temp and the new and only print when its different but for some reason t2 is always zero its like t changes back to 0 after the loop.

Hello

try this

static int t2 = t;

Yes, because that is exactly the way you have it programmed! If you don't want that, make "t" and "t2" global or make them static.
Paul

Try this:

#include "DHT.h"
#define DHTPIN 8
#define DHTTYPE DHT11

int t;
int t2;

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  dht.begin();
}

void loop() {
  t2 = t;
  t = dht.readTemperature();

  if (t != t2) {
    Serial.print(t);
  }

  delay(3000);
}