If you have in your constructor this:

CD74HC4067::channelSelects[16][4] = ...

then you are trying to assign something into the element at position [16][4]. Thats why it's telling you

  cannot convert '' to 'uint8_t {aka
  unsigned char}'

Anyway - you don't even need that second dimension. You can use binary representation like  0b00001000 ...

And if you'll think about previous line, you don't even need any array, you can do it with simple counter value and getting its bits.

However if you want to rely on this array, the constructor should look like:

CD74HC4067::CD74HC4067() :
  channelSelects {
    { 0,0,0,0 }, // channel 0
    { 1,0,0,0 }, // channel 1
    { 0,1,0,0 }, // channel 2
    { 1,1,0,0 }, // channel 3
    { 0,0,1,0 }, // channel 4
    { 1,0,1,0 }, // channel 5
    { 0,1,1,0 }, // channel 6
    { 1,1,1,0 }, // channel 7
    { 0,0,0,1 }, // channel 8
    { 1,0,0,1 }, // channel 9
    { 0,1,0,1 }, // channel 10
    { 1,1,0,1 }, // channel 11
    { 0,0,1,1 }, // channel 12
    { 1,0,1,1 }, // channel 13
    { 0,1,1,1 }, // channel 14
    { 1,1,1,1 }  // channel 15
  }
{
   // constructor code
}

(maybe one more {} enclosure, I'm not sure right now exactly)

EDIT: I'd go this way (if you need only one or two instances):

// ADC READ channel + Address selection pins
template <uint8_t ADC_Chan, uint8_t Addr0, uint8_t Addr1, uint8_t Addr2, uint8_t Addr3>
class Mux16b {
public:
  void initPins () {
    pinMode(Addr0, OUTPUT);
    pinMode(Addr1, OUTPUT);
    pinMode(Addr2, OUTPUT);
    pinMode(Addr3, OUTPUT);
    pinMode(ADC_Chan, INPUT);
  }

  int readMux(uint8_t channel) {
    digitalWrite(Addr0, channel&1 != 0);
    digitalWrite(Addr1, channel&2 != 0);
    digitalWrite(Addr2, channel&4 != 0);
    digitalWrite(Addr3, channel&8 != 0);
    // maybe some delay to stabilize voltage at the ADC_Chan input ??
    return analogRead(ADC_Chan);
  }

  // not necessary but it's easier to use   mux(10) than mux.readMux(10)
  int operator()(uint8_t channel) { return readMux(channel); }
};

// analogRead from A0, Address pins: 4 9 5 2
Mux16b<A0,4,9,5,2>  mux;

void setup() {
  Serial.begin(115200);
  mux.initPins();
}

void loop() {
  Serial.println(mux.readMux(15));

  Serial.println(mux(12)); // using overloaded operator ()

  delay(5000);
}


Restart sequence of NeoPixel stick with a push button at any time

Firstly, good for you trying to avoid delay().

However your while loop pretty much does exactly what delay() does anyway.

Instead you need to change your way of thinking. Instead of "I want to light LEDs 0 to 15 in sequence" you need to instead think "I have 6 LEDs lit. Now I need to light the 7th".

Each time through the loop, if enough time has passed (check the BlinkWithoutDelay example) then light just one more LED.  Once you have lit all 16 you can then restart your sequence.

And when you know how to restart your sequence at the end you should also know how to restart the sequence when you press a button.

For example loop() might look something like this (untested):

void loop() {
    static uint8_t lednum = 0;
    static uint32_t animTicker = millis();

    if (millis() - animTicker >= 1000) { // Once per second
        animTicker = millis();

        lednum++;
        if (lednum > NUM_LEDS_PER_STRIP) lednum = 0; // This resets the sequence

        // Turn on up to lednum LEDs and turn off the others
        for (uint8_t i = 0; i < NUM_LEDS_PER_STRIP; i++) {
            if (i < lednum) {
                ledStrip[i] = CRGB::Blue;
            } else {
                ledStrip[i] = CRGB::Black;
            }
        }

        FastLED.show();
    }

    buttonState = digitalRead(signalButtonPin);

    if (buttonState != lastButtonState) {
        lastButtonState = buttonState;
        if (buttonState == LOW) {
            lednum = 0;
        }
    }
}

The key there is that the variable lednum contains the number of LEDs that you want to display. Once per second, controlled by millis(), the LEDs are updated to display that number of LEDs.


How do I figure out if my board is approaching end of life?

Unfortunately, there isn't much way to really determine "wear" in the context of solid-state electronics.

Probably the things that are most likely to fail are the electrolytic capacitors and the connectors.

First, if you're using an ATmega CPU for something that could possibly injure someone CONTACT ATMEL AND TALK ABOUT SAFETY PRECAUTIONS. The ATmega CPU used in most of the arduino models is not rated for use in such situations.

In EVERY datasheet:

  Atmel products are not intended, authorized, or warranted for use as components in applications intended to support or sustain life.

Now, realistically, this is probably mostly lawyer repellent, but you should still take appropriate precautions.

Really, while there isn't anything on a common arduino board that really wears out except the connectors, why are you trying to save $30 at a potential huge cost? Just buy a new board.

I'd also strongly reccomend you chose a board with a SMT ATmega328P, since that removes the IC socket contacts from the list of concerns. If possible, also remove the pin-headers, and solder wires to the board directly. Try to minimize connectors, since they are frequent points of failure.


Is it possible to find the time taken by millis?

If you want to know exactly how long something will take, there is only one solution: Look at the disassembly!

Starting with the minimal code:

void setup(){};

volatile uint16_t x;
void loop()
{
  x = millis();

}

This code compiled and then fed into avr-objdump -S produces a documented disassembly. Here are the interesting excerpts:

void loop() produces:

000000a8 <loop>:
  a8:   0e 94 a7 00     call    0x14e   ; 0x14e <millis>
  ac:   60 93 00 01     sts 0x0100, r22
  b0:   70 93 01 01     sts 0x0101, r23
  b4:   80 93 02 01     sts 0x0102, r24
  b8:   90 93 03 01     sts 0x0103, r25
  bc:   08 95           ret

Which is a function call (call), four copies (which copy each of the bytes in the uint32_t return value of millis() (note that the arduino docs call this a long, but they are incorrect to not be explicitly specifying the variable sizes)), and finally the function return.

call requires 4 clock cycles, and each sts requires 2 clock cycles, so we have a minimum of 12 clock cycles just for function call overhead.

Now, lets look at the disassembly of the <millis> function, which is located at 0x14e:

unsigned long millis()
{
    unsigned long m;
    uint8_t oldSREG = SREG;
 14e:   8f b7           in  r24, 0x3f   ; 63

    // disable interrupts while we read timer0_millis or we might get an
    // inconsistent value (e.g. in the middle of a write to timer0_millis)
    cli();
 150:   f8 94           cli
    m = timer0_millis;
 152:   20 91 08 01     lds r18, 0x0108
 156:   30 91 09 01     lds r19, 0x0109
 15a:   40 91 0a 01     lds r20, 0x010A
 15e:   50 91 0b 01     lds r21, 0x010B
    SREG = oldSREG;
 162:   8f bf           out 0x3f, r24   ; 63

    return m;
}
 164:   b9 01           movw    r22, r18
 166:   ca 01           movw    r24, r20
 168:   08 95           ret

As you can see, the millis() function is fairly simple:

in saves the interrupt register settings (1 cycle)
cli turns off the interrupts (1 cycle)
lds copy one of the 4 bytes of the current value of the milli counter into a temporary register (2 clock cycles)
lds Byte 2 (2 clock cycles)
lds Byte 3 (2 clock cycles)
lds Byte 4 (2 clock cycles)
out restore interrupt settings (1 clock cycle)
movw shuffle registers around (1 clock cycle)
movw and again (1 clock cycle)
ret return from subroutine  (4 cycles)

So, if we add them all up, we have a total of 17 clock cycles in the millis() function itself, plus a call overhead of 12, for a total of 29 clock cycles.

Assuming a 16 Mhz clock rate (most arduinos), each clock cycle is 1 / 16e6 seconds, or 0.0000000625 seconds, which is 62.5 nanoseconds. 62.5 ns * 29 = 1.812 microseconds.

Therefore, the total execution time for a single millis() call on most Arduinos will be 1.812 microseconds.

AVR Assembly reference

As a side-note, there is space for optimization here! If you update the unsigned long millis(){} function definition to be inline unsigned long millis(){}, you would remove the call overhead (at the cost of slightly larger code size). Furthermore, it looks like the compiler is doing two unnecessary moves (the two movw calls, but I haven't looked at it that closely).

Really, considering the function call overhead is 5 instructions, and the actual contents of the millis() function is only 6 instructions, I think the millis() function should really be inline by default, but the Arduino codebase is rather poorly optimized.

Here is the full disassemby for anyone interested:

sketch_feb13a.cpp.elf:     file format elf32-avr

Disassembly of section .text:

00000000 <__vectors>:
    SREG = oldSREG;

    return m;
}

unsigned long micros() {
   0:   0c 94 34 00     jmp 0x68    ; 0x68 <__ctors_end>
   4:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
   8:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
   c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  10:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  14:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  18:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  1c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  20:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  24:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  28:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  2c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  30:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  34:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  38:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  3c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  40:   0c 94 5f 00     jmp 0xbe    ; 0xbe <__vector_16>
  44:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  48:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  4c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  50:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  54:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  58:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  5c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  60:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
  64:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>

00000068 <__ctors_end>:
  68:   11 24           eor r1, r1
  6a:   1f be           out 0x3f, r1    ; 63
  6c:   cf ef           ldi r28, 0xFF   ; 255
  6e:   d8 e0           ldi r29, 0x08   ; 8
  70:   de bf           out 0x3e, r29   ; 62
  72:   cd bf           out 0x3d, r28   ; 61

00000074 <__do_copy_data>:
  74:   11 e0           ldi r17, 0x01   ; 1
  76:   a0 e0           ldi r26, 0x00   ; 0
  78:   b1 e0           ldi r27, 0x01   ; 1
  7a:   e2 e0           ldi r30, 0x02   ; 2
  7c:   f2 e0           ldi r31, 0x02   ; 2
  7e:   02 c0           rjmp    .+4         ; 0x84 <.do_copy_data_start>

00000080 <.do_copy_data_loop>:
  80:   05 90           lpm r0, Z+
  82:   0d 92           st  X+, r0

00000084 <.do_copy_data_start>:
  84:   a0 30           cpi r26, 0x00   ; 0
  86:   b1 07           cpc r27, r17
  88:   d9 f7           brne    .-10        ; 0x80 <.do_copy_data_loop>

0000008a <__do_clear_bss>:
  8a:   11 e0           ldi r17, 0x01   ; 1
  8c:   a0 e0           ldi r26, 0x00   ; 0
  8e:   b1 e0           ldi r27, 0x01   ; 1
  90:   01 c0           rjmp    .+2         ; 0x94 <.do_clear_bss_start>

00000092 <.do_clear_bss_loop>:
  92:   1d 92           st  X+, r1

00000094 <.do_clear_bss_start>:
  94:   ad 30           cpi r26, 0x0D   ; 13
  96:   b1 07           cpc r27, r17
  98:   e1 f7           brne    .-8         ; 0x92 <.do_clear_bss_loop>
  9a:   0e 94 f0 00     call    0x1e0   ; 0x1e0 <main>
  9e:   0c 94 ff 00     jmp 0x1fe   ; 0x1fe <_exit>

000000a2 <__bad_interrupt>:
  a2:   0c 94 00 00     jmp 0   ; 0x0 <__vectors>

000000a6 <setup>:
  a6:   08 95           ret

000000a8 <loop>:
  a8:   0e 94 a7 00     call    0x14e   ; 0x14e <millis>
  ac:   60 93 00 01     sts 0x0100, r22
  b0:   70 93 01 01     sts 0x0101, r23
  b4:   80 93 02 01     sts 0x0102, r24
  b8:   90 93 03 01     sts 0x0103, r25
  bc:   08 95           ret

000000be <__vector_16>:
#if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ISR(TIM0_OVF_vect)
#else
ISR(TIMER0_OVF_vect)
#endif
{
  be:   1f 92           push    r1
  c0:   0f 92           push    r0
  c2:   0f b6           in  r0, 0x3f    ; 63
  c4:   0f 92           push    r0
  c6:   11 24           eor r1, r1
  c8:   2f 93           push    r18
  ca:   3f 93           push    r19
  cc:   8f 93           push    r24
  ce:   9f 93           push    r25
  d0:   af 93           push    r26
  d2:   bf 93           push    r27
    // copy these to local variables so they can be stored in registers
    // (volatile variables must be read from memory on every access)
    unsigned long m = timer0_millis;
  d4:   80 91 08 01     lds r24, 0x0108
  d8:   90 91 09 01     lds r25, 0x0109
  dc:   a0 91 0a 01     lds r26, 0x010A
  e0:   b0 91 0b 01     lds r27, 0x010B
    unsigned char f = timer0_fract;
  e4:   30 91 0c 01     lds r19, 0x010C

    m += MILLIS_INC;
  e8:   01 96           adiw    r24, 0x01   ; 1
  ea:   a1 1d           adc r26, r1
  ec:   b1 1d           adc r27, r1
    f += FRACT_INC;
  ee:   23 2f           mov r18, r19
  f0:   2d 5f           subi    r18, 0xFD   ; 253
    if (f >= FRACT_MAX) {
  f2:   2d 37           cpi r18, 0x7D   ; 125
  f4:   20 f0           brcs    .+8         ; 0xfe <__vector_16+0x40>
        f -= FRACT_MAX;
  f6:   2d 57           subi    r18, 0x7D   ; 125
        m += 1;
  f8:   01 96           adiw    r24, 0x01   ; 1
  fa:   a1 1d           adc r26, r1
  fc:   b1 1d           adc r27, r1
    }

    timer0_fract = f;
  fe:   20 93 0c 01     sts 0x010C, r18
    timer0_millis = m;
 102:   80 93 08 01     sts 0x0108, r24
 106:   90 93 09 01     sts 0x0109, r25
 10a:   a0 93 0a 01     sts 0x010A, r26
 10e:   b0 93 0b 01     sts 0x010B, r27
    timer0_overflow_count++;
 112:   80 91 04 01     lds r24, 0x0104
 116:   90 91 05 01     lds r25, 0x0105
 11a:   a0 91 06 01     lds r26, 0x0106
 11e:   b0 91 07 01     lds r27, 0x0107
 122:   01 96           adiw    r24, 0x01   ; 1
 124:   a1 1d           adc r26, r1
 126:   b1 1d           adc r27, r1
 128:   80 93 04 01     sts 0x0104, r24
 12c:   90 93 05 01     sts 0x0105, r25
 130:   a0 93 06 01     sts 0x0106, r26
 134:   b0 93 07 01     sts 0x0107, r27
}
 138:   bf 91           pop r27
 13a:   af 91           pop r26
 13c:   9f 91           pop r25
 13e:   8f 91           pop r24
 140:   3f 91           pop r19
 142:   2f 91           pop r18
 144:   0f 90           pop r0
 146:   0f be           out 0x3f, r0    ; 63
 148:   0f 90           pop r0
 14a:   1f 90           pop r1
 14c:   18 95           reti

0000014e <millis>:

unsigned long millis()
{
    unsigned long m;
    uint8_t oldSREG = SREG;
 14e:   8f b7           in  r24, 0x3f   ; 63

    // disable interrupts while we read timer0_millis or we might get an
    // inconsistent value (e.g. in the middle of a write to timer0_millis)
    cli();
 150:   f8 94           cli
    m = timer0_millis;
 152:   20 91 08 01     lds r18, 0x0108
 156:   30 91 09 01     lds r19, 0x0109
 15a:   40 91 0a 01     lds r20, 0x010A
 15e:   50 91 0b 01     lds r21, 0x010B
    SREG = oldSREG;
 162:   8f bf           out 0x3f, r24   ; 63

    return m;
}
 164:   b9 01           movw    r22, r18
 166:   ca 01           movw    r24, r20
 168:   08 95           ret

0000016a <init>:

void init()
{
    // this needs to be called before setup() or some functions won't
    // work there
    sei();
 16a:   78 94           sei

    // on the ATmega168, timer 0 is also used for fast hardware pwm
    // (using phase-correct PWM would mean that timer 0 overflowed half as often
    // resulting in different millis() behavior on the ATmega8 and ATmega168)
#if defined(TCCR0A) && defined(WGM01)
    sbi(TCCR0A, WGM01);
 16c:   84 b5           in  r24, 0x24   ; 36
 16e:   82 60           ori r24, 0x02   ; 2
 170:   84 bd           out 0x24, r24   ; 36
    sbi(TCCR0A, WGM00);
 172:   84 b5           in  r24, 0x24   ; 36
 174:   81 60           ori r24, 0x01   ; 1
 176:   84 bd           out 0x24, r24   ; 36
    // this combination is for the standard atmega8
    sbi(TCCR0, CS01);
    sbi(TCCR0, CS00);
#elif defined(TCCR0B) && defined(CS01) && defined(CS00)
    // this combination is for the standard 168/328/1280/2560
    sbi(TCCR0B, CS01);
 178:   85 b5           in  r24, 0x25   ; 37
 17a:   82 60           ori r24, 0x02   ; 2
 17c:   85 bd           out 0x25, r24   ; 37
    sbi(TCCR0B, CS00);
 17e:   85 b5           in  r24, 0x25   ; 37
 180:   81 60           ori r24, 0x01   ; 1
 182:   85 bd           out 0x25, r24   ; 37

    // enable timer 0 overflow interrupt
#if defined(TIMSK) && defined(TOIE0)
    sbi(TIMSK, TOIE0);
#elif defined(TIMSK0) && defined(TOIE0)
    sbi(TIMSK0, TOIE0);
 184:   ee e6           ldi r30, 0x6E   ; 110
 186:   f0 e0           ldi r31, 0x00   ; 0
 188:   80 81           ld  r24, Z
 18a:   81 60           ori r24, 0x01   ; 1
 18c:   80 83           st  Z, r24
    // this is better for motors as it ensures an even waveform
    // note, however, that fast pwm mode can achieve a frequency of up
    // 8 MHz (with a 16 MHz clock) at 50% duty cycle

#if defined(TCCR1B) && defined(CS11) && defined(CS10)
    TCCR1B = 0;
 18e:   e1 e8           ldi r30, 0x81   ; 129
 190:   f0 e0           ldi r31, 0x00   ; 0
 192:   10 82           st  Z, r1

    // set timer 1 prescale factor to 64
    sbi(TCCR1B, CS11);
 194:   80 81           ld  r24, Z
 196:   82 60           ori r24, 0x02   ; 2
 198:   80 83           st  Z, r24
#if F_CPU >= 8000000L
    sbi(TCCR1B, CS10);
 19a:   80 81           ld  r24, Z
 19c:   81 60           ori r24, 0x01   ; 1
 19e:   80 83           st  Z, r24
    sbi(TCCR1, CS10);
#endif
#endif
    // put timer 1 in 8-bit phase correct pwm mode
#if defined(TCCR1A) && defined(WGM10)
    sbi(TCCR1A, WGM10);
 1a0:   e0 e8           ldi r30, 0x80   ; 128
 1a2:   f0 e0           ldi r31, 0x00   ; 0
 1a4:   80 81           ld  r24, Z
 1a6:   81 60           ori r24, 0x01   ; 1
 1a8:   80 83           st  Z, r24

    // set timer 2 prescale factor to 64
#if defined(TCCR2) && defined(CS22)
    sbi(TCCR2, CS22);
#elif defined(TCCR2B) && defined(CS22)
    sbi(TCCR2B, CS22);
 1aa:   e1 eb           ldi r30, 0xB1   ; 177
 1ac:   f0 e0           ldi r31, 0x00   ; 0
 1ae:   80 81           ld  r24, Z
 1b0:   84 60           ori r24, 0x04   ; 4
 1b2:   80 83           st  Z, r24

    // configure timer 2 for phase correct pwm (8-bit)
#if defined(TCCR2) && defined(WGM20)
    sbi(TCCR2, WGM20);
#elif defined(TCCR2A) && defined(WGM20)
    sbi(TCCR2A, WGM20);
 1b4:   e0 eb           ldi r30, 0xB0   ; 176
 1b6:   f0 e0           ldi r31, 0x00   ; 0
 1b8:   80 81           ld  r24, Z
 1ba:   81 60           ori r24, 0x01   ; 1
 1bc:   80 83           st  Z, r24
#if defined(ADCSRA)
    // set a2d prescale factor to 128
    // 16 MHz / 128 = 125 KHz, inside the desired 50-200 KHz range.
    // XXX: this will not work properly for other clock speeds, and
    // this code should use F_CPU to determine the prescale factor.
    sbi(ADCSRA, ADPS2);
 1be:   ea e7           ldi r30, 0x7A   ; 122
 1c0:   f0 e0           ldi r31, 0x00   ; 0
 1c2:   80 81           ld  r24, Z
 1c4:   84 60           ori r24, 0x04   ; 4
 1c6:   80 83           st  Z, r24
    sbi(ADCSRA, ADPS1);
 1c8:   80 81           ld  r24, Z
 1ca:   82 60           ori r24, 0x02   ; 2
 1cc:   80 83           st  Z, r24
    sbi(ADCSRA, ADPS0);
 1ce:   80 81           ld  r24, Z
 1d0:   81 60           ori r24, 0x01   ; 1
 1d2:   80 83           st  Z, r24

    // enable a2d conversions
    sbi(ADCSRA, ADEN);
 1d4:   80 81           ld  r24, Z
 1d6:   80 68           ori r24, 0x80   ; 128
 1d8:   80 83           st  Z, r24
    // here so they can be used as normal digital i/o; they will be
    // reconnected in Serial.begin()
#if defined(UCSRB)
    UCSRB = 0;
#elif defined(UCSR0B)
    UCSR0B = 0;
 1da:   10 92 c1 00     sts 0x00C1, r1
#endif
}
 1de:   08 95           ret

000001e0 <main>:
#include <Arduino.h>

int main(void)
 1e0:   cf 93           push    r28
 1e2:   df 93           push    r29
{
    init();
 1e4:   0e 94 b5 00     call    0x16a   ; 0x16a <init>

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();
 1e8:   0e 94 53 00     call    0xa6    ; 0xa6 <setup>

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
 1ec:   c0 e0           ldi r28, 0x00   ; 0
 1ee:   d0 e0           ldi r29, 0x00   ; 0
#endif

    setup();

    for (;;) {
        loop();
 1f0:   0e 94 54 00     call    0xa8    ; 0xa8 <loop>
        if (serialEventRun) serialEventRun();
 1f4:   20 97           sbiw    r28, 0x00   ; 0
 1f6:   e1 f3           breq    .-8         ; 0x1f0 <main+0x10>
 1f8:   0e 94 00 00     call    0   ; 0x0 <__vectors>
 1fc:   f9 cf           rjmp    .-14        ; 0x1f0 <main+0x10>

000001fe <_exit>:
 1fe:   f8 94           cli

00000200 <__stop_program>:
 200:   ff cf           rjmp    .-2         ; 0x200 <__stop_program>


Correct use of interrupt vs monitoring switch

No, an interrupt here would be pointless.

You use an interrupt to detect a change on an input whilst you are doing something else. It's a good way of getting instant (or near instant) notification of something happening.

If you're using the input to start something going when there's nothing happening then you gain nothing other than extra complexity by using an interrupt. You're not doing anything else, and you don't need an instant response, so just polling the input is the simplest option.


I want to send the last 10 minute data via bluetooth

What you want for this project is called a ring buffer. Before
reading the rest of this answer, I suggest you stop and take the time to
carefully read the Wikipedia page I am linking to.

Did you read it? Good! Now, yours is a somewhat special case in that you
don't need to continuously keep track of both a read pointer and a write
pointer: you only need the write pointer, as the read happens all in one
big batch.

Once your ring buffer is full, you will start overwriting the oldest
readings, those that are more than 10 minutes old. When the program
is instructed to dump the data, it will send out the whole buffer,
starting with the cell pointed to by the write pointer (the cell that
holds the oldest data point and was about to be overwritten).

There is one special case to take care of. What if the program gets the
command to dump the data while it has less than 20 readings stored?
You could decide that this is a user error, and it's OK for the program
to give garbage. I suggest, however, that the program should be able to
detect this situation, and then only send the valid data. For this, it
needs to store a boolean variable in order to remember whether the
buffer has been filled or not.

Here is an implementation I propose for such a ring buffer, together
with the functions for adding an item and for dumping all the data
through the serial port:

const uint32_t READING_PERIOD = 30000;  // one reading every 30 s
const int MAX_READINGS = 20;           // 20 readings = 10 min

int readings[MAX_READINGS];  // ring buffer
uint8_t reding_index = 0;    // next available slot
bool readings_full = false;  // did we fill the ring buffer?

static void register_reading(int value) {
    readings[reding_index] = value;
    if (++reding_index >= MAX_READINGS) {
        readings_full = true;
        reding_index = 0;
    }
}

static void dump_readings() {
    // If the buffer is full, then the next avaiable slot is the oldest
    // reading in the buffer.
    if (readings_full) {
        for (int i = reding_index; i < MAX_READINGS; i++)
            Serial.println(readings[i]);
    }
    for (int i = 0; i < reding_index; i++)
        Serial.println(readings[i]);
}

Now the main program is quite simple. You time the data taken using the
technique shown in the Blink without delay tutorial. You don't want
to use delay() because, when the program is delaying, it cannot
respond to your commands. There is one last question remaining: when it
dumps the data, should it forget it? In other words, if you ask it twice
to dump the data, with less that 10 minutes in between, should it
give repeated data the second time, or should it only provide the fresh
data? In the code below I assume the later option, and thus reset the
buffer, but in the end it is your choice:

void setup() {
    Serial.begin(9600);
}

void loop() {
    // Periodically take a reading.
    static uint32_t last_reading_time;
    if (millis() - last_reading_time >= READING_PERIOD) {
        last_reading_time += READING_PERIOD;
        register_reading(analogRead(A0));
    }

    // Dump the data on command.
    if (Serial.read() == 't') {
        dump_readings();
        reding_index = 0;       // reset the buffer
        readings_full = false;  // ditto
    }
}


You can't see non-static member variables in a class like that.  The closest is to make it static, which means you get one and only one copy of the variable across all instances of your class:

class ClassB;
class ClassA {
    public:
        int x;
        void foo();

};
class ClassB {
    public:
        static int bfoo;
};

void ClassA::foo() {
    x = ClassB::bfoo + 1;
}

However I suspect that isn't what you want. I suspect you actually want to see the bfoo value stored in class instance B - so you need to tell you classA instance A what and where B is. To do that you will have to pass it when constructing or during some other setup phase.  If you want A to know B and B to know A you can't easily do it during construction, so you will have to do it at a later stage:

class ClassB;

class ClassA {
    public:
        ClassB *B;
        int fooa;
        void begin(ClassB *b) {
            B = b;
        }
        void foo();
};
class ClassB {
    public:
        ClassA *A;
        int foob;
        void begin(ClassA *a) {
            A = a;
        }
        void foo();
};

void ClassA::foo() {
    fooa = B->foob + 1;
}

void ClassB::foo() {
    foob = A->fooa + 1;
}

ClassA A;
ClassB B;

void setup() {
    A.begin(&B);
    B.begin(&A);
}

void loop() {

}


Many of the square or rectangular LEDs with leads  – that is, not surface mount devices (SMD)  –  that I've seen are intended for use as panel indicator lights, so are not very bright.   On the other hand, among SMD devices square, rectangular, and round lights run the whole gamut of brightness.  Of course many white LEDs, square or round, are extremely bright because of being intended for illumination.

For projecting a beam against a ceiling, adding optics to the LED may be the best approach.  For example, buy some 99¢ flashlights like “Waterproof 3500LM Pocket LED Flashlight Zoomable LED Torch Mini Penlight Light” on ebay, and either add a blue filter in front of the lens or replace the LED with an ultrabright blue LED, using the zoomed-out flashlight lens to concentrate the light.  Also, search for 10° or 15° “PMMA LED lens” on ebay, Amazon, aliexpress, etc.

Note, for determining if any given LED will project a tight bright beam, look at the angles of its beam pattern.    This diagram (from Led Buying tips at sunriseled.us) contrasts the intensity of a 30°-beam LED with that of a 70°-beam LED.  The diagram at left below (from dimmable-gu10.com) is typical of intensity-vs-angle diagrams, which usually are shown on a polar plot like that, with a narrower oval corresponding to a tighter beam.  The diagram at right below shows the same information, in a perhaps more easily comprehended form.


Does NodeMCU have some protection against wrong connections that could kill a computer USB?

Most USB ports are shut down when an over-current event is detected.

There is nothing in a NodeMCU that can prevent an over-current event in the case of things like short circuits. The 5V (or VIN on some versions) pin is directly (or sometimes via a single diode) connected to the 5V pin of the USB. Cause a short on the 5V pin and you cause a short on the USB.

Protection is designed to be at the port level not the device level so that devices don't have to be forced to comply to protection "standards" that would drive up costs and result in devices being non-compliant and risk damaging the computer.

If you find that you are often causing shorts on the 5V pin and killing (albeit temporarily) your USB ports you should change your working practices.

It can be good to always connect your devices to an external powered USB hub instead of directly to your computer. That way if you kill a port you can just unplug the hub and plug it back in again to reset all the ports. No need to reboot your computer.

Cheap hubs often just have a simple PTC fuse instead of proper over-current protection which can actually be more useful for device developers since the port won't be disabled, just the external power shut off.

Most Arduino boards do incorporate a PTC fuse in the USB power circuitry, but NodeMCU and similar boards don't.


Calculate the time since arduino started working for a year

The function millis counts up to about 50 days. However, you can make a software timer with millis of, for example, 1Hz. With a unsigned long that counts the seconds, it is easy to count a year.

It will not be reliable. When the power is off, it starts again. A RTC (Real Time Clock) with its own battery is better.

Are you a good software engineer ? How can you be sure that it will work ?


What minimal resistance should be between an input and output pin not to burn Arduino?

Looking towards the high end of recommended (vs absolute maximum) current and considering Ohm's law at a 5v difference if two outputs are trying to drive each other to opposite values, you would probably get away with as little as 250 ohms.  But in most cases that would needlessly waste power, and in the case of multiple instance you could start totaling towards the limit of power supply current for the chip overall.

Typical values for external pull up resistors are more in the range of 1K-10K though higher is not uncommon - the internal pullup which you can optionally activate by setting the output state of an input pin high has a value of several tens of kilo ohms.  Lower values will consume more power, higher values may be less reliable in a noisy situation.


LiPo + charge/boost circuit vs pre-built "power bank" - contrasting portable power sources

The thing to remember with power banks bought on places like eBay and Amazon is:

THEY LIE ABOUT THE CAPACITY

A typical power bank you would expect to get around 3600mAh from, even though it may say 10000mAh, 50000mAh, 1,000,000,000,000mAh, etc.

The only technical difference between rolling your own circuit and a power bank is the low-current switch-off that many (but not all) of them have.  That switch-off is fine if you are always drawing a good amount of current, but once your device goes to sleep and the current drops right down you'll find the power bank will switch off and your device will never wake up again.

However, with rolling your own system you know what you are getting. You know the capacity of your battery.

One further thing to consider: Do you really need 5V? The majority of electronics run from 3.3V nowadays, and the Arduino is no different. There are Arduino boards designed to run from 3.3V, and even 5V boards can be tweaked to run at 3.3V (albeit slower than normal).

So the ideal solution would be:

A single-cell Li-Poly / Li-Ion giving nominal 3.7V
A Li-Ion charger circuit
A low-dropout or switching regulator with max 400mV dropout.

And no boost circuit needed. Also, no logic level shifting when communicating with 3.3V devices.


I have seen SD cards that do not like this section of code:

  // command to go idle in SPI mode
  while (cardCommand(CMD0, 0) != R1_IDLE_STATE) {
    if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) {
      error(SD_CARD_ERROR_CMD0);
      goto fail;
    }
  }

Some SD cards (mine, of course) seem to need a little quiet time to finish their INIT process.  Adding a delay of <something> made the INIT process complete successfully, first time through the loop.

I'm guessing that the SD card spends so much time handling the repeated CMD0 commands (continuously sent by above loop) that they don't get to spend time on the INIT process.  IIRC, the standard says the card is allowed to take up to 2 seconds to INIT (!).  I can't recall, but I think I tried 150ms or so:

  // command to go idle in SPI mode
  while (cardCommand(CMD0, 0) != R1_IDLE_STATE) {
    delay( 150 ); // let SD get some time to work
    if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) {
      error(SD_CARD_ERROR_CMD0);
      goto fail;
    }
  }

I do recall that reinserting the card would sometimes make it work.  I have suggested this to at least one SD card library maintainer, but I think we're all reluctant to impose a delay on all cards.  OTOH, it is just during ::begin.

It might work for you, though.  The above snippet is from SdSpiCard.cpp, but you may have to go looking for it in other places, depending on which library and version you're using.


What is the correct way to wire a piezzo buzzer with a potentiometer and a button?

You are using the Arduino basically as a power supply (in your wiring). The linked wiring is for PWM (analogWrite). This allows pulse output to generate tone (and volume). Here is a good reference.


Is there a preprocessor constant for memory size

Find the io__.h file for your microcontroller, on Linux it is located in /usr/lib/avr/include/avr, on Windows it will be in a somewhat similar location.

Scroll down to the part that says /* Constants */. There are couple interesting macros defined there, FLASHEND being the one you should be interested in. You can use it for example as follows:

#if FLASHEND > 0x8000
/* Include some extra code when sufficient flash is available. */

#endif


Arduino relay module working in a wrong way

That's how they're designed to work energized is LOW de-energized is HIGH you just need to take this into account when writing your Arduino code


post data from node mcu to my sql database

My corrected code working code:

#include <ESP8266WiFi.h>

const char* ssid = "vathsal";
const char* password = "1234567890";

const char* host = "wwwkprstaffcom.000webhostapp.com";
const int ldr = A0;
int val = 0;
String data;
void setup()
{
  Serial.begin(9600);
  Serial.println();

  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" connected");
}

void loop()
{
  val = analogRead(ldr);
  data = "ldr=";

  data.concat(val);
  WiFiClient client;

  Serial.printf("\n[Connecting to %s ... ", host);
  if (client.connect(host, 80))
  {
    Serial.println("connected]");
    client.println("POST /add.php HTTP/1.1");
    client.println("Host: wwwkprstaffcom.000webhostapp.com");
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.print("Content-Length: ");
    client.println(data.length());
    client.println();
    client.print(data);
    Serial.println(val);
    Serial.println("\n[Disconnected]");
  }
  else
  {
    Serial.println("connection failed!]");
    client.stop();
  }
  delay(5000);
}


Finally, I got it. I have fixed length of data. So, I use a counter to calculate the how many characters are there in my data. Now using the index of this characters, I find out proper data and then store in a different variable.

Below is my code:

#include<LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

String responseOne = "";
String responseTwo = "";
String responseThree = "";
bool begin = false;

int counter = 0;

void setup()
{
  Serial.begin(9600);
  lcd.begin(16, 2);
}

void loop()
{

  while(Serial.available() || !begin)
  {
    char in = Serial.read();

    if (in == '{')
    {
      begin = true;
    }

    if(begin)
    {
      counter++;

      if(counter >= 9 && counter <= 12)   // This gives 0.40
      {
        responseOne += (in);              // 0.40 store in responseOne variable
      }

      if(counter >= 22 && counter <= 25)  // This gives 1.05
      {
        responseTwo += (in);              // 1.05 store in responseTwo
      }

      if(counter >= 36 && counter <= 37)  // This gives 14
      {
        responseThree += (in);            // 14 store in responseThree
      }
    }

    if(in == '}')
    {
        break;
    }
    delay(1);
  }

  float newResponseOne = responseOne.toFloat();  // Convert string into Float
  float newResponseTwo = responseTwo.toFloat();  // Convert string into Float
  int newResponseThree = responseThree.toInt();  // Convert string into Integer

  lcd.setCursor(0, 0);
  lcd.print(newResponseOne);

  lcd.setCursor(8, 0);
  lcd.print(newResponseTwo);

  lcd.setCursor(0, 1);
  lcd.print(newResponseThree);
}


Person (phone) detector that trigger an event esp32 cam

Detecting a phone could be easily done by capturing WiFi probe requests which are sent by phones having at least one saved WiFi network. Note that such requests alone are often enough to identify the person, if their home WiFi SSID is set to something like "Davids_wifi".

Software-wise, this would be much easier to do on Linux (think Raspberry Pi or a similar device) which already have all the network sniffing software like tcpdump, which you would otherwise have to find or implement on ESP32.

I'm leaving out the legal implications of what you're trying to do as I don't know what country you are in, but bear in mind that hidden surveillance may be illegal in some cases.


Since your project is to be battery powered, you want to make your system as efficient as is reasonable.

So I am going to take an approach that ends up improving the efficiency of your project.

The button you describe in your link states :

  This button has a domed red plastic cover with a black retaining ring around it. There's an optional LED included

Further, the LED included has a "built in resistor", so that the LED can operate from 12 volts.

Since you would have to install the "optional LED",  why not purchase a Red LED that operates from lower voltage. You will still need a resistor but you won't need to have a voltage converter.

Example  :  Their LED probably has a 2 volt LED (approximate) that operates at perhaps 20 mA).  This would require a 500 ohm resistor (which they incorporate into the LED).  The power loss (wasted) in the resistor is 0.2 watts (200 mW).

Improved Example :  With LED of about 2 volts operating from 3.3 volt power source.  This would require a 68 ohm resistor.  The power loss in the resistor would be 0.027 watts (27 mW).  A substantial improvement in efficiency.

The manufacturer of the button does not give specifications for the LED (the one with the resistor included).  You should connect their LED to a 12 volt power supply and measure the current drawn.  It is possible their LED draws more current than I have shown in the examples.  This would require a re-calculation of the resistor values.

But in any case, the improvement in efficiency will still exist.


How to explain the need/advantage for volatile in terms of microcontroller instruction flow

Short answer: no, volatile cannot be explained in terms of the
figure you show in your question.

Longer answer: there is no direct link between the meaning of volatile
and the architecture depicted in the figure. If you insist in linking
them together, it is possible to find a very weak and indirect link
as follows:

Volatile is all about preventing the compiler from doing some
optimizations when translating your program to assembly. Looking at the
generated assembly can help understanding the effect of volatile.
When learning the assembly language, the figure you show is helpful
in understanding the assembly instructions themselves.

As you see, the link is indirect, mostly because we are talking about
different abstraction levels. Also, the link is weak because the figure
describes specifically the AVR architecture, whereas volatile applies
to any architectures for which there is a C compiler.

To illustrate the first point above, here is an example program which
shows the effect of volatile:

volatile bool volatile_flag;
bool plain_flag;

void setup()
{
    Serial.begin(9600);
}

void loop()
{
    Serial.print("Waiting for volatile flag... ");
    while (!volatile_flag) ; /* wait */
    Serial.println("done.");

    Serial.print("Waiting for plain flag... ");
    while (!plain_flag) ; /* wait */
    Serial.println("done.");
}

As such, the program is not very interesting, it will just hang on the
first loop. But you can imagine there being some ISR that can set the
flags when some external event happens. Then the wait loops would start
to make sense, as they wait for the external event.

Here is the disassembly of the loop() function:

    Serial.print("Waiting for volatile flag... ");
  ce:   60 e0           ldi r22, 0x00   ; 0
  d0:   71 e0           ldi r23, 0x01   ; 1
  d2:   82 e5           ldi r24, 0x52   ; 82
  d4:   91 e0           ldi r25, 0x01   ; 1
  d6:   0e 94 b3 02     call    0x566   ; 0x566 <Print::print(char const*)>
    while (!volatile_flag) ; /* wait */
  da:   80 91 51 01     lds r24, 0x0151
  de:   88 23           and r24, r24
  e0:   e1 f3           breq    .-8         ; 0xda <loop+0xc>
    Serial.println("done.");
  e2:   6e e1           ldi r22, 0x1E   ; 30
  e4:   71 e0           ldi r23, 0x01   ; 1
  e6:   82 e5           ldi r24, 0x52   ; 82
  e8:   91 e0           ldi r25, 0x01   ; 1
  ea:   0e 94 d0 02     call    0x5a0   ; 0x5a0 <Print::println(char const*)>
    Serial.print("Waiting for plain flag... ");
  ee:   64 e2           ldi r22, 0x24   ; 36
  f0:   71 e0           ldi r23, 0x01   ; 1
  f2:   82 e5           ldi r24, 0x52   ; 82
  f4:   91 e0           ldi r25, 0x01   ; 1
  f6:   0e 94 b3 02     call    0x566   ; 0x566 <Print::print(char const*)>
    while (!plain_flag) ; /* wait */
  fa:   80 91 50 01     lds r24, 0x0150
  fe:   81 11           cpse    r24, r1
 100:   01 c0           rjmp    .+2         ; 0x104 <loop+0x36>
 102:   ff cf           rjmp    .-2         ; 0x102 <loop+0x34>
    Serial.println("done.");
 104:   6e e1           ldi r22, 0x1E   ; 30
 106:   71 e0           ldi r23, 0x01   ; 1
 108:   82 e5           ldi r24, 0x52   ; 82
 10a:   91 e0           ldi r25, 0x01   ; 1
 10c:   0c 94 d0 02     jmp 0x5a0   ; 0x5a0 <Print::println(char const*)>

The important thing to notice is how the compiler implemented the
waiting loops. The first one is essentially

0:  lds r24, volatile_flag  ; load the flag from RAM
    tst r24                 ; test it
    breq 0b                 ; if zero, loop back

whereas the second loop is:

    lds r24, plain_flag     ; load the flag from RAM
    cpse r24, r1            ; if zero, skip the following jump
    rjmp 1f                 ; jump over the next loop
0:  rjmp 0b                 ; infinite loop
1:

You may appreciate the first loop has been translated to assembly in a
very literal way, whereas in the second loop the compiler optimized away
all but the first read of the variable. That could be translated back to
C as

if (!plain_flag) {
    for (;;) ;  // hang in an infinite loop
}

The compiler assumed the flag cannot be changed by some external event,
so there is no point in reading it repeatedly. The volatile keyword
prevents the compiler from making such assumption.

And how is all this related to your figure you may ask? Well, if you
happened to not understand the assembly code above, you could check the
AVR Instruction Set Manual to see what each instruction does,
and that's when the figure becomes helpful.


SPIFFS will always claim to successfully open a file that begins with a slash even if that file does not exist.  Remove the leading slash.


The MKR board connects to computer over native USB support of the MCU. The handling of the USB is done by Arduino core functions linked at build to your sketch.
A consequence of using the native USB port is, if your sketch has a problem, it influences the USB communication. In this case you can activate the bootloader to handle the USB port and the upload. It is done by double clicking the reset button on board.
This applies to other SAMD boards (Zero, M0) and to AVR boards with native USB port (Leonardo, Micro) too.


I would suggest, instead of a valve, a Peristaltic Pump.

In short, it comprises a set of rollers that squeeze a flexible tube and push the fluid along. It has good advantages for food use:

Very easy to clean - only the inside of the tube needs cleaning
Pumped fluid is not in physical contact with the pump mechanism so can't be contaminated.

They are used in many sterile environments - medical, industrial, etc., because they are so easy to keep clean and have no way of contaminating the pumped fluid. They are also good with viscous (sticky, gloopy) fluids like soups and sauces.

They can also deliver precisely measured amounts very easily.


Tools Menu -> Board -> Boards Manager - scroll down to the core and see what version it is.


How do I change the code to be able to use the hardware address instead of the Data, Load and CLK pins?

That is not possible as this is two totally different LED drivers. MAX72XX uses a protocol with those signals, while the dot-matrix LED display uses I2C.

You can always port the library to the dot-matrix. Or rewrite the sketch with the dot-matrix library.

Cheers!


Serial.Write(buf,Len) how to read Serial sended array of byte

You have two issues:

Firstly the transmitter is set to 250000 baud (a non-standard rate) while the receiver is set to 9600 baud. Both need to be set to the same rate.

Secondly the transmitter is constantly sending data and the receiver is constantly reading it, there is no way to ensure the two are synchronized. So your receive buffer could well end up being the end of one set of data and then the start of the next e.g. 3,4,1,2. If all you are sending is the same loop over and over this doesn't matter but for real world data it's an issue. If you have a value which you know will never be in your data (e.g. 0 or 0xff) then you can use that as a start of data marker, if not then things get a little more tricky.


Can't get values of max232 with loopback

SoftwareSerial cannot both send and receive at the same time, as it does receiving inside an ISR, and turns interrupts off when sending. Thus this will never work properly.

I suggest you switch to HardwareSerial. Or, if you want to see the results, send using SoftwareSerial and receive using HardwareSerial. For example:

#include <SoftwareSerial.h>
SoftwareSerial mySerial (10, 11); // RX, TX

void setup ()
  {
  Serial.begin (115200);
  mySerial.begin (115200);
  }  // end of setup

unsigned long lastSend;
char c = ' ';
void loop ()
  {
  // time for another test send?
  if (millis () - lastSend >= 500)
    {
    mySerial.print (c++);
    if (c > 'z')
      {
      c = ' ';
      Serial.println ();
      }
    lastSend = millis ();
    }

  // check for response
  if (Serial.available ())
    Serial.print (char (Serial.read ()));
  }  // end of loop

I tested that as a simple loopback and it worked fine. Connect pin 11 (Tx) to pin 0 (Rx). Disconnect the wire to pin 0 whilst uploading.


Detecting the light source location using multiple photoresistors

The answer from Curt Sampson provides several good design considerations, plus the quite-reasonable suggestion that you run some experiments to characterize your LDRs and their placements.

Note that if you want to know which sensor has the highest reading, a simple find-maximum-value loop will do that, without any sorting:

int maxR = reading[1], maxS=1;
for (byte i=2; i <= nSensors; ++i) {
  if (reading[i] > maxR) {
    maxR = reading[i];
    maxS = i;
  }
}
// Now we know sensor maxS has max reading, maxR

The code above follows the 1–6 numbering scheme given in the question, and assumes that reading[i] stands for the reading from sensor i.

Code below, however, numbers the sensors and their readings from 0 to 5 instead of from 1 to 6, to allow simpler conditions in for loops.  From a programming standpoint, it makes sense to call the first sensor 0 if its data is stored in cell 0.

Finding x, y direction of the light

Assumptions behind the following code are that higher readings indicate more light, and that if necessary some background-lighting calibration has been done, and that background lighting has already been subtracted from readings data.  We also assume that maximum readings are less than (2¹⁵)/N, where N is number of sensors.

The point of the following code is to set two variables, x and y, that represent the relative location of a light source.  For example, if x and y are both positive, the light is above and to the right of the top right LDR.  If  x is negative and  y is near zero, the light is to the left of the middle-left LDR.  If knowing the signs of x and y is adequate for your purpose, then there's no need to do more arithmetic than shown.  On the other hand, if you want to compute some sort of angle, you can use atan2(y, x) to compute the direction of the light, in radians.

int reading[nSensors];
const int xdir[] = { -1, 1, -1, 1, -1,  1}; // x-direction sensor weights
const int ydir[] = {  1, 1,  0, 0, -1, -1}; // y-direction sensor weights
int x=0, y=0;
for (byte i=0; i < nSensors; ++i) {
  x += xdir[i] * reading[i];
  y += ydir[i] * reading[i];
}

Edit 1: Tracking the time a light is on

Issues with light-timing include what levels to start or stop timing at; necessary resolution (milliseconds? minutes?); necessary range (eg, is what happened a minute ago relevant); and when to reset accumulated time data.  It may be simplest to track the on times of all the sensors at the same time, then select one of the times or combine some times.  Do you want the largest time, the newest time, the newest large time, or the time corresponding to the largest light?

For example, the code below tracks light levels that remain high long enough to register, in smoothed averages, as above some threshold.  At intervals, current indications are rotated into bit maps that track the last 16 on-off levels for each LDR, and counts of number-of-ons are updated too.

// Initialization ...
uint16_t expAvg[nSensors]={0};  // Exponential averages over time
uint16_t bitMaps[nSensors]={0}; // Track each sensor's last 16 on-off levels
byte onCounts[nSensors]={0};    // Number of recent times sensor avg > threshold
unsigned long prevMilli=millis();
const int markInterval=50;   // ms interval for recording light levels
const int onThreshold=547*16; // Some light-is-on threshold

// In each pass of loop() ...
for (byte i=0; i < nSensors; ++i)
  expAvg[i] = reading[i] + 15*expAvg[i]; // exponential averaging with 1:16 weight

// In loop(), at intervals ...
if (millis()-prevMilli >=  markInterval) {
  prevMilli = millis();
  for (byte i=0; i < nSensors; ++i) {
    onCounts[i] += (expAvg[i] > onThreshold) - (!(bitMaps[i] & 0x8000));
    bitMaps[i] = (bitMaps[i]<<1) | (expAvg[i] > onThreshold);
  }
}


Relationship between baud rate and the frequency of vibration read using ADXL

Firstly, the datasheet for the accelerometer suggests using >=2Mhz SPI communication rate with 3200 or 1600 Hz output data rate operation.

Since the Arduino SPI library default clock is 4Mhz, the Arduino can handle 3200 Hz sampling, so the maximum frequency you could distinguish would be 1600 Hz.

So the Arduino and accelerometer can detect vibrations up to 1600Hz.

Next, you send the data to your laptop. At 9600 BAUD, you are correct in saying that since the data is 24 bits, it will only update your laptop with the Arduino's measured frequency at 9600/24 = 400 Hz. So 400 times a second the Arduino could tell the laptop what frequency it measures, the measurement having a maximum frequency of 1600 Hz.

For the Arduino to simply pass the raw data to the laptop at 3200 Hz, you would need 24 bits * 3200 Hz = 76800 BAUD minimum.

The measurement data is in any case limited by the accelerometer sampling rate of 3200Hz.


Could someone explain this weird looking code, used to setup timers?

This isn't weird looking. It's what normal MCU code actually looks like.

What you have here is an example of the concept of memory-mapped peripherals. Basically, the MCU hardware has special locations in the SRAM address space of the MCU assigned to it. If you write to these addresses, the bits of the byte written to address n control the behaviour of peripheral m.

Basically, certain banks of memory literally have little wires running from the SRAM cell to the hardware. If you write a "1" to this bit in that byte, it sets this SRAM cell to a logical high, which then turns on some portion of the hardware.

If you look into the headers for the MCU, there are great big tables of keyword<->address mappings. This is how things like TCCR1B etc... are resolved at compile time.

This memory-mapping mechanism is extremely broadly used in MCUs. The ATmega MCU in the arduino use it, as do PIC, ARM, MSP430, STM32 and STM8 MCU series, as well as lots of MCUs I'm not immediately familiar with.

Arduino code is the weird stuff, with functions that access the MCU control registers indirectly. While this is somewhat "nicer" looking, it's also much slower, and uses a lot more program space.

The mysterious constants are all described in great detail in the ATmega328P datasheet, which you really should read if you're interested in doing anything more then occationally toggling pins on an arduino.

Select excerpts from the datasheet linked above:

So, for example, TIMSK1 |= (1 << TOIE1); sets the bit TOIE1 in TIMSK1. This is achieved by shifting binary 1 (0b00000001) to the left by TOIE1 bits, with TOIE1 being defined in a header file as 0. This is then bitwise ORed into the current value of TIMSK1, which effectively set this one bit high.

Looking at the documentation for bit 0 of TIMSK1, we can see it is described as

  When this bit is written to one, and the I-flag in the Status Register
  is set (interrupts globally enabled), the Timer/Counter1 Overflow
  interrupt is enabled. The corresponding Interrupt Vector (See
  ”Interrupts” on page 57) is executed when the TOV1 Flag, located in
  TIFR1, is set.

All the other lines should be interpreted in the same manner.

Some notes:

You may also see things like TIMSK1 |= _BV(TOIE1);. _BV() is a commonly used macro originally from the AVR libc implementation. _BV(TOIE1) is functionally identical to (1 << TOIE1), with the benefit of better readability.

Also, you may also see lines such as: TIMSK1 &= ~(1 << TOIE1); or TIMSK1 &= ~_BV(TOIE1);. This has the opposite function of TIMSK1 |= _BV(TOIE1);, in that it unsets the bit TOIE1 in TIMSK1. This is achieved by taking the bit-mask produced by _BV(TOIE1), performing a bitwise NOT operation on it (~), and then ANDing TIMSK1 by this NOTed value (which is 0b11111110).

Note that in all these cases, the value of things like (1 << TOIE1) or _BV(TOIE1) are fully resolved at compile time, so they functionally reduce to a simple constant, and therefore take no execution time to compute at runtime.

Properly written code will generally have comments inline with the code that detail what the registers being assigned to do. Here is a fairly simple soft-SPI routine I wrote recently:

uint8_t transactByteADC(uint8_t outByte)
{
    // Transfers one byte to the ADC, and receives one byte at the same time
    // does nothing with the chip-select
    // MSB first, data clocked on the rising edge

    uint8_t loopCnt;
    uint8_t retDat = 0;

    for (loopCnt = 0; loopCnt < 8; loopCnt++)
    {
        if (outByte & 0x80)         // if current bit is high
            PORTC |= _BV(ADC_MOSI);     // set data line
        else
            PORTC &= ~(_BV(ADC_MOSI));  // else unset it

        outByte <<= 1;              // and shift the output data over for the next iteration
        retDat <<= 1;               // shift over the data read back

        PORTC |= _BV(ADC_SCK);          // Set the clock high

        if (PINC & _BV(ADC_MISO))       // sample the input line
            retDat |= 0x01;         // and set the bit in the retval if the input is high

        PORTC &= ~(_BV(ADC_SCK));       // set clock low
    }
    return retDat;
}

PORTC is the register that controls the value of output pins within PORTC of the ATmega328P. PINC is the register where the input values of PORTC are available. Fundamentally, things like this are what happen internally when you use the digitalWrite or digitalRead functions. However, there is a look-up operation that converts the arduino "pin numbers" into actual hardware pin numbers, which takes somewhere in the realm of 50 clock cycles. As you can probably guess, if you're trying to go fast, wasting 50 clock cycles on an operation that should only require 1 is a bit ridiculous.

The above function probably takes somewhere in the realm of 100-200 clock cycles to transfer 8 bits. This entails 24 pin-writes, and 8 reads. This is many, many times faster then using the digital{stuff} functions.


What format should i use?

int writeValue(const uint8_t value[], int length);

And what is the best way to cast the Struct to the format?

writeValue((uint8_t *)&myStruct, sizeof(myStruct));


Why are my objects losing their member's values?

You might be running out of RAM. I suggest you change all lines like this:

 Serial.println("SWATBOT SETUP COMPLETE");

to use the F macro like this:

 Serial.println(F("SWATBOT SETUP COMPLETE"));

There seem to be a lot of places you could change.

Also I would not put code (implementation) into the .h files. That belongs in .cpp files. The .h files are for declarations.

Inside a class function, using this-> all the time just makes things look cluttered, eg.

StabilityController::StabilityController(RemoteControl* rc, ROSController* ros, IMUController *imu) {
  this->_rc = rc;
  this->_ros = ros;
  this->_imu = imu;


Are there any advantages to Wifi shields as opposed to a Yun?

There's a number of things to consider that could sway your choice one way or another:

Power consumption

The Uno is a small low-power chip to which you add WiFi. The Yun is an Arduino Leonardo with a WiFi router (like you have on your desk) strapped to the back of it.  The Yun will therefore consume considerably more power than the Uno.

Boot time

The Uno takes about 1 second to boot up - faster (instant) if you remove the bootloader and program it direct with a programmer.  The Yun takes minutes to boot.

Stability

The Uno is a solid state single item. The Yun has an entire operating system with filesystems and things.  It's far more likely that the Yun will corrupt itself through power loss than an Uno will get struck by a stray neutrino.

Cost

Yes, the Yun is cheaper. But is cheap always good?

Remote-ability

The Yun can be completely reprogrammed remotely. A new sketch can be uploaded to the Leonardo portion of it without you even having to be in the same country. The same can't be said for the Uno.

Power

The Linux portion of the Yun is considerably more powerful than any normal Arduino.


How can I loop my code? For example after 30 minutes?

You execute the corresponding function only in the setup() function, which is called once on startup of the ESP. After that the loop() function is called repeatedly. The setup() function is meant to "setup" your code for it's functionality, which is then executed in the loop() function. For example you are begin the Wifi connection and connect to a network in there, because you need the network for your main functionality.

So you have to put the code from readSensor() until (and including) sendDataToServer() into the loop() function. This will execute this code repeatedly.

Then you have to introduce some concept of time, else your code will be executed very fast, effectively flooding your webserver. The easiest way would be to add a call to delay(30000), which would delay the code for 30s. But using delay is not considered good coding style, since it is basically busy waiting and you cannot do anything else during that time.

So to be able to add other functionalities in the future you can implement the time concept with non-blocking code. Take the BlinkWithoutDelay example from the Arduino IDE as reference. It uses the millis() function, which counts the milliseconds since the startup. You save a timestamp of the last execution of your code and wait until the difference between the current time (given by millis()) and your timestamp is greater than 30s. In this time the ESP can do other things, since it still goes through the loop() function undisrupted. Then after the timespan you execute the code and reset the timestamp to the current time.


How to power Arduino only when light is on

For a chip like the basic Arduino's ATmega, you don't really "turn it off" to save power, rather you put it into a low-power sleep mode.

First, make sure you aren't consuming more power than needed normally.  Make sure unused peripherals like the ADC are off.  If your program spends most of its time waiting for external events, try reducing the clock speed either with a slower crystal or the 8 MHz oscillator, and with the clock prescale register.

Next, implement a sleep cycle.  Turn off everything you can, and program a hardware timer to generate an interrupt at some point in the future.  Enter sleep mode, so the processor stops and only the logic in the counter is still running.  When the interrupt fires, the ATmega CPU will wake up and continue operating, at which point you enable the ADC, use a GPIO to drive your light sensor, and take a reading from it.  If it doesn't meet your conditions, turn it all off again and go back to sleep until it's worth checking again.

In low power design you must be very careful of things outside the processor stealing power.  Watch out for any resistors pulling signals, if the signals are actively drive against the resistor.  LEDs are an obvious issue.  Also watch out for voltage regulators which may have high quiescent current.  And finally beware of peripheral chips - a stock Arduino has an entire second processor sitting there in the USB-serial adapter wasting power.  So you will either need to customize the firmware of that to shut down too, or else use a simpler board that doesn't have one (don't just hold it in hardware reset, as the reset pin has an internal pullup which will then consume power).


What electronics should I study to create something like a fridge temperature monitor?

A fridge temperature monitor (or any system that talks to world using some data) will include a sensor (temperature sensor like LM35), a controller (to do calculations, arduino ofcourse) and an output (display, like LCD). The topics you should be aware of, are digital electronics, basic passive components (working of resistor, capacitor etc). And a little arduino programming and lots of logic.


What is the best transmitter/receiver to use with an Arduino RC?

That depends largely what is controlling it

Some options include:

wifi, if you have an expansion board, from a PC or phone (spec says: 66ft/20m)
bluetooth works great, directly from your phone (spec says: 32ft/10m - 320ft/100m)
433mhz ASK transmitter/receiver from another Arduino or other hand-designed circuit (spec says: 100m/320ft)
Infrared receiver - from a TV remote! (range unknown, depends on remote & conditions; would not trust it 10m outside without testing).
Cellphone network - longest range (nationwide!). If you get a cheap android to do some of the work, you can use the phone's compass & gps & extra processing power, as well as the camera(s)!
Remote control. I know you said you lost yours, but in case someone else is looking here, you can hook up an rc receiver to an Arduino fairly easily. https://www.sparkfun.com/tutorials/348 for more info.

Many of these ranges specified will depend on the antenna. If your car can tell it's lost signal, then it can stop; otherwise you have to outrun it, or wait for it to hit a wall.

Edited to include cellphone network, and added ranges to options


Would this PCB work?

Possibly, sometimes, under some conditions. See below.

  Is the spacing of the board/lines to other components/side big enough?

Plenty.

  Should I use a copper/ground fill? Which and why?

For your circuit there is no real electrical reason to use a ground plane. However, many fab houses like you to use at least a copper fill in the empty areas since it means less copper has to be etched off the board, and so their etchant lasts longer before it needs to be replaced.

  Are the rounded-off traces actually better as sharp edges?

Yes. Always try to avoid right-angles. Sharp corners radiate EMI noise, mitred corners radiate a lot less.

  It says: 36mm by 15mm isn't this too small to fit all those components?

Not in the slightest.

  Can I actually use the RESET pin as other functions (without changing fuse bits)?

You can only disable the RESET functionality of the RESET pin using the fuse bits - and then it becomes somewhat difficult to program: you need a HVSP (High Voltage Serial Programmer) to get it back into programming mode again.  This blog post details how it is done.

  Doesn't it need any resistors? I've seen some on the RS485 breakout boards.

Your circuit isn't complete.  There are a couple of things missing that you need to add, and some that you might want to add.

The things that are missing:

Decoupling capacitors (100nF) on the power pins of both chips
You should have one larger (10µF typical) reservoir capacitor at the power entry to the board
(Assuming RESET is enabled) Pullup resistor on the RESET pin

The things you might want to add:

RS-485 bus termination resistors

The latter are optional depending on where in the bus your module is. You need termination resistors at both ends, so it is common to have them on the boards but with jumpers to enable/disable them.


Simple but not fully accurate:

Turn on LED
Delay for the amount of pulse width (e.g. 20)
Turn off LED
Delay 5000 ms - pulse width (20) thus 4980 in this example

However, since turn on/off a LED will also take some time, this will take slightly more than 20 + 4980 = 5000 ms.

Thus better is:

Set time to a variable (use millis function).
Turn on LED
Wait until time >= pulse width
Turn off LED
Wait until time >= 5000


Can I control my Arduino using just a 2.4GHz Wireless Transceiver and a wireless Xbox 360 controller?

Short answer is no, unless you have the machine and tools to do reverse engineering on the xbox controller proprietary 2.4Ghz protocol and you must have xbox 360 itself to see what goes on between Xbox 360 and the xBox controller. The time and money spent on these tools(hardware and software) aren't worth it.

The easiest way to do this is to buy the xbox controller receiver, Arduino USB shield and you can easily use your xbox 360 controller with your Arduino.


How many clients can connect to an ESP32?

The SDK API documentation from Espressif directly notes:

uint8_t max_connection
Max number of stations allowed to connect in, default 4, max 4

EDIT
However, another area of the API documentation (The API Guide) notes:

max_connection
Currently, ESP32 Wi-Fi supports up to 10 Wi-Fi connections. If
max_connection > 10, soft-AP defaults the value to 10.


My outputs are not outputting any current at only two of my pinmodes but work fine on the others

I think the problem is not in the output pin (which you say works elsewhere) but in your calculations. I made a Minimal, Complete, and Verifiable example of the part of the code that does the calculations, testing every possible reading you might have got from analogRead(4) (mainly because I found the calculations code rather obscure). Here it is:

float salinity;
void setup()
  {
  Serial.begin(9600);
  }

void loop()
  {
  for (int analogS=0; analogS < 1024; analogS++)
    {
    Serial.print ("analogS = ");
    Serial.print (analogS);
    salinity = 2.0955*pow(10,-19)*pow(analogS,5.8106)*100.000;
    Serial.print (", Salinity = ");
    Serial.print (salinity);
    float target= (salinity-(salinity-.1)*.60);
    float numer=((((target)*.08585-(salinity)*.08585)/(.1-(.1*.15+salinity*.85)))*60.0);
    float denom= ((.1));
    float valve= ((numer/denom)/10.00);
    Serial.print(",  valve = ");
    Serial.println(valve);
    }
   Serial.flush ();
   exit (1);
  }

Testing that reveals:

analogS = 0, Salinity = 0.00,  valve = 3.64
analogS = 1, Salinity = 0.00,  valve = 3.64
analogS = 2, Salinity = 0.00,  valve = 3.64
analogS = 3, Salinity = 0.00,  valve = 3.64
... some lines omitted ...
analogS = 1016, Salinity = 6.21,  valve = 3.64
analogS = 1017, Salinity = 6.25,  valve = 3.64
analogS = 1018, Salinity = 6.28,  valve = 3.64
analogS = 1019, Salinity = 6.32,  valve = 3.64
analogS = 1020, Salinity = 6.35,  valve = 3.64
analogS = 1021, Salinity = 6.39,  valve = 3.64
analogS = 1022, Salinity = 6.43,  valve = 3.64
analogS = 1023, Salinity = 6.46,  valve = 3.64

As you can see, valve is always 3.64, so you will be doing this:

    digitalWrite(6,HIGH);
    delay(3);
    digitalWrite(6,LOW);

In other words, port 6 will be HIGH for 3 milliseconds, probably too short a time for you to notice. Ditto for port 5.

Also this doesn't do what I suspect you think it does:

if(.096<salinity>.104) {
    delay(5000);
}

That will evaluate .096 < salinity to be 0 or 1. Then it will evaluate:

0 > 0.104
1 > 0.104

This is not what you are intending, I think. Try:

if(salinity < .096 || salinity > .104) {
    delay(5000);
}

If that is what you mean, I can't be sure - maybe you mean the opposite:

if(salinity > .096 && salinity < .104) {
    delay(5000);
}

If you write things out clearly, without trying to do shortcuts, it will be much more obvious what the test really is.


1A will be enough to power you arduino but the total powerconsumtion will depend on the amount of leds that you want to drive. If you follow the instuctable, it should be enoug but it's never a good idea to use your power source at max capacity all the time.

It allows you to connect 2 modules indeed.

Why would you need a voltage divider?


Use Arduino Uno digital pins instead of ESP8266

DDA's answer is perfectly correct.
Like he says you need to check the voltage and use a logic level shifter.

However looking at it from another angle there are a whole range of ESP that have an increasing number of digital pins.  You could look at using an ESP-5, or an ESP-12E, these have different forms and increasing number of digital pins.

You could also look at the Wemos range, I believe there is an UNO form board and there is the Wemos D1-Mini, which has 10 digital and 1 analog.

Running on two boards is usually more of an issue than running on one board, god help you if you have synchronisation issues!


How to hook up an LED strip to an Arduino

Depends on what they are and how much you don't know :-)

I'd suggest starting off by looking at the tutorials for NeoPixels and DotStars on Adafruit's site – that should give you a general idea of how things work. Then take a look at the FastLED library, it supports a large number of LED strips and has some decent examples.

The FastLED examples that will show up in the Arduino IDE after you have installed the library.

Once you've gotten as far as identifying the strip you have and reading some of the basic tutorials and trying out some of the examples you'll either know how to do it or have some much more specific questions to ask.

OK, after looking at the info on Amazon and looking more closely at the strip (and the price). I don't think these are individually addressable LEDs. More likely the RGB lines are grounds. So what you would do is to provide a +12V supply on the 12V line and ground one or more the RGB lines to turn on that LED. You could probably control brightness with PWM (pulse width modulation, turning them on and off quickly). The catch here is that the current draw will be more than the Arduino can sink and it's at 12V – two quick ways to kill your board in one tidy package.

You'll need to do more research on this to get the details right, but I think you could use a transistor to do the switching (to protect your Arduino for the 12 V and from the current necessary to drive the LEDs). You would connect an Arduino pin to the base of the transistor to control it. You'd need to select a transistor that can handle the current of all of the LEDs of that color. As a guess I'd figure 60 mA per LED at full brightness (for each color) – this is based on NeoPixels running at 5 V so I could be way off.

If I'm right that these are not individually addressable then the programming would be relatively easy – just turn on the output to turn on the color.

I'd start off by cutting off a strip of the LEDs to experiment with. Use the 12V supply that came with them and see what happens when you connect 12 V to the 12V line and ground one of the color lines. It doesn't look like there is a resistor to limit current, so you should add one to hold the current down. I think the LEDs would be wired in parallel, so you'd be looking at needing to supply 6 times the individual LED current. To be safe you could start at around 20 mA and use a 100Ω 1W resistor – you can find an LED resistor calculator here, be sure to select the parallel calculation and use a low current to start with to be safe.

Once you know that the strip works the way you think it does, try adding a transistor to control each color. Then when you've got that working, hook up to the Arduino. Just remember that you will also need to respect the Arduino's current and voltage limits on the digital pins.


Maximum signal frequency obtained at the gpios of arduino mega 2560

The maximum fundamental frequency you can generate is fcpu/2 - or 8MHz with the default 16MHz resonator / crystal.

What shape the actual signal is, though, is very much dependant on the load on the IO pin. The IO pin has a specific drive strength which will provide limited current into a load. Any capacitance or inductance within that load causes a change in the slew rate (also known as the rise time or fall time) of the IO pin, which affects the shape of the signal by limiting the highest harmonic frequencies you observe.  At the worst case scenario, you get an almost sine wave (only the fundamental frequency gets through). In general though you get more of a rounded-off square wave:

You can improve that slew rate by adding a buffer with a higher drive strength to the output (assuming your buffer has a high enough bandwidth).  However, the IO pin itself will always have a certain amount of curvature to the signal due to its own internal capacitances.

For generating higher frequencies you are better off using a chip that is designed to operate at higher frequencies.


From Arduino reference on delayMicroseonds:

  Currently, the largest value that will produce an accurate delay is 16383. This could change in future Arduino releases. For delays longer than a few thousand microseconds, you should use delay() instead.

Although the reference does not specify further what happens if delay > 16383, a look at the actual code explains this (in wiring.c):

/* Delay for the given number of microseconds.  Assumes a 1, 8, 12, 16, 20 or 24 MHz clock. */
void delayMicroseconds(unsigned int us)
{
...
#elif F_CPU >= 16000000L
    // for the 16 MHz clock on most Arduino boards

    // for a one-microsecond delay, simply return.  the overhead
    // of the function call takes 14 (16) cycles, which is 1us
    if (us <= 1) return; //  = 3 cycles, (4 when true)

    // the following loop takes 1/4 of a microsecond (4 cycles)
    // per iteration, so execute it four times for each microsecond of
    // delay requested.
    us <<= 2; // x4 us, = 4 cycles

    // account for the time taken in the preceeding commands.
    // we just burned 19 (21) cycles above, remove 5, (5*4=20)
    // us is at least 8 so we can substract 5
    us -= 5; // = 2 cycles,
...

    // busy wait
    __asm__ __volatile__ (
        "1: sbiw %0,1" "\n\t" // 2 cycles
        "brne 1b" : "=w" (us) : "0" (us) // 2 cycles
    );
    // return = 4 cycles
}

The line us <<= 2; explains why us should not exceed 16383, otherwise the left-shifted value will overflow (unsigned int is 16 bits on AVR).

In your situation, (20000-2500) << 2 will not be 70000 or 0x11170 in hexa (that does not fit into unsigned int), hence the result will be truncated to 0x1170 i.e. 4464, which will make the last part of the function (the busy wait) wait for the wrong duration.

In order to fix it, you have to split your second delayMicroseconds in one delay in milliseconds plus one delayMicroseconds:

delay(17);
delayMicroseconds(500);


Find the time between HIGH state & LOW state of push button(switch)

First of all, frarugi87 is right.
Second, why not use this:

finalMillis = millis() - previousMillis;
previousMillis = millis();

Instead of what you wrote.

if (digitalRead(buttonPin) == LOW) {
    buttonPushCounter++;
    Serial.println("on");
    Serial.print("number of button pushes:  ");
    Serial.println(buttonPushCounter);
    finalMillis = millis() - previousMillis;
    previousMillis = millis();
    Serial.println(finalMillis);
    while(digitalRead(buttonPin) == LOW){}
  }

It works great.

Hope it helps.

Yoav


As stated in previous answers, frequency measurement is unlikely to be
reliable because the microphone is going to pick up ambient noise, which
is a combination of many individual frequencies. You want instead to see
how much sound amplitude you have at the specific frequency of the
feeding pump. Fourier analysis seems like the natural tool for the job.

However, a Fourier transform is heavy math, and overkill for your
application. You are only interested in the Fourier amplitude at one
specific frequency. Computing that single amplitude is way easier and
faster than doing a full-fledged Fourier transform.

My preferred method for doing that is called homodyne detection. It
is fast enough to be done in real time by an Arduino Uno sampling at
9.6 kHz. Basically you multiply the input signal by both a sine and
a cosine at the target frequency, then you low-pass filter both
products. The two resulting signals are the real and the imaginary part
of the complex amplitude you are looking for.

Here is a small program of mine that does almost exactly what you are
looking for: homodyne.ino. It is set for one specific frequency
(1 kHz, but it's trivial to change), and you will have to adapt it
to be able to change the target frequency between 4.1 and 2.1 kHz.


The voltage on Vin when you power that board thru USB is not relevant ... Vin is not the pin you are looking for

You clearly have a Lolin NodeMCU (V3) board - the existence of Gnd and VU (looks like VV in your picture!!) between A0 and S3 pins indicates that

In documentaion easily found by searching for Lolin V3 pinout - VU is described a USB power output

Use this pin to connect to JD-VCC on the relays

I've just now successfully done this with a 4 relay board

I would connect (nodemcu -> relay)

3V3 to VCC
VU to JD-VCC
Gnd to Gnd
Dn to INm - i.e. choose a D pin on the NodeMCU and connect to an IN pin on the relay


What board to use to send a text message via an arduino board

The GSM Shield will suit your needs. This is a shield, meaning that is a board that will go on top of another Arduino board (e.g UNO, Leonardo, ..., choose whatever you'll need).

This is what it will look like:

To send SMS you'll also need a working SIM card and the GSM library to program the shield. On the previously linked page there are some tutorials to follow in order to check the basic functioning of the setup.


Loop though array values at end of each for loop cycle

I can't quite make out what your if test is supposed to be doing, but don't you want a loop within a loop? Like this?

uint32_t color[] = {red, green, blue,yellow,teal,magenta};

void pulseUp(uint8_t speed)
  {
  const int fadeAmount = 10; //how much to increase each loop
  for (int currentColor = 0; currentColor < 6; currentColor++)
    {
    for (int i = 0; i < strip.numPixels(); i++)
      { //select all pixels
      strip.setPixelColor(i, color[currentColor]); //set color from our array
      }
    for(int brightness = 100; brightness >= 10; brightness -= fadeAmount)
      { //start pulse for loop
      strip.setBrightness(brightness); //set brightness based on brightness
      strip.show(); // send the changes to the strip
      delay(speed); //wait before running again
      }  // end of brightness loop
    }  // end of colour loop
  }  // end of pulseUp


Voltage changes but digitalRead always HIGH

The problem is that when the button isn't pressed, the voltage at pin D3 is just floating. Since there is nothing attached, the voltage at the pin can be anything. To prevent this, you use a pull-down resistor, so that when the button isn't pressed, the voltage at D3 is pulled to ground, and you will get a LOW using digitalRead.

simulate this circuit – Schematic created using CircuitLab


Your problem is that you are storing your text in an unsigned pointer (uint8_t *)instead of a signed pointer (char *).

If you change all your text types to char * then you can directly use atoi().  If you have a lot to change, though, you can just cast the unsigned pointer into a signed one (and make it const at the same time):

analogWrite(13, atoi((const char *)text));


Firstly, to address your compilation error:

RadioComm rComm();

That is not a constructor, that is a function prototype. When you have no parameters to a constructor you must not include the brackets or it confuses the poor little compiler.

RadioComm rComm;

Now - to address your main question.  Well, there's many ways of doing it, but the way I always tackle this is to have your sketch define the RF24 object and pass it to the library for later use.

In the class definition, in the private section, add:

RF24 *radio;

Then change the constructor to have:

RadioComm(RF24 &r);

The constructor itself would then read:

RadioComm::RadioComm(RF24 &r) {
    radio = &r;
}

Now throughout your library, instead of working with radio.whatever you need to work with radio->whatever since you are now using a pointer to an object not the object itself.

Then in your sketch you need to adjust your constructor to be:

RF24 myRadio(7, 8);
RadioComm rComm(myRadio);

The beauty of this is it decouples the configuration of the RF24 class from the RadioComm class, so you can use the same library in a different situation on a different board with different pins without having to change the library - just change the RF24 constructor in your sketch.

It also gives you direct access to the RF24 class in your sketch so you can do any advanced manual tweaks outside the library should you wish to.


Two of those 10mA come from the ATECC608 crypto chip which idles at 2mA.  That leaves 8mA for you to track down.

The WiFi-NINA module has multiple "sleep" modes that range from 30mA down to 4.5µA. Since you can't be in the 30mA "modem sleep" mode (it's too high for your measurements) I suspect it enables "light sleep" at 800µA.

The switching regulator uses 200µA.  So those two together probably account for 1mA in total, leaving you 7mA more to find.

The accelerometer can be up to 1.25mA. I'll assume that since you don't mention it, you haven't set that to "power down" mode.  5.75mA left.

The main MCU is actually quite hungry for power, even when sleeping. Looking at the datasheet it can be between 1.3mA and 2.4mA for the different "idle" modes. Only "standby" mode (where clocks are switched off, etc) drops it below 1mA. With it running a simple program you are looking at 4-6mA.

So it could be that the MCU isn't actually sleeping properly, or that other modules that you think are in low power aren't.

I would suggest manually disabling chips completely (pull their respective RESET pins if available LOW if available) to see how that affects the current.


No. You need a micro-controller at both the sending, and receiving sides.

eBay does set RF remotes with a few buttons. This might be easier and cheaper than making your own.


Atmega1284P 8MHz @ 3.3V?

Yes, you can. Documentation states this is permitted voltage for that frequency:  0 - 10MHz @ 2.7V - 5.5V http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42719-ATmega1284P_Datasheet.pdf

Nick Gammon Arduino bootloaders?

On this page http://www.gammon.com.au/bootloader it states Atmega1284.
In code https://github.com/nickgammon/arduino_sketches/blob/master/Atmega_Self_Read_Signature/Atmega_Self_Read_Signature.ino
there is signature for Atmega1284P so it should work without issues.


Small Arduino with Bluetooth HID interface

Based on the fact that the controller you mentioned has a TI CC2540 Bluetooth processor, I have found a few webpages with information about HID capabilities in the CC2540. Based this the CC2540 should support HID.

Some example code.
Question on the TI forums, with a link to example code.


Sequencing air pistons proble - Help please?

it does not work unless the two sensors close simultaneously

If I understand correctly, the problem is that when your Arduino detects
the second transient signal, the first one is not active anymore, and
your program doesn't remember it has already seen that first signal.
Your Arduino has memory. Thousands of bits of memory! So it can remember
quite a few things. The solution to your problem is to simply make use
of that memory. When you detect a signal that should be useful for a
future decision, take note, store it in a variable. In order for the
variable to be remembered across calls of the function where you set it,
it has to be global. Or, better yet, static local.
Here is how that could look like in code:
// A `static' variable is a variable that remembers its state across
// calls of the function. A global variable would do the same, but
// code is usually clearer when variables are defined close to where
// they are used. A `bool' (for "boolean") is a variable that can only
// be either `true' or `false'.
static bool P5_is_up, P6_is_down;

// If the sensor tells us that the P5 piston went all the way up, take
// note of the fact and remember it.
if (digitalRead(P5_up_sensor) == LOW)
    P5_is_up = true;

// Same for P6 going down.
if (digitalRead(P6_down_sensor) == LOW)
    P6_is_down = true;

// If both pistons finished their travel, we can move to the next
// step. `&&' means "and".
if (P5_is_up && P6_is_down)
    goto_step_3();

You will need to reset those variables to false at the appropriate
time. The example code above doesn't show that as it only deals with the
logic for deciding when it is time to start step 3.
You will probably end up with many of these variables, and lots of
repetitive code. So you will need to structure your program in order to
avoid excessive repetition. But that is not your immediate problem. For
now, try to make the logic work for a single step transition. Once you
get the logic right, you can worry about generalizing the logic to any
transition.


HTTP Post data from Arduino uno using WiFi

Step 1) Upload software serial from example and send AT, you should get reply as AT OK if your connections are correct.
Step 2) Once your connections are correct and if you are uploading the given code then make sure you put your SSID, password, and Server IP which would be the three Strings: HOST, PATH and PORT.

You could alternatively check your server first by sending it a GET or POST using your browser or another software for testing API's(I personally use POSTMAN).

Proceed further once you perform these checks.


Running out of GPIO & looking for suggestions

Two main solutions comes to my mind:

GPIO expander (as you mentioned). It is really easy to use them as digital inputs or outputs. So you can connect button, LED, transistor and maybe even display (you did not specified type of the display, so I assume standard LCD 1602 or 2004 display). You can also connect SPI-CS signals to the expander, but this depends on used libraries...
Auxiliary Arduino e.g. Nano. Arduino can be used for measurement of the temperature and other stuff and NodeMCU for communication. In this case you have to implement some kind of communication between these two boards (SPI, I2C or UART).


How to read OC0A when in CTC (toggle) mode?

If you look into the Arduino Core, you'll find this code for the digital read:

int digitalRead(uint8_t pin)
{
    uint8_t timer = digitalPinToTimer(pin);
    uint8_t bit = digitalPinToBitMask(pin);
    uint8_t port = digitalPinToPort(pin);

    if (port == NOT_A_PIN) return LOW;

    // If the pin that support PWM output, we need to turn it off
    // before getting a digital reading.
    if (timer != NOT_ON_TIMER) turnOffPWM(timer);

    if (*portInputRegister(port) & bit) return HIGH;
    return LOW;
}

That means, disabling PWM is just weird feature in digitalRead.

For reading bitRead(PORTB,3); I'm not so sure if you'll get output value of OC0A, it might be different signal line internally. However you'll get logical level on the port pin by reading bitRead(PINB,3);.


Measurements to prevent breaking an Arduino (or AVR in general):

Precautions

Always remove the USB or adapter plug when you make a change in the circuit.
Check all wires before you switch it on.
Remove or make sure (temporary) loose wires/jumpers do not touch other components or the Arduino (better take them out or 'park' them somewhere else in the breadboard.

Preventing wanted changes resulting in shortcuts

Check again the wires/jumpers you just changed/added.
Make sure no other components/wires/jumpers are touching the Arduino or the breadboard (components).
Clean your desk (if you have space), so if something metal falls/moves, it does not hurt your Arduino.
When changing a shield, always check all wiring to and from it, to your Arduino and the components on the shield itself if needed.

Preventing component shortcuts or overpowering

If you have a wire from a pin to GND or a pin to VSS, always make sure there is either a resistor, or you know why a resistor is not needed. This can also damage directly your Arduino.
Make sure that every component does not get more power than it can handle.
More specific: If you have components using 3.3V, make sure they don't get 5V.
If you have components using 3.3V, make sure they don't get 5V.

Preventing too much heat

Do not just put an Arduino in some case/enclosure ... heat may destroy it, so check before there is enough cooling, add a fan, heatsink or make holes in the enclosure.
If you connect any power source other than USB, check again if it does not generate unnecessary much heat. Unused voltage will generate much heat.

Preventing static electricity

Do not touch components when not needed
If you touch components, make sure you are discharged (touch a radiator, use a wrist band, use an ESD mat, touch grounded wire).

Preventing trivial mistakes

Do not keep drinks next to your Arduino or breadboard (or if you, keep it on the other side).
Watch out for heavy cables not dragging your Arduino from the table/desk ... a USB cable can easily drag an Arduino down.
Watch out when you change cables, not to pull your Arduino from the table/desk.
Keep animals (and people too, to your own judgement) away from your electronics project.


Arduino Nano - How to add multiple sensors? Lithium battery requirements? LED requirements?

Warning: unexperienced experiments even with low voltage may result in dangerous situations. E.g. a typical 10 Ohm resistor on 5 V may get so hot that it starts burning. Make yourself familiar with basic electronics, ideally with the help of someone else who can explain it to you. That person should especially explain the safety instructions first.

Both need to be plugged into the "5v" pin but there seems to be only one.

5 Volts means that this is a voltage source. In an ideal voltage source, you can basically plug in as many components as you like.
A real world voltage source will have a power limit. So you need to find datasheets of all components: the Arduino and the sensors. You can then read how much power the Arduino can provide and you can read how much power the sensors need.
As long as the Arduino can provide more power than the sensors need, that's ok. If it can't stuff will become more complicated, since you'll need another 5 V source and find a way to connect them safely.

Is there a way I could split the pins to add multiple sensors?

One does not split pins, one connects additional wires to a pin.

Will data be taken in simultaneously, and be cross compared with each other for code execution?

The 5V pin is only a voltage source. It will not provide or receive data. You'll need another pin or even multiple other pins to send and receive data.
Sometimes you can only have one device per pin (like a digital out pin), sometimes you can have multiple devices on a few pins (like I²C, SPI, 1Wire).
Typically, you would define what you need and then buy the components so you can build it. This requires a bit of knowledge, so watch some tutorials or introduction videos first.

I dont want to use breadboaard and want to wire directly to chip.

Sorry to be that direct, but at your level of understanding, that's probably not a good idea. Build it on a breadboard first and once it works as intended, make it a soldered circuit.

I need to wire up a rechargeable lithium battery to both projects, I have a 3.7v 1000 Mah lithium battery and a charging port, but do I need more?

As you said your components need 5 V, a 3.7 V battery will not help you at all.
You also need to be careful with the terms: a Mah is something totally different than a mAh. Don't confuse other people by mixing Mega (millions) with milli (1/1000).
Other than that, again, read the data sheets, find out how much current each component needs and sum it up. Then divide the 1000 mAh by the value you found, e.g. 100 mA and you'll get 10 h. That's how long it will last. Maybe it's good for your purpose, maybe not. How should we know that?

I want to make sure it will work with just those 2 parts.

That's great. Just consider all the aspects written in the data sheets of the components and it'll be fine.

I also need to wire a multicolor LED to the board, but do I need any resistors?

Yes. Read the data sheet of the multicolor LED and build a voltage dividor according to the values you find.

Totally new to EE

That's probably true. Maybe you want to start at the beginning and not jump into such a complex project. Get some resistors, measure voltages, measure currents. Make an LED light up. Learn about Ohms law, you'll need it very often. Once you got familiar with the basic stuff, come back to this project.
Honestly, I think you'll destroy components if you start with "a couple of projects".


The issue was resolved by changing my USB cable. the cable in the kit was new and seemed to supply power to the arduino board, but windows was unable to identify the board using that cable. maybe the data wires were damaged.
 in any case, i changed the cable and everything worked smoothly.


The UTFT library has a SmallFont which is 8x12. Not sure whether this is too big for you, but it could be worth looking into. It is ASCII only, so you might want to add some characters yourself. But as someone mentioned, memory is limited, so add sparingly.


Can anyone explain how to use MPL sensor with Arduino MEGA?

Since the device is 3.3V and the Arduino is 5V, you will need a I2C level converter such as the TCA9517. Simply supply the Mega side with 5V and the device side with 3.3V and attach 4.7kohm pull-ups to 5V on the Mega side, and it will convert both SDA and SCL for you. You won't need pull-ups on the device side since it includes pull-ups on the board.

For I1 and I2 (push-pull outputs) you can use either normal level converters or you can use a SN74LVC2G07 along with the pull-ups found on the Mega inputs.


Arduino not detected On El Capitan Public Beta 6

As noted elsewhere, there have been plenty of problems with the CH340 driver and the OSX El Capitan betas, culminating into the driver flat out not working in the latest beta. This is either a bug with OSX or a bug in the driver. I would lean towards this being a bug in the driver, which hasn't been updated since late 2013.

There are other 3rd party drivers that might work on El Capitan. mac-usb-serial.com is the most reliable looking one that I could find, and it does appear to be actively developed. It does cost money, but it is signed (which the mfg. driver isn't) and it has a test utility you can use before purchasing.

The only other options after that are:

Hope that WCH update their driver (don't hold your breath).
Program using an external programmer
Buy an Arduino not using the CH340


if (gameScore >> highScore)

You have the wrong operator there.  >> is right shift, so you are right shifting the gameScore by highScore bits, which if it's more than 16 will end up as 0.

Instead you just want > for greater than:

if (gameScore > highScore)


is a 5V cellphone power supply stabilised?

Yes. USB is a standard. You can even use 5V power packs for portable gizmos.

Caution: Ken Shirrif have a good post about non-original USB chargers and its perils. (A dozen USB chargers in the lab: Apple is very good, but not quite the best). Read them and learn a lot.

I only use the original charger that comes with the cell or tablet (and that usually last longer that the cell or tablet that it comes with). I don't trust any third party USB charger or car adapter after Ken's analysis


Majenko's library works. All praise to Majenko https://github.com/MajenkoLibraries/MCP23S17


Consider using quadrature encoding to detect travel direction using two light beams. A method used in older mechanical mouse pointer devices and track balls. Using an Arduino to decode quadrature encoding is talked about in many places on the web.

Place beam A and beam B such that a chicken waling out of the coop will activate beam B first and beam A second.

Because the activation of beam B occurs first we know the chicken is walking out of the coop.  If beam A occurred first we know the chicken is walking into the coop.

The shape of a chicken is irregular and a chicken may change its mind half way out of the coop.  These and other unexpected anomalies may lead to unexpected results.  Consider supplementing the beams with a PIR sensor outside the coop to confirm there are no chickens left outside.


No programmers available for this board - Programming ESP32 Cam with Ardunio IDE

There are no programmers for ESP32. It only accepts Serial upload over bootloader.
Versions of IDE before 1.8.13 displayed programmers for all board support packages, that is why a programmer could be selected. Now only programmers for package of the selected board are available. But programmers are used only with the "Burn bootloader" or "Upload with programmer" commands, not with standard Serial upload over bootloader.