text:
Weird assembly output
I was taking a look at the disassembly for a loop of mine that seemed to be taking too long and I found these assembly instructions that I don't understand. Why does it load 0 into r25 and then do two adc r25, 25 instructions (which wouldn't do anything since r25 is 0). This is for an ATTiny84 by the way.
EDIT: In general I'm confused about why there are so many instructions required to set DDRA, DDRB, PORTA, and PORTB in the last loop. I feel like an LD to read portOuts[j], OUT to output, and increment of j should be all that's required. I've tried to separate what I think is the relevant part in the disassembly.
void loop() {
  set_sleep_mode(SLEEP_MODE_IDLE);
  button = false;
  DDRA = 0;
  DDRB = 0;
  PORTA = 255;
  PORTB = 255;
  do {
    sleep_mode();
  } while (!button);

//  int digits[4];
//  getTime(digits);
//
//  long lights = calcDisp(digits);
  static const byte highLow[28][2] = {{2, 0}, {2, 1}, {0, 3}, {1, 3}, {1, 0}, {3, 1}, {0, 1},
                                     {0, 2}, {3, 0}, {2, 4}, {3, 4}, {4, 3}, {0, 4}, {4, 0},
                                     {4, 1}, {1, 4}, {1, 5}, {5, 1}, {1, 2}, {5, 3}, {2, 3},
                                     {2, 5}, {5, 2}, {5, 4}, {4, 5}, {3, 5}, {4, 2}, {3, 2}};
  byte portOuts[112];
  byte nLed = 0;
  long lights = 0b00000000000000001111111111111111; // just a constant, for now
  for (byte b = 0; b < 16; ++b) {
    if (bitRead(lights, b)) {
      byte high = highLow[b][0];
      byte low = highLow[b][1];
      byte highA = regs[high][0];
      byte highB = regs[high][1];
      byte lowA = regs[low][0];
      byte lowB = regs[low][1];
      portOuts[4 * nLed] = (highA)|(lowA);
      portOuts[4 * nLed + 1] = (highB)|(lowB);
      portOuts[4 * nLed + 2] = (highA)|(1<<PA6);
      portOuts[4 * nLed + 3] = (highB);
      ++nLed;
    }
  }
  for (byte i = 0; i < 200; ++i) {
    for (byte j = 0; j < nLed * 4;) {
      DDRA = portOuts[j++];
      DDRB = portOuts[j++];
      PORTA = portOuts[j++];
      PORTB = portOuts[j++];
    }
  }

DISASSEMBLY
void loop() {
  set_sleep_mode(SLEEP_MODE_IDLE);
  button = false;
  DDRA = 0;
  DDRB = 0;
  PORTA = 255;
 228:   bb 24           eor     r11, r11
 22a:   ba 94           dec     r11
                                     {2, 5}, {5, 2}, {5, 4}, {4, 5}, {3, 5}, {4, 2}, {3, 2}};
  byte portOuts[112];
  byte nLed = 0;
  long lights = 0b00000000000000001111111111111111; // just a constant, for now
  for (byte b = 0; b < 16; ++b) {
    if (bitRead(lights, b)) {
 22c:   cc 24           eor     r12, r12
 22e:   ca 94           dec     r12
 230:   dc 2c           mov     r13, r12
 232:   e1 2c           mov     r14, r1
 234:   f1 2c           mov     r15, r1
  }
  return lights;
}

void loop() {
  set_sleep_mode(SLEEP_MODE_IDLE);
 236:   85 b7           in      r24, 0x35       ; 53
 238:   87 7e           andi    r24, 0xE7       ; 231
 23a:   85 bf           out     0x35, r24       ; 53
  button = false;
 23c:   10 92 a6 00     sts     0x00A6, r1      ; 0x8000a6 <button>
  DDRA = 0;
 240:   1a ba           out     0x1a, r1        ; 26
  DDRB = 0;
 242:   17 ba           out     0x17, r1        ; 23
  PORTA = 255;
 244:   bb ba           out     0x1b, r11       ; 27
  PORTB = 255;
 246:   b8 ba           out     0x18, r11       ; 24
  do {
    sleep_mode();
 248:   85 b7           in      r24, 0x35       ; 53
 24a:   80 62           ori     r24, 0x20       ; 32
 24c:   85 bf           out     0x35, r24       ; 53
 24e:   88 95           sleep
 250:   85 b7           in      r24, 0x35       ; 53
 252:   8f 7d           andi    r24, 0xDF       ; 223
 254:   85 bf           out     0x35, r24       ; 53
  } while (!button);
 256:   80 91 a6 00     lds     r24, 0x00A6     ; 0x8000a6 <button>
 25a:   88 23           and     r24, r24
 25c:   a9 f3           breq    .-22            ; 0x248 <main+0xec>
 25e:   ac e6           ldi     r26, 0x6C       ; 108
 260:   b0 e0           ldi     r27, 0x00       ; 0
 262:   90 e0           ldi     r25, 0x00       ; 0
 264:   80 e0           ldi     r24, 0x00       ; 0
  static const byte highLow[28][2] = {{2, 0}, {2, 1}, {0, 3}, {1, 3}, {1, 0}, {3, 1}, {0, 1},
                                     {0, 2}, {3, 0}, {2, 4}, {3, 4}, {4, 3}, {0, 4}, {4, 0},
                                     {4, 1}, {1, 4}, {1, 5}, {5, 1}, {1, 2}, {5, 3}, {2, 3},
                                     {2, 5}, {5, 2}, {5, 4}, {4, 5}, {3, 5}, {4, 2}, {3, 2}};
  byte portOuts[112];
  byte nLed = 0;
 266:   60 e0           ldi     r22, 0x00       ; 0
 268:   30 e0           ldi     r19, 0x00       ; 0
 26a:   20 e0           ldi     r18, 0x00       ; 0
 26c:   a9 01           movw    r20, r18
 26e:   44 0f           add     r20, r20
 270:   55 1f           adc     r21, r21
 272:   44 0f           add     r20, r20
 274:   55 1f           adc     r21, r21
  long lights = 0b00000000000000001111111111111111; // just a constant, for now
  for (byte b = 0; b < 16; ++b) {
    if (bitRead(lights, b)) {
 276:   26 01           movw    r4, r12
 278:   37 01           movw    r6, r14
 27a:   08 2e           mov     r0, r24
 27c:   04 c0           rjmp    .+8             ; 0x286 <__stack+0x27>
 27e:   75 94           asr     r7
 280:   67 94           ror     r6
 282:   57 94           ror     r5
 284:   47 94           ror     r4
 286:   0a 94           dec     r0
 288:   d2 f7           brpl    .-12            ; 0x27e <__stack+0x1f>
 28a:   40 fe           sbrs    r4, 0
 28c:   3d c0           rjmp    .+122           ; 0x308 <__stack+0xa9>
      byte high = highLow[b][0];
      byte low = highLow[b][1];
      byte highA = regs[high][0];
 28e:   ec 91           ld      r30, X
 290:   f0 e0           ldi     r31, 0x00       ; 0
 292:   ee 0f           add     r30, r30
 294:   ff 1f           adc     r31, r31
 296:   e0 5a           subi    r30, 0xA0       ; 160
 298:   ff 4f           sbci    r31, 0xFF       ; 255
 29a:   70 81           ld      r23, Z
      byte highB = regs[high][1];
 29c:   a1 80           ldd     r10, Z+1        ; 0x01
      byte lowA = regs[low][0];
 29e:   11 96           adiw    r26, 0x01       ; 1
 2a0:   ec 91           ld      r30, X
 2a2:   11 97           sbiw    r26, 0x01       ; 1
 2a4:   f0 e0           ldi     r31, 0x00       ; 0
      byte lowB = regs[low][1];
 2a6:   ee 0f           add     r30, r30
 2a8:   ff 1f           adc     r31, r31
 2aa:   e0 5a           subi    r30, 0xA0       ; 160
 2ac:   ff 4f           sbci    r31, 0xFF       ; 255
 2ae:   91 80           ldd     r9, Z+1 ; 0x01
      portOuts[4 * nLed] = (highA)|(lowA);
 2b0:   21 e0           ldi     r18, 0x01       ; 1
 2b2:   30 e0           ldi     r19, 0x00       ; 0
 2b4:   2c 0f           add     r18, r28
 2b6:   3d 1f           adc     r19, r29
 2b8:   24 0f           add     r18, r20
 2ba:   35 1f           adc     r19, r21
 2bc:   e0 81           ld      r30, Z
 2be:   7e 2e           mov     r7, r30
 2c0:   77 2a           or      r7, r23
 2c2:   f9 01           movw    r30, r18
 2c4:   70 82           st      Z, r7
      portOuts[4 * nLed + 1] = (highB)|(lowB);
 2c6:   e2 e0           ldi     r30, 0x02       ; 2
 2c8:   f0 e0           ldi     r31, 0x00       ; 0
 2ca:   ec 0f           add     r30, r28
 2cc:   fd 1f           adc     r31, r29
 2ce:   e4 0f           add     r30, r20
 2d0:   f5 1f           adc     r31, r21
 2d2:   2a 2d           mov     r18, r10
 2d4:   29 29           or      r18, r9
 2d6:   20 83           st      Z, r18
      portOuts[4 * nLed + 2] = (highA)|(1<<PA6);
 2d8:   e3 e0           ldi     r30, 0x03       ; 3
 2da:   f0 e0           ldi     r31, 0x00       ; 0
 2dc:   ec 0f           add     r30, r28
 2de:   fd 1f           adc     r31, r29
 2e0:   e4 0f           add     r30, r20
 2e2:   f5 1f           adc     r31, r21
 2e4:   70 64           ori     r23, 0x40       ; 64
 2e6:   70 83           st      Z, r23
      portOuts[4 * nLed + 3] = (highB);
 2e8:   24 e0           ldi     r18, 0x04       ; 4
 2ea:   30 e0           ldi     r19, 0x00       ; 0
 2ec:   2c 0f           add     r18, r28
 2ee:   3d 1f           adc     r19, r29
 2f0:   42 0f           add     r20, r18
 2f2:   53 1f           adc     r21, r19
 2f4:   fa 01           movw    r30, r20
 2f6:   a0 82           st      Z, r10
      ++nLed;
 2f8:   6f 5f           subi    r22, 0xFF       ; 255
 2fa:   26 2f           mov     r18, r22
 2fc:   30 e0           ldi     r19, 0x00       ; 0
 2fe:   a9 01           movw    r20, r18
 300:   44 0f           add     r20, r20
 302:   55 1f           adc     r21, r21
 304:   44 0f           add     r20, r20
 306:   55 1f           adc     r21, r21
 308:   01 96           adiw    r24, 0x01       ; 1
 30a:   12 96           adiw    r26, 0x02       ; 2
                                     {4, 1}, {1, 4}, {1, 5}, {5, 1}, {1, 2}, {5, 3}, {2, 3},
                                     {2, 5}, {5, 2}, {5, 4}, {4, 5}, {3, 5}, {4, 2}, {3, 2}};
  byte portOuts[112];
  byte nLed = 0;
  long lights = 0b00000000000000001111111111111111; // just a constant, for now
  for (byte b = 0; b < 16; ++b) {
 30c:   80 31           cpi     r24, 0x10       ; 16
 30e:   91 05           cpc     r25, r1
 310:   09 f0           breq    .+2             ; 0x314 <__stack+0xb5>
 312:   ac cf           rjmp    .-168           ; 0x26c <__stack+0xd>
 314:   68 ec           ldi     r22, 0xC8       ; 200
      portOuts[4 * nLed + 3] = (highB);
      ++nLed;
    }
  }

####################### START OF RELEVANT SECTION #############################

  for (byte i = 0; i < 200; ++i) {
    for (byte j = 0; j < nLed * 4;) {
 316:   41 15           cp      r20, r1
 318:   51 05           cpc     r21, r1
 31a:   99 f1           breq    .+102           ; 0x382 <__stack+0x123>
 31c:   30 e0           ldi     r19, 0x00       ; 0
 31e:   20 e0           ldi     r18, 0x00       ; 0
 320:   80 e0           ldi     r24, 0x00       ; 0
      DDRA = portOuts[j++];
 322:   e1 e0           ldi     r30, 0x01       ; 1
 324:   f0 e0           ldi     r31, 0x00       ; 0
 326:   ec 0f           add     r30, r28
 328:   fd 1f           adc     r31, r29
 32a:   2e 0f           add     r18, r30
 32c:   3f 1f           adc     r19, r31
 32e:   f9 01           movw    r30, r18
 330:   90 81           ld      r25, Z
 332:   9a bb           out     0x1a, r25       ; 26      STORE IN DDRA
 334:   e1 e0           ldi     r30, 0x01       ; 1
 336:   e8 0f           add     r30, r24
      DDRB = portOuts[j++];
 338:   21 e0           ldi     r18, 0x01       ; 1
 33a:   30 e0           ldi     r19, 0x00       ; 0
 33c:   2c 0f           add     r18, r28
 33e:   3d 1f           adc     r19, r29
 340:   2e 0f           add     r18, r30
 342:   31 1d           adc     r19, r1
 344:   f9 01           movw    r30, r18
 346:   90 81           ld      r25, Z
 348:   97 bb           out     0x17, r25       ; 23      STORE IN DDRB
      PORTA = portOuts[j++];
 34a:   e3 e0           ldi     r30, 0x03       ; 3
 34c:   e8 0f           add     r30, r24
    }
  }
  for (byte i = 0; i < 200; ++i) {
    for (byte j = 0; j < nLed * 4;) {
      DDRA = portOuts[j++];
      DDRB = portOuts[j++];
 34e:   a2 e0           ldi     r26, 0x02       ; 2
 350:   a8 0f           add     r26, r24
      PORTA = portOuts[j++];
 352:   21 e0           ldi     r18, 0x01       ; 1
 354:   30 e0           ldi     r19, 0x00       ; 0
 356:   2c 0f           add     r18, r28
 358:   3d 1f           adc     r19, r29
 35a:   2a 0f           add     r18, r26
 35c:   31 1d           adc     r19, r1
 35e:   d9 01           movw    r26, r18
 360:   9c 91           ld      r25, X
 362:   9b bb           out     0x1b, r25       ; 27      STORE IN PORTA
      PORTB = portOuts[j++];
 364:   8c 5f           subi    r24, 0xFC       ; 252
 366:   21 e0           ldi     r18, 0x01       ; 1
 368:   30 e0           ldi     r19, 0x00       ; 0
 36a:   2c 0f           add     r18, r28
 36c:   3d 1f           adc     r19, r29
 36e:   2e 0f           add     r18, r30
 370:   31 1d           adc     r19, r1
 372:   f9 01           movw    r30, r18
 374:   90 81           ld      r25, Z
 376:   98 bb           out     0x18, r25       ; 24      STORE IN PORTB
      portOuts[4 * nLed + 3] = (highB);
      ++nLed;
    }
  }
  for (byte i = 0; i < 200; ++i) {
    for (byte j = 0; j < nLed * 4;) {
 378:   28 2f           mov     r18, r24
 37a:   30 e0           ldi     r19, 0x00       ; 0
 37c:   24 17           cp      r18, r20
 37e:   35 07           cpc     r19, r21
 380:   84 f2           brlt    .-96            ; 0x322 <__stack+0xc3>   JUMP BACK TO START OF LOOP
 382:   61 50           subi    r22, 0x01       ; 1
      portOuts[4 * nLed + 2] = (highA)|(1<<PA6);
      portOuts[4 * nLed + 3] = (highB);
      ++nLed;
    }
  }
  for (byte i = 0; i < 200; ++i) {
 384:   41 f6           brne    .-112           ; 0x316 <__stack+0xb7>

        setup();

        for (;;) {
                loop();
                if (serialEventRun) serialEventRun();
 386:   01 15           cp      r16, r1
 388:   11 05           cpc     r17, r1
 38a:   09 f4           brne    .+2             ; 0x38e <__stack+0x12f>
 38c:   54 cf           rjmp    .-344           ; 0x236 <main+0xda>
 38e:   38 de           rcall   .-912           ; 0x0 <__vectors>
 390:   52 cf           rjmp    .-348           ; 0x236 <main+0xda>```

Would have to see more code to see what is going on - the compiler can move stuff around so that asm code could be based on source code somewhere else.

which wouldn't do anything since r25 is 0 ... not quite true ... think about what adc does

For example, there could be a jump somewhere to 30e after r25 had been updated to a new value. In this case the ldi r25,0 is just initializing the first pass and it would not be worth it to jump over the initial adds even though they dont do anything on that first pass. .

Also seems like r24 is coming into this block with a useful value, but that code is not shown.

The compiler optimized the computation nLed * 4 into a bit shift, as
Led << 2. It seems nLed is a single byte quantity. However,
nLed * 4 may not fit in one byte, and the semantics of the language
demands that nLed is promoted to an int before the computation. This
is done by extending the variable by a byte of zeros:
    ldi r25, 0

Now the register pair r25:r24 contains nLed extended to 16 bits.
Next step is to shift the whole thing left by two positions. This is
done by repeating this sequence twice:
    lsl r24
    rol r25

The first instruction shifts r24 to the left. The most significant bit
is stored as the carry flag. The second instruction “rotate left through
carry”, is similar to a shift except that the rightmost bit position is
filled by the carry. This is the way to shift a 16-bit value without
loosing a bit.
The instruction lsl and rol are actually aliases of add and adc
respectively. The disassembler does not care about aliases, and
translates the machine code to the most “canonical” instructions, which
is what you see.

Hi Edgar, that's really interesting! I just edited my post to include some additional information. 2 questions is it possible to avoid the promotion and is that what's happening with my j++ lines as well?

@Anubhav: 1. The promotion is demanded by the language, but if you write (byte)(nLed * 4) the compiler may realize it can optimize it out. 2. The statements DDRA = portOuts[j++]; and following require some address calculations. You may get better results by declaring portOuts as static, which would make its address a compile-time constant.

Thanks, that seemed to make it better. What made it really good was doing byte* p = portOuts; outside of my inner loop and then just incrementing that pointer. Now the compiler just generates an LDD and an out as expected.

Simple: adc has three operands. You seem look at it as if it had two :)


text:
Quiescent Current Analog Input ESP8266
I'm planning an ESP8266 project, where I connect a soil moisture sensor to an ESP8266 chip (only the chip, not a board like the NodeMCU) (Analog Input). Since the whole setup will be battery-powered, I'm trying to minimize the quiescent current as much as possible. Now my question is: is there a quiescent current through the analog input pin of the ESP8266? and if yes, how large is this current approximately?
Thanks in advance

If your moisture sensor uses dc, consider watching this video: https://www.youtube.com/watch?v=udmJyncDvw0

That depends on if you're using a NodeMCU or a "naked" ESP8266.
The NodeMCU has a fixed voltage divider with 220K/100K resistors to ground, contributing about 10 µA to quiescent current (plus the much smaller current caused by the ADC input impedance).
If you're using a NodeMCU you also have to worry about the USB-to-Serial chip and the on-board voltage stabilizer.
The input impedance of the ADC input of a "naked" ESP8266 is (probably) a lot higher, 1 or more MΩ, although it is almost impossible to find definitive numbers.

Thanks for your answer. I was also looking for definitive numbers, but couldn't find any. I'm currently switching from the NodeMCU to the naked ESP8266, so your answer fits perfectly :) However if anyone finds out the definitive numbers, please post them here :)

source: Stack Exchange

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

sort: votes


text:
Getting error invalid conversion from 'const char*' to 'const uint8_t*
I have written this sketch, and I am trying to populate the array of wifi hotspots to  set the value in html select using javascript dynamically.
#include <Arduino.h>
#include <Hash.h>
#include "ESP8266WiFi.h"
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>

const char* ap_ssid     = "ESP8266";
const char* ap_password = "0123456789";

// Create AsyncWebServer object on port 8080
AsyncWebServer ap_server(8080);

const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML>

  <meta name="viewport" content="width=device-width, initial-scale=1">

)rawliteral";

void setup() {
  Serial.print("Setting AP (Access Point)…");
  // Remove the password parameter, if you want the AP (Access Point) to be open
  WiFi.softAP(ap_ssid, ap_password);

  IPAddress IP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(IP);

  // Print ESP8266 Local IP Address
  Serial.println(WiFi.localIP());

  // Route for root / web page
  ap_server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) {
    request->send_P(200, "text/html", index_html, getWifiHotspots());
  });

  // Start server
  ap_server.begin();
}

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

}

But I am geting this error
    /Arduino/libraries/ESPAsyncWebServer/src/ESPAsyncWebServer.h:243:10: error:   initializing argument 4 of 'void AsyncWebServerRequest::send_P(int, const String&, const uint8_t*, size_t, AwsTemplateProcessor)' [-fpermissive]

     void send_P(int code, const String& contentType, const uint8_t * content, size_t len,
AwsTemplateProcessor callback=nullptr);
          ^

exit status 1
invalid conversion from 'const char*' to 'const uint8_t* {aka const unsigned char*}' [-fpermissive]

Try to force the conversion in the function parameter: send_P(200, "text/html", (uint8_t *)index_html, getWifiHotspots());.

In the library ESPAsyncWebServer.h are these two possible function variants defined
  void send_P(int code, const String& contentType, const uint8_t * content, size_t len, AwsTemplateProcessor callback=nullptr);
   void send_P(int code, const String& contentType, PGM_P content, AwsTemplateProcessor callback=nullptr);

So  when using
const char index_html[] PROGMEM = R"rawliteral(<YOUR HTML here>)rawliteral";

give the compiler the explicit instruction
ap_server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) {
  request->send_P(200, "text/html", (const uint8_t*) index_html, getWifiHotspots());
 });

The code compiles error free on ArduinoIDE 1.8.12/ESP8266 2.71/ NodeMCUv1 (as not having your definition of getWifiHotspots() I defined it as char)

I see, I am getting error because index_html is of char type and the getWifiHotspots returns array of Strings?

@Ciastopiekarz No, as the error message clearly states, the argument is a const char *, and the function expects a const uint8_t *. -- BTW, actually you are programming C++, and the right cast is static_cast<const uint8_t *>(...).

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


text:
Why do random characters fill up my Arduino LCD Display?
I am making a water pump system for plants and I am running into trouble with displaying my Temperature and Humidity values. I am using a 20x4 LCD, Arduino board uno, Capacitive soil moisture sensor, 5v DC water pump, DHT22, and a single relay. When the motor is on, the display first shows the values as expected. Then, all of a sudden random characters fill and move across my screen. When I don't connect my motor to the Arduino, the values show up on the LCD as expected. Please do leave comments so that I am able to improve my code. Thanks.
//Libraries
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "DHT.h"

//Pins Used
#define DHTpin 2
#define DHTtype DHT22

//Initialization
DHT dht(DHTpin, DHTtype);
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

int sensor_pin = 0; // Soil Sensor input at Analog PIN A0
int pinValue;
int output_value ;
void setup() {
  // put your setup code here, to run once:
  pinMode(3,OUTPUT);
     Serial.begin(9600);
   Serial.println("Reading From the Sensor ...");

  lcd.begin(20, 4);
  delay(4000);
}

  // put your main code here, to run repeatedly:

  void loop() {
  lcd.clear();
  dht.begin();

  float humid = dht.readHumidity();
  float temp = dht.readTemperature();

  lcd.setCursor(0, 2);
  lcd.print("Temperature: ");
  lcd.print(temp);
  lcd.print("C");

  lcd.setCursor(0, 3);
  lcd.print("Humidity: ");
  lcd.print(humid);
  lcd.print("%");

 pinValue = analogRead(sensor_pin);
 output_value = map(pinValue,700, 300,0,100);

  Serial.print("Mositure : ");
  Serial.print(output_value);
  Serial.println("%");
   if(output_value> 0 && output_value <= 51){
    digitalWrite(3,LOW);
    lcd.setCursor(0,0);
    lcd.print("ON");
    lcd.setCursor(0,1);
    lcd.print("MOISTURE VAL: ");
    lcd.print(output_value);
    lcd.print("%");

    delay(1000);

     }else if(output_value > 51 && output_value <= 100){
      digitalWrite(3,HIGH);
      lcd.setCursor(0,0);
      lcd.print("OFF");
      lcd.setCursor(0,1);
      lcd.print("MOISTURE VAL: ");
      lcd.print(output_value);
      lcd.print("%");

      delay(1000);

     }
     delay(1000);
}

EDIT (1)
Here are some pics of the circuitry and the LCD message. If you find these pictures to not be helpful, I can sketch this circuit. Thank You.

Try to display some static string (not DHT/moisture sensor value) on the LCD and switch on the motor. If the problem still occurs, it is probably caused by EMI from the water pump motor.

Please add a wiring diagram into your question, showing how the components are connected to each other. A photograph of the layout would help, too.

How a project is wired can make a difference. Two people could wire up the same schematic and they could have very different results. Schematics will show if lines are connected but do not show how well the overall implementation is executed. Motors can be electrically very noisy. Proper routing of the currents involved is a must for stable operation. It is difficult to go into all the factors that must be considered. In your case it would help if you could post pictures of the way you wired your project.

I have added pictures to my question now

@ JSC, I printed some static strings, and I am still getting these random characters. How do I eliminate the EMI from my system?


text:
Can you program an ESP32 with an Arduino?
I've done it with an ESP-8266 but can't find any articles on how to do it with an ESP-32. I'm working with an ESP-32 on my own PCB, not a dev board. I exposed:

3V3
GND
EN
TX
RX
IO0

I'm pretty sure I can use a standalone programmer but I was expecting to be able to do it with an Arduino. Is that possible? ...if it's super difficult to do like setting up a toolchain and all that I'd rather just spend $10 and get a programmer.

it is the same as with esp8266. there is no programmer.


text:
Reset HC-05 from within Arduino sketch
I have an HC-05 Bluetooth module attached to an Arduino Mega; the module is paired with a Raspberry Pi and fed data via a python program; there's roughly one send and one receive per second of about 35 bytes.
When I first power up the Arduino / HC-05, it flashes quickly, and then after pairing, it flashes twice every second indicating a successful pair & communication. All is good; data is flowing. Periodically (5 minutes? 3 hrs?) & unpredictably, the communication ends; I'm still trying to troubleshoot this; the python code on the RPi reports a not-helpful OSError: [Errno 5] Input/output error on the available() method of the pySerialTransfer library; though I welcome thoughts on that, I realize that question isn't for this forum.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/pi/.local/lib/python3.7/site-packages/pySerialTransfer/pySerialTransfer.py", line 416, in available
    if self.connection.in_waiting:
  File "/home/pi/.local/lib/python3.7/site-packages/serial/serialposix.py", line 467, in in_waiting
    s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str)
OSError: [Errno 5] Input/output error

The HC-05 module continues to flash as if it's connected, even though it is not, and even if I restart the python program, I'm unable to repair with the HC-05.  The only way I can figure out to reconnect to the HC-05 is to power the Arduino / HC-05; then I can reconnect.
So here is the question: is there to reset the HC-05 from within the Arduino sketch? I realize I could attach the VCC to a digital pin to do a full power cycle on the HC-05, but I believe the HC-05 draws on the outer limit of safe current for an Arduino (40ma); I could go thru a relay to do the disconnect, but I wonder if there's a cleaner way with fewer moving parts, or if that is indeed the best way?
Thanks for any guidance!

You could use a logic level MOSFET with low RDSon (e.g. IRLZ44) to switch the supply of the HC-05 and use a digital pin to control it.

Thank you - I've ordered a few of those and will give it a shot!


text:
Bluetooth: read a user provided value and then obtain time from an Android phone
I'm new to Arduino and try to accomplish following 2 things (via Bluetooth module connected to an Android phone):

read an integer value provided by user.
obtain current time from the phone (the Arduino board itself has no clock module).

As for #1 - I'm able to print to the Bluetooth terminal as follows: Serial.println("Enter time to wait(in miliseconds): ");. I see this string on my phone. However I can't manage to read the value from the terminal using timeToWait = Serial.read();. I tried many possible combinations, but in the best case I get it in form of chars' ASCII values. So how can I properly read an integer value from the Bluetooth terminal?
As for #2 - is it possible at all, and if yes - how? If it is not possible to obtain current time via BT from Android phone - is it possible to obtain it via BT from a Linux laptop? How?

Over a serial port, you are transmitting data byte by byte. If you want to interpret them as numbers, you have to parse the data and assemble the numbers yourself.
You could resort to BLE instead, there you may transmit strings and numbers.

could you, please, create a link with "BLE" pointing on what it is? (Docs maybe)... For me and future readers. Thank you!

BLE stands for Bluetooth Low Energy, also known as Bluetooth 4.0.
Official tutorials to be found at e.g. [link] (https://devzone.nordicsemi.com/nordic/short-range-guides/b/bluetooth-low-energy/posts/ble-characteristics-a-beginners-tutorial).
An easy/easier approach would be studying the examples for ESP32 in the Arduino IDE.

I have found this: https://www.arduino.cc/en/Tutorial/ReadASCIIString which looks promising.

and also https://www.arduino.cc/en/Tutorial.StringToIntExample


text:
request for member 'attribute' in 'object', which is of non-class type 'int'
I am trying to create a basic snake game using the arduino UNO along with the MAX72XX module, the LCD module and the analog joystick module. I am wanting to program my program using object orientated programming. I have no experience with C++ so I am struggling quite a bit to understand what the following error is trying to say to me: request for member 'following_direction' in 'snake[0]', which is of non-class type 'int'.Here is the full code:
#include "LedControl.h"
#include <LiquidCrystal.h>
LedControl lc=LedControl(12,10,11,1);
LiquidCrystal lcd(8, 13, 3, 5, 6, 7);

/*lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis() / 1000);*/

class Snake_body
{
  //private:

  public:

    int following_direction;
    int body_length[64];
    int x;
    int y;
    int previous_x;
    int previous_y;

    Snake_body(int x_value, int y_value)
    {
      this->following_direction = 1;
      this->x = x_value;
      this->y = y_value;
      this->previous_y = y_value;
      this->previous_x = x_value;
    }
    /*void configure(int x_value, int y_value)
    {
      this->following_direction = 1;
      this->x = x_value;
      this->y = y_value;
      this->previous_y = y_value;
      this->previous_x = x_value;
    }*/

};

class Power_up
{
  private:

  public:
    virtual void init()
    {
      this->x = 0;
      this->y = 0;
    }

    int x;
    int y;
};

int snake[64];
int snakes_length;

Snake_body *snake_body;
Power_up *power_up;

void setup() {

  lcd.begin(16, 1);

  snakes_length = 1;

  for(int z = 1; z < 64; z++)
  {
  snake[z] = 0;
  }

  snake[0] = new Snake_body(0,0);
  //Snake_body snake[0] = new Snake_body();
  //snake[0].configure(0,0);
  // put your setup code here, to run once:
  lc.shutdown(0,false);
  /* Set the brightness to a medium values */
  lc.setIntensity(0,8);
  /* and clear the display */
  lc.clearDisplay(0);

  pinMode(2, INPUT);
  digitalWrite(2, HIGH);

  Serial.begin(9600);
  power_up->x = random(0, 8);
  power_up->y = random(0, 8);
}

int snake_direction;

void loop()
{
  int x_axis = analogRead(A0);
  int y_axis = analogRead(A1);
  int switcher = digitalRead(2);

   if(x_axis <= 400) //&& x < 7)
   {
     snake[0].following_direction = 0;
     //x += 1;
     //Serial.println("right");
   }

   else if(x_axis >= 600) //&& x > 0)
   {
     snake[0].following_direction = 1;
     //x -= 1;
     //Serial.println("left");
   }

   else if(y_axis <= 400) //&& y > 0)
   {
     snake[0].following_direction = 2;
     //y -= 1;
     //Serial.println("up");
   }

   else if(y_axis >= 600) //&& y < 7)
   {
     snake[0].following_direction = 3;
     //y += 1;
     //Serial.println("down");
   }

  if(snake[0].following_direction == 0 && snake[0].x < 7)
  {
    snake[0].previous_x = snake[0].x;
    snake[0].x += 1;
  }

  else if(snake[0].following_direction == 1 && snake[0].x > 0)
  {
    snake[0].previous_x = snake[0].x;
    snake[0].x -= 1;
  }

  else if(snake[0].following_direction == 2 && snake[0].y > 0)
  {
    snake[0].previous_y = snake[0].y;
    snake[0].y -= 1;
  }

  else if(snake[0].following_direction == 3 && snake[0].y < 7)
  {
    snake[0].previous_y = snake[0].y;
    snake[0].y += 1;
  }

  for(int a = 1; a < 64; a++)
  {
    if(snake[i] != 0)
    {

      snake[i].x = snake[i-1].previous_x;
      snake[i].y = snake[i-1].previous_y;
    }
  }

  lc.setLed(0,power_up->x,power_up->y,true);
  for(int w = 0; w < 64; w++)
  {
    if(snake[w] != 0)
    {
      lc.setLed(0,snake[w].x,snake[w].y,true);
    }
  }

  if(snake[0].x == power_up->x && snake[0].y == power_up->y)
  {
    power_up->x = random(0, 8);
    power_up->y = random(0, 8);

    for(int i = 0; i < 64; i++)
    {
      if(snake[i] == 0)
      {
         Snake_body *snake[i];

         //next_snake_body = new Snake_body();
         snake[i] = new Snake_body(snake[i-1].previous_x, snake[i-1].previous_y);
         //Snake_body next_snake_body;
         //snake[i].configure(snake[i-1].previous_x, snake[i-1].previous_y);
      }
    }
  }
  /*Serial.print("x: ");
  Serial.print(snake.x);
  Serial.println();

  Serial.print("y: ");
  Serial.print(snake.y);
  Serial.println();*/

  if(switcher == 0)
  {
    delay(50);
  }
  else
  {
    delay(100);
  }
  lc.clearDisplay(0);
}

the error is coming from this line here:
else if(snake[0].following_direction == 3 && snake[0].y < 7)

but I think it is also happening at all other lines of which are similar to this one.
I have tried replacing the . in snake[0].following_direction with a -> instead but that just caused the error: base operand of '-> ' is not a pointer. I have experience programming in java python and a few others but not arduino C++.

The problem is indeed in that line:
else if(snake[0].following_direction == 3 && snake[0].y < 7)

And specifically in:
snake[0].following_direction

snake is defined as
int snake[64];

Thus snake[0] is of type int.
And you cannot request the member following_direction from type.
Since you make new instances with:
snake[0] = new Snake_body(0,0)

I assume snake should be an array of Snake_body.
So I suggest (at least) change the type to:
Snake_body snake[64];

Just as a side note, I think one instance of Snake_body can take up like 16 bytes, and you make 64 of them, this results in 1,024 bytes which is half the memory of an Arduino Uno. Also, sometimes a library takes up some space, so keep this in mind if you are intending to add more libraries/global variables or stack space.
Update
Also the following line seems wrong:
snake[0] = new Snake_body(0,0);

You already created 64 instances of Snake_body (and assigned to snake) after you do my change. So you do not need to do this yourself; actually you cannot, unless you create an array of POINTERS to Snake_body.

That is now so obvious that I see that. This was a silly mistake I did not see. Also you are 100% right in thinking that snake is an array of snake_body. I probably did it because I am used to doing arrays of integers. You are such a legend! Cheers!

One problem though, when I have done the line Snake_body snake[64];, it thinks it is a function

Can you add the line and exact error you get (it thinks it is a function, that's not enough for me to see what isi wrong)

I added an update.

Isn't snake[64] just an array that takes in snake objects. How would I exactly define snake[0] as a new snake object. snake[0] is supposed to be the front of the snake.

Would the pointer point at each snake object in the array?

You can write snake[0] = new Snake_body(...), however, than you should declar the type as Snake_body* snakes[64]';, and keep a variable to show how many of the elements are filled/used.

I have already created a mechanism to see how many elements are in the list. That is where  int snakes_length; comes in.

Problem is now solved but the program is still having some work done on it. Its up to the point of what my question is about.

Yes that int variable is a good way to keep track (so it's like a stack object). If the solution helped you upvote it please, and if it solves your problem, also accept the answer (you can click next to the answer). Good luck with your game (I guess) and enjoy Arduino Stack Exchange.


text:
How do I use a shift register with ioAbstraction?
I’m trying to combine this use of the shift register.
With the ioAbstaction library.
But I’m not sure how to read the buttons.
The help in the library seems to suggest more pins for writing than the tutorial for the buttons.
The end goal is to have three LEDs and the buttons connected through the
74HC595 shift register using a minimal number of Ardunio pins.

Downvoter. Why? Is there something constructive you add?

The 74HC595 is a SerialToParallel shift register, mainly to have multiple outputs (SIPO).
You can abuse it to read multiple buttons by multiplexing:
Have one Arduino input pin and several output pins on the shift register to select the current button. This is what the instructables.com is showing.
No idea how that ioAbstraction library might help more than the Arduino-builtin shiftOut() function...

The IoAbstraction library is to enabled event-driven programming, if that helps.

I don't know that library, but I fear you have to enhance it a lot for your needs. And if you want to control your leds with that 595 as well, you got a very specific task I don't see how a generic library might help.


text:
Serial Read Data Loss With Arduino Nano
I am trying to use Serial reading from a python serial code (which is running on my Jetson Nano) in my project, but in some loop in my code, my data is receiving wrong.

I use Serial.readBytesUntil() function for interrupt-like reading.
I use standart blue mini-USB cable for communication.
My Arduino Nano also connected a nRF24L01 module with SPI.
Baudrate is 9600 for both devices. I tried 115200 but there is no difference.
The data loss is about %10 of all loops with both test codes (image-1, image-2).
There is no positive difference when I use RX/TX pins on both boards with level shifter.
When I use the test code in my main code with USB connection, the data loss increases %50 of all loops. But Arduino serial monitor is fine like image-3.
When I use the test code in my main code with RX/TX pins, Arduino serial monitor looks like image-4 and Arduino IDE gives error like image-5.

Here is my receiver test code on my Arduino Nano.
void setup() {

  Serial.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);
  while (!Serial) {}

}

void loop() {
  char buffer[4];
  int deger = 0;
  if (Serial.available() > 0) {
    int size = Serial.readBytesUntil('\n', buffer, 4);

    if (size == 4) {
      Serial.print("deger: ");
      Serial.write(buffer);
      Serial.print("  size: ");
      Serial.print(size);

      // Bytes to integer
      deger = (buffer[1] - 48) * 100 + (int(buffer[2]) - 48) * 10 + (buffer[3] - 48);
      if (buffer[0] == '1') {
        deger = -1*deger; }

      Serial.print(" Sayi: ");
      Serial.println(deger);
      }

    if (deger < 0) {
      digitalWrite(LED_BUILTIN, HIGH);
    }
    else {
      digitalWrite(LED_BUILTIN, LOW);
    }
  }
}

And the python serial transmitter test code.
import serial

ser = serial.Serial('/dev/ttyUSB0',baudrate=9600,timeout=10)
while True:
    hata = -58

    if hata > 0:
        hata = str(hata)
        if len(hata) == 2:
            hata = '00' + hata
        elif len(hata) == 1:
            hata = '000' + hata
        else:
                hata = '0' + hata    #Pozitive, Added 0
    elif hata < 0:
        hata = -1 * hata
        hata = str(hata)
        if len(hata) == 2:
            hata = '10' + hata
        elif len(hata) == 1:
            hata = '100' + hata
        else:
            hata = '1' + hata    #Negative, Added 1
    else:
        hata = str(hata)
        hata = '000' + hata

    # For every loop, sends 4 character and "\n"  Example: 1058\n
    gonder = hata + '\n'       # For readBytesUntil function
    ser.write(gonder.encode('utf-8'))
    print(gonder.encode('utf-8'))

image-1: Arduino test code serial monitor screenshot

image-2: Python test code serial terminal screenshot

image-3: Arduino main project code monitor with USB cable screenshot

image-4: Arduino main project code monitor with RX/TX pins on GPIO screenshot

image-5: Arduino main project code IDE error

So, what did i do wrong?
Thank you!

Already answered on the Arduino forum here

You are overflowing your buffer, and also allowing garbage reads.
First you need 5 bytes for your buffer not 4, and you need to ensure it is zeroed out before using it. This is because you are treating it like a C string, which means it must b zero terminated.
Secondly your use of Serial.readBytesUntil() is flawed.  From the manual:

The function terminates (checks being done in this order) if the determined length has been read, if it times out (see Serial.setTimeout()), or if the terminator character is detected (in which case the function returns the characters up to the last character before the supplied terminator).

You are sending 5 bytes (1058\n) but telling it to read up to 4. Which leaves the \n in the buffer. The next time through you read another 4 bytes, which gives you \n which is the terminating character.
If you must use readBytesUntil then you need to specify a buffer that is bigger than the whole string including the terminator so that the terminator always occurs before the maximum number of bytes read. Including the trailing zero you would thus need at least 6 bytes in your buffer, maybe a couple more "just in case" (one can never tell with Arduino API functions...)
So to roll it all up:
  char buffer[8]; // <- Bigger buffer
  memset(buffer, 0, 8); // <- Clear it out
  int deger = 0;
  if (Serial.available() > 0) {
    int size = Serial.readBytesUntil('\n', buffer, 7); // <- Tell it to read more leaving room for the terminating NULL
    ... etc ...

if (size == 4) {

readBytesUntil doesn't put the terminating character in the buffer. but it is read.

@Juraj Not if it's the 5th character and you're only telling it to read up to 4...

Thank you! I will try to code like you said. What do say about the second problem (image-4, broken serial monitor) ?

That is most likely buffer overflow from your unterminated buffer.


text:
what is causing my esp8266 setup function to reinitialise?
Here is code I have written:
#include <stdio.h>
#include <ESP8266WebServer.h>

#define MAX_WIFI_INIT_RETRY 50
#define WIFI_RETRY_DELAY 500

const char* wifi_ssid = "ssid";
const char* wifi_passwd = "password";

ESP8266WebServer http_rest_server(80);

const int numParams = 20;
String params [numParams];

String toString(String my_array[], int size)
{
  String string;
  for (int i = 0; i < size; i++) {
    string = string + ", " + my_array[i];
  }
  return string;
}

int init_wifi() {
  int retries = 0;
  Serial.println("Connecting to WiFi AP..........");
  WiFi.mode(WIFI_STA);
  WiFi.begin(wifi_ssid, wifi_passwd);
  // check the status of WiFi connection to be WL_CONNECTED
  while ((WiFi.status() != WL_CONNECTED) && (retries < MAX_WIFI_INIT_RETRY)) {
    retries++;
    delay(WIFI_RETRY_DELAY);
    Serial.print("#");
  }
  return WiFi.status(); // return the WiFi connection status
}

void readParams(String (& params) [numParams])
{
  int mn = WiFi.scanNetworks();
  for (int i = 0; i < mn; i++)
  {
    //    Serial.println(WiFi.SSID(i).c_str()); // prints name of all hotspots in serial monitor.
    params [i] = WiFi.SSID(i).c_str();
  }
}

void listHotspots() {
  String results = toString(params, sizeof(params));
  Serial.println(results);
  http_rest_server.send(200, "text/plain", results);
}

void config_rest_server_routing() {
  http_rest_server.on("/", HTTP_GET, []() {
    http_rest_server.send(200, "text/html",
                          "Welcome to the ESP8266 REST Web Server");
  });
  http_rest_server.on("/hotspots", HTTP_GET, listHotspots);
}

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

  init_led_resource();

  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  readParams (params);

  if (init_wifi() == WL_CONNECTED) {
    Serial.print("Connetted to ");
    Serial.print(wifi_ssid);
    Serial.print("--- IP: ");
    Serial.println(WiFi.localIP());
  }
  else {
    Serial.print("Error connecting to: ");
    Serial.println(wifi_ssid);
  }

  config_rest_server_routing();

  http_rest_server.begin();
  Serial.println("HTTP REST Server Started");
}

void loop(void) {
  http_rest_server.handleClient();
}

when I access the root url: i.e. 192.168.0.101/ It opens the root page fine, but when I try to open the 192.168.0.101/hotspots It reboots the ESP8266  until the page stops to make a new attempts and I get nothing in result.
In the serial monitor I am seeing this exception when I try to visit the ip/hotspot page .
Exception (9):
epc1=0x4020148a epc2=0x00000000 epc3=0x00000000 excvaddr=0x4d2d5456 depc=0x00000000

>>>stack>>>

ctx: cont
sp: 3ffffde0 end: 3fffffc0 offset: 01a0
3fffff80:  3fffdad0 3ffee553 3ffee5a4 40201347
3fffff90:  402086b8 6505a8c0 feefeffe feefeffe
3fffffa0:  3fffdad0 00000000 3ffee5e0 40206614
3fffffb0:  feefeffe feefeffe 3ffe8510 40100479
<<<stack<<<

 ets Jan  8 2013,rst cause:4, boot mode:(3,6)

wdt reset
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v8b899c12
~ld
Connecting to WiFi AP..........
######Connetted to Hometelecom1N5E--- IP: 192.168.0.101
HTTP REST Server Started

is it something wrong with the toString function ?

cause 4 is a watchdog reset

so what might be causing watchdog reset ?

not calling a function which 'feeds the dog' long enough. decode the stack trace

nevermind, I figured out solved my problem

When a program crashes, you can debug the crash based on the Fatal exception number.
 Exception (9)  Unaligned read/write operation addresses
     1. Unaligned read/write Cache addresses
     2. Wild pointers

This leads than as Juraj points out to a WD reset:
 rst:4     Hardware WDT reset

To get the exact part of the code paste the >>>stack>>> into the window of the espExeption decoder in the ArduinoIDE. Details how to install and use.
My educated guess is that the heavy use of String class in combination with lot of String operations with the getHotspot function leads to heap corruption and crashes the Esp8266. Try defining fixed char arrays and get rid of the String class to get a stable running system. Post the espExeption decoder result as edit to your question if you thing something else might be fishy

thank you @codebreaker007 I managed to get the code working can you please take a good look at my code review at https://codereview.stackexchange.com/q/242917/22943


text:
Complier overwrote bootloader doing a non-programmer upload
Got this when uploading (no programmer) to a MkrZero.
I had downloaded the board's toolset via the IDE earlier, and uploading smaller sketches worked fine.  On a larger, more complex project, got this:
Sketch uses 31000 bytes (11%) of program storage space. Maximum is 262144 bytes.
Atmel SMART device 0x10010005 found
Device       : ATSAMD21G18A
Chip ID      : 10010005
Version      : v2.0 [Arduino:XYZ] Dec 20 2016 15:36:46
Address      : 8192
Pages        : 3968
Page Size    : 64 bytes
Total Size   : 248KB
Planes       : 1
Lock Regions : 16
Locked       : none
Security     : false
Boot Flash   : true
BOD          : false
BOR          : false
Arduino      : FAST_CHIP_ERASE
Arduino      : FAST_MULTI_PAGE_WRITE
Arduino      : CAN_CHECKSUM_MEMORY_BUFFER
Erase flash
done in 0.800 seconds

Write 31336 bytes to flash (490 pages)

[===                           ] 13% (64/490 pages)
[=======                       ] 26% (128/490 pages)
[===========                   ] 39% (192/490 pages)
[===============               ] 52% (256/490 pages)
[===================           ] 65% (320/490 pages)
[=======================       ] 78% (384/490 pages)
[===========================   ] 91% (448/490 pages)
[==============================] 100% (490/490 pages)
done in 0.234 seconds

Verify 31336 bytes of flash with checksum.
Verify successful
done in 0.075 seconds
CPU reset.

It sounds like it reset the chip completely... and Windows no longer sees a COM port from it via USB.
I've tried:
* The click and double-click on the board's reset button, including at the start of a new upload of a simple sketch
* Restarting the Windows machine
* Looking at device manager to see if any COM ports show up, even temporarily
* Same cable, same computer, different MKRZero - works
Main question:  What could there be in the project to have caused the compiler/loader to do this?    This is the 2nd time this project has triggered a reflash.   It does use the EEPROM API by A. Christian, but I've been able to use that before without this result.
2nd: Any other ways to recover the board?
Thank you for any guidance.

Hmm... Now getting a similar result on a small test-the-led-only sketch, on a brand-new just-out-of-the-box MkrZero.    But, that one seems to still be healthy from a running and native USB connection POV.   So, what causes this FAST_CHIP_ERASE?


text:
Mount arduino metro mini
I'm using an Arduino Metro Mini (for example https://www.adafruit.com/product/2590) in a project, and want to mount it so the micro USB socket is available through a hole in the case.
Is there an easy way to do this? The main difficulty is that the board has to be mounted end-on to the case, which means you need brackets, which also need standoffs since of course neither side of the board is entirely flat; and the screw holes are at the very end, so no space to spare between them and the case. Etc. If that's not clear, glance at the analogous HDMI mount linked below.
Adafruit sells a complete enclosure (https://www.adafruit.com/product/2709), and there's a similar printable one at https://www.thingiverse.com/thing:936519. I could glue that to the case and then put the mini in there. But that seems like overkill.
For some breakout boards Adafruit has a special panel mount (like the HDMI one at https://www.adafruit.com/product/3121) -- but nothing I see there or elsewhere for the metro mini.
Any better solutions out there? Closest i've seen here is Mounting Arduino in an enclosure

are you asking how to mount a device that has 4 holes for screws? ... your question is not really related to the arduino

The USB micro specification includes clearance for mounting through a case. You notice when you plug a cable in there is always a small gap between the socket and the moulded body of the plug. That gap is for the housing of your project. Get a box with a thin enough wall, Cut a hole in it the right shape. Stick / glue / tape / velcro / screw / whatever your board so the socket is behind (and maybe partially inside) the hole you cut. It's not rocket surgery.

What do you mean "neither side of the board is entirely flat"?  Looking at the linked picture of the Arduino Metro Mini it looks to be a perfectly flag rectangular piece of PC board with mounting holes in all 4 corners. Attach a stand-off to every one of those holes, and position the Arduino near the edge of the case so that it's USB connector is barely inside. Measure and cut a hole in the case large enough to insert a USB plug.

i would copy the thingiverse stl object into tinkercad, where i can make a case around it, cutting out parts as needed. you can mount it  "upside-down" on a corner of the case, which lets you press the button with a paper clip. i did just that for nodeMCUs, though eventually i gave up on the imported bracket and make my own with a few cylinders and holes...

What I've done for my projects is to get PC board standoffs of the right height, and use those to mount the board to the bottom of the case.
I measured the height of the USB connector and it's distance from the mounting holes, and calculated where to cut a hole in the side of the case for the USB connector.
I did not look up the USB specification for the depth/clearance of the connector - I just "guesstimated" and it worked fine.


text:
Impossibility to open a file for modification in ESP32
Consider the following code:
#include "SD.h"
#include "Fs.h"

void setup() {
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.print("Initializing SD card...");

  // see if the card is present and can be initialized:
  if (!SD.begin(5)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    while (1);
  }
  Serial.println("card initialized.");

  File file = SD.open("/test.txt", FILE_WRITE);
  file.write((const uint8_t*)"is a test", 10);
  file.close();

  file = SD.open("/test.txt", FILE_WRITE); <-- Tested with APPEND too
  file.seek(0);
  file.write((const uint8_t*)"this", 4);
  file.close();

  file = SD.open("/test.txt", FILE_READ);

  while (file.available()) {
    Serial.write(file.read());
  }
  file.close();
}

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

}

If I open the file with FILE_WRITE the contents of the file are zeroed and I get as output:

"this"

And if I open the file in mode FILE_APPEND then seek() does not work and I get as output:

"is a testthis"

How to modify this program so I get any of both?

"thisis a test" [insert] (or) "thistest" [overwrite]

Using an ESP32 here as I think the File or the SD objects are different than the Arduino ones.

"FILE_WRITE" should be just FILE_WRITE.  It's a macro that equates to "w"

Good catch but that was a paste error, the code was fine. I've fixed the code here but the problem remains.

The ESP32 implementation is somewhat convoluted. It goes through multiple layers of compatibility wrappers to use the underlying SDK calls. If write always truncates, and append never seeks, then there is something wrong or lacking in those compatibility layers. You should open an issue on Github, https://github.com/espressif/arduino-esp32/issues

Thanks, issue opened: https://github.com/espressif/arduino-esp32/issues/4028


text:
Serial printing from flash memory (F() macro, PROGMEM, sprintf_P, SPTR)
I have been testing various techniques on an Arduino Uno  for serial printing from flash memory instead of RAM. At the same time, I have been using the freeMemory() function from Adafruit.
I created a program that prints the word "test", with various methods:
Simple print:
Serial.print("test");
Serial.print(freeMemory());

This call reports free RAM = 2267
Using the F() Macro:
Serial.print(F("test"));
Serial.print(freeMemory());

This call reports free RAM = 2299
Using sprintf_P()
char buf[100];
sprintf_P(buf,PSTR("test"));
Serial.print(buf);
Serial.print(freeMemory());

This call reports free RAM = 2267
Using strcpy_P()
 char buf[100];
 strcpy_P(buf, (PGM_P)F("test"));
 Serial.print(buf);
Serial.print(freeMemory());

This call reports free RAM = 2267
Using strcpy_P and const char[] PROGMEM
char buf[100];
const char buff[] PROGMEM = "test";
strcpy_P(buf, buff);
Serial.print(buf);
Serial.print(freeMemory());

This call reports free RAM = 2267
The basic point of this question is to gather all the possible flash memory printing techniques. Also it would be really useful if you could explain in detail what exactly each of the keywords F(), (PGM_P)F, PSTR, const PROGMEM does.
IMPORTANT EDIT, 1:
Depending on where and how I use the call Serial.print(freeMemory()); the results change. For example, at the last example (PROGMEM, strcpy_P) when I included another Serial.print(freeMemory()); before the call of the printing functions, then both freeMemory() calls report 2299!
Another interesting problem is that the freeMemory() reports 2299 as freeRam, while the SRAM of my Arduino Uno is only 2 kbytes.
EDIT 2:
Following the suggestion in comments, I changed "test" to "testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttest". Now all different methods report a free ram of 2299, including the simple Serial.print().
freeMemory():
#ifdef __arm__
// should use uinstd.h to define sbrk but Due causes a conflict
extern "C" char* sbrk(int incr);
#else  // __ARM__
extern char *__brkval;
#endif  // __arm__
int freeMemory() {
  char top;
#ifdef __arm__
  return &top - reinterpret_cast<char*>(sbrk(0));
#elif defined(CORE_TEENSY) || (ARDUINO > 103 && ARDUINO != 151)
  return &top - __brkval;
#else  // __arm__
  return __brkval ? &top - __brkval : &top - __malloc_heap_start;
#endif  // __arm__
}

Nice report, but I miss a question; I guess you don't use a Uno as that model has 2 KB only.

All those routines use 100 bytes on the stack and nothing else, except maybe transient space within the functions you call which is also on the stack. None of that is relevant to storing data in and reading data from flash. All the things you ask about are macros. You can find what they expand to in the source code of either the core or the compiler.

I suggest you try with a message much longer than "test". There are many details in the compiler optimization process that can make small variations in the memory consumption. Those can make your measurements hard to interpret with such a small string.

Will try immediately, and report back with the results. @MichelKeijzers Strangely enough, I am using an UNO. Any ideas?

@EdgarBonet your suggestion really seems to have an impact. I changed "test" to "testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttest". However the results seem to be even weirder, as all different methods (including the simple Serial.print) report a free RAM of 2299. Let me also point out that this is the freeRam I get when I only call the freeMemory() in my code.

First, the freeMemory() function that you used from Adafruit was originated from a GitHub repository.
I don't know about the __arm__ implementation, but for the AVR one, it is incomplete for handling the corner case when the program does not use the malloc() function. If your program never uses malloc(), the formula used in freeMemory() will produce the wrong result. A simple corrected version for AVR that I used is here:
extern unsigned int __heap_start;
extern char *__brkval;

int freeMemory() {
  char top_of_stack;

  if (__brkval == 0) {
    Serial.println(((int)&top_of_stack - (int)&__heap_start));
  } else {
    Serial.println((int)&top_of_stack - (int)__brkval);
  }
}

explain in detail what exactly does each of the keywords F(), (PGM_P)F, PSTR, const PROGMEM.

PSTR("string literal")
PSTR came into Arduino from part of avr-libs (a C library) defined in avr/pgmspace.h. It is actually a macro, not a function as many think it was, and is defined as:
#define     PSTR(s)   ((const PROGMEM char *)(s))

It looks a little bit intimidating, but it is actually quite simple. It not only tells the avr-gcc that the string literal s should be kept in program memory (i.e., flash memory in the case of Arduino), but it allows the program to convert it into a const char *s PROGMEM variable, so that it can be pass around into some PROGMEM-aware functions as a parameter.
 // This is a PROGMEM-aware function in C
 printMsg_P(const char* str) {
     char buf[strlen_P(str)+1];
     strcpy_P(buf, str);
     puts(buf);
 }

 // This handles the normal string array function
 printMsg(const char* str) {
     puts(str);
 }

F("string literal")
F() is also a macro, but it is not part of the avr/progmem.h. It is actually part of the String class defined in WString.h together with a definition of a class called __FlashStringHelper:
class __FlashStringHelper;
#define F(string_literal) (reinterpret_cast<const __FlashStringHelper *>(PSTR(string_literal)))

To understand the F() macro and the difference between F() and PSTR() take a little bit explanation.
As you can see from the definition of F(), it casts a string literal into a const char* variable using PSTR(), and then recast it into a class __FlashStrngHelper. If you further look at the __FlashStringHelper, it is actually an empty class without any construct or method. It is literally empty, so why is this useful? And why can't it just pass the string literal around by just using PSTR()?
This has to do with C++'s function overload. Function overload is a feature of C++ where multiple methods could have the same function name, but each with different parameters. Within all the Serial.print() methods, there is a method Serial.print(const char* str) that will take in a string literal and print it to serial monitor, but it is not PROGMEM-aware. If you pass in a PROGMEM string literal Serial.print(PSTR("string literal"));, the same method will accept what you pass in because it meet the type checking (remember PSTR is actually const char*), but it will not print out the correct string for PSTR("string literal"), because it simply expecting a normal string.
In C, as we see before, we solve the problem by using two functions with different names for handling normal string and PROGMEM string, but Serial is a C++ class. It needs another function overloaded method to be PROGMEM-aware, and PSTR() is clearly not the solution as we just mentioned.
WSting.h and Print.cpp create an overload method that is PROGMEM-aware by accepting a class as parameter, so that you can pass a F() wrapped string literal which has a data type of class __FlashStringHelper into the Serial.print() and get the print out correctly from program memory. See the source code yourself.
Serial.print(const __FlashStringHelper *ifsh)

So in summary, the F() and PSTR() are alike. Both are telling the compiler to keep the string literal in the program memory, and allow the string literal to be pass around into some function as parameter. But it was designed for different purpose from different programming paradigm (C versus C++). F() is Serial.print()-friendly, while PSTR() is not. If you are getting PSTR() in a function and yet you want to send it to Serial.print(), you will have to explicitly cast it into __FlashStringHelper like this:
Serial.print((__FlashStringHelper*)PSTR("test"));

PGM_P
PGM_P is a macro defined as:
#define     PGM_P   const char *

Whether you want to use PGM_P or const char * is a personal preference. For example, this is copy from PROGMEM (Arduino reference):
const char *const string_table[] PROGMEM = {string_0, string_1, string_2, string_3, string_4, string_5};

can be written as:
PGM_P const string_table[] PROGMEM = {string_0, string_1, string_2, string_3, string_4, string_5};

This is a lengthy explanation, but I hope this will help with better understanding the subject and therefore be able to use the PROGMEM and all the associated macros effectively.

Re “PSTR [...] is defined as [...]”: This definition is introduced by the comment “The #define below is just a dummy that serves documentation purposes only.” The actual definition is somewhat more convoluted.

explain in detail what exactly does each of the keywords F(), (PGM_P)F, PSTR, const PROGMEM.

F() wraps the string literal in PSTR(...) and then casts it to __FlashStringHelper.  This forces it to remain in flash and also gives it a type that the Arduino core can identify as a string in flash for overloading.
PGM_P is a "Pointer to ProGraM mememory". This is the type that all the _P variants of functions require. It's basically const char * provided by avr/pgmspace.h
const PROGMEM is actually two things. const means you're not changing the value, and PROGMEM is another name for __ATTR_PROGMEM__ which itself is an alias for __attribute__((__progmem__)) which is a flag for the compiler to tell it to keep the variable in flash and not copy it to RAM.

So F() and PGM_P are used when you are passing a string literal to a function that expects one of those formats. PROGMEM is used when you're setting up a constant "variable" (oxymoron there, I know...) that points to data in flash.

Could you please explain: sprintf_P(buf,PSTR("test")); ? Is this wrong? Should it be like this: sprintf_P(buf,PGM_P("test")); ? Also what about this command: strcpy_P(buf, (PGM_P)F("test")); which combines both PGM_P and F()?

(PGM_P)F("test") is what I usually use.

(PGM_P)F("test") is equivalent to PSTR("test"). What happen is that F("test") cast the string literal into a class  __FlashStringHelper, and then recast it to PGM_P which basically is a macro as const char*. This is the same as PSTR("test") that converts a string literal s[] to `const char* s variable.


text:
How can I identify GPS sattelites in TinyGPS++?
I can see about 15 satellites (about 10 GPS + 5 Glonass) in u-center, but I see only about 10 satellites using TinyGPS++. I suspect that TinyGPS++ can see GPS only. I see lines containing $GNRMC $GNVTG $GNGGA $GPGSV $GNGLL $GNVTG $GLGSV in the input, so there are information from both constellation. But how can I check which constellations TinyGPS++ takes into account for the output:

Sats=10 Nums=1 3 8 10 11 14 20 22 24 27 28 31 32 36 40  Elevation=46
  17 45 31 69 59 1 43 5 24 9 1 60 36 32  Azimuth=304 255 215 66 267 137
  77 263 28 184 316 140 89 181 150  SNR=12 0 0 17 8 20 0 11 0 11 0 0 21
  0 0

TinyGPS++ is just a text parsing library you can read and examine

https://www.gpsinformation.org/dale/nmea.htm#GSV SNR=0 means the satellite can be seen but may not be being used for your positional fix.

There is a bug in TinyGPS++ as it only counts GPS satellites. See https://github.com/mikalhart/TinyGPSPlus/issues/52
PRN numbers are used to identify satellites:

GPS = 1 to 32
SBAS = 33 to 64 (add 87 for PRN number)
GLO = 65 to 96


text:
HC-05 master and slave
I have a silly question that came to my mind
when communicating between HC-05 and A smartphone, the smartphone is considered as the master,
and the HC-05 is considered a slave.
master will send data to the slave and then the slave will send these data to the MCU.
my question here is that, what is the MCU considered if it is not a master or slave?
if I got something wrong, I'll be glad if you correct it for me.
thank you

What do you mean by "not a master or a slave"? Bluetooth always has a master and a slave. When should the HC-05 ever be none of that?

HC-05 <=> MCU is a serial connection without any master/slave protocol, handshake or whatever.

if MCU is in serial communication with HC-05, then both of them are considered a slave ? @chrisl

You have a misconception about the interfaces involved. Actually we have 2 different interfaces here: Bluetooth and Serial (UART). The HC-05 is a Bluetooth Serial bridge.
The Bluetooth interface has a fixed concept of master and slave. Every connection needs to have only 1 single master. This concept applies only to the communication between HC-05 and the smartphone. It has nothing to do with the MCU itself, because the MCU does not do any Bluetooth communication.
The second interface is the Serial (UART) interface between the HC-05 and the MCU. For this interface there is no concept of master/slave, because it is not needed. Either of them can send independently on their corresponding TX pin and can receive on their RX pin.
These are two totally independent and different communication interfaces. The HC-05 just forwards data between the interfaces.

very clear now thank you !


text:
Hardware/software serial for HC-05
can anyone please tell me the whole difference between hardware and software serial for the HC-05.
I read UART,USB cable, serial and I was like really confused
so what is the difference and advantages between both?
thank you...

Hardware vs Software Serial: Most microcontrollers/Arduinos have at least 1 hardware Serial interface. That means, that for this Serial interface the actual communication protocol (the transmission and receiving of the actual data) is implemented in dedicated hardware inside the microcontroller (which also means there are fixed pins, where you can connect to them on the board). That way you don't need code for doing the complex communication protocol. Instead the main CPU is only involved to handle the received and to-be-transmitted data, which need to be placed in a buffer register. The dedicated hardware then automatically sends and received the data.
As the number of hardware Serial interfaces is limited and fixed for the Arduino board/microcontroller, it happens, that you need more Serial interfaces, than you have in hardware on your board/in your microcontroller. Then you can use SoftwareSerial. That is a library, which handles the complete communication protocol in software, by directly setting and reading the electrical pin states according to the protocol. The advantage is, that you can use this on any digital pins for such an interface. Disadvantage is, that doing such things in software is complex. You can only listen on 1 SoftwareSerial interface at a time and the baudrate is limited (depending on the actual used microcontroller, e.g. it's frequency).
UART vs Serial: UART is the technical term for the used communication interface. Serial is an Arduino term, which is not used that way in other contexts. The real interface type is UART and the Arduino framework just names that Serial to make it simpler.
Connecting over USB cable or pins: Let's take the Arduino Uno as example. It has 1 hardware serial interface. This interface is connected to the pins 0 and 1 (RX and TX), but also internally to an extra chip. That chip handles the USB connection and behaves as a USB-Serial bridge. When communicating with the Serial Monitor in the Arduino IDE, you are actually using this USB-Serial bridge to talk to the microcontroller on the Arduino. But you could also use the RX/TX pins to do that.

Hardware serial uses pins 0/1 on the Uno. You can't change those pins. Those pins are also the pins that are used to communicate with your computer. You can use hardware serial on those pins to communicate with the HC-05 only if you don't want to communicate with your computer.
SoftwareSerial can be used on any pins so can be used at the same time as the hardware serial for communicating with your computer. However SoftwareSerial is somewhat limited in what it can do.
Bigger boards (such as the Mega) usually have more than one hardware serial port. These are connected to the TX1/RX1, TX2/RX2 etc pins. These are the preferred method of connecting to external serial devices since they work more reliably that SoftwareSerial and concurrently with the computer's USB connection.


text:
I connected a bipolar stepper motor with an HC-SRO4 distance sensor but the motor doesn't work
I connected a bipolar stepper motor with an L293D motor driver and a HC-SR04 distance sensor.
Here's the code:
#include<AFMotor.h>
int stepsperrevolution=200;
AF_Stepper motor(stepsperrevolution,1);
int echopin=11;
int trigpin=9;
int dt=2000;
int sensorval;
void setup() {
  Serial.begin(9600);
  motor.setSpeed(10);
  pinMode(echopin,INPUT);
  pinMode(trigpin,OUTPUT);

}

void loop() {

 digitalWrite(trigpin,LOW);
 delayMicroseconds(10);
 digitalWrite(trigpin,HIGH);
 delayMicroseconds(10);
 digitalWrite(trigpin,LOW);
 delayMicroseconds(10);
 sensorval=pulseIn(echopin,HIGH);
 Serial.println(sensorval);

if(sensorval<500){
 motor.step(stepsperrevolution,FORWARD,SINGLE);
  delay(dt);
   }

}

The code works.Although, every time the sersorval prints in the serial monitor, it stops when the value is less than 500, and the stepper doesn't move.

What happens if you decrease delay(dt) ? I'm not sure how much 1 step is, but if there is just one step every 2 seconds it might look like not moving.

I decreased it already but nothing's changed the motor still doesn't move.

Has it ever moved (with an example sketch if it exists for your stepper motor) ? To rule out any circuit/programming error.

put the motor.step(stepsperrevolution,FORWARD,SINGLE); outside of the if block

@MichelKeijzers. Yes the stepper motor moved with an example sketch.

@jsotola I put it outside of the if block but the senorval reads slowly in the serial monitor

did the motor run?


text:
Convert 1-5V to 4-20mA using Arduino
I am trying to convert 1-5V to 0-20mA which is then used to drive VFD.
Actually, I want 1-5V Variable output from Arduino. I am using PWM but its output 0V or 5V depending upon the duty cycle.
Is their any method to obtain any voltage between 1-5V using Arduino or any other module/controller?

Also asked on EE yesterday: https://electronics.stackexchange.com/questions/501845/4-20ma-output-from-arduino-nano

By tuning R4 and C1 and using an appropriate PWM frequency and duty cycle, you already have a (simple and slow) D/A converter that can generate voltages between 0 and 5V, but this might not fit your needs. How fast does it need to be? There are many DACs available to be interfaced with Arduinos.

@VE7JRO, to be fair, that question was about a 4-20mA output. Now they need to generate a 1-5V input for the same circuit and already added an RC filter to try to accomplish that.

@StarCat - The first sentence in the OP's question on EE is "To convert 1-5V to 0-20mA:". Their first sentence here on Ard.SE is very similar. The OP's question on EE has not received any answers, so maybe someone here has the answer. The 741 OP Amp part of the question is better suited for EE because it's off topic for our network, and the OP may want to read this first before choosing that OP Amp: https://electronics.stackexchange.com/questions/304521/reasons-not-to-use-a-741-op-amp

Make C1 ten times bigger.

just use a low pass filter to convert pwm to analog voltage. if you need responsiveness, a 2-stage filter will respond quicker at the same ripple level than a single RC filter. You will likely need an op-amp unity gain amp (aka buffer) after the filter to allow the needed current (RC filters will severely restrict current). To convert the 0-5v to 0-20ma, you can just drive a 250 ohm resistor. If you want 4-20ma, use the map() function to scale.

One cannot use an Arduino to convert 1..5V to 4..20mA.


text:
Running a motor for a 3 seconds continuously with and without interrupt
I have interfaced a dc motor and IR sensor to my nano. The DC motor is supposed to run only if the IR sensor detects an obstacle. Now, I'm trying to get the motor to turn off if continuously obstructed for 3 seconds, and exit the interrupt (in case of the first code with interrupt), and again wait for the sensor to go low again (falling edge). I have implemented this using millis(), but the code doesnt seem to be working consistently, as the timing seems to have gone for a toss (random behavior; sometimes it keeps running continuously and sometimes it stops) . Can anyone on this forum please review it and suggest me a correction. Also, would it be possible to use a LOW trigger instead of falling edge to achieve this ?
#include <LowPower.h>

const int out1 = 5; //motor
const int IRSensor = 3; // connect ir sensor to arduino pin 6
const int LED = 6; // conect Led to arduino pin 9
const int Switch = 2;
const int Mspeed = 175;//0-255
const int Mtime =1500;//500-1000
int statusSensor=1;
int switchSensor=1;
unsigned long prevTime;
volatile int count =0;
volatile int count1=0;
volatile int count2 =0;
volatile int count3=0;
volatile int buttonstate=0;
volatile int lastbuttonstate=0;
volatile bool flag=false;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(out1,OUTPUT);
  //pinMode(out1,OUTPUT);
  pinMode (IRSensor, INPUT); // sensor pin INPUT
  pinMode (LED, OUTPUT); // Led pin OUTPUT
  pinMode(Switch, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(IRSensor),IRinterrupt,FALLING);
}

void loop() {
  // put your main code here, to run repeatedly:
  LowPower.powerDown(SLEEP_FOREVER , ADC_OFF, BOD_OFF);
  delay (100);
  if (flag==true){
  //Serial.println("true");
  switchSensor = digitalRead (Switch);
  //Serial.println ("zloop");

  statusSensor = digitalRead (IRSensor);
  //Serial.println (statusSensor);
  if (count1==1)
  { prevTime = millis();
    Serial.println(prevTime);
  }
  if (millis() - prevTime >= 1000)
  { doSomethingElse();
    Serial.println("going to else");
  }
  }
  //prevState = digitalRead(IRSensor);
  doSomething();

}

void IRinterrupt(){

   flag=true;
  }

void doSomething(){
  buttonstatus();
  if (statusSensor == 0 and switchSensor == 0 and count3==0){

     analogWrite(out1,Mspeed);
     //digitalWrite(out1,HIGH);
     count1=count++;
     Serial.println(count);
     digitalWrite(LED, LOW);
  }
   else if (statusSensor == 0 and switchSensor == 1) {

      //digitalWrite(out1,LOW);
      digitalWrite(LED, HIGH);
      analogWrite(out1,0);
      count=0;
      count1=0;
      prevTime = millis();
      }
   else if (statusSensor == 1 and switchSensor == 0) {

      //digitalWrite(out1,LOW);
      digitalWrite(LED, LOW);
      analogWrite(out1,0);
      count=0;
      count1=0;
      prevTime = millis();
      }
    else {
      //Serial.println ("ir high");
      //digitalWrite(out1,LOW);
      digitalWrite(LED, HIGH);
      analogWrite(out1,0);
      count=0;
      count1=0;
      prevTime = millis();
      buttonstatus();
      }
}
void doSomethingElse(){

      //Serial.println ("ir high else");
      analogWrite(out1,0);
      count=0;
      count1=0;
      prevTime = millis();
      count2++;
      count3=count2;

      //analogWrite(out1,0);
  }

void buttonstatus(){
  buttonstate=digitalRead (IRSensor);
   if (buttonstate != lastbuttonstate) {
    // if the state has changed,
    if (buttonstate == LOW) {
      count3=0;
    }
    delay(50);
   }
   lastbuttonstate = buttonstate;
}

I have written another piece of code without interrupts. How do I achieve the same timing part for this too ?
int out1 = 5; //motor
int IRSensor = 3; // connect ir sensor to arduino pin 6
int LED = 6; // conect Led to arduino pin 9
int Switch = 2;
int statusSensor=1;
int switchSensor=1;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(out1,OUTPUT);
  //pinMode(out1,OUTPUT);
  pinMode (IRSensor, INPUT); // sensor pin INPUT
  pinMode (LED, OUTPUT); // Led pin OUTPUT
  pinMode(Switch, INPUT_PULLUP);
}

void loop() {
  // put your main code here, to run repeatedly:
  switchSensor = digitalRead (Switch);
  //Serial.println (switchSensor);

  statusSensor = digitalRead (IRSensor);
  //Serial.println (statusSensor);
  delayStart = millis();
  //Serial.println ("ir interupt");

   if (statusSensor == 0 and switchSensor == 0){
     Serial.println ("ir low");
     analogWrite(out1,120);
     digitalWrite(LED, LOW);
   }
      else {
      Serial.println ("ir high");
      analogWrite(out1,0);

      }

}

EDIT: I have now successfully implemented the code (without interupts) with timing part in the code below.Also, I have updated the first code in the post with interrupts, but I am not able to get the timing part working. Can, someone please help me how timing can now be done with interrupts, so that the arduino nano is in sleep, until it receives a falling edge on the interrupt pin from the IR sensor, so that it can process the next part. Doing so I believe I would save power consumed since its on all the time.
const int out1 = 5; //motor
const int IRSensor = 3; // connect ir sensor to arduino pin 6
const int LED = 6; // conect Led to arduino pin 9
const int Switch = 2;
const int Mspeed = 175;//0-255
const int Mtime =1500;//500-1000
int statusSensor=1;
int switchSensor=1;
unsigned long prevTime;
volatile int count =0;
volatile int count1=0;
volatile int count2 =0;
volatile int count3=0;
volatile int buttonstate=0;
volatile int lastbuttonstate=0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(out1,OUTPUT);
  pinMode (IRSensor, INPUT); // sensor pin INPUT
  pinMode (LED, OUTPUT); // Led pin OUTPUT
  pinMode(Switch, INPUT_PULLUP);
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(100);
  switchSensor = digitalRead (Switch);
  statusSensor = digitalRead (IRSensor);
  if (count1==1)
  { prevTime = millis();
    Serial.println(prevTime);
  }
  if (millis() - prevTime >= Mtime)
  { doSomethingElse();
    //Serial.println("going to else");
  }
  doSomething();

}

void doSomething(){
  buttonstatus();
  if (statusSensor == 0 and switchSensor == 0 and count3==0){

     analogWrite(out1,Mspeed);
     //digitalWrite(out1,HIGH);
     count1=count++;
     Serial.println(count);
     digitalWrite(LED, LOW);
  }
   else if (statusSensor == 0 and switchSensor == 1) {

      //digitalWrite(out1,LOW);
      digitalWrite(LED, HIGH);
      analogWrite(out1,0);
      count=0;
      count1=0;
      prevTime = millis();
      }
   else if (statusSensor == 1 and switchSensor == 0) {

      //digitalWrite(out1,LOW);
      digitalWrite(LED, LOW);
      analogWrite(out1,0);
      count=0;
      count1=0;
      prevTime = millis();
      }
    else {
      //Serial.println ("ir high");
      //digitalWrite(out1,LOW);
      digitalWrite(LED, HIGH);
      analogWrite(out1,0);
      count=0;
      count1=0;
      prevTime = millis();
      buttonstatus();
      }
}
void doSomethingElse(){

      //Serial.println ("ir high else");
      analogWrite(out1,0);
      count=0;
      count1=0;
      prevTime = millis();
      count2++;
      count3=count2;

      //analogWrite(out1,0);
  }

void buttonstatus(){
  buttonstate=digitalRead (IRSensor);
   if (buttonstate != lastbuttonstate) {
    // if the state has changed,
    if (buttonstate == LOW) {
      count3=0;
    }
    delay(50);
   }
   lastbuttonstate = buttonstate;
}

Comments are not for extended discussion; this conversation has been moved to chat.

I often use a timer loop to read sensors. I've attached some code, which compiles, however I don't have the sensor.
BTW. I am assuming it is a single shot IR sensor that returns 0 if something is detected.
int out1 = 5; //motor
int IRSensor = 3; // connect ir sensor to arduino pin 6
int LED = 6; // conect Led to arduino pin 9
int Switch = 2;
int statusSensor=1;
int switchSensor=1;

unsigned long IRMillis;
int IRInterval = 100;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(out1,OUTPUT);
  //pinMode(out1,OUTPUT);
  pinMode (IRSensor, INPUT); // sensor pin INPUT
  pinMode (LED, OUTPUT); // Led pin OUTPUT
  pinMode(Switch, INPUT_PULLUP);
  IRMillis = millis();
}

void loop() {

   updateIR();

   switchSensor = digitalRead (Switch);

   if ((statusSensor == 0) && (switchSensor == 0)) {
     IRInterval = 3000; // 3 seconds
     statusSensor = 1;
     Serial.println ("ir low");
     analogWrite(out1,120);
     digitalWrite(LED, LOW);
   } else {
     Serial.println ("ir high");
     analogWrite(out1,0);
   }
}

void updateIR() {
  if (millis() - IRMillis > IRInterval) {
    //continue
  } else {
    return;
  }
  IRMillis = millis();
  IRInterval = 100;
  statusSensor = digitalRead (IRSensor);
}

Yes, it returns a 0.

Your interrupt code looks reasonable, except that once you set flag to true you never set it back to false again. You need a way to identify the the IR sensor is no longer active.
Perhaps change your interrupt to fire on a change of state and set the flag to true when it switches to LOW (like it does no) and false when it switches back to high? I'd need to know more about your IR sensor to tell you exactly what to do, but I can tell you that the way your coe is currently written, once you detect the first falling edge on the IRSensor pin, your flag will switch to true and never change back to false.
I also don't understand what all the if/else if/else if logic is supposed to do, so can't really tell if you have any coding errors there.

I'm using an IR sensor which goes low only when an obstacle is detected. There is also float switch (switchsensor) which when goes high (tank being empty), the motor is supposed to go off and turn on an LED. That is why multiple if else statements are there. The same code without the interrupt part (flag) works fine, wherein the motor stops if continuously running for 1.5 seconds. But with interrupt in place, the timing part doesn't work.

Again, your code sets flag=true in the interrupt code, but never sets flag=false. That is wrong.


text:
My indivually addressable LED strip is acting weirdly and I have no idea why
EDIT: I had a typo in the code. I updated the code below to reflect what is shown in the video.
Video of the problem
I'm controlling my LEDs via the Neo_pixel Library for Arduino. My strip (SK6812, RGBW) takes 5V. I wrote very simple instructions for the strip: flash the whole strip one color, rest for 200ms, then flash the whole strip a second color, then rest another 200ms. This should be repeated indefinitely but when either chosen color is red (rgbw[255, 0, 0, 0]) or green (rgbw[0, 255, 0, 0]) the strip will function up as expected for a second or two then remains a solid red or green (depending on which color was chosen). This problem only seems to occur with red or green; blue and white appear to not be an issue. If someone has an idea I should try, please let me know!
The following code is what was executed in the video above:
Neo_Pixel Class Reference
strip.fill(strip.color(255, 0, 0, 0), 0); //fills entire LED strip the color red
strip.show(); //Updates LED strip to reflect changes
delay(200);   //200ms delay
strip.fill(strip.color(0, 0, 0, 255), 0); //fills entire LED strip the color white
strip.show();
delay(200);

There's an error in your code, you're specifying the same color both times.
Also, if you're commanding full-on white, I suspect you may be overloading your power supply and causing it to do whatever it does when you overload the power supply.

That code just shows red over and over.  How would you ever know if that has stopped?  Please post a complete code.

that is not the code that is running in the video ... either delete the video or delete the sketch

try strip.color(32, 0, 0, 0), strip.color(0, 32, 0, 0), etc. If that works you need a bigger PSU.

@Delta_G  Ah that's a typo! I copied the instructions to turn the LED strip red and forgot to change the RGBW value to white. The code now reflects what is shown in the video.

@Harper-ReinstateMonica I thought this might be a problem but I wasn't sure how to tell. I figured if I overloaded the strip, it would go blank instead of remaining a color. I should also mention that the problem does not occur if I light up only half the pixels.

@dandavis I'm still learning the ropes of arduino, is a PSU just power supply?

yup. wall wort. usb charger. psu. dc supply. they have a lot of synonyms...

@dandavis I decreased the RGB values as you suggested and the strip works as expected, guess I gotta get more power! Thanks!


text:
Unable to initialize SD card
I am not able to initialize the SD card. Can't find figure out what the issue is. It fails at the condition
if (!SD.begin(D8)) {
Serial.println("initialization failed!");
return;
}

I am using D1 Mini V2 board and standard SD card module. Pin configuration attached with images below.

Connections are -
GND => GND
VCC => 3.3V
MISO => D6
MOSI => D7
SCK => D5
CS => D8
Code is -
#include <SPI.h>
#include <SD.h>

File myFile;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);

  Serial.print("Initializing SD card...");

  if (!SD.begin(D8)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  myFile = SD.open("test.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }

  // re-open the file for reading:
  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");

    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop() {
  // nothing happens after setup
}

Did you try different SD cards? (preferably smaller older ones, as SDXH for example might not work).

I am using Kingston microSD card

Is it not an SDHC or SDXH card? And did you try it with a default example?

The code copied above is the default example!

I expect the SD card is not supported than. I used a simpler SD card reader for the Uno and it could only read (old) upto 2 GB SD cards.

I myself am using 2gb card. Do you see any error in the code/connection?

this is a 5 V adapter. you have a 3.3 V board

Yep!!, that fixed it, changed VCC=> 5V and it solved the issue. Thanks @Juraj

but you don't need a logic level conversion between esp8266 and SD card adapter. https://i.stack.imgur.com/urotx.jpg

Use "SdFat" library.


text:
Bike Gear Indicator Coding Problem
Lack of practice I forgot many function of C & C++...
Can anyone help me with this coding Please...
I think this is The Main coding:
Topic: Gear indicator
I first found this, Gear_Indicator_Raw
But, There was many problem in those sketch,

Those sketches work just like simple counter,
Can't Show "2" from "0"
No Neutral Detection,

As Bike Gear, (1 N 2 3 4 5) One Down Four up, I made some Changes,
But can't add the Neutral part smoothly...
And here, My code:
#define BUTTON_DOWN 13
#define BUTTON_UP 4
#define BUTTON_N 11

int ledPinA = 7;
int ledPinB = 12;
int ledPinC = 10;
int ledPinD = 9;
int ledPinE = 8;
int ledPinF = 6;
int ledPinG = 5;

int val_up = 0;
int val_down = 0;
int val_n = 0;
int old_val_n = 0;
int old_val_down = 0;
int old_val_up = 0;
int gear = 0;
// The setup() method runs once, when the sketch starts

void setup()
{
  pinMode(BUTTON_N, INPUT);
  pinMode(BUTTON_UP, INPUT);
  pinMode(BUTTON_DOWN, INPUT);

  pinMode(ledPinA, OUTPUT);
  pinMode(ledPinB, OUTPUT);
  pinMode(ledPinC, OUTPUT);
  pinMode(ledPinD, OUTPUT);
  pinMode(ledPinE, OUTPUT);
  pinMode(ledPinF, OUTPUT);
  pinMode(ledPinG, OUTPUT);
}

void led0()
{
  digitalWrite(ledPinA, LOW);
  digitalWrite(ledPinB, LOW);
  digitalWrite(ledPinC, LOW);
  digitalWrite(ledPinD, LOW);
  digitalWrite(ledPinE, LOW);
  digitalWrite(ledPinF, LOW);
  digitalWrite(ledPinG, HIGH);
}
void led1()
{
  digitalWrite(ledPinA, HIGH);
  digitalWrite(ledPinB, LOW);
  digitalWrite(ledPinC, LOW);
  digitalWrite(ledPinD, HIGH);
  digitalWrite(ledPinE, HIGH);
  digitalWrite(ledPinF, HIGH);
  digitalWrite(ledPinG, HIGH);
}
void led2()
{
  digitalWrite(ledPinA, LOW);
  digitalWrite(ledPinB, LOW);
  digitalWrite(ledPinC, HIGH);
  digitalWrite(ledPinD, LOW);
  digitalWrite(ledPinE, LOW);
  digitalWrite(ledPinF, HIGH);
  digitalWrite(ledPinG, LOW);
}
void led3()
{
  digitalWrite(ledPinA, LOW);
  digitalWrite(ledPinB, LOW);
  digitalWrite(ledPinC, LOW);
  digitalWrite(ledPinD, LOW);
  digitalWrite(ledPinE, HIGH);
  digitalWrite(ledPinF, HIGH);
  digitalWrite(ledPinG, LOW);
}
void led4()
{
  digitalWrite(ledPinA, HIGH);
  digitalWrite(ledPinB, LOW);
  digitalWrite(ledPinC, LOW);
  digitalWrite(ledPinD, HIGH);
  digitalWrite(ledPinE, HIGH);
  digitalWrite(ledPinF, LOW);
  digitalWrite(ledPinG, LOW);
}
void led5()
{
  digitalWrite(ledPinA, LOW);
  digitalWrite(ledPinB, HIGH);
  digitalWrite(ledPinC, LOW);
  digitalWrite(ledPinD, LOW);
  digitalWrite(ledPinE, HIGH);
  digitalWrite(ledPinF, LOW);
  digitalWrite(ledPinG, LOW);
}
void led6()
{
  digitalWrite(ledPinA, LOW);
  digitalWrite(ledPinB, HIGH);
  digitalWrite(ledPinC, LOW);
  digitalWrite(ledPinD, LOW);
  digitalWrite(ledPinE, LOW);
  digitalWrite(ledPinF, LOW);
  digitalWrite(ledPinG, LOW);
}
void led7()
{
  digitalWrite(ledPinA, LOW);
  digitalWrite(ledPinB, LOW);
  digitalWrite(ledPinC, LOW);
  digitalWrite(ledPinD, HIGH);
  digitalWrite(ledPinE, HIGH);
  digitalWrite(ledPinF, HIGH);
  digitalWrite(ledPinG, HIGH);
}
void led8()
{
  digitalWrite(ledPinA, LOW);
  digitalWrite(ledPinB, LOW);
  digitalWrite(ledPinC, LOW);
  digitalWrite(ledPinD, LOW);
  digitalWrite(ledPinE, LOW);
  digitalWrite(ledPinF, LOW);
  digitalWrite(ledPinG, LOW);
}
void led9()
{
  digitalWrite(ledPinA, LOW);
  digitalWrite(ledPinB, LOW);
  digitalWrite(ledPinC, LOW);
  digitalWrite(ledPinD, LOW);
  digitalWrite(ledPinE, HIGH);
  digitalWrite(ledPinF, LOW);
  digitalWrite(ledPinG, LOW);
}

void setLed(int number)
{
  switch (number)
  {
    case 0:
      led0();
      break;
    case 1:
      led1();
      break;
    case 2:
      led2();
      break;
    case 3:
      led3();
      break;
    case 4:
      led4();
      break;
    case 5:
      led5();
      break;
    case 6:
      led6();
      break;
    case 7:
      led7();
      break;
    case 8:
      led8();
      break;
    case 9:
      led9();
      break;
  }
}

// the loop() method runs over and over again,
// as long as the Arduino has power

void oldloop()
{
  led0();
  led1();
  led2();
  led3();
  led4();
  led5();
  led6();
  led7();
  led8();
  led9();
}

void loop()
{
//neutral

    val_n =  digitalRead(BUTTON_N);
    if ((val_n == HIGH) &&gear<=2)
    {
      gear = 0;                         //Posted wrong "gear = HIGH"
      delay(100);
    }

// Gear Up

    val_up = digitalRead(BUTTON_UP);
    if ((val_up == HIGH) && (old_val_up == LOW) &&(gear<6) && (gear>0))
    {
      gear += 1;
      delay(100);
    }

    else if ((val_up == HIGH) && (old_val_up == LOW) &&(gear==0))
    {
      gear += 2;
      delay(100);
    }
    old_val_up = val_up;

// Gear Down

    val_down = digitalRead(BUTTON_DOWN);
    if ((val_down == HIGH) && (old_val_down == LOW)&& (gear>1))
    {
      gear -= 1;
      delay(100);
    }

    else   if ((val_down == HIGH) && (old_val_down == LOW) && (gear==0))
    {
      gear += 1;
      delay(100);
    }
    old_val_down = val_down;

// Max Limit

    if (gear >= 5)
    {
      gear = 5;
    }

    setLed(gear);
}

The Problem:

Without the "// neutral" part it's work OK, but can't show "0" without reset.
With the "// neutral" part, While gear up, instead of increasing, display shows "0" after "1".
If I press pin "4" very quickly, then it's increasing to Max gear.

I think there is some problem in this part:
//neutral

    val_n =  digitalRead(BUTTON_N);
    if ((val_n == HIGH) &&gear<=2)
    {
     gear = HIGH;
      delay(100);
    }

And, Please, If anyone can tell me about "Void oldloop()", what this is for?

Likely problem
I'm not sure how to solve the problem, however, I see at least one item that looks strange in the //neutral part:
gear = HIGH;

This seems gear is a pin status (LOW/HIGH), but two lines above:
if ((val_n == HIGH) &&gear<=2)

Here gear is an integer value. This seems quite inconsequent to me.
Pin 4
The reason is you do not have a debouncing algorithm, check for a Debounce Arduino example. When a button is pressed or depressed, it switches sometimes very fast a few times; this might result in multiple increases/decreases of the gear.
oldLoop
The function oldLoop is not used, but if you swap the names of loop and oldLoop you can use the 'test' scenario which is contained in oldLoop.
Some other tips

Use spacing consequently
You can refactor the LED code a lot.
You can use gear++;  to increase or gear--; to decrease.

Update
(Changed debouncing problem for pin 4).
You changed in your neutral code:
gear = 0;

Shouldn't that be gear = 1;? As gear 1 means Neutral (gear 0 is 1).

Oops, sorry, I actually I used "gear=0", But maybe It's a mistake while I was editing it to post here..!!!

Thanks, I shorted the code, as you said, the oldloop is useless, gear++ & gear-- working smoothly... But the neutral function still interrupting with gear up...

Than change the last line from setLed(gear) to setLed(gear == 1 ? 0 : gear) ... at least that's the simplest solution for the code you have now.

No, That does not works for me... But I guess I worked it out with if ((val_up == HIGH) && (val_n == LOW) && (gear>0))... The "oldloop" was confusing me... Let me check couple of times...

All working very good, Also thanks about the debouncing part... It helps... But one last thing... How to ignore "hold" button... Holding the button/sensor little more It keeps increasing/decreasing to max limit... I want the output, only after releasing the button...

You can prevent holding a button when only triggering for a falling edge (i.e. depressing a button), or a rising edge (i.e. pressing a button)... the debounce algorithm will make sure you only have one edge.

kay, after hours I was testing the circuit...The problem raises again...!!! Also change the whole pin set up, then the gear-up running it's own... I think there is issue on pin sensitivity...!! (checked with other boards) Maybe I should use some pull-up resistors...Or use analog pins for Input,,,

No digital pins are ok, but you should indeed use pull-up or pull-down resistors in case the button is depressed.

Yes, I used 10k pull-down... It's working now... Let me check my final & actual project, so I can mark this as solved... :)

Thanks a lot...

Glad it's working!

Your problem is that you are confused about the meaning of gear.
One possible meaning could be 0 = neutral, 1 .. 5 = gear. But then, when changing gears you can't simply do + or -,  as the sequence is 1 - 0 - 2 - 3 - ...
The other interpretation is:  gear-- from 2  means neutral and you display something that indicates neutral ( e.g. a '0' or a '-' ) whenever gear==1, and you display a '1' when you do another gear--, and have a numeric value of 0 in gear.
Your decision.

Actually I was confused about the "oldloop" part, and the original code was very complicated... I kind of shorted it... I think for the 7-segment, it could be done more simple...

Easiest is to change your  switch (number) {   case 0: led1(); break;     case 1:  ledneutral(); break;

All I understand after lots of failing... That, the problem is with Arduino pins sensitivity...!!! -_-  There should be a full list of all common problems..!!!