text:
Attiny85 with arduino as ISP
After serveral attempts, I can't make my arduino UNO to program an attiny85, no matter what I do. I've tried under windows 7 and also under ubuntu 14.04, to no avail. I've followed instructions on hi low tech site and similar ones on arduino site. Even some youtube video. Nothing. The wiring of my arduino is as described in those sites, so it should be correct. I'm using the 10uF capacitor too.
This is the output running avrdude manually, extra verbose:
    zop@mikasa:~$ sudo /usr/share/arduino/hardware/tools/avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf  -q -pattiny85 -cstk500v1 -P/dev/ttyACM0 -b19200 -Uflash:w:/tmp/build2861466093518309047.tmp/Fade.cpp.hex:i -v -v -v -v -v -v -v -v

    avrdude: Version 6.0.1, compiled on Oct 21 2013 at 15:55:32
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "/usr/share/arduino/hardware/tools/avrdude.conf"
             User configuration file is "/home/zop/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : /dev/ttyACM0
             Using Programmer              : stk500v1
             Overriding Baud Rate          : 19200
    avrdude: Send: 0 [30]   [20]
    avrdude: Send: 0 [30]   [20]
    avrdude: Send: 0 [30]   [20]
    avrdude: Send: 0 [30]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [10]
             AVR Part                      : ATtiny85
             Chip Erase delay              : 4500 us
             PAGEL                         : P00
             BS2                           : P00
             RESET disposition             : possible i/o
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65     6     4    0 no        512    4      0  4000  4500 0xff 0xff
                 Memory Ops:
                   Oeration     Inst Bit  Bit Type  Bitno  Value
                   -----------  --------  --------  -----  -----
                   READ               31     VALUE      7      1
                                      30     VALUE      6      0
                                      29     VALUE      5      1
                                      28     VALUE      4      0
                                      27     VALUE      3      0
                                      26     VALUE      2      0
                                      25     VALUE      1      0
                                      24     VALUE      0      0
                                      23     VALUE      7      0
                                      22     VALUE      6      0
                                      21     VALUE      5      0
                                      20    IGNORE      4      0
                                      19    IGNORE      3      0
                                      18    IGNORE      2      0
                                      17    IGNORE      1      0
                                      16   ADDRESS      8      0
                                      15   ADDRESS      7      0
                                      14   ADDRESS      6      0
                                      13   ADDRESS      5      0
                                      12   ADDRESS      4      0
                                      11   ADDRESS      3      0
                                      10   ADDRESS      2      0
                                       9   ADDRESS      1      0
                                       8   ADDRESS      0      0
                                       7    OUTPUT      7      0
                                       6    OUTPUT      6      0
                                       5    OUTPUT      5      0
                                       4    OUTPUT      4      0
                                       3    OUTPUT      3      0
                                       2    OUTPUT      2      0
                                       1    OUTPUT      1      0
                                       0    OUTPUT      0      0
                   WRITE              31     VALUE      7      1
                                      30     VALUE      6      1
                                      29     VALUE      5      0
                                      28     VALUE      4      0
                                      27     VALUE      3      0
                                      26     VALUE      2      0
                                      25     VALUE      1      0
                                      24     VALUE      0      0
                                      23     VALUE      7      0
                                      22     VALUE      6      0
                                      21     VALUE      5      0
                                      20    IGNORE      4      0
                                      19    IGNORE      3      0
                                      18    IGNORE      2      0
                                      17    IGNORE      1      0
                                      16   ADDRESS      8      0
                                      15   ADDRESS      7      0
                                      14   ADDRESS      6      0
                                      13   ADDRESS      5      0
                                      12   ADDRESS      4      0
                                      11   ADDRESS      3      0
                                      10   ADDRESS      2      0
                                       9   ADDRESS      1      0
                                       8   ADDRESS      0      0
                                       7     INPUT      7      0
                                       6     INPUT      6      0
                                       5     INPUT      5      0
                                       4     INPUT      4      0
                                       3     INPUT      3      0
                                       2     INPUT      2      0
                                       1     INPUT      1      0
                                       0     INPUT      0      0
                   LOADPAGE_LO        31     VALUE      7      1
                                      30     VALUE      6      1
                                      29     VALUE      5      0
                                      28     VALUE      4      0
                                      27     VALUE      3      0
                                      26     VALUE      2      0
                                      25     VALUE      1      0
                                      24     VALUE      0      1
                                      23     VALUE      7      0
                                      22     VALUE      6      0
                                      21     VALUE      5      0
                                      20     VALUE      4      0
                                      19     VALUE      3      0
                                      18     VALUE      2      0
                                      17     VALUE      1      0
                                      16     VALUE      0      0
                                      15     VALUE      7      0
                                      14     VALUE      6      0
                                      13     VALUE      5      0
                                      12     VALUE      4      0
                                      11     VALUE      3      0
                                      10     VALUE      2      0
                                       9   ADDRESS      1      0
                                       8   ADDRESS      0      0
                                       7     INPUT      7      0
                                       6     INPUT      6      0
                                       5     INPUT      5      0
                                       4     INPUT      4      0
                                       3     INPUT      3      0
                                       2     INPUT      2      0
                                       1     INPUT      1      0
                                       0     INPUT      0      0
                   WRITEPAGE          31     VALUE      7      1
                                      30     VALUE      6      1
                                      29     VALUE      5      0
                                      28     VALUE      4      0
                                      27     VALUE      3      0
                                      26     VALUE      2      0
                                      25     VALUE      1      1
                                      24     VALUE      0      0
                                      23     VALUE      7      0
                                      22     VALUE      6      0
                                      21    IGNORE      5      0
                                      20    IGNORE      4      0
                                      19    IGNORE      3      0
                                      18    IGNORE      2      0
                                      17    IGNORE      1      0
                                      16   ADDRESS      8      0
                                      15   ADDRESS      7      0
                                      14   ADDRESS      6      0
                                      13   ADDRESS      5      0
                                      12   ADDRESS      4      0
                                      11   ADDRESS      3      0
                                      10   ADDRESS      2      0
                                       9     VALUE      1      0
                                       8     VALUE      0      0
                                       7    IGNORE      7      0
                                       6    IGNORE      6      0
                                       5    IGNORE      5      0
                                       4    IGNORE      4      0
                                       3    IGNORE      3      0
                                       2    IGNORE      2      0
                                       1    IGNORE      1      0
                                       0    IGNORE      0      0
                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               flash         65     6    32    0 yes      8192   64    128  4500  4500 0xff 0xff
                 Memory Ops:
                   Oeration     Inst Bit  Bit Type  Bitno  Value
                   -----------  --------  --------  -----  -----
                   READ_LO            31     VALUE      7      0
                                      30     VALUE      6      0
                                      29     VALUE      5      1
                                      28     VALUE      4      0
                                      27     VALUE      3      0
                                      26     VALUE      2      0
                                      25     VALUE      1      0
                                      24     VALUE      0      0
                                      23     VALUE      7      0
                                      22     VALUE      6      0
                                      21     VALUE      5      0
                                      20     VALUE      4      0
                                      19   ADDRESS     11      0
                                      18   ADDRESS     10      0
                                      17   ADDRESS      9      0
                                      16   ADDRESS      8      0
                                      15   ADDRESS      7      0
                                      14   ADDRESS      6      0
                                      13   ADDRESS      5      0
                                      12   ADDRESS      4      0
                                      11   ADDRESS      3      0
                                      10   ADDRESS      2      0
                                       9   ADDRESS      1      0
                                       8   ADDRESS      0      0
                                       7    OUTPUT      7      0
                                       6    OUTPUT      6      0
                                       5    OUTPUT      5      0
                                       4    OUTPUT      4      0
                                       3    OUTPUT      3      0
                                       2    OUTPUT      2      0
                                       1    OUTPUT      1      0
                                       0    OUTPUT      0      0
                   READ_HI            31     VALUE      7      0
                                      30     VALUE      6      0
                                      29     VALUE      5      1
                                      28     VALUE      4      0
                                      27     VALUE      3      1
                                      26     VALUE      2      0
                                      25     VALUE      1      0
                                      24     VALUE      0      0
                                      23     VALUE      7      0
                                      22     VALUE      6      0
                                      21     VALUE      5      0
                                      20     VALUE      4      0
                                      19   ADDRESS     11      0
                                      18   ADDRESS     10      0
                                      17   ADDRESS      9      0
                                      16   ADDRESS      8      0
                                      15   ADDRESS      7      0
                                      14   ADDRESS      6      0
                                      13   ADDRESS      5      0
                                      12   ADDRESS      4      0
                                      11   ADDRESS      3      0
                                      10   ADDRESS      2      0
                                       9   ADDRESS      1      0
                                       8   ADDRESS      0      0
                                       7    OUTPUT      7      0
                                       6    OUTPUT      6      0
                                       5    OUTPUT      5      0
                                       4    OUTPUT      4      0
                                       3    OUTPUT      3      0
                                       2    OUTPUT      2      0
                                       1    OUTPUT      1      0
                                       0    OUTPUT      0      0
                   LOADPAGE_LO        31     VALUE      7      0
                                      30     VALUE      6      1
                                      29     VALUE      5      0
                                      28     VALUE      4      0
                                      27     VALUE      3      0
                                      26     VALUE      2      0
                                      25     VALUE      1      0
                                      24     VALUE      0      0
                                      23     VALUE      7      0
                                      22     VALUE      6      0
                                      21     VALUE      5      0
                                      20    IGNORE      4      0
                                      19    IGNORE      3      0
                                      18    IGNORE      2      0
                                      17    IGNORE      1      0
                                      16    IGNORE      0      0
                                      15    IGNORE      7      0
                                      14    IGNORE      6      0
                                      13    IGNORE      5      0
                                      12   ADDRESS      4      0
                                      11   ADDRESS      3      0
                                      10   ADDRESS      2      0
                                       9   ADDRESS      1      0
                                       8   ADDRESS      0      0
                                       7     INPUT      7      0
                                       6     INPUT      6      0
                                       5     INPUT      5      0
                                       4     INPUT      4      0
                                       3     INPUT      3      0
                                       2     INPUT      2      0
                                       1     INPUT      1      0
                                       0     INPUT      0      0
                   LOADPAGE_HI        31     VALUE      7      0
                                      30     VALUE      6      1
                                      29     VALUE      5      0
                                      28     VALUE      4      0
                                      27     VALUE      3      1
                                      26     VALUE      2      0
                                      25     VALUE      1      0
                                      24     VALUE      0      0
                                      23     VALUE      7      0
                                      22     VALUE      6      0
                                      21     VALUE      5      0
                                      20    IGNORE      4      0
                                      19    IGNORE      3      0
                                      18    IGNORE      2      0
                                      17    IGNORE      1      0
                                      16    IGNORE      0      0
                                      15    IGNORE      7      0
                                      14    IGNORE      6      0
                                      13    IGNORE      5      0
                                      12   ADDRESS      4      0
                                      11   ADDRESS      3      0
                                      10   ADDRESS      2      0
                                       9   ADDRESS      1      0
                                       8   ADDRESS      0      0
                                       7     INPUT      7      0
                                       6     INPUT      6      0
                                       5     INPUT      5      0
                                       4     INPUT      4      0
                                       3     INPUT      3      0
                                       2     INPUT      2      0
                                       1     INPUT      1      0
                                       0     INPUT      0      0
                   WRITEPAGE          31     VALUE      7      0
                                      30     VALUE      6      1
                                      29     VALUE      5      0
                                      28     VALUE      4      0
                                      27     VALUE      3      1
                                      26     VALUE      2      1
                                      25     VALUE      1      0
                                      24     VALUE      0      0
                                      23     VALUE      7      0
                                      22     VALUE      6      0
                                      21     VALUE      5      0
                                      20     VALUE      4      0
                                      19   ADDRESS     11      0
                                      18   ADDRESS     10      0
                                      17   ADDRESS      9      0
                                      16   ADDRESS      8      0
                                      15   ADDRESS      7      0
                                      14   ADDRESS      6      0
                                      13   ADDRESS      5      0
                                      12    IGNORE      4      0
                                      11    IGNORE      3      0
                                      10    IGNORE      2      0
                                       9    IGNORE      1      0
                                       8    IGNORE      0      0
                                       7    IGNORE      7      0
                                       6    IGNORE      6      0
                                       5    IGNORE      5      0
                                       4    IGNORE      4      0
                                       3    IGNORE      3      0
                                       2    IGNORE      2      0
                                       1    IGNORE      1      0
                                       0    IGNORE      0      0
                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
                 Memory Ops:
                   Oeration     Inst Bit  Bit Type  Bitno  Value
                   -----------  --------  --------  -----  -----
                   READ               31     VALUE      7      0
                                      30     VALUE      6      0
                                      29     VALUE      5      1
                                      28     VALUE      4      1
                                      27     VALUE      3      0
                                      26     VALUE      2      0
                                      25     VALUE      1      0
                                      24     VALUE      0      0
                                      23     VALUE      7      0
                                      22     VALUE      6      0
                                      21     VALUE      5      0
                                      20    IGNORE      4      0
                                      19    IGNORE      3      0
                                      18    IGNORE      2      0
                                      17    IGNORE      1      0
                                      16    IGNORE      0      0
                                      15    IGNORE      7      0
                                      14    IGNORE      6      0
                                      13    IGNORE      5      0
                                      12    IGNORE      4      0
                                      11    IGNORE      3      0
                                      10    IGNORE      2      0
                                       9   ADDRESS      1      0
                                       8   ADDRESS      0      0
                                       7    OUTPUT      7      0
                                       6    OUTPUT      6      0
                                       5    OUTPUT      5      0
                                       4    OUTPUT      4      0
                                       3    OUTPUT      3      0
                                       2    OUTPUT      2      0
                                       1    OUTPUT      1      0
                                       0    OUTPUT      0      0
                                      Block

             Programmer Type : STK500
             Description     : Atmel STK500 Version 1.x firmware
    avrdude: Send: A [41] . [80]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [02]
    avrdude: Recv: . [10]
    avrdude: Send: A [41] . [81]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [01]
    avrdude: Recv: . [10]
    avrdude: Send: A [41] . [82]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [12]
    avrdude: Recv: . [10]
    avrdude: Send: A [41] . [98]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [00]
    avrdude: Recv: . [10]
             Hardware Version: 2
             Firmware Version: 1.18
             Topcard         : Unknown
    avrdude: Send: A [41] . [84]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [00]
    avrdude: Recv: . [10]
    avrdude: Send: A [41] . [85]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [00]
    avrdude: Recv: . [10]
    avrdude: Send: A [41] . [86]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [00]
    avrdude: Recv: . [10]
    avrdude: Send: A [41] . [87]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [00]
    avrdude: Recv: . [10]
    avrdude: Send: A [41] . [89]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [00]
    avrdude: Recv: . [10]
             Vtarget         : 0.0 V
             Varef           : 0.0 V
             Oscillator      : Off
             SCK period      : 0.1 us

    avrdude: Send: A [41] . [81]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [01]
    avrdude: Recv: . [10]
    avrdude: Send: A [41] . [82]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [12]
    avrdude: Recv: . [10]
    avrdude: Send: B [42] . [14] . [00] . [00] . [01] . [01] . [01] . [01] . [03] . [ff] . [ff] . [ff] . [ff] . [00] @ [40] . [02] . [00] . [00] . [00]   [20] . [00]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [10]
    avrdude: PAGEL and BS2 signals not defined in the configuration file for part ATtiny85, using dummy values
    avrdude: Send: E [45] . [05] . [04] . [d7] . [a0] . [01]   [20]
    avrdude: Recv: . [14]
    avrdude: Recv: . [10]
    avrdude: Send: P [50]   [20]
    avrdude: ser_recv(): programmer is not responding
    avrdude: stk500_recv(): programmer is not responding
zop@mikasa:~$

I don't know what else to try, so suggestions are very welcome.
Thanks.
PS: I had to strip out some of the output text because it was bigger than 30000 chars, I hope the info is good enough.

Some key information is missing; what board configuration did you target while uploading the sketch? High Low offers boards.txt with 3 different configurations, make sure to use the 1Mhz (ATtiny85 default). Also, please share your connections from the Arduino to the ATtiny

Try removing the capacitor, and add a wire between 5v and reset on the UNO. You did upload the ArduinoISP example sketch right? (before adding the cap/wire)

@Gerben, the fact that the responses to the first number of requests to the programmer were received is pretty clear evidence that the arduino reset was not a problem and the right sketch was loaded.

avrdude has some weird error messages so I'm not confident enough to say that Send and Recv messages indicate it's working. But it might. Could you post a picture of your wiring? Or maybe the fuses are incorrect. Is it a brand new chip?

Thanks for your answers. The wiring of the Attiny85 is correct. No misidentifications with pin 1 to 5: Dot mark is pin 1. The attiny85 are fresh as they came from the (local) store. The ISP sketch was loaded previously, then using the attiny 1Mhz for the board when trying to upload the blink example (changing pin 13, obviously). Using arduino as ISP as a programmer for the upload to the attiny's (tried 2 different chips). I have to say that I'm sure I'm using a CLONE, eventhough it says "arduino" all over and has the whitish color on the back of the PCB. I don't know if that could be the probl

I have had reliability problems with ArduinoISP until I reduced the baudrate to 9600.

Your log demonstrates that

Your programmer settings were correct.
You have the right sketch loaded on the Arduino
You have the Arduino auto-reset properly disabled.

The failure occurs at the point at which you're trying to enter programming mode. The two most likely error sources are:

Your ATtiny85 is not wired up correctly (e.g. you misidentified pin 5 as pin 1, you used a wrong pin on the Arduino, you crossed two signals, etc).
Your ATtiny85 is in a mode that prevents ISP reprogramming (programming the RSTDIBL fuse is the toughest of these mode, but merely setting the clock source to something odd will also cause this). Does your chip have a past, or is it fresh out of the box?

I spent days with exactly the same problem (well, trying to program a 328p). Then I purchased a USBISP (aka USBICSP), and all my problems went away. I got one which had a "program slowly" jumper - setting this jumper will do the equivalent of -b19200, but without needing to explicitly set it, so you can do it from the Arduino IDE. Just my 2c worth.


text:
Whats the function of the resistor between MCU and its Resonator in Arduino Mega?
I was looking Arduino Mega's schematic and I noticed a resistor between the MCU and its resonator. R3 in this image:

Why is it there and what is its function?

http://forum.arduino.cc/index.php?PHPSESSID=k7m3r8sckc0kmc8oda18gt0l16&topic=176297.msg1309697#msg1309697

@Gerben - This addresses R1, not R3.

Oops. Didn't even see R3. That's indeed a weird location for a resistor.

That resistor limits the drive through the crystal.  If the power applied to the crystal is too high then the slope and phase shift at the resonant frequency will not be optimal and at really high drive levels could cause mechanical damage to the crystal (like that shattered wine glass trick).
See good instruction PDF here, section 2.1.

source: Stack Exchange

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

sort: votes


text:
arduino mega number of simultaneous pulse inputs
I'm looking at this specification page:
http://arduino.cc/en/Main/ArduinoBoardMega2560
It says there are 54 digital input pins. How many of those can be used at the same time to measure pulse input frequency? I've seen examples of a couple pins being used at the same time, but can it handle measuring frequency on say 12 pins at the same time?
Also I am looking at this bluetooth shield:
http://redbearlab.com/bleshield/
Would there be a limit on the number of simultaneous frequency measuring pulse pins when then this is added?
Currently I use an IOIO board and can monitor 9 pulseInput pins (at least it seems like it is simultaneous, but probably not, it has a PIC24FJ256GB206 microcontroller that has 9 input capture modules when used as single precision.) It works well with my around 15-30 Hz signals updated every 250 milliseconds. I'm wanting to move it to arduino for supported connectivity to many other devices. What are the capabilities of the arduino mega?

What are you using to measure?

This depends on how long "the same time" lasts, and what frequencies you want to measure. There is no way for the processor to do anything simultaniously, but it can check all the pins in succession relativly fast. Thats no guarentee its fast enough though. BTW, pulseIn can only measure one pin at a time.

@BrettAM Currently I use an IOIO board and can monitor 9 pulseInput() pins (at least it seems like it is simultaneous, but probably not, it has a PIC24FJ256GB206 microcontroller that has 9 input capture modules when used as single precision.) It works well with my around 15-30 Hz signals updated every 250 milliseconds. I'm wanting to move it to arduino for supported connectivity to many other devices. What are the capabilities of the arduino mega?

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


text:
Multiple boards blinking at same time
I want to make two or more boards to blink an LED at the same time (within 1 ms difference) The boards cannot be connected with wires to each other and will be located in different rooms. How can I do this? What components do I need?

What is the cycle time? Is it okay if they sync every second or so? Or do they have the have the same value returned for millis()? In the first situation you can just send a "pulse" every second. In the latter you'd need to send some actual data, which makes it slightly more complicated. Definitely go with RF. There are some very cheap 433Mhz transmitters and receivers on the market. One arduino will be the master and send. The other boards will have a receiver.

@Gerben I want the LEDs to blink in a fixed time interval (say every minute interval). If the time difference between multiple boards blinking remains within 1ms, then the sync cycle can be every minute or more.

<1ms difference in 60 seconds, means around 17ppm. The crystals on the arduinos have a much higher deviation. So syncing every minute would not be enough, or you have to take the time-difference between 2 syncs and adjust your delays accordingly. Alternatively you could use the internal 8mhz oscillator on the atmega, instead of the crystal. The internal oscillator can be adjusted relatively easy. That way all the boards run at around the same frequency, and every minute any accumulated deviation is reset.

Could you tell us WHY you want them to blink simultaneously in different locations? If we know we can help you better.

@Tom It is for synchronization of multiple devices

Can both arduinos be connected to mains power?

@bigjosh They are in different rooms, powered by battery. Cannot to be wired together.

Have both sync to a master clock using GSM shields. These shields are getting very cheap (as low as $14 on ebay).
The shields receive the time wirelessly from the cellular network and this time base is extremely accurate. Here is some example code to read the current time from the shield...
http://forum.arduino.cc/index.php?topic=163155.msg2102141#msg2102141
Note that you will need a SIM card to get the time, but you should not need an active cellular account.

You can also use real time clock (RTC) modules to syncronize arduinos. These are cheaper than other solutions like GPS or WiFi.

You could certainly do it with multiple Arduinos, each with a WiFi shield, but that would cost a lot of money.
Instead I would suggest building a low power radio transmitter that sends simple morse code clicks, and then building amplifier boards that use the clicks to trigger LED blinks. You'd need to use a frequency that is open for low power use in your country, like the range for garage door openers.
I've seen circuits in old electronics kits for building morse code transmitters, but they might not meet current FCC regulations.

1ms synchronization with WIFI is by no means "certain".  It may be possible, but having tried to do that, it's actually rather tricky - especially if there is a router in between, packet latency can vary widely.  Nor is a simple on-off-keying demodulator likely to yield nice results, as it will be very subject to interference.  However it could possible be used as input to a software phase locked loop - a local timer which would over time speed up or slow down if it found that the radio pulses it did detect tended on average to be a little earlier or later than expected.

Ultimately, some of the simple SPI-interfaced 2.4 GHz RF chips/modules probably could provide a solution - nrf24L01 type stuff - which is cheaper, easier, and less likely to false trigger in the presence of interference than a DIY RF link.  Either a software PLL, or a series of "count down" messages could be used to bridge missed messages.

@ChrisStratton, those are cool, and cheap too! (voted). Point taken about the home brew radio transceiver. You'd need to make an FM transmitter and receiver using PLLs, and that would take quite a few components. Why not post you suggestion as an answer? Seems like the best solution.

Although I was suggesting building one Arduino-based transmitter and a bunch of analog radio receiver based LED flashers. The nrf24L01 solution would require an Arduino per flasher, so the total cost per receiver would be fairly high. Could you rig those up with an ARTiny?

With efficient programming, yes, it should be able to be done with an ATtiny85.  And even an ATmega328p isn't that expensive, nor does it require more support components.  Much of what you pay for in an "Arduino" is the USB interface, PCB, power circuitry, connectors, etc.


text:
Can Arduino control 8 solenoids?
I know very little about Arduino and even less about programming one. Before I purchase a board, and learn how to program it, I was wondering if my idea is feasible.
I want to program the Arduino to sequentially open one after another irrigation valve. There would be approximately eight 24 volt solenoid valves. Each one would need to be open for approximately 15 minutes, then open the next valve in sequence and finally close the previous valve. Similar to a multi-zone irrigation controller.
I see that I may need to use a transistor in the power circuit of the solenoid. But it is not clear to me if the Arduino can control eight solenoids and if so, does each solenoid require its own transistor?

is this what you really want? it is different from irrigation. Each one would need to be open for approximately 15 minutes, then open the next valve in sequence and finally close the previous valve. .... the sequence has to be absolutely clear in your mind, otherwise it will prove difficult to write a program that does what you want it to do.

Are these AC or DC solenoids? I see a lot of irrigation solenoids are AC.

If this is an educational endeavor: welcome.  If this is something you need to get done in a reasonable amount of time, then I recommend using existing irrigation solutions.   There is significant time and $ investment to not only program the device, but select switching mechanisms and ensuring they are hardened for the field

An Arduino can control (at least) 8 devices. Instead of a transistor, it might be much easier to use an 8 way relay controller, something like this:
8 relay module
Just connect all 8 valves to the relays, you power the relay with a separate source for the valves, and connect the pins to the Arduino.
These ones have opto couplers, which give an extra security between the valves and the Arduino.
8 relay module with opto couplers
(note I just put the first entry I found, you might find better/cheaper similar items, e.g. at AliExpress for $4).
As Andre said in a comment below, you can use an Arduino Mega if you need more outputs. Or if you want a challenge you can use use a multiplexer IC like 74HC595 (plenty of examples to be found with Arduino).
For controlling one relay with an Arduino enough examples can be found, for 8 it's similar (just use 8 GPIOs), or a multiplexer IC.

Ya, depending on the amount of current, it is better to have some pysical iscolation between your 24V/higher current side of the valves.  and the 5v/low current side of the arduino.

@ChadG For 10 euro I wouldn't take the risk myself, assuming the valves are more costly (or the risk not irrigating if that is the main goal).

These relay module usualy have opto-coupler isolation, but indeed check.

If you need more than i/o just use an Arduino mega.

@AndreCourchesne Thanks for the comments, I have updated my answer accordingly.

Why would one suggest a 70 IO Mega to control 8  outputs?

@CrossRoads Only in case he needs more outputs ... for 8 it's not needed, but I know from experience projects can grow easily.

@MichelKeijzers I was agreeing with you in case that was not clear, I was saying have physical isolation (Relays) was better then driving it with a transistor. Having opto-couplers on the relays is nice, but probably overkill for those little relays.

@CrossRoads Seeing as the OP had not bought a board, and was still exploring his options(and didn't say if he had planned on any specific board), suggesting a Mega was not out of line. The valves alone are 2/3 of the IO of a Uno, and it would make sense that he would want to add some sort of sensors or manual control down the road.

The choice between a Uno and Mega is also about flash/ram. On some application the Uno 2k of ram can be an issue.

@Chad Maybe optocouplers are overkill, but these all-in-once modules are so cheap, I don't think this 'extra'  is a problem.

Most irrigation valves are AC operated, typically using 24VAC at about 250mA (Double that to 500mA for the inrush current).  The best way to drive these is via a triac.  If you want isolation between your controller and the valve voltage an opto coupler with a triac output is the best way to go.  A good choice given the typical irrigation valve is the Vishay VO3023:  5mA LED input current and 1A output current and only about $0.50 per unit.  Triacs are pretty tough devices and have no moving parts like relays so they are quite reliable.

Yes, you will need something to drive 24 volt solenoids, because the Arduino cannot do it alone.
My preferred method would be to use a ULN2803 device, which will allow you to drive all those eight solenoids (assuming they take less than 500mA or current) and has inbuilt protection against the voltage spike when the solenoid switches off.
http://www.ti.com/lit/ds/symlink/uln2803a.pdf
These devices are available on eBay.
The software will be quite simple for this application and should be well within the capabilities of anyone who reads an Arduino tutorial.

There are 2 wires to a solenoid, and 2 ways to operate them:
1- Closing a relay sends 24V out, with return wires going to 0 volts.
2- 24V Always goes out, and a relay can short the return wire to 0 volts.
Either way, test 2 by running the wires to a control board, and manually activating solenoids. When that works, add Arduino relay control as other suggest.
Keeping the switches will help, if you want to operate a solenoid manually OR you suspect you have a broken relay / solenoid.

An Arduino board is merely a microcontroller with the stuff around it that is necessary to keep it running. By stufff, I mean thinks such as the voltage regulator that provides the power, the oscillator that provides the frequency for the controller, the GPIO pin connectors, and so on.
This is a very simple application and could easily be done by an Arduino. The programming doesn't have to run quickly. You are only doing one thing at a time.
I found an 8-channel relay module that should do what you need. You would need four of them, but they are only about $11 apiece. I have never used this device before, so I don't know how well it works, but the specifications seem right. They can be controlled by almost any computer with output pins that have 5 volts. So you'd need to use an Arduino with 5V output pins.
You will probably need more output pins than a standard Arduino, but that is easy enough to do with the Mega version.

it is not 24 valves. it is 8 24V valves :-)

That makes it even easier. The module I linked can handle 30V DC at 10 amps. It can also handle AC up to 250V. And now only one is needed.

An alternative method is to use an I2c port expander such as a PCF8574.  These are available as break out boards.  By selecting a different I2C address on each break out board up to 64 relays can be controlled using opto isolated relay modules.  Thus 64 0utputs or inputs with just two Arduino pins.

You hardly need that for 8

Yes, Arduino can control eight transistors.
Each solenoid will need a transistor.
Ideal would be to use logic level N-channel MOSFETs that the Arduino 0/5V output can drive directly.  IRFL540 is mentioned a lot, you can get them at digikey.com.
Drive the gate thru a 150 ohm resistor, and have a 10K resistor from the gate to Gnd so the transistor is off while the Arduino is reset (and the IO pins all revert to Inputs).
Depending on the current draw, you may able to use a shift register with Open Drain outputs. TPIC6C595, 100mA. TPIC6B595, 150mA. TPIC6595, and TPIC6A595 are even higher current capable parts.
Add a diode with the same current rating across the solenoid coil, cathode to +24V, so the burst of current generated by the coil when the transistor closes has somewhere to dissipate. (current in a coil wants to keep flowing as the magnetic field in the coil collapses, it can't go thru the turned-off transistor, so it goes thru the coil and dissipates in the coil's wire-resistance).

this is not electronics.stackexchange

Your comment does not make sense. Arduino controlling transistors is a primary function of what it can do.

@Juraj knowing how to hook up the electronic portion of a system to an Arduino is an integral part of choosing/using Arduino devices. What made you think that it was perhaps off topic for this SE?

why not use relay modules? or any other actuator or sensor you can by as module with supporting circuit soldered in factory with so small components? What can he make more specialized for the application, then the of the shelf relay board? the questions are not rhetorical. I really want to know what is the drawback.

The solenoids I installed recently for my irrigation system were 24V AC-powered which would make a MOSFET or BJT transistor unsuitable. A Triac might be better in this case.


text:
Is there a way to connect two Arduinos, when one of them has all of its pins occupied?
I want to connect an Arduino Uno to an Arduino Nano, so that it can send signals. The problem is that the Arduino Uno has a motor shield connected to it, and it takes up all pins of the Arduino.
This is a picture of the whole motor shield contraption if it helps:

Does anybody know any solution for this?

Just because a shield sticks pins into the Arduino it doesn't follow that it uses all those pins. Read the shield schematic or manual to see what is actually used and what is not used. Chances are only a few pins are actually used.

Yeah, i figured that out, but its not really possible to keep only one side of it plugged in. Can i solder wires from the arduino to the pins that are not being used?

Of course you can. Or you may find there are connections on the top that just connect direct to the Arduino pins.

On the image it looks like you can solder pin headers to the shield to connect the other pins from there. Though to say for sure we would need to have a look at the shields datasheet/product page. Can you provide a link for it?

https://5.imimg.com/data5/PX/UK/MY-1833510/l293d-based-arduino-motor-shield.pdf

Pins 0 and 1 are serial pins which are also connected to usb, and you use them when you are programming your board or when you send anything to serial. It is unlikely that any shield uses it unless it has to and it although has a benefit of being able to listen to what the Arduino sends.
I think hitching a ride on pins 1 and 0 (rx/tx) would be the easiest. SO you can print or write to them the same way as you respond to yourself.
Just a warning that when you are sending data between two boards and Print numbers they come as symbols of the numbers, not the numbers themselves So Serial.print(7) would arrive to the next arduino as number 55 or symbol '7'. If you are sending numbers between two arduinos you can use write Serial.write(7); which does not change data, but your serial monitor on a computer wont read it right, or you can send them as symbols, but then the arduino listening may have to convert number symbol to the number. (sooner or later you will have to create yourself a simple function to convert symbols to numbers in your project...

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


text:
How do I connect 20 outputs and 20 inputs to an Arduino board?
I am a mechanical engineer starting my journey with Arduino, so please excuse me if I put some very generalized message.

I need to sequentially operate 20 output relays, and then verify if the correct relay has been triggered. If the correct relay was triggered, the next relay will be triggered after a delay of 1-2 seconds.
I plan to do this with an Arduino Uno so that I can generate error messages if any output has not been triggered.

However, the Uno doesn't have sufficient inputs and outputs to do this. So what are my options?
I want to ask you the below:-

If there are I/O expansion boards available for the Uno? If yes, sharing the details will be helpful;
A friend recommended to use a multiplexer. Can I use a multiplexer to convert a 4 pin output from the Arduino to 16 pin output, and probably use the saved pins to monitor the inputs? If yes, how?
Is there something available like a reverse multiplexer wherein the chip can convert the 16 output signals to 4 pin inputs to the Arduino?

Please let me know the best solution wrt the below parameters - reliability of operation, cost, compactness.
Thanks for your time and support.

use a multiplexer to convert a 4 pin output from arduino to 16 pin output ... no, use a de-multiplexer for that, but that would energize only one relay at a time

please describe in detail how the relays are supposed to behave

your question is not arduino specific ... it is off topic here ... better fit at https://electronics.stackexchange.com/questions

At any moment of time, only 1 relay will be switched on. I plan to use the Normally open connection of relay to switch on a motor. The "normally closed" connection will taken as a input to verify that only one relay has switched on. I hope this is what you meant to ask. The reason why i asked here is to ask if there are any I/O expansion boards for Arduino uno

Is there something available like a reverse multiplexer ... that is incorrect ... you are describing a multiplexer here ... https://hackaday.com/wp-content/uploads/2016/08/mux-demux.gif

@jsotola That’s a bit harsh? It’s a beginner question about connecting to arduino. Hard to see it as off topic.

@RowanP how can it be arduino specific? ... the question would be the same if the OP used RPi or beaglebone or any microcontroller ... also, it is not a question that asks how to interface a switch to an arduino

@jsotola That’s true. But OP is not asking about those other microcontrollers. They are asking about the specific Arduino context. There are good answers already provided that stay in that context, they will be valuable to other readers beginning with Arduino.

Look for port expansion boards for the arduino, there are a lot of them many under a dollar. Typically they are in 8 or 16 channel designs. They probably will have PCF8574 or PCF8575 chips. These are low voltage (typically 5V) for the Arduino. You will have to use an interface if it is connected to another voltage. Each of these modules the channels can be individually programmed as an input or output. You can turn on or any of the outputs in any order and pattern you want. These devices operate with the I2C interface so you need only two lines from the Arduino to drive up to 8 of these modules. The pins should be labeled A4 (SDA), A5 (SCL) depending on the model of Arduino you have. Good luck!

There is a useful comparison of PCF8575 versus MCP23017 I2C port expanders on the Arduino forum. https://forum.arduino.cc/t/i2c-port-expanders-pcf8575c-vs-mcp23017/260337

Instead of using expansion boards, you could use an Arduino Mega or an Arduino Due instead. These have more than enough GPIO pins for 20 inputs and 20 outputs. The price isn't much higher compared to the extra expansion board and the extra wiring required.

If going this route keep in mind that the Mega is 5V (like the Uno) but the Due runs on 3.3V. You’ll likely want to match to your selected relays and sensors.

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


text:
Arduino, problem with interrupt and SSD1306 OLED
I'm not that good at this. Calculates RPM through Peripheral Speed and Interrupt.
Everything works fine when I show this in the IDE with Serial.print without OLED. When I connect an SSD1306 OLED I2C, the interrupt stops working. No serial.print.
If I uncomment the display.display(), Same problem with display.setRotation(90): everything is fine and serial.print starts working, but of course not the OLED.
In the code I have a void addressing, visadisplay(). If I put this addressing in void loop () then everything works but then there is a risk of unsynchronization, wrong values. I have also removed visadisplay(); without change.
Help...
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

// Function for serial display.
// Connections for Nano.
// Hall sensor connection: (Signal out) --- (D2).
// Display connection: (SDA) --- (4A) / (SCL) --- (A5)

volatile unsigned long PulsTid = 0UL;
volatile unsigned long StartTid = 0;
volatile unsigned long SlutTid = 0;
volatile unsigned long CalcTid = 0;
volatile float omkrets = 7.5;
volatile float HastighetPerferi = 0;
volatile unsigned long Rpm = 0;
volatile float Vinkel = 0UL;

void isr() { // interrupt service routine
  Vinkel = 0;
  StartTid = millis();
  CalcTid = SlutTid;

  detachInterrupt(0);             //detaches the interrupt while calculating

  PulsTid = (StartTid - SlutTid);
  HastighetPerferi = (omkrets / PulsTid);
  SlutTid = StartTid;
  Rpm = ((HastighetPerferi / (omkrets / 1000) * 60) / 2); // Calculate speed

  visadisplay();
  attachInterrupt(0, isr, FALLING);  //attaching the interrupt again
}

void visadisplay(void) {
  Serial.print("Varvtal: ");
  Serial.println(Rpm);

  display.setRotation(90);
  display.clearDisplay();
  display.setTextSize(1);              // Text size.
  display.setTextColor(SSD1306_WHITE); // White text.
  display.setCursor(0, 0);             // Start position
  display.println("RPM: ");
  display.setCursor(40, 10);
  display.setTextSize(2);
  display.print(Rpm);
  display.display();
}

void setup() {
  Serial.begin(115200);
  attachInterrupt(0, isr, FALLING);  //attaching the interrupt

  //SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }
}

void loop(){
}

I would guess, that the display code needs interrupts to work during its execution, which is not the case inside an ISR. Serial will just put the data into the buffer, which then gets pushed out later via interrupts. Try to set a flag inside the ISR and then execute the display code in the main loop, if the flag was set

You don’t have to disable and re-enable the interrupts inside an ISR (in fact, you really shouldn’t). Also, an ISR should be very short (as few instructions as possible) and yours isn’t. Take @chrisl ‘s advice and set a flag inside the ISR, test for the flag in the main loop and leave handling of the display code to the main loop.

I2C communication (usually) requires interrupts. You can't use interrupts inside an interrupt. Ergo, you can't use I2C communication inside an interrupt. There's very little you can do in an interrupt.

Your problem is (most likely) that you are doing everything from an interrupt. That is not only bad practice, but on Arduinos it is generally impossible.
On small microcontrollers you typically only have one interrupt priority (occasionally two). That means that only one interrupt can run at a time, and if an interrupt is running then no other interrupt can interrupt it.
So anything that relies on interrupts to operate can never be used inside an interrupt service routine, or it will never function.
That includes things like delay() and, depending on the implementation, such things as Wire (I2C) and SPI.
Instead your ISR really should be as short as possible. It should at most do any short calculations and store results, and then indicate (through the use of a semaphore) to the main thread that it should do some work.
The simplest "fix" to your problem would be to move visadisplay() into loop() and in isr() simply set a bool flag when there is data to display. Your loop() then checks that flag and, if set, resets it and calls visadisplay().
Also, you don't need to detach and re-attach the interrupt all the time - if the ISR is running then interrupts can't happen anyway.
// ... snip ...
volatile bool doDisplay = false;

void isr()          //interrupt service routine
{
  Vinkel = 0;
  StartTid = millis();
  CalcTid = SlutTid;

  PulsTid = (StartTid - SlutTid);
  HastighetPerferi = (omkrets/PulsTid);
  SlutTid = StartTid;
  Rpm = ((HastighetPerferi/(omkrets/1000)* 60)/2);  //Calculate speed

  doDisplay = true; // Signal to the main thread there's data to display
}

// ... snip ...

void loop() {
    if (doDisplay) {       // If there is something to display
        doDisplay = false; // then clear the flag for next time
        visadisplay();     // and display the data.
    }
}

I tested with an LCD display and SPI connection instead of I2C. Then everything works as it should. A bit sad that you have to use circumventing solutions on such elementary needs to connect a display.

About rotating text on OLED, rotation codes are 0, 1, 2, 3
(see Adafruit web site).
So your code should look like:
  Serial.print("Varvtal: ");
  Serial.println(Rpm);

  display.setRotation(1);
  display.clearDisplay();


text:
How to write a program to do 2 different loop | Task?
I wanna write a program for rc-plane navigation
The plane must navigate to 2 waypoints waypoint_1 & waypoint_2
When it reaches to waypoint_1 (with miss-distance =< 5) then navigate to waypoint_2
But i have a problem.
First look at this :
void loop(){

    if (distance-to-waypoint_1 > 5 meters) {
        Navigate to waypoint_1
    if distace-to-waypoint_1 < 5 meters :
        Navigate-to-waypoint_2

If i use a code like this, plane will navigate to waypoint_1 and when it reaches somewhere that has  less than 5 meters distance to waypoint_1, then will navigate to waypoint_2, but if plane fly away and the distance between it's location and waypoint_1 goes greater than 5 meters, plane return to previous navigation and will navigate to waypoint_1 again and ignore navigation to waypoint_2
So, i need a form of programme to first do a loop for navigation to navigate the plane to waypoint_1 and when it reaches the waypoint_1 , do another loop to navigate the plane to waypoint_2
Thanks

When distance between the plane position and waypoint_1 will be equal or less than 5 meters, then will navigate to waypoint_2 but the problem is that when the plane moves away from waypoint_1 to go to waypoint_2, its distance from waypoint_1 will be more than 5 meters, and the first if condition will be established again and it will navigate to waypoint_1 again.

Because of the problem with if condition, if condition will not work for this purpose and it will be established again because of distance

Ok let's say i wanna use the distance as a criterion to know where am i and where I'm not, somehow i measure the distance between my position and Bob's house and if will be greater than 5 meters, i know that I'm not reached Bob's house, so i will use the direction to reach Bob's house. When the distance (only criterion that i use) between my position and Bob's house will be equal or less than 5 meters, i know that i reached Bob's house then, i will use another direction to reach out Mary's house but when i walk away from Bob's house to go to Mary's house, the distance between

My position and Bob's house will be greater than 5 meters (because the only criterion that i use is distance between my position and Houses) so i'll use a new direction to go back to Bob's house again.

Let us continue this discussion in chat.

I think you should use a different logic by using a variable to hold the current target waypoint and separate the code to reach a waypoint and to change it.
Something like this (in pseudocode):
declare variable target_waypoint and set it to waypoint1
loop
    Fly towards target waypoint
    if distance to target waypoint lower than 5
        change target_waypoint to waypoint 2

You can easily extent that for more waypoints by using an array of waypoints and a variable holding the index of the next waypoint:
declare waypoints as array
declare index variable, initialize with zero
set target_waypoint to waypoints[index]
loop
    Fly towards target waypoint
    if distance to target waypoint lower than 5
        increment index
        if index greater than max index
            Either set to zero to loop through all waypoints again
            or do whatever you want to do after the waypoints
        set target_waypoint to waypoints[index]

The code that moves you to the waypoint doesn't care about what waypoint is next. It's only doing this one job. And when you reached a waypoint you simply move the target of that code to a different position.
Much like you yourself would walk between different waypoints. Setting first waypoint as target, walking towards it until you reached it, setting the next waypoint as target and doing the walking again.


text:
Activate a DC motor for a fixed amount of time
I have a single simple DC motor that upon a condition I wish to let it run for 3 minute. How can I do it in Arduino? a simple addition to the code will be great help.
As I use Adafruit motor shield this is my current code:
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_PWMServoDriver.h"

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);

void setup() {
   Serial.begin(9600);           // set up Serial library at 9600 bps
   AFMS.begin();  // create with the default frequency 1.6KHz
}

void loop() {
IOvalue = 1000

if (IOvalue = 1000) {

 //this is the motor I wish to run for 3 min
   myMotor->setSpeed(25);
   myMotor->run(FORWARD);
   delay(100);
 }
}

Thanks a lot

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_PWMServoDriver.h"

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
boolean motorRunning = false;
unsigned long motorStartMillis;
unsigned long motorRunMillis = 180000;

void setup() {
   Serial.begin(9600);           // set up Serial library at 9600 bps
   AFMS.begin();  // create with the default frequency 1.6KHz
}

void loop() {
  IOvalue = 1000

  if (IOvalue = 1000) {
    //this is the motor I wish to run for 3 min
    myMotor->setSpeed(25);
    myMotor->run(FORWARD);
    motorStartMillis = millis();
    motorRunning = true;
  }

  // check if motor is running and time-to-run has elapsed
  if( motorRunning && (millis()-motorStartMillis > motorRunMillis) )
  {
    myMotor->setSpeed(0);
    myMotor->run(RELEASE);
    motorRunning = false;
  }
}

long int currentMillis;
void setup() {
    pinMode(motorPin, OUTPUT);
    digitalWrite(motorPin, LOW);
}
void loop() {
    if(condition is met){
        startOfMotor = millis();
        while(millis() != (startOfMotor+180000)){
            digitalWrite(motorPin, HIGH);
        }
    digitalWrite(motorPin, LOW);
    }
}

This motorPin is the pin to which the motor is connected. millis() gets the milliseconds after the board is started. 3 min = 180 seconds = 180000 ms.

Thanks. I forgot to mention that I use Adafruit motor shield and therefore how can I integrate you code into this snippet.
Code:
void loop() {
…..
….
if (IOvalue = 1000) {
//this is the motor I wish to run for 3 min
myMotor->setSpeed(25);
myMotor->run(FORWARD);
delay(100);
}
}

Can you edit your question to show the code? It is hard to read it in comments.

About the shield.. I need to know more about your setup.

Updated the question and embedded the code.

I have no idea about the Adafruit motor shield. Sorry! (For such simple operations you are better off using the Arduino itself. )


text:
SparkFun EL Sequencer does not work
I have connected to EL wire, 12v EL Inverter to SparkFun EL Sequencer but it does not work (no battery is connected). The connections are the same like in Hookup Guide (https://cdn.sparkfun.com/assets/learn_tutorials/3/6/9/ELSequencerHookUp_bb.png). Furthermore, there is no light indicating that it works but I hear a noise/whistle from the Inverter.
Do I have to program the EL Sequencer or does it automatically turn the EL wire on?

It looks like Sparkfun probably only put the bootloader on the board. The tutorial is written in a way that suggests the need to flash the board.
Also the board does not imediatly work with the 12V inverter. If you have the battery you should attach it and see the PWR LED turn on.
The inverter only provides voltage to the EL wire and not the Microcontroller, power to the microcontroller is provided by way of a regulator(U2), not the LM317 the last quote from the one comment shows how you can connect to the 12V inverter.
What you should do instead of having to go the route of all the wiring is to connect both the battery to BATT IN and the inverter, but ensuring that the microcontroller is programmed before hand.

Arduino Code
Once you have all of your hardware hooked up properly, it’s time to
  program your Sequencer to run the EL Wire display as you want. You
  will need to download the Arduino code in order to follow along with
  the example.
You can also download the most up-to-date code from the EL Sequencer
  GitHub repository.
We will be working with the “SparkFun_EL_Example.ino” example. If you
  need a review on how to upload Arduino code to your board or using the
  Arduino IDE, please check our tutorial here. Also, if you are unsure
  about installing the FTDI drivers, please check out this tutorial.

Also from one of the Tech support notes:

Using 12V to Power Both the EL Inverter & Microcontroller
If you are using a 12V wall adapter to power the 12V Inverter, you
  would still need to provide power to the microcontroller side. One
  solution with your 12V wall adapter to provide power to the 12V
  inverter and Atmega328P is to get a barrel jack adapter to 2 pin JST
  adapter [ https://www.sparkfun.com/products/8734 ], thus connecting
  the 12V wall adapter to the “BATT IN.” This is assuming that your wall
  adapter is using a center positive barrel jack.
From there you can connect the 2 pin JST labeled “DC Out” to the 12V
  inverter’s input voltage. To connect, I recommend using the male DC
  barrel jack adapter [ https://www.sparkfun.com/products/10287 ] and a
  2pin JSt jumper wire [ https://www.sparkfun.com/products/8670 or
  https://www.sparkfun.com/products/8671 ]. You will need to wire strip
  the cable to be able to connect it to the screw terminals.
Lastly, you would need to add a solder jumper to SJ1 so that you
  bypass the voltage regulator between your external power (“BATT IN”)
  to provide power to the inverter’s “DC OUT”. This will provide power
  to your 12V inverter’s input.

Warning: if SJ1 is closed, inverter will see 5V with FTDI plugged in and switch at USB


text:
blink a Grove - RGB LED Stick
I am trying to blink a Grove - RGB LED Stick (10 - WS2813 Mini 3535) with this code:
#include "FastLED.h"

int ledState = LOW;       // ledState used to set the LED
long previousMillis = 0;  // will store last time LED was updated
long interval = 1000;     // interval at which to blink (milliseconds)

#define NUM_LEDS 10
CRGB myLeds[NUM_LEDS];

void setup() {
  FastLED.addLeds<NEOPIXEL, 4>(myLeds, NUM_LEDS);
}

void loop() {
  unsigned long currentMillis = millis();
  FastLED.setBrightness(25);

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      for (int i = 0; i < NUM_LEDS; i++) {
        myLeds[i] = CRGB::White;
        FastLED.show();
      }
    } else {
      for (int i = 0; i < NUM_LEDS; i++) {
        myLeds[i] = CRGB::Black;
        FastLED.show();
      }
    }
  }
}

Any idea why it does not blink?
Thanks

Your code sets the LEDs color depending on the value of ledState, but its value is never updated after initialization, so your LEDs remain white.

Thanks. Added the ledState = HIGH; and ledState = LOW;

@dkin did it now work with adding this?

Yes. Any other idea/comment is always welcome

Well, if the correction of a coding error, which was pointed out by @StarCat , solved the original problem then StarCat should convert the comment into an answer. Failing that, after waiting a reasonable period, the OP should write the answer.

In your code, you define the global variable ledState and initialize it to the value "LOW".
In the loop() function, the ledState variable is used to determine the (next) state of the LED once every 1000 milliseconds, like this:
...
// if the LED is off turn it on and vice-versa:
if (ledState == LOW) {
  for (int i = 0; i < NUM_LEDS; i++) {
    myLeds[i] = CRGB::White;
    FastLED.show();
  }
} else {
  for (int i = 0; i < NUM_LEDS; i++) {
    myLeds[i] = CRGB::Black;
    FastLED.show();
  }
}
...

However, since your code does not change value of ledState to reflect the new state of the LED array, the next time the above if (...) comparison is run, the outcome is the same and the color of the LEDs not be changed.
The simplest change to make your LEDs blink as you intended, would be to change the above piece of code to the following:
...
// if the LED is off turn it on and vice-versa:
if (ledState == LOW) {
  for (int i = 0; i < NUM_LEDS; i++) {
    myLeds[i] = CRGB::White;
    FastLED.show();
    ledState = HIGH;
  }
} else {
  for (int i = 0; i < NUM_LEDS; i++) {
    myLeds[i] = CRGB::Black;
    FastLED.show();
  }
  ledState = LOW;
}
...

An alternative (arguably more elegant) solution would be to declare ledState as a boolean (true/false) variable so that you can further simplify your code:
#include "FastLED.h"

bool ledState = false;    // ledState used to set the LED
long previousMillis = 0;  // will store last time LED was updated
long interval = 1000;     // interval at which to blink (milliseconds)

#define NUM_LEDS 10
CRGB myLeds[NUM_LEDS];

void setup() {
  FastLED.addLeds<NEOPIXEL, 4>(myLeds, NUM_LEDS);
}

void loop() {
  unsigned long currentMillis = millis();
  FastLED.setBrightness(25);

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (!ledState) {
      for (int i = 0; i < NUM_LEDS; i++) {
        myLeds[i] = CRGB::White;
        FastLED.show();
      }
    } else {
      for (int i = 0; i < NUM_LEDS; i++) {
        myLeds[i] = CRGB::Black;
        FastLED.show();
      }
    }
    ledState = !ledState;    // make ledState reflect the new LED state

  }
}


text:
Is there any reason not to solder power leads to the lugs for the power in socket on the reverse side of a mega 2560 rev 3 board?
I have a very tight space for a project that requires a mega board , the "power in" plug takes it over the space available. Are there safety or other concerns soldering to the lugs for the "power in" socket on the reverse of a mega 2560 rev 3 board board? the board is fitted with an elctrofreaks TFT LCD MEGA SHIELD v2.2 and a TFT_320QVT LCD screen. (the elctrofreaks mega shield uses vin pin)  1 other PWM  pin is used  and an esP8266 board on a uart channel The power  is from a regulated power supply. If  I do this, am I correct that the regulator and polyfuse will still be used?

You could also use the Vin pin. But using the underside of the barrel, has the added advantage of first going through a (reverse polarity protection) diode.

Soldering to the underside of the connector is exactly the same as plugging something in to the connector.
Yes the regulator will be used.
No the polyfuse will not be used - that is in the USB power circuit not the barrel jack power circuit.


text:
Having a bunch of global variables or calculate them on the go on an Arduino, as far as memory is concerned
So I'm new in the arduino world but I have a grasp of object oriented programming, and decided to write a little library for running games on an arduino mega using a display. My question is, I'm creating an "Entity" class (to spawn multiple enemies, players, etc) outside the setup() and the loop() functions, so they dont overwrite themselfs when the program is running (don't know if there's a better way), and I want to store position information, like xPos and yPos, but I need to calculate a lot of other stuff based on those two variables, and creating more variables makes the code more easy to read/write.
But I don't know how this would affect the memory usage or speed, because I ran into some problems earlier when I tried to create a big array, it end up using like 300% of the dynamic memory, so I guess that when I declare a global byte, for example, the arduino allocates the whole memory as if you would use the biggest byte possible.
Sorry for bad english :s

Maybe try to change some constant variables to #define values, because they need nearly no storage. Also a ESP32 has 4MB of flash, with that much more place (the Mega has 256KB) place shouldn't be a problem anymore.

Well, I want to know if should I avoid creating more variables that I know they can be calculated easily, but makes the code more readable, or if I just stick to the most basic variables.

Thanks @PythonSchlange, I'll keep that in mind, I never understood the use of #define till now.

On an Arduino Mega, the “biggest byte possible” is 8-bits wide.

@EdgarBonet, yeah, but I was trying to calculate collisiones just using a 2d array, like simulating every pixel in an array, but a 128 x 64 byte array is too big for the dynamic memory.

Yes, 128 × 64 = 8 K, which is the whole RAM of the Mega. Seems you found yourself the answer to your question.

@EdgarBonet, mmm, looks like it, then I'll try to stick to the most basic variables (in a global scope) when memory usage is critical. But the readability's gonna suck :(

The question is one of time vs. space.  If time is more important then use up memory to hold the values.  If memory is more important then you use some time to recalculate things each time.  Only you really know what your project does and what its needs are.  There simply is not one right answer to this question.

On your collision issue: You might have to think of another algorithm, that works with less RAM but caches results. -- That is what I find satisfactory in embedded control: The need to think instead of mindlessly using a lot of resources.


text:
Sensor that detects when metal sieve is clogged with debris
I'm a newbie here and would really appreciate all kinds of suggestions and answers from the experts here.
I am trying to make a small grey water recycling system project, and for the my primary filtration process tank, I will be using a combination of Metal Sieve and Cloth filter medium.
The problem is, I will be making the system alert the user when filters are in need of changing and maintenance.

I made a quick sketch of my idea on paint, and as you can see, I am planning to make my grey water collection tank to look that way.
I am thinking of using pressure sensor to sense the change of weight in the sieve and cloth part of the tank for a minimum amount of time so that the system will not confuse water flow weight vs. the weight of the debris on the metal sieve, but I'm thinking that the pressure sensor is not waterproof.
I'm also thinking of like the laser module, and when the light breaks at certain level, meaning there is too much debris that has to be removed.
I also googled load cells or weight sensors, but I'm really sorry I'm new to this, I don't know what is the best sensor to use for my problem.
I'm thinking of a float switch a few inches on top of my metal sieve and cloth and when it does not go on a OFF state for a certain amount if time, then the sieve is clogged, but my tank could overflow..
I need something that, when the sieve is clogged, the tank will no longer accept grey water input to avoid overflow.
It has to be submersible in water too :'(
Is there a type of sensor that is most suitable for my problem?
Thank you so much everyone. Have a nice day.

I'm confused by your drawing.  Where does the grey water enter the system?  At the top?

even though this is a very interesting project, it is not related to the Arduino

@jsotola, I'm sorry, how is it not related to Arduino? I will be using Arduino to control everything, the pumps, the stuff that displays on the LCD, the switches and leds.

@PeterM im sorry, yes the water comes from the top.. and then exits from the hose connected to the pump, which is the blue colored part

@melanieirenedeocampo your question would be unchanged if you planned to use a Raspberry Pi or if you built your own controller ... that makes the Arduino irrelevant, and makes this question not about Arduino

perhaps you could shut off the inflow briefly and weigh the filter

Weighing the filter is the wrong approach, because a few large rocks will weigh a lot and not impede the flow very much.  A lot of fine sand just too large to go through the filter will be a problem.  You should use a pressure measurement as the answers suggest.  The problem is that the pressure drop across the filter is too large.

I would tackle this not from the point of view of the filter, but from the point of view of the water itself.
The water will be impeded by the filter. As the filter gradually clogs that impediment will increase.  The net result will be a slower flow of water through your filter.
There's a number of things you could do to detect that:

Measure the incoming water flow rate and the outgoing water flow rate and calculate the difference.

This would mean having all the water flowing through two flow meters which would complicate your design as the filter will no longer be able to deposit directly into the tank. But when the difference in flow between the in and out sensors gets above a certain point (to be determined by you) then you can safely say that the filter is blocked.

Measure the "backlog" of water. To do this the input portion of the filter will have to be sealed (or largely sealed). Again the filter will impede water flow, and the more it's clogged the more it impedes. Once the impediment becomes too high the water will start "backing up" up the input pipe as it can't get through the filter fast enough. At this time you can detect that rise in water level with a float switch.

You'd have a simpler design now, as the filter can deposit straight into the tank. Whether you want to detect the rise in water level in the incoming pipe itself or in the gap between the filter and where the pipe comes in depends largely on the size of your filter. With a large filter it may be better to have a smaller space at the top and measure in the pipe. That will "amplify" the level rise and make it easier to detect.

"The net result will be a slower flow of water through your filter." Actually, IIRC, the result of constricting the area that water flows through will increase its speed but decrease its pressure. https://en.wikipedia.org/wiki/Bernoulli%27s_principle

@nick012000 I do electronics, not fluid dynamics. All I know is when my sink gets blocked it backs up and takes longer to empty. What mechanics that's due to I neither know nor care about, but it does happen. I can prove it.

Have you considered a Differential Pressure Sensor, They can be gotten for a few dollars complete with the basic electronics and drift compensation on board.  Try looking for: nxp pressure sensor for a start. These will interface to the Arduino A/D.  I use an absolute one for barometric pressure and a differential to measure the air pressure my fish pond, this tells me if the air line is open or broken.

You could probably improve this answer by discussing Bernoulli's Principle and explaining why there's a drop in pressure.

I am measuring differential pressure not flow. That is a common method of measuring filters to determine when they are due to be changed and or cleaned. The Metal Sieve and Cloth filter medium is the filter.

It seems to me what you want to detect is when the filter starts backing up and the flow of water out of the filter can't keep up with the in-flow. That will let you turn off the in-flow before the tank overflows.
So put a float switch or other level sensing switch on the space above the filter. Set it so it trips when the water standing on top of the filter gets close to the top of the tank. If the filter gets clogged and the water can't flow through fast enough, the water level on top of the filter will start to rise, and when it gets high enough, the level sensor will trip and your Arduino can shut off the flow of gray water into the filter tank.


text:
BLE library for Beetle Bluno BLE with AVR architecture (ATmega328)
When I try to #include <ArduinoBLE.h> in my Arduino program, I get the error:

WARNING: library ArduinoBLE claims to run on samd, megaavr, mbed, apollo3, mbed_nano, mbed_portenta architecture(s) and may be incompatible with your current board which runs on avr architecture(s).

Apart from potentially trying to import an incompatible library, am I doing something wrong? If not, are there any Arduino libraries for AVR architectures that will allow me to transfer data through Bluetooth via dealing with Services, Characteristics, Descriptors, etc.?
The Beetle Bluno BLE board is based on:

ICSP1: ATmega 328P
ICSP2: CC2540

ArduinoBLE is not compatible with CC2540. the CC2540 on Bluno Beetle has AT commands

@Juraj thanks, how can AT commands help me here?

The device is not an Arduino device (Uno, Mega, Nano, Mkr, etc) and ArduinoBLE was made only for Arduino devices with built-in Bluetooth.

it is an Arduino, just the BLE IC is not supported by the ArduinoBLE library


text:
How many ADS1115 ADCs can I connect to a single Arduino Mega 2560
I know we can connect 4 ADS1115s to an Arduino Mega 2560.
Is there any limit on the number of ADS1115s we can connect to the Mega giving each a different address? I have to connect at least 36 ADS1115s.

you could try connecting all 36 ... pull one of 36 address lines high and talk to that one selected device

256(+?)
With 8 TCA9548A 1-to-8 I2C Multiplexers on different I2C addresses, it is a multiplication problem: You can expand the Arduino Mega's I2C port on Digital Pins 20&21 to 8 multiplexers *  8 multiplexer ports * 8 ADS1115 addresses to 256.
It might be possible to go much further if you can wire and code multiple levels of multiplexers.


text:
Sampling rate too slow
I have an Arduino Nano connected to an Adafruit H3LIS331 accelerometer. The sampling is initiated by a button press, which sets a delay to prepare for the measurement, and then the sampling begins. The defined sampling rate is 1 kHz. However, when reading the values from the serial monitor using PySerial, I get approximately 350 samples per second.
Code:
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_H3LIS331.h>
#include <Adafruit_Sensor.h>

// Button pin
#define SWITCH 8

const unsigned long REPETITION_INTERVAL = 1000; // repetition time in milliseconds, 6000ms is 6 seconds

// Initiate H3LIS331 library
Adafruit_H3LIS331 lis = Adafruit_H3LIS331();

void setup(void) {
  Serial.begin(115200);          // Open Serial Monitor
  while (!Serial) delay(10);

  if (! lis.begin_I2C()) {
    Serial.println("Couldnt start H3LIS331 sensor!");
    while (1) yield();
  }

  Serial.println("H3LIS331 found!");

  lis.setRange(H3LIS331_RANGE_400_G);   // Set range of possibe 100, 200, or 400 G! In our case 400g
  Serial.print("Range set to: ");

  switch (lis.getRange()) {
    case H3LIS331_RANGE_100_G: Serial.println("100 g"); break;
    case H3LIS331_RANGE_200_G: Serial.println("200 g"); break;
    case H3LIS331_RANGE_400_G: Serial.println("400 g"); break;
  }

  lis.setDataRate(LIS331_DATARATE_1000_HZ);  // Set data rate/time resolution to 1000Hz
  Serial.print("Data rate set to: ");

  switch (lis.getDataRate()) {
    case LIS331_DATARATE_POWERDOWN: Serial.println("Powered Down"); break;
    case LIS331_DATARATE_50_HZ: Serial.println("50 Hz"); break;
    case LIS331_DATARATE_100_HZ: Serial.println("100 Hz"); break;
    case LIS331_DATARATE_400_HZ: Serial.println("400 Hz"); break;
    case LIS331_DATARATE_1000_HZ: Serial.println("1000 Hz"); break;
    case LIS331_DATARATE_LOWPOWER_0_5_HZ: Serial.println("0.5 Hz Low Power"); break;
    case LIS331_DATARATE_LOWPOWER_1_HZ: Serial.println("1 Hz Low Power"); break;
    case LIS331_DATARATE_LOWPOWER_2_HZ: Serial.println("2 Hz Low Power"); break;
    case LIS331_DATARATE_LOWPOWER_5_HZ: Serial.println("5 Hz Low Power"); break;
    case LIS331_DATARATE_LOWPOWER_10_HZ: Serial.println("10 Hz Low Power"); break;
  }
}

void loop() {
  int buttonPressed = digitalRead(SWITCH);

  // If the button pressed
  if (buttonPressed) {
    Serial.println("5 seconds preparation...");

    // Wait 5 seconds (5000 milliseconds) for the measurement to take effect
    delay(5000);

    Serial.println("Measurement Started");
    unsigned long startTime = millis() + REPETITION_INTERVAL;
    while(startTime >= millis()) {
      // Get a new sensor event, normalized
      sensors_event_t event;
      lis.getEvent(&event);

      // Based the range of the H3LIS331, display the results measured in g
      Serial.print("\t\tX:"); Serial.print(event.acceleration.x / SENSORS_GRAVITY_STANDARD);
      Serial.print(" \tY:"); Serial.print(event.acceleration.y / SENSORS_GRAVITY_STANDARD);
      Serial.print(" \tZ:"); Serial.println(event.acceleration.z / SENSORS_GRAVITY_STANDARD);
    }
    Serial.println("Measurement Ended");
  }
}

How can I speed this up?

You can speed it up by not printing while you sample.

@StarCat Thanks! How can I save the data without printing it?

how do you save startTime?

please copy the content of the  serial monitor and paste it into your question ... format as code

@StarCat is likely correct. Also, understand millis() will eventually roll over and when it does your code will run for a long long time before exiting. Consider storing all your samples in an array and printing it out after sampling is completed.

Thaks you all for the comments.
@starCat, i didn't mention that i do not have and sd card on the arduino nano. How can store the data?


text:
Wemos mini pro switch power from servo with mosfet bs170
I got a servo connected to a wemos/arduino with a capacitor(470uf). Before I didn`t use a cap.
Now with the cap the device use to much power while sleeping(capacitor on the servo). I want to switch off the power to the servo with a MOSFET. I tried this with a BS170 N channel MOSFET. There is a youtube movie with the same settings except for the mainboard. They use an Arduino uno instead a wemos.
When I test the circuit with a led everything is working. When I use a servo instead a led, nothing happen. There is a little sound from the servo(I think not enough voltage).
When I check the voltage without anything hooked on the drain of the mosfet the output is perfect(5V). If I connect a led or a servo the voltage will drop to 3v.
Wemos mini pro has 3.3v output on the gpio pins.
Can someone explain me what I doing wrong? I saw and read some articles about Mosfet. I think it`s not clear enough for me.

Please show your schematic.

Schematic looks OK.  However, I'd choose a MOSFET with a lower R(DSON) and a lower V(GS) threshold.

My supposition:
The MOSFET's R(DSON) is too high and causing a large voltage drop.
A servo uses more current than a little LED.  That current passing through the MOSFET, with an R(DSON) of potentially up to 5Ω, reduces the voltage available to the servo, causing it to not work. Further more, ground for the servo is raised up above the real ground level adding an offset into the logic levels that could cause communication issues.
Suggestion: Pick a MOSFET with a lower R(DSON) (ideally measured in the milli-ohms), and a lower V(GS) threshold (something around 1-2V max would be good).


text:
Sleep power down mode with change interrupt
I want to use to use an IR sensor as an interrupt to wake up my Arduino Uno R3 from the deep sleep power mode and then go back to sleep after changing the state of the relay.
Lets say if I press a button on the remote and the relay is on LOW mode, the relay is turned to HIGH mode and vice versa.
#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <IRremote.h>

/* Sleep Demo
------------

int relayPin = 8;            // LED connected to digital pin 13
int irPin = 2;            // active LOW, ground this pin momentary to wake up
int sleepStatus = 0;        // variable to store a request for sleep
volatile byte state = LOW;

IRrecv irrecv(irPin);
decode_results results;

void setup()
{
  pinMode(relayPin, OUTPUT);         // sets the digital pin as output
  pinMode(irPin, INPUT);
  irrecv.enableIRIn(); // Start the receiver

  /* Now is time to enable a interrupt. In the function call
     attachInterrupt(A, B, C)
     A   can be either 0 or 1 for interrupts on pin 2 or 3.

     B   Name of a function you want to execute while in interrupt A.

     C   Trigger mode of the interrupt pin. can be:
                 LOW        a low level trigger
                 CHANGE     a change in level trigger
                 RISING     a rising edge of a level trigger
                 FALLING    a falling edge of a level trigger

     In all but the IDLE sleep modes only LOW can be used.
  */

  attachInterrupt(0, wakeUpNow, CHANGE); // use interrupt 0 (pin 2) and run function
  // wakeUpNow when pin 2 gets LOW
}

void sleepNow()         // here we put the arduino to sleep
{
  /* Now is the time to set the sleep mode. In the Atmega8 datasheet
     http://www.atmel.com/dyn/resources/prod_documents/doc2486.pdf on page 35
     there is a list of sleep modes which explains which clocks and
     wake up sources are available in which sleep modus.

     In the avr/sleep.h file, the call names of these sleep modus are to be found:

     The 5 different modes are:
         SLEEP_MODE_IDLE         -the least power savings
         SLEEP_MODE_ADC
         SLEEP_MODE_PWR_SAVE
         SLEEP_MODE_STANDBY
         SLEEP_MODE_PWR_DOWN     -the most power savings

     For now, we want as much power savings as possible,
     so we choose the according sleep modus: SLEEP_MODE_PWR_DOWN

  */
  set_sleep_mode(SLEEP_MODE_IDLE);   // sleep mode is set here

  sleep_enable();              // enables the sleep bit in the mcucr register
  // so sleep is possible. just a safety pin

  /* Now is time to enable a interrupt. we do it here so an
     accidentally pushed interrupt button doesn't interrupt
     our running program. if you want to be able to run
     interrupt code besides the sleep function, place it in
     setup() for example.

     In the function call attachInterrupt(A, B, C)
     A   can be either 0 or 1 for interrupts on pin 2 or 3.

     B   Name of a function you want to execute at interrupt for A.

     C   Trigger mode of the interrupt pin. can be:
                 LOW        a low level triggers
                 CHANGE     a change in level triggers
                 RISING     a rising edge of a level triggers
                 FALLING    a falling edge of a level triggers

     In all but the IDLE sleep modes only LOW can be used.
  */

  attachInterrupt(0, wakeUpNow, CHANGE); // use interrupt 0 (pin 2) and run function
  // wakeUpNow when pin 2 gets LOW

  sleep_mode();                // here the device is actually put to sleep!!
  //

  sleep_disable();             // first thing after waking from sleep:
  // disable sleep...
  detachInterrupt(0);          // disables interrupt 0 on pin 2 so the
  // wakeUpNow code will not be executed
  // during normal running time.
  delay(1000);                 // wat 2 sec. so humans can notice the
  // interrupt.
  // LED to show the interrupt is handled
}

void wakeUpNow()        // here the interrupt is handled after wakeup
{
  //execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  if (irrecv.decode(&results)) {
    if (results.value == 0xff629d) {
      state = !state;
      digitalWrite(relayPin, state);
    }
  }
}

void loop()
{

  sleepNow();                      // sleep function called here
}

The Arduino never seems to wake up from sleep when I use the CHANGE interrupt. But if I use with the IDLE sleep mode, it is working.
Can somebody please help me how to fix this ?
Also will this code work with an Arduino Pro Mini or an ATTiny45?

You actually don't need to to worry about interrupts at all for this
project. The IRremote library is itself based on a timer interrupt. As
soon as you irrecv.enableIRIn(), you start receiving a continuous
stream of interrupts... in addition to the timer interrupt initially set
up by the Arduino core.
If you want to save some power, you can call sleep_mode() once in your
loop. That's it. No need to sleep_enable() or sleep_disable(), as
these are already taken care of by sleep_mode(). No need to
set_sleep_mode() either, as the default sleep mode (IDLE) is the only
one that is appropriate for you. No need to attachInterrupt(), as you
will be waken up by these timer interrupts anyway.
Removing all the cruft, your posted code would become:
#include <avr/sleep.h>
#include <IRremote.h>

const int relayPin = 8;
const int irPin = 2;
IRrecv irrecv(irPin);

void setup()
{
    pinMode(relayPin, OUTPUT);
    pinMode(irPin, INPUT);
    irrecv.enableIRIn();
}

void loop()
{
    decode_results results;
    if (irrecv.decode(&results)) {
        if (results.value == 0xff629d) {
            static byte state = LOW;
            state = !state;
            digitalWrite(relayPin, state);
        }
        irrecv.resume();
    }

    // Sleep until next interrupt.
    sleep_mode();
}

The Arduino never seems to wake up from sleep when I use the CHANGE interrupt.
  attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function

That's not a CHANGE interrupt, it's a LOW interrupt. Please post code that supports what you say in the question.

void wakeUpNow()        // here the interrupt is handled after wakeup
{
  //execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  if (irrecv.decode(&results)) {
    if (results.value == 0xff629d) {
      Serial.println("UP");
      state = !state;
      digitalWrite(relayPin, state);
    }
  }
}

Don't do serial prints inside an ISR. In particular, a LOW interrupt keeps being called continuously while the interrupt pin is low.

// timers and code using timers (serial.print and more...) will not work here

You even have a comment saying that the code won't work, yet you posted it in your question.

I changed the code accordingly


text:
string.indexOf() always returns a non-zero value
I am developing a hardware project which contains a facility to change the stored password by any user, if he/she knows the current password.The new password is stored in arduino eeprom. In the main screen, if the user enters the current password, door is unlocked from inside. . The issue faced here is that the point where current password is entered by user, it works fine, but I want to check that '#' is not entered by user in the new password which is not performed properly.
Because in the main screen, when user presses '#' key, change password function is called up, where user is asked to enter current password.
Here is the screenshot of the circuit prepared from fritzing.

The code snippet for entering new password is as under.
lcd.clear();
lcd.print("New Passkey:");
lcd.setCursor(0, 1);
while (j < 4)
{
  char key = keypad4x4.getKey();

  if (key)
  {
    new_password[j++] = key;
    lcd.print(key);
    tone(buzzer, 1000, 50);

    if (j == 4)
    {
      lcd.print("4 reached");
      delay(1000);
      new_password[5] = '\0';
      String str = String(new_password);
      if (str.indexOf('#'))    /** this condition comes out to be true always i.e. always returns a non-zero value**/
      {
        tone(buzzer, 200, 700);
        lcd.clear();
        lcd.print("Invalid Entry");  /** It is printed everytime on lcd**/
        delay(2000);
        key = 0;
        changePass();
        break;
      }
      else  /** this block is not entered, so new password is not saved in EEPROM **/
      {
        for (int i = 0; i < 4; i++)
        {
          EEPROM.write(i, new_password[i]);
        }
        lcd.print(" Done......");
        delay(1000);
        break;
      }
    }
  }
}

and
new_password[5] is used to store new password entered by user.
Now, I am using a string variable to store this new password.
I am using  string.indexof() function to identify whether this new password contains a '#' character anywhere in it.But it seems that when I put this in an if block in code, it becomes true everytime.I have added comments at respective positions to highlight the problem faced by me. I have tested this code in Proteus simulator, and actual project too.
So, my issue is this one, even if correct password is entered by user,without '#', then also, string.indexOf('#') condition becomes true(returns a non-zero value everytime) and thus even valid password is not saved in EEPROM.
I guess I was able to explain my query accurately, please go through the code, and tell me where I am wrong, because I have gone through it many times and could not find the exact issue. Thanks in advance

did you check the reference? https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/indexof/

should be if (str.indexOf('#')+1)

Yes, I have checked the reference before using indexOf() in my code, but the +1 thing you mentioned in your comment,I didn't quite understand it. What does it do??

The problem here is that indexOf returns the position of the character in the string, or -1 if it's not found.
In C 0 is false and everything else is true. That includes -1.
However, your usage if String here to just check for one character is incredibly wasteful and should be avoided. Instead, use strchr:
if (strchr(new_password, '#') != NULL) {
    ... contains # ...
}

It really worked....@Majenko✌