body:
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>```

title: Weird assembly output

Answers: 2

body:
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:

```lisp
    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:

```lisp
    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.

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


body:
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

title: Quiescent Current Analog Input ESP8266

Answers: 1

body:
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.


body:
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]

title: Getting error invalid conversion from 'const char*' to 'const uint8_t*

Answers: 1

body:
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)


body:
[![enter image description here][1]][1]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.

[![enter image description here][2]][2][![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/29XDm.jpg
  [2]: https://i.stack.imgur.com/JjpjF.jpg
  [3]: https://i.stack.imgur.com/jOZCg.jpg

title: Why do random characters fill up my Arduino LCD Display?

Answers: 0


body:
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.

title: Can you program an ESP32 with an Arduino?

Answers: 0


body:
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!

title: Reset HC-05 from within Arduino sketch

Answers: 1

body: 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.


body:
I'm new to Arduino and try to accomplish following 2 things (via Bluetooth module connected to an Android phone):

1. read an integer value provided by user.
2. 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?

title: Bluetooth: read a user provided value and then obtain time from an Android phone

Answers: 1

body:
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.


body:
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++.

title: request for member 'attribute' in 'object', which is of non-class type 'int'

Answers: 1

body:
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`.


body:
I’m trying to combine [this][1] use of the shift register.
With the [ioAbstaction][2] 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.

  [1]: https://www.instructables.com/id/Driving-Dozens-of-Buttons/
  [2]: https://github.com/davetcc/IoAbstraction

title: How do I use a shift register with ioAbstraction?

Answers: 1

body:
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...


body:
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  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 P 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

[![enter image description here][1]][1]

image-2: Python test code serial terminal screenshot

[![enter image description here][2]][2]

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

[![enter image description here][3]][3]

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

[![enter image description here][4]][4]

image-5: Arduino main project code IDE error

[![enter image description here][5]][5]

So, what did i do wrong?
Thank you!

  [1]: https://i.stack.imgur.com/PjtHz.png
  [2]: https://i.stack.imgur.com/J5dNQ.png
  [3]: https://i.stack.imgur.com/jCmhI.png
  [4]: https://i.stack.imgur.com/GTeU4.png
  [5]: https://i.stack.imgur.com/Liaha.png

title: Serial Read Data Loss With Arduino Nano

Answers: 1

body:
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) {


body:
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 ?

title: what is causing my esp8266 setup function to reinitialise?

Answers: 1

body:
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](https://github.com/me-no-dev/EspExceptionDecoder).

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


body:
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.

title: Complier overwrote bootloader doing a non-programmer upload

Answers: 0


body:
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 https://arduino.stackexchange.com/questions/21603/mounting-arduino-in-an-enclosure

title: Mount arduino metro mini

Answers: 1

body:
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.


body:
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.

title: Impossibility to open a file for modification in ESP32

Answers: 0


body:
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()][1] 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__
    }

  [1]: https://learn.adafruit.com/memories-of-an-arduino/measuring-free-memory

title: Serial printing from flash memory (F() macro, PROGMEM, sprintf_P, SPTR)

Answers: 2

body:
> 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.

body:
First, the [freeMemory()](https://learn.adafruit.com/memories-of-an-arduino/measuring-free-memory) function that you used from Adafruit was originated from a [GitHub repository](https://github.com/mpflaga/Arduino-MemoryFree).

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](https://www.nongnu.org/avr-libc/user-manual/group__avr__pgmspace.html). 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](https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/WString.h#L37-L38) 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](https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/Print.cpp#L44-#L55) 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][1]* (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.

  [1]: https://www.arduino.cc/reference/en/language/variables/utilities/progmem/


body:
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

title: How can I identify GPS sattelites in TinyGPS++?

Answers: 1

body:
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


body:
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

title: HC-05 master and slave

Answers: 1

body:
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.


body:
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...

title: Hardware/software serial for HC-05

Answers: 2

body:
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.

body:
- **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.


body:
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.

title: I connected a bipolar stepper motor with an HC-SRO4 distance sensor but the motor doesn't work

Answers: 0


body:
I am trying to convert 1-5V to 0-20mA which is then used to drive VFD.

[![enter image description here][1]][1]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?

  [1]: https://i.stack.imgur.com/EgBW3.png

title: Convert 1-5V to 4-20mA using Arduino

Answers: 0


body:
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;
    }

title: Running a motor for a 3 seconds continuously with and without interrupt

Answers: 2

body:
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);
    }

body:
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.


body:
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](https://imgur.com/gallery/BE3DTWU?s=sms)

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](https://adafruit.github.io/Adafruit_NeoPixel/html/class_adafruit___neo_pixel.html#a19fc274330c0e65907929ee03b93b1c3)

    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);

title: My indivually addressable LED strip is acting weirdly and I have no idea why

Answers: 0


body:
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.
[![Board][1]][1]
[![SD Module][2]][2]

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
    }

  [1]: https://i.stack.imgur.com/z63Hx.png
  [2]: https://i.stack.imgur.com/AC4OJ.png

title: Unable to initialize SD card

Answers: 0


body:
Lack of practice I forgot many function of C & C++...
Can anyone help me with this coding Please...

  [1]: https://forum.arduino.cc/index.php?topic=103620.0;wap
  [2]: https://github.com/BlueAG/Gear-1/blob/master/Gear_Indicator_Raw/Gear_Indicator_Raw.ino
I think this is The Main coding:
[Topic: Gear indicator][1]

I first found this, [Gear_Indicator_Raw][2]

**But, There was many problem in those sketch,**

 1. Those sketches work just like simple counter,
 2. Can't Show "2" from "0"
 3. 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:**

 1. Without the "// neutral" part it's work OK, but can't show "0" without reset.
 2. With the "// neutral" part, While **gear up**, instead of increasing, display shows "0" after "1".
 3. 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?

title: Bike Gear Indicator Coding Problem

Answers: 2

body:
**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).

body:
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.


body:
In a nutshell i want to read a PORTB 5th pin without using digitalRead API ( i am trying to learn baremetal using arduino-uno-r3)

Just to Learn How internal register works i did not used digitalRead API, instead i have used DDRB register to set the 5 bit of DDRB as Low indicating PORTB 5th pin is in input mode then i am using an if statment to check if 5th bit of PINB is high or low my expection was that when i connect arduino pin 13 to 5v  if statment will become TRUE.

    void setup() {
      // put your setup code here, to run once:
      DDRB = DDRB & ~(1<<5);
      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      if(PINB & (1<<5)){
         Serial.println("Got data");
        }
    }

When i executed above code i am constantly getting if as TRUE

title: I am trying to read input from 5th PIN of PORT B?

Answers: 1

body:
There seem to be several, separate issues in your question.

One is a simple matter of language. In English, “1st” is an abbreviation
for “first”, which is an ordinal adjective applied to an item in a list
meaning that there is no other item before it in that list. In the same
vein, “5th” means “fifth”, which applies to the item that has exactly
four items before it. For instance, the list of pins of port B is {PB0,
PB1, PB2, PB3, PB4, PB5}. PB0 is the first in the list, and PB4 is the
fifth. The fact the first item bears the number 0 makes this confusing.
Thus, I recommend avoiding ordinal adjectives altogether and instead
calling the pins by their names, like “digital 13” (Arduino naming) or
“PB5” (AVR naming).

The second issue, and probably your main concern, is about the floating
input pin. You cannot expect a reliable reading from a floating input. I
will not try to explain why, as the issue has been discussed ad nauseam
here and elsewhere. Just do a Web search. The simplest solution is to
use the built-in pull-up resistor and externally connect a push button
between the pin and ground. You will read `LOW` whenever the button is
pressed:

```c++
void setup() {
    pinMode(13, INPUT_PULLUP);
    Serial.begin(9600);
}

void loop() {
    if (digitalRead(13) == HIGH)
        Serial.println("HIGH");
    else
        Serial.println("LOW");
}
```

The last point is about going bare metal and learning how to use the I/O
registers directly. A small warning first: you have to keep in mind that
this is board-specific. You tagged your question with both “arduino-uno”
and “arduino-mega”, but these boards have different pin mappings
(digital 13 is PB7 on the Mega). The general way of using the DDRx,
PORTx and PINx registers is the same across all AVR chips, but is not
portable to Arduinos based on a different architecture.

So let's assume this is intended to work only on an Uno, Nano, or
other board based on an ATmega328P.
Judging from the example code you show, you seem to
already understand pretty well how these registers work. There is no
problem in your code, beside the fact that it requires an external
pull-up. If you want to enable the internal pull-up, you have to set the
appropriate bit in PORTB. This can seem confusing, as the same register
is used for pull-up control (when the pin is in input mode) and for
output control (when the pin is an output). Essentially, each GPIO pin
has four distinct electrical states which are controlled by to I/O bits:

    │ DDRxn │ PORTxn │ state        │
    ├───────┼────────┼──────────────┤
    │   0   │    0   │ INPUT        │
    │   0   │    1   │ INPUT_PULLUP │
    │   1   │    0   │ OUTPUT LOW   │
    │   1   │    1   │ OUTPUT HIGH  │
    └───────┴────────┴──────────────┘

The example program above can be translated to low-level AVR style as
follows:

```c++
void setup() {
    DDRB &= ~_BV(PB5);  // input mode
    PORTB |= _BV(PB5);  // enable pullup
    Serial.begin(9600);
}

void loop() {
    if (PINB & _BV(PB5))
        Serial.println("HIGH");
    else
        Serial.println("LOW");
}
```


body: I saw that it is possible [to sync time from an NTP server over WiFi](https://randomnerdtutorials.com/esp32-date-time-ntp-client-server-arduino/). I have the HC-06 Bluetooth module and an Android phone that can share its Internet connection with Arduino via Bluetooth. Would it be possible to sync time/date using this infrastructure? And if yes - how (which libraries, etc..)? Has anybody done it already and there is a tutorial on that?

title: Bluetooth: sync time from an NTP server via Internet connection shared with Android phone

Answers: 1

body:
No, not really. It is possible, but not easily like you want it to be. The HC-06 is a Bluetooth-Serial bridge. In the Bluetooth protocol there are many types of interfaces, that a client device might expose to the master. A Bluetooth mouse exposes a HID interface, a headset exposes a corresponding audio interface and the HC-06 exposes a pure Serial interface. Thus the HC-06 does not support what ever interface is used for tethering.

Ways, that may make it possible:

- Change the firmware of the HC-06 for exposing the correct interface and interact with it. For this you need to know how to reprogram the HC-06 and how exactly bluetooth works. I guess this is over your current level.

- Write an app for your Andriod smartphone, which plays the Serial-Internet bridge on the phone. The app would translate between Serial and Internet, involving your own protocol on the Serial interface. Easiest, when you just make a specialized app for syncing time, so that it does not have to do any other communication.

And at that point it is just too much work to go either way. It is unlikely, that you find libraries or any code for this, since it just doesn't make much sense. Instead you could move from an Arduino to an ESP, which can directly connect to the WiFi network in question and thus get directly the time from the internet, without tethering. That is way easier and you can use the many libraries, that already exist for that problem.


body:
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 why the serial comes up with unusual characters whenever I am trying to print off variable values. The serial is able to print text, but whenever I try to print variable values the unusual characters come up. I had tried changing the baud to a higher one and that makes no difference. The two variables that I am trying to print off both have an integer data type. I have tried using `Serial.write`, `Serial.print` and `Serial.println`, none of these seem to work. Here is the code if it helps solve the problem:

    #include "LedControl.h"
    #include <LiquidCrystal.h>
    LedControl lc=LedControl(12,10,11,1);
    LiquidCrystal lcd(8, 13, 3, 5, 6, 7);

    class Snake_body
    {

      public:

        int following_direction;
        int x;
        int y;
        int previous_x;
        int previous_y;
        bool enabled;
        Snake_body()
        {
          this->enabled = false;
        }

        void configure(int x_value, int y_value)
        {
          this->enabled = true;
          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;
    };

    Snake_body *snake[64];//this is the snake array that contains the snake objects

    int snakes_length;

    Power_up *power_up;//define the power up object

    int score;

    void setup() {

      Serial.begin(9600);

      lcd.begin(16, 2);

      snakes_length = 1;

      for(int z = 1; z < 64; z++)
      {
        snake[z] = new Snake_body();//create 63 un-enabled snake objects
      }

      snake[0] = new Snake_body();//the 1st snake object is defined
      snake[0]->configure(0,0);//here it is initialised
      power_up = new Power_up();//create the power_up object

      lc.shutdown(0,false);
      lc.setIntensity(0,8);
      lc.clearDisplay(0);
      lcd.setCursor(0, 0);
      score = 0;
      lcd.print("score: ");
      lcd.setCursor(6, 0);
      lcd.print(score);
      pinMode(2, INPUT);
      digitalWrite(2, HIGH);

      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)//each of the if statements are for the direction of the snake head (snake[0])
       {
         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)//used for snake movement
      {
        snake[0]->previous_x = snake[0]->x;
        snake[0]->x += 1;
      }

      else if(snake[0]->following_direction == 1 && snake[0]->x > 0)//used for snake movement
      {
        snake[0]->previous_x = snake[0]->x;
        snake[0]->x -= 1;
      }

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

      else if(snake[0]->following_direction == 3 && snake[0]->y < 7)//used for snake movement
      {
        snake[0]->previous_y = snake[0]->y;
        snake[0]->y += 1;
      }

      if(snake[0]->x == power_up->x && snake[0]->y == power_up->y)//used for collision with power up
      {
        score += 1;
        lcd.setCursor(6,0);
        lcd.print(score);

        power_up->x = random(0, 8);
        power_up->y = random(0, 8);

        for(int j = 0; j < 64; j++)
        {
          if(snake[j]->enabled == false)//enables the next un-enabled snake object in the array
          {
             //Serial.println(true);
             Snake_body *snake[j];

             //next_snake_body = new Snake_body();
             //Snake_body next_snake_body;
             snake[j] = new Snake_body();
             snake[j]->configure(snake[j-1]->previous_x, snake[j-1]->previous_y);
             //Serial.print("x: " + snake[j-1]->previous_x);
             //Serial.print("y: " + snake[j-1]->previous_y);
             snake[j]->following_direction = NULL;
             break;
          }
        }
      }

      for(int i = 1; i < 64; i++)
      {
        if(snake[i]->enabled == true)//updates each snake object in the array
        {

          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);//draws the power up
      for(int w = 0; w < 64; w++)
      {
        if(snake[w]->enabled == true)//draws each snake object that is enabled
        {
          Serial.print("x: " + snake[w]->x);
          Serial.print("y: " + snake[w]->y);
          lc.setLed(0,snake[w]->x,snake[w]->y,true);
        }
      }

      /*Serial->print("x: ");
      Serial->print(snake->x);
      Serial->println();

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

      delay(100);

      lc.clearDisplay(0);
    }

the weird characters that show up are characters like this:
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/Ub9c0.png

with the follow picture `y` is just simply text to show which axis it is, the weird characters are the integer y axis value of the snake object that is being looked at.

title: Arduino serial coming up with weird characters

Answers: 0