void loop() {
for(int i = 0; i <= 10; i++){
if (digitalRead(i) != true){
s = i;
Serial.println(s);
}
}
delay(50);
}
I want print to serial every pins that are LOW, and if no one of the ten pins are LOW i want to print "S" to serial but only one time. I tried a lot of thing but it doesnt work, I don't want the serial monitor to print something like "S2SS5SSSS..." or "SSSSSSSS..." when I do nothing.
Start by getting rid of the delay(50). That's going to mess up anything else that you might want to do with this code in the future.
void loop() {
static unsigned long lastPrinted;
const unsigned long printInterval = 50; //milliseconds, how often to print
if(millis() - lastPrinted >= printInterval) {
printLowPins();
lastPrinted = millis();
}
//any other code can go here and it gets run very rapidly
}
Now we can take your code above and put it into the printLowPins() function I just imagined. You said that you always want it to print something, just a single 'S' if there's no pins low at all?
void printLowPins() {
bool nothingPrinted= true;
for(int i = 0; i <= 10; i++){
if (digitalRead(i) != true){
Serial.println(i);
nothingPrinted= false;
}
}
if(nothingPrinted) {
Serial.println("S");
}
}
Note: you may want to change .println() to .print() to put it on one line like your example.
That is almost what I want, thank you, but now my problem is that I want to print the "S" and the number of the pin that is set to LOW only one time until the pin is set to HIGH and LOW again. I does not have the good word to explain myself because english is not my native language.
I have ten buttons connected to pin 0 to 10 on my arduino mega (I plan to put more in the future), and I have a C# program that read the serial data sent by the arduino, I want the arduino to send the pin that are LOW as fast as possible (the delay(50) was just to make it slower for me to read), but I dont want the arduino to always send data if possible.
It may be easier to manages this from the c# program but would like to know if there is a way to do it from the arduino
No problem. You want to only show changes from HIGH to LOW?
Then you need to keep an array with the values which were most recently printed.
While you are reading about arrays, think about using an array for the pin numbers too. You will always find that you need different pins and can't actually use pins 0-9 in order. Notably, pins 0 and 1 are used for Serial communication on the Mega.