body:
I was trying to use nodemcu for a project. No issues when uploading the OTA sample code. Added led blink to test. But when trying to upload the second sketch via OTA getting an error
>no response from device.

Tried ping to the Nodemcu IP and no issue there. Have the OTA codes in both sketch.
When trying to upload the 2nd second, the led blink will stop for 2,3 seconds and resumes the normal blinking, gets an error in ide after.

How to check if there is any firewall issue?

IDE settings

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

Attaching code below

```
const char* ssid = STASSID;
const char* password = STAPSK;

void setup() {
  Serial.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);

  Serial.println("Booting");
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Connection Failed! Rebooting...");
    delay(5000);
    ESP.restart();
  }

  // Port defaults to 8266
  // ArduinoOTA.setPort(8266);

  // Hostname defaults to esp8266-[ChipID]
  // ArduinoOTA.setHostname("myesp8266");

  // No authentication by default
  // ArduinoOTA.setPassword("admin");

  // Password can be set with it's md5 value as well
  // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
  // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");

  ArduinoOTA.onStart([]() {
    String type;
    if (ArduinoOTA.getCommand() == U_FLASH) {
      type = "sketch";
    } else { // U_FS
      type = "filesystem";
    }

    // NOTE: if updating FS this would be the place to unmount FS using FS.end()
    Serial.println("Start updating " + type);
  });
  ArduinoOTA.onEnd([]() {
    Serial.println("\nEnd");
  });
  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  });
  ArduinoOTA.onError([](ota_error_t error) {
    Serial.printf("Error[%u]: ", error);
    if (error == OTA_AUTH_ERROR) {
      Serial.println("Auth Failed");
    } else if (error == OTA_BEGIN_ERROR) {
      Serial.println("Begin Failed");
    } else if (error == OTA_CONNECT_ERROR) {
      Serial.println("Connect Failed");
    } else if (error == OTA_RECEIVE_ERROR) {
      Serial.println("Receive Failed");
    } else if (error == OTA_END_ERROR) {
      Serial.println("End Failed");
    }
  });
  ArduinoOTA.begin();
  Serial.println("Ready");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  ArduinoOTA.handle();

  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
  delay(100);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(100);

  Serial.println("Looping");
}
```

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

title: Nodemcu OTA - no response issue

Answers: 0


body:
I uploaded in my custom board (ATmega2560 with an external oscillator 16MHz) the MegaCore bootloader using the AVR pinout. I found that when I switch on the board the pin PB7 is activated 2 short times. This happens even with a blank Arduino sketch.

I found out that the problem was the reset pin connection. When the reset pin (for uploading a new sketch) is connected to the board I got the previous behaviour.

How can the reset pin affect only the pin PB7?

PS I found this issue even in the Arduino Mega standard bootloader.

title: MegaCore ATmega2560 PB7 activation randomly at boot

Answers: 1

body:
PB7 is pin 13. That's the traditional LED pin.

The bootloader blinks that LED to indicate it's active.

If you want other behaviour then you will have to compile your own version of the bootloader that doesn't blink the LED.


body:
I am trying to smoke test my Seeeduino XIAO (Arduino-compatible) board with an IMU sensor, the MPU 6050. I mainly care about the accelerometer and gyroscope values.

But when I run my Arduino code on the XIAO, I am only getting -1 values in the Serial Monitor. When I first smoke tested the MPU 6050, I actually saw regular X,Y,Z values (e.g. 123, -456, etc), but it disappeared after a few readings. Both the microcontroller and IMU chips are able to power on, since they both display the LED light. The XIAO seems to display a blue LED light when it is transmitting/receiving data, but I am not entirely sure that is what is going on.

The MPU 6050 communicates via I2C, so I have connected Vcc to 3.3V on the XIAO since I read somewhere that the MPU 6050 runs on 3.3V, Gnd to Gnd, SCL to Pin 5 on the XIAO, SDA to Pin 4, and the INT pin to Pin 2 (not sure if I need the INT pin or not, but I read that it helped clear the buffer I think). Then I have the XIAO connected to my laptop's 5V USB port. Also not sure if I need to connect to 3.3V or 5V from the MPU to the XIAO.

Any idea why I am getting -1 values? I also occasionally get 0 values, but mostly -1s.
Here is a snippet of the output I am getting on the Serial Monitor:

```
12:06:32.476 -> AccX = 0 || AccY = 0 || AccZ = 0 || Temp = 36.53 || GyroX = 0 || GyroY = 0 || GyroZ = 0
12:06:32.578 -> AccX = 0 || AccY = 0 || AccZ = 0 || Temp = 36.53 || GyroX = 0 || GyroY = 0 || GyroZ = 0
12:06:32.681 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:33.057 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:33.159 -> AccX = 0 || AccY = 0 || AccZ = 0 || Temp = 36.53 || GyroX = 0 || GyroY = 0 || GyroZ = 0
12:06:33.465 -> AccX = 0 || AccY = 0 || AccZ = 0 || Temp = 36.53 || GyroX = 0 || GyroY = 0 || GyroZ = 0
12:06:33.566 -> AccX = 0 || AccY = 0 || AccZ = 0 || Temp = 36.53 || GyroX = 0 || GyroY = 0 || GyroZ = 0
12:06:33.738 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:33.841 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:34.014 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:34.390 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:34.492 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:34.596 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:34.699 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:34.903 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:36.378 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:36.480 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:36.584 -> AccX = 0 || AccY = 0 || AccZ = 0 || Temp = 36.53 || GyroX = 0 || GyroY = 0 || GyroZ = 0
12:06:37.064 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:37.710 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:38.122 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:38.257 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:38.393 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:38.529 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
12:06:38.664 -> AccX = -1 || AccY = -1 || AccZ = -1 || Temp = 36.53 || GyroX = -1 || GyroY = -1 || GyroZ = -1
```

Here is the code I found on some tutorial website:
https://www.electronicshub.org/getting-started-arduino-mpu6050/

```
#include<Wire.h>
const int MPU6050_addr=0x68;
int16_t AccX,AccY,AccZ,Temp,GyroX,GyroY,GyroZ;
void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU6050_addr);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);
  Serial.begin(9600);
}
void loop(){
  Wire.beginTransmission(MPU6050_addr);
  Wire.write(0x3B);
  Wire.endTransmission(false);
  Wire.requestFrom(MPU6050_addr,14,true);
  AccX=Wire.read()<<8|Wire.read();
  AccY=Wire.read()<<8|Wire.read();
  AccZ=Wire.read()<<8|Wire.read();
  Temp=Wire.read()<<8|Wire.read();
  GyroX=Wire.read()<<8|Wire.read();
  GyroY=Wire.read()<<8|Wire.read();
  GyroZ=Wire.read()<<8|Wire.read();
  Serial.print("AccX = "); Serial.print(AccX);
  Serial.print(" || AccY = "); Serial.print(AccY);
  Serial.print(" || AccZ = "); Serial.print(AccZ);
  Serial.print(" || Temp = "); Serial.print(Temp/340.00+36.53);
  Serial.print(" || GyroX = "); Serial.print(GyroX);
  Serial.print(" || GyroY = "); Serial.print(GyroY);
  Serial.print(" || GyroZ = "); Serial.println(GyroZ);
  delay(100);
}
```

Attached is my current electronics setup. Yes, I know I should have used a breadboard, but I did not have one on me at the time. The connection was not stable, so maybe that messed with the readings.

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

  [1]: https://i.stack.imgur.com/giIGV.jpg

title: Why am I only getting -1 values in the Serial Monitor, when interfacing with the MPU 6050?

Answers: 1

body:
There may be a couple of issues to consider:

1. In the [6050 specification][1] we see that the 6050 can be configured to show up at address 0x68 or 0x69.  In the photo there appears to be no connection to a pin (AD0?) which may control the 6050 address.  The code appears to expect the 6050 at address 0x68. (Note: The board the 6050 comes on may already deal with this issue by including a pull up or pull down resistor.)

2. An I2C bus normally needs pull up resistors on the data and clock lines as all drivers are normally of type open collector.  Here is part of a figure from the 6850's specification document:

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

(Note: The board the 6050 comes on may already deal with this issue by including 2 pull up resistor.)

3. Look for a working project which is the same or nearly the same as yours.  [Here is a project][3] that uses the same 6050 board connected to an Arduino Uno.

4. Consider if the libraries and other supporting software are truly abstracting your [XIAO hardware][4] (in this case an SAMD21CortexM0+ processor) (the real Arduino Uno uses a ATmega328P processor).  It would not be the first time trying to emulate an Arduino using different and more powerful processors has affected otherwise working sketches with unexpected behaviors.

5. Finally, there appears to be many schematics many with and a few without a 5 volt to 3.3 volt LDO regulators. It may be even with a Low Drop Out regulator that supplying the board with 3.3 volts will not result in 3.3 volts at the 6050 chip.  This may lead to problems.  But supplying a board with no regulator with 5 volts may damage the 6050 chip. Here is one of the schematics found:

[![enter image description here][6]][6]

(Note: In this schematic, the data and clock lines are pulled high on the board.  And pin 9 (AD0) of the 6050 chip is pulled low.)

  [1]: https://cdn.sparkfun.com/datasheets/Components/General IC/PS-MPU-6000A.pdf
  [2]: https://i.stack.imgur.com/XeEUy.jpg
  [3]: https://www.instructables.com/GY-521-MPU6050-3-Axis-Acceleration-Gyroscope-6DOF-/
  [4]: https://media.digikey.com/pdf/Data Sheets/Seeed Technology/102010328_Web.pdf
  [5]: https://components101.com/sites/default/files/inline-images/MPU6050-Circuit_0.png
  [6]: https://i.stack.imgur.com/qkJmn.png


body:
I've got an Arduino Uno (Elegoo R3) and a Hc-05 bluetooth module. First of all i want to send data with an android app (Bluetooth terminal) to the Arduino and turn pin 13 (LED) on.

My Arduino code:

    #include <SoftwareSerial.h>

    int state = 0;

    void setup() {
      //Serial.begin(38400);
      Serial.begin(9600);

      pinMode(13, OUTPUT);
    }

    void loop() {
      if (Serial.available() > 0) {
        state = Serial.read();

        if (state == '1') {
          Serial.println("Turned on LED");

          digitalWrite(13, HIGH);
        }

        if (state == '0') {
          Serial.println("Turned off LED");

          digitalWrite(13, LOW);
        }
      }
    }

The RX and TX pins I have hooked up with the HC-05 but if I connect my smartphone with the HC-05 and type in a 1 or a 0 nothing happens. If I type a 1 or a 0 in my serial monitor on my computer (hooked up via usb to my arduino) it turns the LED on/off. The RX and TX lights also flashes one time. The bluetooth terminal app recognises all what was sent via serial monitor on pc and displays it in the app. But if I type something in the app, it won't flip the LED or show me some "Turned off LED" or "Turned on LED".

I also tried different apps from the PlayStore but all of them didn't work.

Does someone has an idea how I could fix this? Thank you for your answers.

EDIT: A drawing how my Arduino is connected to my HC-05 https://i.stack.imgur.com/N2YsJ.jpg

title: Arduino with HC-05 Bluetooth Module | No data will be transmitted

Answers: 1

body:
> The TX signal coming from either the Arduino or HC-05 should be
> connected to the RX of the other as I understand it, because both are
> labeled from the perspective of their respective chips

Like @timemage already said, I connected TX with TX and RX with RX but this is wrong. The solution was to plug TX (Arduino) with RX (HC-05) and RX (Arduino) with TX (HC-05).

Thank you for your help. :)


body:
I'm using a [PN532 module][1] to read/write [NTAG213 tags][2]. They both should be working at 13.56 MHZ, and [Adafruit should support these tags in their library][3].

The Arduino Uno board and the module are connected as follows

    PN532 Module  |  Arduino Uno
    --------------+-------------
    VCC        |  5V
    GND        |  GND
    SCK        |  D2
    MI            |  D5
    MO/SDA/TX    |  D3
    NSS        |  D4

SPI is enabled on the PN532 module:

    SET 0 -> L
    SET 1 -> H

[Using the `ntag2xx_read` example provided by the library][3], I can pick up MIFARE tags, with an error thrown in the Serial Monitor.

    This doesn't seem to be an NTAG203 tag (UUID length != 7 bytes)!

So far, so good. But when I try to place one of my NTAG213 tags, ***nothing happens***. I thought maybe I'd need to change [the page read to match NTAG213 specs (instead of default NTAG203)][4] but unsurprisingly id didn't change anything.

I'm not sure where to go from there. I don't know whether there's some hardware incompatibility or if I'm missing something in the setup or the code. Any help would be greatly appreciated.

The NTAG213 tags can be read with a smartphone.

----------

The code I'm using is exactly the same as the one linked from the library above (besides page read), I'm pasting it here for future reference

    /**************************************************************************/
    /*!
        @file     readntag203.pde
        @author   KTOWN (Adafruit Industries)
        @license  BSD (see license.txt)

        This example will wait for any NTAG203 or NTAG213 card or tag,
        and will attempt to read from it.

        This is an example sketch for the Adafruit PN532 NFC/RFID breakout boards
        This library works with the Adafruit NFC breakout
          ----> https://www.adafruit.com/products/364

        Check out the links above for our tutorials and wiring diagrams
        These chips use SPI or I2C to communicate.

        Adafruit invests time and resources providing this open source code,
        please support Adafruit and open-source hardware by purchasing
        products from Adafruit!
    */
    /**************************************************************************/
    #include <Wire.h>
    #include <SPI.h>
    #include <Adafruit_PN532.h>

    // If using the breakout with SPI, define the pins for SPI communication.
    #define PN532_SCK  (2)
    #define PN532_MOSI (3)
    #define PN532_SS   (4)
    #define PN532_MISO (5)

    // If using the breakout or shield with I2C, define just the pins connected
    // to the IRQ and reset lines.  Use the values below (2, 3) for the shield!
    #define PN532_IRQ   (2)
    #define PN532_RESET (3)  // Not connected by default on the NFC Shield

    // Uncomment just _one_ line below depending on how your breakout or shield
    // is connected to the Arduino:

    // Use this line for a breakout with a software SPI connection (recommended):
    Adafruit_PN532 nfc(PN532_SCK, PN532_MISO, PN532_MOSI, PN532_SS);

    // Use this line for a breakout with a hardware SPI connection.  Note that
    // the PN532 SCK, MOSI, and MISO pins need to be connected to the Arduino's
    // hardware SPI SCK, MOSI, and MISO pins.  On an Arduino Uno these are
    // SCK = 13, MOSI = 11, MISO = 12.  The SS line can be any digital IO pin.
    //Adafruit_PN532 nfc(PN532_SS);

    // Or use this line for a breakout or shield with an I2C connection:
    //Adafruit_PN532 nfc(PN532_IRQ, PN532_RESET);

    void setup(void) {
      Serial.begin(115200);
      while (!Serial) delay(10); // for Leonardo/Micro/Zero

      Serial.println("Hello!");

      nfc.begin();

      uint32_t versiondata = nfc.getFirmwareVersion();
      if (! versiondata) {
        Serial.print("Didn't find PN53x board");
        while (1); // halt
      }
      // Got ok data, print it out!
      Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
      Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
      Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

      // configure board to read RFID tags
      nfc.SAMConfig();

      Serial.println("Waiting for an ISO14443A Card ...");
    }

    void loop(void) {
      uint8_t success;
      uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
      uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)

      // Wait for an NTAG203 card.  When one is found 'uid' will be populated with
      // the UID, and uidLength will indicate the size of the UUID (normally 7)
      success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

      if (success) {
        // Display some basic information about the card
        Serial.println("Found an ISO14443A card");
        Serial.print("  UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
        Serial.print("  UID Value: ");
        nfc.PrintHex(uid, uidLength);
        Serial.println("");

        if (uidLength == 7)
        {
          uint8_t data[32];

          // We probably have an NTAG2xx card (though it could be Ultralight as well)
          Serial.println("Seems to be an NTAG2xx tag (7 byte UID)");

          // NTAG2x3 cards have 39*4 bytes of user pages (156 user bytes),
          // starting at page 4 ... larger cards just add pages to the end of
          // this range:

          // See: http://www.nxp.com/documents/short_data_sheet/NTAG203_SDS.pdf

          // TAG Type       PAGES   USER START    USER STOP
          // --------       -----   ----------    ---------
          // NTAG 203       42      4             39
          // NTAG 213       45      4             39
          // NTAG 215       135     4             129
          // NTAG 216       231     4             225

          for (uint8_t i = 0; i < 45; i++)
          {
            success = nfc.ntag2xx_ReadPage(i, data);

            // Display the current page number
            Serial.print("PAGE ");
            if (i < 10)
            {
              Serial.print("0");
              Serial.print(i);
            }
            else
            {
              Serial.print(i);
            }
            Serial.print(": ");

            // Display the results, depending on 'success'
            if (success)
            {
              // Dump the page data
              nfc.PrintHexChar(data, 4);
            }
            else
            {
              Serial.println("Unable to read the requested page!");
            }
          }
        }
        else
        {
          Serial.println("This doesn't seem to be an NTAG203 tag (UUID length != 7 bytes)!");
        }

        // Wait a bit before trying again
        Serial.println("\n\nSend a character to scan another tag!");
        Serial.flush();
        while (!Serial.available());
        while (Serial.available()) {
        Serial.read();
        }
        Serial.flush();
      }
    }

And nothing happens in the monitor after the setup

    22:28:56.855 -> Hello!
    22:28:56.888 -> Found chip PN532
    22:28:56.888 -> Firmware ver. 1.6
    22:28:56.922 -> Waiting for an ISO14443A Card ...

If I uncomment `#define PN532DEBUG` in `Adafruit_PN532.cpp`, I get some extra logs but still none when I pass my NTAG213 tag. Adding a timeout doesn't help the tag to be detected either.

    // Passing the NTAG213 here
    15:51:00.519 -> Sending : 0x0, 0x0, 0xFF, 0x4, 0xFC, 0xD4, 0x4A, 0x1, 0x0, 0xE1, 0x0,
    15:51:01.582 -> TIMEOUT!
    15:51:01.582 -> No card(s) read
    15:51:01.582 -> Sending : 0x0, 0x0, 0xFF, 0x4, 0xFC, 0xD4, 0x4A, 0x1, 0x0, 0xE1, 0x0,
    15:51:02.614 -> TIMEOUT!
    15:51:02.614 -> No card(s) read
    15:51:02.614 -> Sending : 0x0, 0x0, 0xFF, 0x4, 0xFC, 0xD4, 0x4A, 0x1, 0x0, 0xE1, 0x0,

    // Passing another tag here
    15:51:03.212 -> Reading:  0x0 0x0 0xFF 0xC 0xF4 0xD5 0x4B 0x1 0x1 0x0 0x4 0x8 0x4 0x47 0xF5 0xC 0xD8 0xAE 0x0 0xAA
    15:51:03.212 -> Found an ISO14443A card
    15:51:03.212 ->   UID Length: 4 bytes
    15:51:03.249 ->   UID Value: 0x47 0xF5 0x0C 0xD8
    15:51:03.249 ->
    15:51:03.249 -> This doesn't seem to be an NTAG203 tag (UUID length != 7 bytes)!
    15:51:03.249 ->
    15:51:03.249 ->
    15:51:03.249 -> Send a character to scan another tag!

  [1]: https://fr.aliexpress.com/item/4001169120990.html
  [2]: https://fr.aliexpress.com/item/32960281764.html
  [3]: https://github.com/adafruit/Adafruit-PN532/blob/master/examples/ntag2xx_read/ntag2xx_read.ino
  [4]: https://github.com/adafruit/Adafruit-PN532/blob/master/examples/ntag2xx_read/ntag2xx_read.ino#L114

title: NP532 doesn't detect NTAG213 tag

Answers: 0


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

To save power, I removed the linear regulator from my Arduino Nano clone and powered it via the 5V pin from a regulated source (a rechargeable USB phone charger). However, I've noticed that removing the linear regulator causes the TX pin to stay on all the time, which results in my phone not being able to communicate with the HC05 bluetooth module although it connects fine. I checked that the TX pin is not caused by `Serial.print` and noticed the same behavior on all the Nano's I've removed linear regulators from. The Nano's I've tested with the linear regulator work fine, though they use more power than I'd like. I've tried resetting the device, but the problem persists.

I'm wondering what's causing this? Isn't powering via 5V pin suppose to bypass the regulator? So what could cause the missing regulator to affect the TX pin? Unfortunately, I'm not experienced enough to connect the dots using the schematic so I was hoping someone could help me.

Though I'm not sure if it'll help, I'ved included my sketch below. Basically, I'm making using a ultrasonic sensor to communicate distance with my phone via bluetooth. It also plays music when it detects movement (using PIR sensor). Since the application is outdoor use I'm powering via battery and trying to minimize energy use. I got it down to ~4 mA by removing linear regulator.

    #include <avr/sleep.h>

    #define bluetoothIntPin 2
    #define pirInterruptPin 3
    volatile int state = 0;

    int bt_pin = 9;
    int pirPin = 8;
    int stateData = 0;
    int ultraPin = 10;
    int trigPin = 11;    // Trigger
    int echoPin = 12;    // Echo
    int piezoPin = 5;
    long duration, cm;
    unsigned char inches;
    unsigned long timer;
    volatile bool signalReceived = false;
    volatile bool pirSignalReceived = false;
    bool toggle_pir = false;
    int incomingByte = 0;
    bool song_in_progress = false;
    int song_type = 69;

    int nokia_melody[] = {

      // Nokia Ringtone
      // Score available at https://musescore.com/user/29944637/scores/5266155

      NOTE_E5, 8, NOTE_D5, 8, NOTE_FS4, 4, NOTE_GS4, 4,
      NOTE_CS5, 8, NOTE_B4, 8, NOTE_D4, 4, NOTE_E4, 4,
      NOTE_B4, 8, NOTE_A4, 8, NOTE_CS4, 4, NOTE_E4, 4,
      NOTE_A4, 2,
    };

    void setup() {
      pinMode(13, OUTPUT); //set pin 13 as output
      pinMode(ultraPin, OUTPUT);
      pinMode(trigPin, OUTPUT);
      pinMode(pirPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(LED_BUILTIN, OUTPUT);
      digitalWrite(bt_pin, HIGH);
      digitalWrite(bluetoothIntPin, HIGH);
      digitalWrite(pirInterruptPin, HIGH);
      digitalWrite(ultraPin, LOW);
      digitalWrite(pirPin, LOW);
      Serial.begin(9600); // Default communication rate of the Bluetooth module
      attachInterrupt(digitalPinToInterrupt(bluetoothIntPin), bluetooth_interrupt, CHANGE);
      attachInterrupt(digitalPinToInterrupt(pirInterruptPin), pir_interrupt, CHANGE);
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);
      sleep_enable();
      sleep_cpu();
    }

    void pir_interrupt(){
      // play sound effect
      digitalWrite(LED_BUILTIN, HIGH);
      delay(5000);
      digitalWrite(LED_BUILTIN, LOW);
      pirSignalReceived = true;
    }

    void bluetooth_interrupt(){
      state = !state;
      signalReceived = true;
    }

    void play_song(int melody[], int notes){
          // sizeof gives the number of bytes, each int value is composed of two bytes (16 bits)
        // there are two values per note (pitch and duration), so for each note there are four bytes

        // this calculates the duration of a whole note in ms
        song_in_progress = true;
        int wholenote = (60000 * 4) / tempo;

        int divider = 0, noteDuration = 0;
        for (int thisNote = 0; thisNote < notes * 2; thisNote = thisNote + 2) {

        // calculates the duration of each note
        divider = melody[thisNote + 1];
        if (divider > 0) {
          // regular note, just proceed
          noteDuration = (wholenote) / divider;
        } else if (divider < 0) {
          // dotted notes are represented with negative durations!!
          noteDuration = (wholenote) / abs(divider);
          noteDuration *= 1.5; // increases the duration in half for dotted notes
        }

        // we only play the note for 90% of the duration, leaving 10% as a pause
        tone(piezoPin, melody[thisNote], noteDuration * 0.9);

        // Wait for the specief duration before playing the next note.
        delay(noteDuration);

        // stop the waveform generation before the next note.
        noTone(piezoPin);
      }
      song_in_progress = false;
    }

    void play_tone_once(){
      if (!song_in_progress){
         if (song_type==69){
          int notes = sizeof(nokia_melody) / sizeof(nokia_melody[0]) / 2;
          play_song(nokia_melody, notes);
        }
        if (song_type==79){
          int notes = sizeof(starwars_melody) / sizeof(starwars_melody[0]) / 2;
          play_song(starwars_melody, notes);
        }
      }
    }

    void loop() {
      if (signalReceived){
        sleep_disable();
        Serial.write(50);
        delay(500);
        timer = millis();
        digitalWrite(ultraPin, HIGH);
        digitalWrite(pirPin, HIGH);
        while (true){
            digitalWrite(trigPin, LOW);
            delayMicroseconds(2);
            digitalWrite(trigPin, HIGH);
            delayMicroseconds(10);
            digitalWrite(trigPin, LOW);
            pinMode(echoPin, INPUT);
            duration = pulseIn(echoPin, HIGH);
            cm = (duration / 2) / 29.1;   // Divide by 29.1 or multiply by 0.0343
            inches = (duration / 2) / 74; // Divide by 74 or multiply by 0.0135
            Serial.write(inches);
            delay(50);
            incomingByte = Serial.read();
            if (pirSignalReceived){
              play_tone_once();
              pirSignalReceived = false;
            }
            else if (incomingByte == 69){ // automatic pir
              song_type = 69; //nokia
            }
            else if (incomingByte == 79){
              song_type = 79; // starwars
            }
            else if (incomingByte == 89){
              toggle_pir = !toggle_pir;
              if (toggle_pir){
                digitalWrite(pirPin, HIGH); // automate tone
              } else {
                digitalWrite(pirPin, LOW);
              }
            }
            else if (incomingByte == 99){
              digitalWrite(pirPin, LOW);
              play_tone_once();
            }
            if (incomingByte != 49 && incomingByte!=69 && incomingByte != 79 && incomingByte != 89 && incomingByte != 99){
              // receipt from android
              unsigned long timeElapse = millis() - timer;
              if (timeElapse > 7000) {
                break; // exit and SLEEP
              }
            }
            else {
                // reset the timer
                timer = millis();
              }
      }
      digitalWrite(pirPin, LOW);
      digitalWrite(ultraPin, LOW);
      digitalWrite(LED_BUILTIN, LOW);
      signalReceived = false;
      sleep_enable();
      sleep_cpu();
      }
    }

  [1]: https://i.stack.imgur.com/hTIVl.jpg

title: TX Pin Stays Lit After Removing Voltage Regulator

Answers: 1

body:
My Nano clone appears to be the same make as yours.  Certainly the underside of it looks identical.  On my clone, and I believe yours, the TX LED is wired as follows

```#
5V -- RESISTOR -- LED -- TXD/D1
```

The 5V node is just the 5V pin which is fed by USB bus voltage via a diode or by the output of the AMS1117 voltage regulator.  The TTL level serial TX signal idles high and sinks current through the LED when transmitting the start bit and low data bits.  Incidentally, the RX led is wired in the same manner.  By contrast the official Nano uses an FTDI that has dedicated LED driving pins.

It seems likely that you have bridged something with the solder that was holding the AMS1117 on the board in the process of removing it.  I would note that the regulator is mounted directly under the LEDs and their current limiting resistors and there are at least three vias in that part of the board.


body:
I have a weird problem, and it's probably because I'm doing something wrong. I'm quite new to Arduino.

My Uno R3 (Elegoo) has been working fine for a month. It has been sitting on a bench for the past week, unused though. Last night I tried to push a sketch from the IDE: v1.8.14 on Windows 10 Pro (fully updated), board: Arduino Uno, Com port 5. I got this error:

```
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe6

```

So, I googled it and tried to fix it. No luck. And, the code changes frequently (right now it's 0x3a). So, I tried

* Using the blink sketch
* Rebooting my laptop
* Using a different USB port
* Using a different USB cable
* Using different settings in the IDE (Mega 2560 with the ATMega2560 processor)
* Using a different operating system (Ubuntu) on a different laptop with a different version of the IDE (1.8.13)
* Using a different Arduino (A Freenove Uno r3 from a robot kit)

Using a different board on windows does work! So, my original board is bricked maybe?

I got the same result, more or less. The only difference was that the response code changed. On Ubuntu, the response code is always 0x00 so I suspect the changing code is down to some problem in windows (I trust Linux a lot more than windows). I used the default blink sketch for all these attempts.

Note: I do have a green 'on' led and the L is orange and does the 3xflash on powerup and reset. This is the only USB port in use, so there's only one to choose in the IDE (happens to be com5) and it's clearly shown as Arduino. When I push the sketch, the orange L led stays solid orange and there is no flashing of the rx or tx leds.

Update:
I have read, with interest:
https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board/13293#13293

Because of this I have now checked the power rail with a multimeter and found 5v and 3.3v respectively on USB, and with a 9v battery I have 3.3v and 7.8v respectively. The L led flashes 3 times as expected on power up and reset.

Also, I have nothing attached to the board at all.

When I tried the loopback test the board would not power-on with reset connected to ground, so I don't know how to proceed with that.

I have just tried the Atmega16U2 chip test, and it failed. I'm pretty sure the wiring is correct (though it's hard to tell -- I can't find a dot indicating pin 1 on the good board so I'm guessing it's close to the 'n' in 'on' as mentioned in the post).

How could I have damaged this? What could I have possibly done to break that? I was only driving leds.

title: Can't sync with programmer Arduino Uno

Answers: 2

body:
A few things to make sure:

 - Disconnect your Arduino from any sensor or module
 - Closely look at the Arduino to see any signs of worn-out solder or damage
 - Make sure that the programming USB cable is plugged in all the way on the Arduino and the computer
 - Check the temperature of the ATMEGA chip, as well as, the voltage regulator

If everything looks normal there, you can try reflashing the bootloader on it. You can only do this if you have another Arduino Uno. Here is a good guide: https://www.instructables.com/How-to-Upload-Bootloader-to-Any-Arduino-/. Try that and then comment on what worked and what did not.

body:
Sometimes boards can glitch depending on wear and tear or on how well they have been manufactured. Personally I always buy boards direct from the Arduino store and  I have never had this issue. One thing that could help is placing a 0.1 uF capacitor between the +5V pin and ground and another between AVcc and ground. There will be some on the PCB already but this can help in some cases. Another thing that can help is pressing the reset buttom just after pressing upload on your PC.

Unfortunately, when out of sync errors occur it can be heavily luck based as to what works and how long it takes. Hopefully one of these tricks will work! But like you say, if other boards are working fine then it could just be bricked


body:
My UNO having some stability issues because of  heavy memory use, I'm now optimizing the code
now looking to reduce the digital read memory use with the help of port manipulation. I got the code for      'digitial write' but no idea for the digital read pinMode(powerStatus, INPUT);digitalRead(powerStatus)
Thanks

title: Port manipulation

Answers: 1

body:
To read a pin you simply read the port the pin is part of then mask out which pin within that port you want to read.

For example to read pin D11 you need to read bit 3 of port B.

```
if (PINB & (1 << 3)) {
    // HIGH
} else {
    // LOW
}
```

However this doesn't address the underlying problems you're having with your sketch.  Saving on flash memory by optimizing your code will not fix instabilities (if anything it will introduce new instabilities from new untested code).

Instabilities related to memory are due to a lack of (or fragmentation of) SRAM not flash.  Optimizing code like this will save flash, but won't directly affect your SRAM usage at all.

Instead you need to optimize your SRAM usage by:

* Make sure all string literals are kept in PROGMEM by using the `F()` macro where appropriate
* Avoid use of `String` and instead stick to `char *` with pre-allocated buffers.
* Don't use `new` and `delete` or `malloc` and `free` as this will fragment your heap and cause instability (this is the underlying problem with `String`).


body:
I need to record the appearance of a signal from the sensor on the PD0 pin. This is the first time in my life that I want to use an interrupt for this.
With your help, I configured the sketch for my pin PD0

    #include <avr/interrupt.h>

    volatile int value = 0;

    void setup()
    {
      cli();
      PCICR |= 0b00000100;    // turn on port d
      PCMSK2 |= 0b00000001;    // turn on pins PD0 (PCINT16)
      sei();

      Serial.begin(9600);
    }

    void loop()
    {
      Serial.println(value);
    }

    ISR(PCINT2_vect)// Port D, PCINT16 - PCINT23
    {
      value++;
    }

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

I need to wait and take a certain action when a high signal comes from the sensor. For example, add one to the constant.[![enter image description here][2]][2]
I also did not understand when interruptions occur. When the signal changes from bottom to top, when from top to bottom, or no matter how? Can't see if these settings are here? Maybe it is set somehow by default?

  [1]: https://i.stack.imgur.com/uLmaQ.jpg
  [2]: https://i.stack.imgur.com/FJHcK.jpg

title: Assign an interrupt to any pin of the atmega328 microcontroller

Answers: 1

body:
Here is a link to a good tutorial on how to enable, respond to, and clear interrupts on the ATMega328P device:

[Arduino Pin Change Interrupts][1]

I'll repeat the overall steps here in case this URL disappears in the future:

First, you must enable pin change interrupts:

[![Pin change Interrupts][2]][2]

Note the use of 3 bits in the PCICR register [0:2].  These enable pin change interrupts on ports B, C, or D in general.  You can choose any combination of these ports or all of the ports as you desire.

Next, you select which pin or pins on the enabled ports that you want to receive interrupts from.  You have control here over each individual port bit:

[![Pin Change Bits][3]][3]

Then you must write an ISR (Interrupt Service Routine) to handle the interrupt once it occurs.  You have the option of up to THREE ISRs, one to handle each port or you can have a single ISR to handle any pin change interrupt.  The way this works is that when an interrupt happens on an enabled port and pin, the AVR chip calls the ISR that you have configured for that event:

[![AVR ISR][4]][4]

So when an interrupt happens, how do you know which pin(s) caused the ISR?  Let's assume you used a single ISR to handle all 3 ports.  At this point you know only that an interrupt happened somewhere.  That's the purpose of the PCIFR register bits.  From the AVR datasheet we see this:

[![AVR PCIFR Bits][5]][5]

By checking the status of these bits you can now tell which pin or pins caused the interrupt.  Note that there CAN BE MORE THAN ONE, so it's up to you to decide the priority of each one and handle them accordingly.  Note that you only get ONE chance to read these during any ISR function call since they get cleared when the ISR executes.

One last note.  You MUST call the sei(); function to enable any interrupt to the CPU before any interrupt will happen.

In your example, however, you seem to be attempting to generate a pin change interrupt on an output. This is probably NOT what you want.  Try simply using the existing LED output pin as an indicator and choose a different pin, setup as INPUT, to be your pin change interrupt source.

  [1]: https://thewanderingengineer.com/2014/08/11/arduino-pin-change-interrupts/
  [2]: https://i.stack.imgur.com/Tfc7J.png
  [3]: https://i.stack.imgur.com/6WjYK.png
  [4]: https://i.stack.imgur.com/SMMx4.png
  [5]: https://i.stack.imgur.com/6ocpk.png


body:
I'm currently in the process of making a DIY pen plotter using an Arduino CNC Shield and GRBL Code. Right now I'm connecting the power supply to the shield. I got a standard 12v supply and I cut off the barrel connector so I can connect the supply directly to the CNC Shield. I can't seem to figure out which wire is negative and which is positive. I don't have a multimeter on me so can't test it but I have attached a picture of the information on the power supply which I think should be able to give someone with more knowledge, insight onto the polarity. I think the left wire is negative but not one hundred percent sure. If I risk a test will this damage my circuits or power supply ? Sorry for such an easy question I just don't want to accidentally fry my circuits as have been working on this for a really long time !!
Thank you so much,
Arav[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/Aggxn.jpg

title: Will plugging in a 12v power supply in the wrong polarity to a CNC SHIELD fry my circuit or damage my power supply?

Answers: 1

body:
If you wire the power into that shield wrongly you risk killing things - and with those big electrolytics reverse polarity could get *very* messy indeed.

You need to identify the polarity before you wire it in, and to do that you need something that is sensitive to polarity.

If you don't have a DMM you can do it with a simple resistor and LED in series - an LED will only work if the polarity is right.

Take a normal LED of the 5mm type (they're easier to identify) and look for the flat edge on the flange around the base. That indicates which is the "negative" or cathode of the LED.  Alternatively look for which of the legs is the shorter of the two, which is also an indication of which is the cathode.

Connect a resistor to this identified negative leg. You want the resistor to be at least 1kΩ, but no more than 10kΩ. You don't need the LED to be bright...

Connect your wires, one to the LED and the other to the resistor.

If the LED lights up then the wire connected to the LED is positive and the wire connected to the resistor is negative.  If it doesn't light up then the wires are reversed.  In this case check it by swapping the wires over - the LED should now light up.


body:
```c++
#include <AFMotor.h>
#include <NewPing.h>
#include <Servo.h>

#define TRIG_PIN A0
#define ECHO_PIN A1
#define MAX_DISTANCE 200
#define MAX_SPEED 190
#define MAX_SPEED_OFFSET 20

NewPing sonar (TRIG_PIN,ECHO_PIN,MAX_DISTANCE);

AF_DCMotor motor1(1, MOTOR12_1KHZ);
AF_DCMotor motor2(2, MOTOR12_1KHZ);
AF_DCMotor motor3(3, MOTOR34_1KHZ);
AF_DCMotor motor4(4, MOTOR34_1KHZ);

Servo myservo;
boolean goesForward=fclose;
int distance = 100;
int speedSet = 0;

void setup() {
  myservo.attach(10);
  myservo.write(115);
  delay(2000);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
}

void loop() {
  int distanceR = 0;
  int distanceL = 0;
  delay (40);

  if (distance <= 15); {
    moveStop();
    delay(100);
    moveForward();
    delay(300);
    moveStop();
    delay(200);
    distanceR = lookRight();
    delay(200);
    distanceL = lookLeft();
    delay(200);

    if (distanceR>=distanceL) {
      turnRight();
      moveStop();
    } else {
      turnLeft();
      moveStop();
    }}else {
      moveForward();
    }
      distance=readPing();
  }

  int lookRight() {
    myservo.write(170);
    delay(500);
    int distance=readPing();
    delay(100);
    myservo.write(115);
    return distance;
    delay(100);
  }

  int readPing() {
    delay(70);
    int cm = sonar.ping_cm();
    if (cm ==) {
      cm=250;
    }
      return cm;
  }

  void moveStop() {
    motor1.run(RELEASE);
    motor2.run(RELEASE);
    motor3.run(RELEASE);
    motor4.run(RELEASE);
  }

  void moveForward() {
    if (!goesForward) {
      goesFORWARD=true;
      motor1.run(FORWARD);
      motor2.run(FORWARD);
      motor3.run(FORWARD);
      motor4.run(FORWARD);
      for (speedSet=0; speedSet<MAX_SPEED;speedSet+=2) {
        motor1.setSpeed(speed.Set};
        motor2.setSpeed(speed.Set};
        motor3.setSpeed(speed.Set};
        motor4.setSpeed(speed.Set};
        delay(5);
      }
    }
  }

  void moveBackward() {
    goesFORWARD=false;
    motor1.run(BACKWARD);
    motor2.run(BACKWARD);
    motor3.run(BACKWARD);
    motor4.run(BACKWARD);
    for (speedSet=0; speedSet<MAX_SPEED;speedSet+=2) {
      motor1.setSpeed(speed.Set};
      motor2.setSpeed(speed.Set};
      motor3.setSpeed(speed.Set};
      motor4.setSpeed(speed.Set};
      delay(5);
    }
  }

  void moveRight() {
    motor1.run(FORWARD);
    motor2.run(FORWARD);
    motor3.run(BACKWARD);
    motor4.run(BACKWARD);
    delay (500);
    motor1.run(FORWARD);
    motor2.run(FORWARD);
    motor3.run(FORWARD);
    motor4.run(FORWARD);
  }

  void moveRight() {
    motor1.run(BACKWARD);
    motor2.run(BACKWARD);
    motor3.run(FORWARD);
    motor4.run(FORWARD);
    delay (500);
    motor1.run(FORWARD);
    motor2.run(FORWARD);
    motor3.run(FORWARD);
    motor4.run(FORWARD);
  }

```
this is the error code
```
Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "Arduino Uno"
C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino: In function 'void loop()':

sketch_nov27b:53:13: error: 'lookLeft' was not declared in this scope
 distanceL = lookLeft();
             ^~~~~~~~

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino:53:13: note: suggested alternative: 'lookRight'

 distanceL = lookLeft();
             ^~~~~~~~
              lookRight

sketch_nov27b:58:1: error: 'turnRight' was not declared in this scope
 turnRight();
 ^~~~~~~~~

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino:58:1: note: suggested alternative: 'lookRight'

 turnRight();
 ^~~~~~~~~
 lookRight

sketch_nov27b:62:1: error: 'turnLeft' was not declared in this scope
 turnLeft();
 ^~~~~~~~

Sketch_nov27b:65:4: error: 'else' without a previous 'if'

   }else

    ^~~~

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino: In function 'int readPing()':

sketch_nov27b:86:10: error: expected primary-expression before ')' token

   if(cm==)

          ^

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino: In function 'void moveForward()':

sketch_nov27b:104:1: error: 'goesFORWARD' was not declared in this scope

 goesFORWARD=true;

 ^~~~~~~~~~~

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino:104:1: note: suggested alternative: 'FORWARD'

 goesFORWARD=true;

 ^~~~~~~~~~~

 FORWARD

sketch_nov27b:111:17: error: 'speed' was not declared in this scope

 motor1.setSpeed(speed.Set};

                 ^~~~~

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino:111:17: note: suggested alternative: 'speedSet'

 motor1.setSpeed(speed.Set};

                 ^~~~~

                 speedSet

sketch_nov27b:112:17: error: 'speed' was not declared in this scope

 motor2.setSpeed(speed.Set};

                 ^~~~~

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino:112:17: note: suggested alternative: 'speedSet'

 motor2.setSpeed(speed.Set};

                 ^~~~~

                 speedSet

sketch_nov27b:113:17: error: 'speed' was not declared in this scope

 motor3.setSpeed(speed.Set};

                 ^~~~~

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino:113:17: note: suggested alternative: 'speedSet'

 motor3.setSpeed(speed.Set};

                 ^~~~~

                 speedSet

C:\Users\amish\Documents\Arduino\sketch_nov27b\sketch_nov27b.ino: At global scope:

sketch_nov27b:114:1: error: 'motor4' does not name a type

 motor4.setSpeed(speed.Set};

 ^~~~~~

sketch_nov27b:114:26: error: expected declaration before '}' token

 motor4.setSpeed(speed.Set};

                          ^

Multiple libraries were found for "Servo.h"

 Used: C:\Users\amish\Documents\Arduino\libraries\Servo

 Not used: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\libraries\Servo

exit status 1

'lookLeft' was not declared in this scope

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
```

title: i was trying to rebuild my code for my bot but then there are errors coming up i am in the middle of my project so i need quick help

Answers: 1

body:
Your code is riddled with typographical and basic syntax errors. Such things as using brackets instead of parentheses, semicolons after an `if` meaning it will do nothing, etc.

Sort out your basic syntax errors (hint: autoformat can help you with the indenting to highlight your problems) and you will see where you have gone wrong.

For instance, after autoformatting your code with `astyle` the `moveForward()` function has turned into this mess:

``` 98 void moveForward() {
 99     if (!goesForward) {
100         goesFORWARD = true;
101         motor1.run(FORWARD);
102         motor2.run(FORWARD);
103         motor3.run(FORWARD);
104         motor4.run(FORWARD);
105
106         for (speedSet = 0; speedSet < MAX_SPEED; speedSet += 2) {
107             motor1.setSpeed(speed.Set
108         };
109
110         motor2.setSpeed(speed.Set
111     };
112
113     motor3.setSpeed(speed.Set
114 };
115 motor4.setSpeed(speed.Set
116 };
117 delay(5);
118 }
119 }
120 }
```

Also, you have no `lookLeft` function - instead you have two `lookRight` functions.  You really should *read* what you've written.


body:
I have created a gui in python that allows an arduino controlled mecanum wheel cart to move around.

The cart allows for 8 different move directions and can rotate left and right. Commands are sent over a serial connection between the laptop(w10, python) and the arduino.

I have an Enum class in python representing the different move directions.

I have a corresponding enum in the arduino to interprete the commands from the python task.

What is an easy way to share a single common enum definition for both coding environments?

title: share enum between python and arduino

Answers: 1

body:
One approach that I have used for similar purposes is to generate the appropriate header files (or module or whatever) from a simple text file for all the required uses.

Since you already know python this should be pretty easy. Quick "proof of concept" follows. (Warning: I barely know any python.)

One downside to this is that you have to remember to regenerate the header/module each time you update the enum (keys or values) - don't forget to recompile for the C++ part. If you have a build system, it is best to integrate that code generation step into it.

A variation of this is to parse one of the language's source code to extract the definition and output it in a format suitable for the other. That is generally much harder to do though if you want to make it robust.

---

### robot.enum

    UP    1
    DOWN  2
    LEFT  3
    RIGHT 4
    JUMP  5

### enum_generator.py

<!-- language: lang-python -->

    def python_enum(filename):
        with open(filename, 'w') as w:
            w.write('class Robot(Enum):\n')
            with open('robot.enum') as r:
                for line in r:
                    parts = line.split()
                    w.write(f'    {parts[0]} = {parts[1]}\n')

    def cplusplus_enum(filename):
        with open(filename, 'w') as w:
            w.write('#pragma once\n')
            w.write('enum Robot: int {\n')
            with open('robot.enum') as f:
                for line in f:
                    parts = line.split()
                    w.write(f'  {parts[0]} = {parts[1]},\n')
            w.write('};');

    python_enum('robot_enum.py')
    cplusplus_enum('robot_enum.h')


body:
```c++
#include <Servo.h>

const int x =  200

//Naming the servosServo
Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4;
Servo servo5;
Servo servo6;

void setup()
{
  Serial.begin(9600);
  servo2.attach(10);
  servo3.attach(11);
  servo4.attach(3);
  servo5.attach(6);
  servo6.attach(5);
}

void loop()
{
  //Printing the EMG data
  Serial.println(analogRead(0));

  if (analogRead(5) > 200)
  {
    servo2.write(180);
    servo3.write(148);
    servo4.write(89);
    servo5.write(180);
    servo6.write(180);
  } else if (analogRead(0) < 200)
  {
    servo2.write(38);
    servo3.write(10);
    servo4.write(0);
    servo5.write(16);
    servo6.write(16);
  }

  delay(100);
}
```

- I don't know if the problem is in the code or in the circuit.

title: Does anybodyknow how to program Muscle Sensors v3?

Answers: 0


body:
What would happen if I connected a fan as shown in the following picture:

[![Fan connected to +12V of the power supply and GND of the arduino][1]][1]

 - +12V is supplied by the power supply that also powers the Arduino.
 - GND, however, is connected to a GND pin of the Arduino instead of the power supply.

I guess that would not work? Or are GND from the Arduino and GND from the power supply identical in this case?

----------

If you read the accepted answer, please also note the comments below. The power consumption of the consumer (fan) is important.

  [1]: https://i.stack.imgur.com/FNoHH.jpg

title: Are the GND pins of an Arduino identical to GND of its power supply?

Answers: 1

body:
"Ground" is just a lump of metal and each ground "pin" is connected to it. That includes the ground connection in the barrel jack. It's all one thing.

Wherever you connect your fan's ground to it's all ground.  That is, as long as all grounds external to the Arduino are connected, ultimately, to the Arudino.


body:
I am working with TinyGPS++ library and Arduino-nano and I want to change the update rate.
I worked before with Adafruit GPS and uses the below code for updating it.

    // Set the update rate
     GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);   // 1 Hz update rate

I have also worked with `NMEAGPS.h` to update every 30sec.

    gps.send_P( &gpsPort, F("PMTK220,30000") );        //update 1time in 30s

So how to change the upsate rate for TinyGPS++ library? as I want to update 1 time in 30seconds.

title: How to change the update rate in TinyGPS++?

Answers: 0


body:
I am quite noobish with using the interrupts on Arduino and I am facing a strange problem. I am using an Arduino Pro Mini, a light sensor and an RTC module(DS3231) which has set 2 alarms, one at sunrise and one at the sunset. Each time the DST triggers the alarm, the interrupt routine (here onAlarm()) blocks the state of Arduino and nothing happens form there. Is there anything wrong with the code I write?

The code bellow is a little bit simplified, I just let the method calls, not the whole declarations of them.

    #include <avr/sleep.h>//this AVR library contains the methods that controls the sleep modes
    #include <avr/power.h>
    #include <DS3232RTC.h>  //RTC Library https://github.com/JChristensen/DS3232RTC

    #define ldrInterruptPin  2
    #define DS2331interruptPin 3

    void setup() {

      Serial.begin(9600);//Start Serial Comunication
      Wire.begin();

      //_____________________setup DS3231 interrupts_________
      pinMode(DS2331interruptPin, INPUT_PULLUP);
      digitalWrite(DS2331interruptPin, HIGH);
      attachInterrupt(digitalPinToInterrupt(DS2331interruptPin), onAlarm, FALLING);

      //_____________________setup LD235R interrupts_________
      pinMode(ldrInterruptPin, INPUT);
      digitalWrite(ldrInterruptPin, HIGH);
      attachInterrupt(digitalPinToInterrupt(ldrInterruptPin), irq1, RISING);

      resetDS3231Alarms();

      time_t t = RTC.get();
      setUpAlarms();
    }

    void loop() {
     //read the light sensor vlaues
    }

Adn this is the onAlarm function:

      void onAlarm() {
      Serial.println("ALARM");
      formatTime(timestamp, RTC.get());
      if (RTC.alarm(ALARM_1))
      {
        Serial << F("SLEEP alarm at ") << timestamp << endl;
        goToSleep();
      }
      else if (RTC.alarm(ALARM_2))
      {
        Serial << F("WakeUP Alarm at ") << timestamp << endl;

        Serial.println("Time to Wake up......!");
        sleep_disable();
        Serial.println("I woke up!!!");
        attachInterrupt(digitalPinToInterrupt(ldrInterruptPin), irq1, RISING);
      }
      //update the sleep and wakeup times based on curreent day
      setUpAlarms();
    };

resetAlarms()

    void resetDS3231Alarms() {
      // initialize the alarms to known values, clear the alarm flags, clear the alarm interrupt flags
      RTC.setAlarm(ALM1_MATCH_DATE, 0, 0, 0, 1);
      RTC.setAlarm(ALM2_MATCH_DATE, 0, 0, 0, 1);
      RTC.alarm(ALARM_1);
      RTC.alarm(ALARM_2);
      RTC.alarmInterrupt(ALARM_1, false);
      RTC.alarmInterrupt(ALARM_2, false);
      RTC.squareWave(SQWAVE_NONE);
    }

Every time an alarm occurs, the code blocks and outputs exactly what is in the serial monitor capture bellow:
It just prints "AL" form the Serial.println("ALARM"); and nothing happens from there

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

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

Does anyone know what causes this issue and how can it be solved?

title: Arduino with interrupts enters in a locking state

Answers: 1

body:
When the AVR processor goes to sleep, the _only_ way it can wake up is
by an interrupt. If it goes to sleep with interrupts disabled, then it
will never wake up.

Interrupt routines are by default non-interruptible: the first thing the
processor does when servicing an interrupt is to disable further
interrupts. Your `onAlarm()` function is thus running with interrupts
disabled. If it goes to sleep, it will lock the processor.

A quick and dirty fix would be to call `interrupts()` right before going
to sleep. I would not recommend that though, as you will end up piling
interrupt contexts one over another. The proper fix would be to trim
down your interrupt  service routines to the bare minimum that must be
done immediately, and handle everything else in regular code, within
`loop()`. In this particular case, setting a `volatile bool` might well
be the only thing you really need to do. Your `loop()` would test that
`bool` and take care of everything else.


body:
I have bought an Arduino starter kit online. Everything seem to work, but when I try for example to use `if`s (and other conditional statements), the LEDs do not turn on. Here is the code for a little project I am currently working on:

```c++
int redpin = 3;
int greenpin = 2;
int bluepin = 4;
String color;
String msg = "Insert color: ";

void setup() {
  // put your setup code here, to run once:
  pinMode(redpin,OUTPUT);
  pinMode(greenpin,OUTPUT);
  pinMode(bluepin,OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println(msg);
  while (Serial.available() == 0) {}
  color = Serial.readString();

  if (color == "red") {
    digitalWrite(redpin, HIGH);
    digitalWrite(greenpin, LOW);
    digitalWrite(bluepin, LOW);
  }
  if (color == "green") {
    digitalWrite(greenpin, HIGH);
    digitalWrite(redpin, LOW);
    digitalWrite(bluepin, LOW);
  }
  if (color == "blue") {
    digitalWrite(greenpin, LOW);
    digitalWrite(redpin, LOW);
    digitalWrite(bluepin, HIGH);
  }

  if (color == "off") {
    digitalWrite(greenpin, LOW);
    digitalWrite(redpin, LOW);
    digitalWrite(bluepin, LOW);
  }
}
```

I tried turning on the RGB LED with single `digitalWrite()` functions and it works. I think that the `if` statements in the code are the problem.

I`m using an Arduino Mega 2560 BTW.

title: Comparing a String after reading it from Serial fails

Answers: 1

body:
After `color = Serial.readString();` `color` also contains a newline character.

You can remove that by adding the line `color.trim();`, or even better, avoid the newline altogether by using `Serial.readStringUntil('\n');` which discards the terminating newline character.

Also, you could, and maybe should, avoid using the `String` class and use:
```c++
char color[10]; // char array as buffer for reading from Serial
```
```c++
int number = Serial.readBytesUntil('\n', color, 10); //Read input and length
color[number] = '\0'; //Terminate the string by adding '\0' at its end
```
```c++
if (strcmp(color, "red") == 0) //Use strcmp(), not ==
```
respectively.


body:
I'm trying to use a cheap keyboard with 37 keys as a MIDI controller by reading the multiplexed keys with an Arduino nano. The keys are grouped in six groups with a max of 8 keys per group. Which results in my setup of 8 digital INPUTS which are pulled HIGH, and 6 OUTPUTS, which are pulled LOW, when reading that group of keys.
This works great when I only have 3 groups in my loop. However whenever I add another group it does not work anymore. It doesn't matter which groups are activated.

One group reading looks like this:

    digitalWrite(A0, LOW);
    for (byte j = 12; j > 4; j--)
    {
      uint8_t note = offset + 20 + (12-j);
      uint8_t key_state = digitalRead(j);

      if ( (key_state == 0) && (notes_pressed[note] == 1) )
      {
        notes_pressed[note] = 0;
        Serial.write(note + 100);
      } else if ( (key_state == 1) && (notes_pressed[note] == 0) )
      {
        notes_pressed[note] = 1;
        Serial.write(note);
      }
    }
    digitalWrite(A0, HIGH);

With A0 being the group pin.

I think this has to do with the pins not being able to be pulled low as quickly because of weak output drivers or something similar. Unfortunately I don't have an oscilloscope to check the levels.
I have added delays to ensure the levels have settled when the reading occurs but to no avail.

Edit:
Schematic is pretty much just this. The diodes in the keyboard I left out, but they are there as necessary:
[![schematic][1]][1]

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

    #include "HardwareSerial.h"

    #define offset 48

    void midi_note_off(byte channel, byte key, byte velocity);
    void midi_note_on(byte channel, byte key, byte velocity);
    void midi_command(byte command, byte channel, byte param1, byte param2);

    byte notes_pressed[37];
    void setup() {
      Serial.begin(115200);
      pinMode(12, INPUT_PULLUP);
      pinMode(11, INPUT_PULLUP);
      pinMode(10, INPUT_PULLUP);
      pinMode(9, INPUT_PULLUP);
      pinMode(8, INPUT_PULLUP);
      pinMode(7, INPUT_PULLUP);
      pinMode(6, INPUT_PULLUP);
      pinMode(5, INPUT_PULLUP);
      pinMode(4, OUTPUT);
      pinMode(3, OUTPUT);
      pinMode(2, OUTPUT);
      pinMode(A2, OUTPUT);
      pinMode(A1, OUTPUT);
      pinMode(A0, OUTPUT);

      digitalWrite(4, HIGH);
      digitalWrite(3, HIGH);
      digitalWrite(2, HIGH);
      digitalWrite(A0, HIGH);
      digitalWrite(A1, HIGH);
      digitalWrite(A2, HIGH);
    }

    void loop() {
      digitalWrite(4, LOW);
      for (byte j = 8; j > 4; j--)
      {
        uint8_t note = offset + (8-j);
        uint8_t key_state = digitalRead(j);

        if ( (key_state == 0) && (notes_pressed[note] == 1) )
        {
          notes_pressed[note] = 0;
          Serial.write(note + 100);
        } else if ( (key_state == 1) && (notes_pressed[note] == 0) )
        {
          notes_pressed[note] = 1;
          Serial.write(note);
        }
      }
      digitalWrite(4, HIGH);

      digitalWrite(3, LOW);
      for (byte j = 12; j > 4; j--)
      {
        uint8_t note = offset + 4 + (12 - j);
        uint8_t key_state = digitalRead(j);

        if ( (key_state == 0) && (notes_pressed[note] == 1) )
        {
          notes_pressed[note] = 0;
          Serial.write(note + 100);
        } else if ( (key_state == 1) && (notes_pressed[note] == 0) )
        {
          notes_pressed[note] = 1;
          Serial.write(note);
        }
      }
      digitalWrite(3, HIGH);

      digitalWrite(2, LOW);
      for (byte j = 12; j > 4; j--)
      {
        uint8_t note = offset + 12 + (12-j);
        uint8_t key_state = digitalRead(j);

        if ( (key_state == 0) && (notes_pressed[note] == 1) )
        {
          notes_pressed[note] = 0;
          Serial.write(note + 100);
        } else if ( (key_state == 1) && (notes_pressed[note] == 0) )
        {
          notes_pressed[note] = 1;
          Serial.write(note);
        }
      }
      digitalWrite(2, HIGH);

      digitalWrite(A0, LOW);
      for (byte j = 12; j > 4; j--)
      {
        uint8_t note = offset + 20 + (12-j);
        uint8_t key_state = digitalRead(j);

        if ( (key_state == 0) && (notes_pressed[note] == 1) )
        {
          notes_pressed[note] = 0;
          Serial.write(note + 100);
        } else if ( (key_state == 1) && (notes_pressed[note] == 0) )
        {
          notes_pressed[note] = 1;
          Serial.write(note);
        }
      }
      digitalWrite(A0, HIGH);

      digitalWrite(A1, LOW);
      for (byte j = 12; j > 4; j--)
      {
        uint8_t note = offset + 28 + (12-j);
        uint8_t key_state = digitalRead(j);

        if ( (key_state == 0) && (notes_pressed[note] == 1) )
        {
          notes_pressed[note] = 0;
          Serial.write(note + 100);
        } else if ( (key_state == 1) && (notes_pressed[note] == 0) )
        {
          notes_pressed[note] = 1;
          Serial.write(note);
        }
      }
      digitalWrite(A1, HIGH);

      digitalWrite(A2, LOW);
      for (byte j = 5; j > 4; j--)
      {
        uint8_t note = offset + 36 + (5-j);
        uint8_t key_state = digitalRead(j);

        if ( (key_state == 0) && (notes_pressed[note] == 1) )
        {
          notes_pressed[note] = 0;
          Serial.write(note + 100);
        } else if ( (key_state == 1) && (notes_pressed[note] == 0) )
        {
          notes_pressed[note] = 1;
          Serial.write(note);
        }
      }
      digitalWrite(A2, HIGH);
    }

I know the last part looping over a single value is unnessecary but it should still work.

title: Multiplexing a piano keyboard with arduino nano

Answers: 2

body:
There are several issues to be considered when designing a [switch matrix][1] for an embedded processor regardless if it is a musical or computer keyboard:

 1. [Contact bounce][2]: This is more important for a computer keyboard
    then a musical keyboard.  However if the switch are particularly
    bad, it may audible.  Software may be used to mitigate the problem
    but will also add delay between the key press and the beginning of
    the note's sound.
 2. [Pull Ups][3]: Any logic input should not be left unconnected or
    floating.  This can lead to unexpected results.  Use Pull Up
    resistors (or Pull Down depending on your design) to mitigate this
    problem.  The [Arduino Uno's][4] embedded processor ([the
    ATmega328P][5]) comes with built in Pull Up resistors.
    The Arduino IDE abstracts this feature by including a parameter it
    the [pinMode() function][6] call to invoke this feature.
 3. [Rollover][7]: In a switch matrix 1 or 2 simultaneous switch
    closure can be uniquely detected.  However, if 3 switch closures
    connect 2 rows and 2 columns together, they can not be uniquely
    detected.  This is because current can flow through the 3 closed
    switches activating both rows and both columns nullifying the
    ability for the embedded processor to scan individual rows or
    columns.  To mitigate this problem a diode is added to all
    switches in the switch matrix such that there is no current path
    between rows or columns.

From the [Rollover wikipedia page][8]:
> Most music keyboards use isolation diodes in their keyboard matrix to
> implement full n-key rollover, making them immune to both key ghosting
> and key jamming

This image if from [this stack exchange question][9]:
[![This image is from [this stack exchange question][8].][10]][10]

  [1]: https://en.wikipedia.org/wiki/Keyboard_matrix_circuit
  [2]: https://en.wikipedia.org/wiki/Switch#Contact_bounce
  [3]: https://en.wikipedia.org/wiki/Pull-up_resistor
  [4]: https://store.arduino.cc/usa/arduino-uno-rev3
  [5]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf
  [6]: https://www.arduino.cc/reference/en/language/functions/digital-io/pinmode/
  [7]: https://en.wikipedia.org/wiki/Rollover_(key)
  [8]: https://en.wikipedia.org/wiki/Rollover_(key)#n-key_rollover
  [9]: https://arduino.stackexchange.com/questions/31885/need-help-in-circuit-diagram-of-88-reed-switch-matrix
  [10]: https://i.stack.imgur.com/76A84.jpg

body:
A few excerpts from the program:

```c++
#define offset 48
//...
byte notes_pressed[37];  // valid indices: 0 – 36
//...
uint8_t note = offset + (8-j);  // j ≤ 8, thus note ≥ 48
//...
notes_pressed[note] = 0;
```

That last line writes past the end of the `notes_pressed` array, and
overwrites who knows what in memory. This could be the source of the
issue you are facing.


body:
In a simplified example, I have a microcontroller functioning as a data acquisition device - sensor data is received over UART, and then saved to an SD card.

This received data is in the form of a 12 byte struct, received at 1kHz. The microcontroller receiving the data is an esp32, with an SD card connected over spi. Not an uncommon issue, but if a typical SD card write is triggered everytime new data is received, it will take longer than the gap between samples to  write the data.

What is typically considered the best practice for this type of system, presuming the data will always be received faster than it can be written. I have seen examples of circular buffers, but presumably these will eventually fill completely and samples will be missed.

In my particular example, I have the bonus second cpu core in the esp32. Therefore, my thinking is to use 2 alternating buffers. Data will be received on core 1, and placed into the active buffer. When the buffer is full, incoming data will be written to the second buffer, and the first will be written to the SD card by core 2.

Is this a sensible solution to the problem? I am hesitant to implement anything that simply relies on an improvement in SD write speed, as I will likely need to increase the size of the data payload in the future and don't want to run into this issue again later on.

title: Best buffering practice for continuous SD card writing

Answers: 4

body:
Buffers will help you if at some point the input stream stops, so the "slower" device (e.g. the SD card) can catchup. If *the data will always be received faster than it can be written* (note **always**) then no buffer will help you.

But I assume you meant that there times where you get bursts of input data at 1Khz, then it will stop. So, as long as the _average_ input data rate is lower than the ability for the SD to persist the data, you will be fine.

The SD card library already has a buffer (as @Majenko pointed out), so most likely you won't need to do anything. Seem like something you can test relatively simply.

The 2 core approach sounds somewhat overkill (not to mention some synchronization issues you will have to deal with)

body:
> Is this a sensible solution to the problem?

No, unfortunately not. The size of the buffer is limited by the available RAM on your chip. Jumping between multiple buffers or cores will not change that, since it is a hardware limitation.

> I am hesitant to implement anything that simply relies on an improvement in SD write speed, as I will likely need to increase the size of the data payload in the future and don't want to run into this issue again later on.

When you are continuously receiving faster than you can write, you only have 2 options:

- Improve write speed
- Reduce the needed data size

There is no other way, and that's a logical conclusion, not so much a programmical or hardware conclusion. It that situation the amount of "buffered" data will increase indefinitely, so you would need an infinite amount of memory. And that doesn't exist in real world. The same principle would apply to a high end PC with lots of memory, it will just be full after longer time, than with an ESP.

- Improving write speed:
    - On various sites I have read, that you can use the SD card with different SPI frequencies. A higher frequency would mean a higher transaction speed. You can investigate further at this point.
    - Writing a full 512 byte page at once and only closing and opening the file again, if really needed, will improve the overall speed.

- Reduce the needed data size
    - Maybe you can compromise with your data resolution and then pack those values as dense as possible (like packing two 4-bit values into a single byte of transmission).
    - You can research for compression code, so that you can compress your data lossless before transmitting it. Though the result will always depend on the kind of your data. Also mind, that in this case you are trading transmission size for computation time and RAM.

About buffers:

I would say, a normal circular buffer does not bring you much advantages here, since with the SD card you don't want to do bytewise data transmission. The 2 buffer approach, that you mentioned, seems good to me. Though doing handling with different cores does not make much sense to me. The UART receiving itself is done by hardware and some ISRs. You can do all the SD card transmissions in your main code, just making sure, that you regularly copy the received data from the Serial buffer into your buffer.

body:
Forgive my non-technical analogy, but this is how my brain works.   Hope you can get past the conclusion that "this isn't a technical answer", until you at least see it from this different perspective.

Buffers, input streams, and sampling rates, storage rates all relate strongly to filling up a bath.   Taps, water, baths and plug holes?   WTF?

Try slightly blocking the plug hole in your bath, and turn both taps on full.

The water that's drained away is the rate of which data is stored to the SD card.  That's the storage-rate.

The remaining water which doesn't drain away fast enough causes the bath the fill up.   The water is the sampling rate, the bath is the buffer.

If the taps remain on, and water is leaving the taps faster than the water can escape from the partially blocked hole will cause the bath to fill up with water.

So, if the blockage isn't cleared, the bath will eventually overflow.

Either you turn the taps down, use a bigger bath, or increase the drainage rate.

body:
One approach would be to use Circular Buffering. It involves using a fixed-size buffer that wraps around itself, allowing data to be continuously written and overwritten. This approach eliminates the need for costly memory reallocation or shifting operations. As new data is written, older data is overwritten in a circular fashion. But, you will need to choose the appropriate buffer size. A larger buffer size can help handle bursts of data However, larger buffers also consume more memory.

If one buffer isn't enough, then you could use Two buffers instead. While one buffer is being written to the SD card, the other buffer can be used to receive new incoming data. Once the write operation is completed, the roles of the buffers are swapped. This technique can help improve efficiency by minimizing data transfer and write latency, which is the goal you aim at. I've used this type of buffer for audio data acquisition, and it worked well, got rid of the buffer overflow issues.

The other method would be to use DMA,  if your microcontroller or system supports it, which I think it does, using DMA for SD card writing can offload the data transfer task from the CPU. DMA allows direct memory access without CPU intervention, enabling faster and more efficient data transfers. DMA can significantly reduce the overhead associated with continuous SD card writing.

For DMA, you might want to check this:
https://github.com/RobTillaart/DAC8552/issues/8 and this: https://github.com/espressif/esp-idf/blob/master/examples/peripherals/spi_master/lcd/main/spi_master_example_main.c


body:
Looking to merge two different 2D arrays of different row sizes into one long array:

 ```
  int 2dArray1[][] = {
    {1, 2, 3},
    {4, 5, 6}};
  int 2dArray2[][] = {
    {10, 20},
    {30, 40}};
  int 1dLongArray[10];
```
 This is where I need help in order to have the values of 1dLongarray be arranged as follows:
```
1, 2, 3, 10, 20, 4, 5, 6, 30, 40
```
How would I achieve this? Thanks in advance.

title: Merging two 2-d arrays in order of axes

Answers: 1

body:
Consider using loops of length specific to the desired number of transactions.  For example, using this pseudo code create a sketch which follows this pattern:

    initialize i to zero
    loop 2 times for each row using the variable x
      loop 3 times for each element in first array using the variable y
        long array [i] = first array[x][y]
        increment i
      loop 2 times for each element in a second array using the variable z
        long array [i] = second array[x][z]
        increment i


body:
I have been gradually converting many devices from i2c to spi for various reasons.  I noticed in tutorials like [this from arduino.cc][1] that `SPI.beginTransaction` is explicitly called out.  Then they link to examples such as [this][2] and [this][3] where they don't use `SPI.beginTransaction`.  In working through my own devices I found that I could often (almost always) forgo the use of `SPI.beginTransaction`.  The only case where I found problems was when I had 2 devices that used different SPI settings.

I went to Google and other searches for a simple reason for `SPI.beginTransactions` and found discussions of interrupts and locks and settings.  There was much discussions about users applications wrapping all calls with `SPI.beginTransaction` and `SPI.endTransaction`.  There were bugs when libraries didn't wrap everywhere.

This leads me to the conclusion that making calls to `SPI.beginTransaction` are only needed when the SPI settings need to change, but in practice you should always do it.  Is there documentation or examples that definitely state the purpose and proper (best practice) usage of it?

  [1]: https://www.arduino.cc/en/Reference/SPI
  [2]: https://www.arduino.cc/en/Tutorial/LibraryExamples/BarometricPressureSensor
  [3]: https://www.arduino.cc/en/Tutorial/LibraryExamples/DigitalPotControl

title: When is SPI.beginTransaction required?

Answers: 3

body:
It appears calling the method [beginTransaction()][1] prevents additional SPI transactions from interrupting the current transaction.  Calling [endTransaction()][2] allows access to the SPI hardware again. This added complexity may sound odd.  Especially in the simple Arduino sketch-writing paradigm.  But as programs grow in complexity, more SPI devices are added and interrupts are used to quickly access SPI devices - the likely hood of SPI contention increases.

In the [SPIClass source code][3], there is this comment immediately before the beginTransaction() method:

      // Before using SPI.transfer() or asserting chip select pins,
      // this function is used to gain exclusive access to the SPI bus
      // and configure the correct settings.

So, it may be, that if the sketch-code is particularly well behaved and does not need protection from accidentally using the SPI hardware from multiple concurrent transactions, that these two methods need not be used.  But why take the chance.

  [1]: https://www.arduino.cc/en/Reference/SPIbeginTransaction
  [2]: https://www.arduino.cc/en/Reference/SPIendTransaction
  [3]: https://github.com/arduino/ArduinoCore-avr/blob/master/libraries/SPI/src/SPI.h

body:
Every modern Arduino library for a SPI device should use SPI library with beginTransaction to be able to coexists with libraries for SPI devices using different modes and speed.

Recently we had here [a question][1] about two libraries for SPI not working together. The devices required different modes. The libraries didn't use beginTransaction, they only used SPI.begin() in initialization. It is not possible to use these libraries together.

The STM32 core supports switching CS pin with enhanced beginTransaction and endTransaction but this is not so useful as it looks. Many devices use CS as 'commit' and the CS must be switched several times inside one 'transaction'.

If you write a library you don't know with what other SPI devices on bus it will be used so call [`beginTransaction`][2] as the library gets control and [`endTransaction`][3] as the public library function returns control out of the library.

  [1]: https://arduino.stackexchange.com/questions/78050/my-two-slave-spi-setup-on-arduino-not-working-correctly/78055#78055
  [2]: https://www.arduino.cc/en/Reference/SPIbeginTransaction
  [3]: https://www.arduino.cc/en/Reference/SPIendTransaction

body:
Although this question has an accepted answer, I'd like to provide some background and historical reasons to OP's question.

Transactional SPI using `SPI.beginTransaction()` was introduced in 2014, it was not available in the early version of the Arduinos or example codes published before that. As the results, there are still many codes out there on the Internet show the old way of setting up the SPI configuration, and this include the exampes provided by Arduino.cc on its [library reference page](https://www.arduino.cc/en/Reference/SPI) even up to today, the authors of the library did not make any changes in those examples to show the usage of new API.

What the `SPI.beginTransaction()` does is to allow you to set unique SPI settings(through `SPISettings` object) for your application, even if other devices use different settings. `SPI.beginTransaction()` behave like a locking mechanism to gain the exclusive use of the SPI bus, and therefore requires `SPI.endTransaction()` to release the bus for others to access it. `SPI.beginTransaction()` provides better cross-device compatibility and solve software conflicts and allowing multiple SPI devices to properly share the SPI bus. You should therefore use the `SPI.beginTransaction()` in your SPI sketch. You should also using `SPISettings` object to configure your SPI communication interface, and not use the deprecated methods such as `SPI.setBitOrder()`, `SPI.setClockDivider()` and `SPI.setDataMode()` for setting up the SPI configuration.

Although rarely need today, there is a pre-defined macro `SPI_HAS_TRANSACTION` in SPI library for checking whether the firmware of the Arduino board supports `SPI.beginTransaction()`. It is useful for providing backward compatibility if you are writing an Arduino library.

    #ifdef SPI_HAS_TRANSACTION
      SPI.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE0));
    #elseif
      // use old Arduino SPI library syntax
    #endif


body:
I am sending data from an ESP8266 to an Uno (I need to use the Uno because it has more inputs than the ESP and I need those for my project.) The ESP8266 is connected to the Uno's Serial pins 0/1 RX/TX (communicating on BAUD rate of 9600), and then I have a SoftwareSerial out from the Uno (on a BAUD rate of 57600) for debugging. Something weird is happening though. The transfer works a couple times and then I get this in the log:

    --------------- CUT HERE FOR EXCEPTION DECODER ---------------

    Exception (0):
    epc1=0x40239ba1 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000000 depc=0x00000000

    >>>stack>>>

    ctx: sys
    sp: 3fffebd0 end: 3fffffb0 offset: 0190
    3fffed60:  40239b2e 3feffe00 3fffd9d0 00000050
    3fffed70:  000005e0 00000000 40103501 3ffed4d0
    3fffed80:  0000003c 00000000 00000022 401049e6
    3fffed90:  401049c8 3fffc100 3ffef2a0 00000000
    3fffeda0:  00000000 4022279f 00000020 40100198
    3fffedb0:  400005e1 150cc636 00000005 4010144c
    3fffedc0:  4022279f 00000030 00000010 3ffefdcc
    3fffedd0:  40221007 3fff051a 00000014 00000000
    3fffede0:  00000000 00000061 00000061 00000001
    3fffedf0:  3ffecdb8 00000006 00000000 3fff04fc
    3fffee00:  3fff051a 3ffef2a0 00000061 00000000
    3fffee10:  3ffe9be8 7fffffff 50800000 00000001
    3fffee20:  00000001 00004a08 00000142 401006d7

Any ideas what could be causing this? Here is the code that the Uno uses for receiving from the ESP and printing to the SoftwareSerial (Serial is the RX/TX and mySerial is the SoftwareSerial). It uses a couple helper functions I haven't included here but let me know if you need them:

    void receiveFromESP() {
      if (Serial.available() > 0   ) {
        endofTransmission == 0;
        alreadyZeroed = 0 ;
        receivedChar = Serial.read();
        mySerial.print(receivedChar);
        if (receivedChar == '[' ) {
          lastNum = 0 ;
          commaNumber = 0 ;
          lastWasNum = 0 ;
        }
        if (receivedChar == '*' ) {
          lastNum = 0 ;
          commaNumber = 0 ;
          lastWasNum = 0 ;
          createArray[0] = 4;
          createArray[1] = 4;
          createArray[2] = 4;
          createArray[3] = 4;
        }
        if (receivedChar == 'A'
            || receivedChar == 'B'
            || receivedChar == 'C'
            || receivedChar == 'D'
            || receivedChar == 'E'
            || receivedChar == 'F'
            || receivedChar == 'G'
            || receivedChar == 'H'
            || receivedChar == 'I'
            || receivedChar == 'J'
            || receivedChar == ','
           ) {
          if (lastWasNum == 1) {
            createArray[commaNumber] = lastNum;
            commaNumber++;
          }
          lastWasNum = 0 ;
          createArray[commaNumber] = charToNumber(receivedChar);
          commaNumber++;
          lastNum = 0 ;
        }
        if (receivedChar == ']') {
          lastWasNum = 0 ;
          endofTransmission = 1 ;
          for (int i = 0; i < 50; i++) {
            mySerial.print(createArray[i]);
            mySerial.print(':');
          }
        }
        if (
          receivedChar == '0'
          ||  receivedChar == '1'
          ||  receivedChar == '2'
          ||  receivedChar == '3'
          ||  receivedChar == '4'
          ||  receivedChar == '5'
          ||  receivedChar == '6'
          ||  receivedChar == '7'
          ||  receivedChar == '8'
          ||  receivedChar == '9'
        ) {
          lastWasNum = 1;
          receivedCharInt = (int)receivedChar - 48;
          lastNum = lastNum * 10 + receivedCharInt;
        }
        t = millis();
      }
    };

As requested, here is the full ESP code:

    #include <Arduino.h>
    #include <ESP8266WiFi.h>
    #include <ESP8266WiFiMulti.h>
    #include <ESP8266HTTPClient.h>
    #include <WiFiClient.h>

    #include <DNSServer.h>            //Local DNS Server used for redirecting all requests to the configuration portal
    #include <ESP8266WebServer.h>     //Local WebServer used to serve the configuration portal
    #include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager WiFi Configuration Magic

    #define SERIAL_BUFFER_SIZE 256

    void setup() {

      Serial.begin(9600);
      for (uint8_t t = 4; t > 0; t--) {
        Serial.printf("*WIFISETUP] WAIT %d...\n", t);
        Serial.flush();
        delay(1000);
      }
      WiFiManager wifiManager;
      wifiManager.setConfigPortalTimeout(120);
      //first parameter is name of access point, second is the password
      wifiManager.autoConnect("AP-NAME", "AP-PASSWORD");
    }

    void loop() {
        WiFiClient client;
        HTTPClient http;
        if (http.begin(client, "[URL]")) {  // HTTP
          // start connection and send HTTP header
          http.addHeader("Content-Type", "text/plain");
          http.addHeader("Authorization", "Basic dXNlcm5hbWU6cGFzc3dvcmQ=");
          int httpCode = http.GET();

          if (httpCode == 200 ) {  // HTTP header has been sent and Server response header has been handled
            // file found at server
            if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
              String payload = http.getString();
              Serial.println(payload);
            }
          } else{
            if (httpCode > 0 ){
              //website problem
              Serial.printf("[2,1,1,1]");
            }
            if (httpCode == -1 ){
              //wifi problem
              Serial.printf("[4,1,1,1]");
              ESP.reset();
            }
          }
          http.end();
        } else {
          Serial.printf("[HTTP} Unable to connect\n");
        }
      delay(10000);
    }

title: Error sending data from ESP8266 to Uno

Answers: 1

body: Why not use a PCF8574 I2C expansion board, they work great on 3V3. If you need more inputs or outputs use the PCF8575. There are a lot of I2C expansion boards you can select from. They will also be faster and less convoluted then your existing solution.


body:
Im currently moving a servo from one side to another by using the typical for loop like this:

    int lightON = 180;
    int lightOFF = 90;

    if (buttonState == HIGH) {

      digitalWrite(LED, HIGH);
      for (pos1 = lightOFF; pos1 <= lightON; pos1 += 1) {
        servo1.write(pos1);
        delay(15);
      }
      digitalWrite(LED, LOW);

    }

That would be moving the servo one way and if I push the button again the servo would move another way.

    if (buttonState == LOW) {

      digitalWrite(LED, HIGH);
      for (pos1 = lightON; pos1 >= lightOFF; pos1 -= 1) {
        servo1.write(pos1);
        delay(15);
      }
      digitalWrite(LED, LOW);

    }

The thing is, I have this very same code in 3 other servos and I don't want to be repeating the same code with 2 different variables (pos and servo) over and over again, so I tried

    void runServoLight(int pos, int light1, int light2, Servo servo, int state) {

      if (state == 1) {

      digitalWrite(LED, HIGH);

      for (pos = light1; pos <= light2; pos += 1) {
         servo.write(pos);
         delay(15);
      }

      digitalWrite(LED, LOW);

      } else if (state == 0) {

      digitalWrite(LED, HIGH);

      for (pos = light2; pos >= light1; pos -= 1) {
        servo.write(pos);
        delay(15);
      }

      digitalWrite(LED, LOW);

      }

    }

Now instead of running the whole for loop code I only run:

    runServoLight(pos1, lightON, lightOFF, servo1, 1);

The problem is that it doesn't seem to work and I can understand why, I may be writing the function wrong but im nor really sure. I would really appreciate some help. Thank you!

title: How to move a servo with a function

Answers: 2

body:
You wrote:

> ```c++
> void runServoLight(
>         int pos, int light1, int light2, Servo servo, int state)
> ```

Here you are giving the list of parameters used by the function. In C++,
parameters are by default passed _by value_. This means that, when the
function is called, the arguments passed in the call are _copied_ into
the parameters listed here, which are local variables of the function.
Changes to those parameters will not propagate to the arguments provided
by the caller.

This can be an issue for the `Servo` object. This object keeps some
internal state, which has the memory of the current configuration of the
timers. Since you are working on a copy of the provided object, the
original object is not updated when you act on the copy. I do not know
whether this is making your program misbehave, but it would be safer to
pass the `Servo` object _by reference_:

```c++
void runServoLight(
        int pos, int light1, int light2, Servo &servo, int state)
```

This way the object will not be copied: the function will instead work
on the original object provided by the caller.

The same may apply to the _pos_ parameter. The very first thing the
function does with this parameter is to overwrite it. Then there is no
point in receiving that value from the caller. You can instead remove
the parameter and create a local variable with the same name:

```c++
void runServoLight(int light1, int light2, Servo &servo, int state) {
    int pos;  // local variable
    ...
}
```

If you want the caller's version of this variable to be updated, you
could pass it by reference, just like the `Servo` object. It is,
however, more efficient to keep the variable local and have the function
return the final position. The call would then look like:

```c++
pos1 = runServoLight(lightON, lightOFF, servo1, 1);
```

One final point that is not visible in the snippets you showed: are you
doing _edge detection_ on the buttons? Edge detection means that you act
on the _changes_ of state of the buttons, not on the states themselves.
For example, you move from `lightOFF ` to `lightON` not when the button
state _is_ `HIGH` but rather when it _turns_ `HIGH`.

body:
This is not a solution, however, by rafactoring it makes your sketch more maintainable as duplicated code is removed:

    void runServoLight(int pos, int light1, int light2, Servo servo, int state)
    {
      if (state == 1) {
        process(light1, light2, +1, servo);
      }
      else if (state == 0) {
        process(light2, light1, -1, servo);
      }
    }

    def process(int this_light, int other_light, int delta, Servo servo)
    {
      digitalWrite(LED, HIGH);
      for (pos = this_light; pos >= other_light; pos += delta) {
        servo.write(pos);
        delay(15);
      }
      digitalWrite(LED, LOW);
    }

Instead of the state integer, it's more clear to use an enumeration and use a `switch` statement.

    #include "Servo.h"

    const int LED = 13;

    enum EServoState { LEFT, RIGHT };

    void runServoLight(int light1, int light2, Servo servo, EServoState state);

    void setup()
    {
    }

    void loop()
    {
      int light1 = 1;
      int light2 = 2;
      EServoState state;
      Servo servo;
      runServoLight(light1, light2, servo, state);
    }

    void runServoLight(int light1, int light2, Servo servo, EServoState state)
    {
      switch (state)
      {
      case LEFT:
        process(light1, light2, +1, servo);
        break;

      case RIGHT:
        process(light2, light1, -1, servo);
        break;

      //default:
       // Handle program error
      }
    }

    void process(int this_light, int other_light, int delta, Servo servo)
    {
      digitalWrite(LED, HIGH);
      for (int pos = this_light; pos >= other_light; pos += delta)
      {
        servo.write(pos);
        delay(15);
      }
      digitalWrite(LED, LOW);
    }


body:
I tried to make a simple project with Attiny85 chip and DHT11 sensor. After 2 days of struggle, made it finally work, but not quite as expected. [TinyDHT](https://github.com/adafruit/TinyDHT) library does work, while [DHTNEW](https://github.com/RobTillaart/DHTNew/) does not.

I wonder,

* what can be changed to make any of the libraries work at lower clock rate?
* how to make DHTNew work?

My results so far:

with TinyDHT:

* @ 16 MHz works nominally, showing valid T/H values (if I breathe on the sensor, it shows 95-99% humidity)
* @ 8 MHz, shows nothing (either nan, or zeros)
* @ 1 MHz, shows temp/hum as 5, 5 (or 50, 50, can't tell)

with DHTNEW:

* @ 16 MHz returns SENSOR_NOT_READY
* @ 16 MHz with `mySensor.setDisableIRQ(true);` -> WAITING_FOR_READ at first, then nothing (nan or 0)
* @ 8 MHz WAITING_FOR_READ at first, then TIMEOUT_C
* @ 8 MHz with `setDisableIRQ` -> always TIMEOUT_C
* @ 1 MHz always TIMEOUT_A

Here's the setup on photo and as a scheme. Arduino UNO works as a programmator for Attiny chip, as shown in [this tutorial](https://www.instructables.com/How-to-Program-an-Attiny85-From-an-Arduino-Uno/). After I upload the code to Attiny85, the chip starts working normally, and there's no need to disconnect the Arduino board. (For actual work, I disconnect it, connect 5V power, and it works the same way.)

Settings in the IDE:

* Board: Attiny25/45/85
* Processor: Attiny85
* Clock: Internal from 1 to 16 MHz
* Programmer: Arduino as ISP

How I test this:

* change clock frequency
* run Tools -> Burn bootloader
* run Sketch -> Upload
* wait till upload ends (RX/TX diodes stop blinking)
* the LED on breadboard blinks me the numbers

[![Physical look][1]][1]

[![Connection scheme][2]][2]

* [Code for TinyDHT](https://pastebin.com/YdQ3xYER)
* [Code for DHTNEW](https://pastebin.com/q5mEWCan)

  [1]: https://i.stack.imgur.com/0LX54.jpg
  [2]: https://i.stack.imgur.com/qLge7.jpg

title: DHTNEW library not working with ATTiny85 + DHT11

Answers: 0