text:
HG-C 1100 measurement sensor
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:
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?

I can't make much sense out the question as written except that the display doesn't show what you expected. The the sensor display seems to have modes for Standard, Inverted, and Offset.  If it doesn't have anything to do with that, and actually has something to do with the Arduino, maybe clarify the question somewhat.

But when I add the arduino code and see in the serial monitor, the values aren't as like the top of the sensor. if the first sensor is -17.5, it is taking as -17.78. if the second sensor is -21.5, it is taking as -21.12.
I have to know why there is a difference.
But the metal I place between the sensor gives me the proper output.
Have you got my point?                                                                                The serial monitor and the top of the sensor value is different.

"Have you got my point?"  No, I haven't.  Nor do I know what to ask you.  Maybe someone else will.  Failing that, you'll have to figure out how to clarify the question until someone understands it well enough.

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


text:
LED Blink in assembly with timer1 output compare interrupt not working
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

I am not set up to test your code right now, perhaps later.  But:
    ; 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.

OPS, Yup that Was it although I read the datasheet and saw that it was 100 don't know how it ended up as 111. anyway as a suggestion for an environment I use avrdude and avra assembler on linux mint terminal with the arduino uno

and the main frequency in my country is around 60 HZ and the LED clearly didn't blink on that frequency it was fast but not that fast at all. How is that? is there an explanation for the altered frequency?

Well, the frequency of what appears on T1 is being effectively divided by what you're doing with your ISR/TCNT1/OCRA1A; one cycle on T1 is not one execution of sbi PINB, LED_PIN, and each toggling corresponds to just the high or just the low period of the LED cycle.  Then, you might also have high frequency components being seen at T1.  If you wanted to experiment with that, the thing to do would be to feed a solid 60Hz into T1 to eliminate the unknown components there.   By the way, your ISR should probably be preserving r16.

source: Stack Exchange

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

sort: votes


text:
How can I use attached interrupt on my project?
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.

So... change the RX and TX of the fingerprint sensor to some other pins...?

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 is modeled after the regular attachInterrupt function, so it should be familiar looking to you.  It's in the library manager; you don't need to get it from github.
NOTE: The O.P. opened a another question 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.

Thank you sir for the help.

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


text:
How to name the temperature sensors instead of printing address using ds2482-100 and ds18b20 sensor- Help
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.

`*
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");
   }

   }

You've almost done it - but you can't compare one array to another as you would compare two ints. Instead you have to compare them byte by byte and test that both byte[0]s match, both byte[1]s match, ..., etc until you reach the end of the arrays. Some languages support comparing or doing arithmetic and array transformations on an entire array with a single statement. C++ doesn't support that.

Like JRobert said, it's not a feature of the language.  It is, however, available to you in a couple of ways on the ESP8266.  The C library (and therefore C++) has memcmp(), which will compare sequences of bytes.  The ESP8266 also comes with a fairly complete C++ standard library, including std::equal, which can be used to compare arrays of anything that supports ==.

Thanks a lot for the reply, I am trying it with 2 sensors,since I am new to this programming I am unable to write it correctly, and moreover I want to use it for 10 or more than 10 temperature sensors in that case is it possible to use memcmp(). Thank you


text:
Writing file from SD card to ethernet client stops sending after about 2980 characters, STM32f7 board
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.

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


text:
Is there a way to make the RESET pin work in the inverse?
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.

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.

simulate this circuit – Schematic created using CircuitLab
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.

Thanks for sharing this. I will give this a go and update how I get on

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.

Since there is already a 10K pullup resistor on the reset pin you will want the pulldown to be considerably smaller than that. Probably in the order of 100Ω. That will cause considerable power wastage...

Thanks so much for sharing this! I’ve Bus true this out, hope we, it doesn’t seem to want to work. I have both cables with the alligator clips hooked up to 5V (am I right to do this or does the second clip need to go elsewhere?) It’s worth mentioning in doing this on a veroboard and haven’t yet snipped the kegs off the resistor. Interestingly enough, when the leg hooked up to ground touches one of the alligator cables, the board resets. Also, I was using a 10k before I saw the second comment. I have a 220 one around. Would that work? And could that perhaps be the issue?


text:
Connecting LEDs and push buttons 12 feet away from Arduino UNO
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.

I am planning to use a 10 pin IDC connector and IDC ribbon cable for the same.
THe LEDs' current is about 2 mA each (white LEDs)
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.
I have put a capacitor of 10 nF across the switch to address denounce.
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!

This might work.  I would occasionally expect there will be "unexpected" events.  If this is for security or safety defiantly consider an alternative.  If this is for fun, go for it.  If it works as expected great.  If not try something else.

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.


text:
does EEPROM reset itself when a new code is uploaded?
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?

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.

and in Tools menu don't set "Erase flash" to "All flash content"


text:
I2C pull up resistors and an I2C MUX
I have a rig with 5 light sensors on an I2C mux 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.

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 on each bus that it's providing:

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

Beyond that, the ambient light sensor breakout seems to provide its own 4.7K pull-ups. AVR-based Arduinos (and probably others) also enable their own, admittedly weak, pull-ups in the guts of the wire library.
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 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.  But, really I think what you have is probably fine.

but do i have too many pull up resistors? i thought i am supposed to only have 1 set? should i remove the ones on the lux sensors then?

I've converted the bulk of my previous (now deleted) comment, addressing yours, into an addition on the answer.

Try replacing some of the bulk 1.0uF caps with something in the 10 - 100 nF range to add high frequency bypassing.


text:
Arduino on/off PWM
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?
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);
}

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


text:
Getting all data of my JSON object from Serial.read() at once
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.

There is no such thing as "a whole string" in serial. There is only single bytes. It is your job to decide (and program it so it understands) what a string is.

Then how can I watch for example for line break?

WHy do yoiu ithink you need to? And if you want to get serial data into a variable and then use that serial data for some other thing, just use whatever you stored in your variable. Once you read from serial it's gone from serial forever. But you saved it in data, so just use it from there?

What about Serial.readStringUntil() and read to e. g. \n?

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, 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:
#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:

Thanks much, this sounds like the thing I need.

If this ends up being the route you take, and doing so doesn't invalidate any other answers (that may appear between now and then), you might consider changing the question title slightly to "Getting all data of my JSON object from Serial.read() at once" to improve findability and matching between question and answer.

It definitely looks like a great way to do it, but I can't seem to make it work, when I change the data variable to Serial.read() like this DeserializationError error = deserializeJson(response, Serial.read());  I get  Error compiling for board arduino UNO

It may be a while, but I'll reread your comment above and see if I can't provide a minimal example.  The ArduinoJSON documentation is quite good though, so I expect there will be one there as well.

@krystof18, please have a look at How to do serial communication between two boards?

@krystof18, with regard to the specific line given above, it's expecting a reference to a Stream, which Serial is.  By calling .read() there you're trying to pass a single character (or indication of the lack of a character; -1) into the deserializeJson function.

@BenoitBlanchon, do you mind if I draw your comment up into the answer body?

@timemage, I don't mind; please do.


text:
Serial.println won't format DEC
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);
  }

}

you write into the EEPROM the received character, not a number. you print a number.

I do not understand what you are expecting your program to do.  Computers (usually) communicate using ASCII.  You read 1 value from another computer.  That's likely ASCII.  You store this into the EEPROM.  Then you print  that from the EEPROM back to another computer.  And you see what you initially typed in.  Sounds normal.  Wait, was your assignment to read ASCII, convert that into a number to store into the EEPROM then read that number out and print it?  If so, you are missing steps.  Sounds like you need to go back and 1st understand what the problem is trying to teach you.

The problem is that I write an integer into the EEPROM but it prints out ASCII even with the "DEC" argument. However, when I switch the "DEC" to BIN or OCT, it prints out Binary and Octal values respectively. But when I use "DEC" it only gives me the ASCII rather than the exact DEC value of the integer that I put in. Am I missing something?

What do you mean 'the integer I put in'? How are you putting in an integer over serial, which works on ASCII characters?

rewrite your code to print integers from 0 to 20 ... what do you see?

Please [edit] your question and show us what you get and what you expect. This means some example of input and output. And why you think it works for other bases.

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.

Serial.read() returns a character, which is always represented as ASCII code number. the return type of read is int to be able to return -1 if nothing is read.

@Joshua: this answer makes no sense; read and try to understand the comments.


text:
External Interrupts, Mega2560
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.

Please, do not post a screenshot of your code, post the code itself. It's way easier to copy-paste (which is useful for testing).

What do you mean with "persistent error"? Please be more specific

Yea sorry, what I mean is the measurement seems to be off by a fixed amount. Whether the sensor is 10cm or 50cm away from an object, there's some error quantity that is fixed. the shorter the distance, the larger a proportion the error is. Longer distance gives smalled error.

How large of an error?


text:
Arduino Uno R3 stops executing code, when trying to instantiate multiple HX711 objects
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):
Changelog:

Code is now embedded in the question.

If the code is important to the question, it should be brought into the question.  That said, it's already better than most first-questions here.

comment out lines 118-121 ... see if it crashes in a different place

@jsotola Interestingly enough it still crashes at the same line, which is unexpected. I figured it would crash after Sensor 3 now, basically shifting the problem back.

try changing all four set_scale to -63

maybe something is wrong with sensor 3 ... move the four lines of sensor3 code to before the sensor1 code

@jsotola changing the calibration values did nothing, but I tried a few permutations of initializing the sensors.
1 - 2 - 4 - 3: 1, 2, 4 init 3 not showing
3 - 1- 2 - 4: No init output at all
4 - 2 - 1 - 3: 4, 2, 1 init 3 not showing
I think you may be right about the 3rd sensor, but this begs the question: Why is it behaving itself in the test code and just acting up in the project code itself? I will need to investigate this weird behaviour.

I wonder if you are not running out of stack / heap RAM.  You might try a Arduino platform with a processor which has more (RAM) memory (before pulling all your hair out).  Do you need to measure weight fast?  You may want to try to only construct 2 instances of the scale measurement class at a time.  Construct 2, measure 2, destroy them the repeat connecting to the other 2 sensors.   Then start all over again.  Every class instantiation uses the same program code.  But you use up a block of RAM to hold data from each instantiation.  Welcome to C++ programming.

Why is it behaving itself in the test code and just acting up in the project code itself?
...so, what is the difference between the "test code" and the "project code"?

After some digging I found that the offensive line is SENSOR3.tare();. The Arduino won't get past that one.
The app is expecting the data as close to real-time as possible and we already have some latency thanks to the Bluetooth connection.  I was also suspecting a memory shortage, but if those memory test codes floating around every Arduino forum are somewhat accurate, I should be in the clear.

swap sensor 1 and sensor 3 pin definitions

Now sensor 3 is working and 1 is acting up, again stuck at the tare() call. Sounds like you are thinking about a hardware problem?

now swap only either the DATA or SCK pins ... sounds like A4 or A5 is being interfered with ... maybe one of the libraries uses it ....... or try just reversing the pins for sensor 3

A4 & A5 are the same pins as SCL/SDA on the Uno R3. The RTC and sensor are hooked up directly to the same pins.

You guys are geniuses, I would have never figured that out!
Sensor 3 is now using A5 and 4 instead is working perfectly.
Thank you so much for your time and help!

Maybe a bit late, but I notice you use a DHT11 (humidity and temperature sensor) library, initialize a DHT11 sensor on pin 8 but never read or use the sensor in your code. I think it's better to remove it from the code.

You'll need to use a library that support multiple HX711's. The HX711-multi 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.

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.

I don't know why someone voted this down, I was about to suggest the same thing. In particular saveSettings which instantiates a File object may use a lot of RAM. You don't have a lot in reserve.


text:
Using ICSP pins as SPI in Arduino Due
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?

on Due there is no ICSP programming. those pins are only for SPI

The Due's SPI is odd, to say the least. From what I recall, it doesn't have multiple SPI ports. Instead it uses multiple hardware SS pins to look like multiple ports in hardware. Just stick to one channel with multiple slaves. The Due is just a mess. It's no wonder it got retired in short order...

@Majenko, Due is not retired

@Juraj They resurrected it?! Morons! The Due is the second worst Arduino of all time, only beaten by the Intel Galileo abortion.


text:
How to get current WiFi signal strength?
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?

You use WiFi.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


text:
Atmega328p with arduino without the board
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.

Does that 328P have the optiboot bootloader, like an Uno?

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


text:
Pro Micro board not responding to anything
I just got a couple of Arduino Pro Micros for a custom keyboard build. Before testing them with the Arduino IDE, I tried to test them with qmk 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.

If RESET is connected to GND then the Arduino is going to do nothing. Nothing at all. Nada. It'll be like it's not even there. ttyS0 is the internal UART of your PC (it may not even have a connector...).

activate the bootloader with a double reset. Micro is not Mini. for "burn bootloader" you need a programmer hardware

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.

the sketch handles the usb, without working sketch there is no USB and the bootloader must be activated to handle USB


text:
How to set maximal execution time of operation
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.

so, the program does something different when it deserializes successfuly and you want to know why it does something different?

Yes that too, I have a lot of questions about this weird behaviour

What exactly are you sending over serial? The first character will be echoed back over Serial. It does not get used by the deseriallzation. That might be a problem depending on what you are sending.

Do you know, what the timeout of the deserialization from serial is? That timeout is propably what takes so long.

I don't know and i couldn't find it either, but I've noticed that the lower Serial.setTimeout the shorter the duration of waiting, but when u set it too low, it doesn't want to deserialize anything (the current 10s is minimum for it to work correctly)

I think you shouldn't deserialize directly from Serial. Instead send the json data with a newline character at the end, read the data into a buffer, until you read the newline character. Then do the deserialization on that buffer. Currently you are clearly butchering the json string. You still didn't write, what exactly you are sending via serial. Please include that information in your question

remove the big timeout. add while (Serial.read() != -1); after deserializeJson to read out the newline characters which cause to enter the deserialization without data. and remove Serial.write(Serial.read());


text:
DC Motor Shuddering
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) 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.

That's a lot of motor controller for a wee motor! It's unclear what the schematic looks like when you're running off the breadboard power supply, though, or why you'd need both a breadboard power supply and the power off the motor controller module.

Arduino Vin requires at least 7V to be powered properly, not 5V. It actually accept voltage from 7V to 12V, so connect the DC12V directly to the Arduino Vin which will be used internally to drive the regulator to generate the 5V.

@DaveNewton Like i said its only a test motor. I plan on using it to power 20A DC Motors for my carrier robot. The motor controller module requires 5V. i was initially giving it via the +5V Arduino pin but now am providing it through the breadboard supply

@hcheung Thanks a ton! That worked like a charm, the only problem is running 2 drivers simultaneously case the 2nd motor to be extremely slow. I guess it's because the DC 12V adapter gives 1.5 A current only which is insufficient for the second motor right?


text:
Where is all of the Arduino Documentation?
Aside from the main website, I have noticed that it is hard to find documentation for specific Arduino add-ons, such as (This is just one example):
https://www.amazon.com/gp/product/B00OGYXN8C/ref=ppx_yo_dt_b_asin_title_o04_s01?ie=UTF8&psc=1#descriptionAndDetails
Is this fairly normal or are you just expected to "just know what to do" with every Arduino component after a while? I realize that the IDE does have samples, but they don't always help.

You search for tutorials, libraries and their documentation, etc. For example, for this, I searched for "HiLetgo 1602 LCD Keypad Shield 1602 LCD Expansion Shield arduino" (although "1602 LCD Keypad Shield Arduino" would be sufficient) and found multiple tutorials and examples. The "main website" has documentation for Arduino products, not random products from other companies. It's precisely the same for RPi, although with fewer standardized boards/peripheral chipsets.

It's pretty normal, since 90% are churned out by factories in China, and documentation is very much a luxury. Go to a reputable supplier (Adafruit, etc) for good quality and good support.

@Majenko Is this question really opinion based? I was at maybe 5/6th of writing an answer, that gives more context about the documentation topic (which is the OP is clearly lacking). I would say this is worth an answer. The OP asks how one is expected to navigate in the Arduino community. While surely having room for opinion, the question targets the broad consensus and how finding information works in the Arduino community. Voting to reopen.

@chrisl i'd say it's more of a rant than a question.

The OP is clearly frustrated, but that doesn't make it a rant. An answer might help here. I can understand the frustration from having lacking documentation. The reasons for such a lack are also important to know. And I think we are seeing (and answering) questions on this site, that are way worse that this. I'm totally willing to answer this question (though I might do so tomorrow and not now. It's time for bed here)

It turns rant-y on "I'm taking my RPi and going home" (even though the situation is roughly equivalent delta more Arduino clone HW). It turns opinion-y because there's no answer to "where is all the Arduino documentation", which is (again roughly) unanswerable. I'm not opposed to an expository response, but it's not "answerable" in the traditional sense--on main this would be closed for identical reasons; I don't know how the Arduino SE rolls yet.

@chrisl if enough people think it's worth reopening (by voting for it) then who am I to argue?

@DaveNewton I just edited out the main rant part. We'll see what the community makes of it...

Where is all of the Arduino Documentation?

Arduino
So far as I know, the Arduino name is owned by the Italian company Arduino AG.
Arduino AG provide documentation on the website arduino.cc for the products they manufacture.
Arduino AG have no responsibilities for documenting products designed and manufactured by other businesses.
Other businesses
There are many other businesses that design and, in some cases, manufacture products that are designed to be compatible with or to work with products manufactured by Arduino AG. They don't need permission from Arduino AG unless they are using the trademarks or other intellectual property of Arduino AG. In addition, Arduino AG make many designs available under a permissive licence that does not give Arduino AG any control over or responsibility for documentation of cloned or derivative products manufactured or marketed by other businesses.
Examples include Adafruit, Sparkfun and many others.
These businesses provide documentation for the products they manufacture.
Some other businesses might choose to manufacture products without providing documentation or without providing documentation in English. For example a small Chinese manufacturer might only provide documentation in Chinese or provide none at all, expecting users to make use of documentation provided by the community or by the designer whose open-source designs they are using or whose proprietary designs their product is functionally equivalent to.
Open Source Designers
Many hobbyists and small-scale makers provide documentation for use of their designs for products.

I'd like to add to what JRobert said of finding the information the "hard way"(i.e. looking into the datasheet of the chip it used, and understand how it works from schematic).
In the Arduino world, a lot of hardware/shields are so called Open Source Hardware, meaning that many companies can produce the same hardware with the schematic that is released under Open Source hardware license. China happened to be the country where it has the complete value-chain from components, to manufacturing and cheap labour. They are good in producing such products at large quantity and selling at low price, and they are not necessary good in developing original product, and certainly not in documentation (especially in English). These products are not necessary China "knock-off" as many people call it.
Since it is open hardware products, there are multiple vendors producing it and there are many information available on the internet, and take the example you provide, it is "1602 LCD Keypad Shield", and if your google it with this phase, you will soon find this pdf which is not exactly from the same company of your shield, but it is remarkably similar that you can try.
This applied to many hardware/shields that are available in the market. I hope this provide a general guidance and an "easy way" to find the information in your tinkering journey. Of course, if you want to learn more, go dig out the datasheet and schematic as JRobert mentioned.

To be fair, you're really talking about non-Arduino (capital-A) parts from a multitude of suppliers. And yes, the documentation varies in its depth, quality of translation if it wasn't originally written in English, and even availability at all. Taking the part you linked (from a retailer that storefronts for sellers (sometimes not in this country), who sell from component builders (often not in this country, who build with of parts from supplied factories definitely not in this country, ..., you get the idea. There may or may not exist any documentation specifically for this LCD/keypad combination shield.
But just by reading Amazon's seller's part description, I found that it consists of (at least) a 1602 LCD module and an HD44780 LCD controller chip, for both of which I can quickly find and download datasheets. The sixth image to the left of the description is a schematic of the board which shows that the left, right, up, down, and select buttons are 'multiplexed onto an output called AD0. I might have confirm that that is - or isn't - the Arduino's Analog-0 pin, but in any case, now I know what I have to write to decode which button was pressed from the board's analog output.
All this, and the part costs under US$7.00. For that price (and an assumption that these shields aren't being made in huge quantities), a maker couldn't possibly be able to create a custom datasheet for the shield as a whole, but they did supply a schematic, and their board's components are identified, and those components do, in fact have datasheets online.
Slightly awkward, perhaps, especially if one is thinking in terms of parts like MCUs such as the Atmega328 family, that are made in huge enough quantities that its datasheet runs to nearly 700 pages of engineering-ese. Still, the information is there and accessible, without requiring a way lot of digging.
That's part of being an experimenter.

With this particular board, you're quite fortunate in finding a supplier with an actual website and description: HiLetGo LCD1602 Input/Output expansion board LCD Keypad Shield for Arduino. The fact that the photos of the HiLetGo site show the DFRobot logo — the company that hcheung already referred to — shows just how radically open Open Hardware can get! In this case, DFRobot has pretty decent documentation: LCD KeyPad Shield For Arduino: SKU DFR0009 - DFRobot — but even they don't link to the official LiquidCrystal documentation, but a much older archived version.
The Arduino team admits that they “… never entirely got to grips with Arduino documentation”. Their own "Find in Reference" tool in the IDE will sometimes dead-end to error pages on the arduino.cc site. For example, "find in reference" for Serial will take you to a local copy of the documentation that has broken links for the Arduino Leonardo documentation.
It's not always the case, but typically if an Arduino shield costs less than $10 on Amazon then the cost of "just know[ing] what to do" is passed on to you, the user.


text:
Using OR with a while loop
I am trying to get two limits to or on the same while statement. Can this be done?
while (digitalRead (home_limit)) {

This works for one(1) limit,
But when I try using two(2) limits  is does not work. I can't find the proper configuration. I tried this.
while (digitalRead (home_limit1) || (home_limit2)) {

I also tried other combinations with no luck.
Does anyone know how to do an or (||) statement with a while digital read?

Firstly, when posting code select it and press ctrl+k to formatt it properly.
Try putting digitalRead in for both conditions and also specify what digitalRead value it should be

In while(digitalRead(home_limit1) || home_limit2), the program will not evaluate home_limit2 as long as digitalRead(home_limit1) return 1, is that what you want? do you really means while(digitalRead(home_limit1) && home_limit2)? If this is not what you want, you will need to edit your post to explain in plain English of what you want first.

I have a slide with two limits on it. One at each end of the slide. I'm doing experiments with this slide. At one time during programming I want home_limit1 to operate as a home switch for the CW direction. In a different program I want the slide to run in the opposite direction, CCW and now home_limit2 will now act as a home switch. I just wanted to know if I could or 2 digital reads together as shown above. while(digitalRead(home_limit1) || home_limit2). This way I could change the logic below the statement and make the motor run to the counterclockwise Direction and trip home_limit2.

digitalRead() is a function. It takes one parameter (the pin number) and returns the state of that pin.  It's that return value that you want to OR with another. Which means you have to read the state of both pins, separately, and OR the results together:
while (digitalRead(home_limit1) || digitalRead(home_limit2)) {
    ....
}

Thank you, would it be possible to show me that code?Not sure how to use the return values of both to OR them in the program.

@BillPatton You mean aside from the example I've already given you?

Yes please. How would I go about accomplishing this in your estimation.

@BillPatton by using the code example that I already provided!

@BillPatton: Majenko's line of code in this answer is all you need. digitalRead(home_limit1) returns the state of this pin: a zero or a one. Likewise digitalRead(home_limit2) returns the state of that pin: a zero or a one. The while loop will be executed until both digitalReads return a zero.

Ok I see. I'll give that a try thank you very much.


text:
Reading a flash ROM chip (M45PE20) through SPI with an ATMEGA 2560 -- output only FF's
I'm trying to communicate through SPI to a Flash ROM chip (M45PE20) with an ATMEGA 2560. I'm looking to read the data off the chip, but the output I'm getting is nothing but FF's. I've checked my wiring and everything looks okay on that end, I also don't have a scope to probe the output unfortunately.
I've the crude code below:
void setup() {
  Serial.begin(9600);
  pinMode(SS, OUTPUT);
  digitalWrite(SS, HIGH);
  SPI.begin();
}

void loop() {
  Serial.println("Starting");
  Serial.println("Waiting 1s");
  delay(1000);
  SPI.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE0));

  digitalWrite(SS, LOW);
  Serial.println(SPI.transfer(0x03));
  Serial.println(SPI.transfer(0x00));
  Serial.println(SPI.transfer(0x00));
  Serial.println(SPI.transfer(0x00));
  for (int i = 0; i < 16384; i++) {
    Serial.print(i * 32, HEX);
    Serial.print(" ");
    for (int j = 0; j < 32; j++) {
      Serial.print(SPI.transfer(0xFF), HEX);
      Serial.print(" ");
    }
    Serial.println();
  }

  Serial.println();
  digitalWrite(SS, HIGH);
  delay(500);
  SPI.endTransaction();
  delay(5000);
}

Link to datasheet: https://drive.google.com/file/d/1_Zlg-hb5B08u7_m_N4_addmmjyv_nANS/view?usp=sharing
Picture of specific read command from datasheet:

Can you provide a wiring diagram? Also, a blank/new chip will be full of 0xFF.

I will update my post tomorrow evening, this is part of a game cartridge so the wiring is going to be a bit weird looking.
I can also confirm that the chip is filled with random data, and not full of 0xFF.


text:
Send Multiple Sensors Data into single Packet in Arduino
I have two sensors data in packet but now I want to send these two sensors data into single packet in which these two sensors data are gathered. I mean I want to have a packet in which I have oxygen, heart rate and pedometer values.  Can anyone suggest me how to do it. Code for both sensors are given below. I have already try a lot of ways but all in vain. I will be very thankful for your suggestion and time.
For Sensor 1
#include <Wire.h>
#include "MAX30105.h"
#include "spo2_algorithm.h"

MAX30105 particleSensor;

#define MAX_BRIGHTNESS 255

#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
//Arduino Uno doesn't have enough SRAM to store 100 samples of IR led data and red led data in 32-bit format
//To solve this problem, 16-bit MSB of the sampled data will be truncated. Samples become 16-bit data.
uint16_t irBuffer[100]; //infrared LED sensor data
uint16_t redBuffer[100];  //red LED sensor data
#else
uint32_t irBuffer[100]; //infrared LED sensor data
uint32_t redBuffer[100];  //red LED sensor data
#endif

int32_t bufferLength; //data length
int32_t spo2; //SPO2 value
int8_t validSPO2; //indicator to show if the SPO2 calculation is valid
int32_t heartRate; //heart rate value
int8_t validHeartRate; //indicator to show if the heart rate calculation is valid
uint16_t checkSum = 0;

byte pulseLED = 11; //Must be on PWM pin
byte readLED = 13; //Blinks with each data read

byte ledBrightness = 60; //Options: 0=Off to 255=50mA
byte sampleAverage = 4; //Options: 1, 2, 4, 8, 16, 32
byte ledMode = 2; //Options: 1 = Red only, 2 = Red + IR, 3 = Red + IR + Green
byte sampleRate = 100; //Options: 50, 100, 200, 400, 800, 1000, 1600, 3200
int pulseWidth = 411; //Options: 69, 118, 215, 411
int adcRange = 4096; //Options: 2048, 4096, 8192, 16384

void setup()
{

}

void loop()
{
  Serial.begin(9600);
  wait_for_Max30102();
  start_signal();
  if (!particleSensor.begin(Wire, I2C_SPEED_FAST)) //Use default I2C port, 400kHz speed
  {
    Serial.println(F("MAX30105 was not found. Please check wiring/power."));
    while (1);
  }

  Serial.println(F("Attach sensor to finger with rubber band. Press any key to start conversion"));
  //while (Serial.available() == 0) ; //wait until user presses a key
  Serial.read();

  particleSensor.setup(ledBrightness, sampleAverage, ledMode, sampleRate, pulseWidth, adcRange); //Configure sensor with these settings
  bufferLength = 100; //buffer length of 100 stores 4 seconds of samples running at 25sps

  //read the first 100 samples, and determine the signal range
  for (byte i = 0 ; i < bufferLength ; i++)
  {
    while (particleSensor.available() == false) //do we have new data?
      particleSensor.check(); //Check the sensor for new data

    redBuffer[i] = particleSensor.getRed();
    irBuffer[i] = particleSensor.getIR();
    particleSensor.nextSample(); //We're finished with this sample so move to next sample

    /*Serial.print(F("red="));
    Serial.print("\t");
    Serial.print(redBuffer[i], BIN);
    Serial.print("\t");
    Serial.print(redBuffer[i], DEC);
    Serial.print("\n");
    Serial.print(F(", ir="));
    Serial.print("\t");
    Serial.println(irBuffer[i], BIN);
    Serial.print("\t");
    Serial.print(irBuffer[i], DEC);
    Serial.print("\n");*/
  }

  //calculate heart rate and SpO2 after first 100 samples (first 4 seconds of samples)
  maxim_heart_rate_and_oxygen_saturation(irBuffer, bufferLength, redBuffer, &spo2, &validSPO2, &heartRate, &validHeartRate);

  //Continuously taking samples from MAX30102.  Heart rate and SpO2 are calculated every 1 second
  while (1)
  {
    //dumping the first 25 sets of samples in the memory and shift the last 75 sets of samples to the top
    for (byte i = 25; i < 100; i++)
    {
      redBuffer[i - 25] = redBuffer[i];
      irBuffer[i - 25] = irBuffer[i];
    }

    //take 25 sets of samples before calculating the heart rate.
    for (byte i = 75; i < 100; i++)
    {
      while (particleSensor.available() == false) //do we have new data?
        particleSensor.check(); //Check the sensor for new data

      digitalWrite(readLED, !digitalRead(readLED)); //Blink onboard LED with every data read

      redBuffer[i] = particleSensor.getRed();
      irBuffer[i] = particleSensor.getIR();
      particleSensor.nextSample(); //We're finished with this sample so move to next sample

      checkSum = redBuffer[i] + irBuffer[i] + heartRate + validHeartRate + spo2 + validSPO2;

      //send samples and calculation result to terminal program through UART
      Serial.print(F("RED: "));
      Serial.print("\t");
      Serial.print(redBuffer[i], BIN);
      Serial.print("\t");
      Serial.print(redBuffer[i], DEC);
      Serial.println("");

      Serial.print(F("IR: "));
      Serial.print("\t");
      Serial.print(irBuffer[i], BIN);
      Serial.print("\t");
      Serial.print(irBuffer[i], DEC);
      Serial.println("");

      Serial.print(F("HR: "));
      Serial.print("\t");
      Serial.print(heartRate, BIN);
      Serial.print("\t");
      Serial.print("\t");
      Serial.print(heartRate, DEC);
      //Serial.println("\t");
      //Serial.print("(HRvalid = ");
      //Serial.print("\t");
      //Serial.print(validHeartRate, BIN);
      //Serial.print("\t");
      //Serial.print(validHeartRate, DEC);
      //Serial.print((" )"));
      Serial.println("");

      Serial.print(F("SPO2: "));
      Serial.print("\t");
      Serial.print(spo2, BIN);
      Serial.print("\t");
      Serial.print("\t");
      Serial.print(spo2, DEC);
      //Serial.println("\t");
      //Serial.print("(SPO2Valid = ");
      //Serial.println(validSPO2, BIN);
      //Serial.print("\t");
      //Serial.println(validSPO2, DEC);
      //Serial.print(" )");
      Serial.print("\n");
      Serial.println("");

      Serial.print(F("Checksum Byte: "));
      Serial.print("\t");
      Serial.print(checkSum, BIN);
      Serial.print("\t");
      if((byte)checkSum == (byte)(redBuffer[i] + irBuffer[i] + heartRate + validHeartRate + spo2 + validSPO2)){Serial.print("(CHECKSUM_OK)");}
      else {Serial.print("(CHECKSUM_ERROR)");}
      Serial.println("\n");
      Serial.println("\n");
      Serial.println("");
      Serial.println("");
      Serial.println("");
      delay(1000);
    }

    //After gathering 25 new samples recalculate HR and SP02
    maxim_heart_rate_and_oxygen_saturation(irBuffer, bufferLength, redBuffer, &spo2, &validSPO2, &heartRate, &validHeartRate);

  }
  Serial.end();
}

void wait_for_Max30102()
{
delay(2000);
}

void start_signal(){
pinMode(readLED, OUTPUT);
pinMode(pulseLED, OUTPUT);
digitalWrite(pulseLED, LOW);
digitalWrite(readLED, LOW);
delay(18);
digitalWrite(pulseLED, HIGH);
digitalWrite(readLED, HIGH);
pinMode(pulseLED, INPUT);
pinMode(readLED, INPUT);
digitalWrite(pulseLED, HIGH);
digitalWrite(readLED, HIGH);
}

For Sensor 2:
#include <Wire.h>

#define DEVICE (0x53)    //ADXL345 device address
#define TO_READ (6)        //num of bytes we are going to read each time (two bytes for each axis)

#define offsetX   -10.5       // OFFSET values
#define offsetY   -2.5
#define offsetZ   -4.5

#define gainX     257.5        // GAIN factors
#define gainY     254.5
#define gainZ     248.5

byte buff[TO_READ] ;    //6 bytes buffer for saving data read from the device
char str[512];                      //string buffer to transform data before sending it to the serial port

int x,y,z, X;

int xavg, yavg,zavg, steps=0, flag=0;
int xval[15]={0}, yval[15]={0}, zval[15]={0};
int threshhold = 60.0;

uint16_t checkSum = 0;

void setup(){}

void loop()
{
for(unsigned int x = 0; x < 5; x++)
{ clv(); }
Serial.end();
}

void start_signal(){
  writeTo(DEVICE, 0x2D, 0);
  writeTo(DEVICE, 0x2D, 16);
  writeTo(DEVICE, 0x2D, 8);
}

void clv(){
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(9600);  // start serial for output
  start_signal();
  //Turning on the ADXL345

  int regAddress = 0x32;    //first axis-acceleration-data register on the ADXL345

  readFrom(DEVICE, regAddress, TO_READ, buff); //read the acceleration data from the ADXL345

   //each axis reading comes in 10 bit resolution, ie 2 bytes.  Least Significat Byte first!!
   //thus we are converting both bytes in to one int
  x = (((int)buff[1]) << 8) | buff[0];
  y = (((int)buff[3])<< 8) | buff[2];
  z = (((int)buff[5]) << 8) | buff[4];

//we send the x y z values as a string to the serial port
 //sprintf(str, "%d %d %d", x, y, z);
 //Serial.print(str);
 //Serial.print(10, byte());

  Serial.print("X = ");
  Serial.println(x);
  Serial.print("Y = ");
  Serial.println(y);
  Serial.print("Z = ");
  Serial.println(z);

 //write steps
  X = ArduinoPedometerSteps();
  Serial.print("steps = ");
  Serial.println(X);
  Serial.println(" ");

  //It appears that delay is needed in order not to clog the port
  Serial.print(F("X: "));
  Serial.print("\t");
  Serial.print(x, BIN);
  Serial.print("\t");
  Serial.print(x, DEC);
  Serial.print("\n");

  Serial.print(F("Y: "));
  Serial.print("\t");
  Serial.print(y, BIN);
  Serial.print("\t");
  Serial.print(y, DEC);
  Serial.print("\n");

  Serial.print(F("Z: "));
  Serial.print("\t");
  Serial.print(z, BIN);
  Serial.print("\t");
  Serial.print(z, DEC);
  Serial.print("\n");
  Serial.print(F("steps: "));
 Serial.print("\t");
 Serial.print(X, BIN);
 Serial.print("\t");
 Serial.print(X, DEC);
 Serial.println("\n");

checkSum = x + y + z + X;

 Serial.print(F("Checksum Byte: "));
 Serial.print("\t");
 Serial.print(checkSum, BIN);
 Serial.print("\t");
 if((byte)checkSum == (byte)(x + y + z + X)){Serial.print("(CHECKSUM_OK)");}
 else {Serial.print("(CHECKSUM_ERROR)");}
 Serial.println("\n");
 Serial.println("\n");
 Serial.println("");
 Serial.println("");
 Serial.println("");
 delay(150);
}

//---------------- Functions
//Writes val to address register on device
void writeTo(int device, byte address, byte val) {
   Wire.beginTransmission(device); //start transmission to device
   Wire.write(address);        // send register address
   Wire.write(val);        // send value to write
   Wire.endTransmission(); //end transmission
}

//reads num bytes starting from address register on device in to buff array
void readFrom(int device, byte address, int num, byte buff[]) {
  Wire.beginTransmission(device); //start transmission to device
  Wire.write(address);        //sends address to read from
  Wire.endTransmission(); //end transmission

  Wire.beginTransmission(device); //start transmission to device
  Wire.requestFrom(device, num);    // request 6 bytes from device

  int i = 0;
  while(Wire.available())    //device may send less than requested (abnormal)
  {
    buff[i] = Wire.read(); // receive a byte
    i++;
  }
  Wire.endTransmission(); //end transmission
}

//Get pedometer.

int ArduinoPedometerSteps(){
    int acc=0;
    int totvect[15]={0};
    int totave[15]={0};
    int xaccl[15]={0};
    int yaccl[15]={0};
    int zaccl[15]={0};
    for (int i=0;i<15;i++)
    {
      xaccl[i]= x;
      delay(1);
      yaccl[i]= y;
      delay(1);
      zaccl[i]= z;
      delay(1);
      totvect[i] = sqrt(((xaccl[i]-xavg)* (xaccl[i]-xavg))+ ((yaccl[i] - yavg)*(yaccl[i] - yavg)) + ((zval[i] - zavg)*(zval[i] - zavg)));
      totave[i] = (totvect[i] + totvect[i-1]) / 2 ;
      //Serial.print("Total Average = ");
      //Serial.println(totave[i] );

      //delay(50);

      //cal steps
      if (totave[i]>threshhold && flag==0)
      {
         steps=steps+1;
         flag=1;
      }
      else if (totave[i] > threshhold && flag==1)
      {
          //do nothing
      }
      if (totave[i] <threshhold  && flag==1)
      {
        flag=0;
      }
     // Serial.print("steps=");
     // Serial.println(steps);
     return(steps);
    }
  delay(100);
 }

Are you trying to combine two programs together, or do you have a single program that already contains all the sensor code and you're trying to work out how to "send" that data? Send it to what, over what medium?

What do you mean by “packet”? You seem to be sending over Serial, and there is no such thing as a “packet” over Serial: you can only send a stream of bytes.

@EdgarBonet In a previous question the OP asked how to send packets of binary data over serial. I gave an answer explaining a general concept with start byte, message length and data bytes as protocol imposed on the serial stream. Though I cannot see that implemented in the codes above.

@chrisl after your instructions i followed this site: https://www.engineersgarage.com/microcontroller-projects/articles-arduino-dht11-humidity-temperature-sensor-interfacing/ . i found that they are sending start bit then adding data and at the end checksum bytes are added. But i think so i cannot implement it in really good way. I am really new on arduino. can you please guide me by seeing the code given above?

@EdgarBonet can you please guide me how to convert this stream of bytes into packet?

this is Q&A site. for guidance please use a forum