how to print Serial one time in loop

I am monitoring lamp condition which is on and off buy menually
i use this code for monitoring it work but it print continuous command i want to print it only one if lamp is ON or OFF

int i = 8;
int var;

void setup()
{
Serial.begin(9600);
pinMode(i,INPUT);
}
void loop()
{
var = digitalRead(i);
if ( var == HIGH)
{
Serial.println("ON");
}
else
{
Serial.println("OFF");
}
}

please help me gys

You could use another variable say varPrev and compare var to it each time through loop(). If it changed, print; otherwise don’t. Each time through loop update varPrev with var.

Edit: Check the State Change Detection example.

Hi,
A member already answered you questions but in case you want to try one that I used for the same purpose.

Here it is for you to try.

int i = 8;
int var;
byte toggle = 1 ;

void setup() {
Serial.begin(9600);
pinMode(i, INPUT_PULLUP);
}
void loop() {

var = digitalRead(i);

if (var == toggle ) {
return;
}
else if ( var == 1) {
Serial.println("ON" );
toggle = 1;
}
else if ( var == 0) {
Serial.println("OFF");
toggle = 0;
}
}

thank you sooo much gys i actually got what i want .... :slight_smile: :slight_smile: :slight_smile: