message:
I2C Devices Interference

I am currently trying to connect 3 I2C Devices to an Arduino Mega, as detailed in the fritzing sketch. The Sensors are: Max86150 PPG Sensor on a breakout board (5v), MLX90614 IR Temperature Sensor (3.3V) and a SM9336 Pressure Sensor(3.3V). Essentially I can connect all devices and read off the sensors using individual sketches, but when I combine the sketches the values are not consistent and then the sketch crashes after only a few seconds.

Weirdly enough, when I combine a sketch with either the Temperature sensor and the Pressure sensor or the Temperature Sensor and PPG Sensor, it will work. But Pressure and PPG do not work together.

Does anyone have any idea what could be happening? I did have it working for a small while with some different wires, could this have anything to do with it? But even still some results I was reading from the sensor were the error values (e.g. the value you get when there is nothing connected, but it wasn't crashing). For reference I am using 30 AWG wires and strip board instead of the breadboard in the Fritzing. [![Fritzing Sketch][1]][1]

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

    //PPG
    #include "max86150.h"
    MAX86150 max86150Sensor;
    uint16_t ppgunsigned16;
    uint16_t irdata;

    // Pressure Sensor
    #include <Wire.h>

    #define PressureSensor_Data 0x30 // Pressure Register address
    #define TemperatureSensor_Data 0x2E // Pressure Temp Sensor Address

    int P0,T0,P1,T1;
    int SMD993Address = 0x6C; // Device Address

    //Timing
    #define INTERVAL 10 //10 milliseconds per sample for 100 Hz, change this for different sampling rates.
    uint32_t lastMicros = 0;

    // Temp
    #include <Adafruit_MLX90614.h>
    Adafruit_MLX90614 mlx = Adafruit_MLX90614();

    void ppgsetup()
    {
      max86150Sensor.setup();
    }

    void PPG() {

    while (1){
     if(max86150Sensor.check()>0)
        {
            ppgunsigned16 = (uint16_t) (max86150Sensor.getFIFORed()>>2);

            Serial.println(ppgunsigned16);
      //ppgunsigned16 = (uint16_t) (max86150Sensor.getFIFORed()>>2);
      //Serial.println(ppgunsigned16);

      if (ppgunsigned16 > 7000){

         for (int z = 0; z <= 500; z++){//This takes a reading every 10 milliseconds for 5000 milli seconds which is 5 seconds, 500 readings
           digitalWrite(ledPin,HIGH);//turning LED on
            //if (micros() - lastMicros > INTERVAL) { //This takes a reading every 100th of a second
                //lastMicros = micros(); // do this first or your interval is too long!

                if(max86150Sensor.check()>0)
        {
            ppgunsigned16 = (uint16_t) (max86150Sensor.getFIFORed()>>2);
            irdata = (uint16_t) (max86150Sensor.getFIFOIR()>>2);

            Serial.print(ppgunsigned16);
            Serial.print(",");
            Serial.println(irdata);
                //Serial.print("Check PPG");Serial.println(y);
                //mySerial.write(84);mySerial.print(ppgunsigned16);mySerial.print("/");
                //mySerial.write(83);mySerial.print(irdata);mySerial.print("/");
        }
        }
        digitalWrite(ledPin,LOW);//turning LED off
        break;

    }
    }
    }
    }

    void spirometry() {

        for (int x = 0; x <= 500; x++){
        Wire.beginTransmission(SMD993Address);
        Wire.write(PressureSensor_Data);
        Wire.write(TemperatureSensor_Data);
        Wire.endTransmission();
        Wire.requestFrom(SMD993Address,2);//This takes a reading every 100 milliseconds for 10000 milli seconds which is 10 seconds

        //if (micros() - lastMicros > INTERVAL) { //This takes a reading every 1000th of a second
          //lastMicros = micros(); // do this first or your interval is too long!

        if(Wire.available()<= 2) {
        P0 = Wire.read();
        P1 = Wire.read();
          }

        int Ptotal = P0 + (P1<<8); //The high byte is transmitted second so that

        Serial.println(Ptotal); // Print Ptotal to the serial monitor
        //mySerial.write(81);mySerial.print(Ptotal);mySerial.print("/");// Send PTotal over BLE with flag 81, this will change as sending via bytes is more efficient

        }

      }

    void temperature() {
      for (int y = 0; y <= 10; y++){
          mlx.begin();
          Serial.println(mlx.readObjectTempC());
          mySerial.write(82);mySerial.print(mlx.readObjectTempC());mySerial.print("/");
          delay(10);
    }
    }

    void setup() {

      // BT
      mySerial.begin(9600);
      Serial.begin(9600);//Sets BT Serial Comms to 115200, ensure that BT is allowing for this
      //LED
      pinMode(ledPin, OUTPUT);
      // PPG
        // Initialize sensor
        if (max86150Sensor.begin(Wire, I2C_SPEED_FAST) == false)
        {
            Serial.println("MAX86150 was not found. Please check wiring/power. ");
            while (1);
        }
        Serial.println(max86150Sensor.readPartID());
        ppgsetup();

      //Pressure Sensor

      //Temp

      //Sleep
      sleep();

    }

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

       PPG();
       delay(10000);
       spirometry();
       delay(1000);
       temperature();

    }

body: I had a similar problem sometime ago, where I attached 2 servo driver boards and a battery hat (that used I2C for reading power levels) to a Raspberry Pi. The battery board worked alone and the servo boards worked alone, but when all three were present, the battery board stopped working. And all had unique addresses. After a few hours of going nuts, I realised that there were pullup resistors on the pi and all three boards attached. The total resistance of all 4 parallel pullup resistors were out of spec for I2C. I removed the resistors from the servo boards and everything started working together. So maybe you could disable the pullups on all baords except the Arduino and see if that is the problem.


sender: user

sender: assistant

body:
As pointed out by @peterpaulkeifer; Here

```
// Initialize sensor
    if (max86150Sensor.begin(Wire, I2C_SPEED_FAST) == false)
    {
        Serial.println("MAX86150 was not found. Please check wiring/power. ");
        while (1);
    }
```

I was setting the I2C Speed of the I2C Interface bus to fast and it seems that the pressure sensor was not able to handle this and would therefore give error answers and then crash.


message:
RTClib now() within while loop does not update

I ran into this while trying to make a battery monitor and wondered where I went wrong. Using `RTClib` available in the Arduino IDE or from [adafruit github][1], I ran into problems when trying to call `now` within a `while` loop inside of `loop`.  Here is a simple example:

    #include "RTClib.h"

    #define ledPIN 13

    RTC_PCF8523 rtc;

    void setup() {
      // put your setup code here, to run once:
      pinMode(ledPIN, OUTPUT);
      digitalWrite(ledPIN, LOW);
      Serial.begin(9600);
      while(!Serial) {/* wait for Serial */}
      rtc.begin();
      rtc.start();
      digitalWrite(ledPIN, HIGH);
     }

    void loop() {
      // put your main code here, to run repeatedly:
      char fmt[] = "YYYY/MM/DD-hh:mm:ss\n";
      while (millis() < 60000){
        Serial.println((rtc.now()).toString(fmt));
        delay(5000);
      }
      Serial.println("Finished");
      digitalWrite(ledPIN, LOW);
      while(1) { /* do nothing forever */ }
    }

 The output of this little test will be the same time repeated every 5ish seconds.  If it matters I am using a Feather M0 with the FeatherLogger that has an RTC on it.  Changing this `loop` function to this:

    void loop() {
      // put your main code here, to run repeatedly:
      char fmt[] = "YYYY/MM/DD-hh:mm:ss\n";
      if (millis() < 60000){
        Serial.println((rtc.now()).toString(fmt));
        delay(5000);
      } else {
        Serial.println("Finished");
        digitalWrite(ledPIN, LOW);
        while(1) { /* do nothing forever */ }
      }
    }

shows that `now` does in fact update the time every 5ish seconds.  I looked at the code for `now` and it appears to do very basic i2c commands to get the time and report it back.  The only thing I can think of is that the compiler created a (not so) temporary `DateTime` object for me within the `while` loop and the RTC library does not provide a convenient constructor or operator to overwrite the existing object.

I tested my theory with this

    void loop() {
      // put your main code here, to run repeatedly:
      char fmt[] = "YYYY/MM/DD-hh:mm:ss\n";
      while (millis() < 60000){
        DateTime t1 = rtc.now();
        Serial.println(t1.toString(fmt));
        delay(5000);
      }
      Serial.println("Finished");
      digitalWrite(ledPIN, LOW);
      while(1) { /* do nothing forever */ }
    }

But again, the time did not change so clearly I don't understand what's happening here.  Why doesn't the rtc `now` function work as intended within a `while` loop inside the `loop` function?

  [1]: https://github.com/adafruit/RTClib

body:
See the [documentation of `DateTime::toString()`][toString]:

> The _buffer_ parameter should be initialized by the caller with a
> string specifying the requested format. This format string may contain
> any of the following specifiers: [...] The specifiers within _buffer_
> will be overwritten with the appropriate values from the `DateTime`.
> Any characters not belonging to one of the above specifiers are left
> as-is.

The important thing to realize is that the `buffer` parameter is used
**both** as input (for the format description) and as output (for the
formatted date and time). You initialize it with a format description
(`"YYYY/MM/DD-hh:mm:ss\n"`). Then, after the first call to `toString()`,
the same buffer contains the formatted date and time. It does **not**
contain the format description anymore. On the second call to
`toString()`, as per the rule “_Any characters not belonging to one of
the above specifiers are left as-is_”, the buffer is not modified.

**Solution**: Put the buffer initialization within the same `while` loop
as the call to `toString()`.

[toString]: https://adafruit.github.io/RTClib/html/class_date_time.html#a3753bf2ae254315a56f7ee38ff0b188b


message:
changing bitrate of audio recording and taking samples from audio in arduino

I am looking to make a baby cry detection module that is a part of a bigger project i.e. IOT based baby monitoring system. Using AI, i have a dataset (of baby crying and not crying) to train model using binary classification through logistic regression. The problem is that the dataset has a 10kbps sample rate. and arduino records audio on 192kbps probably. so i need the arduino recorded audio to be 10kbps. secondly i need 100 weights or samples from the arduino recorded audio. so lets say the audio is of 5 seconds, so i need a sample after every 50ms so that the total samples would be 100. the main problem is i don't know how to take samples from an audio being recorded or a prerecorded audio using arduino. The 100 samples would then be multiplied by the 100 samples from the trained model and then added and then sigmoid function will be used so that at the end we can know whether the baby is crying or not. All the deployment of the model will be done in arduino. Any help regarding taking the samples or bitrate, would be much appreciated. Thanks in advance! :)

body:
First of all, I am pretty sure your idea of using discrete ADC samples
as predictors for your model is hopelessly naive. As explained by
Majenko, you cannot expect anything meaningful from a sound recording
taken at 20 samples per second. You may have more luck using
spectral intensities as predictors. I suggest you start by doing some
time–frequency analysis on your training data, just to get some ideas on
what predictors may be worth trying. In any case, I strongly suggest you
train **and test** your model on your computer, before committing any
code to the Arduino.

That being said, sampling a signal at 20 Hz is quite easy: wait for
50 ms (or 50,000 µs for better accuracy), take one sample,
repeat. The only caveat is that you have to use `millis()` or `micros()`
rather than `delay()` or `delayMicroseconds()`, otherwise the sampling
period will be longer than expected because of the time needed to
execute the code.

Applying the sigmoid function just to compare the result to 0.5 makes
little sense. You know the sigmoid is larger than 0.5 only when its
argument is positive, so you can trivially save yourself expensive
floating point operations.

Here is a tentative implementation of (my understanding of) the idea you
suggest:

```c++
const uint8_t mic_pin = A0;
const size_t sample_count = 100;
const uint32_t sample_period = 50000;  // 50,000 us = 50 ms
const int weights[sample_count] = { 12, -42, 23 /* etc... */};

void setup() {
    Serial.begin(9600);
}

void loop() {
    // Record the samples.
    int samples[sample_count];
    uint32_t last_sample = micros();
    for (size_t i = 0; i < sample_count; i++) {
        while (micros() - last_sample < sample_period) { /* wait */ }
        samples[i] = analogRead(mic_pin);
        last_sample += sample_period;
    }

    // Compute the weighted sum.
    long sum = 0;
    for (size_t i = 0; i < sample_count; i++) {
        sum += (long) samples[i] * weights[i];
    }

    // Predict.
    if (sum >= 0) {
        Serial.println("The baby is crying!");
    }
}
```


message:
Arduino send commands fast

I need cnc machine to run as smooth as possible.

It receives commands like this "M_XY 10.233 20.123".

If i send command by command there is a slight delay between commands and its noticeable.
I set serial timeout to 5 ms.

I tried to send n commands and store them on arduino, but arduino cant store much in ram. There is a huge delay while sending n commands.

I was thinking about converting letters (machine writes letters) to bezier and sending arc by arc or letter by letter in arcs. Can atmega328p interpolate bezier fast enough?

Would it be faster if i send numbers in bytes instead of strings?
That would be 4 bytes per float and merge with union on arduino.

Is there any better way of doing this i don't know of?

Edit:
This is how string commands are processed.

    void addCommByte(const byte b){
      if(commID == MAX_COMM+1){
        commID = 0;
        Serial.println("TOO LONG COMMAND");
        Serial.flush();
        return;
      }

      if(b == '\n'){
        comm[commID] = '\n';
        commID = 0;

        processCommand();
      }
      else if(b == '\r')
      {
        commID = 0;
      }
      else
      {
        comm[commID++] = b;
      }
    }

    void loop() {
      Serial.flush();
      while(Serial.available() > 0) {
        addCommByte(Serial.read());
      }
    }

Edit. Way better way.

C# side. Check for endianness in c#. Arduino is little endian.

            public void MOV_X(float mm)
                {
                    SendCharAsByte("q"[0]);
                    SendFloatAsBytes(mm);
                }
            public void SendFloatAsBytes(float f)
            {
                byte[] vOut = BitConverter.GetBytes(f);
                serialPort.Write(vOut, 0, 4);
            }

            public void SendShortAsBytes(short f)
            {
                byte[] vOut = BitConverter.GetBytes(f);
                serialPort.Write(vOut, 0, 2);
            }

            public void SendCharAsByte(char c)
            {
                byte[] aaa = new byte[1];
                aaa[0] = (byte)c;
                serialPort.Write(aaa, 0, 1);
            }

Arduino side.

    void loop() {
      while(Serial.available() > 0) {
        processV2(Serial.read());
      }
    }
    // from processV2
    if(byt == 'q'){   // mov x
        float mm = readFloat();
        if(X_DIR == 1) mm *= -1.0;

        stepperXY.moveXForMMSync(mm);
        Serial.println("p");
        return;
      }
    // merge bytes
    union u_tag {
       byte b[4];
       float fval;
    } u;

    float readFloat(){
      Serial.readBytes(u.b, 4);
      return u.fval;
    }

There is no need to flush serial.

body: If you have an existing CNC, you may have to abide by its comm protocol.  Otherwise, if the Arduino is part of a CNC you are building, and it is supposed to accept commands from a host computer, the first thing to do is make sure your baud rate is set higher than the default.  I have found 115200 to be a good choice for stability.  Next, you should avoid sending TTY-type text strings, and send binary values instead. You'd send an initial byte or word to specify the command type, followed by the data.  In my open-source DaqPort sketch for high-speed data acquisition <https://www.daqarta.com/dw_rraa.htm> I use the high nybble of the command to specify the general type, and the low nybble to specify more detail like channel number.  The sketch uses a big loop with if(Serial.available() > 0) to read the first byte, and a switch/case to determine what to do.  The the specific command reads the proper number of bytes and does whatever.  This is *way* faster than having to parse text and convert to binary.


message:
Reading bits from a const char pointer

I'm getting a bit tripped up on const char pointers lately.

I'm getting a message from a server that comes through as either a c style string, a standard library string, or a WString:

[![return types][1]][1]

[![underlying types][2]][2]

I'm sending down a buffer of 32bit values from my server that aren't ascii or utf text, they're just bit values I want to parse and read on the esp32 side:

[![example data from the server][3]][3]

I thought "oh, I'll just mask the bit values 32 bits at a time and right shift the data to get the message (in reverse order, but still I can work with that). The problem that I'm running into is that I can shift numbers but not strings or byte arrays.

I wrote out a function to allow me to grab a piece of the string 32 bits at a time and convert that into a number while using an offset:

```
uint_fast32_t get32BitInt(const char *data, int offset = 0)
{

  uint32_t payload = 0;
  for (uint8_t i = 0; i < 8; i++)
  {
    payload <<= 0;
    payload += data[i + offset];
  }
  return payload;
}
```

But when I try to grab the first couple of 32 bit chunks the data isn't what I expected:

```
void handleGameFrame(const char *data, uint32_t length)
{

  uint8_t phaseAndColission = get32BitInt(data, 32);
  uint8_t player = getByte(data, 32 * 2);

  Serial.print("data: ");
  Serial.println(data);
  Serial.print("phaseAndColission: ");
  Serial.println(phaseAndColission, DEC);
  Serial.print("player: ");
  Serial.println(player, DEC);

}
```

yields:

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

I know the `Serial.println(data);` isn't going to output anything b/c it's a c-string of non-printable values, but the other chunk grabbing isn't giving me the same output from my server. It's hard to verify everything without being able to see all of the bits in the overall `data` pointer and I think I tied myself in (another) knot.

Is there a good way to parse 32 bit values out of a const c-string?

  [1]: https://i.stack.imgur.com/yaBmn.png
  [2]: https://i.stack.imgur.com/n0iXM.png
  [3]: https://i.stack.imgur.com/kKuDh.png
  [4]: https://i.stack.imgur.com/2vy86.png

body:
You wrote:
> I wrote out a function to allow me to grab a piece of the string 32
> bits at a time and convert that into a number while using an offset

This function is almost correct. Try this:

```c++
uint_fast32_t get32BitInt(const char *data, int offset = 0)
{

  uint32_t payload = 0;
  for (uint8_t i = 0; i < 4; i++)
  {
    payload <<= 8;
    payload |= data[i + offset];
  }
  return payload;
}
```

Compared to your version, the differences are:

* It reads 4 bytes instead of 8, as 32 bits are four bytes.

* For each byte being read, it shifts the payload by 8 bits (i.e. one
  byte) instead of zero. Shifting by zero has no effect.

* It uses `|=` instead of `+=`: just a micro-optimization for the sake
  of 8-bit MCUs. It shouldn't make much if a difference on a 32-bit
  micro.


message:
Sense person connected to TENS unit

So let's say I use a store-bought TENS unit for liability. I want to make a challenge where you need to hold on to the TENS unit for 10 seconds before it activates a solenoid. How can I have an Arduino detect if someone is touching some metal posts connected to the unit? Would I need to measure the current for the tens unit or something? Any ideas/suggestions? Thanks!

Edit- Not sure if this should be in Arduino or Electrical Engineering, feel free to move it.

body: I think the main problem here is that you want to measure in the presence of high voltage from the TENS. Not having experience with TENS circuits, I would suppose that their contact pins are connected to the high voltage source through resistors to limit the current. (Or some equivalent current-limiting scheme.)  If so, the voltage between the contacts should drop when there is a person connected. You should be able to detect that drop with the Arduino.  The "obvious" approach would be to use voltage dividers to reduce the no-load voltage to less than 5V so the Arduino ADCs can handle it. You'd need high-value resistors in the dividers so they don't load the TENS... maybe 1 Megohm or more for each divider.  One problem with this simplistic approach is that the TENS is putting out its stimulus using brief pulses, which may be too quick to catch with the ADCs.  To get around that, you'd feed the output of each divider through a diode to an R-C filter.  (Note that you need the diode anyway, since the TENS output is probably AC and the Arduino ADCS only want DC.)  This may take a fair amount of experimentation to get the values right, which you should do *without* the Arduino... just a DVM or scope that you can start at a high-voltage range until you sure you have everything worked out to 0-5V.


message:
Problem with my usb plug

First of all, we connected our usb plug to arduino board (starter kit). After that, we completed Project 1 successfully (circuit with led and switch.) We tried unplug the usb cable, but it was very difficult, we had to pull very hard, but we couldn't unplug it. Finally, I managed to take it away with the help of my partner. I was pulling the usb and my partner was keeping the arduino board stable. The result wasn't very nice, we probably broke the usb cable. You can see what I mean in these images, the metallic coating part of the cable is still stuck on the board.

https://ibb.co/6wtf02J

https://ibb.co/4pZg2w0

https://ibb.co/WPchtgN

https://ibb.co/gPHZYnt

Nevertheless, we put the remaining cable back where it was, and the board seems to be working normally.

My question is if it safe to use it. Is there any chance of electrical damage or something like that?

Thank you!

P.S. In addition, we are planning to buy a new arduino starter kit. How can we avoid this problem with the new board?

body:
Without the center part of the USB plug, it should be possible to make some deformations of that shield without damaging rest of the usb connector and pull it out. Aim for the weakest spot - seam (usually in the middle of bottom).

But even if you damage on board connector, it can be replaced (but it might be better to give it to someone with soldering experience - at least for unsoldering it)

And as noted in comments, even without working usb connector it can be programmed either by connecting USB-TTL serial converter to D0/D1 (but without auto-reset, unless you provide 100nF capacitor between reset and RTS), or it can be programmed by another Arduino as SPI (it needs bit more wires, and by default it doesn't burn bootloader, so if you fix USB, you'll have to burn bootloader).
Easier might be swapping Atmega328p between boards, however it needs some practice, so you won't bend or rip pins)


message:
Convert fuel level sender resistance ranges - good Arduino project?

I've noodled around with Arduino a bit, worked some tutorials.  I have an engineering & programming background, but electronics isn't my first language.  So apologies if this is a dumb question.

Here's the problem.  I've swapped a 2007 GM engine into an older Toyota Land Cruiser.  I need to make it compliant with the emissions equipment that was originally on the 2007 vehicle.  Most of that is pretty straight forward - catalytic converters, O2 sensors, charcoal canister, purge & vent solenoid valves, a pressure sensor.  The one bit I haven't figured out yet is fuel level.  The evaporative emissions system requires a fuel level input to the PCM (Powertrain Control Module) so it can figure out when & how to run the fuel system pressure test - the one that turns on your check engine light if your gas cap isn't on tight enough.

One solution would be to put in a GM fuel level sender ... but that involves draining the tank, dropping it, maybe cutting new holes, more wiring, etc.  I'm hoping I can fix this in software :)

The GM fuel level sending unit reads 0 ohms empty and 90 ohms full.  The existing Toyota sending unit should be 110 ohm empty and 3 ohm full.

So ... is it a feasible thing to build an Arduino based project that reads the resistance from the Toyota sender (without interfering with the Toyota gauge) and translates that to the range expected by the GM PCM?

I'm thinking something like this is the core of it: https://www.arduino.cc/en/Tutorial/LibraryExamples/DigitalPotControl  But I don't know what I don't know.

Thanks folks - additional information based on responses:

The Toyota sender is definitely a 12V two terminal unit.  Car electrical systems are nominally 12V, but typically are about 13.3V in operation.

The GM sensor is two terminal also.  According to the wiring diagram, one terminal goes to a low reference pin on the PCM and the other goes to a pin on the PCM labeled fuel level signal.

But it doesn't tell you the voltage they're applying on that pin - could be just 5V, other stuff coming out of the PCM is.  I couldn't find a test procedure either.  I'll pin that connector and see what I can measure next time I'm out there.

The fuel level signal is used for two things in the evaporative emissions (evap) system.

1. The evap vacuum test can only run when the tank is between approximately 1/3 to 2/3 full.
2. The vacuum test is calibrated against how full the tank is - lower fuel level means more air space in the tank means the pressure will change more slowly then compared to a fuller tank.

body:
The Toyota sensor may be using 12V instead of 5V, which would mean you'd need to use a voltage divider to get it down to the range that the Arduino analog inputs can read.

You will need to find a digital potentiometer that can handle the voltage range that the
GM controller wants to see.  This may be 0-12V, which would be a problem since the AD5206 is only good for 5V.

However, as dandavis implies with his RC filter comment, you may be able to simulate the full 0-12V range with PWM, where the Arduino pin drives a transistor to chop up the 12V, and an RC filter smooths the result for the GM control unit.  That's probably your best approach.

Alternatively, if the GM controller is only looking for a go/no-go level, you can use the
transistor to switch in a simple voltage divider to get the right voltage from 12V.

The sensors are (presumably) just variable resistors (2-terminal) not full 3-terminal potentioneters.  They will most likely be using a series resistor to make a voltage divider, and the control unit (or gage in the Toyota) will reading the resulting voltage. You will want to either find out the value of the series resistor or measure the voltage that the gage sees.  It might already be in the 0-5V range.  The GM control unit may have the series resistor built in (or be using a current source), in which case you should measure the voltage its sensor input sees when you give it the max and min resistance.  This will be good to know when you are trying to drive it with your own circuit,


message:
How to flash a NodeMCU (ESP8266) with an external FTDI programmer?

Hi my USB to UART bridge (CP2102) seems to be broken on one of my NodeMCU Dev Boards with ESP8266.

It seems to be just that specific board since all other boards that I have can be flashed without problems.
I have a FTDI Programmer like this one:
[FTDI Programmer][1]

Now I would like to flash the Nodemcu using the FTDI programmer but I'm not sure how to wire it up.
I know that those programmers cant power up the ESP8266 by itself thats why I would use a micro USB cable that doesnt have a data wire to power up the nodemcu.

This is how I would wire everything up:
[![enter image description here][2]][2]

  [1]: https://ae01.alicdn.com/kf/H20e215e2865f48678845010232b87464E/FT232RL-FTDI-USB-3-3-V-5-5-V-zu-TTL-Serielle-Adapter-Modul-f-r.jpg
  [2]: https://i.stack.imgur.com/LDazU.png

Is this the correct way to wire up the programmer with the nodemcu? I want to be sure that nothing is going to mess up with the nodemcu or the programmer.

NodeMCU       FTDI
GND    ---->  GND
RX     ---->  TX
TX     ---->  RX

body:
Assuming your FTDI Basic is the 3.3V version, then yeah that will work fine provided you that manually reset the board yourself and enter the boot-loader using the buttons.

If you're independently powering the boards you may want to insert some series resistance in the RX and TX connections in case your signal receiving end is not powered while the sending side is.  In short you don't want the TX signal from one of your devices (boards) trying to power the receiving device (board) through its protection/clamp diodes.

In regard to comment about resistor value:
The value of the resistor depends on what you can get away with in terms of its effect on the signal and how much current is allowed through the clamp diodes on the other board.  A couple of Kbyte is probably sufficient, better than nothing in any case. Use a bit more if you can and still get a reliable signal through.  If you have the boards both powered before you connect them and you're careful about connecting them, then there's no opportunity for that.  It may also just be that they're robust enough that you don't need them at all.  I usually put some in though.  The second reason which I didn't state above is just that it protects you from being outright stupid and accidentally connecting them to the wrong thing; wrong signal, or to VCC or GND on the other side.


message:
SIM A9G: +CME ERROR: 53 failure

I'm using a SIM A9G.  When I send HTTP GET command from the serial monitor, it responds. But, it doesn't work when included in the code.

```c++
#include <SoftwareSerial.h>
SoftwareSerial myserial(8, 7); // RX: 8, TX:7

void setup()
{
//  Wire.begin(I2C_SLAVE_ADDRESS);
  Serial.begin(19200);
  myserial.begin(19200);    // 9600, 19200, 38400, 57600, 74880, 115200

//  ET.begin(details(mydata), &Wire);
  Serial.println("JSON Initializing...");
  Serial.println("GPRS Starting..........");

//  myserial.listen();
  myserial.println("AT");
  delay(500);

  myserial.println("AT+CREG=?");     //Check Network regiistration, wait a while
  delay(1000);
  ShowSerialData();

  myserial.println("AT+CCID");  //Specify the connection type
  delay(1000);
  ShowSerialData();

  myserial.println("AT+CGATT=1");
  delay(2000);
  ShowSerialData();

  myserial.println("AT+CGDCONT=1,\"IP\",\"web.gprs.mtnnigeria.net\"");//Specify the APN
  delay(2000);
  ShowSerialData();

  delay(2000);
}

void loop()
{
  myserial.println("AT+CGATT=1");
  delay(2000);
  ShowSerialData();

  myserial.println("AT+CGACT=1,1");
  delay(2000);
  ShowSerialData();

  myserial.println("AT+HTTPGET=\"https://postman-echo.com/get?foo1=bar1&foo2=bar2\"");
  delay(5000);
  ShowSerialData();

  myserial.println("AT+CCLK?");
  delay(1000);
  ShowSerialData();

  delay(3000);
}

void ShowSerialData()
{
  while (myserial.available() != 0)
  {
    Serial.write(myserial.read());
    //delay(50);
  }
}
```

The output at the serial monitor is the following:
```None
+CGATT:1

OK
AT+CGACT=1,1

OK
E⸮⸮T⸮OZ⸮y:/⸮͵*⸮⸮⸮m/⸮⸮⸮⸮⸮=bar1&foo2=bar2"

+CME ERROR: 53
failure, pelase check your network or certificate!

AT+CCLK?

+CCLK: "21/02/22,18:19:43+01"

OK
```

body:
You must use this sequence.

AT+CREG=?
AT+CCID
AT+CGATT=1
AT+CGDCONT=1,"IP","ba.amx"
AT+CGACT=1,1


message:
Connect multiple Arduinos to ESP32's RTC?

> Depending on usage frequency, may get the occasional collision where
> both test for availability at the same time - if occurring too
> frequently, maybe add something simple like one arduino only does time
> updates on even seconds, the other on odd seconds.

https://forum.arduino.cc/index.php?topic=64049.0

I need events executed in the multiple receiving Arduino's to occur in sync (simultaneously). Is there a library or something, probably using the ESP32's RTC, to ensure events occur in sync?

Example system:
 - ESP32 sender/master
 - Arduino1 receiver controlling LEDs (Christmas lights)
 - Arduino2 receiver controlling stepper motors (Mary figure)
 - Arduino3 receiver controlling stepper motors (Joseph figure)

The issue is that they are sent data at different times by the user.

Say, the user selects settings for Mary. That data is sent to the ESP32, and then that data is sent to all the Arduinos, but only "gets into" the MaryArduino.

Then, the user selects settings for the lights. That data is sent to the ESP32, and then data is sent to all the Arduinos, but only "gets into the LightsAruino.

Etc.

However, I need everything to start at the same time.

The data is not simultaneously sent. It is sent one after the other, as slow as the user selects their settings. However, the sequence of events must simultaneously occur.

body:
Give the master a single signal wire that is connected to all of the slaves and that signal LOW while the master sends commands to each slave. Let each of the slave Arduinos simply store its message but not act on it while the signal wire is LOW.

When the slaves are supposed to start, raise the signal level to HIGH. Each slave Arduino now executes whatever command it had been sent. The RTC now only needs to be connected to the Master, which controls all of the timing.


message:
Input Capture Mode PPM signal

Greetings to all members of the Forum. I would like to express my deepest gratitude, with respect to the title of this post.
The last week I am trying to capture and decode a PPM Signal from an RC transmitter. Although I have seen many different approaches and codes online, using methods like Input Capture Mode and Pin Change Interrupts I would like to seek some help on my approach.
Most of the codes I have found online present glitches and instabilities while trying to read the time between the rising pulses.
I have tried to read and understand how to set up the Input Capture registers on the Atmega 32u4 chip, aka Arduino Pro Micro / Lepnardo, but I cannot find a proper way of defining the registers as well as the ISR (_vec) function.
In the next few lines I will try to explain the code I have written so far, but I will need some help with respect to the initialization of registers.
Please bare with me, as any help will be much appreciated. Without further ado, let me introduce you to the following lines.
```

#define STICK_CENTER 1500
#define STICK_HALFWAY 500
#define THRESHOLD 15

#define MIN_PULSE_WIDTH (STICK_CENTER - STICK_HALFWAY - 15)
#define MAX_PULSE_WIDTH (STICK_CENTER + STICK_HALFWAY + 15)

#define RC_CHANNELS_COUNT 8

#define PPM_CAPTURE_PIN 4
#define NEWFRAME_PULSE_WIDTH 2000
#define TIMER_COUNT_DIVIDER 2

void rc_setup_ppm() {
  setupPins();
  initTimer();
}

void setupPins(void) {
  // Set up the Input Capture pin
  pinMode(PPM_CAPTURE_PIN, INPUT);
  digitalWrite(PPM_CAPTURE_PIN, 1); // enable the pullup
}

void initTimer(void) {
  cli();

  TIFR = (1 << ICF1); //Clear any Interrupt flags
  PRR |= (0 << PRTIM1); //Enable Timer1
  TCCR1A = 0; //Clear TCCR1A
  TCCR1B = 0; //Clear TCCR1B
  TCCR1C = 0; //Clear TCCR1C
  TCCR1B = (1 << ICNC1) | (1 << ICES1) | (1 << WGM13) | (1 << WGM12) | (0 << CS12) | (1 << CS11) | (0 << CS10);
  TIMSK1 |= (1 << ICIE1); //Enable input capture
  TIFR1 = (1 << ICF1); //Clear interrupt flag

 sei();
}

uint16_t adjust(uint16_t diff, uint8_t chan) {

  return diff / TIMER_COUNT_DIVIDER;
}

ISR(TIMER1_CAPT_vect) {
  union twoBytes {
    uint16_t word;
    uint8_t  byte[2];
  } timeValue;

  uint16_t now, diff;
  static uint16_t last = 0;
  static uint8_t chan = 0;

  timeValue.byte[0] = ICR1L;    // grab captured timer value (low byte)
  timeValue.byte[1] = ICR1H;    // grab captured timer value (high byte)

  now = timeValue.word;
  diff = now - last;
  last = now;

  //all numbers are microseconds multiplied by TIMER_COUNT_DIVIDER (as prescaler is set to 1/8 of 16 MHz)
  if (diff > (NEWFRAME_PULSE_WIDTH * TIMER_COUNT_DIVIDER)) {
    chan = 0;  // new data frame detected, start again
  }
  else {
    if (diff > (MIN_PULSE_WIDTH * TIMER_COUNT_DIVIDER - THRESHOLD)
        && diff < (MAX_PULSE_WIDTH * TIMER_COUNT_DIVIDER + THRESHOLD)
        && chan < RC_CHANNELS_COUNT)
    {
      rc_values[chan] = adjust(diff, chan); //store detected value
    }
    chan++; //no value detected within expected range, move to next channel
  }
}
```
**Given the above I would like to help setting the initialization routine of the registers. Some information about my signal:**

 *PPM includes 8 different channels as a summed signal. In total 9 pulses while each one, has a time duration from 998 - 2012 microsecs.*

*The time frame of each pulse is easy to be changed though the transmitter settings. Also the total period of the frame can be changed. By the first I mean the HIGH time of each pulse, and by the second I mean the total frame period after the 8 channels have been scanned. Given these, the time periods are 26.5 mills and 350 microsecs.*

Enough with these. Going back to the actual code you will see the cli(); and sei(); functions. Do I really have to set these during that part of the code?
Also do I need to reset or delete any active flags? Should I include any flags (e.g. Overflow flag after the counter has reached its peack value)

At this point I would also like to mention that I am using a prescaler of 1/8, which results to a tick period of apx. 0.5 microsecs.
Also, I am capturing only the rising part of the pulses. And I am using an Input canceler, but given the datasheet specifications I have seen that the cancel frame is 4 periods long. Is there any possible way to use a low latency filtering scheme?

Please take some time to read this post, as I am confident enough that any responses will help others too clarify these topics.
I know that I have included many different aspects and I feel sorry for this.

Many thanks,
Koutsoukos Theodosios

body:
> Do I really have to set these during that part of the code?

No, you don't. I would, however, change the order of the last
initializations:

* Update `TIFR1` right before `TIMSK1` in order to avoid an interrupt to
  be triggered immediately.

* Set `TCCR1B` last in order for the timer to start only when it has
  been fully configured.

> Also do I need to reset or delete any active flags?

AFAIK the Arduino core does not use the Timer 1 interrupts. You can take
control of all the bits in the registers (e.g. `TIMSK1 = (1 << ICIE1);`)
instead of only some selected bits. It shouldn't make a difference
though.

> Should I include any flags (e.g. Overflow flag after the counter has
> reached its peak value)

Do not worry about overflows. The computation `diff = now - last` is
done modulo 216 and, owing to the rules of modular
arithmetics, gives the correct result even across an overflow.

> And I am using an Input canceler, but given the datasheet
> specifications I have seen that the cancel frame is 4 periods long.

This creates a delay of “four system clock cycles”, or 0.25 µs. Do
you really care about such a small latency? Please note that, since all
edges suffer the same latency, it doesn't affect the calculated
differences.

Now, if I may, a couple of comments about your code:

```c++
  pinMode(PPM_CAPTURE_PIN, INPUT);
  digitalWrite(PPM_CAPTURE_PIN, 1); // enable the pullup
```

This can be simplified an made more explicit:

```c++
  pinMode(PPM_CAPTURE_PIN, INPUT_PULLUP);
```

Then,

```c++
  union twoBytes {
    uint16_t word;
    uint8_t  byte[2];
  } timeValue;
  timeValue.byte[0] = ICR1L;    // grab captured timer value (low byte)
  timeValue.byte[1] = ICR1H;    // grab captured timer value (high byte)
  now = timeValue.word;
```

This used to be the way to read 16-bit registers a long time ago. Since
many years now, the C compiler knows how to do it, you just have to
issue:

```c++
  now = ICR1;
```


message:
Arduino MKR GMS alternative

I’m starting on a project about monitoring the soil in the agriculture field and also to visualise the data remotely. The aim of this project is collect the atmospheric data as well as the soil related parameters and then send them to cloud where they’ll be presented on the dashboard. I decide to use Arduino as my development board and Arduino MKR GMS 1400 would be perfect for this project. However this board is quite expensive. So just wondering that are there any alternative I can use for this project

Thank you

body:
There are multiple options for this project as you just want to send/ upload data on the cloud server rather than using Arduino MKR 1400 you can use any of the following.
1. Arduino UNO with GSM module: As per your requirement you can use Arduino UNO to read the data from the sensor and the GSM module will be used to upload the same on the cloud server. There are various GSM modules available in the market which are cheap also and good. You can also use [SIM800][1] one of the GSM module.

Other GSM modules which you could use can be,

[SIM900][2], [Quectel EC-20][3], [Quectel M95][4]. You can also visit [SIMCONN website][5] where you can find multiple GSM module options.

2. You can also use ESP8266 or ESP32 which are Wi-Fi modules but in this case you will require a internet/ Wi-Fi connection near the controller. ESP8266/ ESP32 will read data from the sensors and can also upload the same to the cloud servers. But as you said you are using them to monitor agriculture field it won't be possible to have a Wi-Fi which will cover such long range.

3. One of the possible solutions to the problem is to use RF-link to transmit data and collect it at a base-station and from the base station you can upload/ send them to the server.

4. You can also make use of the [LoRa][6] Network to communicate along the fields and then receive data from the whole field at a base station and then upload them to the server. But this could be a more expensive solution.

  [1]: https://simcom.ee/modules/gsm-gprs/sim800/
  [2]: https://simcom.ee/modules/gsm-gprs/sim900/
  [3]: https://www.quectel.com/product/ec20r21.htm
  [4]: https://www.quectel.com/product/m95.htm
  [5]: https://simcom.ee/?gsm-gprs
  [6]: https://www.semtech.com/lora/what-is-lora


message:
Collecting data from a timer interrupt and storing it into an array

My question is: how can I use an ISR and store the data I get from my analog inputs into an array for easier data analysis.

More specifically, I want to collect my data using an ISR function (internal timer interrupt), then store the collected data into an array. This way I can analyze the data more easily.

I have posted the code below. I have posted code showing how I implemented my ISR *without* storing the data into an array. I was wondering I anyone could help me out with this (how to store that data into an array). Thank you.

```c++
const int A0_pin = PC0;
const int A1_pin = PC1;

const uint16_t t1_load = 0;
const uint16_t t1_comp = 3173;

float count = 0;
float num = 0;

void setup() {

  //Set A0 and A1 pins as inputs
  DDRC &= ~(1 << A0_pin);
  DDRC &= ~(1 << A1_pin);

  //Reset Timer1 Control Reg A
  TCCR1A = 0;

  //Set CTC mode
  TCCR1B &= ~(1 << WGM13);
  TCCR1B |= (1 << WGM12);

  //Set to prescaler of 256
  TCCR1B |= (1 << CS12);
  TCCR1B &= ~(1 << CS11);
  TCCR1B &= ~(1 << CS10);

  //Reset Timer1 and set compare value
  TCNT1 = t1_load;
  OCR1A = t1_comp;

  //Enable Timer1 compare interrupt
  TIMSK1 = (1 << OCIE1A);

  //Enable global interrupt
  sei();

  Serial.begin(9600);
  Serial.println("CLEARDATA"); //clears up any data left from previous projects
  Serial.println("LABEL,TIME,TIMER,AVG,GAUGE0, GUAGE1"); //always write LABEL, so excel knows the next things will be the names of the columns
  Serial.println("RESETTIMER"); //resets timer to 0
}

void loop() {
}

ISR(TIMER1_COMPA_vect) {
  TCNT1 = t1_load;
  float Gauge0 = analogRead(A0_pin);
  float Gauge1 = analogRead(A1_pin); //44

  //conversion of read data, to voltage range (0-100 percentVolts)
  float gauge0 = Gauge0 * (100.0 / 1023.0);
  float gauge1 = Gauge1 * (100.0 / 1023.0);
  float add = gauge0 + gauge1;
  float AVG = ((gauge0 + gauge1) / 2);

  Serial.print("DATA,TIME,TIMER,");
  Serial.print(add);
  Serial.print(",");
  Serial.print(gauge0);
  Serial.print(",");
  Serial.println(gauge1);
}
```

In the code, I want to store the `gauge1` and the `gauge0` values into an array essentially.

body:
You can create two arrays, e.g.:

    #define MAX_LENGTH 20

    volatile float _gauge0[MAX_LENGTH];
    volatile float _gauge1[MAX_LENGTH];

    volatile int _filled = 0;

The _filled value shows that `_gauge0` is filled from 0 upto (excluding) `_filled`.

So when adding two values you use:

    _gauge0[_filled] = some value;
    _gauge1[_filled] = some_other_value;
    _filled++;

After processing, you reset `_filled` to 0 to refill both arrays again.

Because the Arduino has a limited amount of SRAM it's best to use a fixed array size (20 in this case). You have to make it `volatile` as it's used from within the ISR.

I'm not sure what you want to do with the data. If you want to gather like 20 (or a fixed amount of values), you can use the above.

If you need a continuous amount of memory and get the last x results, you can better use a so-called ring buffer (search for this, there are many articles about it).

Note that because of the limited amount of SRAM, it might be best not to store calculated values (like average and sum), unless you need the highest performance. This is a tradeoff which I cannot make as I don't know your requirements.

While processing, you use `noInterrupts()` before and `interrupts` after the processing of the data, otherwise interrupts will continue during processing. Make sure the handling of the processing takes as less time as possible as you might miss interrupts. Preferably only do the calculations and switch on interrupts before sending results via serial for example.


body:
Storing the data into arrays is not an end in itself. The question is:
what do you want to do with these arrays? The way to proceed depends on
that purpose.

If you want the data acquisition (`analogRead()`) and the processing
(computation and printing) to proceed _in parallel_, then you will need
the arrays for buffering the data between those two processes. As
mentioned by Michel Keijzers in his answer, you will have to research
the concept of [ring buffer][].

There is a ring buffer implementation in the Arduino core you can use as
inspiration: when reading data from the Serial port, the incoming bytes
are [received by an ISR][rx_complete] and stored in a ring buffer. [The
`Serial.read()` method][read] can then be used to retrieve these bytes
and process them outside the interrupt context.

Another option is to alternate between an acquisition phase and a
processing phase. This can be an interesting approach if the acquisition
rate is too fast for the processing to be performed in real time. In
this case, you do not need a ring buffer. Instead, you have the ISR fill
the arrays and, when they are full, the main program can take on and
start the processing. For coordinating these jobs, you just need a
boolean to keep track of whether you are performing the acquisition
phase or the processing phase. Note that, since accessing a boolean is
an atomic operation, you do not need to disable interrupts for this.

Here is an example implementation of this strategy. The variable
`sampling_done` is used to coordinate the two processes:

```c++
const size_t sample_count = 256;

volatile int gauge0[sample_count];
volatile int gauge1[sample_count];
volatile bool sampling_done = false;

ISR(TIMER1_COMPA_vect) {
    if (sampling_done) return;  // nothing to do

    static size_t sample_idx = 0;
    gauge0[sample_idx] = analogRead(A0);
    gauge1[sample_idx] = analogRead(A1);
    if (++sample_idx >= sample_count) {
        sample_idx = 0;  // prepare for next round
        sampling_done = true;
    }
}

void process_samples(int Gauge0, int Gauge1) {
    // Whatever needs to be done with the samples:
    // computation, printing...
}

void loop() {
    if (sampling_done) {
        for (size_t i = 0; i < sample_count; i++) {
            process_samples(gauge0[i], gauge1[i]);
        }
        sampling_done = false;  // start next sampling round
    }
}
```

Now some random remarks:

* There is no need to `sei()` in `setup()`: interrupts have already been
  enabled by the Arduino core initialization.

* Do not reset `TCNT1` within the ISR: this is handled automatically by
  the CTC mode. If you do this in software, you risk missing timer
  ticks.

* Do not store the readings in `float` variables: they take twice the
  memory of an `int` and all operations on floats are incredibly slow
  compared to the equivalent operations on ints.

* The scale factor for converting the readings to percent scale is
  `100.0/1024`: the maximum possible analog reading (1023) is one ADC
  step below the reference voltage: see the datasheet.

* You should remove unused variables as soon as they become unused
  (`count`, `num`, `AVG`). Once you do that you should notice you do not
  need floats at all.

[ring buffer]: https://en.wikipedia.org/wiki/Circular_buffer
[rx_complete]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/cores/arduino/HardwareSerial_private.h#L101-L121
[read]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/cores/arduino/HardwareSerial.cpp#L180-L190


body: My DaquinOscope <https://www.daqarta.com/dw_rroo.htm>  uses the open-source DaqPort sketch <https://www.daqarta.com/dw_rraa.htm> to sample in batches, then transfer the data to the host in one high-speed blast.  It takes 1024 total samples, which in your case of 2 channels would be 512 per channel. It stores only the raw data, unscaled... the host is the place for that. The host processes and displays the results in real time. Since this uses a UNO with only 2K RAM, tricky array storage was required to fit in 1024 samples.  In 8-bit mode this is just a 1024-byte array, but for 10-bit it uses a supplemental array of 256 bytes.  On each sample the low byte is stored in the 1024-byte array, and the upper 2 bits are shifted into a 4-sample byte of the 256-byte array.  Feel free to download and use Daqarta for this... no charge for Arduino use. You may want to do this just to work out other issues even if you plan to later use your own host software.  Or you can use Daqarta macros to do whatever you ultimately want.


message:
micros() resolution for Portenta H7

Is there any way to know the resolution of micros() for the Arduino Portenta H7. I have checked for other boards e.g. Nano which is mentioned as 4 uS. However, I couldn't find one for Portenta H7.

Is there any way to measure or look for that

body:
The **micros()** [language reference][1] states that, "[The micros() function] returns the number of microseconds since the Arduino board began running the current program. This number will overflow (go back to zero), after approximately 70 minutes. **On the boards from the Arduino Portenta family this function has a resolution of one microsecond on all cores.** On 16 MHz Arduino boards (e.g. Duemilanove and Nano), this function has a resolution of four microseconds (i.e. the value returned is always a multiple of four). On 8 MHz Arduino boards (e.g. the LilyPad), this function has a resolution of eight microseconds.

It seems likely that the doco was updated some time after the OP posted the question.

  [1]: https://www.arduino.cc/reference/en/language/functions/time/micros/


message:
Save highlighted text as int variable

I build a macro keyboard and one thing I do alot is add a set amount to numbers mostly in 3d modeling programs. I add and remove 0.25 and 0.125 all the time. I want to make a macro that copies selected text, adds or subtracts a value then pastes it back.

I known the simple copy and paste commands but how do I get my arduino program to grab that copied value?

Can this even be done?

body:
You have to write an application for your PC that

* reads a number from the clipboard
* adds some constant
* puts the result back in the clipboard
* quits

Then you have to configure you desktop environment in order to have this
application launched from a keyboard shortcut.

Once you have done that, you can do the whole operation from a regular
keyboard: Ctrl-C + Launcher shortcut + Ctrl-V.

If you can do it from a regular keyboard, you can do it from the Arduino
emulating a regular keyboard.

**Edit**: The way you do the first two steps is very dependent on the OS
running on your PC. On Linux, for example, the mentioned “application”
can be a minimal shell script:

```sh
#!/bin/bash

x=$(xclip -o -selection clipboard)
xclip -i -selection clipboard <<< $(bc <<< "$x + 0.25")
```

These steps are, however, outside the scope of this site.


message:
Simple ESP to ESP reading blink program not reading input voltage

One ESP32's 3v3 is connected to GPIO 26 of another ESP32.
The program is uploaded. The built-in LED lights for two seconds as expected. Then, it turns off. No matter what GPIO pin the 3v3 is connected to (besides 2), the LED remains off.

    /*
     * ON Board LED GPIO 2
     */

    #define LED 2
    #define inPin 26

    void setup()
    {
      Serial.begin(9600);
      // Pins 34, 35, 36, 39 are input only
      pinMode(LED, OUTPUT);

      // Sanity check LED works
      digitalWrite(LED, HIGH);
      delay(2000);
    }

    void loop()
    {
      Serial.println(digitalRead(inPin));
      digitalWrite(LED, digitalRead(inPin));
    }

Any reason this is happening? Grounds are connected. Simply trying to turn LED on/off if external voltage occurs at any GPIO pin (e.g., 26).

body:
Arduino GPIO automatically set as inputs, so I assumed the same for ESP32. Once the `pinMode` of the input pin was set, it worked:

    #define LED 2 // ON Board LED GPIO 2
    #define inPin 26

    void setup()
    {
      Serial.begin(9600);
      // Pins 34, 35, 36, 39 are input only
      pinMode(LED, OUTPUT);
      pinMode(inPin, INPUT); // <----------
    }

    void loop()
    {
      Serial.println(digitalRead(inPin));
      digitalWrite(LED, digitalRead(inPin));
    }


message:
Linking the Arduino Bootloader In Atmel Studio

I have been trying to get the Arduino bootloader to compile into my firmware binary in Atmel Studio. I got the bootloader project to link and compile. I use ArduinoCore and the bootloader as a dependencies to my main code. The dependency tree looks like:

 1. ArduinoCore
 2. bootloader
 3. Main firmware

**The Bootloader**

It took me a bit to get the bootloader to accept the rest of ArduinoCore as a dependency but it compiles into a static library. I use the bootloader linker to specify the memory location of the bootloader binary. It should start at 0x0 and provide a jump to the main firmware, located at 0x2000.

Bootloader linker flags:

    -Tbootloader_samd21x18.ld -Wl

And here are the contents of the linker script:

      FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 0x2000 /* First 8KB used by bootloader */
      RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00008000-0x0004 /* 4 bytes used by bootloader to keep data between resets */

This is based off of the .cProj file that comes with the linker. It is compiled as a static library so I can include it into my final binary.

**Main Firmware**

My code has both the ArduinoCore and the bootloader static libraries as dependencies:

    libm
    libArduinoCore
    libbootloader

And I am using these linker flags:

    -Tflash_with_bootloader.ld -Wl,--cref -Os -Wl,--check-sections -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align

The contents of this linker script are moved out by 8KB in order to accommodate the bootloader at the start of the binary:

     FLASH (rx) : ORIGIN = 0x00000000+0x2000, LENGTH = 0x00040000-0x2000  /* First 8KB used by bootloader */
        RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00008000

And yet, my entry point does not appear to ever hit the bootloader. It jumps straight to "main.cpp" from ArduinoCore. The firmware runs as expected, but the bootloader does not appear to have been included.

Is this some kind of dependency issue? Am I misusing the linkers?

Any help with getting this to compile under a single binary would be very much appreciated. Thank you very much!

body:
This isn't exactly 100% the answer I was looking for, because I still want to know how I can use a static library build, as I mention in my post, and compile everything as a single binary. This method is essentially gluing two binaries together.

I found this great and informative post over here:
https://www.avrfreaks.net/forum/can-you-combine-appbootloader-using-as7

It uses srec_cat to concatenate two binaries after building them:
https://www.keil.com/support/docs/2666.htm

I use the offset specified from the '.ld' file using

```srec_cat <firmware1.bin> -Binary <firmware2.bin> -Binary -offset 0x2000 -o <firmwareOut.bin>```

As the post suggests, I set this up as a post-build event and set my build dependencies accordingly so that a full clean and make will produce a consolidated binary including the bootloader.

If anyone tries this, make sure you only use the non-bootloader binary generated by your main project build. The bootloader places new firmware at location 0x2000 and your firmware will break if it finds a bootloader at the location where the firmware is supposed to be. When uploading firmware to the bootloader, it does not overwrite the bootloader.


message:
How to exit out of a timer interrupt (ISR(TIMER1_COMPA_vect))

I have a code here where I collect an array of data and do some data analysis with the data. The only thing I'm struggle with is how to exit the ISR after I am done running my code. I am using a pre-scalar of 256 and running the ISR once (1Hz)

```
const signed int numReadings = 21;
volatile int gauge0[numReadings];
volatile int gauge1[numReadings];
volatile int add[numReadings];
volatile int deltaGAUGE;
volatile int slopeADD;
volatile int mean;

const int A0_pin = PC0;
const int A1_pin = PC1;

const uint16_t t1_load = 0;
const uint16_t t1_comp = 62500;

void setup() {

  //Set A0 and A1 pins as inputs
  DDRC &= ~(1 << A0_pin);
  DDRC &= ~(1 << A1_pin);

  //Reset Timer1 Control Reg A
  TCCR1A = 0;

  //Set CTC mode
  TCCR1B &= ~(1 << WGM13);
  TCCR1B |= (1 << WGM12);

  //Set to prescaler of 1024
  TCCR1B |= (1 << CS12);
  TCCR1B &= ~(1 << CS11);
  TCCR1B &= ~(1 << CS10);

  //Reset Timer1 and set compare value
  TCNT1 = t1_load;
  OCR1A = t1_comp;

  //Enable Timer1 compare interrupt
  TIMSK1 = (1 << OCIE1A);

  //Enable global interrupt
  sei();

       Serial.begin(9600);
       Serial.println(" ");
       Serial.println("START");
        Serial.println(" ");

}

ISR(TIMER1_COMPA_vect){

       Serial.println(" ");
        for (unsigned int i=0; i<numReadings; i++)
            {
                        gauge0[i] = (analogRead(A0_pin))*(100.00/1024.0);
                        gauge1[i] = (analogRead(A1_pin))*(100.00/1024.0);
                        add[i] = ((gauge0[i]+gauge1[i]));

                        deltaGAUGE = abs(add[20] - add[0]);
                        slopeADD = abs((add[20]-add[0])/(20-0));
                        mean = (add[1]+add[2]+add[3]+add[4]+add[5]+add[6]+add[7]+add[8]+add[9]+add[10]+

                     add[11]+add[12]+add[13]+add[14]+add[15]+add[16]+add[17]+add[18]+add[19]+add[20])/20;

                        if(i == 20)
                {
                      Serial.print("This of the delta AVG reading: ");
                      Serial.println(deltaGAUGE);
                      Serial.println(" ");
                      Serial.print("This of the slope reading: ");
                      Serial.println(slopeADD);
                      Serial.println(" ");
                      Serial.print("This of the mean reading: ");
                      Serial.println(mean);
                      Serial.println(" ");
                      Serial.println("END");
              }

                        delay(50); //wait .05 sec

          }

}

void loop()
{

}

```

When I run the circuit, the interrupt keep executing every seconds for an infinite amount of time, while I just want it to run once and exit.

I have tried the ```exit(0)``` command but I get an output that looks like this
```
START

This of the delta AVG reading: 0

This of t

```

As you can see, The program does not execute completely. Anyone have any idea how I can fix this, or anyhow I can better my code? thank you.

body:
As some of the comments have suggested, I would either get rid of the ISR or reduce the size significantly. When using ISRs, it is recommended that you keep the code as small as possible. Use it to set variables, for example

    //these two variables are global
    ISR(TIMER1_COMPA_vect){
        someValue = true;
        numberOfValues++;
    }

you should also never use any Serial functions inside an ISR as these use interrupts themselves which can cause all kinds of problems

After using the ISR to update global variables, you can then use if() or while() statements within the loop() function to execute your serial print functions and such

P.S. on a side note, I would recommend changing your code where you calculated mean from

        mean = (add[1]+add[2]+add[3]+add[4]+add[5]+add[6]+add[7]+add[8]+add[9]+add[10]+
    add[11]+add[12]+add[13]+add[14]+add[15]+add[16]+add[17]+add[18]+add[19]+add[20])/20;
to

    for(uint8_t i = 1;i<=20;i++){
        mean += add[i];
    }
    mean /= 20;


body: Use ```cli();``` to completely disable interrupt. Then use ```sei();``` to re-enable the interrupt if you need it later.


message:
Explanation of code found online

i found following code online, to read the value of a touch sensor... i am having difficulties understanding how the 2 second timeout on the marked line works..
` if ((touch_sensor_value (TOUCH_timeSeconds * 1000))) {`

`touch_sensor_value` is the value read from the touch input.. and the rest?? i dont see any comparison with anything in the parenthesis, i cant figure out how this if condition is working...

    #define TOUCH_timeSeconds 2
    uint64_t now = millis();
    unsigned long lastTrigger_TOUCH = 0;
    bool startTimer_TOUCH = false;
    bool buttonIsPressed = false;

    int touch_sensor_value = 0;
    //Mux control pins
    int s0 = 26;
    int s1 = 27;
    int s2 = 14;
    int s3 = 12;
    //State array
    int currentState ;
    //Mux in “SIG” pin
    int SIG_pin = 33; //is touch sensor
    void setup()
    {
    pinMode(s0, OUTPUT);
    pinMode(s1, OUTPUT);
    pinMode(s2, OUTPUT);
    pinMode(s3, OUTPUT);

    digitalWrite(s0, LOW);
    digitalWrite(s1, LOW);
    digitalWrite(s2, LOW);
    digitalWrite(s3, LOW);

    Serial.begin(115200);
    Serial.println(“Multiplexing 1 Touch sensor ESP32 using CD7HC4067 MUX”);

    }

    void loop() {

    for (int i = 0; i < 16; i ++) {
    currentState = readMux(i);
    touch_sensor_value = touchRead(T9);

    if ((touch_sensor_value (TOUCH_timeSeconds * 1000))) {    <-----!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    Serial.println(“2 Second LOCK OUT: No rapidly repeating readings”);
    buttonIsPressed = false;
    startTimer_TOUCH = false;
    return;
    }

    //

    }

    // delay(1000);
    }

    int readMux(int channel) {
    int controlPin[] = {s0, s1, s2, s3};

    int muxChannel[16][4] = {
    {0, 0, 0, 0}, //channel 0
    {1, 0, 0, 0}, //channel 1
    {0, 1, 0, 0}, //channel 2
    {1, 1, 0, 0}, //channel 3
    {0, 0, 1, 0}, //channel 4
    {1, 0, 1, 0}, //channel 5
    {0, 1, 1, 0}, //channel 6
    {1, 1, 1, 0}, //channel 7
    {0, 0, 0, 1}, //channel 8
    {1, 0, 0, 1}, //channel 9
    {0, 1, 0, 1}, //channel 10
    {1, 1, 0, 1}, //channel 11
    {0, 0, 1, 1}, //channel 12
    {1, 0, 1, 1}, //channel 13
    {0, 1, 1, 1}, //channel 14
    {1, 1, 1, 1} //channel 15
    };

    //loop through the 4 sig
    for (int i = 0; i < 4; i ++) {
    digitalWrite(controlPin[i], muxChannel[channel][i]);
    }

    //read the value at the SIG pin
    int val = analogRead(SIG_pin);

    //return the value
    return val;
    }

body:
The comment form of a blog is not an appropriate place to publish source
code, as the content-management system (Wordpress here) quite often does
some destructive transformations. For example, here:

```c++
Serial.println(“2 Second LOCK OUT: No rapidly repeating readings”);
```

Wordpress tried to be “helpful” and replaced the ASCII quotes (") with
typographic quotes (“ and ”), which makes the line non-compilable.

As for the line you are asking about:

```c++
if ((touch_sensor_value  (TOUCH_timeSeconds * 1000)))
```

it is likely missing a less-than sign (<), as those are often stripped
from user-generated content for security reasons. I don't know why some
of those signs went through the filter, maybe it has something to do
with the white space surrounding them, but this is pure guess.

Given that the code has been destructively mangled, your options are
either to guess from the context, or post a comment asking for
clarification.


message:
Does setting a value always mean setting a Arduino pin?

One thing that always confused me was why we use int or other commands to set the variables to have pin numbers as if those commands were always restricted to pin numbers only. For example

    int ledPin = 13;

Does putting a random number in place of 13 that isn't a pin number cause an error? Right now I haven't checked yet.

I've only begun to realize that if you want to use variables in relation to pins or push buttons you have to set values first and then do associated functions like digitalRead. The commands like int are not like in other programming languages where you can set any values and do mathematical computations. I know it might seem obvious to someone who is used to Arduino, but this perspective is something that helped me grasp things better. Before that, I totally could not understand how things worked because of being confused with how int or other similar variables worked.

body:
Note that this is just a C/C++ integer declaration, assigning a value to a variable, like any variable (irrelevant if it is for pin numbers).

You don't have to use a variable, there are similar variations:

**Variable**

    int pinNumber = 13;

in `begin`:

    pinMode(pinNumber, OUTPUT);
    digitalWrite(pinNumber, HIGH);

**Const**

Preferably I like to use a const:

    const int PIN_NUMBER = 13;

Or even better, since it always is a low value:

    const uint8_t PIN_NUMBER = 13;

And use it with capitals.

    pinMode(PIN_NUMBER, OUTPUT);
    digitalWrite(PIN_NUMBER, HIGH);

**#define**

    #define PIN_NUMBER 13

    pinMode(PIN_NUMBER, OUTPUT);
    digitalWrite(PIN_NUMBER, HIGH);

The reason variables are used, is that when you want to use another pin number, you only need to change it in one place, making the sketch better maintainable/adaptable.

I don't know what happens when you give an illegal number (you can try it out yourself).


message:
Ethernet Shield not connecting

I've mounted an Ethernet Shield on top of an Arduino UNO. The Arduino is connected via usb to my pc and to the network via ethernet through a switch.
I'm running a simplified verison of the WebServer example and the function to Ethernet.begin() always returns EthernetNoHardware.

I've tried different setups changing the ethernet cables and connecting directly to the router. I also tried adding specific ip, gateway and subnet parameters to Ethernet.begin() however the output doesn't change and the server can't be reached:

```
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0xCC, 0x1E }; //mac address on the sticker
IPAddress ip(192, 168, 1, 134);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);
IPAddress DNSserver(192,168,1,1);
EthernetServer server(80);

void setup() {
  Ethernet.init(10);
  Serial.begin(9600);
  while (!Serial) {
    ;
  }

  Ethernet.begin(mac, ip, gateway, subnet);

  if (Ethernet.hardwareStatus() == EthernetNoHardware) {
    Serial.println("Ethernet shield not found.");
  }

  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}
```

output:

```lang-none
Ethernet shield not found.
server is at 192.168.1.134
```

Any idea on what the issue might be?

body:
In your sketch DNS IP parameter is missing in `Ethernet.begin`.

It should be `Ethernet.begin(mac, ip, dns, gateway, subnet);`


message:
Program size optimization

I am trying to spare a few bytes of program size.
I faced a problem which I cannot understand and I hope somebody will help.

Look at this empty sketch, pleas. It takes just 444 bytes:

    void setup()
    {
    }

    void loop()
    {
    }

However, this one – 1332 bytes already!

    void f() {
     Serial.println(1);
    }

    void setup()
    {
    }

    void loop()
    {
    }

Why?
It is supposed that function `f()` will be cut-off during the linkage stage. But it is not.
And what can I do to cut such things off, since they are not used in the code?

body:
Using the `Serial` object pulls HardwareSerial0.o into your program
linkage. This file defines, among other things, the ISRs (interrupt
service routines) associated with the serial port. ISRs are defined
using [the `ISR()` macro][isr] from the acr-libc. This macro creates a
function prototype and assigns some attributes to the function,
including [the `used` attribute][used] which tells the linker that it
should consider the function to be used, even if it cannot spot a single
call to it within the compiled program. The ISR cannot then be removed,
and it in turn keeps lots of code from the `Serial` implementation.

**Edit**: As pointed out by the busybee in a comment, although `f()`
cannot be removed at link time, it can be removed at compile time if you
give it the `static` qualifier. This has the added benefit of triggering
a compiler warning:

> **warning**: '_void f()_' defined but not used [**-Wunused-function**]

[isr]: https://www.nongnu.org/avr-libc/user-manual/group__avr__interrupts.html
[used]: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-unused-function-attribute


message:
Keep Alive for Arduino

Sometimes the arduino locks up for some reason. It would be nice to know why, but the problem is more general. I have found a hardware keep alive that resets the controller if it doesn't respond:

[Arduino Keep Alive with AT-Tiny][1]

This would work, but i wonder if there are there features like this built in to any of the processors that can be used in the Arduino environment (ESP8266, ESP32, or the like).

**Maybe folks know of a processor with the "Keep Alive" feature?**

**How would i determine if this "keep alive" feature is present for a specific processor?**

Thanks for any suggestions!

Mark

  [1]: https://diyodemag.com/projects/arduino_keepalive

body:
personally, I have never experienced my Arduino crashing. I even have a board running for one of my university projects measuring temperature, time and resistance of a sensor and saves the data to a micro SD card that has been running for over 3 months from batteries without issues!

What do you mean by 'locks up'? If you run the blink programme, does that stop or does It work ok?

In the link you provide, the idea of resetting devices in a complex IOT project is a smart idea, but you run into the risk of having your issue repeating over and over again if you do not know what is causing the problem


body:
Reference link: https://create.arduino.cc/projecthub/rafitc/what-is-watchdog-timer-fffe20

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

* Watchdog timers can be found in the datasheet. If there is no intervention to this module by the software, the MCU will be reset. basically, restarting all the functions.
* It is a bad idea to use WDT to solve your particular topic. You should try to fix the issue
* The external watchdog timers (Example: [ADM8320][2]) is more reliable than internal ones
[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/KVEpd.png
  [2]: https://www.analog.com/en/products/adm8320.html
  [3]: https://i.stack.imgur.com/txpjF.png


message:
Timer Interrupt Collision

I am working with a MEGA2560 trying to implement velocity ramps for three steppers at the same time. The goal is to move to different positions applying accelerations and decelerations while finishing all of them at the same time.

In order to do so, from the distances to move of each of the motors, I calculate the amount of steps to do and the velocities for each of those steps in order to ensure that all the motors finish at the same time. For so, I use timers 3, 4 and 5 in compare mode. This way, at each interruption, I make the motors do one step and, after that, I set the new compare value for the timer in order to reach the new velocity to move at.

My problem is that, at some point, my interruptions crash and one of the motors stops working. This only happens under one condition: when motor 1 has to do 18 steps and motor 2, 34. In this case, both motors 1 and 3 finish but motor 2 gets stuck and does not move any more. Although, if its motor 1 who has to do 34 steps and motor 2, 18, everything works. Motor 1 is related to timer 3 and motor 2 to timer 4. This makes me think this must be related to the priorities of the interruptions.

In the following code you can see my interruptions:
```
ISR(TIMER3_COMPA_vect) {
    m1_step();
    m1_steps_done++;
    m1_configure_vel();
}
ISR(TIMER4_COMPA_vect) {
    m2_step();
    m2_steps_done++;
    m2_configure_vel();
}
ISR(TIMER5_COMPA_vect) {
    m3_step();
    m3_steps_done++;
    m3_configure_vel();
}
```
While, in the velocity configuration I have:
```

void m1_configure_vel() {

  if (m1_steps_done < m1_acceleration_steps) {
    m1_temp_vel = m1_temp_vel + acceleration;
  }
  else if (m1_steps_done <= (m1_steps - m1_acceleration_steps)) {
    m1_temp_vel = m1_temp_vel;
  }
  else if (m1_steps_done < m1_steps) {
    m1_temp_vel = m1_temp_vel - acceleration;
  }
  else {
    m1_temp_vel = 0;
    m1_finished = true;
  }
  if (m1_temp_vel <=0){
    m1_temp_vel = 0;
  }

  OCR3A = frequency_to_compare_value(m1_temp_vel);
}
```
As you can see, all I do here is, depending on the steps done by the motor and the amount of steps to do, I increase, maintain or decrease the motor's velocity and set the compare value for the timer.

The whole thing is that this code works fine, the ramps are calculated properly and motors move correctly. The problem is that, under the condition I explained before, interruptions may collide due to their priorities and one of them just stops to happen.

I was wondering if anyone had any idea or have faced something like this before.

body:
I think the problem is being caused by the size of your ISR's.
When using ISR's, it's important to make the code as short as possible and you should certainly avoid using any functions!

I would change each of your ISRs to:

    ISR(TIMER3_COMPA_vect) {
        m1_steps_done++;
    }
    ISR(TIMER4_COMPA_vect) {
        m2_steps_done++;
    }
    ISR(TIMER5_COMPA_vect) {
        m3_steps_done++;
    }

then, in the main loop of your code, you can change it so that if m1_steps_done, or m2_steps_done or m3_steps_done has increased, execute the step and configure functions


body: Another approach might be to use a single timer instead of 3 separate ones.  Maintain 3 software counters and increment all of them on each interrupt, with separate limit tests and resets.  This will be slightly slower, but there will be no possibility of collisions.


message:
Connection Pro-Mini & ESP8266 using Serial

I wish to create a system consists of WEMOS mini & Pro-Mini sharing info using Serial ( one MCU is dedicated to react input-output, and second for MQTT commands ) sharing same Power input. From what I read in tutorials, at boot Serial wires have to be disconnected, in order to accomplish boot.

A) is that true that at boot Serial has to be disconnected?

B) is there a way that 2 MCU can be connected at all times, including reboot when needed ( such as power failures ) ?

body:
> A) is that true that at boot Serial has to be disconnected?

No, that is not true. However if you are using `Serial` to communicate on the Pro Mini you will need to disconnect the ESP8266 in order to program the Pro Mini as it will interfere with serial communication to the PC.

> B) is there a way that 2 MCU can be connected at all times, including reboot when needed ( such as power failures ) ?

Given that A) is a no, then B) is irrelevant. It will just boot.

The only caveat is that the ESP8266 will squirt some boot messages out of serial as it boots at 74880 baud, so you have to be able to cope with that noise in whatever protocol you design between the two boards.


body:
> A) is that true that at boot Serial has to be disconnected?

Not exactly, if you're careful about what is communicating with what and when.  That you protect against multiple things driving the same connection, etc.  And you don't mind being very confused a lot of the time.  And that you're holding one board in reset while the other is being programmed.

> B) is there a way that 2 MCU can be connected at all times, including
> reboot when needed ( such as power failures ) ?

If you don't have a compelling reason to avoid it, you may be better off using I2C between the two of them.  Then your serial is left alone on both boards to behave as it normally does.  You don't need to sort out conflicts between boards trying to use serial to talk to each other and trying to use their serial transceivers to talk to the host and the conclusion that results from the host and both boards all see traffic from different things.  And you have an open collector setup between your two boards which makes independently powering them somewhat less of a problem.

If you do try to use the Pro Mini and ESP8266 USARTs connected together, you should have some series resistance in the connection between the FTDI (or whatever) TX signal and the RX on the Pro Mini. Or between the Pro Mini RX and the WEMOS TX.  In other words, anywhere you have two pins driving what would otherwise by the same node in the circuit, you need some current limiting in case they drive in opposite directions, as will happen if you connect their serial connections together.  If you look at the Wemos D1 mini schematic or the Arduino UNO, Nano, etc schematics you'll see they've inserted some resistance there for that reason.  If you look at the Pro Mini schematic you'll see the FTDI TX line is connected directly to the AVR's RX.

Below you asked why you would need the FTDI connection.  If you're not programming the Pro Mini and not using it power the Pro Mini, then you don't.

However, if you're thinking you're going to be able to program the Pro Mini using the serial transceiver on the Wemos and the connection between them, that isn't going to work.  The Wemos serial transceiver's TX would be connected to its ESP8266's RX, which would be connected over to the Pro Mini's TX (not RX) because project is operating normally it needs to receive data from the Pro Mini on that pin.  Allowing the Wemos serial transceiver to talk to the Pro Mini's RX would require you to wire it in a way that the two boards couldn't use their USARTs to talk to each other.  The two usages are only compatible with two different wiring schemes.


message:
esp32 crashes when trying to dereference a pointer value

I have a websocket listener that is giving me a std::string of my message payload (I want the bytes) and I wrote a function that pulls each of the bytes out and puts them into 32 bit integer variables, adds that integer to an array of 32 bit integers, and passes back the pointer address:

```
uint32_t *get32BitInt(WebsocketsMessage message)
{
  std::string raw = message.rawData();
  uint32_t chunks[message.length() / 4];
  int chunkIndex = 0;
  for (int i = 0; i < message.length(); i += 4)
  {
    uint32_t chunk = 0;
    for (int j = 0; j < 4; j++)
    {
      chunk <<= 8;
      chunk |= raw.at(i + j);
    }
    chunks[chunkIndex] = chunk;
    chunkIndex++;
  }
  return chunks;
}
```

And I know that parsing and array building works because if I add a loop before I exit the overall function call it prints them out just fine.

[![parser builds array correctly][1]][1]

And in the function that calls the parser I can print out the address of the pointer that was passed back.

But, as soon as I try to dereference anything my microcontroller crashes:

[![crash][2]][2]

I know that I'm pretty green to pointers and I'm probably misunderstanding something, but I keep looking at docs and examples of passing arrays as pointers and it seems right.

Also, something worth noting is that it doesn't seem to be an issue with the actual number printing, because if I store the first number of the array into a variable and then try to print a line after the assignment the controller crashes after the assignment but before the next serial print:

[![crash at assignment][3]][3]

  [1]: https://i.stack.imgur.com/L9eRG.png
  [2]: https://i.stack.imgur.com/HTud3.jpg
  [3]: https://i.stack.imgur.com/wYrhO.png

body:
Ah, one of my friends pointed out the issue. It's a scope snag:

> chunks is allocated on the stack in get32BitInt By returning a pointer to chunks, you are pointing to memory that is deallocated. Think of it as pointing to a member variable of a class that has already been destroyed
>
> when you try to dereference deallocated memory, bad things can happen. usually in debug the compiler makes sure you fail hard
>
> the easiest way to test this is to allocate chunks outside of that function and pass it in as a reference

So yeah, I was allocating memory within the scope of a function and then blowing that memory contents away when that functions scope ended.

I refactored my code to move the array outside of the scope of the parsing function and passed the pointer in to the parsing function to get populated:

```
void get32BitInt(WebsocketsMessage message, uint32_t *chunks)
{
  Serial.println("--------------------------------");
  Serial.println("raw parse:");

  std::string raw = message.rawData();

  // uint32_t chunks[message.length() / 4];
  int chunkIndex = 0;

  for (int i = 0; i < message.length(); i += 4)
  {
    uint32_t chunk = 0;
    for (int j = 0; j < 4; j++)
    {
      chunk <<= 8;
      chunk |= raw.at(i + j);
    }
    chunks[chunkIndex] = chunk;
    chunkIndex++;
  }

  Serial.println("parsed chunks:");
  for (int i = 0; i < 11; i++)
  {
    Serial.print(chunks[i], HEX);
    Serial.print(" == ");
    Serial.println(chunks[i], BIN);
  }

  Serial.println("--------------------------------");
}

void addWebsocketListener()
{

  client.onMessage([&](WebsocketsMessage message) {

    uint32_t gameFrame[message.length() / 4]; // *try moving gameFrame out of scope
    get32BitInt(message, gameFrame);

    Serial.print("game frame address: ");
    Serial.println((int)&gameFrame);

    Serial.println("storing first 32 bit integer in a variable");
    uint32_t firstNumber = *gameFrame;

    Serial.print("game frame first value: ");
    Serial.println(firstNumber, HEX);

    Serial.println("printing frame:");
    for (int i = 0; i < 11; i++)
    {
      Serial.println(gameFrame[i], HEX);
    }
  });
}

```

And now my controller isn't crashing :D

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

And now I understand scope when dealing with pointers a bit better :)

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


message:
How do I switch between while loops before the current loop finishes? IR Remote + LED's

I have a project that requires rotation of a tank tread. I've simulated LED's to go off in a rotation using an IR Remote. I want to stop the clockwise rotation halfway through so I can immediately rotation counterclockwise.

Unfortunately, my code waits until after the complete rotation (or the complete while/if loop) to move into the ccw rotation loop. How do I code this to immediately switch between loops?

Here is my code:

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

int RECV_PIN = 10;
int Switch = 10;
IRrecv irrecv(RECV_PIN);
decode_results results;

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

  pinMode(2, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);

  irrecv.enableIRIn();         // Start the receiver
}

void loop()
{
  if (irrecv.decode(&results))
  {
    Serial.println(results.value);
    irrecv.resume();           // Receive the next value
  }

  while (results.value == 16615543)     // button 2: clockwise rotation
  {
    digitalWrite(2, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(9, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(3, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(2, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(4, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(3, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(5, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(4, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(6, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(5, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(7, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(6, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(8, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(7, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(9, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(8, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)
  }

  while (results.value == 16580863)     //power button - break other loops and wait for next IR transmission
  {
    digitalWrite(2, LOW);
    digitalWrite(3, LOW);
    digitalWrite(4, LOW);
    digitalWrite(5, LOW);
    digitalWrite(6, LOW);
    digitalWrite(7, LOW);
    digitalWrite(8, LOW);
    digitalWrite(9, LOW);
  }

  while (results.value == 16619623)     // button 8: ccw rotation
  {
    digitalWrite(9, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(2, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(8, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(9, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(7, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(8, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(6, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(7, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(5, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(6, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(4, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(5, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(3, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(4, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

    digitalWrite(2, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(3, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)
  }
}
```

body:
> How do I code this to immediately switch between loops?

You don't. You remove the loops. You don't want them - they can never end, since there is no way for the results to change between iterations.

You have a fundamental misunderstanding of how IR remotes work. There can be no "while" since a remote sends a signal either just once per button press, or repeatedly while the button is held down, depending on the function the button is supposed to perform.

Instead all you can do is "If the button has been pressed then do something". There's no "It's currently pressed" or "It's been released", only "I got a signal that it's pressed".


body:
In addition to Majenko's answer, what you should use is a so called State engine.

First you define an enum:

    enum EState { Off, Clockwise, CounterClockwise };

    EState _state;

In `setup` you set  `_state` to some default value.

In `loop` you check for button changes, and set the state accordingly.

Then you act on the state:

    switch (_state)
    {
    case EState::Off:
        {
            // Switch all off
            for (int n = 0; n < 9; n++)
            {
                digitalWrite(n, LOW);
            }
        }
        break;

    case EState::Clockwise:
        ... See below

    case EState::CounterClockwise:
        ... Similar as above
    }

For the Clockwise and CounterClockwise states, you have to keep a variable, that increases every 100 ms, resets itself when going to the new state.

Depending on the step value, you do something. e.g. for the first two clockwise steps:

    digitalWrite(2, HIGH);
    delay(500);                // Wait for 500 millisecond(s)

    digitalWrite(9, LOW);
    delay(1000);               // Wait for 1000 millisecond(s)

you can make a switch like this inside the case you already have (or better: create a new function):

    switch (_step)
    {
    case 0: // 0 ms
        digitalWrite(2, HIGH);
        break;

    case 5: // 500 ms
        delay(1000);

    ...

Note it is a bit more clean to create a sort of hash/array but the above should work too. You can increase `_step` every 100 ms or only when the (counter)clockwise states are active.


message:
Chips & High voltage: Connected in Series?

I have 3 micro-controllers that will be connected to a battery, and I need to provide each of them between 3 and 5 volts maximum.

I have 3V batteries but they do not seem to provide enough power, while putting to of them in series would fry the chips as it busts the 6 volts max.

My question is, if I provide 9 volts to 3 chips connected in series, would current drop be distributed evenly to 3V across all chips, or would for example fry the first one?

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

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

<!-- End schematic -->

body:
If  you put three resistors of the same value in series, then you would get equal voltage division between them.

But chips are not like resistors. Their current usage is not constant and typically vary by orders of magnitude even within each clock cycle. See why this would be a problem?

If you have good 3V batteries that supply 3V up to the maximum current that the chips can draw, and the chips are rated to run reliably at 3V then there is another problem. Maybe you need decoupling capacitors across the chips?