message:
How do software interfaces compare to hardware interfaces in therms of speed and reliability?

The Arduino core includes numerous software interfaces mimicking the hardware interfaces provided by the chip and even extending beyond. My question is, if in a project I can either use software or hardware protocol, what would be the difference in stability, speed and versatility? Is there a reason why hardware interfaces are preferred? Because anyways the protocol is handled by the CPU or am I mistaking something?

body:
In your question you ask about all communication interfaces in general, so the answer will be as general as your question.

Hardware interfaces should always be preferred to software interfaces, though there are situations, where it is a better or needed to use a software interface due to limited resources.

> Because anyways the protocol is handled by the CPU

That is mostly wrong. The communication protocol is done by the hardware in most cases, if you use hardware interfaces. Serial (UART) for example automatically sends out the byte, that is placed in the hardware buffer, with the set configuration. It does not rely on any software for that. The same goes for SPI or I2C. The protocol of the interface is handled via hardware.

Though at least for Arduino Core/library users there is more to it, that get's handled automatically. Since the interface hardware is limited, the software have to take care of the resulting or needed data. For example: All the interfaces mentioned above use a 1 byte buffer for the data. The software must read or write this data, so that the hardware can work. If you don't read the byte of data, that was received by the Serial interface, it might get overwritten by the next byte. The hardware cannot provide a buffer, that is generally big enough, since the manufacturer cannot know, how long the transmissions will be. So the interfaces get a 1 byte buffer and the software has to do the rest. For this reason all the libraries use a bigger buffer in their software, that gets filled, when the hardware sends a corresponding interrupt.

So: Hardware interfaces implement the basic interface protocol (how the bits get transmitted) in hardware, thus the software only has to provide and read the byte data. The stability, speed and versatility is only determined by how the manufacturer build the hardware of that interface. This limit is clearly specified in the datasheet and does not change with the code.

For software interfaces, everything is done in software. This also involves monitoring and setting the corresponding pins with the correct timing. In the best case the software can utilize general hardware functions like a pin interrupt, but if it cannot do this, it has to constantly monitor (poll) the pins to receive something. Software interfaces are often called "bit banged", because the software manually pushes out each individual bit with the exact needed timing. That is a tedious task, which often blocks the execution of other code, since the timing often is critical. Especially the timing introduces limits, since doing things in software often involves many clock cycles more, than it could be done by dedicated hardware (consider all the code to poll a pin and the multiple if statements to react to specific situations). For example: When you write data with `SoftwareSerial` the call to the write function will block, because is manually pushes out bit after bit. Or with SPI: With hardware SPI you can go to incredible clock speeds in the MHz range. You won't every get near that with software, because the software simply cannot run this fast.

Note, that depending on the actual hardware of the used chip, a library may need to implement parts of the protocol in software. For example this is the case for using I2C on an ATtiny85, which does not have full I2C hardware support. Instead the USI (Universal Serial Interface) can be used to implement some functions of the protocol in hardware and the rest in software.

**TL;DR**

- Hardware interfaces lift the heavy duty of handling the low level protocol (transmitting the bits by the needed standard) (which can be rather complex) from the software
- The Software then only handles the byte data, not it's transmission
- Translating complex protocols from dedicated hardware to software (bit banging the data through simple pins) imposes great limits on speed and reliability.


sender: user

sender: assistant

body:
Using a hardware interface takes a lot of load from the CPU. Let's take an asynchronous serial interface for example.

With the UART built-in hardware you'll get parallel-serial conversion and back done in hardware. The CPU "just" needs to store the data to be sent in a register. The receiving part is handled completely by the hardware and the CPU "just" needs to look at the "received" flag before reading the data. Or it sets up an interrupt as callback.

If you use a software interface the CPU needs to convert the parallel data to serial with several instructions and, really important, needs to maintain a certain timing. For receiving this might be even harder because of the asynchronous nature of the protocol. A timer might be usable to clock the communication, for example by an interrupt, but this puts a lot of load on the CPU. Certain conditions might make this usage impossible, too.

Now you might think about the issues you mentioned:

**Stability:** If done correctly both approaches are equally stable, meant as reliable function. If you have more tasks to be done you might not be able to meet the requirements. This comes "earlier" with software interfaces than with hardware interfaces due to the higher load.

**Speed:** Hardware interfaces can be faster than software interfaces because the hardware is commonly clocked faster than what is possible by software which needs multiple instructions for one step. But speed is always a relative issue. There are libraries implementing USB1.1 via software, and the USB1.1 protocol is both fast and really complex.

**Versatility:** Software interfaces are more versatile because hardware interfaces are limited in their capabilities. If a hardware interface can't do what you need there is no way to make it do this. Software can do "anything" as long as the CPU has enough time and resources for this.

Hardware interfaces are preferred because they are simpler to use and commonly don't put hard requirements on your software architecture.


message:
Does a pulldown resistor use less battery power than a pullup resistor?

I am designing a circuit connected to a simple open-close sensor, like a switch. For ease of construction, the circuit with the sensor switch closes to ground, and uses a 1 MΩ pullup resistor to Vcc to signal `HIGH` when the switch is open.

I realize that power is flowing the entire time the switch is open, which may (or may not) drain the battery. Would it be more efficient to use a pulldown resistor to ground, and have the switch open to Vcc?

Tangentially, should there be a resistor on the connection to Vcc as well? Either to reduce current (save battery power) or prevent damage to the ATmega328?

Thank you!

body:
The input current does not depend on the pin level. Have a look at [this discussion][1] from avrfreaks. The input impedance of a digital pin is extremely high. The leakage current of the Atmega328P (here as example chip) is mentioned to be 1uA for both pin states. So this current is both unavoidable and neglectable from a normal view.

But the input impedance of a digital input pin is not only dependent on this leakage current. There is also a capacitance, which will lower the impedance for higher frequencies. So, if you drive the input with higher frequencies, the input will draw more current. But you only have a switch connected to it, which is very very low frequency.

So it doesn't matter, if you pullup or pulldown. The main current consumption will result from the moments, where the switch is activated, since then a current flows through the pullup/pulldown resistor to ground.

> Tangentially, should there be a resistor on the connection to Vcc as well?

No need for a resistor there. The input impedance of the pin is already high enough and you don't want to create a voltage divider with your pulldown resistor (which would change the voltage levels at the pin).

  [1]: https://www.avrfreaks.net/forum/input-impedance-digital-ios-atmega328p


body:
>I realize that power is flowing the entire time the switch is open, which may (or may not) drain the battery.

No, it doesn't. You get a small spike as the switch is opened or closed, as the gate capacitance is charged or discharged, but other than that there is negligible current draw by a pin, which remains static regardless of the direction of the biasing resistor.

> Tangentially, should there be a resistor on the connection to Vcc as well? Either to reduce current (save battery power) or prevent damage to the ATmega328?

Absolutely not.  The current draw of the MCU is not static. That means that the current through such a resistor would not be static, and so the voltage dropped across that resistor would fluctuate too - meaning if the current draw rises above a certain point the chip will be starved of power and will "brown out".

You only need a resistor to limit current when you have a device that cannot control the current by itself, such as an LED or other "non-linear" device.


body:
If the sensor does provide two defined voltage levels, you do not need a pullup or pulldown resistor, but if it's only a switch: either (closed) connected to Vcc or GND, or (open) not connected, you need a pullup or pulldown resistor to get a defined voltage level in case there's "nothing else" (except the wire to the switch catching noise out of the air) connected to the digital input pin.

When the switch is open, the pullup/pulldown resistor is connected to the input pin and nothing but that neglectable leakage current is flowing.

When that switch is closed, some current will flow through that resistor, according to Ohm's law. You have to optimize between that current and the risk of catching some noise signal. Typically, µControllers like the Arduino atmel atmega328p have builtin pullup resistors of ~30k..50k, which should be fine for standard situations.

If you fear the battery drain, you can experiment with bigger resistors, but first make sure to build a scenario where the usual situation is "switch open". e.g. A fridge's door switch should be NC, but pressed while the door is closed.  :)


message:
How to increase the range to IR transistor receiver

I have a Arduino project which controls LED using IR Receiver and Transistor.The circuits works fine,But the problem is the LED is Blinking Brightly  only for short range basically between 5-8 cm,but when i used my TV remote it works at for very long range(above 1 m).I have tried giving high voltage to IR Transistor,but no use.
Please help to solve this problem!!
Thanks in Advance!

body:
The reason your TV remote can work over a much longer distance is because it doesn't just turn an LED on and off.

Instead it turns the LED on and off *really fast*, and then turns that "turning on and off" on and off as well.

In technical terms: the light is modulated with a carrier frequency.  Just the same as a radio signal is modulated with a carrier frequency, you can do the same with light.

The receiver then samples the light falling on it over time and passes it through a *band pass filter* to remove any frequencies in the changes of light intensity that aren't within the frequency of the carrier signal.  What is left is then low-pass filtered to recover the overall "on-off" signal that is being transmitted.

Much of that is hard to do using an Arduino, so an IR *receiver* is used which integrates all the filtering and recovery of the signal. These are sold with different frequency sensitivities, and if you then turn an IR LED on and off at that stated frequency it will be able to "see" it far more efficiently than just having a light on or off.

There is a [library for the Arduino](https://github.com/z3t0/Arduino-IRremote) that can handle the modulating of the LED at the right frequency for your chosen IR receiver.


message:
Temperature anomaly on BS18B20 + NodeMCU on Tingspeak

Temperature drops occasionally from 59+C to -13C or to other random values. Used sketch and info from this site:
http://internetofthinking.blogspot.com/2016/02/upload-ds18b20-temperature-sensor-data.html

NodeMCU powered by phone charger 5v 1a via microUSB.
Placing 4.7 kOm resistor between data wire and 3v3 didn't help me.

Does anyone know how to solve this issue? Like filtering results and pushing to server only values that do not differ by more than n*C, or something like that?

Here is the sketch

    #include <ESP8266WiFi.h>
    #include <OneWire.h>
    #include <DallasTemperature.h>

    #define myPeriodic 15 //in sec | Thingspeak pub is 15sec
    #define ONE_WIRE_BUS 2  // DS18B20 on arduino pin2 corresponds to D4 on physical board

    OneWire oneWire(ONE_WIRE_BUS);
    DallasTemperature DS18B20(&oneWire);
    float prevTemp = 0;
    const char* server = "api.thingspeak.com";
    String apiKey ="-";
    const char* MY_SSID = "-";
    const char* MY_PWD = "-";
    int sent = 0;
    void setup() {
      Serial.begin(115200);
      connectWifi();
    }

    void loop() {
      float temp;
      //char buffer[10];
      DS18B20.requestTemperatures();
      temp = DS18B20.getTempCByIndex(0)+5;
      //String tempC = dtostrf(temp, 4, 1, buffer);//handled in sendTemp()
      Serial.print(String(sent)+" Temperature: ");
      Serial.println(temp);

      //if (temp != prevTemp)
      //{
      //sendTeperatureTS(temp);
      //prevTemp = temp;
      //}

      sendTeperatureTS(temp);
      int count = myPeriodic;
      while(count--)
      delay(1000);
    }

    void connectWifi()
    {
      Serial.print("Connecting to "+*MY_SSID);
      WiFi.begin(MY_SSID, MY_PWD);
      while (WiFi.status() != WL_CONNECTED) {
      delay(1000);
      Serial.print(".");
      }

      Serial.println("");
      Serial.println("Connected");
      Serial.println("");
    }//end connect

    void sendTeperatureTS(float temp)
    {
       WiFiClient client;

       if (client.connect(server, 80)) { // use ip 184.106.153.149 or api.thingspeak.com
       Serial.println("WiFi Client connected ");

       String postStr = apiKey;
       postStr += "&field1=";
       postStr += String(temp);
       postStr += "\r\n\r\n";

       client.print("POST /update HTTP/1.1\n");
       client.print("Host: api.thingspeak.com\n");
       client.print("Connection: close\n");
       client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
       client.print("Content-Type: application/x-www-form-urlencoded\n");
       client.print("Content-Length: ");
       client.print(postStr.length());
       client.print("\n\n");
       client.print(postStr);
       delay(1000);

       }//end if
       sent++;
     client.stop();
    }//end send

[![thingspeak][1]][1]

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

body:
Discarding (potentially) bogus readings could help as a last resort, but something's going on to cause those bogus readings. You'd be better off finding and fixing that than finding a work-around.

These are pretty stable devices and you shouldn't see more than a couple of LSB (a few 1/4 degC). I'm inclined to suggest noise pickup on the one-wire bus but the bogus samples in your photo look identical. I have a >15' parasitic one-wire bus, just a twisted pair with no shield, and a DS18b20 close to the MCU and another out at the end. I do smooth the input but no de-spiking.

Have you checked the device's Scratchpad CRC between converting and reading the temperature? How is your device hooked up (diagram)? Is it in parasitic mode?


body:
> Have you checked the device's Scratchpad CRC

Idk how to.

> How is your device hooked up (diagram)

Device is hooked up in normal mode, right like in this pic
[![enter image description here][1]][1]

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

DS18b20 (waterproof) is located on top of the boiler in a special pit for measuring temperatures, there are definitely no any sort of microwaves here, and the temp is not higher than 80C.
I'll try today to change the power supply, just in case, and later switch the sensor into parasite mode.


message:
arduino & drivers to control 5 brushed CIM motors independently?

i am a complete newbie in electronics but i'm a bit familiar with C.
i am building a machine that requires 5 little engines (12V 2.5in brushed CIM motors) & motor drivers (i need to adjust each motor's speed).
i've got an arduino UNO which i think is too small to control that many motors.
i would like to know if the setup i want was feasible to your opinion and which ardunio would i need to do that ?
i guess an Arduino Mega ?

also, i came accross this tutorial : https://howtomechatronics.com/tutorials/arduino/arduino-dc-motor-control-tutorial-l298n-pwm-h-bridge/
it explains how to configure an arduino with a driver & two motors.

in fact i want to prepare the same kind of thing but with 5 motors that i can control independently.

which hardware would you recommend to do such a thing please ?

many thanks !
regards

body:
You should have just enough I/O with UNO, so long as you don't want to connect any other hardware/sensors.  Since this is unlikely, it would be better to use another board like Mega, but I'll provide solutions anyway in case you want to try them out:

- **Option 1**:  For 5 motors controlled with L298N boards you'll need 15 output pins, 5 of which should be PWM.  Fortunately, there are 5 PWM outputs on the Arduino UNO on `PORTB` and `PORTD`.  The remaining 10 outputs need only be digital (`PORTB` has 1 and `PORTD` has 5).  You can use `DDRC` and `PORTC` commands to change function of the analog inputs labeled A0-A5, making them digital output, thereby gaining 6 more digital output pins for a total of 12 (more than the minimum 10 needed).
- **Option 2**:  It is possible to use other PWM motor drivers that reduce number of pins required.  Examples are DRV8838 ([link to supplier][1]) and DRV8833 ([link to supplier][2]) where 2 wires are needed per motor channel.  As a bonus, these drivers are also significantly more compact than L298N.

  [1]: https://www.pololu.com/product/2990
  [2]: https://www.pololu.com/product/2130


message:
buiReliable time in ISR

I'm using a Nano. The code below is a simplified workup of my problem code.

The point of it is asynchronous debounced button press detection. The actual code sets a volatile bool to tell the main loop it saw a press, but this simplified version toggles the state of the built-in LED. Another LED follows the state of the pushbutton to make it possible to see whether the ISR is firing appropriately.

```
#define SHORT_PRESS_MS 50
#define PUSHBUTTON_PIN 2
#define BUILTIN_LED_PIN 13
#define OTHER_LED_PIN 12
volatile unsigned long fallTime = 0;
volatile int builtinLedState = LOW;
void isr_change()
{
 unsigned long now = millis();
 int pushbuttonState = digitalRead(PUSHBUTTON_PIN);
 // show switch state with LED and 120 Ohms on D12
 digitalWrite(OTHER_LED_PIN, pushbuttonState);
 if ((pushbuttonState == LOW) || (fallTime == 0))
 { // change to low => falling edge
  fallTime = now;
 }
 if (pushbuttonState == HIGH)
 { // change to high => rising edge
  long pressMs = now - fallTime;
  if (pressMs > SHORT_PRESS_MS)
  {
   builtinLedState = !builtinLedState;
   digitalWrite(BUILTIN_LED_PIN, builtinLedState);
  }
 }
}
void setup()
{
 pinMode(PUSHBUTTON_PIN, INPUT_PULLUP);
 pinMode(BUILTIN_LED_PIN, OUTPUT);
 pinMode(OTHER_LED_PIN, OUTPUT);
 attachInterrupt(digitalPinToInterrupt(PUSHBUTTON_PIN), isr_change, CHANGE);
}
void loop() {}
```

When this runs, OTHER_LED slavishly follows the button. There is no perceptible lag and it never gets out of synch no matter how machine-gun my antics with the button.

However, toggling of the built-in LED is not reliable. That OTHER_LED remains in sync with the button state implies that the event is always firing and the state is always what I expect, so it seems like there is a problem with my attempt to measure time.

What is the right way to measure time inside an ISR?

----

Applying suggested diagnostics confirmed the hypothesis of the accepted answer. Having determined the nature of the problem, I rewrote the ISR as follows.

```
void isr_change()
{
 static long fallTime = 0;
 static int lastPushbuttonState;
 int pushbuttonState = digitalRead(PUSHBUTTON_PIN);
 if (lastPushbuttonState != pushbuttonState)
 {
  long now = millis();
  if (pushbuttonState == LOW)
  { // change to low => falling edge
   fallTime = now;
  }
  if (pushbuttonState == HIGH)
  { // change to high => rising edge
   long pressMs = now - fallTime;
   if (pressMs > SHORT_PRESS_MS)
   {
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
   }
  }
 }
}
```
Testing reveals that the problem is resolved and the intended behaviour is occurring (reliably detect presses of minimum duration).

Also of interest is the use of `static` to carry values between ISR invocations with local scope, rather than using global volatile variables.

body:
you toggle the state of the main LED on CHANGE to HIGH. how should it be in sync with the other LED? and there could be more fast changes (bounce) which human eye can't see on LED

result of the sketch:

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

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


body:
I cannot make sense of this:

```c++
if ((pushbuttonState == LOW) || (fallTime == 0))
```

Why `|| (fallTime == 0)`? Other than this, your ISR looks fine to me.
And your way of measuring the time is correct. The only scenario I can
imagine that can make the toggling unreliable is the ISR missing
transitions, which can happen if the input pin gives very short spikes.

Here is my scenario:

The button is pressed, `fallTime` holds the correct value, you release
the button. At this point, the bouncing button generates a very short
positive pulse: LOW → HIGH → LOW. The first transition triggers an
interrupt request. However, there is some [latency][] in handling the
request. By the time the ISR starts running, the pin has already toggled
back to LOW, and the ISR then incorrectly updates `fallTime`.

A little bit later, the pin toggles back to HIGH for good. However,
`now` is very close to `fallTime`, and the rising edge gets ignored.

You can check whether you have missed transitions by toggling the LED
every time you see the same state as in the previous ISR run:

```c++
void isr_change()
{
    static uint8_t previous_pin_state;
    uint8_t pin_state = digitalRead(PUSHBUTTON_PIN);
    if (pin_state == previous_pin_state)
        digitalWrite(LED_BUILTIN, !digiatlRead(LED_BUILTIN));
    previous_pin_state = pin_state;
}
```

[latency]: https://arduino.stackexchange.com/a/8926


message:
Receive whole string in serial sending data?

I connect my NodeMCU to Arduino Uno. The goal is to receive the whole string for example "12", every 1 sec.

This is my code on Arduino Uno side ( the sender)

    int mock = 0;

    void setup() {
      Serial.begin(115200);
      s.begin(115200);
    }

    void loop() {
     //Write mock to NodeMCU
     s.print((int)mock,DEC);
     s.println();

        mock++;
     delay(1000);
    }

On NodeMCU side ( the receiver)

     char data; //Initialized variable to store recieved data
     String line;
     void setup() {
       Serial.begin(115200);
       s.begin(115200);
       while (!Serial) {
        ;
      }
    }

    void loop() {

     if( s.available() >= 2) {
      for (int i = 0; i< 2; i++ ) {
       data = s.read();
       line += data;
      }
      delay(1000);
     }

     Serial.print(line);

    }

But the result on the serial panel is not what I expected
[![Serial terminal][1]][1]

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

How can I make it so that I can receive something like

    12
    (wait one sec)
    13
    (wait one sec)
    ....

Node MCU just prints the whole thing, I can't delay it.

body:
If you send "12" you send 4 characters/bytes: '1', '2' and a new line which is two characters:  ('\r', '\n').

On the receiver side you check for two characters (not the new line), so you should take it into account.

Actually, since you will eventually reach "100" you will receive 5 characters ('1', '0', '0', '\r', \'n').

So it is better to change the receiver side to store the bytes in line UNTIL a new line is received (than you can support values of any length).

Also remove the delay on the receiver side, or at least decrease it a lot, because it doesn't matter to check (too) often. if there is no byte available, it will check again. Now it can happen at time 1001 ms a byte would be received, but at time 1000 ms it is checked and it will not be checked again until time 2000 ms.


body:
in your nodemcu use

    void loop() {
        if(s.readBytesUntil('\n',data ,2)>0)
          Serial.println(data);
        delay(1000);
    }

> Serial.readBytesUntil(character, buffer, length)

**Serial.readBytesUntil()** reads characters from the serial buffer into an array. The function terminates (checks being done in this order) if the determined length has been read, if it times out , or if the terminator character is detected (in which case the function returns the characters up to the last character before the supplied terminator). The terminator itself is not returned in the buffer.

**Serial.readBytesUntil()** returns the number of characters read into the buffer. 0 means that the length parameter <= 0, a time out occurred before any other input, or a termination character was found before any other input.


message:
Variable sets to 32767 - MATLAB Arduino

I am running out of ideas of what may be causing this problem, and I would appreciate some help identifying anything I am overlooking.

## Quick Problem Summary

A variable gets set to 32767 quite often and I am unsure why. I tried checking if it was a types problem, if there was somewhere in my code it could overflow, any division by 0, initialising all variables in all sections of the code, and have now tried to cast all relevant variables to `int`. What else could I try?

This is how this variable gets set in a C++ function:
```c
readValue = readAverage(A0);
targetValue = 2000; // Some constant number set beforehand
myVariable = targetValue - static_cast<int>(round(readValue));

// After some operations that only check if myVariable is within a range

// There are several states in which LOG_myVariable can get set in case there is an error where data wants to get logged
LOG_myVariable = myVariable
```

All of the variables above are public and get initialised to 0. See in the context section to see how the `readAverage` function works.

This code block above gets repeated thousands of times in a loop and exits when I send an interrupt. `LOG_myVariable` only gets set in the method above. Sometimes it gives me normal values that I would expect, but it is returning 32767 very often. Is this some C++ syntax or function I am overlooking?

### Some context:
An Arduino Due is using the [MATLAB 2019 - Arduino Support Package Add-on](https://www.mathworks.com/hardware-support/arduino-matlab.html). The variables described above are stored in memory and are dynamically overwritten during every logging function. I send them back to MATLAB via the C++ `commandHandler` as:

```c
byte dataOut[2] = {
                  highByte(LOG_myVariable),
                  lowByte(LOG_myVariable)
                  };
sendResponseMsg(commandID, dataOut, 2);
```

In MATLAB, I convert it within a method after requesting the `dataOut` via `sendCommand`:

```matlab
[dataOut] = sendCommand(arduinoObj, arduinoObj.LibraryName, commandID, dataIn);
            % Converts the two High and Low bytes from [dataOut] into a single integer.
            myVariableMATLAB = 256 * dataOut(1) + dataOut(2);
```

`readAverage` works like this:
```c
/*
Reads the raw ADC sampled value of a pin an averagePoints amount of times.
All the values get averaged and the function returns `outputAverage`.
Note
*/
int myClass::readAverage(const uint8_t pin) {
  int i = 1, outputAverage = 0;  // Iteration value, OutputAverage
  double sum = 0, runningAverage = 0;
  // Array Initialization
  int readings[70] = { 0 };

  for (i = 0; i <= 70; i++) {
    if ((runningAverage >= 0) && (runningAverage <= 4096)) {
      // First 10% readings to setup a runningAverage value
      if (i < 70 * 0.1) {
        readings[i] = static_cast<int>(analogRead(pin));
        sum += readings[i];
        runningAverage = static_cast<int>(sum/(i+1));

      } else if (i >= 70 * 0.1) {
        // Normal Operation
        readings[i] = static_cast<int>(analogRead(pin));

        // Filtering Outliers
        // If xReading is within [LOWER_PERCENTAGE, HIGHER_PERCENTAGE] * runningAverage range.
        if ((readings[i] >= LOWER_PERCENTAGE * runningAverage)
        && (readings[i] < HIGHER_PERCENTAGE * runningAverage)) {
          sum += readings[i];
          runningAverage = static_cast<int>(sum/(i+1));
        } else {
          // Enter Error/ Out of Bounds Log Mode, how?
          // Meant to filter out
        }
      }
    } else {
      /* Enter Unknown Error Mode
      Note it defaults to a single measurement, but no signal is sent to mention this.
      */
      runningAverage = static_cast<int>(analogRead(pin));
    }
  }
  outputAverage = static_cast<int>(round(runningAverage));
  return outputAverage;
}
```

Any tips on improving the code/logic are always appreciated too!

body:
Some findings:

* Your for loop iterates over 71 results, but your array has only the length 70.
You may overwrite variables in the memory behind the array.

* You can use `else` instead of `else if (i >= 70 * 0.1)` because it is just the negation of the `if (i < 70 * 0.1)`. In the else case `(i >= 70 * 0.1)` is always true.

What is the type of `myVariable`? If you assign incompatible types (signage or length) an over- or underflow can happen. `32767 = 2^15 - 1 = 0b0011111111111111` (14 bits on) that looks pretty much like an underflow and a conversion of incompatible types.

**EDIT:**

By a second read of your question I saw another possibility of failure:

You copy the bytes of a two byte signed integer into 2 bytes and send it to matlab.

    byte dataOut[2] = {
      highByte( LOG_myVariable ),
      lowByte( LOG_myVariable )
     };

Let's say you have a negative number in `LOG_myVariable`. In Memory this is represented with a one in the highest bit (MSBit) and the complementary bit string plus one (two's complement: See [Wikipedia](https://en.wikipedia.org/wiki/Signed_number_representations)).

An Example:

16 bit signed int -1 is represented as `0b1111111111111111` you split it in two bytes `0b11111111` and `0b11111111`. The you send it to Matlab.

Now it depends on how Matlab interprets the bytes. Are that unsigned int8 or signed int8? you combine the bytes like so:

     myVariableMATLAB = 256 * dataOut(1) + dataOut(2);

If Matlab interprets the bytes as unsigned  you get `256*(-1) + (-1) == -257` but that's not -1. And if it interprets the bytes unsigned it gets `256*255+255 == 65535` which is also not -1. I bet there is a negative number that gives you 32767.


message:
Can't get OC1B (pin 10) to output

I'm trying to get this program to use channel B for the output waveform using the phase correct PWM mode and using OCR1A as the top. With a 50% duty ratio I'm attempting to  get a 10 Hz freq. I'm able to adjust the OC1A (Pin 9) if I set TCCR1A to 0x43; but nothing comes from pin 10. Code:

    include "avr/io.h"

    void setup()
    {
     DDRB = 0x6; //set pins 9 and 10 as output

     /*set operation Toggle mode; WGM13:0 = 1011 phase correct PWM
    CS12:0 = 101 prescaler = 1024*/
     TCCR1A = 0x23;
     TCCR1B = 0x15;

     OCR1A = 0x187; //391 for 50% duty cycle
     TCNT1 = 0; //clear counter and update OCR1A
    }
    void loop()
    { }

body:
You are using Timer/Counter 1 in Fast PWM Mode with TOP set to OCR1A:
`OCR1A`only describes the number to what it counts up so, 0…391 in your case.
You have to define the duty cycle with `OCR1B`. 50% would be 195.


message:
My two ultrasonic sensors are reading inaccurately

I am having trouble getting two of my ultra sonic sensors to read accurate results in cm. I am using a HC-SR04 currently.

I get random numbers at different distances with an object in front (smooth cover book)

Test 1:
Real distance: 10 cm
Sensor 1: 0.00cm
Sensor 2: 82.42

Test 2:
Real distance: 10cm
Sensor 1: 92.11cm
Sensor 2: 95.03

Against the wall with no book:

Test 1:
Real distance: 10 cm
Sensor 1:0.00cm
Sensor 2: 13.20

Test 2:
Real distance: 10 cm
Sensor 1:24.37cm
Sensor 2:26.75

The numbers constantly fluctuate. I am trying to get accurate results.

I am not sure if the sensors are broken or if my code is incorrect.I appreciate any help.

Here is my set up: [![My setup[1]][1]

    #define trigPin1 13
    #define echoPin1 12
    #define trigPin2 11
    #define echoPin2 10

    float duration, distance, duration1, distance1, duration2, distance2;

    void setup() {
      Serial.begin (9600);
      pinMode (trigPin1, OUTPUT);
      pinMode (echoPin1, INPUT);
      pinMode (trigPin2, OUTPUT);
      pinMode (echoPin2, INPUT);

    }

    void loop() {

      FindRange(trigPin1, echoPin1);
      duration1 = duration;
      distance1 = distance;
      FindRange(trigPin2, echoPin2);
      duration2 = duration;
      distance2 = distance;
      Serial.print(distance1);
      Serial.print(" cm  ");
      Serial.print(distance2);
      Serial.println(" cm");
      delay(100);

    }

    void FindRange(int trigPin, int echoPin) {

      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);

      duration = pulseIn(echoPin, HIGH);
      distance = (duration / 2) * 0.0345;
      delay(100);

    }

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

body:
In the loop you trigger trgPin1 then trigPin2 but in the first range find you read echoPin2 instead of echoPin1.

    void loop() {

      FindRange(trigPin1, echoPin2);
      duration1 = duration;
      distance1 = distance;
      FindRange(trigPin2, echoPin2);
      duration2 = duration;
      distance2 = distance;
      Serial.print(distance1);
      Serial.print(" cm  ");
      Serial.print(distance2);
      Serial.println(" cm");
      delay(100);

    }

must be

    void loop()
    {
      FindRange(trigPin1, echoPin1);
      duration1 = duration;
      distance1 = distance;

      FindRange(trigPin2, echoPin2);
      duration2 = duration;
      distance2 = distance;

      Serial.print(distance1);
      Serial.print(" cm  ");
      Serial.print(distance2);
      Serial.println(" cm");

      delay(100);
    }


body:
The working principle of HC-SR04 is based the reflection of ultrasonic wave. Therefore, It measures distance inaccurately in the following case:

 - The obstacle is something that can **adsorbs the ultrasonic wave**. For example, cotton wool.
 - The obstacle is faced in non-90-degree. In this case, the obstacle may **reflect the ultrasonic wave to another direction**
 - The obstacle's surface can **diffuse the ultrasonic wave**

You can see the working principle of HC-SR04 [here][1].

One more thing: two ultrasonic sensor may interfere to each other if they work at the same time. Try to give delay(100); between two reads

    void loop()
    {
      FindRange(trigPin1, echoPin1);
      duration1 = duration;
      distance1 = distance;

      delay(100);

      FindRange(trigPin2, echoPin2);
      duration2 = duration;
      distance2 = distance;

      Serial.print(distance1);
      Serial.print(" cm  ");
      Serial.print(distance2);
      Serial.println(" cm");

      delay(100);
    }

  [1]: https://arduinogetstarted.com/tutorials/arduino-ultrasonic-sensor#content_about_ultrasonic_sensor


body:
I am not sure but may be it helps just by checking principle of working of this sensors as it is depicted for low range distance you must be carefull about reflection from other source of ultrasonic. I think it would be a good Idea to place a delay between these two module so to make sure it get less noise from each other

      FindRange(trigPin1, echoPin1);
      duration1 = duration;
      distance1 = distance;
      delay(1000);//add delay
      FindRange(trigPin2, echoPin2);
      duration2 = duration;
      distance2 = distance;
      delay(1000);//add delay
the other reason for getting zero may be your controller could not measure reflection from wall due to lowspeed sampling (if you are polling) or reading time with low precision so I have a suggestion for you if you are familiar with STM32 there is a built-in hardware implementation for measure time of pulse using timers called one-pulse mode it may helps you get precision you need
[![enter image description here][1]][1]

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


body:
I tested your code as it currently is with my own HC-SR04s and a clone Arduino Nano (since that is, what I have here currently). It works like a charm. The values are rather good, maybe accurate about +-1cm. I checked in the change between 10 and 70cm with my desk plate and a wall as obstacle. (I just looked, if the values are plausible. I didn't investigate thoroughly, how accurate the values are).

So I guess, that your sensors are broken.


body:
Where they are plugged in they won't work as the rows (like the other side) are connected. Example: [http://wiring.org.co/learning/tutorials/breadboard/imgs/breadboard-02.jpg][1]

They aren't connected to the other pins, and they are connected themselves.

[![Look at the connection][2]][2]

  [1]: http://wiring.org.co/learning/tutorials/breadboard/imgs/breadboard-02.jpg
  [2]: https://i.stack.imgur.com/7xeLq.png


body:
change the MCU, that arduino is a chinese version.
Use a original or other original board.

I had the same problem with two diferents projects, and it happend the same to me. One with ultrasonic and other with RF24 module. In both projects, some really extrange things happens. But when i change for one original arduino, everything works perfect.


message:
ESP8266 Arduino MQTT callback with dynamic topics

I have a program that depending on user input, it creates one or several objects that will publish data to a MQTT broker, each one with a different topic. This is already done. The ESP8266 also has subscribe itself to the same topics it publishes.
Now, the problem is that I have to create a dynamic callback in the ESP8266 to read the all the posible arriving topics to which the ESP8266 has subscribed and I am having trouble with that.

The callback function model is:

    void MQTTcallback(char* topic, byte* payload, unsigned int length) {

    // handle message arrived

    }

The possible topics can be:

ObjectTL/TL_1

ObjectTL/TL_2

ObjectTL/TL_3

...

ObjectTL/TL_X

The number (TL_X) depends of the user input I mention at the beginning.
Thanks!

body:
I think using sscanf may help you

    void MQTTcallback(char* topic, byte* payload, unsigned int length) {

      sscanf(data, "ObjectTL/TL_%d", dynamicTopicName);
      // handle message arrived
      your_dynamic_function(dynamicTopicName,byte* payload, unsigned int length)

    }


message:
C++ State Machine / Wpmf-convesion

I'm quite a newbie using C ++. I am trying to implement in C ++, the state machine described in this link for C language:
[https://barrgroup.com/Embedded-Systems/How-To/Coding-State-Machines][1].

I have created an Fsm class, which implements the behavior of the state machine, and a Machine class, whose methods will be the states.

The code works, but it generates a warning (-Wpmf-conversions) when I try to save the memory address of a Machine method, in `State state__`

    class Fsm
    {
    public:
     typedef void (*State)();
    private:
     State state__;
    public:
     Fsm(State state);
     void dispatch();
    };

    Fsm::Fsm(State state)
    {
     state__ = state ;
    } //Fsm

    void Fsm::dispatch()
    {
     (*state__)() ;
    }

    class Machine : public Fsm
    {
    public:
     Machine() : Fsm((State)&Machine::initial) {}       // ctor
    };

I'm using an Atmega2560, with AVR-GCC compiler.

  [1]: https://barrgroup.com/Embedded-Systems/How-To/State-Machines-Event-Driven-Systems

body:
A pointer to a member function is not allowed in C++. GCC *can* allow it, but moans at you because it's non-standard.

In C++ the normal way of dealing with the kind of thing you want is through class inheritance.

Typically you would create your base `Fsm` class that implements the basic functionality of your state machine control, then overlay over the top of that (create a new class that inherits the `Fsm` class) another class that implements your specific machine functionality.  You can declare functions in your base `Fsm` class that are *pure virtual* - that is, they exist, but have no body. It's then the job of the child class to actually implement that functionality.  The parent `Fsm` class then knows about those functions and can call them.

So you would have something like:

    class Fsm {
        public:
            void dispatch();
        protected:
            virtual void initial() = 0;
    };

    void Fsm::dispatch() {
        initial() ;
    }

    class Machine : public Fsm {
        protected:
            void initial() {
                 Serial.println("Here");
            }
    };

    Machine mach;

    mach.dispatch(); // --> "Here"

`Fsm` knows about `initial()`, but the function hasn't been further defined.  `Machine` implements `initial()`.  You then create an instance of `Machine` which contains everything needed.  Calling `dispatch()` runs the function in the `Fsm` parent class which then calls `initial()` in the child `Machine` class.


message:
Arduino IDE won't use selected port

I'm trying to program an ATtiny85, using an *AVRISP mkII* programmer (this one: https://www.amazon.de/dp/B00IYNAXUC/ref=cm_sw_r_sms_c_api_i_VXOWDb3H3N5ND) with the Arduino IDE (version 1.8.10 on Ubuntu 18.10). For the ATtiny, I've installed https://github.com/damellis/attiny using the board manager, as recommended in countless tutorials.

Now, everything seems to be recognized fine, and I've selected the programmers port in the IDE: `/dev/ttyACM0`.
But when I try to upload a sketch, the IDE instead trys to pass `usb` as the port to `avrdude`. This is only visble when enabling verbose output: (paths abbreviated)

    /home/[...]/avrdude -C/home/[...]/avr/etc/avrdude.conf -v -pattiny85 -cstk500v2 -Pusb -Uflash:w:/tmp/arduino_build_728460/sketch.ino.hex:i

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

             System wide configuration file is "/home/[...]/avrdude.conf"
             User configuration file is "/home/[...]/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

             Using Port                    : usb
             Using Programmer              : stk500v2
    avrdude: usbdev_open(): did not find any USB device "usb" (0x03eb:0x2104)

    avrdude done.  Thank you.

`usb` isn't even a selectable port in the IDE!

Simply pasting the avrdude command (first line in the output above) to a terminal and changing `usb` to `/dev/ttyACM0` makes it program the IC perfectly (but of course, that's a rather cumbersome workaround).

Also, selecting another programmer in the IDE (like AVR ISP, without the mkII) makes it use the correct port (but of course it won't work, since it's the wrong programmer).

Am I doing something wrong, or is this an actual bug in the Arduino IDE?

body:
I would say you have to select  the Arduino as ISP Programmer. Not the mkII ISP. Perhaps the attiny board library can handle connection to attiny dev boards over usb if you use the standard programmer. But that's just a very very rough guess. But selecting the Arduino as ISP is a requirement.

**Edit:**

No you can not use the Arduino as ISP if you use an STK500 programmer.

D. A. Mellis' tool is designed for an Arduino as a programmer.

But if your work around does the programming, the mkII is the right tool. You have to find out, how the IDE builds the CLI string to start `avrdude`.

The tool you installed contains a text file called `platform.txt`:

    name=ATtiny Microcontrollers

    tools.avrdude.path={runtime.tools.avrdude.path}
    tools.avrdude.erase.params.verbose=-v -v -v -v
    tools.avrdude.erase.params.quiet=-q -q
    tools.avrdude.erase.pattern="{cmd.path}" "-C{config.path}" {erase.verbose} -p{build.mcu} -c{protocol} {program.extra_params} -e -Uefuse:w:{bootloader.extended_fuses}:m -Uhfuse:w:{bootloader.high_fuses}:m -Ulfuse:w:{bootloader.low_fuses}:m

    tools.avrdude.bootloader.params.verbose=-v -v -v -v
    tools.avrdude.bootloader.params.quiet=-q -q
    tools.avrdude.bootloader.pattern="{cmd.path}" "-C{config.path}" {bootloader.verbose} -p{build.mcu} -c{protocol} {program.extra_params}

I would say the entry `tools.avrdude.bootloader.pattern` does the trick. Especially the variable `{program.extra_params}`. You have to find out how the IDE is building this variable. One of it's options must be `-P<Port>`. But why does the IDE use the value `usb` for `<port>`?

I'll try to find out. But I have no access to an IDE at the moment. If you (or someone else) find a solution before me, please add an answer and mark it as accepted, so I need not investigate further.


body:
You mean that the STK500 v2 programmer uses an emulated serial port
rather than direct USB? Then I guess there is a bug in the Arduino IDE.
The file `programmers.txt` [contains the following lines][programmers]
describing the programmer:

```text
avrispmkii.name=AVRISP mkII
avrispmkii.communication=usb
avrispmkii.protocol=stk500v2
avrispmkii.program.protocol=stk500v2
avrispmkii.program.tool=avrdude
avrispmkii.program.extra_params=-Pusb
```

You may locate this file in your Arduino installation and replace the
last line from this snippet by

```text
avrispmkii.program.extra_params=-P{serial.port}
```

If that works, it would be a good idea to submit a pull request with the
fix to the Arduino team.

Alternatively, you may try selecting “Atmel STK500 development board” as
a programmer. This is supposed to autodetect the version of the STK500
protocol, and uses the correct serial port.

**Edit**: you may also have to replace

    avrispmkii.communication=usb

by

    avrispmkii.communication=serial

C.f. [this bug report][issue258], which seems to cover the exact issue you are
facing.

[programmers]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.1/programmers.txt#L8-L13
[issue258]: https://github.com/arduino/ArduinoCore-avr/issues/258


message:
Is it possible to load both the arduino bootloader and a sketch onto an atmega328p via icsp?

i am familiar with uploading an arduino bootloader onto an atmega328p using another arduino via the arduino IDE. i have also installed software 'sketches' using that process which i believe leaves out the bootloader(meaning one wouldnt be able to upload new sketches in the future via usb). my question is: is it possible to load both the bootloader and a software program onto the chip via icsp? many thanks in advance.

body:
The Arduino builder creates for AVR boards not only hex file for the sketch, but it creates a combined hex with bootloader and sketch too. It is for example for Blink.hex a Blink_with_bootloader.hex. If you use in IDE the "Export compiled binary" command in Tools menu, the builder puts the hex files next to ino file in your sketch folder.

If you want the command "Upload using programmer" to upload hex with the bootloader, modify in platform.txt the `tools.avrdude.bootloader.pattern` key to use `"-Uflash:w:{build.path}/{build.project_name}_with_bootloader.hex:i"`


message:
Do some arduino pins give signals when the controller starts?

For example, on the ESP32 board there are several contacts that can issue pulses when the controller starts, which is connected with the operation of the chip itself. It is not recommended to connect devices that respond to input signals from the ESP to these contacts.

Tell me, are there any contacts on the Arduino UNO (Atmega328P) that give out any impulses at startup?

In particular, it is important for me to know about the following contacts:

 1. PB1 (9 pin)
 2. PD4 (4 pin)
 3. PD5 (5 pin)

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

Thank you!

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

body:
Most Arduino boards come with a bootloader of some form.  This bootloader may do things with IO pins. However apart from that, no, nothing else happens to any IO pins.

The bootloader may:

* Flash pin 13 (built in LED)
* Configure and communicate on pins 0/1 (UART)

With no bootloader then absolutely nothing happens on any IO pins.


message:
multiple invdividual servo controll arduino

I want to declare 11 servo motors in my code. Is there a better way to do that than just declare everyone under each other. The reason is that i have a code that will set the rotation for one at a time. The best would be a list so i could iterate over which server i want to move.
```C
Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4;
Servo servo5;
Servo servo6;
//etc
void moveServo(int n,int deg){
  servo[n].write(deg); //something like this
}

```

body:
Consider using a specific processor / Arduino-board.  In [this thread][1] there are references to using the Arduino 1280 board with the [Arduino Servo Library][2] to control up to 48 servos using a combination of hardware and software.

In C++ when you "instantiate" a class you are making good use of memory space as you do not really create duplicate code. All you create are copies of the variables necessary to support each instantiation. There should only be one copy of the code in memory.  To iterate over each instantiation consider using a [switch/case statement][3].

  [1]: https://forum.arduino.cc/index.php?topic=60328.0
  [2]: https://www.arduino.cc/en/reference/servo
  [3]: https://www.arduino.cc/reference/en/language/structure/control-structure/switchcase/


body:
First: Your code would not work, since `servo` is not defined and thus not an array to iterate over. You would need to first define the array and then fill it with Servo elements.

    Servo servo[11];

    void setup(){
        for(int i=0;i<11;i++){
            servo[i] = new Servo();
        }
    }

The different `Servo` objects are created dynamically. In most cases it is bad to use dynamic allocation on a microcontroller with litte RAM, but it is ok, when you only use it once at the start.


message:
Taking data from main 120V 50/60Hz power

How can I take data from my house main power and reconstruct it signal? I used an transformer and an inverter amplifier to low voltage to 5 volts and read it with A0 analog pin, but I got a very strange datan and just a few numbers

`data = analogRead(A0);
 Serial.println(data);`

body:
The Serial output on an Arduino is quite slow. By printing your output, you will slow down the readings so much that it will appear to be nonsense.

You should collect a series of readings into a C array of floats in RAM, stop recording, and then log that array of values.

Note that you don't have a lot of RAM to work with on most Arduinos, so you will only be able to record a small number of values. A Mega 2560 has a lot more memory than others (8KB). It's still not a lot, but better than other boards. One of the ARM based Arduinos will have both a much faster processor and a lot more RAM.


message:
How to check if a LED is on?

I have a circuit board / device that can be in different states. It indicates in which state it is by turning on one of three LED's. Now I want to use an ESP8266 to tell me (over the network) the current state. What kind of circuit would I need for this? (I have thought about using photodiodes, but I would much rather solder something directly to the board)

body:
If the device turning the LEDs on / off runs on 3.3 Volts (has ground to 3.3 Volts outputs), then you might consider directly connecting the 3.3 Volt outputs to the GPIO pins of the ESP8266.  If the device turning the LEDs on / off runs on higher voltages consider either using the appropriate [level shifter][1] or the appropriate [optical isolator][2]:

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

  [1]: https://en.wikipedia.org/wiki/Level_shifter
  [2]: https://en.wikipedia.org/wiki/Opto-isolator
  [3]: https://i.stack.imgur.com/3YHEd.png


message:
Detecting how many button presses(single tap, double tap etc) with two simultaneous buttons

noob here

So what I am trying to do is output a different number depending on the number of button presses e.g. for 1 button press it should output 1 and so forth. After that I only really want the outputs for 1 to 4 presses. I am using these inputs for a game.  Right now, it does work and counts up until 4 and then resets back to 0. The problem that I am having is it continues after 1 click to 2 clicks; what I want it to do is count 1 click when its clicked once, twice when its clicked twice etc. I am trying to use a debouncing code to distinguish between single tap, double tap, triple tap etc
@VE7JRO kindly provided a great solution to this problem, albeit it was for one button. I am trying to adjust the code to accommodate 2 separate buttons (on separate pins), but it is giving me an error.

This is the code:

    #include <Bounce2.h>

    // Connect both buttons in series with one connection
    // to GND and the other to a digital pin.
    const int buttonPin1 = 2;
    const int buttonPin2 = 3;

    class Button
    {
      private:

        int m_buttonPin1;
        int m_buttonPin2;
        int m_counter;
        unsigned long m_buttonPressTimeout;
        unsigned long m_previousMillis;

      public:

        Button(int button):
          m_buttonPin1(buttonPin1),
          m_buttonPin2(buttonPin2),
          m_counter(0),
          m_buttonPressTimeout(1500), // Button press timeout 500 ms.
          m_previousMillis(0){}

        void Update()
        {
          int valA = digitalRead(button1); // read button stateint
          int  valB = digitalRead(button2); // read button state
           if (valA == LOW &&valB == LOW)
           {
          if(m_counter > 0 && millis() - m_previousMillis >= m_buttonPressTimeout)
          {
            Serial.print("Count from Update() just before it's re-set to 0 = ");
            Serial.println(GetCounter());
            m_counter = 0;
          }
        }

        void IncrementCounter(){
          m_counter++;
          if(m_counter > 4){m_counter = 4;}
          if(m_counter == 1){
            m_previousMillis = millis();
          }
        }

        byte GetCounter(){
          return m_counter;
        }

    };

    Bounce button1Debouncer = Bounce();
    Bounce button2Debouncer = Bounce();
    Button MyButton(buttonPin1);
    Button MyButton(buttonPin2);

    void setup(){

      Serial.begin(9600);

      pinMode(buttonPin1, INPUT_PULLUP);
      button1Debouncer.attach(buttonPin);
      button1Debouncer.interval(5);
      pinMode(buttonPin2, INPUT_PULLUP);
      button2Debouncer.attach(buttonPin);
      button2Debouncer.interval(5);

    }

    void loop(){

      // Call the Update function as fast as possible.
      MyButton.Update();

      // Button pressed.
      if(button1Debouncer.update() && button2Debouncer.update())
      {
        if(button1Debouncer.fell() && button2Debouncer.fell()){
          MyButton.IncrementCounter();
          Serial.print("Count from Button Debouncer = ");
          Serial.println(MyButton.GetCounter());
        }
      }

    }
    }
The error is: "'buttonPin1' is not a type", I do not understand this error as it didn't give that error for when a single button was used.

body:
It is likely you are experiencing problems associated with button [contact bounce][1]. This is where the processor is so fast that it "sees" the button make several contacts when the user only intends for 1 contact to be seen by the program. Consider using [this button de-bounce library][2] instead of reading the state of the buttons directly in the sketch.

The code for the above debounce Arduino library is [hosted here at github.com][3]. In general, people using github.com will have an "example" folder along with the source code and documentation folders.  The [debounce Arduino library example folder is here][4].  There are about half a dozen Arduino sketch examples including [this 2 button example][5] which might be used as the starting point for the project in the question.

There may be a logic problem in the code when interpreting the number of button presses into "a", "b", "c" & "d".  The [modulo operator "%"][6] is used.  And in the first test, the number of button presses % 1 is tested. If the result is zero the test is true.  As any number % 1 has no remainder this test will always be zero and therefor always true.  As all other tests are nested inside "else" statements none of the other tests will be executed.  Instead consider using a [switch / case statement][7] where the code switches on the number of button presses and the case statements are "case 1:", case 2:", "case 3:" & "default:".  It is good coding practice to always have a "default:" case in a switch statement.  Here we use "default:" instead of "case 4:". After using the value representing the number of button presses, always remember to clear this value before the next iteration.  Remember, any "global" values (values defined outside a function) will retain their values between calls to that function. Any "local" value (values defined inside a function) will not retain their values and need to be initialize each time they are used.

  [1]: https://en.wikipedia.org/wiki/Switch#Contact_bounce
  [2]: https://playground.arduino.cc/Code/Bounce/
  [3]: https://github.com/thomasfredericks/Bounce2
  [4]: https://github.com/thomasfredericks/Bounce2/tree/master/examples
  [5]: https://github.com/thomasfredericks/Bounce2/blob/master/examples/bounce2buttons/bounce2buttons.ino
  [6]: https://www.arduino.cc/reference/en/language/structure/arithmetic-operators/modulo/
  [7]: https://www.arduino.cc/reference/en/language/structure/control-structure/switchcase/


body:
You SHOULD pay attention to the following issues:

**1. Floating input problem:**

***Symptom:*** the reading value from the input pin is not matched with the button's pressing state.

***Cause:*** input pin is NOT used pull-up or pull-down resistor.

***Solution:*** Use pull-up or pull-down resistor. See [Arduino Button (with pull-up/pull-down)][1]

**2. Chattering phenomenon**

It should be considered in only some application that needs to detect exactly number of the pressing.

***Symptom:*** Button is pressed one, but Arduino code detects several times.

***Cause:*** Due to mechanical and physical issues, the state of the button (or switch) is quickly toggled between LOW and HIGH several times

***Solution:*** Debounce. See [Arduino Button Debounce][2]

  [1]: https://arduinogetstarted.com/tutorials/arduino-button
  [2]: https://arduinogetstarted.com/tutorials/arduino-button-debounce


body:
Your updated code has lots of problems. To do button debouncing, try something like this:

    //Adjust debounceTime as desired. Shorter times will make fore faster button
    //response, but make the debouncing less effective. 50 is 1/20th of a second.
    #define debounceTime 50

    unsigned long nextButtonCheckTime = 0;
    bool buttonAState = false;
    bool buttonBState = false;

    void loop() {
      //Only check the buttons if the debounce time has passed
      if (millis() > nextButtonCheckTime)
        bool newButtonAState = digitalRead(buttonAPin) == LOW;
        bool newButtonBState = digitalRead(buttonBPin) == LOW;
        //If one or both buttons have changed state
        if  (buttonAState != newButtonAState || buttonBState != newButtonBState)) {
          nextButtonCheckTime = millis() + debounceTime;
          buttonAState = newButtonAState;
          buttonBState = newButtonBState;
          //Handle change of button state
        }
      }
    }

That is pseudocode. It almost certainly contains syntax errors. You should use it as a guide, and rewrite it to suit your needs. Do **not** say "I copied your code into my sketch and it won't compile."


body:
If it’s possible to connect the 2 buttons in series, then this sketch may give you the desired results.

    #include <Bounce2.h>

    // Connect both buttons in series with one connection
    // to GND and the other to a digital pin.
    const byte buttonPin = 2;

    class Button{

      private:

        byte m_buttonPin;
        byte m_counter;
        unsigned long m_buttonPressTimeout;
        unsigned long m_previousMillis;

      public:

        Button(byte buttonPin):
          m_buttonPin(buttonPin),
          m_counter(0),
          m_buttonPressTimeout(500), // Button press timeout 500 ms.
          m_previousMillis(0){}

        void Update(){
          if(m_counter > 0 && millis() - m_previousMillis >= m_buttonPressTimeout){
            Serial.print("Count from Update() just before it's re-set to 0 = ");
            Serial.println(GetCounter());
            m_counter = 0;
          }
        }

        void IncrementCounter(){
          m_counter++;
          if(m_counter > 4){m_counter = 4;}
          if(m_counter == 1){
            m_previousMillis = millis();
          }
        }

        byte GetCounter(){
          return m_counter;
        }

    };

    Bounce buttonDebouncer = Bounce();
    Button MyButton(buttonPin);

    void setup(){

      Serial.begin(9600);

      pinMode(buttonPin, INPUT_PULLUP);
      buttonDebouncer.attach(buttonPin);
      buttonDebouncer.interval(5);

    }

    void loop(){

      // Call the Update function as fast as possible.
      MyButton.Update();

      // Button pressed.
      if(buttonDebouncer.update()){
        if(buttonDebouncer.fell()){
          MyButton.IncrementCounter();
          Serial.print("Count from Button Debouncer = ");
          Serial.println(MyButton.GetCounter());
        }
      }

    }

**EDIT**

Based on your last update to the question:

> I am trying to adjust the code to accommodate 2 separate buttons (on separate pins), but it is giving me an error.

I have updated the sketch to use 2 buttons on separate digital pins.

    #include <Bounce2.h>

    // Connect each button with one connection
    // to GND and the other to a digital pin.
    const byte buttonPin = 2;
    const byte buttonPin2 = 3;

    class Button{

      private:

        byte m_buttonPin;
        byte m_counter = 0;
        unsigned long m_buttonPressTimeout;
        unsigned long m_previousMillis;

      public:

        Button(byte buttonPin):
          m_buttonPin(buttonPin),
          m_counter(0),
          m_buttonPressTimeout(750), // Button press timeout in ms.
          m_previousMillis(0){}

        void Update(){
          if(m_counter > 0 && millis() - m_previousMillis >= m_buttonPressTimeout){
            Serial.print("Count from Update() just before it's reset to 0 = ");
            Serial.println(GetCounter());
            m_counter = 0;
          }
        }

        void IncrementCounter(){
          m_counter++;
          if(m_counter > 4){m_counter = 4;}
          if(m_counter == 1){
            m_previousMillis = millis();
          }
        }

        friend void IncrementCounter(Button&);

        void IncrementCounter(Button&){
          IncrementCounter();
        }

        byte GetCounter(){
          return m_counter;
        }

    };

    Bounce buttonOneDebouncer = Bounce();
    Bounce buttonTwoDebouncer = Bounce();
    Button ButtonOne(buttonPin);
    Button ButtonTwo(buttonPin2);

    void setup(){
      Serial.begin(9600);
      pinMode(buttonPin, INPUT_PULLUP);
      pinMode(buttonPin2, INPUT_PULLUP);
      buttonOneDebouncer.attach(buttonPin);
      buttonTwoDebouncer.attach(buttonPin2);
      buttonOneDebouncer.interval(25);
      buttonTwoDebouncer.interval(25);
    }

    void loop(){

      // Call the Update function as fast as possible.
      ButtonOne.Update();
      ButtonTwo.Update();

      // Button one pressed.
      if(buttonOneDebouncer.update()){
        if(buttonOneDebouncer.fell()){
          if(digitalRead(buttonPin2) == 0){
            ButtonOne.IncrementCounter();
          }
        }
      }

      // Button two pressed.
      if(buttonTwoDebouncer.update()){
        if(buttonTwoDebouncer.fell()){
          if(digitalRead(buttonPin) == 0){
            ButtonOne.IncrementCounter(ButtonTwo);
          }
        }
      }

    }


message:
Is there some better documentation somewhere for Arduino classes and API's?

For example, it looks like Serial extends HardwareSerial, which extends Stream, which extends Print. But I don't think you can figure this out by reading the reference documentation on https://www.arduino.cc/ and it doesn't appear that you can easily navigate the class hierarchy in the Arduino IDE. They seem to go out of their way to hide the class hierarchy?

I guess I'm spoiled by modern languages that have automatically generated documentation, but it seems like there should be a more complete reference somewhere?

body: What I did/do when loading a new core is generating a [doxygen](https://www.doxygen.nl) visualisation help class hierachy in HTML. Although most of the core libs have no detailed doxygen documenation the [dot/graphviz](http://www.graphviz.org/) solves the problem without installation of other IDEs (which also have their specific problems, or need a lot of learning). <br>As an added bonus I can document my source code in a clean and transparent way available in most IDEs and OS.


message:
How to document a custom library in Arduino

I have created my own library and it is working flawlessly. Now I want to add some documentation to it that the Arduino IDE can understand.

For the functions from the Arduino IDE itself like `delay(ms)` you can right click them and then select `Find in Reference`. How can I add this feature to my own library?

body:
Arduino uses the [keyword.txt file][1] to highlight words and to define a reference page to keywords. But the reference page must be in `reference` folder of IDE installation and the keyword.txt contains only a filename, not the path.

> REFERENCE_LINK This field specifies the Arduino Language Reference page to open via Right Click > Find in Reference or Help > Find in Reference when the cursor is on that keyword. Generally it does not make sense to define the REFERENCE_LINK field for 3rd party library keywords since they are not likely to be in the Arduino Language Reference.

I have a library which implements WiFiClient and WiFiServer like the Arduino WiFi library, so I can link in keywords.txt to Arduino reference like this:

    WiFiClient KEYWORD2 WiFiClient
    WiFiServer KEYWORD2 WiFiServer
    WiFiUDP  KEYWORD2 WiFiUDPConstructor

The names used are names of html files in `Arduino\reference\www.arduino.cc\en\Reference`.

  [1]: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification#keywords


body:
OK, time for my most comprehensive answer on StackExchange so far (tanks to @Juraj for helping out with this).

To demonstrate all the steps needed for this, this answer will use an example library that will be called `Foo`.

Here we go:

To add documentation to your library that the Arduino IDE can work with, you first need to place your library in the correct directory. Thats either in your `library` folder in your `sketchbook` folder (you can locate it by selecting `File>Preferences>Sketchbook location`, by default this is

    C:\Users\YourUsername\Documents\Arduino\libraries

or

    InstallationDirectoryOfYourIDE\portable\sketchbook\libraries

if you are using a portable installation) or in

    InstallationDirectoryOfYourIDE\libraries

In which of the two places you put your library is up to you, both work (except if you put in both places at the same time). You should keep this in mind though: If you put your library in the `libraries` folder of your sketchbook, only you will have access to that library. If there are other users on the same PC that shall be able to use your library, you have to put in in the general libraries folder (if you don't have access to that folder because it belongs to another user and you are not the admin, then too bad, sorry ;).

Your library has to contain at least a file `Foo.h` which can be located directly in the folder of your library (old standard) or in a subfolder `src` in your library folder (up to date standard). What the file contains is for the sake of this example absolutely arbitrary (e.g. just leave it empty).

Next you need a valid `library.properties` file for your library. You can create and edit it with any text editor like notepad. This file has to be placed directly into the folder of the library.

Here is a bare minimum example for this file that works:

> name=Foo

> version=1.0.0

> author=Your name

> maintainer=Your name

> sentence=Something

> paragraph=Whatever

> url=http://example.com

More information on how this file works (and other things to consider when creating a library) can be found at the [Arduino Library Specification][1].

Now we can specify which words the IDE shall highlight and which of them shall link to which reference page (to make sure that this works in principle it is not necessary to create your own `.html` files yet). To do this, create a file `keywords.txt` in the folder of your library. In it you write something like this:

    foo KEYWORD2 Foo

In this example `foo` is the keyword that will be highlighted in the IDE (and on right click present the option `Find in Reference`). `KEYWORD2` specifies how exactly `foo` will be highlighted (colour, boldness, etc.), in this case it will appear like normal text in orange (once again, see the [Arduino Library Specification][1] for more details on this). `Foo` is the name of the `.html` file (without the extension) that is opened when you right click `foo` in the IDE and select `Find in Reference`. It has to be located in this folder:

    InstallationDirectoryOfYourIDE\reference\www.arduino.cc\en\Reference

The three words are separated by true `tab`s (not multiple `space` characters). Before creating your own `.html` file you can just copy one of the files there and rename it to `Foo`. Note that your library doesn't have to contain anything else besides the three mentioned files and some file in the reference folder for this to work. At this point you should restart your IDE and check whether your keyword `foo` is highlighted and offers the option `Find in Reference` when you right click it. If so, success! You can now move on to create your own `.html` file to put in the reference folder.

You could start by just changing one of the existent files to fit the style of the Arduino API, but you could also create your entirely own files. The probably best option however is to write your library according to doxygen standards and then let doxygen do the work for you creating the file automatically.

Just one more thing to be mentioned: This method works for any keywords that are used in the way `yourKeyword` or `something.yourKeyword`, but not `Something::yourKeyword` (this is how you would use a static function or variable in your library). According to @Juraj this is something caused by the IDE. There is a workaround for this though: Replace each line in the `keywords.txt` file

    yourKeyword KEYWORDX ReferenceFile

with

    yourKeyword KEYWORDX ReferenceFile
    YourLibrary::yourKeyword KEYWORDX ReferenceFile

This way `yourKeyword` will be highlighted as you would expect it but occurrences like `YourLibrary::yourKeyword` will also bring up the option `Find in Reference` when right clicked.

That's it for today. Thanks and bye bye!

  [1]: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification


message:
What are exactly XTAL1 and XTAL2 pins in Arduino Uno/Nano?

I know that the blow red encircled component is the 16MHz Crystal Oscillator (XTAL):

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

But PB6 and PB7 pins are called XTAL1 and XTAL2 pins which are not accessible by the Arduino board.

Are these pins where the 16MHz crystal oscillator is connected. But if so why are they two of them? I searched net but couldn't find explicit information about these.

How many clocks in total this board have?

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

body: Yes they connect to the crystal. There's two of them because a crystal has two pins.


body:
The Crystal in Red is for the Atmega16U2 that manages the USB interface with its high speed connection to the PC (12 MHz for USB2 I think).

The Resonator in Yellow is for the Atmega328P.  It is less precise than the crystal oscillator.

PB6 and PB7 are dedicated to the external crystal or resonator by the fuse settings used for Arduino.

You can read more about the XTAL1, XTAL2 pins and the fuses from the device datasheet

https://www.microchip.com/wwwproducts/en/ATMEGA328P

You can connect a crystal to the pins, but you will also need 22pF caps to connect from the pins to Gnd. And remove the resonator.  Current Uno layout does not really support making those connections.


body:
XTAL1 is the input and XTAL2 is the output of the oscillator.
Using 8MHz internal RC oscillator instead of the crystal, you can use PB6 and PB7 as I/O, like other I/Os.


message:
Arduino - Extracting Multiple Strings from Serial Read

I am trying to write an Arduino code that reads a long string, example <11,22,33>, through the Serial Monitor and then stores the 11,22, and 33 into separate bins of a matrix array.

So the user could input: <11,22,33>
And the code would store the three entries into a matrix of strings:

    matrix[0]=11;

    matrix[1]=22;

    matrix[2]=33;

Whenever I try to run the code the only result that's outputted is

    matrix[0]=33;

    matrix[1]=33;

    matrix[2]=33;

But the strange part is when I put print commands after the Matrix[i]=data line in the code, the output shows the correct numbers! I'm not sure where the issue is and if somehow I made all entries the final entry. Any help is appreciated!

    // Example 3 - Receive with start- and end-markers

    const byte numChars = 32;
    char data[numChars];    //data entry for appending Serial data
    char *matrix[numChars]; //matrix of data entries
    static byte i=0;  //matrix index

    boolean newData = false;

    void setup() {
        Serial.begin(9600);
        Serial.println("<Arduino is ready>");
    }

    void loop() {
        recvWithStartEndMarkers();
        showNewData();
        Serial.println(matrix[1]);
    }

    void recvWithStartEndMarkers() {
        static boolean recvInProgress = false;
        static byte ind = 0;  //data index
        char startMarker = '<';
        char midMarker = ',';
        char endMarker = '>';
        char rc;    //Serial read character

        while (Serial.available() > 0 && newData == false) {
            rc = Serial.read();

            if (rc == startMarker) {
                recvInProgress = true;  //if startMarker arrives then enter secondary if below
            }

            else if (recvInProgress) {  //begin appending characters if startMarker activated switch

                if (rc == midMarker) {  //if midMarker is reached...
                    matrix[i]=data;     //append data to i-th entry in matrix
                    i++;                //add to matrix index
                    data[0] = '\0';     //clear data
                    ind = 0;            //reset data index
                }
                else if (rc == endMarker) {     //if endMarker is reached...
                    matrix[i]=data;             //append data to last entry in matrix (ensures last data is appended)
                    data[ind] = '\0';           // terminate the string
                    recvInProgress = false;
                    ind = 0;                    //reset counters for data and matrix
                    i = 0;
                    newData = true;
                }
                else {
                    data[ind] = rc;           //eppend Serial character into data
                    ind++;                    //add to data index
                    if (ind >= numChars) {
                        ind = numChars - 1;
                    }
                }
            }
        }
    }

    void showNewData() {
        if (newData == true) {
            Serial.print("This just in ... ");
            Serial.println(matrix[0]);
            Serial.println(matrix[1]);
            Serial.println(matrix[2]);
            newData = false;
        }
    }

body:
You define pointers for each value as :

    char *matrix[numChars]; //matrix of data entries

However, in all cases you let it point to data:

    matrix[i]=data;

Than you set the value starting from that address. So what happens is after you read the first value (11), and `matrix[0]` contains '11', than `matrix[1]` points to the same data which you write the value 22 to. And you do the same for 33. So you end up with 3 pointers to the same address (`data`) containing/overwriting the last value (33). So you get three times 33.

You should either continuing writing the string in `data` and refer to the correct part inside the string `data`.  If you want to do a `Serial.println`, you have to end the strings with `\0`, so the string `data` and matrix references should be:

    index:    0   1  2  3  4  5  6  7  8
    data:     1   1 \0  2  2 \0  3  3 \0
    matrix:  [0]       [1]      [2]
    i:        0         1        2

It will help if you change

    matrix[i]=data;

to

    matrix[i]=&(data[ind]);


message:
Including keypad library removes sound from my piezo element

I am using the keypad library to include keypad and input numbers. when a specific number is entered a sound must be made.
However when I input using the serial monitor , sound is working. But when I include keypad , it only inputs numbers but not sound.
Help please , how can I make both work?
Thanks.

`#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte rowPins[ROWS] = {12, 11, 10, 9}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {8,7,6,5}; //connect to the column pinouts
`

Then I get the input from keypad and store as result

`char guess = 'n';
 char keypressed = keypad.getKey();
  if (keypressed != NO_KEY) {
    char guess = keypressed;`

in void loop, it get result(key from keypad) and must play it: Tried separate sketch it works. but with keypad only input is , not sound.

` Serial.print("You guessed:");
      Serial.println(guess);
      result = checkYourself(guess);
      Serial.println(result);
      playSound(result);`

check yourself takes in guess from keypad ,checks then returns as result.
play sound function works when tried in another sketch( sorry not posting too much code its very long)

body: Please make sure that the pin connected to piezo does NOT used by keypad


body: I was able to solve it , piezo dissent work in pin 9 but works when connected to pin 13.


message:
Common button on two Arduinos and two computers

We have two computers giving two presentations that need to    be triggered in sync. I know how to send the space button via Arduino, but I want to check it will be safe for the computers. If each Arduino is connected to their computer via USB, both data pins togeather and both grounds togeather (not sure if I can find a dt momentarily push button in two days). Is there anything I should keep in mind incase both sides are not at the same voltage as eachother?

body:
The ground of both computers are connected also via their power lines. You get a ground loop that *might* result in malfunctions and/or defects.

Think about using a galvanically separated connection, for example via an optocouple.


body:
As long as you don't have to send anything from the pcs to the arduinos (or at least not with both) you can simply connect the arduinos TX with both pc's RX. This way you need only one arduino. Use series resistors (1k) to handle voltage differences between the pcs.
If you need two arduinos you're fine without galvanic isolation, but I recommend series resistors on the reading gpios as well (just in case you configure the ports as outputs accidentially). In case you use laptops which usually don't have PE, you have to connect the arduinos grounds as well.


message:
SD Card and Lora module arduino uno

Background: When working on the 2 modules separately they were working perfectly.

Problem: In the code attached we tried integrating them but Lora wouldn't receive any data unless we commented out parts of the SDC function. Is there a fix to this?

This is where the problem occurs:

```
Serial.print("Data received: ");
 Serial.print(received);

 if(received=="ANEMO"){
```
No matter how much we feed it with TRUE data from another Lora with these codes it simply shows blank and false.

Please Help this poor lamb. This for our school project. Hopefully, you can spare me some of your time. Thank you so much in advance.

for the CS pins:
Lora: pin 10,  SD: pin 5

other SPI pins follow the standard pins.

PS: In the code, we have commented out some of the lines within the SDC function as based on our observation:
```
myFile = SD.open("HG.txt", FILE_WRITE);
   myFile.close();
```
These 2 lines are the ones causing our Lora to not display the data it is receiving in the (String receive variable).

Thank you, good sir/ma'am, once again hopefully you can assist me.

Here is the complete code:

```
#include <SPI.h>
#include <SD.h>
#include <RH_RF95.h>
#define RFM95_CS 10
#define RFM95_RST 9
#define RFM95_INT 2
#define RF95_FREQ 868.0
RH_RF95 rf95(RFM95_CS, RFM95_INT);
unsigned long millisecs;
int cnt;
float valu;
String jh;
int code=1;
String received;

File myFile;

void setup(){
 Serial.begin(115200);
 if (!SD.begin(5)) {
    Serial.println("Card failed, or not present");
    while (1);
  }
  else{
  Serial.println("card initialized.");
  }

  delay(100);

 pinMode(RFM95_RST, OUTPUT);
 digitalWrite(RFM95_RST, HIGH);
 while (!Serial);
 Serial.println("Arduino LoRa RX Test!");
 digitalWrite(RFM95_RST, LOW);
 delay(10);
 digitalWrite(RFM95_RST, HIGH);
 delay(10);
 while (!rf95.init()) {
 Serial.println("LoRa radio init failed");
 while (1);
 }
 Serial.println("LoRa radio init OK!");
 if (!rf95.setFrequency(RF95_FREQ)) {
 Serial.println("setFrequency failed");
 while (1);
 }
 Serial.print("Set Freq to: "); Serial.println(RF95_FREQ);
 rf95.setTxPower(23, false);
}

void lorA(){
  while(code==1){
if (rf95.waitAvailableTimeout(1000)){
 Serial.println("dayun ");
 uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
 uint8_t len = sizeof(buf);
 if (rf95.recv(buf, &len)){
 cnt++;
 Serial.print("Data number: ");
 Serial.println(cnt);
 received=(char*)buf;
 Serial.print("Data received: ");
 Serial.print(received);

 if(received=="ANEMO"){
 uint8_t data[] = "And hello back to you";
 rf95.send(data, sizeof(data));
 rf95.waitPacketSent();
 Serial.println("Sent a reply");
 code=0;
 }
 }
 else{
 Serial.println("Receive failed");
 }
 }
 }
 }

void SDC(){
  while(code==0){
  Serial.println("SDC");
//  File dataFile = SD.open("HG.txt", FILE_WRITE);
//  String dataString="Hans";
//  if (dataFile) {
//  dataFile.println(dataString);
//  dataFile.close();
//    Serial.println("closed");
//    Serial.println(dataString);
    code=1;
//  }
//  else {
//    Serial.println("error opening datalog.txt");
//  }

  }
  }

void loop(){
  Serial.println("loop");
  lorA();
  Serial.println("mid");
  SDC();
}
```

body:
all of your problem can be solved through a simple trick ... Just follow it...

1. Use Sdfat library insted of SD
2. just follow SPI datasheet..

follow below code ... it works with LORA AND SD both together

    ...

    #include <SdFat.h>
    #include <SPI.h>
    #include <RHReliableDatagram.h>
    #include <RH_RF95.h>

    SdFat sd;
    SdFile myFile;

    #define chipSelect 4

    #define RFM95_CS 10 //
    #define RFM95_RST 9
    #define RFM95_INT 2

    // Singleton instance of the radio driver
    RH_RF95 rf95(RFM95_CS,RFM95_INT);
    //RH_RF95 driver(5, 2); // Rocket Scream Mini Ultra Pro with the RFM95W

    // Class to manage message delivery and receipt, using the driver declared above
    RHReliableDatagram manager(rf95, 2);

    void setup() {

      Serial.begin(9600);
      while (!Serial) {}  // wait for Leonardo

      delay(100);

      // Initialize SdFat or print a detailed error message and halt
      // Use half speed like the native library.
      // change to SPI_FULL_SPEED for more performance.
      pinMode(RFM95_CS, OUTPUT);
      digitalWrite(RFM95_CS, HIGH);
      digitalWrite(4, LOW);

      if (!sd.begin(chipSelect, SPI_HALF_SPEED)) sd.initErrorHalt();

    /*

    /*
     * //Open file and write  ...
     *
      // open the file for write at end like the Native SD library
      if (!myFile.open("mrinmoy.txt", O_RDWR | O_CREAT | O_AT_END)) {
        sd.errorHalt("opening test.txt for write failed");
      }

      // if the file opened okay, write to it:
      Serial.print("Writing to test.txt...");
      myFile.println("testing 1, 2, 3.");

      // close the file:
      myFile.close();
      Serial.println("done.");
      */

      /*
      // open the file for reading....

      if (!myFile.open("mrinmoy.txt", O_READ))
      {
        sd.errorHalt("opening test.txt for read failed");
      }

      Serial.println("mrinmoy.txt:");

      // read from the file until there's nothing else in it:
      int data;

      while ((data = myFile.read()) >= 0) Serial.write(data);
      // close the file:
      myFile.close();
      */

      // manual reset
      digitalWrite(RFM95_RST, LOW);
      delay(10);
      digitalWrite(RFM95_RST, HIGH);
      delay(10);

      digitalWrite(RFM95_CS, LOW);
      digitalWrite(4,HIGH);

      while (!manager.init()) {
        Serial.println("LoRa radio init failed");
        while (1);
      }
      Serial.println("LoRa radio init OK!");

     // digitalWrite(RFM95_CS, LOW);

    }

    void loop()
    {
       uint8_t data[] = " Hi.. This is node 1.";
     //   unsigned char sd_data[50];
    // Dont put this on the stack:
     // uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
       uint8_t buf[50];
      // nothing happens after setup

      //LoRa.setPins( LoRa_CS, LoRa_RST, DI0 );
      digitalWrite(4,HIGH);    //  deselet SD Card SPI
      digitalWrite(RFM95_CS, LOW);    //  SELECT (low) LoRa SPI
      SPI.begin();

      // Send a message to manager_client
      if (manager.sendtoWait((uint8_t*)data,sizeof(data),1))
      {
        Serial.print("successfully sent to: ");
        Serial.println(1);
      }
      else
      {
        Serial.println("send failed");
      }

      // receiver ....

       // Now wait for a reply from the server
       uint8_t len = sizeof(buf);
       uint8_t from;

       if (manager.recvfromAckTimeout(buf, &len, 2000, &from))
        {
          Serial.print("Got Response From : 0x");
          Serial.print(from, HEX);
          Serial.print(": ");
          Serial.println((char*)buf);
        }
        else
        {

        }
     //   digitalWrite(4, LOW);
       SPI.end();

       digitalWrite(4, LOW);    //  deselet SD Card SPI
       digitalWrite(RFM95_CS,HIGH);    //  SELECT (low) LoRa SPI
       SPI.begin();

     if (!myFile.open("mrinmoy.txt", O_READ))
      {
        sd.errorHalt("opening test.txt for read failed");
      }

      Serial.println("mrinmoy.txt:");
      char ch;
      String str;
      int i=0;
      uint8_t sd_data[50];

      while (myFile.available()>0)
      {
        ch= myFile.read();
        str+=ch;
      }

      String str2=str;
      Serial.println(str2);
      Serial.println(str2.length());

      myFile.close();
      SPI.end();

      delay(500);
    }

use this trick ... your system will work perfectly ...


message:
Distorted audio from mcp3002

I have setup a MCP3002 to convert an analog signal to digital signal. When I read it directly through serial and convert it to a wav file, it sounds relative clear. Serial is limited for samples per second though, I can get about 7000 sps.

When I send the signal directly to a server I can reach around 17.500 sps. however when I convert this to a wav file, it also sounds relative clear, but with a slight distortion/'robot voice' through the audio.

Is there a simple way to prevent this, or why is this happening?

The code how I read the SPI is in this question:
[Reading data from MCP3002][1]

  [1]: https://arduino.stackexchange.com/questions/69573/reading-data-from-the-mcp3002

body:
From the code you linked to, it appears the SPI port is completely
controlled by the software:

```c++
void loop() {
    ...
    msb = SPI.transfer(cmd);
    lsb = SPI.transfer(0);
    ...
}
```

This means that the timing of the SPI transaction (when exactly it
starts) and, by extension, the timing of the ADC conversion, is
dependent on the timing of your code execution. You have no good control
on that timing. It depends on what other things may be in your loop, and
on the other interrupt sources (timers, network...).

The least you can do is set up a timer interrupt, and run the SPI from
the interrupt handler. Your timings should then be more consistent. You
will still have some jitter due to the interrupt handler being delayed
by some critical sections, including other interrupts. But it may be
good enough for your application.

For best results, you would ideally want the timing to be completely
controlled by hardware. Maybe there is a way to trigger the SPI port
from a timer. This depends on the specific MCU you are using: you will
have to dig into the datasheet.


message:
Arduino beginners kit example not working

I bought a beginners kit and can get all but one of the examples to work. I have tried different board layouts and varied the code with no success. When I first run the code the LED is off. When I ground pin 9 the LED comes on and stays on. Grounding pin 8 does not turn off the LED once it is lit.

    int ledPin = 5;
    int buttonApin = 9;
    int buttonBpin = 8;

    byte leds = 0;

    void setup()
    {
      pinMode(ledPin, OUTPUT);
      pinMode(buttonApin, INPUT_PULLUP);
      pinMode(buttonBpin, INPUT_PULLUP);
    }

    void loop()
    {
      if (digitalRead(buttonApin) == LOW)
      {
        digitalWrite(ledPin, HIGH);
      }
      if (digitalRead(buttonBpin) == LOW)
      {
        digitalWrite(ledPin, LOW);
      }
    }

[![Circuit diagram][1]][1]

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

body:
This kind of button has 4 pins. These pins are internally connected in pairs. It's easy to make a mistake when wiring. Please post the real picture of your wiring. Or you can refer to read more about button pin [in this post][1]

  [1]: https://arduinogetstarted.com/tutorials/arduino-button#content_about_button


message:
Pulse Sensor Working Bottom-Side-Up Better?

i recently bought me an pulse-heartbeat sensor.
Connected him to my brand new M1 mini as well.

I wrote a piece of Code which just outputs the Raw ADC Value from A0 (where the pulse sensor is connected).

Now I'm confused.. When i open Serial Plotter, i get this:

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

Which is confusing because i don't get useable Values when putting the sensor up side down, which is the promoted way to do this (i guess!!)

When i press the other side against my wrist, i get this:
[![enter image description here][2]][2]
Which i can work with..

But it still doesnt look like some of those perfect diagrams on the internet.

Any can help me understand why i get this type of behaviour?

thanks, nice friday , luca

  [1]: https://i.stack.imgur.com/r7CMe.png
  [2]: https://i.stack.imgur.com/QIP54.png

body:
From what I see, this is a pulse sensor that work with light. It emits a bright light beam, that is reflected by the pulsing blood. To work, it must send the light directed to your veins. It should work well on your finger, because the probability to target a vein directly is much greater with a small finger then e.g. a wide wrist. Also the veins in your finger are closer to your skin and the oxygen situation is more different while pulsing, so the blood has more impact on the reflection.

The second curve might be a light source in your room, or an electrical wave. (?) I doubt it is your heart, because, if the numbers below the graph are milliseconds, then your heartbeat would be between 10-15 beats / second, i.e. 600 - 900 per minute. That would be too much even for a hummingbird ;-).


message:
wake from powerDown to check sensor then put back to sleep

I am using an Arduino Pro Mini with various sensors.  I am powering it with 2 3.7v 3400mA batteries which I recharge with a solar panel.  I take a reading from the batteries and if the  reading is above a certain number I disconnect the solar panel from the batteries using a relay.  Then when the battery reading gets below a certain number I switch back on the solar panel using the same relay.  This all works fine.
To conserve energy I want to delay the loop to the Arduino's activities for say two hours.
Right now I call lowPower(); at the end of the loop{.
void lowPower(){ is

    LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);

Which I continually repeat for the two hours I want.
The problem is during this two hours the high or low limit of the battery charge could be reached but I wouldn't know it.

What I would like to do is repeat

    LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);

for 15 minutes and then check the batteries and turn on or off the solar charger as need.
Then repeat the whole thing until two hrs is reached.
At that point I would rerun the loop{ to check all sensors etc.
I have tried the following

       void loop(){
        //code to run other sensors etc.
        if (Delay ==4) {
      delay(180000);
    //check the battery to begin with
    sensorBatValue = analogRead(batteryInPin);
      delay(500);
    if(chargeSwitch ==1){
     if(sensorBatValue < batteryNoCharge) {
      }
     else if(sensorBatValue > batteryNoCharge) {
         digitalWrite(10,HIGH);
       delay(1000);
       digitalWrite(10,LOW);
       chargeSwitch = 2;
      }
       }
    else if(chargeSwitch ==2){
        if(sensorBatValue > batteryCharge) {
        }
        else if(sensorBatValue < batteryCharge) {
          digitalWrite(13,HIGH);
        delay(1000);
       digitalWrite(13,LOW);
       chargeSwitch = 1;
        }
      }
    //put to sleep
    lowPower();
    //check battery again
    delay(180000);//real
    sensorBatValue = analogRead(batteryInPin);
      delay(500);
    if(chargeSwitch ==1){
     if(sensorBatValue < batteryNoCharge) {
      }
     else if(sensorBatValue > batteryNoCharge) {
         digitalWrite(10,HIGH);
       delay(1000);
       digitalWrite(10,LOW);
       chargeSwitch = 2;
      }
       }
    else if(chargeSwitch ==2){
        if(sensorBatValue > batteryCharge) {
        }
        else if(sensorBatValue < batteryCharge) {
          digitalWrite(13,HIGH);
        delay(1000);
       digitalWrite(13,LOW);
       chargeSwitch = 1;
        }
      }
    // put to sleep
    lowPower();
    //repeat for total of 2 hours.
    }

     void lowPower(){
        LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
        LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
        LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
        LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
        //repeat until 15 minutes is reached
    }

This doesn't seem to work.  The Arduino waits the correct time but from what I can tell the battery is never checked.

Or should I try

        void loop(){
        everything
        if (Delay ==4) {
      delay(180000);//real
      sensorBatValue = analogRead(batteryInPin);
      delay(500);
    if(chargeSwitch ==1){
     if(sensorBatValue < batteryNoCharge) {
      }
     else if(sensorBatValue > batteryNoCharge) {
         digitalWrite(10,HIGH);
       delay(1000);
       digitalWrite(10,LOW);
       chargeSwitch = 2;
      }
       }
    else if(chargeSwitch ==2){
        if(sensorBatValue > batteryCharge) {
        }
        else if(sensorBatValue < batteryCharge) {
          digitalWrite(13,HIGH);
        delay(1000);
       digitalWrite(13,LOW);
       chargeSwitch = 1;
        }
      }
        //include the checking of the battery inside the lowPower
        void lowPower(){
        LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
        LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
        LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
        LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
        etc.
        LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF);
        //check battery after 15 min.
        delay(500);
           sensorBatValue = analogRead(batteryInPin);
        delay(500);
        if(chargeSwitch ==1){
         if(sensorBatValue < batteryNoCharge) {
         }
         else if(sensorBatValue > batteryNoCharge) {
             digitalWrite(10,HIGH);
           delay(1000);
           digitalWrite(10,LOW);
           chargeSwitch = 2;
          }
           }
        else if(chargeSwitch ==2){
            if(sensorBatValue > batteryCharge) {
           }
            else if(sensorBatValue < batteryCharge) {
              digitalWrite(13,HIGH);
            delay(1000);
           digitalWrite(13,LOW);
           chargeSwitch = 1;
            }
          }
        //then repeat to two hours
        }

Do I need to do something to wake up the Arduino and Turn on the battery sensor pin and turn back on ADC?

Not sure how to do this Please HELP.

body: Try to use an external timer. I have the same problem approximatly.


body:
In your function `lowPower()`, instead of repeating the LowPower.powerDown(), loop over that call enough time to make up the total sleep-time you need. That's the general case. For your specific case, where you need 15-minute intervals and 2-hour intervals, `lowPower()` should loop 113 times (15:04, since 15 *60 doesn't divide evenly by 8). In your `loop()` function, loop over `lowPower()` 8 times (to make 2 hours), and each time it returns, check your battery. When the loop over `lowPower()` exits, it's time to do your "every 2 hours" jobs.

Because the 8s doesn't evenly divide 15 minutes, this timing isn't exact (but neither is the watchdog timer!), so you may want to tweak things a little, such as using a 4-second sleep, which does divide evenly.

Also, when I indented your code, I found `void lowPower()` nested inside the `loop()` function. C doesn't support that. If that was unintentional, check the pairing of your braces.