body:
I have the two example codes from MFRC522 Library and I want to combine them together so I can at first read the data from the tag and then write something new on it by using the serial input. I´ve already tried but I cant figure out why it doesnt work. While it waits for an input to write on the chip the Serial Monitor shows: "PCD_Authenticate() failed: Timeout in communication".

This is the code for read data:

    * Initial Author: ryand1011 (https://github.com/ryand1011)
     *
     * Reads data written by a program such as "rfid_write_personal_data.ino"
     *
     * See: https://github.com/miguelbalboa/rfid/tree/master/examples/rfid_write_personal_data
     *
     * Uses MIFARE RFID card using RFID-RC522 reader
     * Uses MFRC522 - Library
     * -----------------------------------------------------------------------------------------
     *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
     *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
     * Signal      Pin          Pin           Pin       Pin        Pin              Pin
     * -----------------------------------------------------------------------------------------
     * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
     * SPI SS      SDA(SS)      10            53        D10        10               10
     * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
     * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
     * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
    */

    #include <SPI.h>
    #include <MFRC522.h>

    #define RST_PIN         9           // Configurable, see typical pin layout above
    #define SS_PIN          10          // Configurable, see typical pin layout above

    MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

    //*****************************************************************************************//
    void setup() {
      Serial.begin(9600);                                           // Initialize serial communications with the PC
      SPI.begin();                                                  // Init SPI bus
      mfrc522.PCD_Init();                                              // Init MFRC522 card
      Serial.println(F("Read personal data on a MIFARE PICC:"));    //shows in serial that it is ready to read
    }

    //*****************************************************************************************//
    void loop() {

      // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
      MFRC522::MIFARE_Key key;
      for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;

      //some variables we need
      byte block;
      byte len;
      MFRC522::StatusCode status;

      //-------------------------------------------

      // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
      if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
      }

      // Select one of the cards
      if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
      }

      Serial.println(F("**Card Detected:**"));

      //-------------------------------------------

      mfrc522.PICC_DumpDetailsToSerial(&(mfrc522.uid)); //dump some details about the card

      //mfrc522.PICC_DumpToSerial(&(mfrc522.uid));      //uncomment this to see all blocks in hex

      //-------------------------------------------

      Serial.print(F("Name: "));

      byte buffer1[18];

      block = 4;
      len = 18;

      //------------------------------------------- GET FIRST NAME
      status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 4, &key, &(mfrc522.uid)); //line 834 of MFRC522.cpp file
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("Authentication failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }

      status = mfrc522.MIFARE_Read(block, buffer1, &len);
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("Reading failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }

      //PRINT FIRST NAME
      for (uint8_t i = 0; i < 16; i++)
      {
        if (buffer1[i] != 32)
        {
          Serial.write(buffer1[i]);
        }
      }
      Serial.print(" ");

      //---------------------------------------- GET LAST NAME

      byte buffer2[18];
      block = 1;

      status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 1, &key, &(mfrc522.uid)); //line 834
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("Authentication failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }

      status = mfrc522.MIFARE_Read(block, buffer2, &len);
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("Reading failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }

      //PRINT LAST NAME
      for (uint8_t i = 0; i < 16; i++) {
        Serial.write(buffer2[i] );
      }

      //----------------------------------------

      Serial.println(F("\n**End Reading**\n"));

      delay(1000); //change value if you want to read cards faster

      mfrc522.PICC_HaltA();
      mfrc522.PCD_StopCrypto1();
    }
    //*****************************************************************************************//

  and for writing data:

    /*
     * Write personal data of a MIFARE RFID card using a RFID-RC522 reader
     * Uses MFRC522 - Library to use ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS SPI W AND R BY COOQROBOT.
     * -----------------------------------------------------------------------------------------
     *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
     *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
     * Signal      Pin          Pin           Pin       Pin        Pin              Pin
     * -----------------------------------------------------------------------------------------
     * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
     * SPI SS      SDA(SS)      10            53        D10        10               10
     * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
     * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
     * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
     *
     * Hardware required:
     * Arduino
     * PCD (Proximity Coupling Device): NXP MFRC522 Contactless Reader IC
     * PICC (Proximity Integrated Circuit Card): A card or tag using the ISO 14443A interface, eg Mifare or NTAG203.
     * The reader can be found on eBay for around 5 dollars. Search for "mf-rc522" on ebay.com.
     */

    #include <SPI.h>
    #include <MFRC522.h>

    #define RST_PIN         9           // Configurable, see typical pin layout above
    #define SS_PIN          10          // Configurable, see typical pin layout above

    MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

    void setup() {
      Serial.begin(9600);        // Initialize serial communications with the PC
      SPI.begin();               // Init SPI bus
      mfrc522.PCD_Init();        // Init MFRC522 card
      Serial.println(F("Write personal data on a MIFARE PICC "));
    }

    void loop() {

      // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
      MFRC522::MIFARE_Key key;
      for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;

      // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
      if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
      }

      // Select one of the cards
      if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
      }

      Serial.print(F("Card UID:"));    //Dump UID
      for (byte i = 0; i < mfrc522.uid.size; i++) {
        Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
        Serial.print(mfrc522.uid.uidByte[i], HEX);
      }
      Serial.print(F(" PICC type: "));   // Dump PICC type
      MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
      Serial.println(mfrc522.PICC_GetTypeName(piccType));

      byte buffer[34];
      byte block;
      MFRC522::StatusCode status;
      byte len;

      Serial.setTimeout(20000L) ;     // wait until 20 seconds for input from serial
      // Ask personal data: Family name
      Serial.println(F("Type Family name, ending with #"));
      len = Serial.readBytesUntil('#', (char *) buffer, 30) ; // read family name from serial
      for (byte i = len; i < 30; i++) buffer[i] = ' ';     // pad with spaces

      block = 1;
      //Serial.println(F("Authenticating using key A..."));
      status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("PCD_Authenticate() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }
      else Serial.println(F("PCD_Authenticate() success: "));

      // Write block
      status = mfrc522.MIFARE_Write(block, buffer, 16);
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("MIFARE_Write() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }
      else Serial.println(F("MIFARE_Write() success: "));

      block = 2;
      //Serial.println(F("Authenticating using key A..."));
      status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("PCD_Authenticate() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }

      // Write block
      status = mfrc522.MIFARE_Write(block, &buffer[16], 16);
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("MIFARE_Write() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }
      else Serial.println(F("MIFARE_Write() success: "));

      // Ask personal data: First name
      Serial.println(F("Type First name, ending with #"));
      len = Serial.readBytesUntil('#', (char *) buffer, 20) ; // read first name from serial
      for (byte i = len; i < 20; i++) buffer[i] = ' ';     // pad with spaces

      block = 4;
      //Serial.println(F("Authenticating using key A..."));
      status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("PCD_Authenticate() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }

      // Write block
      status = mfrc522.MIFARE_Write(block, buffer, 16);
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("MIFARE_Write() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }
      else Serial.println(F("MIFARE_Write() success: "));

      block = 5;
      //Serial.println(F("Authenticating using key A..."));
      status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("PCD_Authenticate() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }

      // Write block
      status = mfrc522.MIFARE_Write(block, &buffer[16], 16);
      if (status != MFRC522::STATUS_OK) {
        Serial.print(F("MIFARE_Write() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
      }
      else Serial.println(F("MIFARE_Write() success: "));

      Serial.println(" ");
      mfrc522.PICC_HaltA(); // Halt PICC
      mfrc522.PCD_StopCrypto1();  // Stop encryption on PCD

    }

title: How to combine Read/Write Data Code for RFID tag?

Answers: 0


body:
I'm making a long LED display made up of 3 (8x32) LED matrices to go inside of a car. I can't seem to find any in-depth guides on this sort of thing. If anybody has examples that they would like to share please do!

The major issue I'm having is power. I'm extremely new to electronics, and I don't understand how these lights can be powered separately, and still be addressably lit by the Arduino?

Parts:
3* LED matrices (8x32)

https://www.amazon.com/gp/product/B088BTXHRG/ref=ppx_yo_dt_b_asin_title_o01_s00?ie=UTF8&psc=1

1* Mega 2560

Here's the mock-up schema:

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

I forgot to draw in a switch, and a power line leading to the Arduino. But let's assume there will be a switch before the resistor and a line that feeds power to the MEGA 2560.

What in this schematic doesn't look or sound right?

Thank you all in advance for your help. This is probably not at all how to go about building circuits, and I'm trying my best to learn. All advice is wanted!

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

title: First Arduino Project - Need Advice (powering WS2812B LEDs)

Answers: 1

body:
**Powering the LED panels**

Powering your panels will be your greatest challenge!

These LED panels are powered by a single +5V power input per panel and *do not need a resistor in the power supply path* (they actually need a very low resitance path). You do need a good quality +12V DC -> +5V DC power supply (or multiple, as explained below).

Since 3 x 256 RGB LEDs require a large amount of power when they're all lighted at the same time (something like 60mA * 768 =~ 46A), the power supply should be able to accomodate that. It might be better to use three individual, smaller (~15A) power supplies. You could opt for power supplies smaller than 15A, but you should ensure that all LEDs will never light up at full intensity at the same time.

For supplying power from a 12V car battery, you could use high quality 12V DC to 5V DC buck converters (they're efficient). Use good quality cable with a diameter large enough for transporting the large currents necessary. If you need connections in the path of the power supply, make sure they are good quality as well. To reduce losses in long stretches of wire, you should place the buck converter(s) near the LED panels.

**Connecting the data lines**

The color and intensity of Individual LEDs is controlled via the data input coming from your Arduino and it only needs one input to control all 768 LEDs. The first panel's "data out" should be connected to the next panel's "data in" and so on, like your drawing.

**Software**

I recommend you look up the [*FastLED library*](https://github.com/FastLED/FastLED) and some of its examples to get familiar with controlling large amounts of addressable RGB LEDs. There are many good examples and interesting projects out there.


body:
The code below sends data to Raspberry Pi every 20 millisecond. The code works fine but sometimes python throws an error. Why this is happening? Should I give more time between `writeData`?

**Error:**

    > Traceback (most recent call last):   File "rpi-I2C.py", line 33, in
    > <module>
    > writeData("360")   File "rpi-I2C.py", line 12, in writeData
    > bus.write_i2c_block_data(address,0x00,byteValue) OSError: [Errno 121] Remote I/O error

**Python code:**

    import smbus
    import time
    # for RPI version 1, use bus = smbus.SMBus(0)
    bus = smbus.SMBus(1)

    # This is the address we setup in the Arduino Program
    address = 0x04

    #http://www.raspberry-projects.com/pi/programming-in-python/i2c-programming-in-python/using-the-i2c-interface-2
    def writeData(value):
        byteValue = StringToBytes(value)
        bus.write_i2c_block_data(address,0x00,byteValue)
        #first byte is 0=command byte.. just is.
        return -1

    def StringToBytes(val):
            retVal = []
            for c in val:
                    retVal.append(ord(c))
            return retVal

    while True:
        print("sending test")
        writeData("left")
        time.sleep(0.02)

        #print('Sending OPEN-00-00');
        writeData("right")
        time.sleep(0.02)

        #print('Sending WIN-12-200');
        writeData("360")
        time.sleep(0.02)

**Arduino code**:

    #include <Wire.h>
    #define SLAVE_ADDRESS 0x04

    volatile boolean receiveFlag = false;
    char temp[32];
    String command;

    void setup() {
      Wire.begin(SLAVE_ADDRESS);
      // define callbacks for i2c communication
      Wire.onReceive(receiveEvent);
      Serial.begin(115200);
      Serial.println("Ready!");
    }

    void loop() {
      if (receiveFlag == true) {
        Serial.println(temp);
        receiveFlag = false;
      }
    }

    void receiveEvent(int howMany) {
      for (int i = 0; i < howMany; i++) {
        temp[i] = Wire.read();
        temp[i + 1] = '\0';  //add null after ea. char
      }

      //RPi first byte is cmd byte so shift everything to the left 1 pos so temp contains our string
      for (int i = 0; i < howMany; ++i)
        temp[i] = temp[i + 1];
        receiveFlag = true;
      }

title: Error in I2C Communication Between Arduino and Raspberry Pi

Answers: 1

body: A RPI uses 3.3v logic while an arduino uses 5v logic you can use a logic converter but by now it's probly to late and maybe your arduino or RPI is broken (_**Sorry!**_)


body:
I have multiple Arduino WeMos D1 boards, with a mix of versions bought months apart.  One of these boards is working but I need to update it and I am not sure if it is R1 or R2 (the pinouts are different).  I do not have physical access to it (it is 200+ miles away in an area that is locked down) but I can connect through another device over WiFi.

It has the following included:

    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>
    #include <ESP8266mDNS.h>

    #include <WiFiUdp.h>
    #include <ArduinoOTA.h>

So, I can even browse to a Webserver to run commands.  How can I add to the code (or even replace it) to return a value that tells me which version the board is?  According to [this][1] you can do it with an AT command, but I am not sure how to pass an AT command from the WebServer interface (or any other way).

EDIT: I guess I may have confused the issue with my phrasing.  I can connect to the board and upload a new sketch (using OTA).  My question is, can I put something in a new sketch to determine the board details and upload it.  Once I get that, I can then put in a the actual sketch that I want.

  [1]: https://arduino.stackexchange.com/q/47321/26515

title: How to get version of Arduino board remotely

Answers: 1

body:
There's nothing you can do with your currently loaded sketch. The board can *only* do exactly what you have programmed it to do and nothing more.

* There *are* no "AT" commands. They only exist if you load the AT firmware instead of your own firmware
* You can't magically make your code do things it wasn't programmed to do1

However the only real differences between the two boards is the version of the ESP8266 module in use: ESP-12E vs ESP-12F, (and the *only* difference between those modules is the layout of the PCB antenna in order to achieve FCC certification) and the addition of some unpopulated serial and I2C pins.

<s>Aside from that the only other differences are purely cosmetic or of no consequence to your software.

So it really doesn't matter which board you have or which you compile your code for.</s>

----
1: Unless you can cause some buffer overflow and inject new code into memory to execute, but to do that you'd need to be a l33t h4x0r.

----
**Addendum:**

It appears they have two boards, named the same, with different pin arrangements (both sadly very stupidly designed, but there you are).  All I can suggest is compile for one, install it, and see if it works. If it doesn't, then compile for the other and see if that works.

Or compile some special firmware that will probe what you have attached and work out what is attached where - then install and run that.


body:
I am unable to get any reading from a [PMS5003][1] connected to an ESP32.

In trying to debug this problem, I have a very minimal setup. Only the PMS5003 is connected to the ESP32, and using the following the code.

    #include <Arduino.h>
    #define PMS_DEBUG
    #include <PMSerial.h>

    SerialPM pms(PMSx003,Serial2)

    void setup() {
      Serial.begin(9600);
      Serial2.begin(9600);
      pms.init();
    }

    void loop() {
      pms.read();
      Serial.println(pms.pm25);
      Serial.println(pms.status);
    }

`pms25` always returns `0`. When the PMS5003 is properly connected to the ESP32, `status` always returns "Wrong message start".

Why would the device be sending the wrong start code, and what steps can I take to debug this?

I have tried connecting to different serial pins, including following the ESP32 software serial example provided by the [PMSerial][2] library. In all cases, it simply looks as though the PMS5003 sensor is mot transmitting anything - indeed no fans are switching on and there is no sign of life at all from the device. However, I am very much a beginner, and don't know enough to tell whether this is a problem with the device, the library or something I have done.

Very grateful for suggestions how to debug this.

# Edit

example serial data

    0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x6D, 0x0, 0xE0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x97, 0x0, 0x0, 0x0, 0xF8,

    0x0, 0x0, 0x0, 0x0, 0xA, 0x0, 0x0, 0x1, 0x0, 0xB0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF0, 0x0, 0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0xBB, 0x1, 0x0, 0x5F, 0x0,

  [1]: https://www.aqmd.gov/docs/default-source/aq-spec/resources-page/plantower-pms5003-manual_v2-3.pdf
  [2]: https://github.com/avaldebe/PMserial

title: Why would a serial device not be sending the correct start code?

Answers: 0


body:
The Arduino I2S [reference][1] describes the I2S standard and functions available with the standard I2S library, (Bizarrely it doesn't reference the existing `read()` function which is used in the [examples][2] but that is beside the point). There also exists an [ArduinoSound][3] library, however I have the same issue with this.

I would like to record audio from WM8731 connected up to Arduino. I am using an SAMD arduino part.

But, I have a tremendous issue with the `I2S.read()` function. The `I2S.read()` function only returns a singular value, however the I2S standard is *intrinsically* stereo.

This is particularly important for my project as I am only interested in the LEFT channel as the RIGHT channel is muted.

I would expect this to either:

 - return a pair of values (i.e left /right) samples for that particular point in time , OR
 - return a singular sample with extra information telling me which channel that is was retrieved from.

However it seems this is not the case. ([Github][4])

I also assume that the I2S is buffered making it impossible to simply read the WS pin state, as I will probably be popping a sample from the buffer that was push into the buffer at some point in the past.

So, is it possible to know *which* channel the sample was returned from the `I2S.read()` function or does this mean that the library needs to be modified?

I am more interested in using the samd library as other libraries such as AudioLibrary is limited to 16-bit - I need 32-bit resolution.

  [1]: https://www.arduino.cc/en/Reference/I2S
  [2]: https://www.arduino.cc/en/Tutorial/LibraryExamples/I2SInputSerialPlotter
  [3]: https://www.arduino.cc/en/Reference/ArduinoSound
  [4]: https://github.com/arduino/ArduinoCore-samd/blob/master/libraries/I2S/src/I2S.cpp

title: I2S read() is which channel?

Answers: 1

body:
From my understanding it's just retrieving subsequent samples from the DMA buffer, which means you will alternately get left and right samples from each read. It would be more normal to use the `read(buffer, len)` variant to read two (or more) samples at once.

```c++
int16_t pair[2]; // change to int32_t for 32 bit samples
I2S.read(pair, sizeof(pair));
```


body: Hi to all first of All my english is not good I brought Arduino motor shield  and n..d. E.p 8266 but the connect pin are not compatible how i will connect to node i want to make robo car

title: Arduino motor shield not compatible with nodemcu

Answers: 0


body: Hey I'm working on a home automation system where I can replace one of my 2 way switches to an Arduino Or node MCU controlled one but I want to avoid normal relays because as of what I know they can be unreliable and tend to fail. So is there any way I can replace my switch with an Arduino controlled switch and also I cannot use solid state relay as it has only two terminals and it cannot replace my two way switch.

title: 2 way switch with Arduino?

Answers: 2

body:
Like Gil said, it sounds like what you are calling a two-way switch is actually a three-way switch. These are typically wired like this (but not always, make sure to double check!):

[![three-way switch][1]][1]

To replace one of the two switches with a relay, you can simply connect a SPDT relay with the load/hot wire (depending on which side you're adding the relay from) to the common contact, and then the two traveler wires to the normally open and normally closed contacts. This effectively takes your existing wiring and directly swaps in a relay -- after all, the relay is literally a switch, just electrically activated instead of manually.

I can't speak to the reliability or lack thereof of a specific model of relay, but a normal power relay is more than adequate for home automation in almost all cases; you don't need anything too fancy. Yes, there will be a mechanical point of failure, but they are typically rated for 100,000+ actuations minimum on a decent relay (like [this one][2] from SparkFun, for example) which will take quite some time to reach. Avoid the super cheap relays both for safety and reliability, and you should be fine.

  [1]: https://i.stack.imgur.com/PkvpB.png
  [2]: https://www.sparkfun.com/products/15093

body: I have not had good luck with these relays, the modules themselves are OK I just solder in a new relay. Try looking for: "solid state 3 way switch"  I found this on my first try. DPST 1NO 1NC 8Amp Power Relay Module. It was labeled "OONO". Consider what happens when the power fails in just the controls, light circuit or both. What will you have then, and then when the power comes back on. I use larger relays and have not have any failures, they are rated at 20A 277V with 24VDC coile.


body:
I don't have my USB type A cable to program my UNO, I would like to program it via a NodeMCU ESP8266.

Maybe with the TX and Rx pins, I've seen people program certain versions of ESP with a UNO board.

How do I do this and is it possible?

title: How to program and arduino UNO via NodeMCU ESP8266?

Answers: 1

body:
The UNO's USB connection is little more than a USB to UART converter.  The NodeMCU's USB connection is *also* little more than a USB to UART converter.

With a little *jiggery pokery* (yes, that's a technical term) you can replace one with the other.

By keeping the NodeMCU in RESET mode (tie the EN pin low, or hold the RESET button) you can use the TX and RX pins as the output to the onboard USB to UART converter to connect to the TX and RX pins of the Arduino.

The tricky part is getting the Arduino to reset at the right time: you have to press the Arduino's RESET button at just the right time. Normally this is done by a small capacitor between the DTR signal of the USB to UART converter and the RESET pin, but you don't have access to the DTR signal, so you will have to do it manually. Timing here is everything. Press upload, and *just as AVRDude starts to execute* you press RESET. Having verbose compilation turned on in the IDE can help.

It may take a few attempts to get it right.


body:
I'm trying to connect an Arduino Nano 33 to an `mqtt broker` with TLS authenticaton on the broker side. To do that I need my Arduino board to have access to the the `root` certificate.

My understanding is that unlike ESP32, the Nano's NINA wifi module does not have a `WiFiSSLClient` object with a `setCACert` method that you can use to pass the root certificate. Instead, the NINA's client has a `connectSSL()` method which uses whatever root certificate you have uploaded to the Nano using Arduino's IDE. However, as it can bee seen in this [tutorial](https://support.arduino.cc/hc/en-us/articles/360016119219-How-to-add-certificates-to-Wifi-Nina-Wifi-101-Modules-), it looks like it is only possible to upload public domain root certificates by entering the website.

But what if I wanted to upload a `root` certificate that I have generated using OpenSSL. Would that be possible?

title: Is it possible to upload a private root certificate to an Arduino Nano33?

Answers: 0


body:
I'm using a SparkFun HX711 board and an Adafruit AdaLogger (M0) Featherboard. I have cut the trace on the back of the HX711 to get a faster data rate (should be about 80 sps). I did this by reviewing the spec sheet and confirming with this post ([Github link for faster rates][1]).

Before I read from the board I get startTime from micros() and immediately after I get get the scale data, I call micros() again and record the endTime. I then write this data along with the load cell data to an SD card. Then to check the time, after the experiment is over in excel I take 1/((endTime - startTime)*10^-6) to get the approximate number of samples per second.

My issue is that apparently, I'm recording at a max of around 6000 SPS but commonly around 600 SPS. Which, would be awesome if I wasn't so sure that it was a lie. I was hoping someone could take a look and see what I'm doing wrong? I used this same code on a different M0 with an unmodified HX711 and was getting around 10 SPS. The only thing different (I thought) was cutting the trace on the back of the board to enable the higher rate.

In the GitHub link above, they do mention that you can get a faster rate if you splice in a faster crystal with a cap to bridge pins 13 and 14. I have not done this, but perhaps the faster processor on the Feather might be playing some of a role in this?

VCC and VDD are both connected to 3.3V and GND is connected to the ground pin on the Feather. Pin 11 is connected to DAT and Pin 10 is connected to CLK

    #include <SPI.h>
    #include <SD.h>
    #include "HX711.h"

    #define FILE_BASE_NAME "FAST" // max six characters
    #define DOUT_one 11   // Red
    #define CLK_one  10   // Orange

    const uint8_t CS_PIN = 4;
    const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1;

    char fileName[] = FILE_BASE_NAME "00.csv";

    float calibration_factor_one = -7050; // needs to be calibrated still

    File file;

    long startTime=0;
    long endTime =0;

    String dataString = "";

    double scale_one_value = 0.0;

    HX711 scale_one;

    void SetUpSDCard(){
      if (!SD.begin(CS_PIN)) {
        Serial.println(F("begin failed"));
        return;
        }
       while (SD.exists(fileName)) {
        if (fileName[BASE_NAME_SIZE + 1] != '9') {
          fileName[BASE_NAME_SIZE + 1]++;
        } else if (fileName[BASE_NAME_SIZE] != '9') {
          fileName[BASE_NAME_SIZE + 1] = '0';
          fileName[BASE_NAME_SIZE]++;
        } else {
          Serial.println(F("Can't create file name"));
          return;
        }
      }
       file = SD.open(fileName, FILE_WRITE);
      if (!file) {
        Serial.println(F("open failed"));
        return;
      }
      Serial.print(F("opened: "));
      Serial.println(fileName);
      }

    void SetUpLoadCell(){
      Serial.println("Remove all weight from scale");
      scale_one.begin(DOUT_one, CLK_one);
      scale_one.set_scale();
      scale_one.tare();

      long zero_factor_one = scale_one.read_average(); //Get a baseline reading
      Serial.print("Zero factor: ");
      Serial.println(zero_factor_one);
      Serial.println("Load cell one initialized");
      scale_one.set_scale(calibration_factor_one); //Adjust to this calibration factor
      }

    void LogData(){
      startTime= micros();
      scale_one_value = scale_one.get_units();
      endTime = micros();

      dataString = String(startTime) + "," + String(scale_one_value) + "," + String(endTime);
      file.println(dataString);
      file.flush();
      }

    void setup() {
      Serial.begin(9600);
      SetUpSDCard();
      Serial.println("Remove all weight from scale");
      SetUpLoadCell();
    }

    void loop() {
      LogData();
    }

Then the saved data that is on the SD card is as follows, this is just the first 20 lines.

    3383895, 0,      3384049
    3401786, 0,      3401938
    3411851, 0,      3412004
    3421850, -0.02, 3422004
    3432012, -0.03, 3432164
    3442074, 0.01,   3442226
    3452118, 0,      3452269
    3462299, 0,      3462450
    3472441, 0.03,   3473497
    3483434, 0.03,   3485070
    3495011, 0.02,   3496638
    3506580, 0.01, 3508211
    3518576, 0.03, 3519785
    3529783, 0.02, 3531353
    3541282,    0,     3542924
    3552831, 0,     3554495
    3564476, 0,     3566070
    3575900, 0.01, 3577638
    3587476, -0.01, 3589209
    3599068, -0.03, 3600782

  [1]: https://github.com/olkal/HX711_ADC/issues/29

title: HX711 Ridiculous speeds

Answers: 1

body:
You're not measuring how many samples you do in a second, instead you're measuring the amount of time it takes to retrieve one sample from the HX711.

You store the time, retrieve the next sample, then store the time again. Then you spend a comparative age storing that data to the SD card, during which time the HX711 is taking any number of other samples.  By the time you eventually get around to reading from the HX711 again it's already ready to give you a sample.

You need to factor in the amount of time it takes to write to the SD card to have any kind of meaningful results - that is, the total amount of time that it takes to execute a loop(), or more simply: how long since the last time your logData() function has been run.

The actual sampling time of the HX711 will probably pale into insignificance compared to all the rest of your sequential code.


body:
I am new to Arduino. I am currently working on a project which requires color detection using the TCS34725 Adafruit sensor module.
For the project, I need to calibrate the sensor with RGB colors. Color patches of RGB will be exposed to the sensor. After exposing each color patch, a push button will be pressed and then the calibration for that color should start.
1. Calibrate for Red

2. Calibrate for Green

3. Calibrate for Blue

After calibration, the sensor needs to detect the colors of objects.
I have no idea what is meant by calibrating the sensor for RGB values. Can someone please be kind enough to explain it to me.

Thank you in advance.

title: Calibrating Adafruit TCS34725 for RGB colors

Answers: 0


body:
I recently removed a GD25B32CPIG flash memory chip from a commercial coin-operated arcade game. Apparently it has all the game's sounds stored directly on the chip. I decided to see if I can learn to communicate with the chip to read the current data and write new data to it so that I can possibly change the game's sounds as the game itself doesn't have the ability to do that.

After searching online, I found [schematics][1] for the chip, including its functions and pinouts.

[![Pinout of the GD25B32CPIG][2]][2]

I've wired it up to my Arduino Uno's MOSI, MISO, CK, and SS pins as well as the 3.3V and GND for power. This is the only part I know is correct.

Unfortunately, I am lost on what to do next since I've never used the SPI library by itself (normally other libraries handle the SPI connections in my other projects). Nobody else has a tutorial on this particular chip and I'm a little bit lost by the datasheet's commands. I also did some research on SPI and found the tutorials to be a bit confusing.

I haven't tested anything because I don't want to alter the data unless I know what I'm doing.

The question:
-----------------
Is there a way to read all data at once and write to a particular register?

  [1]: https://www.gigadevice.com/datasheet/gd25b32c/
  [2]: https://i.stack.imgur.com/fjzKl.png

title: Reading and writing to GD25B32CPIG flash memory

Answers: 0


body:
I'm trying to make a cable checker to help me make custom cables for my computer. I'm thinking I plug the cable ends into sockets on the device, then the Arduino checks between different pins to make sure that no wires are in the wrong spot or unplugged.

So I'm thinking it runs through like this:

I plug the cable into connectors on the device. The Arduino has the PSU pinouts saved. Pin 1 represents one end of the cable, pin 2 represents the opposite end. Same with 3-4/5-6 etc. If the cable is assembled correctly, it should act as a connection between pins 1-2, pins 3-4, 5-6 etc.

tests pin 1 - 2 to see if they're connected, if yes, light up a green LED, if not, light up a red LED

tests pin 3 - 4, does the same thing

Repeats this  for every wire in the cable

Am I on the right track? How would I do this? I've seen people talking about pullup resistors but I'm also seeing people say that shorting can damage the board

title: How to test custom cables?

Answers: 1

body:
The scope of your question is too wide for a simple answer so let us constrain it to slow signals (audio frequencies or less) over short cables (not more than several meters) in a electrically clean environment (such as found in most homes).

That said, it is likely most looking for similar solutions reading your question will have different specific requirements.  So to make this question and answer useful to others let us consider the most generic, economical and Arduino based solution.

 1. Most cables worth automatically testing will have far more individual connections than common Arduino boards, such as the Arduino Uno, have GPIO pins.  Consider using a GPIO expander or multiple Arduinos which communicate with each other to coordinate efforts.
 2. When testing a cable that will be used for low frequencies, short distance and low immunity to noise it is likely the only faults that are of concern are OPENS and SHORTS.
 3. As this design uses GPIO pins we have the following options at any given GPIO pin: Drive High, Drive Low and Input With Pull Ups.
 4. Build a cable test rig where one end (the near end) of the cable under test is connected to GPIO pins designated as the driver side and the other end of the cable under test (the far end) is connected to GPIO pins designated as the sensing side.
 5. For a SHORTS and OPENS test set all the sensing  and driving GPIO pins to Input With Pull Ups.  Verify that all sensing GPIO pins report a 1.  Next change one and only one of the driver GPIO pins to an output and send a 0.  Record that state of all sensing GPIO pins.  Return the driver GPIO pin to Input with NO PULL UPS and repeat these steps for the next GPIO driver pin.
 6. If this is a STRAIGHT THROUGH cable only 1 sensing GPIO pin should report a 0 in each testing pattern recorded.  If more than 1 sensing GPIO pin reports a 0 then there is a short between the 0 reporting pins.  If none of the GPIO pins reports a 0 then there is an open for that GPIO pin.
 7. Use the same test for cables containing intentional SHORTS (perhaps multiple ground pins are shorted together) expecting to see the associated GPIO pins to all change to 0 at the same time.
 8. For even more complex cables containing loop backs at both ends consider only the "GPIO pin set to an output sending 0" as the driver and record the state of ALL OTHER GPIO pins as they are now all possible outputs.


body:
I am using two HG-C 1100 measurement sensor for measuring the width of the metal. In the top of the sensor I will be having the measurement value. The sensor is capable of measuring the dimensions from -35mm to 35mm.
So I am using the formula:

```cpp
int First_sample = analogRead(6);
int Second_sample = analogRead(7);
float First_sensor = (map(First_sample, 1023, 0, -3500, 3500) / 100.0);
float Second_sensor = (map(Second_sample, 0, 1023, -3500, 3500) / 100.0);
Serial.print("First_sensor:");
Serial.println(First_sensor, 3);
Serial.print("Second_sensor:");
Serial.println(Second_sensor, 3);
Final_sensor = (First_sensor - Second_sensor);
Serial.println(Final_sensor, 4);
```
If I use this code, I will get the proper width of the metal. But when I place the metal in between the sensor, I am getting the exact width in the serial monitor. But at the top of the sensors the values are different.
I don't why the analog values are different on the serial monitor and the top of the sensors. But the output of the sensor is perfect in the serial monitor.
Can anyone help me with this?

title: HG-C 1100 measurement sensor

Answers: 1

body:
The HG-C1100 has a resolution of 70 μm (= 0.07 mm) over a measuring range of 70 mm.
You quote errors of 0.28 and 0.38 mm, which is worse than can be expected (±0,07 mm).
The resolution is 1‰ of the measuring range. Therefore the 10 bits range (1024) of the Arduino's Analog-Digital Converter (ADC) is sufficient.

You map the ADC output of 0-1023 to a range of -3500 to +3500 which results in a value in 0,01 mm. Then you divide by 100.0 resulting in a value in mm.

According to Arduino's Reference the function map() uses integer arithmetic, but the arguments are longs and the calculation order is such that maximal accuracy is maintained. This provides sufficient accuracy for this purpose. I am only not sure if you constants should be post fixed wit an "L".

So far everything looks all right.

The errors you mention correspond to about 5 counts of the ADC.
I assume the solution lies in taking measures to prevent noise entering your signals (signal conditioning).

Addition:<br />
When you read the same sensor repeatedly do you get stable readings? You could try to use an average over multiple readings. Did you look at the signal(s) with an oscilloscope?


body:
I was trying to have some fun with avr-assembly on my arduino and I tried the following codes to blink my LED

first I tried the ISR approach and when It didn't work I tried the CTC mode one,
both codes are listed respectively. on the first one the LED lightsup and stay that way (no blinking) on the second one it just stays off

one more thing to note is on trying to load OCR1AL first The led would blink nicely if my hand got near PORTD pins for some reason,

I guessed it's some grounding problem and It's fixed when I pulled high all PORTD pins and it disappeared completely when I figured out that I need to load (the high byte) OCR1AH first

```
.nolist
.include "m328Pdef.inc"
.list

.org  0x0000
jmp  Init

.org  0x0016
jmp  TIMER1_COMPA

.EQU LED_PIN = PB1

Init:
 ;ldi  r16, 255
 ;out  DDRD, r16
 ;out  PORTD, r16

 ;First configure The led pin as output and initilize it to high
 sbi  DDRB, LED_PIN
 sbi  PORTB, LED_PIN

 ;Second Enable Global Interrupts
 sei

 ;Enable the Output compare Interrupt in the TIMSK1 Register
 ldi  r16, 0b00000010
 sts  TIMSK1, r16

 ; Reset the TCCR1A
 ldi  r16, 0b00000000
 sts  TCCR1A, r16

 ; Set the prescalar to 256 in the Timer Control 1B register
 ldi  r16, 0b00000111
 sts  TCCR1B, r16

 ;Now load the value for Output compare register 31250 or   01111011 00100000  or 15625 =  00111101 00001001
 ldi  r16, 0b00111101
 ldi  r17, 0b00001001
 sts  OCR1AH, r16
 sts  OCR1AL, r17

LOOP:

 rjmp  LOOP

TIMER1_COMPA:
 ;First Reset the coutner
 ldi  r16, 0
 sts  TCNT1H, r16
 sts  TCNT1L, r16

 ;Second Toggle the Pin (LED) state
 sbi  PINB, LED_PIN

 reti

```

**CTC:**
```
.nolist
.include "m328Pdef.inc"
.list

.org  0x0000
jmp  Init

.org  0x0016
jmp  TIMER1_COMPA

.EQU LED_PIN = PB1

Init:
 ;ldi  r16, 255
 ;out  DDRD, r16
 ;out  PORTD, r16

 ;First configure The led pin as output and initilize it to high
 sbi  DDRB, LED_PIN
 sbi  PORTB, LED_PIN

 ;Second Enable Global Interrupts
 sei

 ;Enable the Output compare Interrupt in the TIMSK1 Register
 ldi  r16, 0b00000010
 sts  TIMSK1, r16

 ; Reset the TCCR1A
 ldi  r16, 0b01000000
 sts  TCCR1A, r16

 ; Set the prescalar to 256 in the Timer Control 1 registers
 ldi  r16, 0b00001111
 sts  TCCR1B, r16

 ;Now load the value for Output compare register 31250 or   01111011 00100000  or 15625 =  00111101 00001001
 ldi  r16, 0b00111101
 ldi  r17, 0b00001001
 sts  OCR1AH, r16
 sts  OCR1AL, r17

LOOP:
 rjmp  LOOP

TIMER1_COMPA:
 ;First Reset the coutner
 ;ldi  r16, 0
    ;sts  TCNT1H, r16
 ;sts  TCNT1L, r16

 ;;Second Toggle the Pin (LED) state
 ;sbi  PINB, LED_PIN

 reti

```

title: LED Blink in assembly with timer1 output compare interrupt not working

Answers: 1

body:
I am not set up to test your code right now, perhaps later.  But:

```none
    ; Set the prescalar to 256 in the Timer Control 1B register
    ldi     r16, 0b00000111
    sts     TCCR1B, r16
```

When set to ones, the low order three bits of TCCR1B, select an external clock source at the T1 pin, for clocking on a rising edge.  Probably what's happening is that when you finger is near enough the T1 pin you are capacitively coupling mains frequency to it causing it to tick.

/256 prescaler would have `100` in the lower three bits.

If I manage to get a proper environment up to test your code, I'll look into it a bit more thoroughly.


body:
Hi I have a coinslot project and connected with a fingerprint sensor it was stated in the ardiuno forum that it will work on pin 2 and 3 , but it is already used pins of the finger print sensor .

Coinslot signal is in pin 9 and the in2,3 is for the rx and tx of the fingerprint sensor.

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

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

title: How can I use attached interrupt on my project?

Answers: 1

body:
If you can't rearrange the pins like Majenko suggests in the their comment, something you can do is is use pin change interrupts rather than the regular "external" interrupts.  On the UNO, these are available on all of the "digital" capable pins, which also includes most of the "analog" pins if you have an SMT UNO, or all of them if you have a DIP model.

[NiceHood's PinChangeInterrupt library][1] is modeled after the regular `attachInterrupt` function, so it should be [familiar looking to you][2].  It's in the library manager; you don't need to get it from github.

NOTE: The O.P. opened a another [question][3] which seems to be this same thing, only with different context and specific code.  There I've given **more details on what's outlined above but in relation to that that specific code in an [answer there][4]**.

  [1]: https://github.com/NicoHood/PinChangeInterrupt
  [2]: https://github.com/NicoHood/PinChangeInterrupt/blob/1.2.9/examples/PinChangeInterrupt_LowLevel/PinChangeInterrupt_LowLevel.ino#L50
  [3]: https://arduino.stackexchange.com/q/84325/70020
  [4]: https://arduino.stackexchange.com/a/84326/70020


body:
I am using 10 ds18b20 Temperature sensors using with "DS2482-100" I2C board and Arduino
so when I am getting the output like this:- "ROM = 28 46 04 1F 0D 00 00 74 96014B467FFF0A100A 25.3 2699 Dc", so Instead of address I want to name it "Sensor-1", "Sensor-2"  like that any tutorial or help would be appreciated.

 1. `*
 Arduino library for controlling DS2482-100 and DS2482-800 1-wire masters.
 Uses Wire library to communicate with DS2482 so be sure to call Wire.begin() before using the library.
 Quick example modeled after Onewire example:
*/

         #include <OneWire.h>
         #include <Wire.h>
         #include <DS2482.h>
         #include <DallasTemperature.h>

         DS2482 ds(0);  //channels ds2482-800 is 0 to 7, DS2482-100 is just set 0

         byte data[12]; //holding for onewire capture
         byte addr[8]; //1wire wire address and CRC
         long time_temp;

         uint8_t sensor1[8] = { 0x28, 0x00, 0xF9, 0x1E, 0x0D, 0x00, 0x00, 0x76 };
         uint8_t sensor3[8] = { 0x28, 0x61, 0x64, 0x12, 0x3F, 0xFD, 0x80, 0xC6 };

         void setup()
         {
            Wire.begin();
            ds.reset();
            pinMode(13, OUTPUT);

            // start serial port
             Serial.begin(57600);
             time_temp = millis();
         }

         void loop()
        {

           //do search

          if ( !ds.wireSearch(addr))
          {
            if(addr == sensor1)
            {
            Serial.print("sensor1");
            };
         Serial.print("No more addresses.\n");
         ds.wireResetSearch();

        return;
        }

        Serial.print("ROM =");
        for ( int i = 0; i < 8; i++) {
        Serial.write(' ');
        if (addr[i] < 16) Serial.print("0");
        Serial.print(addr[i], HEX);
        }

        if (ds.crc8(addr, 7) != addr[7]) {
        Serial.println("CRC is not valid!");
        return;
        }

        //test if device code DS18b20
         if (addr[0] == 0x28) {

         //read temperature data.
          ds.wireReset();
          ds.selectChannel(0);
          ds.wireSelect(addr);
          ds.configure(0x05); //set bus on strong pull-up after next write until next command
          ds.wireWriteByte(0x44); //convert temperature on this device
          delay(770); //wait for conversion 750ms Plus margin
          ds.wireReset();
          ds.selectChannel(0);
          ds.wireSelect(addr);
          ds.wireWriteByte(0xbe);         // Read Scratchpad command

          //display hex values of scratchpad
          Serial.print(" ");
          for ( int i = 0; i < 9; i++)
          {

           data[i] = ds.wireReadByte();

          if (data[i] < 16)Serial.print("0");
          Serial.print(data[i], HEX);

        }
          Serial.print(" ");

          //convert to decimal temperature

            int LowByte = data[0];
            int HighByte = data[1];
            int TReading = (HighByte << 8) + LowByte;
            int SignBit = TReading & 0x8000;  // test most sig bit
            if (SignBit) // negative
        {
            TReading = (TReading ^ 0xffff) + 1; // 2's comp
        }

            int Tc_100 = (double)TReading * 0.0625 * 10;

            if (SignBit) // If its negative
        {
            Tc_100 = 0 - Tc_100;
        }

          //print temp for each device

           Serial.print(Tc_100 / 10);
           Serial.print(".");
           Serial.print(Tc_100 % 10);
           Serial.print(" ");
           Serial.print(millis() - time_temp);
           Serial.println(" Dc");
           }

           }

title: How to name the temperature sensors instead of printing address using ds2482-100 and ds18b20 sensor- Help

Answers: 0


body:
I am attempting to write a file found on an SD card to a connected Ethernet client. The file opens fine, and we have no problems writing to the client. For testing purposes I also write the lines read from the file to the serial port at the same time as being written to the client. What is happening though, is that the entire file contents are displayed in the serial monitor, but the browser only receives about 2978 characters. the actual file, not including the header, sent separately, is 4426 bytes long. I ran a test sending about 260000 via 8000 "client.print(...)" statements and this worked fine.

I have attached code. Anything not necessary to the basic function of the code has been stripped out to give us the minimum required to debug. I am using the libraries **EthernetWebServer_SSL_STM32** & **sdFat**. My code is derived from the **WebServer** example.

    /****************************************************************************************************************************
      WebServer.ino - Simple Arduino web server sample for ESP8266 AT-command shield
      For STM32F/L/H/G/WB/MP1 with built-in Ethernet LAN8742A (Nucleo-144, DISCOVERY, etc) or W5x00/ENC28J60 shield/module

      EthernetWebServer_SSL_STM32 is a library for STM32 using the Ethernet shields to run WebServer and Client with/without SSL
      Use SSLClient Library code from https://github.com/OPEnSLab-OSU/SSLClient

      Built by Khoi Hoang https://github.com/khoih-prog/EthernetWebServer_SSL_STM32
      Licensed under MIT license
     *****************************************************************************************************************************/
    #define REPLY_HEADER "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n"

        void Process_Client_Request()
        {
            FsFile   file;
            char   line[500];
            char   Received_Character = '\0';
            uint32_t Character_Index    =   0;
            uint32_t n;
            uint32_t File_Length_Bytes;
            uint32_t File_Length_Lines;

         // listen for incoming clients
         EthernetClient client = server.available();

        // static  ArduinoOutStream sout(client);
         static  ArduinoOutStream cout(Serial);

         if (client)
         {
          // an http request ends with a blank line
          bool currentLineIsBlank = true;

          while (client.connected())
          {
           if (client.available())
           {
            char c = client.read();
            Serial.write(c);
            // if you've gotten to the end of the line (received a newline
            // character) and the line is blank, the http request has ended,
            // so you can send a reply
            if (c == '\n' && currentLineIsBlank)
            {
             Serial.println(F("Sending response:\n"));

             // send a standard http response header
             // use \r\n instead of many println statements to speedup data send
             client.print(REPLY_HEADER);
             Serial.println(F(REPLY_HEADER));

             // Open the SD card
             if (!sd.begin(SD_CONFIG))
             {
              sd.initErrorHalt(&Serial);
             }

             // Specify the file to read
             char fileName[] = "404.htm";

             // Open the file to READ from the SD card
             if (!file.open(fileName, O_READ))
             {
              sd.errorHalt(&Serial, F("open failed"));
             }

             File_Length_Bytes = file.fileSize();
             File_Length_Lines = 0;

             Serial.print(__DATE__); Serial.print(", "); Serial.println(__TIME__);

             while ((n = file.fgets(line, sizeof(line))) > 0)
             {
              // Write the line to the client
              client.print(line);

              // Print the line
              Serial.print(line);

              File_Length_Lines++;
             }
             file.close();
             break;
            }

            if (c == '\n')
            {
             // you're starting a new line
             currentLineIsBlank = true;
            }

            else if (c != '\r')
            {
             // you've gotten a character on the current line
             currentLineIsBlank = false;
            }
           }
          }
          // give the web browser time to receive the data
          delay(10);

          // close the connection:
          client.stop();
          Serial.println(F("\n\nClient disconnected"));

          Serial.println("\n");
          Serial.print("Total bytes read: "); Serial.println(File_Length_Bytes);
          Serial.print("Total lines read: "); Serial.println(File_Length_Lines);
          Serial.println("");
         }
        }

Any ideas what I am doing wrong?

I tried removing all references to the SD card, and hard-coded a phrase to be sent out via the while() loop - this worked fine. Please see the code below:

    #define REPLY_HEADER "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n"

    void Process_Client_Request()
    {
        uint32_t File_Length_Bytes;
        uint32_t File_Length_Lines;
     uint16_t   c;
     uint32_t  LineCount = 0;

     // listen for incoming clients
     EthernetClient client = server.available();

       // Open serial communications and wait for port to open:
       Serial.begin(115200);
       while (!Serial);

     if (client)
     {
      // an http request ends with a blank line
      bool currentLineIsBlank = true;

      while (client.connected())
      {
       if (client.available())
       {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank)
        {
         Serial.println(F("Sending response:\n"));

         // send a standard http response header
         // use \r\n instead of many println statements to speedup data send
         client.print(REPLY_HEADER);
         Serial.println(F(REPLY_HEADER));

         client.print("");
         Serial.println("");

         while (LineCount < 8000)
         {
          client.print("This is line number: "); client.print(++LineCount); client.print("
\r\n");
          Serial.print("This is line number: "); Serial.print(LineCount); Serial.print("
\r\n");
         }

         client.print("");
         Serial.println("");
         break;
        }

        if (c == '\n')
        {
         // you're starting a new line
         currentLineIsBlank = true;
        }

        else if (c != '\r')
        {
         // you've gotten a character on the current line
         currentLineIsBlank = false;
        }
       }
      }
      // give the web browser time to receive the data
      delay(10);

      // close the connection:
      client.stop();
      Serial.println(F("\n\nClient disconnected"));

      Serial.println("\n");
     }
    }

When reading a line of text from the SD card and printing it to the client, transmission to the client terminates after about 1279 characters, give or take. When this happens, the web browser continues to wait for more data.

title: Writing file from SD card to ethernet client stops sending after about 2980 characters, STM32f7 board

Answers: 0


body:
Is there a way for me to have this work the opposite way?

I have one cable with an alligator clip hooked up to the reset pin and another hooked up to ground.

When I clip them both together, the board resets.

However, I would like for this to work in the opposite way such that they’re already clipped together and when you detach the cables, the board resets.

title: Is there a way to make the RESET pin work in the inverse?

Answers: 2

body:
The easiest way to do that would be to use an external pulldown resistor (a resistor from the reset pin to ground) and connect to Vcc (5V on the Nano) via your alligator cables.

As long as the alligator cables are connected, the reset pin is held HIGH through them. When you disconnect them, the pulldown resistor pulls the reset pin to LOW. That holds the Nano in reset until you again connect the alligator clips.

If you want the Nano to reset and then directly work again without the alligator clips reconnected, it gets more difficult. One way I can think of is building a monostable vibrator circuit, which gets in the excited state, when your alligator clips are disconnected, resets the Arduino and then goes back into the stable stable, letting the Arduino execute its code. Though that is more an electrical question, than an Arduino one.

body:
My personal preference would be to attach a NOT gate to the RESET pin.  This can be constructed very simply from a single NPN transistor (or N-channel MOSFET) and a resistor.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/XgkOA.png)

<!-- End schematic -->

With the wire disconnected R1 turns on Q1 which pulls the RESET pin LOW.  With the wire connected Q1 is turned off, allowing RESET to be pulled back up by the pullup resistor that's built into the Arduino.

This method also won't interfere with the programming reset action of the Arduino.


body:
I have a PCB (let's call it remote PCB) on which I have 4 LEDs and 4 buttons mounted. The remote PCB is far away from my desk (about 12 feet away). The LEDs are used to indicate the status and the buttons are for various state inputs.

All of them are connected to UNO directly.

 1. I am planning to use a 10 pin IDC connector and IDC ribbon cable for the same.
 2. THe LEDs' current is about 2 mA each (white LEDs)
 3. The push buttons will make a ground connection when pressed, else the internal pull-up of the UNO will keep the GPIO at a high level.
 4. I have put a capacitor of 10 nF across the switch to address denounce.
 5. I have a series resistor of 1-kilo ohm for all four Switches on the remote PCB

I would like to know if this is okay? Will there be any problem due to the length. The LEDs are for indication and won't blink faster than 200 ms at any point in time. They will be used to indicate status which is very slow signals.
Thanks in Advance!

title: Connecting LEDs and push buttons 12 feet away from Arduino UNO

Answers: 1

body: That is a big no-no. You are adding extremely long antennas to the Arduino asking for problems. At a minimum on the inputs add a 10K series resistor at the Arduino pins.  My preference would be to put the capacitors at the arduino pins to help decouple noise etc as well as the pull up resistors on the wire side of the 10K resistors. Use a buffer of some type for the LEDs, a transistor would work. This may work but for how long and how many processors can you destroy over time.


body: I have a Nodemcu with which i'm doing a project. So whenever there is a power loss i want values of some of the variables to not be reset, because of that im trying to store the values in EEPROM of the nodemcu. But the problem is i want to know if the EEPROM will get reset when a new code is uploaded and also since the nodemcu stores wifi credentials in the EEPROM i dont want to accedentally select an EEPROM address in which the wifi credentials are stored and cause a problem. Can anyone tell me the safe EEPROM addresses to use and also if EEPROM will get rest if  a new code is uploaded?

title: does EEPROM reset itself when a new code is uploaded?

Answers: 1

body:
The esp family chips do not have EEPROM. Instead they just dedicate a small section of flash to pretend to be EEPROM.

That flash section, depending on the core version, is either a dedicated EEPROM partition, or a dedicated key in the nvram partition. Either way it's separate to the wi-fi credentials, which are stored in their own key in the nvram partition.

EEPROM can be erased when you upload code if the partition layout changes. It's less likely to be erased if it's a newer version of the core where it's stored in the nvram.

For safety, don't change the partition size, and ideally use ArduinoOTA which will never change the partitions or erase the nvram.


body:
I have a rig with 5 light [sensors][1] on an [I2C mux][2] and I am wondering if I need only 1 pull-up resister set for the whole bus or one on each branch from the mux?

Or should I remove all the pull-ups from the branches and leave the one on the mux?

My issue is that the Arduino softlocks after 5-60 min of running, and it always softlocks on a read lux call.

  [1]: https://www.sparkfun.com/products/15436
  [2]: https://www.sparkfun.com/products/16784

title: I2C pull up resistors and an I2C MUX

Answers: 1

body:
From what I can tell, the I2C bus multiplexer itself receives and re-transmits on what amounts to a completely separate bus.  So, each bus would need its own pull-up resistors.  That said, the board you've linked that breaks out the multiplexer chip [has pull-up resistors][1] on each bus that it's providing:

[![Excerpt of Sparkfun Multiplexer breakout showing bus pull-up resistors on far side of multiplexor.][2]][2]

The breakout also has pull-ups on the bus going to the multiplexor itself:

[![Excerpt of Sparkfun Multiplexer breakout showing bus pull-up resistors on near side of multiplexor.][3]][3]

Beyond that, the ambient light sensor [breakout seems to provide its own 4.7K pull-ups][4]. AVR-based Arduinos (and probably others) also enable their own, admittedly weak, pull-ups in the [guts of the wire library][5].

It seems you should not necessarily need to add any additional pull-up resistors of your own to what is already on the buses.

---

With regard to the O.P. comment given below concerned about too many pull-up resistors.

At some point probably below (perhaps far below) 500 ohms some devices may have trouble sinking enough current to create a LOW. The AVR wouldn't have a problem with 500 ohms for example.

The ATMega328P datasheet (along with most other AVR datasheets) will tell you that the internal pullup value is between 20K-50K.  If you're concerned about too-many-parallel-resistors/too-many-current-paths/too-little-total-resistence, you can take the 20K figure along with multiplexer breakout's 4.7K figure, to [calculate][6] `pow(1 / 20e3 + 1 / 4.7e3, -1)`, for about 3.8K, which should be fine.  If you do the same calculation on the multiplexor's individual bus resistor 4.7k and the ambient light sensor breakout's own 4.7k resistor, you get 2.35 k (half), which is also probably fine.  If anything both of these total figures can be made smaller (by adding yet *another* parallel resistor) for longer buses and at higher frequencies.  If you're worried about these figures you can lower the I2C clock rate.  You can also examine the edges of your signal with a scope.  Also if you really want to dig into this stuff, you read in [the official I2C manual][7].  But, really I think what you have is probably fine.

  [1]: https://cdn.sparkfun.com/assets/7/2/f/c/6/Qwiic_Mux_Schematic.pdf
  [2]: https://i.stack.imgur.com/g0ouG.png
  [3]: https://i.stack.imgur.com/rKrZ4.png
  [4]: https://cdn.sparkfun.com/assets/e/7/0/9/4/SparkFun_Ambient_Light_Sensor_VEML6030_Schem.pdf
  [5]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/libraries/Wire/src/utility/twi.c#L87
  [6]: https://www.allaboutcircuits.com/tools/parallel-resistance-calculator/
  [7]: https://www.nxp.com/docs/en/user-guide/UM10204.pdf


body:
When I turn on DC motor with a button I get a a fixed PWM value that goes into a loop till button state changes.

What should I change that I could change X value with potentiometer in a loop?

```c++
int X = A0;
int SW = 2;
int Xval=5;
int SWval;
int buttonNew;
int buttonOld = 1;
int buttonState= 1;
int engine = 6;

void setup() { // This executes once
  Serial.begin(9600);
  pinMode(X, INPUT);
  pinMode(SW, INPUT_PULLUP);
}

void loop() { // This loops continuously
  Xval = analogRead(X);
  buttonNew = digitalRead(SW);

  if (buttonOld == 0 && buttonNew == 1) {
    if (buttonState == 0) {
      analogWrite(engine, Xval);
      buttonState = 1;
    }
    else {
      digitalWrite(engine, LOW);
      buttonState = 0;
    }
  }

  buttonOld = buttonNew;
  delay(1);
  Serial.print("button");
  Serial.print(SWval);
  Serial.print("          X=");
  Serial.println(Xval);
}
```

title: Arduino on/off PWM

Answers: 1

body:
Move the analogWrite out of the button-state-change code, and it will update the PWM continually, instead of only when the button is pressed.

See the code below.

I also change the variable name `buttonState` to `motorState`, as it indicates the state of the motor (On/Off). And I inverted it, so `1` means the motor is ON.

The other thing I did was to increase the delay to 10ms, so you don't get any issues with switch-bounce.

``` lang-cpp
int X = A0;
int SW = 2;
int Xval=5;
int SWval;
int buttonNew;
int buttonOld = 1;
int motorState= 0;//indicates whether the motor is on/off
int engine = 6;

void setup() { // This executes once
  Serial.begin(9600);
  pinMode(X, INPUT);
  pinMode(SW, INPUT_PULLUP);
}

void loop() { // This loops continuously
  buttonNew = digitalRead(SW);
  if (buttonOld == 0 && buttonNew == 1) {
    if (motorState == 0) {
      motorState = 1;
    }
    else {
      motorState = 0;
    }
  }
  buttonOld = buttonNew;

  if (motorState == 1) {
    Xval = analogRead(X);
    analogWrite(engine, Xval);
  }
  else {
    digitalWrite(engine, LOW);
  }

  delay(10);
  Serial.print("button");
  Serial.print(SWval);
  Serial.print("          X=");
  Serial.println(Xval);
}
```


body:
I'm new to Arduino and I'm building a project that fetches data from a website (using ESP8266) and then transfers them to my `Arduino UNO` via serial port.

Data coming from ESP8266 every 20s - `[{"x": 0,"y": 0,"rgb": [255, 200, 174]},{"x": 1,"y": 0,"rgb": [255, 200, 174]},{"x": 2,"y": 0,"rgb": [255, 200, 174]}]`

But when I print the data like this
```

void loop() {

  if (Serial.available()) {
    Serial.write(Serial.read()); // This line prints only one character out of whole string

    data =  Serial.read(); // so this doesn't work

    DeserializationError error = deserializeJson(response, data);
    if (error) {
      Serial.print(F("deserializeJson() failed: "));
      Serial.println(error.f_str());
      return;
    }
    for (JsonObject elem : response.as<JsonArray>()) {
      int x = elem["x"]; // 2, 2, 2
      int y = elem["y"]; // 2, 2, 2
      JsonArray rgb = elem["rgb"];

      int rgb_0 = rgb[0]; // 255, 255, 255
      int rgb_1 = rgb[1]; // 255, 255, 255
      int rgb_2 = rgb[2]; // 255, 255, 255
      //Serial.print(x);
    }
  }
  delay(1000);   //then it waits 1 second and goes from the start
}
```

How can I make it to get the whole string and save it into a variable?

Thanks, much for answering.

title: Getting all data of my JSON object from Serial.read() at once

Answers: 1

body:
I was going to put this as a comment, but maybe it belongs as an answer:

For what it's worth, ArduinoJSON seems to be able to [deserialize directly from a stream](https://arduinojson.org/v6/api/json/deserializejson/), i.e. `Serial`, which may obviate the question *as asked*.  Presumably it knows where to stop deserializing, because it knows when it has received an entire JSON object; being a proper JSON parser, it can probably work this out better than you can without, you know, writing a JSON parser.

The following was just thrown together, now the author is here you should probably just follow their direction, but here's the code anyway:

```c++
#include <ArduinoJson.h>

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

void print_transmission_counter( {
    static unsigned long received_object_counter;
    Serial.println(F("\n\n\n\n"));
    for (int i = 0; i < 30; ++i) {
        Serial.write('-');
    }
    Serial.write('[');
    Serial.print(received_object_counter++);
    Serial.println(']');
}

void loop() {
    static StaticJsonDocument<256> json_doc;
    static bool led_state;

    print_transmission_counter();

    const auto deser_err = deserializeJson(json_doc, Serial);
    if (deser_err) {
        Serial.print(F("Failed to deserialize, reason: \""));
        Serial.print(deser_err.c_str());
        Serial.println('"');
    } else  {
        Serial.print(F("Recevied valid json document with "));
        Serial.print(json_doc.size());
        Serial.println(F(" elements."));
        Serial.println(F("Pretty printed back at you:"));
        serializeJsonPretty(json_doc, Serial);
        Serial.println();
    }

    // Just give some visual indication that the loop is progressing
    led_state = !led_state;
    digitalWrite(LED_BUILTIN, led_state);
}

//  vim:sw=2:ts=2:et:nowrap:ft=cpp:
```


body:
This is weirding me out. So I wrote to the EEPROM and I would like to read from the address and format it in Base 10, err... Decimal. The normal number thingy that's not ASCII. But it keeps returning ASCII values when I write:

`Serial.println(EEPROM.read(address), DEC)`.

Wait for the weird part, when I format in other bases like, say BIN, or OCT, it outputs in the correct base. Please help. Here's the full snippet of the tiny program.

    #include <EEPROM.h>
    int addr = 0;
    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);

    }

    void loop() {
      // put your main code here, to run repeatedly:
      if(Serial.available() > 0){
        int rc = Serial.read();
        EEPROM.write(addr, rc);
        Serial.println(EEPROM.read(addr), DEC);
      }

    }

title: Serial.println won't format DEC

Answers: 1

body:
I finally figured it out. Apparently, when I call Serial.read() and assign it to "int rc", It sort of converts the actual ASCII values into integer. So reading the number 3 from the Serial monitor and assigning it to rc stores 51 in rc. So the trick I found to that was to use

    int rc = Serial.read()-'0'

That way, I am storing 51-48 which is, 3 (Since 48 is the ASCII value for 0).

Thanks.


body:
I have a question for you guys. I have some code that triggers an ultra-sonic sensor to measure distance. My code uses the EICRB register and executes in interrupt when it sees a transition on the interrupt pin. The interrupt routine is supposed to calculate the time of the echo pulse that comes from the sensor. The width of the pin is proportional to the distance measured.

I'm not sure why I'm not getting great results. There seems to be a persistent error in my measurement and I'm not sure why. It's probably something stupid. Here's a screenshot of the code I have if anyone can lend some help. Thanks for reading.

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

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

title: External Interrupts, Mega2560

Answers: 0


body:
This is my first time asking something on this platform, so if form or anything else is off, please feel free to point out things about how I could refine it and ask more concisely in the future.

I'm trying to develop an orthosis, which uses 4 load cells (full-bridge type) and 4 HX711 load cell amplifiers to inform patients via an app when they exceed their prescribed weight limit.

I have test code to calibrate the load cells and the code for the project itself. On the same Arduino, with the same components connected the test code, which only instantiates 4 HX711 objects and reads them after calibration, works fine. The full-blown project code uses exactly the same lines as well as the same hardware setup, but after the 2nd HX711 is instantiated I get no further Serial output and for all I can tell without a debugging jig, it looks like the Arduino stops executing code. If I try running the project code with only two HX711 objects (leaving the others physically connected, but commenting out the respective lines) the code works just fine.

So far I tried measuring RAM consumption, the Arduino should have 2048 bytes available, of which my project code seems to use 1483 bytes. My sensor test code uses 276 bytes, which means that technically I shouldn't be able to run out of memory. I also tried using another Arduino as a power source for the HX711 modules, just in case that the entire setup is asking for too much from a single Arduino - had no luck with that either. I would be really thankful for any pointers in the right direction since I can't figure it out on my own.

I'm using the following library for my HX711 modules: https://github.com/bogde/HX711

Project code (stops working after line 126):
```
#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>
#include "DHT.h"
#include "RTClib.h"
#include "HX711.h"

#define DHTPIN (uint8_t) 8
#define DHTTYPE DHT11
#define LED (uint8_t) 5
#define BUZZER (uint8_t) 9
#define BAUD 9600
#define NUM_CHARS (byte) 32
#define CHIP_SELECT (uint8_t) 10
#define SENSOR1_DATA (uint8_t) A0
#define SENSOR2_DATA (uint8_t) A2
#define SENSOR3_DATA (uint8_t) A4
#define SENSOR4_DATA (uint8_t) 7
#define SENSOR1_SCK (uint8_t) A1
#define SENSOR2_SCK (uint8_t) A3
#define SENSOR3_SCK (uint8_t) A5
#define SENSOR4_SCK (uint8_t) 6
#define TEST_DURATION 3000
#define NOT_CONNECTED 0
#define LIVE_VIEW 1
#define SETTINGS 2

// Constants
const int CHAR_SIZE = sizeof(char);

// Hardware interface settings
SoftwareSerial btSerial(2, 3);
RTC_DS1307 rtc;
DHT dht(DHTPIN, DHTTYPE);

HX711 SENSOR1;
HX711 SENSOR2;
HX711 SENSOR3;
HX711 SENSOR4;

// Hardware status & settings
boolean ledEnabled = true;
boolean isLedOn = false;
boolean buzzerEnabled = true;
boolean isBuzzerOn = false;
boolean error = false;

float threshold1 = 0.0f;
float threshold2 = 0.0f;
float threshold3 = 0.0f;
float threshold4 = 0.0f;

// Hardware testing
boolean ledTestinProgress = false;
unsigned long ledTestStart = 0;
boolean buzzerTestinProgress = false;
unsigned long buzzerTestStart = 0;

// Modes
int8_t mode = 0;

// Bluetooth
char data[NUM_CHARS];
boolean newData = false;

void receive();
void processMessage();
void testLED();
void testBuzzer();
void loadSettings();
void saveSettings();

extern void* __bss_end;
extern void* __brkval;

int get_free_memory()
{
  int free_memory;

  if((int)__brkval == 0)
    free_memory = ((int)&free_memory) - ((int)&__bss_end);
  else
    free_memory = ((int)&free_memory) - ((int)__brkval);

  return free_memory;
}

void setup() {
    pinMode(LED, OUTPUT);
    pinMode(BUZZER, OUTPUT);
    Serial.begin(BAUD);
    rtc.begin();
    if (!SD.begin(CHIP_SELECT)) {
        Serial.println(F("ERROR: SD init failed."));
        error = true;
    } else {
        loadSettings();

        Serial.println(F("SD initialized."));
        Serial.println(F("Settings: "));
        Serial.print(F("LED: "));
        Serial.println(ledEnabled);
        Serial.print(F("Buzzer: "));
        Serial.println(buzzerEnabled);
        Serial.print(F("Threshold 1: "));
        Serial.println(threshold1);
        Serial.print(F("Threshold 2: "));
        Serial.println(threshold2);
        Serial.print(F("Threshold 3: "));
        Serial.println(threshold3);
        Serial.print(F("Threshold 4: "));
        Serial.println(threshold4);

    }

    dht.begin();

    SENSOR1.begin(SENSOR1_DATA, SENSOR1_SCK);
    SENSOR1.set_scale(-63.f);
    SENSOR1.tare();
    Serial.println(F("Sensor 1 initialized."));

    SENSOR2.begin(SENSOR2_DATA, SENSOR2_SCK);
    SENSOR2.set_scale(-58.f);
    SENSOR2.tare();
    Serial.println(F("Sensor 2 initialized."));

    SENSOR3.begin(SENSOR3_DATA, SENSOR3_SCK);
    SENSOR3.set_scale(-50.f);
    SENSOR3.tare();
    Serial.println(F("Sensor 3 initialized."));

    SENSOR4.begin(SENSOR4_DATA, SENSOR4_SCK);
    SENSOR4.set_scale(-46.f);
    SENSOR4.tare();
    Serial.println(F("Sensor 4 initialized."));

    btSerial.begin(BAUD);
}

void loop() {
    if (!error) {
        receive();
        processMessage();

        DateTime now = rtc.now();
        float sensor1 = SENSOR1.get_units() / 1000;
        float sensor2 = SENSOR2.get_units() / 1000;
        float sensor3 = SENSOR3.get_units() / 1000;
        float sensor4 = SENSOR4.get_units() / 1000;

        Serial.print(F("Sensor 1: "));
        Serial.println(sensor1);
        Serial.print(F("Sensor 2: "));
        Serial.println(sensor2);
        Serial.print(F("Sensor 3: "));
        Serial.println(sensor3);
        Serial.print(F("Sensor 4: "));
        Serial.println(sensor4);

        if (isnan(sensor1) || isnan(sensor2) || isnan(sensor3) || isnan(sensor4)) return;

        if (!buzzerTestinProgress && !ledTestinProgress) {
            if (threshold1 > 0 && sensor1 > threshold1 ||
                threshold2 > 0 && sensor2 > threshold2 ||
                threshold3 > 0 && sensor3 > threshold3 ||
                threshold4 > 0 && sensor4 > threshold4) {
                if (buzzerEnabled)
                {
                    tone(BUZZER, 1000);
                    isBuzzerOn = true;
                }
                if (ledEnabled) {
                    digitalWrite(LED, HIGH);
                    isLedOn = true;
                }
            } else {
                if (isBuzzerOn) {
                    noTone(BUZZER);
                    isBuzzerOn = false;
                }

                if (isLedOn) {
                    digitalWrite(LED, LOW);
                    isLedOn = false;
                }
            }
        }

        if (mode == LIVE_VIEW) {
            btSerial.print(F("<"));
            btSerial.print(F("M;"));
            btSerial.print(now.unixtime());
            btSerial.print(F(";"));
            if (threshold1 > -1.0f) btSerial.print(sensor1);
            else btSerial.print(-1.0f);
            btSerial.print(F(";"));
            if (threshold2 > -1.0f) btSerial.print(sensor2);
            else btSerial.print(-1.0f);
            btSerial.print(F(";"));
            if (threshold3 > -1.0f) btSerial.print(sensor3);
            else btSerial.print(-1.0f);
            btSerial.print(F(";"));
            if (threshold4 > -1.0f) btSerial.print(sensor4);
            else btSerial.print(-1.0f);
            btSerial.println(F(">"));
        }

        if (ledTestinProgress && ((millis() - ledTestStart >= TEST_DURATION))) {
            ledTestStart = 0;
            ledTestinProgress = false;
            digitalWrite(LED, LOW);
        }

        if (buzzerTestinProgress && ((millis() - buzzerTestStart >= TEST_DURATION))) {
            buzzerTestStart = 0;
            buzzerTestinProgress = false;
            noTone(BUZZER);
        }

        delay(250);
    } else {
        tone(BUZZER, 1000);
        digitalWrite(LED, HIGH);
        delay(1000);
        noTone(BUZZER);
        digitalWrite(LED, LOW);
        delay(1000);
    }

    Serial.print(F("Free RAM: "));
    Serial.println(get_free_memory());
}

// Receive a Bluetooth message from the companion app
// Valid messages are encapsulated within '<' and '>' to ensure that the whole message is received.
void receive() {
    static boolean receiving = false;
    static byte index = 0;
    char startMarker = '<';
    char endMarker = '>';
    char rc;

    while (btSerial.available() > 0 && !newData) {
        rc = btSerial.read();
        delay(10);

        if (receiving) {
            if (rc != endMarker) {
                data[index] = rc;
                index++;

                if (index >= NUM_CHARS) {
                    index = NUM_CHARS - 1;
                }
            } else {
                data[index] = '\0';
                receiving = false;
                index = 0;
                newData = true;
            }
        } else if (rc == startMarker) {
            receiving = true;
        }
    }
}

// Processes a received message based on length and content
void processMessage() {
    if (newData) {
        int dataLength = strlen(data);

        Serial.println(data);

        if (dataLength == 1) {
            switch (data[0]) {
                case 'l': mode = LIVE_VIEW;
                break;
                case 's': {
                    mode = SETTINGS;
                    btSerial.print(F("<S;"));
                    btSerial.print(ledEnabled);
                    btSerial.print(F(";"));
                    btSerial.print(buzzerEnabled);
                    btSerial.print(F(";"));
                    btSerial.print(threshold1);
                    btSerial.print(F(";"));
                    btSerial.print(threshold2);
                    btSerial.print(F(";"));
                    btSerial.print(threshold3);
                    btSerial.print(F(";"));
                    btSerial.print(threshold4);
                    btSerial.println(F(">"));
                }
                break;
                case 'H': btSerial.println(F("<W>"));
            }
        } else if (dataLength == 2) {
            if (strcmp(data, "LT") == 0) testLED();
            if (strcmp(data, "BT") == 0) testBuzzer();
        } else {
            char* token = strtok(data, ";");
            int count = 0;

            if (strcmp(token, "S") == 0) {
                while (token != NULL) {
                    token = strtok(NULL, ";");
                    if (count == 0) ledEnabled = atoi(token);
                    if (count == 1) buzzerEnabled = atoi(token);
                    if (count == 2) threshold1 = atof(token);
                    if (count == 3) threshold2 = atof(token);
                    if (count == 4) threshold3 = atof(token);
                    if (count == 5) threshold4 = atof(token);
                    count++;
                }

                saveSettings();
            }
        }

        newData = false;
    }
}

// Initiate an LED test
void testLED() {
    ledTestStart = millis();
    ledTestinProgress = true;
    digitalWrite(LED, HIGH);
}

// Initiate a buzzer test
void testBuzzer() {
    buzzerTestStart = millis();
    buzzerTestinProgress = true;
    tone(BUZZER, 1000);
}

// Load settings from SD card
void loadSettings() {
    File settingsFile = SD.open("settings.txt", FILE_READ);

    if (settingsFile) {

        char settings[10];
        int index = 0;

        while (settingsFile.available()) {
            settings[index] = settingsFile.read();
            index++;
        }

        settingsFile.close();
        settings[index] = '\0';

        int count = 0;

        char* token = strtok(settings, ";");
        ledEnabled = atoi(token);

        while (token != NULL) {
            token = strtok(NULL, ";");
            if (count == 0) buzzerEnabled = atoi(token);
            if (count == 1) threshold1 = atof(token);
            if (count == 2) threshold2 = atof(token);
            if (count == 3) threshold3 = atof(token);
            if (count == 4) threshold4 = atof(token);
            count++;
        }
    } else {
        Serial.println(F("ERROR: Reading settings failed."));
        error = true;
    }
}

// Save settings to SD card
void saveSettings() {
    SD.remove("settings.txt");

    File settingsFile = SD.open("settings.txt", FILE_WRITE);
    if (settingsFile) {
        settingsFile.print(ledEnabled);
        settingsFile.print(";");
        settingsFile.print(buzzerEnabled);
        settingsFile.print(";");
        settingsFile.print(threshold1);
        settingsFile.print(";");
        settingsFile.print(threshold2);
        settingsFile.print(";");
        settingsFile.print(threshold3);
        settingsFile.print(";");
        settingsFile.print(threshold4);
        settingsFile.println(";");

        settingsFile.close();
    } else {
        Serial.println(F("ERROR: Saving settings failed."));
        error = true;
    }
}
```
Sensor test code (working flawlessly with the same hardware setup):
```
#include "HX711.h"

#define SENSOR1_DATA (uint8_t) A0
#define SENSOR2_DATA (uint8_t) A2
#define SENSOR3_DATA (uint8_t) A4
#define SENSOR4_DATA (uint8_t) 7
#define SENSOR1_SCK (uint8_t) A1
#define SENSOR2_SCK (uint8_t) A3
#define SENSOR3_SCK (uint8_t) A5
#define SENSOR4_SCK (uint8_t) 6

extern void* __bss_end;
extern void* __brkval;

HX711 SENSOR1;
HX711 SENSOR2;
HX711 SENSOR3;
HX711 SENSOR4;

int get_free_memory()
{
  int free_memory;

  if((int) __brkval == 0)
    free_memory = ((int)&free_memory) - ((int)&__bss_end);
  else
    free_memory = ((int)&free_memory) - ((int)__brkval);

  return free_memory;
}

void setup() {
    Serial.begin(9600);
    Serial.println(F("Sensor Test"));

    SENSOR1.begin(SENSOR1_DATA, SENSOR1_SCK);
    SENSOR1.set_scale(-63.f);
    SENSOR1.tare();
    Serial.println(F("Sensor 1 initialized."));

    SENSOR2.begin(SENSOR2_DATA, SENSOR2_SCK);
    SENSOR2.set_scale(-58.f);
    SENSOR2.tare();
    Serial.println(F("Sensor 2 initialized."));

    SENSOR3.begin(SENSOR3_DATA, SENSOR3_SCK);
    SENSOR3.set_scale(-50.f);
    SENSOR3.tare();
    Serial.println(F("Sensor 3 initialized."));

    SENSOR4.begin(SENSOR4_DATA, SENSOR4_SCK);
    SENSOR4.set_scale(-46.f);
    SENSOR4.tare();
    Serial.println(F("Sensor 4 initialized."));
}

void loop() {
  Serial.print(F("S1: "));
  Serial.print(SENSOR1.get_units(), 1);
  Serial.print(F(" | S2: "));
  Serial.print(SENSOR2.get_units(), 1);
  Serial.print(F(" | S3: "));
  Serial.print(SENSOR3.get_units(), 1);
  Serial.print(F(" | S4: "));
  Serial.println(SENSOR4.get_units(), 1);
  Serial.print(F("Free RAM: "));
  Serial.println(get_free_memory());
}
```

Wiring diagram (Fritzing): [![Wiring diagram][1]][1]

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

Changelog:
- Code is now embedded in the question.

title: Arduino Uno R3 stops executing code, when trying to instantiate multiple HX711 objects

Answers: 2

body:
You'll need to use a library that support multiple HX711's. The [HX711-multi][1] library by compugician has worked great for me.

> The main difference this library introduces is the ability to sample multiple HX711 units simultaneously. It is optimized for intoducing minimal (effectively zero) overhead.

  [1]: https://github.com/compugician/HX711-multi

body:
If I have seen this correctly, you are currently only measuring the memory requirement in the loop().
To find out how much memory your code is using you should measure the memory consumption in any function which is memory hungry. You should call this line in all functions that are likely to put a heavy load on the heap.

    freeRAM = min(freeRAM, get_free_memory());

freeRAM is a global defined int with an initial value of 2048 (or what the RAM size is).
It is not enough to measure the memory usage only in loop(), because every function uses the heap during a call and frees the memory afterwards if variables not static.


body:
I am using two RFID sensors operating on SPI with arduino Due. They will not be operating at the same time.
Is it favorable to use the ICSP pins as SPI pins for one of them, or use them in a one master two slaves configuration with the SPI header?

title: Using ICSP pins as SPI in Arduino Due

Answers: 0


body:
I have a LCD display where in I'm displaying a WiFi signal logo. I want to reduce the number of bars on the logo, indicating that the signal strength is dropping. I got the reducing bars on the LCD completed, I still have to find out the actual signal strength.

How do I find the signal strength of the connected network with ESP8266 based NodeMCU?

title: How to get current WiFi signal strength?

Answers: 1

body:
You use [`WiFi.RSSI()`](https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/station-class.html#rssi):

> # RSSI
>
> Return the signal strength of Wi-Fi network, that is formally called Received Signal Strength Indication (RSSI).
>
>     WiFi.RSSI()
>
> Signal strength value is provided in dBm. The type of returned value is int32_t.
>
> Example code:
>
>     Serial.printf("RSSI: %d dBm\n", WiFi.RSSI());
>
> Example output:
>
>     RSSI: -68 dBm


body:
Perhaps this is a beginners question and I am not sure. I currently have a custom made circuit with an atmega328p chip connected to an mpu6050. However, when I program in Arduino I am not sure what to do? I can't pick a "board" as the atmega328p doesn't belong to a board? (from what I'm aware at least)

How in Arduino do I choose to program for my atmega328p chip? Without having to pick a board such as Arduino Uno etc. As I don't have any board for this. Or does the atmega328p chip always belong to a certain board?

I have a fully working circuit with a cyrstal (16MHz), battery sources, atmega328p etc. But I don't know how to program it with Arduino? I can program it in C, but would like to use Arduino due to certain libraries.

title: Atmega328p with arduino without the board

Answers: 1

body:
The board option is actually selecting a variant out of the installed cores (which provide the basic Arduino framework for a group of boards/chips). Each core can support multiple variants/boards/chips and can give each of them individual lists of options. There certainly also is a core, which supports the Atmega328p with all needed config options (like the frequency setting). You just need to install it from the boards manager.

Though, since you use a 16MHz crystal just like the Uno/Nano, you could just select the Uno or Nano as board. Neither the Arduino IDE, nor the Atmega328p can know, that the Atmega is actually a standalone one and not mounted on an Arduino board. So you can just use that board when you keep the config options inherent to an Arduino Uno/Nano (frequency setting and pin mapping mainly).


body:
I just got a couple of Arduino Pro Micros for a [custom keyboard](https://github.com/omkbd/ErgoDash) build. Before testing them with the Arduino IDE, I tried to test them with [qmk](https://github.com/qmk/qmk_firmware) by shorting `RST` to `GND` to try and flash it. After a few seconds of holding `RST`, I got a single blink and nothing else, and qmk didn't seem to have detected the reset.

I've tried setting "Board" to "Arduino Micro" and "Arduino Pro or Pro Mini". I'm on Arch Linux and no matter which USB port is plugged in, the IDE only shows `/dev/ttyS0`). I tried uploading the "Blink" example, as well as "Burn Bootloader", but only got `programmer is not responding` like so:

```
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         Using Port                    : /dev/ttyS0
         Using Programmer              : arduino
         Overriding Baud Rate          : 19200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

avrdude done.  Thank you.

```

title: Pro Micro board not responding to anything

Answers: 1

body:
It turns out I had to use the port `ttyACM0` (and not `ttyS0`) which wasn't found at the time. The port was there the next day and I have no idea why it wasn't there before.

Also, I thought I had to press and hold `RST` for a couple of seconds to reset the Pro Micro, but I actually have to press it twice in a row.

I've managed to flash the firmware for my keyboard by double-pressing `RST`.


body:
I'm JSON deserializing output from ESP8266 in  my Arduino UNO, but when it fails (for some reason every time after it deserializes successfully) the program lags for few seconds and I don't want that to happen (at least not for a long time)

```
#include "SevSeg.h"
#include <ArduinoJson.h>
SevSeg sevseg;

StaticJsonDocument<500> response;

String data;

void setup(){
  Serial.begin(74880);
  Serial.setTimeout(10000);
  while (!Serial) {
     // wait for serial port to connect. Needed for native USB port only
  }
  byte numDigits = 4;
  byte digitPins[] = {2, 3, 4, 5};
  byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
  bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
  byte hardwareConfig = COMMON_ANODE; // See README.md for options
  bool updateWithDelays = false; // Default 'false' is Recommended
  bool leadingZeros = false; // Use 'true' if you'd like to keep the leading zeros
  bool disableDecPoint = false; // Use 'true' if your decimal point doesn't exist or isn't connected. Then, you only need to specify 7 segmentPins[]

  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments,
  updateWithDelays, leadingZeros, disableDecPoint);
  Serial.println("running");

}

void loop(){

       if (Serial.available()) {
            Serial.write(Serial.read());
            const auto deser_err = deserializeJson(response, Serial);

            if (!deser_err) {

                if(response["type"] == "num"){
                  sevseg.setNumber(response["data"],response["dot"]);
                }else{
                  sevseg.setChars(response["data"]);
                }
                String data = response["data"];
                Serial.println(data);

            }else{
              Serial.print(F("Failed to deserialize, reason: \""));
              Serial.print(deser_err.c_str());
              Serial.println('"');
            }

      }

  sevseg.refreshDisplay();

}
```
The response
```
running  //runs everytime I turn on the arduino
21:43:03.797 -> {null
21:43:03.797 -> :null
21:43:03.797 -> ,null
21:43:03.797 -> :null
21:43:03.797 -> ,null
21:43:03.797 -> :Failed to deserialize, reason: "InvalidInput" // for some reason I have to send request 2 times because for the first time it always fails
21:43:03.797 ->
Uove //correct data received
21:43:04.772 -> // this timestamp isn't right it is like 5 seconds after correct data
Failed to deserialize, reason: "EmptyInput"
```
What can I do for this not to happen for the first time or in a shorter duration?

I'd be really thankful for any answer.

title: How to set maximal execution time of operation

Answers: 0


body:
I am testing my BTS7960 Module with my UNO for bi-directional rotation of DC Motor. I am using a small DC motor as a test (like the one [here][1]) and I am powering the UNO via USB cable. The problem is whenever I try to shift it to take power from my MB102 supply instead of USB connector, the DC motor starts shuddering and stalling. But it runs completely fine when connected via USB cable.
I think there is something wrong with my connections but I can't figure out where.

The code is fairly straightforward and is attached below

    void setup() {  // put your setup code here, to run once:

    Serial.begin(9600);
      pinMode(2,OUTPUT); //R_EN
      pinMode(3,OUTPUT); //L_EN
      pinMode(8,OUTPUT); //L_PWM
      pinMode(12,OUTPUT); // R_PWM
      digitalWrite(3,HIGH);
      digitalWrite(2,HIGH);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      digitalWrite(12,HIGH);
      delay(5000);
      digitalWrite(12,LOW);
      delay(1000);
      digitalWrite(8,HIGH);
      delay(5000);
      digitalWrite(8,LOW);
      delay(1000);
    }
I am trying to find a good circuit simulator for the schematics for better visualization, if anyone has any leads it would be really appreciated

The connections are as follows:

DC 12V is provided to BTS7960. The R_EN and L_EN are connected to pins 2 and 3 of the Arduino. the R_PWM and L_PWM are connected to digital pins 8 and 12 of the Arduino. VCC and Ground are connected to +5 and GND pins respectively while another GND pin is connected to the DC12V negative.

When connecting MB102, DC12 is supplied via the Jack while the +5V and GND Headers are used to supply power to Arduino via Vin and GND Pin of Arduino respectively.

  [1]: https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQN0slDbIrUc3YH8YWSL4lsIdlmZjjPbscVJj9AMC1ZUry3rWXxFfS723rjRl-qWREUFrI&usqp=CAU

title: DC Motor Shuddering

Answers: 0