Led keeps on after statement is reached

Hi, i made a sketct but it doesn't work flawless. In the code i state if x==255 then the led needs to burn, it does that but when the value gets lower again (under 255) then the led stays on. I made sure that the led couldnt get a 255 reading by turning the potentiometer which simulates a sensor al the way down to 0 so there's no posibility it will read 255.

Setup: i have 2 arduino's wired togheter true I2c (master slave) the master has an ethernetshield 2 ontop of it which send out een webserver from the SD card (the html page is on the SD card) which shows the 3 potentiometer values on the webserver. I wired the potentiometers to A0, A1 and A2 the reads are directly sended over I2c to the slave which reads the data and lights a led when a value of 255 is reached (highest read possible).

here is the code of the arduino with the ethernetshield (master)

#include <SPI.h>
#include <Ethernet2.h>
#include <SD.h>
#include <Wire.h>

// size of buffer used to capture HTTP requests
#define REQ_BUF_SZ   50

// MAC address from Ethernet shield sticker under board
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(10, 10, 2, 143); // IP address, may need to change depending on network
EthernetServer server(80);  // create a server at port 80
File webFile;               // the web page file on the SD card
char HTTP_req[REQ_BUF_SZ] = {0}; // buffered HTTP request stored as null terminated string
char req_index = 0;              // index into HTTP_req buffer
  int X = 0;
  int Y = 0;
  int Z = 0;
//const int ss = 53;

void setup()
{
  Wire.begin();

  //pinMode(53, OUTPUT);
  /* disable Ethernet chip
    pinMode(10, OUTPUT);
    digitalWrite(10, HIGH);*/
 
  Serial.begin(9600);       // for debugging

  // initialize SD card
  Serial.println("Initializing SD card...");
  if (!SD.begin(4)) {
    Serial.println("ERROR - SD card initialization failed!");
    return;    // init failed
  }
  Serial.println("SUCCESS - SD card initialized.");
  // check for index.htm file
  if (!SD.exists("index.htm")) {
    Serial.println("ERROR - Can't find the index.htm file!");
    return;  // can't find index file
  }
  Serial.println("SUCCESS - Found index.htm file.");

  Ethernet.begin(mac, ip);  // initialize Ethernet device
  server.begin();           // start to listen for clients
}

void loop()
{
  X = analogRead(A0);
  Wire.beginTransmission(8); // transmit to device #8
  Wire.write("X is ");       
  Wire.write(X/4);             
  Wire.endTransmission();    // stop transmitting
  Serial.println(X);

   Y = analogRead(A1);
  Wire.beginTransmission(8); // transmit to device #8
  Wire.write("Y is ");       
  Wire.write(Y/4);             
  Wire.endTransmission();    // stop transmitting
  Serial.println(Y);

   Z = analogRead(A2);
  Wire.beginTransmission(8); // transmit to device #8
  Wire.write("Z is ");       
  Wire.write(Z/4);             
  Wire.endTransmission();    // stop transmitting
  Serial.println(Z);


                 EthernetClient client = server.available();  // try to get client

  if (client) {  // got client?
  boolean currentLineIsBlank = true;
  while (client.connected()) {
      if (client.available()) {   // client data available to read
        char c = client.read(); // read 1 byte (character) from client
        // buffer first part of HTTP request in HTTP_req array (string)
        // leave last element in array as 0 to null terminate string (REQ_BUF_SZ - 1)
        if (req_index < (REQ_BUF_SZ - 1)) {
          HTTP_req[req_index] = c;          // save HTTP request character
          req_index++;
        }
        // last line of client request is blank and ends with \n
        // respond to client only after last line received
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          // remainder of header follows below, depending on if
          // web page or XML page is requested
          // Ajax request - send XML file
          if (StrContains(HTTP_req, "ajax_inputs")) {
            // send rest of HTTP header
            client.println("Content-Type: text/xml");
            client.println("Connection: keep-alive");
            client.println();
            // send XML file containing input states
            XML_response(client);
          }
          else {  // web page request
            // send rest of HTTP header
            client.println("Content-Type: text/html");
            client.println("Connection: keep-alive");
            client.println();
            // send web page
            webFile = SD.open("index.htm");        // open web page file
            if (webFile) {
              while (webFile.available()) {
                client.write(webFile.read()); // send web page to client
              }
              webFile.close();
            }
          }
          // display received HTTP request on serial port
          Serial.print(HTTP_req);
          // reset buffer index and all buffer elements to 0
          req_index = 0;
          StrClear(HTTP_req, REQ_BUF_SZ);
          break;
        }
        // every line of text received from the client ends with \r\n
        if (c == '\n') {
          // last character on line of received text
          // starting new line with next character read
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          // a text character was received from client
          currentLineIsBlank = false;
        }
      } // end if (client.available())
    } // end while (client.connected())
    delay(1);      // give the web browser time to receive the data
    client.stop(); // close the connection
  } // end if (client)
}

// send the XML file with switch statuses and analog value
void XML_response(EthernetClient cl)
{
  int analog_val1;
  int analog_val2;
  int analog_val3;

  cl.print("<?xml version = \"1.0\" ?>");
  cl.print("<inputs>");
  cl.print("<button1>");
  analog_val1 = analogRead(1);
  cl.print("<analog1>");
  cl.print(analog_val1);
  cl.print("</analog1>");
  cl.print("</button1>");

  cl.print("<button2>");
  analog_val2 = analogRead(2);
  cl.print("<analog2>");
  cl.print(analog_val2);
  cl.print("</analog2>");
  cl.print("</button2>");


  cl.print("<button3>");
  analog_val3 = analogRead(3);
  cl.print("<analog3>");
  cl.print(analog_val3);
  cl.print("</analog3>");
  cl.print("</button3>");
  cl.print("</inputs>");
}

// sets every element of str to 0 (clears array)
void StrClear(char *str, char length)
{
  for (int i = 0; i < length; i++) {
    str[i] = 0;
  }
}

// searches for the string sfind in the string str
// returns 1 if string found
// returns 0 if string not found
char StrContains(char *str, char *sfind)
{
  char found = 0;
  char index = 0;
  char len;

  len = strlen(str);

  if (strlen(sfind) > len) {
    return 0;
  }
  while (index < len) {
    if (str[index] == sfind[found]) {
      found++;
      if (strlen(sfind) == found) {
        return 1;
      }
    }
    else {
      found = 0;
    }
    index++;
  }

  return 0;
}

This is the code for the slave

// Wire Slave Receiver
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Receives data as an I2C/TWI slave device
// Refer to the "Wire Master Writer" example for use with this

// Created 29 March 2006

// This example code is in the public domain.
int LED = 46;

#include <Wire.h>

void setup() {
  Wire.begin(8);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output
pinMode(LED, OUTPUT);
}

void loop() {
  delay(100);

}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
  }
  int x = Wire.read();    // receive byte as an integer
  Serial.println(x);         // print the integer
 if  (x == 255) {

   digitalWrite(LED, HIGH);
   delay(5000);
   return;
}

}

Does anyone have an explanation why the leds keeps burning after it read 255 once? If i pres reset then the led is turned of and i can do another reading, but what i want to do is when it reads 255 from the I2c bus it needs to light up and otherwise turn low again and wait for the next 255 reading. Hope someone could help me with this problem.

Please always do a Tools > Auto Format on your code before posting it. This will make it easier for you to spot bugs and make it easier for us to read. If you're using the Arduino Web Editor you will not have access to this useful tool but it's still unacceptable to post poorly formatted code. I recommend you to use the standard IDE instead.

There's nothing in your code that would ever change the state of the LED pin back to LOW.

pert:
Please always do a Tools > Auto Format on your code before posting it. This will make it easier for you to spot bugs and make it easier for us to read. If you're using the Arduino Web Editor you will not have access to this useful tool but it's still unacceptable to post poorly formatted code. I recommend you to use the standard IDE instead.

There's nothing in your code that would ever change the state of the LED pin back to LOW.

hi, i used the autoformat thingy (ctrl+t)

If im not mistaken in this while loop i made an if statement ''if x==255 then digital.write led,high'' so when the value isn't 255 the led wont light up right, so i asumed the led would turn low again when it loses the 255 value. how would you suggest to do this otherwise?

void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
  }
  int x = Wire.read();    // receive byte as an integer
  Serial.println(x);         // print the integer
  if  (x == 255) {

    digitalWrite(LED, HIGH);
    delay(5000);
    return;
  }

}

If you set a pin HIGH it's going to stay HIGH until you set it LOW. The Arduino won't magically know it's supposed to go LOW if you don't tell it to. It seems like you're trying to run before you learn to crawl. I recommend you to study File > Examples > 01.Basics > Blink and the associated tutorial:

pert:
If you set a pin HIGH it's going to stay HIGH until you set it LOW. The Arduino won't magically know it's supposed to go LOW if you don't tell it to. It seems like you're trying to run before you learn to crawl. I recommend you to study File > Examples > 01.Basics > Blink and the associated tutorial:
https://www.arduino.cc/en/Tutorial/Blink

So beacause i asumed that an if statement will only be executed when the statement is reached, which in my oppinion is not so weird to asume if you just started i cant progress further and need to learn the basics again? I just asumed something wrong if maybe you could just help me with an solution or an tip on how to look at it i could work it out. So do you maybe have an solution on how to solve this or an example so i can see for myself what i did wrong. The sentence ''it seems like you're trying to run before you learn to crawl'' is irrelevant and not nessasary you could've just said you did something wrong here and there you should look there, search the web for ... or that kind of things which would be more usefull for me and other that read this topic.

Hi,
Try this statement.

https://www.arduino.cc/en/Reference/Else

Tom... :slight_smile:

AngelinaNoLee:
i cant progress further and need to learn the basics again?

Clearly you never learned the basics in the first place so yes you do need to take a few steps back before you will be able to progress further in an efficient manner. That's just the way it works. I know the impulse is to just skip over the boring stuff but it will only cause a lot of frustration in the end. You have a lot of complex code running on two different Arduinos but you don't even understand how to blink an LED. The key to success, whether you're a beginner or a pro, is to break a project down into stages and get each part working perfectly before moving on to the next one. You're having trouble turning an LED on and off so you need to write the most minimal code that can do that, get it working, make sure you understand every line of that code before proceeding to add it into your project. Luckily for you a minimal LED blinking sketch was already written for you so part of that process is already done. In the time you've spent arguing about it you could have just done it and been on to the next step in your project.

TomGeorge:
Hi,
Try this statement.

https://www.arduino.cc/en/Reference/Else

Tom... :slight_smile:

I'll try this thanks hope this solves my problem

TomGeorge:
Hi,
Try this statement.

https://www.arduino.cc/en/Reference/Else

Tom... :slight_smile:

Thanks for the link after that I got the statement right. Thanks Tom

This is the working code now.

int LED = 46;

#include <Wire.h>

void setup() {
  Wire.begin(8);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output
  pinMode(LED, OUTPUT);
}

void loop() {
  delay(100);

}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
  }
  int x = Wire.read();    // receive byte as an integer
  Serial.println(x);         // print the integer
  if  (x > 254) {

    digitalWrite(LED, HIGH);
    
    
  }
else
{
  digitalWrite(LED, LOW);
}
}

pert:
Please always do a Tools > Auto Format on your code before posting it. This will make it easier for you to spot bugs and make it easier for us to read. If you're using the Arduino Web Editor you will not have access to this useful tool but it's still unacceptable to post poorly formatted code. I recommend you to use the standard IDE instead.

pert:

... I cant do more auto formatting this is what the compiler does so pls stop posting this its irrelevant.

AngelinaNoLee:
... I cant do more auto formatting

Why not. It takes a fraction of a second to do Ctrl+t. Are you really so lazy?

AngelinaNoLee:
this is what the compiler does

Wrong. You're the one who failed to properly format your code. The compiler has absolutely nothing to do with code formatting.

AngelinaNoLee:
pls stop posting this its irrelevant.

If you want me to stop then just do an auto format on your code before posting it to the forum.

pert:
Why not. It takes a fraction of a second to do Ctrl+t. Are you really so lazy?
Wrong. You're the one who failed to properly format your code. The compiler has absolutely nothing to do with code formatting.
If you want me to stop then just do an auto format on your code before posting it to the forum.

Like i said i did autoformat it using ctrl+t, even in the first post but that aside. If you cant get this after me saying it 3/4 times am i really the dumb one then? cmon man it even states this ''No adjustments required for automatic formatting.'' in the bottom left, so i have no clue were you on about.

If you auto format your code then these lines:

AngelinaNoLee:

else

{
  digitalWrite(LED, LOW);
}
}

Would be properly indented:

  else
  {
    digitalWrite(LED, LOW);
  }
}

pert:
If you auto format your code then these lines:Would be properly indented:

  else

{
    digitalWrite(LED, LOW);
  }
}

I'm done discusing this, i see no benefits in this.

AngelinaNoLee:
I'm done discusing this, i see no benefits in this.

It's OK to admit you were wrong.

AngelinaNoLee:
I'm done discusing this, i see no benefits in this.

pert:
It's OK to admit you were wrong.

pert:
Please always do a Tools > Auto Format on your code before posting it. This will make it easier for you to spot bugs and make it easier for us to read. If you're using the Arduino Web Editor you will not have access to this useful tool but it's still unacceptable to post poorly formatted code. I recommend you to use the standard IDE instead.

AngelinaNoLee:
I'm done discusing this, i see no benefits in this.

He told you the benefits (highlighted in red). Why wouldn't you want to make it as easy as possible for someone to give you free help/advice? C++ is a language that these folks read fluently. It has a structure just like any other language.

And
when
not properly formatted
, it makes it
unnecessarily more difficult
to read.

DangerToMyself:
He told you the benefits (highlighted in red). Why wouldn't you want to make it as easy as possible for someone to give you free help/advice? C++ is a language that these folks read fluently. It has a structure just like any other language.

And
when
not properly formatted
, it makes it
unnecessarily more difficult
to read.

The discusion was about wether or not it was formatted, i formatted it im sure of that (using ctrl+t) and when pressed again the sketch said cant make more autoformat changes so then its autoformatted.