text:
Controlled power-down for automotive application
I'm working on an automotive project that uses an Arduino Mega 2560.
What I need is a circuit that allows the unit to sense when the external power feed drops (triggering an interrupt?) so that the software can preserve state to the non-volatile memory and then shut down.
I was thinking some sort of capacitor/battery to run it once the eternal feed drops, but the hardware side of things is not my strong skillset - I'm more of a software kinda person.

I have been working with the new 47L16 from Microchip for this kind of thing - save state on power loss. It does it all for you (available in DIP for those that don't like surface mount).

That looks like just what I need! Do you know of any tutorials/examples I can look at for hooking it up the the Mega?

No, I don't know of any. I just worked from the datasheet - it has all you need to know, you just have to understand it.

Consider a battery backup for low power devices.  This article from allaboutcircuits.com discusses how to build a 12 to 5 volt power supply with its own battery backup.
In your specific case, run a second 12 to 5 volt regulated signal to one of the processor's digital inputs.  When the 12 volts shuts off, the signal to the processor's digital input will go low.  Poll this input and when you see it go low shutdown the processor or put the processor into a deep sleep mode to draw as little current as possible from the back up battery.
The ATmega2560 processor may not be the best chose for this. There are processors that can drop down into the nA range and still wake up periodically to check if they should be powered all the way back up.

Thanks, I'll do some experiments with my board to see how long it takes to actually shut down after power is cut.

I found a thread about this.  Unfortunately it discounts the built in ATmega2560 brownout circuit for the reasons I gave above.  If so, I really think the ATmega2560 design is flawed with respect to this feature.

There is also this rather involved thread in the Arduino forums.  At one point someone is talking about re-flashing the Arduino boot loader.

The AVR brownout detector only does the minimum needed: It re-sets the AVR and keeps it in reset while VCC is under a certain level to prevent programs going wild - It's not capable to trigger any safety action in the software.

Oh, wait - in almost all cars there is a power supply from the battery which is not shut down.  This is used for features like car-stereo-theft-prevention and the car-alarms.  You could use this as a power source and use your switched-car-power supply to trigger a controlled shutdown.  But be very very careful about drawing minimal or no current when shut down.  As I doubt there is anything preventing you from draining your car's battery.  (I'll change may answer in light of this.)

I am going to change my answer for the 2nd time. While I feel you are competent, I also feel that answers that could cause problems should not be left up for all time.  Instead I found a battery back up article for low power devices that may be a better fit.

You are right, cars have "live on ignition" and "always live" circuits. But the device I'm building is plug-in (using the car's aux power socket) and so whether this is always live, or live on ignition will depend on the car it's plugged into (most are live on ignition though)


text:
How to send MFRC522 data to a C# app using a NodeMCU TCP server?
I am trying to send MFRC522 data to a C# application through a NodeMCU acting as an access point for the C# app. I have modified the code I got from this site.
#include ESP8266WiFi.h>
#include SPI.h>
#include MFRC522.h>

const char* AP_SSID ="IoT4143" ;
const char* AP_PASSWORD ="iot4143";

#define RST_PIN D3
#define SS_PIN D4

MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

WiFiServer server(80);
WiFiClient client;

void wifiConnect() {
  WiFi.disconnect();
  WiFi.softAP(AP_SSID, AP_PASSWORD);

  int watchDog = 0;
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    watchDog++;
    if(watchDog == 60) {
      WiFi.disconnect();
      WiFi.printDiag(Serial);
      watchDog = 0;
      return;
    }
  }
  server.begin();
}

void setup() {
  Serial.begin(115200);
  SPI.begin();      // Init SPI bus
  mfrc522.PCD_Init();   // Init MFRC522
  mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
  Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
  wifiConnect();
}

void loop() {
  //Are we connected to WiFi?
  if(WiFi.status() != WL_CONNECTED) {
    wifiConnect();
  }

  //Wait for a connection attempt
  client = server.available();
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  int watchDog = 0;
  while(!client.available()) {
    delay(1);
    if(watchDog == 10000) {
      watchDog = 0;
      return;
    }
    watchDog++;
  }
  sendData();
}

void sendData() {
  // Read the first line of the request
  String request = client.readStringUntil('\r');
  client.flush();

  // Match the request
  while(request=="READSTOP") {
    Serial.println("RFID READING STARTED..."); //Forward to C# App
    if (!mfrc522.PICC_IsNewCardPresent()) {
      return;
    }
    // Select one of the cards
    if (!mfrc522.PICC_ReadCardSerial()) {
      return;
    }
    // Dump debug info about the card; PICC_HaltA() is automatically called
    client.print(mfrc522.uid));
  }
  Serial.println("RFID READING STOPPED"); //Stop server
  delay(1);
  client.stop();
}

I am very new to hardware/network programming. I don't know what will be possible errors in this code and whether it will work or not.
When I verified the code in the Arduino IDE, there was an error on this line of code:
client.print(mfrc522.uid));

error:= no matching function for call to 'WiFiClient::print(MFRC522::Uid&)'

When the connect button in the application is clicked the "READSTART" string is sent to NodeMCU and when disconnect is clicked the "READSTOP" string is sent.
Please help!

client.print(mfrc522.uid)); How many opening and closing parentheses do you count in that line? Hmm...?

Sorry it was a typo even after i corrected that i got the same error..

MFRC522::uid is a struct (see source code). There's no defined way to print it.
If you want to write the raw bytes over the TCP connection, you can just use
client.write((uint8_t*)mfrc522.uid.uidByte, mfrc522.uid.size);

If you want to write it as ASCII text, you can use the following:
void byte_to_str(char* buff, uint8_t val) {  // convert an 8-bit byte to a string of 2 hexadecimal characters
  buff[0] = nibble_to_hex(val >> 4);
  buff[1] = nibble_to_hex(val);
}

char nibble_to_hex(uint8_t nibble) {  // convert a 4-bit nibble to a hexadecimal character
  nibble &= 0xF;
  return nibble > 9 ? nibble - 10 + 'A' : nibble + '0';
}

void printHEX(Stream &s, uint8_t *data, size_t length) {
  char *buffer = new char[length*2];
  for (size_t i = 0; i < length; i++) {
    byte_to_str(&buffer[i*2], data[i]);
  }
  s.write(buffer, length*2);
  delete[] buffer;
}

Then use it like this:
  printHEX(client, mfrc522.uid.uidByte, mfrc522.uid.size);

It loops over all bytes in the UID, converts them to ASCII (hexadecimal representation, so 2 characters per byte), and then writes the text over the TCP connection.
(Note that there are many other problems with your code as well, e.g. the includes are missing the opening '<'.)

Thank you @tttapa for your explanation, the includes missing '<' was purposly done other than that what could be the possible errors/problems you are taking abt????

In file included from \libraries\ESP8266WiFi\src/ESP8266WiFi.h:39:0,
             from \typrojectTRY1.ino:1:

src/WiFiClient.h: In instantiation of 'size_t WiFiClient::write(T&, size_t) [with T = unsigned char [10]; size_t = unsigned int]':
\typrojectTRY1.ino:103:53:   required from here
libraries\ESP8266WiFi\src/WiFiClient.h:123:36: error: request for member 'available' in 'source', which is of non-class type 'unsigned char [10]'  (part1/2)

size_t left = source.available();
\libraries\ESP8266WiFi\src/WiFiClient.h:127:5: error: request for member 'read' in 'source', which is of non-class type 'unsigned char [10]'
 source.read(buffer.get(), will_send);

Error compiling for board NodeMCU 1.0 (ESP-12E Module); part(2/2) now i am getting this error seriously i don't what it means i am a c# programmer.

@VenkateshShiga : I updated my answer. You have to cast it to a uint8_t*.

Thank you,i have done compiling there isn't any error...

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Detecting if a push button was pressed and released
I want to detect if a push button was pressed and released again. So I thought the right approach would be to first wait while the pin yields LOW and then wait while the pin yields HIGH:
void push(int pin) {
  // wait until button was pushed down...
  while (digitalRead(pin) == LOW);
  // ... and released again
  while (digitalRead(pin) == HIGH);
}

That function can be easily reused. The code works fine, but I am just wondering if that solution is considered clean and a good practice.

You can ask google how they solve this problem in c with microcontrollers. For the search you can use: button debouncing microcontroller or button state change microcontroller. I think the solution above is only good, when you run this function only one time. In this case the state changes (bouncing) will do nothing. For example if you want to count the presses find another solution.

it only supports one button, so that's kind of weak.

No, I wouldn't consider that good practice - for one good reason: it's blocking.
Your system can't be doing anything else at all while you're waiting on the button. That may be fine for some situations, but far from ideal for 99% of others.
It is better to remember the state of the button and detect that change of state.
Personally, to make it properly portable, I would implement a class to contain all the state information.  Something like:
class Button {
    private:
        bool _state;
        uint8_t _pin;

    public:
        Button(uint8_t pin) : _pin(pin) {}

        void begin() {
            pinMode(_pin, INPUT_PULLUP);
            _state = digitalRead(_pin);
        }

        bool isReleased() {
            bool v = digitalRead(_pin);
            if (v != _state) {
                _state = v;
                if (_state) {
                    return true;
                }
            }
            return false;
        }
};

Then you can do something like:
Button myButton(3);

void setup() {
    myButton.begin();
    Serial.begin(115200);
}

void loop() {
    if (myButton.isReleased()) {
        Serial.println(F("Released"));
    }
}

Every time myButton.isReleased() is called the current button state is compared against the state it was last time it was called. If it's changed then the button must either have been pressed or released. So you remember that change. If it's been released then you return a true, otherwise return a false.
You can now easily have it work with many buttons:
Button myButton(3);
Button myOtherButton(4);

void setup() {
    myButton.begin();
    myOtherButton.begin();
    Serial.begin(115200);
}

void loop() {
    if (myButton.isReleased()) {
        Serial.println(F("Released 1"));
    }
    if (myOtherButton.isReleased()) {
        Serial.println(F("Released 2"));
    }
}

Thank you, the blocking might clearly be an issue, however not in my specific use case (a reaction time game). I didn't use C++ features yet, but for abstracting a state, it's clearly a good idea.

I concur with Majenko, although your code would work, the code is blocking, meaning that your code stops at that point until the button is released again. The remaining code in your loop does not execute until the button is resolved.
A much better method is to check the state of the button in each passing of the loop. If the state changes (ie goes low) you can set a flag. Then when you read that the button is high again and the flag has been set then you execute the appropriate code. For example:
const int buttonPin = 2;     // the number of the pushbutton pin
boolean buttonWasLow = false;         // variable flag for when the pushbutton goes low

void setup() {
    pinMode(buttonPin, INPUT);    // initialize the pushbutton pin as an input:
}

void loop() {
    // read the state of the pushbutton and set a flag if it is low:
    if (digitalRead(buttonPin) == LOW)  {
        buttonWasLow = true;
    }

    // This if statement will only fire on the rising edge of the button input
    if (digitalRead(buttonPin) == HIGH && buttonWasLow)  {
        // reset the button low flag
        buttonWasLow = false;

        // Button event here
    }
}

My favorite way to detect a rising edge of an input is actually much simpler:
void loop() {
    button = digitalRead(buttonPin);

    // If the button is pressed
    if (button && !buttonLast)
    {
        // Button event here
    }

    // Update button flag
    buttonLast = button;
}

user8886193 brings up the very good point about button debounce.

Bouncing is the tendency of any two metal contacts in an electronic device to generate multiple signals as the contacts close or open; debouncing is any kind of hardware device or software that ensures that only a single signal will be acted upon for a single opening or closing of a contact.

I prefer to debounce the pushbutton inputs through hardware by adding a 100nF (or larger) from the input pin to ground. Note that this requires a 10K (or larger) resistance in series with the button circuit in order for the capacitor to charge/discharge.
Alternatively, in software, the most common debounce for beginners is adding a delay such as delay(100);, which would look something like this:
void loop() {
    button = digitalRead(buttonPin);

    // If the button is pressed
    if (button && !buttonLast)
    {
        // Button event here
        delay(100);  // <---- Delay inserted after the button event
    }

    // Update button flag
    buttonLast = button;
}

This has the downside that it is blocking for 100ms while the delay executes. A better method is to debounce without a delay. One of the built in examples demonstrates button debounce. The main loop is shown below:
void loop() {
    // read the state of the switch into a local variable:
    int reading = digitalRead(buttonPin);

    // check to see if you just pressed the button
    // (i.e. the input went from LOW to HIGH), and you've waited long enough
    // since the last press to ignore any noise:

    // If the switch changed, due to noise or pressing:
    if (reading != lastButtonState) {
        // reset the debouncing timer
        lastDebounceTime = millis();
    }

    if ((millis() - lastDebounceTime) > debounceDelay) {
        // whatever the reading is at, it's been there for longer than the debounce
        // delay, so take it as the actual current state:

        // if the button state has changed:
        if (reading != buttonState) {
            buttonState = reading;

            // only toggle the LED if the new button state is HIGH
            if (buttonState == HIGH) {
                ledState = !ledState;
            }
        }
    }

    // set the LED:
    digitalWrite(ledPin, ledState);

    // save the reading. Next time through the loop, it'll be the lastButtonState:
    lastButtonState = reading;
}

I usually put a capacitor next to my push button in order to get a clean up/low signal right away.

@sa_leinad could you comment on why you chose the capacitor value (100nF) you did?

The values come from the RC timing constant t = RC. You want to aim for a few milliseconds to get any reduction in the button switching noise. A good article is from the Embedded with Elliot blog: https://hackaday.com/2015/12/09/embed-with-elliot-debounce-your-noisy-buttons-part-i/

The voltage across the capacitor rises slowly in spite of the bouncing switch, and increasing the component values will make it even slower to reach the logical high. Component values could be changed about until the ideal charge and discharge rates cause a delay that outlasts the bouncing and a stable interval has passed. - Excerpt from Debouncing switches in hardware and software

"I usually put a capacitor next to my push button"
Yep, a 1uF capacitor across the button. No need to fiddle with code. See Nick Gammon's excellent switch tutorial http://www.gammon.com.au/switches that covers all kinds of conceivable situations (high or low, GND or +5V, internal pull-up or pull-down, capacitor debounce or software debounce, etc.)

@sa_leinad Well, the OP (Mr. Bucher) already received a complex answer to a simple problem and accepted it as best answer ; )

@Systembolaget Please still put it as an answer. It will help others who have the same problem as the OP. Plus sometimes a simple and concise answer is more helpful than a long wordy answer (at least to some people).

"I usually put a capacitor next to my push button"

A 1uF capacitor across the button is easy, cheap and means no need to fiddle with debouncing codes. See Nick Gammon's excellent switch tutorial that covers almost any conceivable situation when using switches with Arduinos and clones (high or low, GND or +5V, internal pull-up or pull-down, capacitor debounce or software debounce, etc.). In any case, Nick Gammon has many great explanatory examples on his site and where else he comments online.

+1 for the link to Nick Gammon's tutorial, it is indeed excellent!

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Purpose of USB (FTDI) and ICSP connectors
As an Arduino newbie I am a little bit confused about possible ways of programming and communicating with this device. I have done some research and it seems that:
ICSP is used for programming with a bootloader in MCU.
The USB (FTDI) port is used (mostly) for sending text messages to the PC and programming without a bootloader.
Am I right? How can I detect whether I have a bootloader installed (Uno R3 clone)? Thank you very much!

The ICSP is used for 'bare metal' programming. This what you'd use if you wanted to replace or remove the bootloader, change the clock oscillator settings, or program the device as a bare 328.
The USB port is for communicating with a program running on the Arduino. When it's first booted, the bootloader program checks to see if there's any activity on the serial link from the Arduino host program on a PC. If there is, then it allows downloading of a program from it. If not, it continues on to the last code that was programmed into it.
The easiest way to see whether a bootloader is installed is simply to start it up with the PC host, and see whether it can talk to it.

This is slightly mis-stating things.  "bare metal" programming tends to refer to approaches with little in the way of runtime framework, for example targeting the ATmega not the Arduino APIs, and is something you can do even when using the bootloader to get your code onto the chip.  Rather, the ICSP connector is for chips that haven't been initialized with a bootloader, or need the kinds of fuse or oscillator settings you mention which the bootloader may be unwilling to make.

As for the ability of a PC host to talk with the board, the base of that is really determined by the virtual USB firmware in the other ATmega on the board - there will be a virtual serial device if that exists, even if the main ATmega has been pulled off the board.  To determine if there's a bootloader in the main ATmega, one should use avrdude (likely via the Arduino IDE) to try to upload something - but failure in that could as easily be a wrong baud rate, lack of auto reset, or bad manual reset timing, as a missing bootloader.


text:
Is there GUI to flash a sketch with new variables?
I'm dabbling in a project and would like to add a feature, but I need some help from the community.
My project returns a response from the wunderground api and lights an led based on the temperature in the response. I plan to enclose the circuits and use a single led on the enclosure to display the temperature. I have most of the sketch logic knocked out, but need help with sharing the project.
If I gave this project to someone, they would need to update the sketch to include their wifi name and password, as well as the zip code where they live.
Is there a way I can do this without using the arduino ide? A use case for this would be: the user plugs the arduino into their machine, the gui loads, the user would enter variables, and then the board would get flashed with the new variables.
Is this a pie in the sky proposition, or something that could be implemented?
Thanks for your input.

Without the IDE? Store the variables in eeprom and then flash just the eeprom maybe??

@jsotola thanks for pointing out the typo. Do you have any suggestions or ideas on how to implement a solution?

some kind of a script that generates the necessary eeprom image file and then calls avrdude in order to transfer the image file to arduino's eeprom .... but i would go with the answer from @per1234

what are you using for the wifi module??

if you are using something like an ESP8266, then it is possible that you do not need the arduino at all.

The common way to do this is to build the configuration UI into your program. Then the user has no need to be messing with the firmware.
Since your device has WiFi this can easily be done by serving a configuration web page that is loaded in the browser. But how can you make a connection before the credentials for the WiFi router have been configured? The answer is for the device to serve as an access point (AP). So you connect a computer with WiFi to the device's AP, open the configuration page in the browser on that computer, and then configure the credentials as well as any other configurations you might like.
The configuration parameters are written to EEPROM so that they will be preserved.
In its most simple form there would be a specific IP address that must be opened in the browser but more user friendly is to create a captive portal so that after connecting to the AP any URL opened in the browser will load the configuration page.
Of course all this will increase the memory usage of your program and apparently you are using the Arduino Uno so this is fairly scarce to begin with. You'll need to determine whether there is enough extra memory for it.

I had wondered if having a configuration UI on a web page would be a possible solution. I think your answer should give me enough information to do some research. Thanks.


text:
Connecting multiple clients to a server in Wifi
What is the best method or retrieving information such as temperature from multiple wifi clients with a ESP8266-01 ?
I have one server and five client running with ESP8266.
I have seen post ang Get method. JSON files. client-server transfers.
What is the best method to do that ?
I am reading temperature so I do not need the clients to be all connected at the same time. So reading the client one after another in a loop would be great.
thanks in advance
Ken

This isn't really an Arduino question. A server can only query clients if the clients are maintaining connections to it, so often instead people just have the clients connect and post values.  Or you can keep the connection open and try to reconnect automatically if it breaks - this does sometimes give you the ability to ask, but also costs more server resources per client.  Also look at things like MQTT.

https://github.com/internetofhomethings/ESP8266-MQTT-HTTP-Server

Hi jsotola,  I am not seeing where in your link that multiple clients are called. I was thinking of adding an IP address to each clients and making a GET command to each IP to get the information.

@ken: that's the right track: an http server can be polled at any time, whereas a client must stay connected, which is not ideal. the other option is to have each sensor "phone home" on a schedule, so that the server doesn't need to maintain a client list/routine.

you do not need http for this. use plain socket communication. create a WiFiServer on every 'sensor' and ask from the main esp8266 over WiFiClient object. the WiFiServer creates a WiFiClient object and the Clients can exchange what you want.
snippet from my code:
void loop() {
  WiFiClient client = telnetServer.available();
  if (!client) {
    delay(100);
    return;
  }
  if (client.status() != 4) {
    client.stop();
    delay(1000);
    return;
  }
  while (client.connected()) {
    if (!client.available())
      continue;
    char c = client.read();
    if (c == '\n') {
      long v = s.toInt();
      s = "";
      analogWrite(PWM_PIN, v);
      v = readElSens();
      client.println(v);
    } else {
      s += c;
    }
  }
  delay(100);
}

Hi. I get what you are saying. But how do you go from one sensor to another sensor. All I see in your code and more on the internet ''while (client.connected()) {...''   but I need to identify the client as in client1.connected....client2.connected..  but arduino IDE does not allow me to do that.

code is for the esp with a sensor. in this case the client is the central esp and the servers are the sensor esps

I understand what you are saying concerning client-server. But I dont understand how I make the rotation from the multiple sensors. Each of my 5 sensors are on a ESP8266 chip. I should of mentionned that earlier.

and the WiFi network is created by a router or by the main esp?

add a server to the main esp too and let the sensor esps register to main esp over it

I am logging on to myprovider wifi. I have an arduino web server running wich i have access over the internet with dns and port forwarding.


text:
prgramming arduino led on then off
i want the led to light at the beginning and stays like this for a while then turns off, so i wrote:
int led=13;
void setup() {
  pinMode(led,OUTPUT);
}
void loop() {
    digitalWrite(led,HIGH);
    delay (5000);
    digitalWrite (led,LOW);
}

as i understand it should start with high means on digitalWrite(led,HIGH)...and stays like this for 5000us  delay (5000)  then it should turn off with  digitalWrite (led,LOW).
but why its not working, it starts with off for afew seconds then stays on..what i understand wrong with these simple steps ????

when you reset the arduino it starts to run the code. ... it runs all the code in void setup() only once, then it runs all the code in void loop() and repeats running the code in void loop() over and over until you reset the arduino, or turn it off.   .... if you want the arduino to do something only once then do not put the code in void loop()

Thnx, can you please answer my other question here.  https://arduino.stackexchange.com/questions/47858/arduino-led-flashes-with-one-button-press/48164?noredirect=1#comment95932_48164

It immediately loops, from the digital write low to digital write high. Add a second delay after the low, so that it waits before it loops to the top again.

thnx, can you please explain to me that loop and why it acts like that...as i understand it should end with digitalwrite off... because its the last step at the programm

i added the timer after low..but what happens is a flash..it repeat itself...but i want it so start with on for a definte time then it  ends with off and stays off

The "loop()" will keep repeating itself, turning the led on and off forever.
If you want turn the led on just once, put the commands for turn the led on in "setup()" section:

void setup() {
    pinMode(led,OUTPUT);
    digitalWrite(led,HIGH);
    delay (5000);
    digitalWrite (led,LOW);
}
void loop() {
}
Other method would be add a variable to count how much times the led should light. I copied the following sketch from here

int ledPin =  13;    // LED connected to digital pin 13
int alreadyBlinked = 0;

// The setup() method runs once, when the sketch starts
void setup()   {
pinMode(ledPin, OUTPUT);    // initialize the digital pin as an output:
}

// the loop() method runs over and over again,
// as long as the Arduino has power
void loop()
{
     if(alreadyBlinked == 0)
     {
            digitalWrite(ledPin, HIGH);   // set the LED on
            delay(5000);                  // wait for five seconds
            digitalWrite(ledPin, LOW);    // set the LED off
            alreadyBlinked = 1;
      }
}

When the variable "alreadyBlinked" is set to 1, the led will not turn on again.

thnx , i got it, i just wanted to understand the structure of the program and instructions, now for more understanding of the loop  i put once  void loop(){ digitalWrite(led,HIGH);
digitalWrite(led,LOW);}  and once    high then low, but why on both cases the led always stays on ???

Did you check the variables names? Is the led correctly connected? One pin of the led should be connected to the arduino output, and the other pin to the ground. In the first option, digitalwrite (led,LOW) is the last command, so, the led should stay off after setup. In the second option, digitalWrite(ledPin, LOW) is issued before alreadyBlinked = 1, and, since then, the led will not turn on again. I'll try this sketch tomorrow.

yes, i checked..i got it now

That delay does not do anything but wasting 5 seconds...you need to do like:
void loop() {
    digitalWrite(led,HIGH);
    delay (2500);
    digitalWrite (led,LOW);
    delay (2500);
}

The code runs sequentially...in your code after turning off the led it immediately turns it on again and waits 5 seconds...this is so fat that you do not notice it.

i have applied this but it blinks, it doesnt stop ...i want it to stop after lighting for a few seconds

thnx for the explaining that its so fast so i wont notice

The loop function as its name suggests will happen over and over again. You need to set a flag. e.g. An integer that counts how many time the loop has been executed. Then an if statement to check and operate accordingly


text:
Multiple delays
I have a sketch with multiple functions in it. The 2 main functions in that sketch are get_data and post_data.
Now these functions are called from loop(). The thing is I want these functions to run at different times. Basically I want the get_data function to run once every 4 minutes and the post_data function to run once every hour. How can I achieve that?
As far as I know, you can't run multiple programs together on an Arduino Mega.
P.S: I'm new to Arduino programming.

in loop function ... check time ... if 4 minutes then call get_data ... check time ... if 1 hour then call post_data  .... that's it, the whole loop..... you could also check time for the 1 hour at the end of get_data and call post_data from there

can u tell how can i check time in arduino mega with wiznet w5100 ethernet shield .. I dont know much about arduino since am new to it

google arduino time    .... also this  .... https://www.pjrc.com/teensy/td_libs_TimeAlarms.html

Look at the “Blink Without Delay” Arduino tutorial.

I imagine that you tried to figure out how to do it whit the delay() function (if it's not your case, it is for most Arduino beginners). Well... you can't use delay() in this case (and in most other cases) because it completely blocks the program for a given time (1) (except for interrupts, but i won't treat interrupts here). In general it is better not to use delays, except for very simple programs or in initialisation routines (i.e. in stuff you usually put in setup()).

Since your delays are quite long I imagine that you don't need much precision (i.e. you don't need to be more precise than a millisecond). So you could do like that:
void setup() {}

// Times at which we last called the functions
// (These are global variables, which are in general best avoided)
unsigned long lastGetData = 0;
unsigned long lastPostData = 0;

void loop() {

    //                           min.  sec.  milliseconds
    if(millis() - lastGetData >= 4   * 60  * 1000) {

        lastGetData = millis();
        get_Data();
    }

    //                            min.  sec.  milliseconds
    if(millis() - lastPostData >= 60  * 60  * 1000) {

        lastPostData = millis();
        post_Data();
    }
}

void get_Data() {
    // ...
}

void post_Data() {
    // ...
}

Notes:

millis() returns the time since the startup of the Arduino in millisecond. To get more precision you could also use micros() which returns the same but in microseconds (then you would need to multiply the number in the if condition by 1000).
you can add as much functions as you want whit different execution delays. But you must keep every function as short as possible, i.e. you must not use delay()s, because while executing a function if the time to execute another function comes that function will only be called after the end of the current one.
I used the => sign, and not ==, so that even if the loop doesn't evaluates one if condition in the very milliseconds in which it becomes true it can positively evaluate it some milliseconds later (e.g. after the end of another running function).

I took the liberty to fix a few bugs: the time comparison was backwards, the test was not rollover-safe, and get/post were mixed up.

@EdgarBonet, changed your code so that the run time of get_Data() does not affect the 4 second period (same for post_Data())

@jsotola: 1) If you want the average period to not be affected by the time taken by the code to run, you should just replace lastGetData = millis(); by lastGetData += GET_DATA_PERIOD;. Your proposed edit does not achieve the promised constant period: think for example about the interaction between the getData() code and the postData() timing. 2) When you propose such sort of edit, there is no reason to also change the naming style of the functions.

@EdgarBonet Firs of all, thank you for the first edit!! ;)  ---  About your last comment, wouldn't that interaction also affect a lastGetData += GET_DATA_PERIOD; implementation? In any case I edited according to jsotola's comment because I think it's slightly more consistent and easier for a vary beginner to understand (it's time? first reset timer, then perform action, like you would do with a real life timer) and it increases the precision of the period if getData() and postData() take a variable amount of time to execute.

@EdgarBonet, no offence intended. ... 1) you are absolutely correct. i only changed it to point out that it is something to think about.  ....  2) the OP used that naming style in the question. ...

@jsotola --- 1) I see your point and just accepted your edit (removing some comments which only had sense in the context of your previous comment) --- 2) You'r right, I didn't pay attention to the OP's naming conventions, I just read his question twice before writing my answer... but I'll leave it as it is and I hope we'll not speak about naming conventions again in those comments. ;) --- And thanks for your comment/edit!

With lastGetData += GET_DATA_PERIOD;, you may still have a scheduled action delayed by some other running code, but those delays don't add up. Thus, you get jitter, but no drift.

Well Thank You everyone for the input. I tired the millis() and it worked like a charm

I think you can use timer for it. In microcontroller with c you can use interrupts. You will need one timer and two compare interrupts. In the interrupts you can set different flags.
For example in first interrupt:
....
getSomething = true;
....

For example in second interrupt:
....
postSomething = true;
....

For example in your loop:
....
if(postSomething){
//your code to post something
postSomething = false;
}

if(getSomething){
//your code to get something
getSomething = false;
}

These functions are only called when the timer interrupt is called (the time reached). In the Handler you set the flag (do not execute big code). In loop you can check if a flag is set and execute than the code. I think in Arduino you can do the same.

Using a hardware timer for such slow things adds useless complexity.

If you don't need absolute precision, I've written a timer class that doesn't use an interrupt: TimerAction. Usage to simply subclass the base object, define an action() method in the subclass, construct your subclass defining the time interval to run, and place a call to the object's loop() method in your main loop() function in every sketch.
In your case, you'd create a subclass for each of your get_data and post_data actions. This would require two objects to be constructed, and both of them having their loop() method called in the main loop() function.

If it works in your situation:
void loop() {
  static int n;

  delay(4 * 60000);
  get_data();

  if (n-- == 0) {
    post_data();
    n = 14;
  }
}

You may need to adjust the 14 and post-decrement to fit your needs.


text:
Accessing digital pins from the Atmega 16u2 on the Uno
I'm running a custom firmware on the ATmega16U2 (Switch-Fightstick).
Is it possible to access the digital pins of the UNO from the ATmega16U2?

No, only the ATmega328P has access to the external pins of the Uno. You would need to write code for both the '328P and the '16U2 to communicate the pin values and changes over serial since that is the only channel connecting the MCUs.

that is not entirely true ... four of the pins are available

@jsotola: True, but none of them are the "digital" (i.e. Dn) pins of the Uno.

they are digital pins of the UNO ... use a jumper

There is a 4-pin header JP2 on the board that brings out the following pins from the '16U2
PB4, PB5, PB6, PB7

and the ICSP connector
PB1, PB2, PB3

Thank you for letting me know, although the accepted answer better suits my question. It's a bit of a hassle though that they are filled with solder by default on the UNO...


text:
Unable to upload sketches to Sparkfun Redboard
I have two sparkfun redboards. Neither board will allow a sketch to be uploaded from the Arduino IDE.
I plug in a board and it powers on. In the Arduino software I select Tools->Port->COM4 (the only option) and Tools->Board->Arduino/Genuino Uno. Then compile and upload the Blink example. I get the following errors:
Sketch uses 928 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\andy\AppData\Local\Temp\arduino_build_463875/Blink.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x5f
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x5f

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

I understand that this is a fairly generic error indicating failure to communicate with the board, but I don't know what to do about it. I have various Arduino Unos and Arduino Megas and can upload sketches to them without a problem. Since it seems unlikely that both redboards are faulty (different batch numbers), I suspect a software problem relating to the ftdi-based serial comms used by the redboards.
I'm using Windows 10 x64 with Arduino IDE v1.8.5 and FTDI drivers v2.12.28.0 x64 (all latest). I've also tried another windows 10 machine and a different usb cable, with the same results.
I'd appreciate any suggestions.
Update
I've tried using an ftdi cable to connect to the boards on pins 0 and 1. I get the same error message.
I've also tried running avrdude manually and varying some of the parameters. No luck with that either.

Are you sure it's on COM4?

@Majenko Yes. With the board connected, device manager shows the only serial port as COM4. And COM4 is the only port choice offered by the Arduino IDE.

And without the board connected com4 vanishes?

does your PC make the bum-bum-ding sound when you plug in the board?

@Majenko Yes. When I disconnect the board, COM4 vanishes from the device manager and also Tools->Ports in the Arduino IDE, and the device manager shows no serial ports and Tools->Ports is greyed out.

@dandavis Yes. And a similar but different sound when I disconnect the board.

the programmer name may be incorrect

@jsotola I've gone through the list of programmer ids supported by avrdude but none seem applicable except "arduino". Maybe "arduino-ft232r" might work but I'm not using the ISP and am not sure of the pinouts.

jumper RX and TX (pin 0&1)  .... use the serial monitor in the arduino IDE .... type anything on the keyboard and see if it echoes back .... remove jumper and try again (just to make sure that it no longer echoes)

@jsotola Thanks for the suggestion. I tried the loopback test and I get characters echoed back to me. Removed the jumper and echoing stopped.

I've updated the question. Tried using an ftdi cable to connect to the boards on pins 0 and 1, and also tried running avrdude manually. No luck.


text:
RxCpp on Arduino?
I would like to make use of some sort of event bus on Arduino.
Lately I have been making use Reactive Extensions on a number of different platforms, Android, Angular, iOS, etc, and found them very useful.
I tried to install the library and compile something (just including the headers in the example) and I got the following error.
/home/john/Arduino/libraries/rxcpp/rx-trace.hpp:97:57: error: 'exception_ptr' in namespace 'std' does not name a type
     inline void on_error_enter(const Subscriber&, const std::exception_ptr&) {}
                                                     ^

Before I spend too much time trying to force something that will not work, does anyone know if this will work on Arduino, or of any other event bus library that works well on the platform?

Well, exceptions are disabled, basicaly all c++ libraries aren't available and so on....


text:
Need to set a FAILSAFE in an if else loop
This works but I would like to have a timed failsafe...
If the FLOAT_PIN goes LOW for more than 3 seconds, it will turn SOLENOID_PIN to LOW.
I can't figure out how to incorporate it into my loop. I tried delay() and started playing with millis() but all I keep finding is LED blinking samples...
I'm not very good with C++ - still learning.
const int FLOAT_PIN = 8; // Pin connected to FLOAT switch
const int SOLENOID_PIN = A0; // SOLENOID pin - active-high

void setup() {
  Serial.begin(9600);
  // Since the other end of the FLOAT switch is connected to ground, we need
  // to pull-up the FLOAT switch pin internally.
  pinMode(FLOAT_PIN, INPUT_PULLUP);
  pinMode(SOLENOID_PIN, OUTPUT);
}

void loop() {
  int floatswitch = digitalRead(FLOAT_PIN); // Read the state of the float switch

  if (floatswitch == HIGH) {
    // If the pin reads high, water is OFF.
    Serial.println("Switch closed");
    digitalWrite(SOLENOID_PIN, HIGH); // Turn the SOLENOID on
  } else {
    digitalWrite(SOLENOID_PIN, LOW); // Turn the SOLENOID off
  }
}

use a flag floatFlag.... if floatSwitch == high and floatFlag == false (floatFlag = true; tim = currentTime;) ...... if floatSwitch == low (floatFlag == false) ....... if floatFlag == true and currentTime == tim +3 seconds (turn on valve)

Also asked at: http://forum.arduino.cc/index.php?topic=519688 If you're going to do that then please be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

This is one of those cases when thinking in terms of a finite state
machine makes the programming quite straightforward. Here I would
use three states:

In the OFF state, the switch is LOW and the solenoid is off
in the ON state, the switch is HIGH and the solenoid is on
in the DELAYING state, the switch is LOW, but the program is
keeping the switch HIGH for three seconds.

The possible transitions are:

OFF → ON when the switch goes HIGH
ON → DELAYING when the switch goes LOW
DELAYING → OFF after three second in this state
DELAYING → ON when the switch goes HIGH.

The last transition is meant to ensure that LOW states of the switch
that last less than three seconds do not turn the solenoid off.
And here is a tentative implementation. Keep your constants and your
setup(), and replace your loop() with this:
const uint32_t DELAY_TIME = 3000;  // time to deay the -> off transition

void loop() {
    static enum {OFF, ON, DELAYING} state;
    static uint32_t start_delay;
    int floatswitch = digitalRead(FLOAT_PIN);

    switch (state) {
        case OFF:
            if (floatswitch == HIGH) {
                Serial.println("Switch closed");
                digitalWrite(SOLENOID_PIN, HIGH); // Turn the SOLENOID on
                state = ON;
            }
            break;
        case ON:
            if (floatswitch == LOW) {
                start_delay = millis();
                state = DELAYING;
            }
            break;
        case DELAYING:
            if (floatswitch == HIGH) {
                state = ON;
            }
            else if (millis() - start_delay >= DELAY_TIME) {
                digitalWrite(SOLENOID_PIN, LOW); // Turn the SOLENOID off
                state = OFF;
            }
            break;
    }
}

think its backwards. Worked but backwards, it's preventing it from turning off for 3 seconds, rather then turning off if its on for more then 3 seconds.

no matter what I do it works one way but not the other... not sure what i did wrong.

@MikeS: I can't understand your comment “it's preventing it from turning off for 3 seconds, rather then turning off if its on for more then 3 seconds”. I wrote this answer to match your question as written. If this is not the behavior you expect, please, edit your question with a more explicit description of your expectations.

your example works, but not as intended. Float goes low, turn on solenoid, Float goes high, turns off solenoid but delays 3 seconds once Float is high. The logic about is right, not sure if your states are written correctly. Can it be written outside the loop that Solenoid can only be high for X seconds (no matter the output of the FLOAT?)

@MikeS: This works exactly as intended – as I intended it to work based on my understanding of your question. I assume you didn't read my last comment, so let me repeat: please, update your question and add an explicit and clear description of the behaviour you expect.


text:
LED fade class strobes for unknown reason
Okay, so here is what I'm trying to accomplish:
I have four LEDs, under my fish tank, that I want to fade in and out.  I want each LED to fade at a different rate, start at a different "brightness" with PWM, and get a "new" fade-rate every once in a while.  Ultimately, it'll make the bottom of the fish tank "pulse" in a "natural" way.
The code I'm using to accomplish this can be found in my GIT repo.  There is also a GIF of it "working," there.

Now, here is my problem:
Every once in a while, one of the LEDs (not a specific one) will stop fading and start blinking like a strobe light.  I'm not sure what's causing this blinking, since it seems to happen randomly.
The other three LEDs seem to continue to fade in/out while the "bad" LED is spaz-ing out, and it doesn't seem to be isolated to a specific LED.  It also doesn't seem to affect only one LED at a time, although it's usually only one LED "blinking" and any given time... but I have seen two going at the same time.
It also doesn't seem to be specific to the "high" or "low" PWM levels, either... it can happen at "bright" levels, "dim" levels, or even in the middle of the fading transition.

Here's what I've tried:
I've tried different Arduino boards, and I've taken the LED count down to a single LED.  I've changed variable types from bytes to ints, and back and forth with that tactic.  I've been combing through this sketch all day, and I don't see anything that stands out to me as causing the problem.
So, now I'm turning to you all, hoping that someone will be able to see where I've screwed up my code.
Thank you, in advance!

EDIT:  Since I've been asked for direct posting of my code, instead of just a link to the source code:
Here is the main .ino file:
#include "led_controller.h"

// Set pin numbers for each LED
byte led1 = 3,
           led2 = 6,
           led3 = 9,
           led4 = 11;

void setup(){
    pinMode( led1, OUTPUT );
    pinMode( led2, OUTPUT );
    pinMode( led3, OUTPUT );
    pinMode( led4, OUTPUT );
}

// Initialize our four classes for our four LEDs
LED a( led1 ),
    b( led2 ),
    c( led3 ),
    d( led4 );

void loop(){
    a.ledChange();
    b.ledChange();
    c.ledChange();
    d.ledChange();

    delay( 60 );
}

And the header file with the class:
// Create our custom LED class
class LED{
    private:
        // Set higest and lowest brightnesses for LEDs
        byte highest = 250,
             lowest = 5;
        byte pin, brightness, isNeg; // Random necessary variables
        int change; // Set the inc/decrement rate for the LED
        int checkNeg(); // See if our change rate is negative, or not
        void changeChange(); // Get a new change rate
    public:
        LED( byte led ); // Define our constructor
        void ledChange ();
};

// Define our constructor
LED::LED( byte led ){
    pin = led;
    changeChange();

    // Set the initial LED brightness by random
    brightness = random( lowest, highest );

    // Randomly determine if the LED will start brightening or darkening
    if( random( 1, 2 ) == 1 )
        change *= -1;
}

// Get a new change rate
void LED::changeChange(){
    change = random( 1, 4 );

    if( isNeg )
        change *= -1;
}

int LED::checkNeg(){
    if( change < 0 )
        return 1; // If `change` is negative, return true
    return 0;
}

void LED::ledChange(){
    // Flip LED change value between brightening and darkening
    if( brightness <= lowest || brightness >= highest ){
        change *= -1;

        isNeg = checkNeg(); // Determine if we're brightening/dimming the LEDs

        // A 1-in-25 chance to change the fade-rate
        if( random( 25 ) == 13 )
            changeChange();
    }

    brightness += change; // Adjust the LEDs brightness

    analogWrite( pin, brightness ); // Brighten/darken the LED
}

Sounds like integer wraparound to me.

It sounds like the values you are using for PWM are going outside of the range needed for the fading in and out effect. As part of changing the values, make sure that the value generated for the next setting is within the range for the LED effect that you want to see. I am not sure what library you are using or what PWM settings are being changed or I could be more specific. I am not willing to take the time to peruse your git repository so if you want to update your question with the specific code that generates a new setting, that may be helpful.

I believe I'm staying well between the byte values of 0 and 255.  I am just using the regular Arduino analogWrite() function for PWM.

I added some Serial.print() statements to your code to point out the bug:
This is the modified LED::changeLed() function I used:
void LED::ledChange() {

  /**/Serial.print(brightness);

  // Flip LED change value between brightening and darkening
  if ( brightness <= lowest || brightness >= highest ) {
    change *= -1;

    isNeg = checkNeg(); // Determine if we're brightening/dimming the LEDs

    // A 1-in-25 chance to change the fade-rate
    if ( random (25) == 13 )
      changeChange();

  }

  brightness += change; // Adjust the LEDs brightness

  analogWrite( pin, brightness ); // Brighten/darken the LED

  /**/Serial.print("\t+ ");
  /**/Serial.print(change);
  /**/Serial.print("\t= ");
  /**/Serial.print(brightness);
  /**/Serial.print("\t");
  /**/for (int i = 0; i < (brightness / 5); i++) Serial.print("*");
  /**/Serial.print("\n");
}

I marked the additional lines with /**/.
Here is a piece of the serial monitor output, where the bug occurred.  The columns are organised as follows: brightness before the function changed it + change = brightness at the end of this function. The * lines graphically represent the LED brightness (i.e. the last number); this allowed me to run your sketch without a physical LED, at much higher speed (I deleted the delay(60) in loop()).
183        +    3         =    186  *************************************
186        +    3         =    189  *************************************
189        +    3         =    192  **************************************
192        +    3         =    195  ***************************************
195        +    3         =    198  ***************************************
198        +    3         =    201  ****************************************
201        +    3         =    204  ****************************************
204        +    3         =    207  *****************************************
207        +    3         =    210  ******************************************
210        +    3         =    213  ******************************************
213        +    3         =    216  *******************************************
216        +    3         =    219  *******************************************
219        +    3         =    222  ********************************************
222        +    3         =    225  *********************************************
225        +    3         =    228  *********************************************
228        +    3         =    231  **********************************************
231        +    3         =    234  **********************************************
234        +    3         =    237  ***********************************************
237        +    3         =    240  ************************************************
240        +    3         =    243  ************************************************
243        +    3         =    246  *************************************************
246        +    3         =    249  *************************************************
249        +    3         =    252  ************************************************** #####
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    1         =    252  **************************************************
252        +    -1          =    251  **************************************************
251        +    3         =    254  **************************************************
254        +    -3          =    251  **************************************************
251        +    3         =    254  **************************************************
254        +    -3          =    251  **************************************************
251        +    3         =    254  **************************************************
254        +    -3          =    251  **************************************************
251        +    3         =    254  **************************************************
254        +    -1          =    253  **************************************************
253        +    1         =    254  **************************************************
254        +    -1          =    253  **************************************************
253        +    1         =    254  **************************************************
254        +    -1          =    253  **************************************************
253        +    1         =    254  **************************************************
254        +    -1          =    253  **************************************************
253        +    1         =    254  **************************************************
254        +    -1          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -2          =    253  **************************************************
253        +    2         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    1         =    255  ***************************************************
255        +    -1          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************
254        +    2         =    0
0        +    -2          =    254  **************************************************

The bug begins at the line I marked with ####. I'll try to narrate the events from the point of view of your function, starting from line #### (1):

Is brightness 249 in range? yes -> don't invert sign | add 3 | return
Is brightness 252 in range? no -> invert | change fade rate? yes, new fade rate = ±1 | add -1 (we just inverted the sign) | return
Is brightness 251 in range? no -> invert (here's the bug!) | change fade rate? no | add +1 (ve should subtract, but we just inverted the sign...) | return
It continues like that until a fade rate change occurs, oscillating between 251 and 252. That looks out like a constant brightness.
The fade rate increases and the oscillation values change, maybe approaching 255 (if the smaller value goes below 250 the led will continue to behave properly, but that's not our case).
Another fader rathe change causes the program to make brightness greater than 255 (in our case 254 + 2). And if you add 2 to a one-byte unsigned variable holding a value of 254 you won't get 256 (the variable can't hold that value) but 0. That's something called "integer wraparound", as Majenko pointed out in his comment to your question.

So, that was a long description of a very simple problem.
To solve it you cold for instance prevent the brightness value to be greater than 250 and smaller than 5 adding two lines to your ledChange function:
void LED::ledChange(){
    // Flip LED change value between brightening and darkening
    if( brightness <= lowest || brightness >= highest ){
        change *= -1;

        isNeg = checkNeg(); // Determine if we're brightening/dimming the LEDs

        // A 1-in-25 chance to change the fade-rate
        if( random( 25 ) == 13 )
            changeChange();
    }

    /**/ if(brightness > highest) brightness = highest;
    /**/ else if (brightness < lowest) brightness = lowest;

    brightness += change; // Adjust the LEDs brightness

    analogWrite( pin, brightness ); // Brighten/darken the LED
}

Holy cow!!!  You are absolutely amazing!  I have stepped away from this, because I was just getting frustrated, and could NOT figure it out... but you nailed it on the head!  I wish I could give you more than just a fake internet point.


text:
Problem communicating with ENC28J60
I want to send/receive strings to/from an ENC28J60 via a C# application. I used my own "protocol" to do this. For example I send "" to Arduino and it replies with a string containing temperature values. This method works fine in Serial communication mode, but freezes in Network mode. What am I missing here? Is there a better method to do this? I'm new to socket programming. I'm using UIPEthernet.h by ntruchsess.
My server-side (Arduino) code:

void checkAndReceiveFromTCPClients(){
  size_t size;
  if (EClient = EServer.available()){
    char* strIn;
    if(size = EClient.available() > 0){
      strIn = (char*)malloc(size + 1);
      memset(strIn, 0, size + 1);
      EClient.read(strIn, size);
    }
    strIn[size] = 0;
    String strInput = String(strIn);
    strInput.trim();
    //This replies to client (sends string) with a string (EClient.write(answer)):
    InterpretInputString(strInput);
    //EClient.stop();
    EClient.flush();
  }
}

C# code:
string SendAndReceiveOverNet(string Command) {
    Byte[] data = System.Text.Encoding.ASCII.GetBytes(Command);
    NetworkStream stream = TClient.GetStream();
    stream.Write(data, 0, data.Length);
    data = new Byte[256];
    String responseData = String.Empty;
    Int32 bytes = stream.Read(data, 0, data.Length);
    responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
    return responseData;
}

Something like this is needed here. If you use stream.Read without TClient.Available, the program will freeze or crash.
C# code:
string SendAndReceiveOverNet(string Command) {
    Byte[] data = System.Text.Encoding.ASCII.GetBytes(Command);
    NetworkStream stream = TClient.GetStream();
    stream.Write(data, 0, data.Length);
    String responseData = String.Empty;
    Int32 size = TClient.Available;
    if (size > 0)
    {
        data = new Byte[size];
        Int32 bytes = stream.Read(data, 0, data.Length);
        responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
    }
    return responseData;
}

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Low-power detect rise and fall of input signal
For a very low-power-project (where I want to keep the micro-controller asleep or powerless as much as possible), I need to detect the rising and the falling of an input-signal (which could power-on the controller and send a signal).
I tried sleeping and waking up the controller via an interrupt, but it would be even better to switch of the controller completely and just power up when there is a change in input signal (only a few times a day, with a signal length of several minutes).
Making the controller powerless (and processing all there is to be done in the setup before switching off again) is a better solution than the deep sleep solution, because of the low frequency of occurence of the input signal changes.

The output does not have to be exactly 30 seconds, it can be any other value. It could use a power latch.
I looked at monostable circuits but they only detect (generate a pulse) on rising.
Does anyone have a solution (which only costs a few uAmps) for this?
Thanks.
Addendum:
Voltage is 3.3V, current is "as low as possible" because this circuit should work as long as possible on a few cells. The input signal is generated by a mercury switch mounted on a bridge (which can be opened and closed)...
Instead of waking up from deep sleep (and being able to calculate the number of hours the circuit can last on an small battery) it is far better to power off "completely" and being able to calculate the number of activations from the bridge-movement (as long as the electronics I am looking for consume less than the deep sleep). Power consumption by the micro-controller+circuits is in deep sleep >10mA (too much for battery).

Powerless or deep sleep may not make a sizable difference. Anything below 1 µA is less than the self-discharge of the battery. I have an ATmega running since 2012 off the same pair of AA cells, sleeping most of the time.

what generates the input signal? what is the voltage and available current, if any?

What board are you using? 10mA is quite a lot.

You can generate a pulse on any edge of a signal using some logic gates. For instance combining a rising edge detector with a falling edge detector and adding a time delay would probably achieve what you want:

simulate this circuit – Schematic created using CircuitLab
Simulate it here.
The length of time the pulse is on for is (roughly) defined by the time constant of R1 and C1.  That's T=RC, so in this instance 100 x 0.0000001 =  10uS.
for a time of (say) 30 seconds, you will want to massively increase those values. For example, 470uF and 80K would give you around 32 seconds.
Power consumption? Well, that's all dependent on the logic gates and how you build the circuit.  74HC chips are pretty efficient now (far better than the old 74LS ones), but you will want to reduce it down to as few chips and gates as possible. That means converting the circuit to just one gate type (for example NAND) and reducing redundancy in the circuit to minimise power consumption.

You can replace all the gates by a single XOR between the current and the delayed input.


text:
4-digit 7-segment display resets when common pin set to HIGH
I'm trying to make a simple stopwatch application with my Arduino Mega 2560 and a 4-digit 7-segment display, but the leftmost three digits only light up for a split second before they go out every time the counter increments up. The rightmost digit is counting normally.
After going back to basics to diagnose the problem, I've discovered that every time one of the common pins is set back to high so I can pick another digit to manipulate, the digit goes blank.
Code for my basic program, which should display "0123" on my display.
int A = 2;
int B = 3;
int C = 4;
int D = 5;
int E = 6;
int f = 7;
int G = 8;
int P = 9;

int D4 = 10;
int D3 = 11;
int D2 = 12;
int D1 = 13;

void setup() {
  pinMode(A, OUTPUT);
  pinMode(B, OUTPUT);
  pinMode(C, OUTPUT);
  pinMode(D, OUTPUT);
  pinMode(E, OUTPUT);
  pinMode(f, OUTPUT);
  pinMode(G, OUTPUT);
  pinMode(P, OUTPUT);
  pinMode(D1, OUTPUT);
  pinMode(D2, OUTPUT);
  pinMode(D3, OUTPUT);
  pinMode(D4, OUTPUT);

  digitalWrite(D1, LOW);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, HIGH);
  delay(5);

  //0
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, HIGH);
  digitalWrite(E, HIGH);
  digitalWrite(f, HIGH);
  digitalWrite(G, LOW);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, LOW);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, HIGH);
  delay(5);

  //1
  digitalWrite(A, LOW);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, LOW);
  digitalWrite(E, LOW);
  digitalWrite(f, LOW);
  digitalWrite(G, LOW);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, LOW);
  digitalWrite(D4, HIGH);
  delay(5);

  //2
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, LOW);
  digitalWrite(D, HIGH);
  digitalWrite(E, HIGH);
  digitalWrite(f, LOW);
  digitalWrite(G, HIGH);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, LOW);
  delay(5);

  //3
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, HIGH);
  digitalWrite(E, LOW);
  digitalWrite(f, LOW);
  digitalWrite(G, HIGH);

}

void loop() {
}

But all the display shows is a 3 on the rightmost digit. I followed the video in this guide and hooked my Mega up the same way. Is this still the right way to code a 4 digit display to make all the digits display different numbers, or is this normal behavior?

These 4-digit LED displays use multiplexing which means that (to keep the pin count down) you only display each digit for a brief time. Because of the eye's persistence of vision, if you repeatedly display the 4 digits they all appear to be lit up.
I have a video that illustrates this effect with a LED sign. There are a lot more than 4 digits, but the video gradually shows what happens if the delay between each digit is reduced. Watch it through to the end or you won't get the effect. It is about 45 seconds long.
In your case, as jsotola suggested in their answer, if you move the code which displays the digits out of setup and into loop then the code is done repeatedly, which means that the digits are now displayed repeatedly, and you should see all of them.
Since, in your original code, you had the display code in setup then it was done once, and the final digit was the only one you saw.

This should work (sort of). It will be flickery, but it should give you a starting place to work from.
int A = 2;
int B = 3;
int C = 4;
int D = 5;
int E = 6;
int f = 7;
int G = 8;
int P = 9;

int D4 = 10;
int D3 = 11;
int D2 = 12;
int D1 = 13;

void setup() {

  // put your setup code here, to run once:
  pinMode(A, OUTPUT);
  pinMode(B, OUTPUT);
  pinMode(C, OUTPUT);
  pinMode(D, OUTPUT);
  pinMode(E, OUTPUT);
  pinMode(f, OUTPUT);
  pinMode(G, OUTPUT);
  pinMode(P, OUTPUT);
  pinMode(D1, OUTPUT);
  pinMode(D2, OUTPUT);
  pinMode(D3, OUTPUT);
  pinMode(D4, OUTPUT);

}

void loop() {
  // put your main code here, to run repeatedly:

  digitalWrite(D1, LOW);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, HIGH);

  //0
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, HIGH);
  digitalWrite(E, HIGH);
  digitalWrite(f, HIGH);
  digitalWrite(G, LOW);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, LOW);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, HIGH);

  //1
  digitalWrite(A, LOW);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, LOW);
  digitalWrite(E, LOW);
  digitalWrite(f, LOW);
  digitalWrite(G, LOW);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, LOW);
  digitalWrite(D4, HIGH);

  //2
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, LOW);
  digitalWrite(D, HIGH);
  digitalWrite(E, HIGH);
  digitalWrite(f, LOW);
  digitalWrite(G, HIGH);

  digitalWrite(D1, HIGH);
  digitalWrite(D2, HIGH);
  digitalWrite(D3, HIGH);
  digitalWrite(D4, LOW);

  //3
  digitalWrite(A, HIGH);
  digitalWrite(B, HIGH);
  digitalWrite(C, HIGH);
  digitalWrite(D, HIGH);
  digitalWrite(E, LOW);
  digitalWrite(f, LOW);
  digitalWrite(G, HIGH);
}


text:
Using millis() to toggle an LED every 500 milliseconds
I thought the code below would toggle an LED every 500 milliseconds. But it does not work. I'm not able to catch the mistake, which must be very silly.
void setup() {
  pinMode(3, OUTPUT);
}

void loop() {
  unsigned long cnt=millis();
  if(!(cnt % 500)) {
    PORTD^= (1<<PD3);
  }
}

Anyhow the code below works. But why not the previous code?
void loop() {
  static unsigned long prev=0;
  // Note: First time case is not handled. As soon as we want to toggle,
  // we must store millis() in prev. In this case this happens after reset and may not be an issue.
  unsigned long current = millis();
  if((unsigned long)(current - prev) >= 500) {
    PORTD^= (1<<PD3);
    prev = current;
  }
}

A further problem with the first example, not yet mentioned, is that the if() logic is reversed. if( !(cnt % 500) ) is equivalent to if( (cnt % 500) != 0 ), which is true for 499 values and false for only one. The "!" creates the opposite effect to what was wanted.

if (!(millis() % 500)) ...

There are two issues with this. The first, and most obvious, is that the
condition will be true for a full millisecond. During that millisecond
you will be toggling the LED on and off very fast. Whether you end up
doing an odd or even number of toggles is anyone's guess.
The second and less obvious problem is that millis() skips some
values. Roughly one integer every 42 is skipped over. This is because
the millis() counter is incremented once every 1024 µs, getting
24 µs late on each increment. Once all those delays add up to a
full millisecond, millis() catches up by incrementing the counter by
two milliseconds instead of one. This is why you should never condition
something on millis() having one specific value.
The almost correct solution to this problem is shown in Juraj's answer:

if (millis() > next) ...

This is not quite correct because it fails each time millis() rolls
over back to zero. The correct solution is
static unsigned long last;
if (millis() - last >= 500) {
    last += 500;
    ...
}

Because the subtraction follows the rules of modular arithmetic, this is
guaranteed to work across the rollover events.

the overrun is after 49 days. if the sketch has restart scheduled every day the the subtraction is unnecessary

@Juraj: Scheduling restarts is a very contrived way of avoiding the rollover “issue”, which is a non-issue to start with if you do the arithmetic properly.

if it has scheduled restart for other reasons

@Juraj Then when those restarts stop... suddenly you have an unexpected, bizarre situation.

You're in good company with scheduled reboots! https://www.theguardian.com/business/2015/may/01/us-aviation-authority-boeing-787-dreamliner-bug-could-cause-loss-of-control And if you forget it's just a trivial complete electric shutdown of Boeing’s 787 and [potential] “loss of control” of the aircraft.

And don't forget, this is the same crowd that asks people to put timers on their routers so they reboot once a month.

initialize variable last

@Juraj: It's static, therefore it's initialized by the rules of the language. You can add = 0 if you don't trust the language, or = -500 if you want the first iteration to start right away, or even = millis() - 500 if your setup() takes an insanely long time.

Your timing doesn't work, because it has a low probability to read a millisecond that is an exact multiple of 500.
Do it this way:
  static unsigned long next = millis();
  if (millis() - next > 500) {
    next += 500;

void loop() {
  unsigned long cnt=millis();
  if(!(cnt % 500)) {
    PORTD^= (1<<PD3);
  }
}

At every iteration, cnt is set with the number of milliseconds elapsed since you turned on the Arduino... So this is not gonna work. At all. What you need is two variables. One that holds the last millis() count when you blinked the LED, and for the current millis() count:
unsigned long lastCount;
void setup() {
  pinMode(3, OUTPUT);
  lastCount=millis();
}

void loop() {
  unsigned long cnt=millis();
  if((cnt-lastCount)>499) {
    PORTD^= (1<<PD3);
    lastCount=cnt;
  }
}

I always use this
if((millis()/500)%2==0))
{
    PORTD |= (1<<PD3);
}
else
{
    PORTD &= ~(1<<PD3);
}

It first divides millis by 500ms. So you get the number of 500ms chucks (since the Arduino started). Then you check to see if this number is even. If so, turn the led pin on. Else turn the led pin off.

Division is a computationally expensive operation on most embedded micros.  You should avoid it if possible.


text:
for loop running infinitely
void writereg() {
  digitalWrite(latchPin, LOW);
  for (int i = 7; i >= 0; i--) {
    digitalWrite(clockPin, LOW);
    Serial.print("wswitch&&&&&&");
    Serial.print(i);
    Serial.print("----------------------");
    digitalWrite(dataPin, switches[i].stat);
    Serial.println(switches[i].stat);
    digitalWrite(clockPin, HIGH);
  }
  digitalWrite(latchPin, HIGH);
  touched = false;
}

I don't understand what's wrong with what I'm doing here, but this for loop runs into an almost infinite loop and prints crazily. I'm a newbie to electronics and Arduino and I don't understand what's wrong here. Please help.
This is my switch class:
struct Swtch
{
  int num;
  bool stat;
  bool touched;
};

Swtch switches[8] = {{1, 0, 0}, {2, 0, 0}, {3, 0, 0}, {4, 0, 0}, {5, 0, 0}, {6, 0, 0}, {7, 0, 0}, {8, 0, 0}};

From the output, it looks like i is not an int but a byte (or unsigned char  or uint8_t). In this case, what you observe is normal because an unsigned is always positive, hence the loop never ends. Are you sure the output posted here matches the code in your question?

Yes. Its the same code that produces this output. i is an int only and not a byte.

Could you show how switches was declared (and details of the underlying type)?

i have edited the question. Please see and let me know if it can solve the issue im facing.

Thanks, unfortunately, that did not show any potential issue of memory overwriting (which is what I thought of when I asked you to add this code). Sorry to insist, but I am really surprised that i is an int. Just in case, do you have special compilation options?

As a test, could you replace your loop with for (int i = 0; i <= 7; i++) and inside the loop body, replace i everywhere with 7 - i ? That would not explain the behavior you get, but that should fix your problem.

Im not sure about this. I was not facing this issue when I was working with Arduino Uno. I have compiled this code to a Atmega328p now and this causes the issue. The code was working properly in Uno.

Let us continue this discussion in chat.

After a chat with OP, it turned out this was a more complex issue, probably a memory overrun.
This cannot be seen in this small snippet, but the whole program is using memory extensively (global variables and dynamic memory heap allocation).
Heavy use of String variables is a likely explanation for the observed behavior.
Also a lot of string literals are putting more pressure on memory in the OP program.
Here are my suggestions:

Replace all "..." string literals with flash-stored strings with F("..."). That will reduce the initial SRAM size used.
Replace all String variables with pure C-string (char* and char arrays) and use standard C string functions such as strcpy, strcat, strlen, strcmp, strchr... This forces to pre-allocate string to their maximum size, but this can be controlled at compile-time (for string variables defined as global). For this point, I also suggest to read a good tutorial on strings in C language.
Use const whenever possible (instead of variables that waste memory)
Use the smallest type needed for each variable, e.g. avoid int (2 bytes) when you need to store a boolean value, prefer bool type (only one byte) or even use 1 byte to store 8 boolean values and use boolean logic to manipulate each value.

Thanks and i would make all the changes that you suggested. Thanks a lot!

Like jfpoilpret said, it looks like i is being treated as an unsigned char or uint8_t causing it to never go below zero. Instead it wraps around to 255, the max value of an 8-bit unsigned integer, as you can see in line 9 of your output. The condition to remain in the loop is i >= 0 which means the loop will never exit. A solution is to add a case for if i is above the starting value:
for (int i = 7; i >= 0 && i <= 7; i--) {

I would recommend finding out why int is being treated as uint8_t for any future projects

I tried this too. But it didnt work.

I have noticed that you have incorrectly declared the switches array.
Your code:
struct Swtch
{
  int num;
  bool stat;
  bool touched;
};

Swtch switches[8] = {{1, 0, 0}, {2, 0, 0}, {3, 0, 0}, {4, 0, 0}, {5, 0, 0}, {6, 0, 0}, {7, 0, 0}, {8, 0, 0}};

It should be:
struct Swtch
{
  int num;
  bool stat;
  bool touched;
};

struct Swtch switches[8] = {{1, 0, 0}, {2, 0, 0}, {3, 0, 0}, {4, 0, 0}, {5, 0, 0}, {6, 0, 0}, {7, 0, 0}, {8, 0, 0}};

Alternatively, you could make a typedef struct:
typedef struct
{
  int num;
  bool stat;
  bool touched;
}Swtch;

Swtch switches[8] = {{1, 0, 0}, {2, 0, 0}, {3, 0, 0}, {4, 0, 0}, {5, 0, 0}, {6, 0, 0}, {7, 0, 0}, {8, 0, 0}};

References:
https://stackoverflow.com/a/32185804/6075112
https://overiq.com/c-programming/101/array-of-structures-in-c/#initializing-array-of-structures
https://stackoverflow.com/a/3275389/6075112

This would be true for C,  not for C++, and I do not know in what language the code in the question is.

The Arduino development tools by default use C++.

Isn't the typedef the best practice?

@sa_leinad: No. In C++, it's generally considered quite ugly, as there's no good reason for it. (C++ lets you treat user-defined type names like built-in type names in nearly all cases.)

Thanks all for your comments. I have learnt something today!


text:
Are there documented Arduino class or file name restrictions?
I ran into a strange problem were the compiler could not find a header file that I knew existed.
The problem was I created a class called ArduinoEvent and put it in ArduinoEvent.hpp,  but when I tried to include it in a client file, the compiler complained that the file did not exist.
In file included from sketch/NetworkConnection.hpp:4:0,
                 from /home/john/development/arduino/esp_pump_monitor/app.ino:4:
sketch/MyEvent.h:5:28: fatal error: ArduinoEvent.hpp: No such file or directory
 #include "ArduinoEvent.hpp"
                            ^

After realizing that the compiler copies the files into another directory,  I took a look and found that it had copied the ArduinoEvent.hpp file to
ArduinoEvent.hpp.cpp.  Since all the other files were copied fine, I simply renamed the file to BrduinoEvent.hpp and then everything was fine.
After searching I could not find anything that would imply that I could not name a class / file ArduinoBlah, so I was going to open an issue, but wanted to see if this restriction was documented somewhere and I just could not find it.
Update
I originally assumed the problem was due to the file being called ArduinoXxxx, but I hit this again with another file.  I think the issue is related to the files being in the "top" folder.  I noticed the process copies the xxx.ino files to xxx.ino.cpp,  so I think that's what is happening and somehow it thinks various files are .ino files while they are not.  As a workaround I moved all my class files to a lib folder and include them from there #include "./lib/xxx.hpp" for example.  This seems to be working.

A partial answer may be found at: https://github.com/arduino/Arduino/wiki/Build-Process

Try renaming *.hpp → *.h.

same thing happens,  but if I use the name .cpp or even include an empty .cpp file it seems ok


text:
DAC using Arduino Leonardo
I am as new to Arduino as it can get. To start off, I am trying to build a DAC using an Arduino Leonardo. I have a digital signal coming from my dual differential comparator. I want to convert this to an analog signal.
First, I will read the digital signal in a digital pin (can someone point me which is good? There are so many of them. I was overwhelmed). Then I send out a PWM signal (confused with the pin again). Then I use a simple RC circuit to filter out the PWM signal to produce a simple sine wave.
Am I going towards the correct direction? If not, please any suggestion would be helpful.

Which dual differential comparator you are using. It would be great if you could add your circuit and any details of what you have tried and what didn't work.

A dual differential comparator is a type of comparator which gives digital signal as output

@sa_leinad LM2903

please describe the signals at the comparator inputs and how they relate to the final analog output

@sa_leinad: please check the edited picture. I have added my circuit diagram. I have a hall sensor which varies its output voltage with respect to the magnetic field. This output is connected to the Comparator. which outputs a digital signal.

How did you come to this circuit? I don't think see how the 100k feedback resistor is doing anything.

You want to convert the input into a sine wave? It's pretty simple to filter a PWM signal into a varying voltage, but getting a variable sine wave out of it might be asking too much. Are you looking to vary the frequency of the output wave with the input, the amplitude, or both? And what frequency of sine wave are you hoping to generate?

Yes you are going in the right direction.
Comparators
You haven't as yet detailed how you plan to connect the 2 comparators to the Arduino, but I imagine it would be something similar to this:

simulate this circuit – Schematic created using CircuitLab
In the circuit above, X and Y are either high or low based on the analog voltages of A, B, C & D. I have created a truth table below with some arbitrary voltages to output. The value column corresponds to the value needed for the analogWrite() function.

Note: If you need your analog output to be able to source some current you can add an Op-Amp in a unity gain configuration at the output of the RC filter.

Examples To Read
To output the analog value, the 4 best suited inbuilt examples/tutorials to look at are:
Dimmer: Send serial values to change the brightness of an LED.
Fading: Use an analog output (PWM pin) to fade an LED.
Analog In Out Serial: Read an analog input pin, map the result, and then use that data to dim or brighten an LED.
Read ASCII String: Parse a comma-separated string of integers to fade an LED.
What all of these examples have in common is the analogWrite() function:
// writes the analog value (range from 0 to 255):
analogWrite(pin, value);

Dimmer is a simple example where a serial value is read and then output on one of the PWM pins.
Fading is probably the most basic example of using the analogWrite() function (PWM output).
I included Analog In Out Serial as it uses the map() command.
I included Read ASCII String as it shows how to parse multiple values on the serial string.

PWM Pins
You can use pins 3, 5, 6, 9, 10, 11, and 13 on the Arduino Leonardo to output the PWM using the analogWrite() function.

Control
I recommend the following tutorials for your control. You could either use the if-else command or the switch-case command.

Thanks for your detailed reply. But I have only 1 comparator, how do I modify this to my need?

What analog voltages do you need? (One for your LOW signal and one for your HIGH). What you have tried and what didn't work?