message:
How to program an Arduino Uno to collect data using a timer interrupt and analyze that data in matlab?

I working on a project where I want to collect sensor data (from a sensor) and I want to analyze the first 20 data sample (e.g., find the range, trendline e.t.c.). I know how to compile a timer interrupt in Arduino IDE (using an ISR timer), but how would I be able to do this something similar (ISR timer) in MATLAB. The reason being, I want to collect my sensor data at exactly 20 Hz and using a delay function can prove to be inaccurate. Also, when I run a sample program that collects data in MATLAB, my sample frequencies change from 15Hz to even 24Hz (as shown below) . Does anyone have any suggestion on how I can do this? If the question is not clear enough I can elaborate more in the comments.

This is my MATLAB code:

```
clear all;
a = arduino('com4', 'uno');
i = 0;
v1 = zeros(1e4,1);
v2 = zeros(1e4,1);
x = zeros(1e4,1);
t = timer('TimerFcn', 'stat=false; disp(''Timer!'')',...
                 'StartDelay',5,'Period', 1);
start(t)

stat=true;
tic
while(stat==true)
   %while i<60
    i = i + 1;
    v1(i) = readVoltage(a, 'A0');
    v2(i) = readVoltage(a, 'A1');
    x(i) = i;
    disp(x(i));
    pause(.00001);

  % end
end
toc

% %Plot voltage versus time
v1 = v1(1:i);
v2 = v2(1:i);
x = x(1:i);

p = v1;
n = v2;
%Plot voltage versus time
figure(1);
plot(x,p,'-',x,n,'-')
xlabel('Elapsed time (sec)')
ylabel('v')
title('Ten Seconds of voltage Data')
%set(gca,'xlim',[t(1) t(i)])
legend('v1', 'v2');

%
delete(t) % Always delete timer objects after using them.
```

Output is
```
>> Timer
     1

     2

     3

     4

     5

     6

     7

     8

     9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    55

    56

    57

    58

    59

    60

    61

    62

    63

    64

    65

    66

    67

    68

    69

    70

    71

    72

    73

    74

    75

Timer!
    76

Elapsed time is 5.032553 seconds.
>>
```

I apologize for the long output. But as you can see, I specified a pause time of .00001, which should give me well over a 20Hz sampling frequency. But I only get 76 samples/5 seconds = 15.2Hz. Also, sometime when I run this the program may collect 79sample/5secons, or even  121sample/5seconds. It just is not consistent. I was hoping to solve this with a timer interrupt that will be hard coded in MATLAB to collect data at exactly 20Hz. Please let me know what y'all think. Thank you.

body:
Each communication with Arduino takes 20ms, you have two in the loop so in the ideal conditions you could get 25 readings/second. [See here the source][1]

This also depends on the size of the data you request.

I think [this is what you are looking for][2] but I cant give you any advice since I don't have Matlab and Octave is not having this feature.

  [1]: https://www.mathworks.com/help/supportpkg/arduinoio/ug/custom-library-concepts.html#bu73xge
  [2]: https://www.mathworks.com/help/supportpkg/arduinoio/ug/code-generation-from-matlab-function-block.html


sender: user

sender: assistant

body:
I've configured the timer differently making use of its `UserData` property. The timer will update the data every fixed period for a specified number of samples.

```matlab
close all;
clear all;

% Some useful constants.
NUM_SAMPLES = 20;
PERIOD = 0.05;

global a;
a = arduino('com4', 'uno');

% Initialise data. It will be updated by the timer.
data.i = 0;
data.v1 = zeros(NUM_SAMPLES, 1);
data.v2 = zeros(NUM_SAMPLES, 1);
data.x = (1:NUM_SAMPLES) * PERIOD;

% Initialise timer for a fixed period for a specific number of samples.
t = timer;
t.ExecutionMode = 'fixedRate';
t.Period = PERIOD;
t.TasksToExecute = NUM_SAMPLES;
t.TimerFcn = @TimerCallback;
t.UserData = data;

% Run the timer and wait for it to complete.
start(t);
wait(t);
stop(t);
data = t.UserData;  % Retrieve the updated data.
delete(t);

% Plot voltage versus time.
figure(1);
plot(data.x, data.v1, '-', data.x, data.v2, '-');
xlabel('Elapsed time (s)');
ylabel('Voltage (V)');
title('Voltage Data');
st = sprintf("%0.3f seconds", NUM_SAMPLES * PERIOD);
subtitle(st);
legend('v1', 'v2');

function TimerCallback(obj, event)
    global a;
    obj.UserData.i = obj.UserData.i + 1;
    obj.UserData.v1(obj.UserData.i) = readVoltage(a, 'A0');
    obj.UserData.v2(obj.UserData.i) = readVoltage(a, 'A1');
end
```


message:
How to run multiple DC motors in different patterns?

I am a complete novice in programming and I hope someone could guide me here. I am doing a haptic research project, where 8 DC coin vibrating motors would be fitted on the fingers of subjects (excluding thumbs), and the subject has to respond the number of fingers they feel the vibrations on.

Every trial has to have a different pattern of outputs, say: in first trial, 4 motors are activated-motor 1, motor5, motor8 and motor 3. In a single trial, the motors have to have a common delay of 150 ms and 4 seconds break after next one starts.

**My question is, that in 8 motors, there are 255 different activation patterns possible. How do I define all these 255 patterns and randomise their sequence?
I am using the mega board and connecting each motor to a PWM pin and all having a common ground.**

Here is a sample code with 3 such combinations (only seven motors are connected here):

```c++
#define viboutpin 2
#define viboutpin1 3
#define viboutpin2 4
#define viboutpin3 5
#define viboutpin4 6
#define viboutpin5 7
#define viboutpin6 8

void setup() {
     pinMode(viboutpin,OUTPUT);// define a pin as output
     pinMode(viboutpin1,OUTPUT);
     pinMode(viboutpin2,OUTPUT);
     pinMode(viboutpin3,OUTPUT);
     pinMode(viboutpin4,OUTPUT);// define a pin as output
     pinMode(viboutpin5,OUTPUT);
     pinMode(viboutpin6,OUTPUT);
}

void loop() {
    digitalWrite(viboutpin,HIGH);
    digitalWrite(viboutpin1,HIGH);
    digitalWrite(viboutpin2,HIGH);
    digitalWrite(viboutpin3,HIGH);
    digitalWrite(viboutpin4,HIGH);
    digitalWrite(viboutpin5,HIGH);
    digitalWrite(viboutpin6,HIGH);
    delay(150);
    digitalWrite(viboutpin, LOW);
    digitalWrite(viboutpin1,LOW);
    digitalWrite(viboutpin2,LOW);
    digitalWrite(viboutpin3,LOW);
    digitalWrite(viboutpin4,LOW);
    digitalWrite(viboutpin5,LOW);
    digitalWrite(viboutpin6,LOW);
    delay(2000);

    digitalWrite(viboutpin2,HIGH);
    digitalWrite(viboutpin6,HIGH);
    delay(150);
    digitalWrite(viboutpin2,LOW);
    digitalWrite(viboutpin6,LOW);
    delay(2000);

    digitalWrite(viboutpin4,HIGH);
    delay(150);
    digitalWrite(viboutpin4,LOW);
    delay(2000);
}
```

body:
Why not generate a psuedo random number from 0 to 255 and use it as a code for which motors are to be activated - bit 0 == viboutputpin0, etc.? Then one function can look at each bit in turn and activate that motor if the bit is set, delay, and stop the motors.

You'll probably want to test your code with a few pre-defined test patterns instead of the random ones, and once you're satisfied that it works, randomly seed the random number generator so your project will generate a different pattern each time. One way to do that is to ask via terminal for the operator to click the 'Send' button (or tap the space bar if you're using a separate terminal emulator that sends key by key). Measure the time from the request to the response in microseconds, discard the 2 or 3 least significant bits of the result and keep the next 8. The micros() function's resolution is 4 usec at 16 MHz, is the reason for discarding those 2 lower bits.


message:
No "Huge APP partition scheme" (ESP32)

I recently downloaded the expressif ESP32 library and I'm trying to run the CameraWebServer example. Attempting to compile it results in the following error:

```
Sketch uses 2529577 bytes (192%) of program storage space. Maximum is 1310720 bytes.
Sketch too big; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing it.
```

I can reduce this number (192%) to 120% by changing partition scheme from "Default" to "No OTA (Large APP)". Online I've seen people using a partition scheme called "Huge APP", which I believe would solve my problem, but I don't see that option in Tools. Only "Default", "Large App" and "Minimal SPIFFS" (which doesn't work either).

How can I get the "Huge APP" partition scheme option in Arduino IDE?

body:
I was able to fix the issue by editing the boards.txt file and adding the following lines:

```
lolin32.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA/1MB SPIFFS)
lolin32.menu.PartitionScheme.huge_app.build.partitions=huge_app
lolin32.menu.PartitionScheme.huge_app.upload.maximum_size=3145728
```

This will add a "Huge APP" partition scheme to WEMOS Lolin32.


message:
Why do I need to use latin-1 instead of utf-8 when using python with arduino?

When reading and writing with a python serial port connection to arduino, if I don't use latin-1 ('ISO-8859-1'), the results are not as expected. Like if I have

```
int outP = 5;
//...
int outV = Serial.read();
analogWrite(outP, outV);
```

While with python I have

```
serial_port.write(chr(255).encode())
```
I read 3.78 V from the pin, whereas if I use

```
serial_port.write(chr(255).encode(encoding = 'latin-1'))
```
I get 5.04 V. I have read latin-1 and utf-8 don't always match, but is there something about arduino that requires using latin-1? Of course, these return different values when testing each encoding, using 255 gives b'\xc3\xbf' (from 'Ã¿') with utf-8 or b'\xff' from ('ÿ') with latin-1, but why does arduino work with latin-1?

FYI other options that work are
```
v = 255

serial_port.write(v.to_bytes(1, byteorder = 'big'))

serial_port.write(bytes[v])

```

body:
> but is there something about arduino that requires using latin-1?

No, not really.

What it comes down to is that `Serial.read()` reads bytes, irrespective of whatever encoding they may be being used with.  ISO-8859 only encodes character code points in the 0-255 range, so when you choose a 0-255 code point and send it as ISO-8859, it gets sent as 1 byte, which is how you're code has been written to receive it.

A 255 code point as utf-8 would require multiple bytes to encode and so would result in multiple `Serial.read()` calls for a given value.

If you open a python3 REPL and put `chr(255).encode()` or more explicitly `chr(255).encode('utf-8')` you will see it results in `b'\xc3\xbf'`.  So on the Arduino side you will see this as two separate `Serial.read()` results, `0xC3` and `0xBF`.

When you're just taking in strings and UTF-8 and splatting them out via `Serial.println()`, the Arduino is blissfully unaware of that they're UTF-8 and not ISO-8859.  Really you could use any encoding you wanted, the the caveat being that if you're using c-strings to store them, the encoding would need to be one that doens't allow for a single null byte to be in the middle of the string.

---

You may want to look into using [struct.pack][1] rather than cobbling together python bytestrings with sequences of `chr()` and `.encode(whatever)`. `struct.pack` will also result in a bytestring, but it's more purpose built for doing this.

You can `import struct` and then `struct.pack('B', 255)` will result in `b'\xff` same as `chr(255).encode('iso8859-1')`, but at least expresses intent.  `'B'` here signifies an `unsigned char` range, you'll find the format specifiers in the documentation. You'll get a greater benefit when you begin using multiple fields where `struct.pack` will be a lot less unwieldy than the `chr` and `encode` and string concatenation.

  [1]: https://docs.python.org/3/library/struct.html#struct.pack


message:
Control DC motor in both directions with two relays

I am using an Arduino and two relays to control 12V DC motor.
I need to rotate the motor in both directions.

For the first trials it worked fine. Finally one next switching fried my Arduino.

I think there is something wrong in the schematic.
I believe that Arduino was killed by reverse voltage spike produced by motor.

I already know that I need a diode across the motor. However, I have two directions here.

So, what is the proper schematic for my task?

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

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

body:
In short, you're probably overloading your regulator.

It's difficult to say for sure, but I have a suspicion and can give a framework for thinking about it with some very crude numbers.

If you're powering the Nano from a 12 V source, you are dropping 7 V across the regulator.  If you do the math on this 7 V drop, it means every 14 mA drawn through the regulator induces nearly a tenth Watt of heat in the regulator.  7 V * 0.014 A = 0.098 W.  I'm guessing you have a budget of perhaps 300mW based on the way the Nano's regulator is set up.

The ATmega328P says it uses 5.2 mA (typical) or 9 mA (maximum) at 5 V and active at 8 MHz.  But really it will use more at the 16 MHz frequency.  For sake of argument, I'm just going to say it's using 14 mA, because it makes the math easy and because power usage scales somewhat linearly with frequency.

Just the power led will use about 3 mA, if it's an official Nano, but for simplicity sake, I'll call it 7 mA, being half of 14 mA and we'll ignore the fact that there are other loads on the board like the serial transceiver.

Your relay coils will use *at least* 30 mA, but likely more, perhaps a lot more.  But for ease of calculation lets go optimistic and say they only use 28 mA (cause 2 * 14 mA).

So we have the ATMega328P inducing 100 mW in the regulator, the power led and some extras adding 50 mW. at at least one relay coil energized for another 200 mW.  So right there you're already at 350 mW.  If you screwed up and managed to energize both relays, 550 mW.  Hopefully the regulator will enter thermal shutdown when this happens, in which case all you need to do is let it cool down and, you know, stop doing that.  But it may also just die,which is more likely if you have a clone that happens to use a crappier regulator.

But, I think these numbers are conservative.  For example, a datasheet for a Songle SRD-05VDC-SL-C relay that a lot of these modules use seems to say it will use closer **70 mA** each, rather than 28 mA.  This means operating just one of these coils by itself, nevermind the rest of the Arduino, will cause nearly half a Watt to be dissipated in the regulator if you're powering from 12 V.  If you managed to turn on both coils well... nothing good.

If this is not *the* problem you're having, it is *a* problem.  You can save yourself a fair bit of trouble by powering your Nano from USB with a powered hub or reasonable quality USB-output wall adapter.  Doing so bypasses your regulator altogether.

If you're going to continue staging down 12 V to 5 V for the relay coils, then you may need an external regulator to operate the relay modules, just to unload the the Nano's regulator.  Exactly how you'd go about that depends somewhat on the construction of the relay module.  Some of them make it a bit easier on you and are design to accept voltage from a second source for the coils.


message:
Unable to compile c++11 libraries despite having added -std=c++11 in platform.txt

I want to use c++ data structures such as vectors, arrays, map... in my Arduino sketch. I made sure to **add -std=c++11 and -std=gnu++11 in platform.txt**, I am still getting the following error message:

> fatal error: unordered_map: No such file or directory
> #include <unordered_map> compilation terminated. exit status 1 unordered_map: No such file or directory

Here's a snapshot from ~/arduino-nightly/hardware/arduino/avr/platform.txt:

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

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

Versions:

 - Arduino ide: 1.8.14
 - g++: 5.4.0
 - avr-g++: 4.9.2

**What else should I set up?**

body:
The AVR-based Arduinos don't come with anything close to a full C++ standard library implementation.  They have [avr-libc][1] which is fairly complete to at least the [C99 standard][2], that is the C standard from 1999, not C++.  What you're doing with `-std=c++11` is influencing the standard used by the compiler to interpret the C++ language itself.  This does work fine on AVR based Arduinos, but is not going to give you the sort of C++ containers you may be used to on a desktop or larger embedded system, like an ESP8266.

Much of the C++ standard library would be completely out of place on an AVR based Arduino, particularly those parts that make use of dynamic allocation like `unordered_map` in your error message.

There are *some* parts of the C++ library implemented via [Arduino STL][3].  Whether or not you *should* be using containers from it is another question.

If you do try to use Arduino STL, I'd encourage you to use more conservative parts of it.  Something like an `unordered_map`, but with less (or no) dynamic allocation could be implemented by using Arduino STL's `std::array` and functions from its `<algorithm>` header, like their `std::find` or `std::lower_bound`, etc.  Trying to use a C++ `map` or `vector` container or something of that sort is kind of asking for trouble, more so on the more common AVR-based Arduinos with only roughly 2 Kbyte of RAM.

  [1]: https://nongnu.org/avr-libc/
  [2]: https://en.wikipedia.org/wiki/C99
  [3]: https://www.arduino.cc/reference/en/libraries/arduinostl/


message:
Arduino Core for the Raspberry Pi Pico

I recently bought a Raspberry Pi Pico to play with, and am attempting to upload my first program to it *the Arduino way*, as my own operating system rather than a c++ program over an existing operating system (meaning to replace the built-in Raspberry Pi Pico operating system which runs MicroPython, not in the sense of running Linux, Windows, Mac, or any derivative or fork). I have not found any record of people hacking it like that - is it possible? If so, how would I go about it? Sorry if this is in the wrong Stack Exchange.

body:
Here is the library for the Arduino IDE and a Raspberry Pi pico.

https://github.com/lrusak/Arduino-Core-Pico

Just install normally as a .zip.


body:
Official support.
-----------------

Apparently there's official support for it, now anyway.

I was digging around in the [Arduino-mbed core][1], trying to help someone else, specifically in the [boards.txt][2] and spied the line:

> pico.name=Raspberry Pi Pico

Unfortunately, I don't have any way to give it a proper test as I don't have one of these.  But I did go so far as to install the core and compile a simple hello world program.

In boards manager
-----
Search for "mbed rp2040"; these names sometimes change, but those terms work well now.  You can see in the lower item, I have version 2.0.0 installed.

[![Boards manager dialog shown with search terms "mbed rp2020"][3]][3]

Board menu selection
----

`Tools`/`Board`/`Arduino Mbed OS RP2040`/`Raspberry Pi Pico`

[![Shows Menu with board selected.][4]][4]

Seems to work.
-------------
As you see it at least builds without error.  As I said, I'm unable to give it a real test.  But that at least looks promising.

[![Shows successful build.][5]][5]

  [1]: https://github.com/arduino/ArduinoCore-mbed/
  [2]: https://github.com/arduino/ArduinoCore-mbed/blob/2.0.0/boards.txt
  [3]: https://i.stack.imgur.com/CSz4e.png
  [4]: https://i.stack.imgur.com/GvLEf.png
  [5]: https://i.stack.imgur.com/fWqTS.png


body:
It is worth mentioning [this excellent alternative](https://github.com/earlephilhower/arduino-pico) to the Arduino one from Earle F. Philhower. It seems well-maintained and doesn't depend on Mbed OS, so it leaves more space (ram and flash) for your application.

[Here](https://github.com/earlephilhower/arduino-pico/issues/117#issuecomment-830356795) an informal comparative list.


message:
4x4 matrix keypad not working

I'm working on a research project that allows me to press a button on a matrix that then outputs a parameter like temperature, humidity etc. But I cannot find out what is wrong with the buttons, when I press them nothing is happening. Thank you very much! I've attached what the connection between the Arduino and the keypad looks like.

    #include <EEPROM.h>
    #include <GravityTDS.h>
    #include "DHT.h"
    #include <LiquidCrystal_I2C.h>
    #include <Wire.h>
    #include <Servo.h>
    #include <OneWire.h>
    #include <DallasTemperature.h>
    #include <Keypad.h>
    LiquidCrystal_I2C lcd(0x27, 16, 2);
    #define DHTPIN 7
    #define DHTTYPE DHT11   // DHT 11
    #define SensorPin A0            //pH meter Analog output to Arduino Analog Input 0
    #define Offset 0.00            //deviation compensate
    #define LED 13
    #define samplingInterval 20
    #define printInterval 800
    #define ArrayLenth  40    //times of collection
    #define PUMPPIN 9
    #define ONE_WIRE_BUS 4
    int pHArray[ArrayLenth];   //Store the average value of the sensor feedback
    int pHArrayIndex = 0;
    OneWire oneWire(ONE_WIRE_BUS);
    DallasTemperature sensors(&oneWire);
    Servo myservo;
    GravityTDS gravityTds;
    DHT dht(DHTPIN, DHTTYPE);

    char incomingByte;
    String inputString;
    int pump = 9; // Output for pump Control
    double avg;
    int h;
    float t;
    float tdsValue;
    float temperature = t;
    static unsigned long samplingTime = millis();
    static unsigned long printTime = millis();
    static float pHValue, voltage;

    const byte ROWS = 4;
    const byte COLS = 4;

    char hexaKeys[ROWS][COLS] = {
      {'A', 'B', 'C', 'D'},
      {'E', 'F', 'G', 'H'},
      {'I', 'J', 'K', 'L'},
      {'M', 'N', 'O', 'P'}
    };

    byte rowPins[ROWS] = {44, 42, 40, 38};
    byte colPins[COLS] = {36, 34, 32, 30};

    Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

    void setup() {

      lcd.begin();
      pinMode(pump, OUTPUT); //sets the digital pin as output
      digitalWrite(pump, LOW); // Initial state of the pump
      Serial.begin(9600);
      gravityTds.setPin(A1);
      gravityTds.setAref(5.0);
      gravityTds.setAdcRange(1024);
      gravityTds.begin();
      dht.begin();
      sensors.begin();
    }

    double averagearray(int* arr, int number) {
      int i;
      int max, min;
      long amount = 0;
      if (number <= 0) {
        Serial.println("Error number for the array to avraging!/n");
        return 0;
      }
      else if (number < 5) { //less than 5, calculated directly statistics
        for (i = 0; i < number; i++) {
          amount += arr[i];
        }
        avg = amount / number;
        return avg;
      } else {
        if (arr[0] < arr[1]) {
          min = arr[0]; max = arr[1];
        }
        else {
          min = arr[1]; max = arr[0];
        }
        for (i = 2; i < number; i++) {
          if (arr[i] < min) {
            amount += min;      //arr<min
            min = arr[i];
          } else {
            if (arr[i] > max) {
              amount += max;  //arr>max
              max = arr[i];
            } else {
              amount += arr[i]; //min<=arr<=max
            }
          }//if
        }//for
        avg = (double)amount / (number - 2);
      }//if
      return avg;
    }

    void loop() {
      lcd.print("working so far. test1");
      delay(5000);
      char customKey = customKeypad.getKey();
      int pumptime = 1000;
      switch (customKey) {
        case 'A':
          // pump
          digitalWrite(pump, HIGH); // on pump
          delay(pumptime);
          digitalWrite(pump, LOW);//off pump
          break;
        case 'B':
          // add pump time
          pumptime += 500;
          break;
        case 'C':
          // less pump time
          pumptime -= 500;
          break;
        case 'D':
          // reset pump time
          pumptime = 1000;
          break;
        case 'E':
          //temp
          sensors.requestTemperatures();
          lcd.setCursor(0, 0);
          lcd.print("Celsius temperature: ");
          lcd.print(sensors.getTempCByIndex(0));
          lcd.print((char)223);
          lcd.print("C");
          delay(5000);
          lcd.clear();
          break;
        case 'F':
          // Temperature & humidity
          h = dht.readHumidity();
          t = dht.readTemperature();
          lcd.setCursor(0, 0);
          lcd.print("Humidity:");
          lcd.print(h);
          lcd.print("%");
          lcd.setCursor(0, 1);
          lcd.print("Temperature:");
          lcd.print(t);
          lcd.print((char)223);
          lcd.print("C");
          delay(5000);
          lcd.clear();
          break;
        case 'G':
          // TDS
          h = dht.readHumidity();
          t = dht.readTemperature();
          temperature = t;
          gravityTds.setTemperature(temperature);
          gravityTds.update();
          tdsValue = gravityTds.getTdsValue();
          lcd.setCursor(0, 0);
          lcd.print("TDS: ");
          lcd.print(tdsValue);
          lcd.print("ppm");
          delay(5000);
          lcd.clear();
          delay(5000);
          lcd.clear();
          break;
        case 'H':
          // pH
          lcd.clear();
          lcd.setCursor(0, 0);
          if (millis() - samplingTime > samplingInterval)
          {
            pHArray[pHArrayIndex++] = analogRead(SensorPin);
            if (pHArrayIndex == ArrayLenth)pHArrayIndex = 0;
            voltage = averagearray(pHArray, ArrayLenth) * 5.0 / 1024;
            pHValue = 3.5 * voltage + Offset;
            samplingTime = millis();
          }
          if (millis() - printTime > printInterval)  //Every 800 milliseconds, print a numerical, convert the state of the LED indicator
          {
            lcd.print("Voltage:");
            lcd.print(voltage, 2);
            lcd.print("    pH value: ");
            lcd.println(pHValue, 2);
            digitalWrite(LED, digitalRead(LED) ^ 1);
            printTime = millis();
          }
          delay(5000);
          lcd.clear();
          break;
        case 'I':
          // test buttons
          lcd.print("buttons are working");
          delay(5000);
          lcd.clear();
          break;
        case 'J':
          //
          lcd.print("buttons are working");
          delay(5000);
          lcd.clear();
          break;
        case 'K':
          //
          lcd.print("buttons are working");
          delay(5000);
          lcd.clear();
          break;
        case 'L':
          //
          lcd.print("buttons are working");
          delay(5000);
          lcd.clear();
          break;
        case 'M':
          //
          lcd.print("buttons are working");
          delay(5000);
          lcd.clear();
          break;
        case 'N':
          //
          lcd.print("buttons are working");
          delay(5000);
          lcd.clear();
          break;
        case 'O':
          //
          lcd.print("buttons are working");
          delay(5000);
          lcd.clear();
          break;
        case 'P':
          //
          lcd.print("buttons are working");
          delay(5000);
          lcd.clear();
          break;
      }//switch
      lcd.print("working so far. test2");
      myservo.write(0);
      delay(10000);
      myservo.write(90);

      delay(1800000);

}

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

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

body:
Imho, your delay function in loop() is a root cause.
First, you should remove the below code

      myservo.write(0);
      delay(10000);
      myservo.write(90);

      delay(1800000);

Then,please reduce delay(5000) -> delay(200).
Build and execute your code.
Press and hold a single button and take a look what happen in LCD. At least, you able to confirm the keypad hardware works well or not.


message:
Power LED Matrix With LiPo Battery & ESP32

I want to power an ESP32 with a 3.7V LiPo battery. There's a LED matrix of 64 WS2812 LEDs attached to the ESP32. I learned that I need a buck boost converter to power the microcontroller as it needs a 5V power input. The boost converter delivers that when there is no matrix attached. However if the matrix is attached it only receives about 2.7V. Turning the potentiometer on the boost converter changes nothing in this case. What is the reason for this? I am sorry if this question seems basic to you. I am an beginner with electronics.

Here is a rather hideous scetch of the connections. I hope this is okay:
[![enter image description here][1]][1]

This is the buck converter I used: https://www.amazon.de/gp/product/B079H3YD8V/ref=ppx_yo_dt_b_asin_title_o02_s00?ie=UTF8&psc=1

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

body:
The way you have it set up is fine if you aren't going to light up all the LEDs at full brightness. And if you do, you're not going to break your ESP32 Dev Board the way you have it set up in your diagram (since you are not running the power THROUGH the board). The LiPo battery probably has its own little regulator on it to prevent it from being damaged.

Check your dev board specifications on how much power you actually need to supply to the Vin pin. [The ESP32 chip operates between 2.3 and 3.6 volts (3.3 recommended).][1] Your dev board regulates the 5v to provide that amount to the chip.

Most likely, your dev board will run fine on the 3.7V provided by your LiPo without the buck-boost. I use a similar setup (without a buck-boost) to demo little projects to friends. I use a ESP32U-01 dev board from EZSBC, a 64 LED Matrix from Adafruit, and a 3.7v LiPo battery.

Depending on how many LEDs are lit (and what color), you shouldn't expect the battery to last very long. And the overall brightness of your led matrix will be limited.

If you are using the [FastLED Animation Library][2], I would recommend setting a power limit using set_max_power_in_milliwatts function and limiting it to 1500mW for starters. Again, if you are not drawing power THROUGH the ESP32 board, you're fine.

  [1]: https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf
  [2]: http://fastled.io/


message:
Code for mapping voltage on a sensor and outputting a value in liters

I got a Resistive sender fuel gauge sketch off the internet that I have adapted.  The Resistive sender is a floating magnet that activates read switches to vary the resistance.  Using a stable 5v power source and 100-ohm resistor I have a voltage bridge that is connected to the sender and pin A1.  The original sketch uses this to get the voltage into liters:

```c++
TankValue0 = map(sensorTankValue0, 352, 824, 0, 100);
if (TankValue0 < 0) {
  TankValue0 = 0;
}
if (TankValue0 > 100) {
  TankValue0 = 100;
```

The lower range is not too far off but as you get to the top it is out to lunch.

I have mapped the segments of MY float sensor's intervals, and have found there to be 17 distinct points-- I measured the voltage at each point and made a table (I mean like on paper) to relate the measured voltage at a given point to a distance in mm, and then converted that to the relevant metric of liters in a tank when the float switch is reading a given voltage.

V    |L
-----|--
4.04 |94
3.981|88
3.902|84
3.81 |81
3.703|77
3.637|72
3.564|69
3.483|65
3.393|61
3.293|57
3.18 |53
3.053|50
2.908|46
2.546|42
2.192|38
1.726|35

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

How do I get that information into the sketch to give me a read-out of L in my tank?

I have no programming knowledge really. I work with Arduino IDE a lot, but only using sketches other people have written.  So, I have a huge basic knowledge gap.  So, please bare that in mind.

This is the whole sketch:

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

int TankValue0;
int TankValue1;

LiquidCrystal_I2C lcd(0x27, 16, 2);   // set the LCD address to 0x27 for a 16 chars and 2 line display

void setup() {
  lcd.init();                          // initialize the lcd
  lcd.init();
  lcd.backlight();
  lcd.setCursor(1, 0);
  lcd.clear();
  lcd.print("WORD");
  lcd.setCursor(0, 1);
  lcd.print("TO");
  delay(1500);
  lcd.clear();
  lcd.print("YO ");
  lcd.setCursor(0, 1);
  lcd.print("MOMMA");
  delay(2000);
  lcd.clear();
  pinMode(A0, INPUT);
  Serial.begin(9600);               // starting the Serial Monitor

}
void loop() {
  int sensorTankValue0 = analogRead(A0);
  int sensorTankValue1 = analogRead(A1);
  TankValue0 = map(sensorTankValue0, 352, 824, 34, 94);
  TankValue1 = map(sensorTankValue1, 785, 310, 0, 100);
  if (TankValue0 < 0) {
    TankValue0 = 0;
  }
  if (TankValue1 < 0) {
    TankValue1 = 0;
  }
  if (TankValue0 > 100) {
    TankValue0 = 100;
  }
  if (TankValue1 > 100) {
    TankValue1 = 100;
  }
  lcd.print("S.V. SAVANNAH");
  lcd.setCursor(0, 1);
  delay(100);
  lcd.print("DAY TANK   ");
  lcd.print(TankValue0);
  lcd.print("%");
  lcd.setCursor(0, 0);

  delay(1000);
  lcd.clear();
}
```

body:
Curve fitting
-------------

Well, a lazy way to do it is just to fit a curve to it, using Excel, or Libreoffice, Google Docs or whatever.  Here's gnuplot being used that way to fit a cubic polynomial to it:

"points.txt" containing your data, tab-delimited:
```txt
4.04    94
3.981   88
3.902   84
3.81    81
3.703   77
3.637   72
3.564   69
3.483   65
3.393   61
3.293   57
3.18    53
3.053   50
2.908   46
2.546   42
2.192   38
1.726   35
```

Gnuplot session:

```txt
gnuplot> f(x) = A*(x**3) + B*(x**2) + C*x + D
gnuplot> fit f(x) "points.txt" via A, B, C, D
iter      chisq       delta/lim  lambda   A             B             C             D
   0 1.8323200047e+01   0.00e+00  9.28e+01    2.818423e+00  -1.100151e+01   1.447650e+01   2.873579e+01
   1 1.8323200047e+01  -4.65e-10  9.28e+00    2.818423e+00  -1.100151e+01   1.447650e+01   2.873579e+01
iter      chisq       delta/lim  lambda   A             B             C             D

After 1 iterations the fit converged.
final sum of squares of residuals : 18.3232
rel. change during last iteration : -4.6534e-15

degrees of freedom    (FIT_NDF)                        : 12
rms of residuals      (FIT_STDFIT) = sqrt(WSSR/ndf)    : 1.23569
variance of residuals (reduced chisquare) = WSSR/ndf   : 1.52693

Final set of parameters            Asymptotic Standard Error
=======================            ==========================
A               = 2.81842          +/- 1.156        (41.02%)
B               = -11.0015         +/- 10.22        (92.86%)
C               = 14.4765          +/- 29.11        (201.1%)
D               = 28.7358          +/- 26.52        (92.27%)

correlation matrix of the fit parameters:
                A      B      C      D
A               1.000
B              -0.998  1.000
C               0.990 -0.997  1.000
D              -0.974  0.987 -0.996  1.000
```

And here's what looks like against the actual data with `plot "points.txt" with linespoints, f(x)`:
[![Curve fitting with data.][1]][1]

So you have a function:
```c++
float f(float x) {
  static const float A =   2.81842;
  static const float B = -11.0015 ;
  static const float C =  14.4765 ;
  static const float D =  28.7358 ;
  const float x_squared = x * x;
  const float x_cubed   = x * x_squared;

  return A * x_cubed + B * x_squared + C * x + D;
}
```

If you don't care about the code size and the slowness of `float` arithmetic, then that might be okay.

Otherwise you may want to convert that function to something like fixed point arithmetic.

A cubic polynomial may be overkill, but then whole technique may be also.

Peicewise Linear
-----------------

You can make a table of you points and just do what graphing programs typically do, linear interpolation between the points.

```c++
float f(float x) {
  static const struct pt {
    float v;
    int l;
  } points[] = {
    {0.0  ,  0},  // I put this here for testing, but put a better value here.
    {1.726, 35},
    {2.192, 38},
    {2.546, 42},
    {2.908, 46},
    {3.053, 50},
    {3.18 , 53},
    {3.293, 57},
    {3.393, 61},
    {3.483, 65},
    {3.564, 69},
    {3.637, 72},
    {3.703, 77},
    {3.81 , 81},
    {3.902, 84},
    {3.981, 88},
    {4.04 , 94}
    // you should probably have another entry here so that readings up to 5V work.
  };
  static const size_t table_len = sizeof points / sizeof points[0];

  for (size_t i = 0; i < table_len - 1; ++i) {
    if (x >= points[i].v && x < points[i + 1].v) {
      return
            (x - points[i].v)
          / (points[i + 1].v - points[i].v)
          * (points[i + 1].l - points[i].l)
          + points[i].l;
    }
  }

  return -1;
}
```

Sitting in the center of this in the `return` statement is basically a crude implementation of Arduino's `map()`, but for floating point, which again, you don't really need floating point, even if you want to use this piecewise approach.

In short, you find which two entries of the table you're sitting between, and apply what amounts to `map()` on the line segment formed by the two table entries.

PROGMEM
--------

Either of the curve fitting or piecewise approach could be used to generate a much larger lookup table out of which you could just chose the nearest point.

If you're doing this on an AVR-based Arduino, the table for the piecewise linear approach or a pure lookup table approach could use [`PROGMEM`][2] for the array.

Regarding float and fixed point
-------------------------------
Any of these techniques could be adapted to fixed-point math.
Which ever you use, if you're on AVR based Arduino, keep in mind that there's no hardware floating point support at all, and although `double` exists as a type it is implemented in avr-gcc as a single precision `float`.

If you're using one of the non-AVR based Arduinos, it may have support for `float` (and maybe for `double`), in which case the generated code may not be so bad, though may still be slower than using integers.

If you can do everything with integers, resulting code should be a lot smaller and faster.  I'm guessing for what you're doing, if either of them are more important, it's probably being smaller.

For using integers, you may be able to keep your input "voltage" as an ADC count, not having an intermediate voltage calculation.  And even if you want single digit liters when you're done, the intermediate interpolation, curve fitting, or table lookup may require that you work in something like centiliters, milliliters, so that values like the `A` constant from the curve-fitting example can be represented as an integer, e.g.  2818 mL  rather than a cruder 3 L.  If you're not using a plain lookup table and finding the nearest entry, that is if you're using the curve or piecewise linear approach, doing everything in integer arithmetic from ADC count to mL.  Although you'll need to run another curve fitting, since the `A`, `B`, etc will representing mL-per-ADC-count not L-per-Volt.  Or scale them from the value given.

And there are other options, piecewise cubic splines, etc.

  [1]: https://i.stack.imgur.com/w0Tgc.png
  [2]: https://www.arduino.cc/reference/en/language/variables/utilities/progmem/


message:
Arduino changing output based on wire voltage

I’m new to arduino and I want to build myself smart switch that can be turned of both manualy and via wifi, is there any way to change position of relay based on if another wire is live or not? Im from europe so we have 230V  outlets.

Thanks for the answer.

[![This is "diagram" of my design][1]][1]

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

body:
Maybe a wire coil wound around the wire could pick up the frequency. Though I won't write about this, since I don't know much about how you would measure this, and because I think, that you are looking the wrong way.

You want to switch one device with multiple switches (how these switches are operates is not important for now). You can look at how this is normally done in eletrical installations. Here the switches are all connected to your breaker box. And there is one component, that waits for trigger signals from the switches and will switch the target device (the light in this case) accordingly. So in the end there is only one place, where the light is switched: in the breaker box. The switches in the room are only triggers. The current for the light does not flow through them. Also they don't necessarily need to carry mains voltage (triggers could also be low voltage) (though it seems they are in fact just using mains voltage, for which I don't know the reason. Maybe to avoid additional voltage conversion).

So I propose the following solution: The mains wires (230V) are only connected to the light and a (suitable) relay board. The relay board is connected to the Arduino, which can act as a Smart Switch (switching via WiFi, time based or whatever). For manual switching you can connect a switch or button to the Arduino and program the Arduino to read it and control the relay accordingly.

This solution is way easier, than trying to sense the live voltage on the lines, and this will most likely make it more reliable . It comes down to controlling an relay board and reading a button/switch, both things with tons of tutorials on the web

Note: Since mains voltage is always really dangerous, you should be really really caution. Don't use mains voltage, when developing your device. A simple LED with current limiting resistir connected to the power line of the Arduino through the relay is sufficient to check the complete functionality. Only connect mains voltage, if you are really really sure, that you did everything correct


message:
Weird serial behavior on atmega2560

**EDIT**
This seems to be something to do with the oscillators. Switching to the internal oscillator and writing straight avr-c allows me to run a basic blink program. Writing the same basic blink in arduino and flashing with the IDE (through serial or usbasp) results in a non functional program. I'd like to be able to use the oscillator because it doesn't look like I can get everything done in time at 8MHZ

I have an arduino mega 2560 which a few weeks ago was working fine. Now, I'm trying to output some data from it, and 've broken it down to a very, very basic proof of concept:

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

    void loop() {
       // put your main code here, to run repeatedly:
       Serial.println("hello");
    }

This prints:

    hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

indefinitely on the screen. If I change the baud to 115200, I get the "hello" and the newline, and slowly start getting garbage afterwards. If I switch to 234500, I get a few prints, and then nothing.

Adding a delay after the print does not change the frequency of the serial prints:

    void loop() {
    // put your main code here, to run repeatedly:
        Serial.println("hello");
        delay(100000);
    }

They still come in immediately.

I have a feeling this has something to do with timing of an interrupt, but I'm not setting anything up. I plan to reflash and fix the fuses, but my usbASP cable is broken right now. Any other input on what might be going on here?

Edit:
This occurs on two different boards. I originally had some i2c devices (mag/gryo/barometer) on board, but those have since been removed. I have tried two different usb cables in two different USB ports. This might be on the host side?

Edit:
Both the TX and Rx lights are solid this whole time. Almost as if there's a loopback. My other laptop won't even boot right now. I'm concerned a surge from a storm last night might have taken out both of these machines

More testing:
Looking at the output on a scope, the board is actually only outputting an "h" character. If I do:

    Serial.println('U');
    delay(1000);
I get a square wave, so the delay doesn't run at all.
If I do:
    Serial.println('U');
    Serial.println('U'); //or any other character
    delay(1000);

I get a U character over the scope, and then an empty serial frame. The delay still doesn't run, but it looks like the second println is exiting.

Even burning a new bootloader fails on these boards

body:
Answering my own question - a bit of a walk of shame here.

I had disabled the internal TIMER0_OVF_vect in the arduino core code, so that I could write my own (for another project). I wrapped in in an #if 0 so I could go and bring it back when I needed it.

Today, I learned that the atmega interrupts aren't filled with an IRET by default, but instead hit the reset vector, resetting the board. Anything I compiled on this library would reset whenever TIMER0 overflowed, because my ifdefs didn't cover the TIMSK setting in the arduino core either

The "Serial.println isn't exiting" was actually "the board is resetting before it can complete" and explains why faster bauds could print more data.

Not much smarter than hairless apes, sometimes.


message:
Remove unwanted characters from char type

I'm working on an ESP8266 module that needs to fetch date data from [worldtimeapi](http://worldtimeapi.org/api/timezone/Region/City), everything works fine but the problem is **How do I strip of the time field off the datetime JSON response without loop**.

**Note:** Arduino JSON library was used in deserializing the response data and it seems the library only supports `char` data type.

``` lang-c++
void loop ()
{
  // Initialize the request object
  HTTPClient request;

// Make a http request
  request.begin(dateTime);
  delay(2000);

  // Check the request status code.
int  responseCode = request.GET(); //Get the api host response code.
  Serial.print("Response code is: ");
  Serial.println(responseCode);
  if (responseCode == 200); // If the server returned OK
  {
      String responseData = request.getString();
      Serial.println("Response from the server is:");
      Serial.println(responseData);
        // Deserialize the JSON response data
       StaticJsonDocument<715> result; // Declare data storage to stack

      //Check for error during data deserialization
      DeserializationError error = deserializeJson(result, responseData);

      if (error)
      {
        Serial.print(F("Response deserialization failed with reason: "));
        Serial.println(error.f_str());
        return;
      }

      else
      {
        char abbreviation = result["abbreviation"];  // Returns the current time zone abbreviation
        char timezone = result["timezone"]; // Returns the current time zone
        char datetime = result["datetime"]; // "2021-03-12T17:04:0
        char date = datetime.remove(9,22); // This line throws error : request for member 'remove' in 'datetime', which is of non-class type 'char'

        Serial.print("Current time is ");
        Serial.print(datetime);
        Serial.print(" ");
        Serial.print(abbreviation);
        Serial.print(" ");
        Serial.println(timezone);
        delay(2000);
      }

  }

}
```

body:
You can use `strtok` to split the string on the T character:

```c++
char *datepart = strtok(datetime, "T");
char *timepart = strtok(NULL, "T");

Serial.print("The current date is: ");
Serial.println(datepart);
Serial.print("The current time is: ");
Serial.println(timepart);
```

An alternative is to just find the `T` and turn it into the NULL terminating character:

```c++
char *T = strchr(datetime, 'T');
*T = 0;
```

----

If you need to copy the string data into a temporary string first you can do:

```c++
char temp[strlen(datetime)+1];
strcpy(temp, datetime);
```

Then operate on `temp` instead of `datetime`.


message:
using a variable to index an array

I'm using the keypad library to return a number 1-9. (im fairly sure this returns an int)
I have an array (data) showing the state of each button press.
so i would like the number returned by the keypad (key) to be the index number that gets edited from 0 to 1 and from 1 to 0.

```c++
    //REMOTE KEYPAD TO CONTROL OUTPUTS OVER SERIAL

#include <Keypad.h>

const byte ROWS = 4; //four rows
const byte COLS = 4; //three columns
char keys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},

};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

int iAm = 1;                                    //this is device number 1
float checkSum = 0.00;                          //check sum to send as serial
float voltage = 5.26;                           //system voltage
bool data[8] {0, 0, 0, 0, 0, 0, 0, 0, 0};       //keypad output call

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

void loop() {

  int key = keypad.getKey();

  if (key) {
        data[key] = 1;

    //checkSum = voltage * (iAm + data[0] + data[1] + data[2] + data[3] + data[4] + data[5] + data[6] + data[7] + data[8] + data[9]);
    //Serial.print(iAm);
    //Serial.print("/");
    Serial.print(data[1]);
    Serial.print("/");
    Serial.print(data[2]);
    Serial.print("/");
    Serial.print(data[3]);
    Serial.print("/");
    Serial.print(data[4]);
    Serial.print("/");
    Serial.print(data[5]);
    Serial.print("/");
    Serial.print(data[6]);
    Serial.print("/");
    Serial.print(data[7]);
    Serial.print("/");
    Serial.print(data[8]);
    Serial.print("/");
    Serial.print(data[9]);
    Serial.print("/");
    Serial.print(voltage);
    Serial.println("/");
    //Serial.println(checkSum);

  }

}
```

i can edit the index location by typing data[1] = 1 but not as a variable so i suspect an index cant be addressed as int? but i don't know what it should be addressed as or how to change it to that.

body:
not going to pretend i understand why all my keypad numbers are 48 higher than the number printed on the keypad but:

    int key2 = key -48;

works


message:
Controlling op amps amplification ratio by arduino

Is there any option how to control amplification ratio of operational amplifier by some logic signal which can be produced by arduino? I am talking about some clasic op amp like lm356 or ui741 in basic inverting or non-inverting circuit (i would like to use non-inverting circuit in my application). I know only about digital potentiometer like solution but i think that it isn't profesional and most eficient solution, so I want to know your opinion. Thanks for reply.

body:
The basic principle is easy to implement.  A non-inverting configuration has a resistor Ri from the inverting input to ground, and a feedback resistor Rf from the same input to the output.  The signal is applied to the non-inverting input.  The gain is 1+Rf/Ri.  You can control the gain by changing Ri, which can be done via a CD4016 quad analog switch and 4 resistors.
HOWEVER, the Arduino is a 0-5V device.  The CD4016 can handle 15V, but to switch it the digital input must pass through half the supply.  The op-amps you mention will require bipolar supplies to handle AC signals (which I assume is what you want), so you could run them with +/-7.5V, with the CD4016 powered between them.  Then to get the Arduino 0-5V to toggle the CD4016 you'd need some level-shifting transistors to get it to +/-7.5.  The upshot is that this is surely going to be more trouble than it's worth.

However, if you are willing to drop the ancient op-amps and use a modern single-supply type (MCP6021, LT1013, etc) that runs on 0-5V, you can use input and output capacitors to convert the signal to AC, then just use the CD4016 as-is. Or JFET transistors, or even bipolars to switch the gain resistor under Arduino control if you don't need audiophile quality.


message:
Atmega 328P U crash on 5V/1A

Atmega 328PU crash on 5v/1A. Why? It works on 5V/400ma but when i switch it to 5V/1A power it crash. Any idea or solution for this?

body:
Nothing wong, if your power supply is trustworthy enough, then , if u even provide 100000 Amps of current with 5 volt,
 your IC won't burn, in your case , it burnt because your power supply seems to be defective, and please check the voltage of the power supply which is supposed to be defective, so it output more than 5 volts burning or crashing your ic...

Note:

I have personally worked with 5 volt 6 amp power supply which is very well precise and my ic is working full fledged without any problems.


message:
Strange behavior from uint32_t, acting like signed int (Nano clone)

I'm having trouble with these variables. As you can see they're uint32_t type, so they should have a maximum value of 4 million or so, but they're rolling over and going negative at 32,767 like a signed int. Here's the relevant code:

```
byte lPin = 7;
char buff[100];
uint32_t loAvg = 0;
uint32_t hiAvg = 0;

void setup() {
  pinMode(lPin, OUTPUT);
  digitalWrite(lPin, HIGH); // Active LOW, so this is off

  Serial.begin(9600);
  // Generate high/low averages
  for(int i = 0; i < 100; i++) {
    loAvg += analogRead(A0);
  }
  loAvg /= 100;

  digitalWrite(lPin, LOW);
  delay(500);

  for(int i = 0; i < 100; i++) {
    hiAvg += analogRead(A0);
  }
  hiAvg /= 100;

  digitalWrite(lPin, HIGH);
  delay(500);

  sprintf(buff, "loAvg=%d, hiAvg=%d", loAvg, hiAvg);
  Serial.println(buff);

  Serial.println(hiAvg);
  digitalWrite(lPin, LOW);
  hiAvg = 0;
}

void loop() {
  sprintf(buff, "test=%d", hiAvg);
  Serial.println(buff);
  hiAvg+=100;
}
```

I removed a bunch of stuff from the code to save posting the whole (much longer) thing. If it ends up being relevant I can though, I just think I narrowed the problem down to this. Observing the serial monitor I get this on startup:

```
loAvg=287, hiAvg=0
933
test=0
test=100
test=200
...
```

The `test=#` repeats until 32700, then continues at -32736. I'm confused by the hiAvg=0 followed by the 933, showing that it totally is getting a high average, because that's around what it should be. Even if it's the sprintf() messing with it, in the setup function the value should only be around the 900 range so it wouldn't overflow there. Any ideas anyone?

body:
`%d` expects a signed int. `%u` expects an unsigned int. Insert the `l` modifier to expect a long in each of those cases. So you need a format code of `%lu` to print a uint32_t.

The following code:

    #include <Arduino.h>

    void setup()
    {
     uint32_t x=110000;
     char buf[50];

       // Open console
       Serial.begin(115200);

     sprintf(buf, "%%d: %d\n", x);  Serial.print(buf);
     sprintf(buf, "%%u: %u\n", x);  Serial.print(buf);
     sprintf(buf, "%%ld: %ld\n", x); Serial.print(buf);
     sprintf(buf, "%%lu: %lu\n", x); Serial.print(buf);
    }

    void loop() {
       ;
    }

prints this:

    %d: -21072
    %u: 44464
    %ld: 110000
    %lu: 110000


body:
*`printf` and bit-width specified types
---------------------------------------

`#include <inttypes.h>` or C++'s `#include <cinttypes>` counterpart (when you have it; not on AVR-based Arduinos) gives access to macros defined for the format specifiers for each of the fixed, fast, and least versions of these types.  All of these macros expand to some string literal or another.

For `uint32_t` the macro defining to its format specifier is `PRIu32`.  For an AVR, this is `"%lu"`.  It needn't be `"%lu"` in  the general case.  `uint32_t` is one of the types where you can often get away with using `"%lu"` and have it either work out being exactly correct for the platform or somewhat incorrect but working anyway because it's a platform where `unsigned int` and `unsigned long` happen to have the same representation.

In C and C++, and so Arduino, adjacent string literals are concatenated into one logical string in the early phases of compilation that follow the macro preprocessor.  So, the intention is that you choose the correct macro and you put them following something like `"%"` or `""` if you wanted a minimum-width of 12.  As in `"%" PRIu32` and `"" PRIu32` respectively.  So, in your case,  having included (directly or indirectly) `<stdint.h>` for `uint32_t` and `<inttypes.h>` for `PRIu32` or their C++ counterpart headers, and then your code looks something like:

```c++
snprintf(
  buf,
  sizeof buf,
  "loAvg=%" PRIu32 ", hiAvg=%" PRIu32,
  loAvg,
  hiAvg
);
```

There's little to no reason to not use the s**n**printf.  The reason why the non-n version exists at all is mostly that `snprintf` showed up in 1999, instead of circa the mid 1970s.  I'd say it's pretty safe to use `snprintf` now.  There probably hasn't been an Arduino that doesn't support it.  About the only reason to use `sprintf` would be if you were calling it with a null pointer for the buffer argument to get it to do a dry run and tell how much memory you need for the result, and you just didn't want to supply a limiting size.

There are `PRI...` [macros for all of the combinations][1] of standard bit width and choice of signed decimal, unsigned decimal, lowercase hex, uppercase hex, etc.  E.g `"%" "PRId16"` is  for `int16_t` in decimal, `"%" PRIX64` for `uint64_t` in hexadecimal with uppercase alphabetics.  The are ones for the `fast` and `least` bitwidth types, and whole show is repeated with macros starting with `SCN` for the `scanf` specifiers, not that you should use the `scanf` family functions for anything really.

`snprintf` and `sprintf` are variadic functions.  After the format specifier there's no type information available to the compiler to know what conversions to apply.  It will convert types smaller than `int` rank up to `int` on `unsigned int`, but that's about it.  E.g. it will not reliably down-convert an `unsigned long long` into an `unsigned int`, the way it would if the types were known.  Modern compilers will sometimes warn you if you grossly misapply format specifiers, but they're not required to.  They're not expected to dissect the format string and attempt to recover type information.  So it's up to you to make sure whatever you pass in for arguments matches with the format specifiers.  As you've seen it's confusing if you get it wrong with `printf`-type functions, but it doesn't cause real problems unless you, you know, don't limit it to stay within the output buffer with the s**n**printf version.  In the case of passing in an `unsigned long long` where an `unsigned int` was expected, in practice, for a little-endian system like AVR, it may appear to do that for one argument.  But then it may fail on the next argument, because the size of the last argument was in correct, it is now reading from the wrong place.

`Print`/`Stream`/`Serial` concatenating and buffering
-----------------------------------------------

The way you're using `sprintf` in your code isn't taking advantage of any of its features that `Serial`/`Print` doesn't do.

```c++
Serial.print(F("loAvg="));
Serial.print(loAvg);
Serial.print(F(", hiAvg="));
Serial.println(hiAvg);
```

Despite taking four lines, this is actually smaller, faster, more reliable code than the `sprintf` one-liner.

Putting the output into a buffer first might make sense if you were going to put it into a packet, like for UDP or nRF24L01.  But, `Print`/`Stream`/`Serial` already concatenates and buffers things for you.

---

Incidentally, if you're going to use `printf` functions and you're doing it on an AVR-based Arduino, look at the avr-libc [documentation for the `_P` variants][2] that take their format strings from PROGMEM and the [`PSTR` macro][3].

It is also possible to complete the implementation of `<stdio.h>` for `stdout` and `stderr` through libc-specific means.  So, if you really want to, you can have the regular `printf` function pushing data out through `Serial` (among other things) such that you *don't* need to buffer repeatedly with `sprintf`.

  [1]: https://en.cppreference.com/w/cpp/header/cinttypes
  [2]: https://www.nongnu.org/avr-libc/user-manual/group__avr__stdio.html
  [3]: https://www.nongnu.org/avr-libc/user-manual/group__avr__pgmspace.html#ga05ca900ebf7cd121be73c654d9ccb3eb


message:
Arduino Leonardo doesn't print anything to Serial Monitor with my specific code

I did a project with an Arduino Leonardo and a fingerprint sensor (DY50).
When I uploaded the ```enroll``` example from the ```Adafruit Fingerprint Library``` and saved my fingerprint, everything worked. But when I upload my code, it doesn't print anything.

**My Code**
```
#include <Keyboard.h>
#include <Adafruit_Fingerprint.h>
#define mySerial Serial1

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);
int fingerprintID = 0;
String inData;
bool isRight;
int pos;

//Number of services to log in
#define servNum 5

//Login URLs for Google, Amazon, Stackoverflow, Arduino and Github
String LogInURL[] = {"https://accounts.google.com/signin", "https://www.amazon.de/ap/signin", "https://stackoverflow.com/users/login", "https://login.arduino.cc/", "https://github.com/login"};
String LogInUser[] = {"user.name@gmail.com", "user.name@example.com", "user.name@example.com", "username", "username"};
String LogInPwd[] = {"password", "password", "password", "password", "password"};

void donothing() {};

void StepsBefore(int serviceNum){
  switch(serviceNum){
    case 0: donothing(); break;
    case 1: donothing(); break;
    case 2: for(int k=0; k<18; k++) Keyboard.press(KEY_TAB); Keyboard.release(KEY_TAB); break;
    case 3: for(int k=0; k<2; k++) Keyboard.press(KEY_TAB); Keyboard.release(KEY_TAB); break;
    case 4: donothing(); break;
    default: Serial.println("Error: Number not recognized."); break;
  }
}

void StepsAfter(int serviceNum){
  switch(serviceNum){
    case 0: Keyboard.println(); break;
    case 1: Keyboard.println(); break;
    case 2: Keyboard.press(KEY_TAB); Keyboard.release(KEY_TAB); break;
    case 3: Keyboard.press(KEY_TAB); Keyboard.release(KEY_TAB); break;
    case 4: for(int k=0; k<2; k++) Keyboard.press(KEY_TAB); Keyboard.release(KEY_TAB); break;
    default: Serial.println("Error: Number not recognized."); break;
  }
}

int getFingerprintIDez() {
  uint8_t p = finger.getImage();
  if (p != FINGERPRINT_OK)  return -1;
  p = finger.image2Tz();
  if (p != FINGERPRINT_OK)  return -1;
  p = finger.fingerFastSearch();
  if (p != FINGERPRINT_OK)  return -1;
  Serial.print("Found ID #");
  Serial.print(finger.fingerID);
  Serial.print(" with confidence of ");
  Serial.println(finger.confidence);
  return finger.fingerID;
}

void askForFingerprint() {
  fingerprintID = getFingerprintIDez();
    delay(50);
    if(fingerprintID == 1){
      isRight = true;
    }
}

void delAfterChar(String inString, String fromToKill){
  pos = inString.indexOf(fromToKill);
  inString.remove(pos, 1000);
  inData = inString;
}

void setup() {
 Serial.begin(115200);
 Serial.println("Debug 1");
 Keyboard.begin();
 Serial.println("Debug 2");
 finger.begin(57600);
 Serial.println("Debug 3");
    if(finger.verifyPassword()) {
        Serial.println("Found fingerprint sensor!");
    }
    else {
        Serial.println("Did not find fingerprint sensor :(");
        while (1) { delay(1); }
    }
}
void loop() {
  inData = Serial.read();
  delAfterChar(inData, "?openid"); //Amazon
  delAfterChar(inData, "/v2/"); //Google
  delAfterChar(inData, "?ssrc"); //Stackoverflow
  delAfterChar(inData, "login?state"); //Arduino
 for (int i=0; i<servNum; i++){
     if(inData == LogInURL[i]){
        askForFingerprint();
        if(isRight == true){
           StepsBefore(i);
           Keyboard.print(LogInUser[i]);
           StepsAfter(i);
           Keyboard.println(LogInPwd[i]);
        }
        else Serial.println("Finger not recognized");
     }
 }
}
```
**What I've tried so far**

 - I changed the baud rate from ```9600``` to ```15200```, didn't help
 - Added a few debug points in the ```setup``` to check for an error there, nothing changed
 - Uploaded a simple Hello World via Serial Monitor sketch, worked perfectly

**Question**

What could be the issue? It compiles with no error message. If you see any coding mistakes, feedback would be great.

**EDIT**

Using ```SoftwareSerial``` instead didn't help either.

body: As @Juraj pointed out, I just forgot to use ```while (!Serial)``` in the ```setup```, probably because I use other boards that don't need this more often.


message:
Arduino Uno with Sensor, Bluetooth Module and tftlcd

In code attached below I am using tftlcd display of 2.4 inch in which i want to show clock as home page, when user click on tftlcd screen then a screen appears which can show three options to user which are about the sensors user want to use. There are three sensors in this code: Pulse oximeter, glucose meter, pedometer. After choosing some option(sensor) the data of sensor will appear on screen.
I have write code for all this procedure which is given below:

    //include all libraries
    #include <Wire.h>
    #include <SPFD5408_Adafruit_GFX.h>
    #include <SPFD5408_Adafruit_TFTLCD.h>
    #include <SPFD5408_TouchScreen.h>
    #include "MAX30105.h"
    #include "spo2_algorithm.h"

    //Exit buttons
    bool backsensed = false;
    bool resetsensed = false;

    //Include Max30102 lib
    MAX30105 particleSensor;

    //Define LCD pins
    #define YP A1  // must be an analog pin, use "An" notation!
    #define XM A2  // must be an analog pin, use "An" notation!
    #define YM 7   // can be a digital pin
    #define XP 6   // can be a digital pin

    //pedometer
    const int xpin = A3;
    const int ypin = A4;
    const int zpin = A5;
    byte p[8] = {0x1F,
      0x1F,
      0x1F,
      0x1F,
      0x1F,
      0x1F,
      0x1F,
      0x1F
    };
    float threshold = 100;
    float xval[100] = {0};
    float yval[100] = {0};
    float zval[100] = {0};
    float xavg, yavg, zavg;
    int steps, flag = 0;
    //pulseoxi
    #define MAX_BRIGHTNESS 255
    #if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
    uint16_t irBuffer[100]; //infrared LED sensor data
    uint16_t redBuffer[100];  //red LED sensor data
    #else
    uint32_t irBuffer[100]; //infrared LED sensor data
    uint32_t redBuffer[100];  //red LED sensor data
    #endif
    int32_t bufferLength; //data length
    int32_t spo2; //SPO2 value
    int8_t validSPO2; //indicator to show if the SPO2 calculation is valid
    int32_t heartRate; //heart rate value
    int8_t validHeartRate; //indicator to show if the heart rate calculation is valid
    byte pulseLED = 11; //Must be on PWM pin
    byte readLED = 13; //Blinks with each data read

    // LCD Calibrate values
    #define TS_MINX 100
    #define TS_MINY 120
    #define TS_MAXX 920
    #define TS_MAXY 940

    // For better pressure precision, we need to know the resistance between X+ and X- Use any multimeter to read it
    // For the one we're using, its 300 ohms across the X plate
    TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);

    #define LCD_CS A3
    #define LCD_CD A2
    #define LCD_WR A1
    #define LCD_RD A0
    #define LCD_RESET A4

    Adafruit_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET);

    int BLUE = tft.color565(50, 50, 255);
    #define TFT_BLACK   0x0000
    #define TFT_DARKBLUE 0x0010
    #define VIOLET 0x8888
    #define TFT_RED     0xF800
    #define TFT_GREEN   0x07E0
    #define TFT_CYAN    0x07FF
    #define TFT_MAGENTA 0xF81F
    #define TFT_YELLOW  0xFFE0
    #define TFT_WHITE   0xFFFF
    #define TFT_GREY    0x5AEB
    #define TFT_BLUE    0x001F
    #define GOLD 0xFEA0
    #define BROWN 0xA145
    #define SILVER 0xC618
    #define LIME 0x07E0
    #define BLUE  0x001F

    //button screen
    int currentpcolour;
    int currentpage;
    bool running;

    //Minimum and maximum pressure to sense the touch
    #define MINPRESSURE 10
    #define MAXPRESSURE 1000

    //clock
    float sx = 0, sy = 1, mx = 1, my = 0, hx = -1, hy = 0;
    float sdeg = 0, mdeg = 0, hdeg = 0;
    uint16_t osx = 120, osy = 120, omx = 120, omy = 120, ohx = 120, ohy = 120;
    int16_t x0 = 0, x1 = 0, yy0 = 0, yy1 = 0, x00 = 0, yy00 = 0;
    uint32_t targetTime = 0;
    uint16_t xpos;
    uint8_t conv2d(const char* p) {
      uint8_t v = 0;
      if ('0' <= *p && *p <= '9')
        v = *p - '0';
      return 10 * v + *++p - '0';
    }
    uint8_t hh = conv2d(__TIME__), mm = conv2d(__TIME__ + 3), ss = conv2d(__TIME__ + 6);
    boolean initial = 1;
    char d;

    //for buttons
    void drawHome()
    {
      tft.fillScreen(TFT_BLACK);
      tft.drawRoundRect(0, 0, 319, 240, 8, TFT_YELLOW);     //Page border

      tft.fillRoundRect(60, 180, 200, 40, 8, TFT_DARKBLUE);
      tft.drawRoundRect(60, 180, 200, 40, 8, TFT_YELLOW);  //PEDO

      tft.fillRoundRect(60, 130, 200, 40, 8, TFT_DARKBLUE);   //Glu
      tft.drawRoundRect(60, 130, 200, 40, 8, TFT_YELLOW);

      tft.fillRoundRect(60, 80, 200, 40, 8, TFT_DARKBLUE);
      tft.drawRoundRect(60, 80, 200, 40, 8, TFT_YELLOW); //Pulse oxi and heart rate

      tft.setCursor(25, 20);
      tft.setTextSize(3);
      tft.setTextColor(TFT_WHITE);
      tft.print("Welcome Here..");
      tft.setCursor(25, 50);
      tft.setTextSize(2);
      tft.setTextColor(TFT_YELLOW);
      tft.print("Choose Your Sensor");
      tft.setTextColor(TFT_WHITE);
      tft.setCursor(110, 195);
      tft.print("Pedometer");

      tft.setCursor(80, 145);
      tft.print("Glucose Sensor");

      tft.setCursor(80, 95);
      tft.print("Pulse Oximeter");
      //  delay(500);

      }

      void setup()
    {
      tft.reset();
      tft.begin(0x9341);
      tft.setRotation(1);
      currentpage = 0; //clock page
      tft.setTextColor(TFT_WHITE);// text color
      tft.fillScreen(TFT_BLACK);// background color

      xpos = tft.width() / 2;
      tft.drawCircle(xpos, 120, 125, TFT_YELLOW);
      tft.fillCircle(xpos, 120, 118, TFT_BLUE);
      tft.fillCircle(xpos, 120, 110, TFT_BLACK);
      for (int a=95; a<104; a++){
      tft.drawCircle(xpos, 120, a, TFT_WHITE);}

      for (int i = 0; i < 360; i += 30) {
        sx = cos((i - 90) * 0.0174532925);
        sy = sin((i - 90) * 0.0174532925);
        x0 = sx * 114 + xpos;
        yy0 = sy * 114 + 120;
        x1 = sx * 100 + xpos;
        yy1 = sy * 100 + 120;
        tft.drawLine(x0, yy0, x1, yy1, TFT_YELLOW);
      }
      for (int i = 0; i < 360; i += 6) {
        sx = cos((i - 90) * 0.0174532925);
        sy = sin((i - 90) * 0.0174532925);
        x0 = sx * 102 + xpos;
        yy0 = sy * 102 + 120;
        x00 = sx * 92 + xpos;
        yy00 = sy * 92 + 120;
        // Draw minute markers
        tft.drawPixel(x0, yy0, TFT_GREEN);
        tft.drawLine(x0, yy0, x00, yy00, TFT_BLACK);
        tft.drawLine(x0+1, yy0+1, x00+1, yy00+1, TFT_BLACK);
        // Draw main quadrant dots
        if (i == 0 || i == 180) tft.fillCircle(x0, yy0, 2, TFT_WHITE);
        if (i == 90 || i == 270) tft.fillCircle(x0, yy0, 2, TFT_WHITE);
      }
      tft.fillCircle(xpos, 121, 3, TFT_WHITE);
      targetTime = millis() + 1000;
      //touch event
      tft.setCursor (80, 250);
      tft.setTextSize (1);
      tft.setTextColor(TFT_BLACK);
      tft.println("Touch to proceed");
      waitOneTouch(); // Wait touch
      drawHome(); //buttons screeen
    }

    void loop(){
      if (currentpage == 0){
      if (targetTime < millis()) {             //clock code
        targetTime = millis() + 1000;
        ss++;
        if (ss == 60) {
          ss = 0;
          mm++;
          if (mm > 59) {
            mm = 0;
            hh++;
            if (hh > 23) {
              hh = 0;
            }
          }
        }
        sdeg = ss * 6;                     // 0-59 -> 0-354
        mdeg = mm * 6 + sdeg * 0.01666667; // 0-59 -> 0-360 - includes seconds, but these increments are not used
        hdeg = hh * 30 + mdeg * 0.0833333; // 0-11 -> 0-360 - includes minutes and seconds, but these increments are not used
        hx = cos((hdeg - 90) * 0.0174532925);
        hy = sin((hdeg - 90) * 0.0174532925);
        mx = cos((mdeg - 90) * 0.0174532925);
        my = sin((mdeg - 90) * 0.0174532925);
        sx = cos((sdeg - 90) * 0.0174532925);
        sy = sin((sdeg - 90) * 0.0174532925);
        if (ss == 0 || initial) {
          initial = 0;
          // Erase hour and minute hand positions every minute
          tft.drawLine(ohx, ohy, xpos, 121, TFT_BLACK);
          ohx = hx * 62 + xpos + 1;
          ohy = hy * 62 + 121;
          tft.drawLine(omx, omy, xpos, 121, TFT_BLACK);
          omx = mx * 84 + xpos;
          omy = my * 84 + 121;
        }
        // Redraw new hand positions, hour and minute hands not erased here to avoid flicker
        tft.drawLine(osx, osy, xpos, 121, TFT_BLACK);
        osx = sx * 90 + xpos + 1;
        osy = sy * 90 + 121;
        tft.drawLine(osx, osy, xpos, 121, TFT_RED);
        tft.drawLine(ohx, ohy, xpos, 121, TFT_CYAN);
        tft.drawLine(omx, omy, xpos, 121, TFT_WHITE);
        tft.drawLine(osx, osy, xpos, 121, TFT_RED);
        tft.fillCircle(xpos, 121, 3, TFT_RED);
        tft.setCursor(xpos-30, 50);
        tft.setTextSize(2);
        tft.print("Glucoxy");

      // Draw MINI clock face "SECOND"
      tft.drawCircle(xpos, 155, 20, TFT_YELLOW);
      tft.drawCircle(xpos, 155, 18, TFT_BLUE);
      tft.drawCircle(xpos, 155, 17, TFT_CYAN);
      tft.drawCircle(xpos, 155, 16, TFT_CYAN);
      tft.fillRect(xpos-10, 149,22,15,TFT_BLACK); //erase
      if(ss<10){tft.setCursor(xpos-10, 149); tft.setTextSize(2);
      tft.print('0'); tft.setCursor(xpos+2, 149);}
      else{
      tft.setCursor(xpos-10, 149);}
      tft.setTextSize(2);
      tft.print(ss);
      // Draw MINI clock face "Minutes"
      tft.drawCircle(xpos+35, 117, 20, TFT_YELLOW);
      tft.drawCircle(xpos+35, 117, 18, TFT_BLUE);
      tft.drawCircle(xpos+35, 117, 17, TFT_CYAN);
      tft.drawCircle(xpos+35, 117, 16, TFT_CYAN);
     tft.fillRect(xpos+25, 111,22,15,TFT_BLACK); //erase
      if(mm<10){tft.setCursor(xpos+25, 111); tft.setTextSize(2);
      tft.print('0'); tft.setCursor(xpos+37, 111);}
      else{
      tft.setCursor(xpos+25, 111);}
      tft.println(mm);
      // Draw MINI clock face "Hour"
      tft.drawCircle(xpos-35, 117, 20, TFT_YELLOW);
      tft.drawCircle(xpos-35, 117, 18, TFT_BLUE);
      tft.drawCircle(xpos-35, 117, 17, TFT_CYAN);
      tft.drawCircle(xpos-35, 117, 16, TFT_CYAN);
      tft.fillRect(xpos-45, 111,22,15,TFT_BLACK); //erase
      if(hh<10){tft.setCursor(xpos-45, 111); tft.setTextSize(2);
      tft.print('0'); tft.setCursor(xpos-33, 111);}
      else{
      tft.setCursor(xpos-45, 111);}
      tft.setTextSize(2);
      tft.print(hh);
      //tft.setCursor(xpos-65, 111);
      //tft.println(':');
      if (hh>=0 && hh<12) d='A'; else {d='P';}
      tft.drawRoundRect(xpos-14,72,29,21,5,TFT_CYAN);
      tft.fillRect(xpos-11, 75,23,15,TFT_BLACK); //erase
      tft.setCursor(xpos-11, 75);
      tft.setTextSize(2);
      tft.print(d);
      tft.println('M');
      }
      }
      //home page
      if (currentpage == 1){
      digitalWrite(13, HIGH);
      TSPoint p = ts.getPoint();     // Read touchscreen
      digitalWrite(13, LOW);
      pinMode(XM, OUTPUT);
      pinMode(YP, OUTPUT);
      {if (p.z > 10 && p.z < 1000)
        {
          if (p.x > 736 && p.x < 855 && p.y > 255 && p.y < 725  && p.z > MINPRESSURE && p.z < MAXPRESSURE)
          {
            Serial.println("Pedometer");
            tft.fillRoundRect(60, 180, 200, 40, 8, TFT_WHITE);
            delay(70);
            tft.fillRoundRect(60, 180, 200, 40, 8, TFT_WHITE);
            tft.drawRoundRect(60, 180, 200, 40, 8, TFT_YELLOW);
            tft.setCursor(65, 195);
            tft.println("  Pedometer");
            delay(70);
            currentpage = 2;
            startPedo();
          }
          else if (p.x > 563 && p.x < 683 && p.y > 275 && p.y < 750)
          {
            Serial.println("Glucose Sensor");

            tft.fillRoundRect(60, 130, 200, 40, 8, TFT_WHITE);   //rgb led
            delay(70);
            tft.fillRoundRect(60, 130, 200, 40, 8, TFT_WHITE);   //rgb led
            tft.drawRoundRect(60, 130, 200, 40, 8, TFT_YELLOW);   //rgb led
            tft.setCursor(105, 145);
            tft.print("Glucose Sensor");
            delay(70);
            currentpage = 3;
            startGlu();
          }
          if (p.x > 403 && p.x < 525 && p.y > 271 && p.y < 725)
          {
            Serial.println("Pulse Oximeter");
            currentpage = 4;
            tft.fillRoundRect(60, 80, 200, 40, 8, TFT_WHITE);
            delay(70);
            tft.fillRoundRect(60, 80, 200, 40, 8, TFT_WHITE);
            tft.drawRoundRect(60, 80, 200, 40, 8, TFT_YELLOW);
            tft.setCursor(80, 95);
            tft.print("Pulse Oximeter");
            delay(70);
           // startPulse();

          }
        }
      }
      if (currentpage == 2) //pedo
      {
        senseBack();
        if (backsensed)
        {
          currentpage = 1;
          drawHome();
        }
        sensereset();
        calibrate();
      }
      if (currentpage == 3) // glucose
      {
         senseBack();
         if (backsensed)
         {
          currentpage = 0;
          drawHome();
         }
        sensereset();
      }

      if (currentpage == 4)  //pulse oxi
      {
        senseBack();
         if (backsensed)
         {
          currentpage = 1;
          drawHome();
         }
        sensereset();
        pinMode(pulseLED, OUTPUT);
      pinMode(readLED, OUTPUT);
      if (!particleSensor.begin(Wire, I2C_SPEED_FAST)) //Use default I2C port, 400kHz speed  // Initialize sensor
      {
        Serial.println(F("MAX30105 was not found. Please check wiring/power."));
        while (1);
      }
      Serial.println(F("Attach sensor to finger with rubber band. Press any key to start conversion"));
      while (Serial.available() == 0) ; //wait until user presses a key
      Serial.read();
      byte ledBrightness = 60; //Options: 0=Off to 255=50mA
      byte sampleAverage = 4; //Options: 1, 2, 4, 8, 16, 32
      byte ledMode = 2; //Options: 1 = Red only, 2 = Red + IR, 3 = Red + IR + Green
      byte sampleRate = 100; //Options: 50, 100, 200, 400, 800, 1000, 1600, 3200
      int pulseWidth = 411; //Options: 69, 118, 215, 411
      int adcRange = 4096; //Options: 2048, 4096, 8192, 16384
      particleSensor.setup(ledBrightness, sampleAverage, ledMode, sampleRate, pulseWidth, adcRange); //Configure sensor with these settings
      startPulse();
      }
    }

    }
    // Wait one touch
    TSPoint waitOneTouch() {
      TSPoint p;
      do {
        p= ts.getPoint();
        pinMode(XM, OUTPUT); //Pins configures again for TFT control
        pinMode(YP, OUTPUT);
      } while((p.z < MINPRESSURE )|| (p.z > MAXPRESSURE));
      return p;
    }
    void sensereset()
    {
      digitalWrite(13, HIGH);
      TSPoint p = ts.getPoint();     // Read touchscreen
      digitalWrite(13, LOW);
      pinMode(XM, OUTPUT);
      pinMode(YP, OUTPUT);
      if (p.x < 199 && p.y < 293 && !running)
        resetsensed = true;
      else
        resetsensed = false;
    }
    void startPedo()        //-------------------pedometer function--------------------------
    {
      int acc = 0;
      float totvect[100] = {0};
      float totave[100] = {0};
      float xaccl[100] = {0};
      float yaccl[100] = {0};
      float zaccl[100] = {0};
      for (int a = 0; a < 100; a++)
      {
        xaccl[a] = float(analogRead(xpin) - 345);
        delay(1);
        yaccl[a] = float(analogRead(ypin) - 346);
        delay(1);
        zaccl[a] = float(analogRead(zpin) - 416);
        delay(1);
        totvect[a] = sqrt(((xaccl[a] - xavg) * (xaccl[a] - xavg)) + ((yaccl[a] - yavg) * (yaccl[a] - yavg)) + ((zval[a] - zavg) * (zval[a] - zavg)));
        totave[a] = (totvect[a] + totvect[a - 1]) / 2 ;
        Serial.println("totave[a]");
        Serial.println(totave[a]);
        delay(100);
        if (totave[a] > threshold && flag == 0)
        {
          steps = steps + 1;
          flag = 1;
        }
        else if (totave[a] > threshold && flag == 1)
        {
          // Don't Count
        }
        if (totave[a] < threshold   && flag == 1)
        {
          flag = 0;
        }
        if (steps < 0) {
          steps = 0;
        }
        Serial.println('\n');
        Serial.print("steps: ");
        Serial.println(steps);
        delay(1000);
      }
      delay(1000);
      //print results on lcd
      tft.setCursor(130, 145);
      tft.setTextSize(3);
      tft.setTextColor(TFT_WHITE);
      tft.print(steps);

      }
    void calibrate()            //<----------------------calibrate funtion--------------------->
    {
      float sum = 0;
      float sum1 = 0;
      float sum2 = 0;
      for (int i = 0; i < 100; i++) {
        xval[i] = float(analogRead(xpin) - 345);
        sum = xval[i] + sum;
      }
      delay(100);
      xavg = sum / 100.0;
      Serial.println(xavg);
      for (int j = 0; j < 100; j++)
      {
        yval[j] = float(analogRead(ypin) - 346);
        sum1 = yval[j] + sum1;
      }
      yavg = sum1 / 100.0;
      Serial.println(yavg);
      delay(100);
      for (int q = 0; q < 100; q++)
      {
        zval[q] = float(analogRead(zpin) - 416);
        sum2 = zval[q] + sum2;
      }
      zavg = sum2 / 100.0;
      delay(100);
      Serial.println(zavg);
    }
    void senseBack()
    {
      digitalWrite(13, HIGH);
      TSPoint p = ts.getPoint();     // Read touchscreen
      digitalWrite(13, LOW);

      pinMode(XM, OUTPUT);
      pinMode(YP, OUTPUT);
      if (p.y < 305 && p.x < 285 && p.x > 239 && !running)
      {
        backsensed = true;

      }
      else
        backsensed = false;
    }
    void startGlu()                 //-------------------------------startGlu-------------------------
    {
      }
    void startPulse()             //--------------------------------startpulse-----------------------
    {
      bufferLength = 100; //buffer length of 100 stores 4 seconds of samples running at 25sps

      //read the first 100 samples, and determine the signal range
      for (byte i = 0 ; i < bufferLength ; i++)
      {
        while (particleSensor.available() == false) //do we have new data?
          particleSensor.check(); //Check the sensor for new data
        redBuffer[i] = particleSensor.getRed();
        irBuffer[i] = particleSensor.getIR();
        particleSensor.nextSample(); //We're finished with this sample so move to next sample
        Serial.print(F("red="));
        Serial.print(redBuffer[i], DEC);
        Serial.print(F(", ir="));
        Serial.println(irBuffer[i], DEC);
      }
      //calculate heart rate and SpO2 after first 100 samples (first 4 seconds of samples)
      maxim_heart_rate_and_oxygen_saturation(irBuffer, bufferLength, redBuffer, &spo2, &validSPO2, &heartRate, &validHeartRate);
      //Continuously taking samples from MAX30102.  Heart rate and SpO2 are calculated every 1 second
      while (1)
      {
        //dumping the first 25 sets of samples in the memory and shift the last 75 sets of samples to the top
        for (byte i = 25; i < 100; i++)
        {
          redBuffer[i - 25] = redBuffer[i];
          irBuffer[i - 25] = irBuffer[i];
        }
        //take 25 sets of samples before calculating the heart rate.
        for (byte i = 75; i < 100; i++)
        {
          while (particleSensor.available() == false) //do we have new data?
            particleSensor.check(); //Check the sensor for new data
          digitalWrite(readLED, !digitalRead(readLED)); //Blink onboard LED with every data read
          redBuffer[i] = particleSensor.getRed();
          irBuffer[i] = particleSensor.getIR();
          particleSensor.nextSample(); //We're finished with this sample so move to next sample
          //send samples and calculation result to terminal program through UART
          Serial.print(F("red="));
          Serial.print(redBuffer[i], DEC);
          Serial.print(F(", ir="));
          Serial.print(irBuffer[i], DEC);
          Serial.print(F(", HR="));
          Serial.print(heartRate, DEC);
          Serial.print(F(", HRvalid="));
          Serial.print(validHeartRate, DEC);
          Serial.print(F(", SPO2="));
          Serial.print(spo2, DEC);
          Serial.print(F(", SPO2Valid="));
          Serial.println(validSPO2, DEC);
        }

        //After gathering 25 new samples recalculate HR and SP02
        maxim_heart_rate_and_oxygen_saturation(irBuffer, bufferLength, redBuffer, &spo2, &validSPO2, &heartRate, &validHeartRate);
        //print results on lcd
        tft.setCursor(130,145);
      tft.setTextSize(3);
      tft.setTextColor(TFT_WHITE);
      tft.print(heartRate);

      }

    }
Please see above code whether it works perfect as i want. I am getting error when i try to compile this code which is given below
[![enter image description here][1]][1]

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

My questions are:
1. whether this code is right, if not then point out my mistakes.
2. Solution of error shown in image.

body:
The Arduino Uno doesn't have enough SRAM, the current Rev3 has just 2 KB. You can circumvent that by using less variables, use `#define xpin` instead of `const int`, etc.
[Here][1] is an article about how to reduce memory usage, give it a try.

Another option is to use a different Microcontroller with more SRAM, with at least 3KB like a Arduino Mega, ESP32. But first try to optimize your program, if you don't have another unused board lying around anyway.

**EDIT:**

You might also take a look at the header files if you can optimize anything there.

  [1]: https://create.arduino.cc/projecthub/john-bradnam/reducing-your-memory-usage-26ca05


body:
Arduino Mega has **8192 bytes** of SRAM which will solve your problem.

Reduce the RAM usage ([ref][1])

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

  [1]: https://arduinojson.org/v6/how-to/reduce-memory-usage/
  [2]: https://i.stack.imgur.com/4Pn8B.png


message:
Sharing clock pin on Pro Micro

I am trying to get both a SPI LED matrix display and an NRF24L01 to both work on the same Arduino Pro Micro. I know they both want to use the clock pin but how do I get them to share? Can I use the CS pin to turn off one device while trying to use the other? The display does can be set only when something needs to change so it's not always running.

body:
It is indeed possible and supported to use [different CS (chip select) or SS (“slave select”) lines to address individual SPI devices on a single bus](https://en.wikipedia.org/wiki/Serial_Peripheral_Interface#Independent_slave_configuration) run by an SPI “master”.

[![SPI three slaves on single bus][1]][1]
*Image from Wikipedia*

Many SPI TFT Touch displays need this to address the display controller and the touch controller as individual SPI devices and/or an integrated SD Card interface (wich also uses SPI).

The MOSI, MISO and SCLK lines can be reused and shared between perpiheral devices, as long as only one device is actively being addressed at any point in time. I.e. only one SS/CS may be active at any time and the software must support such sharing of SPI resources.

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


message:
Error compiling for board Arduino Uno SIM7000

I'm using  **[botletics / SIM7000-LTE-Shield][1]** with Arduino Uno, I selected all examples but all end up with the same Error

    C:\Users\lenovo\Documents\Arduino\libraries\SIM7000\Adafruit_FONA.cpp: In member function 'boolean Adafruit_FONA::postData(const char*, uint16_t, const char*, const char*, const char*)':
    C:\Users\lenovo\Documents\Arduino\libraries\SIM7000\Adafruit_FONA.cpp:2045:3: error: expected ';' before 'readline'
    readline(10000);
    ^~~~~~~~
    exit status 1
    Error compiling for board Arduino Uno.

  [1]: https://github.com/botletics/SIM7000-LTE-Shield

body:
I cloned botletics comparatively gigantic repo.  They've modified the Adafruit library without changing the name.

The problem appears to be that you are working out of the current master branch.  Switch to the latest tag, 1.1.0, and the SMS_Response example will compile just fine.  I didn't try all of the others.

[Direct link to the zip file for the 1.1.0 tag.][1]

  [1]: https://codeload.github.com/botletics/SIM7000-LTE-Shield/zip/1.1.0


message:
HC-05 Module not receiving commands and not pairing

I'm working on a project where I'll need to establish a connection between two HC-05 modules, each connected to an Arduino, but for now I'm just trying to get one to work and connect to my phone, but I'm not sure if I'm doing anything right...

I'm not able to give AT-Commands, and as a result the device is not able to pair with my phone.
My setup looks something like this:

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

With minor differences being that I'm using an Uno board instead of a Mega, the RX and TX pins are connected to...well, I tried a lot of different pins, from the default RX/TX pins to specifying other pins like the ones in the code, as well as reversing the connections (RX to TX, TX to RX), also this schematic neglected to mention the 'ENABLE' pin, which I connected to my Arduino's 3,3V pin.

I tried a lot of different code samples, the latest one I tried is the following:
```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(38400);
  Serial.println("Enter AT commands:"); // a prompt in Serial Monitor
  // Deleted while loop, unnecessary

  mySerial.begin(38400);
}

void loop() { // run over and over
  //if (Serial3.available()) { // we don't use Serial3 any more
  if (mySerial.available()) {
    //Serial.write(Serial3.read());
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    //Serial3.write(Serial.read());
    mySerial.write(Serial.read());
  }
}
```
Which I blatantly ripped-off from [this answer][2], with minor changes.

So, I connect my Arduino to my PC, upload the code, connect my module, set the serial monitor's baud rate to 38400 and...a bunch of gibberish appear on screen, just an alternating sequence of the characters *'x'* and *'?'*, to my understanding that's actually the message *"Enter AT commands:"* written in my code...

Now, with this exact setup, I'm now actually receiving a response to my commands, except the response is also gibberish, this is as far as I've gotten.

EDIT: By following some of the comments and setting the Serial baud rate to 38400, I managed to get other Reponses to my commands, but it's just a new type of gibberish and it's still not actually responding to my commands.

The thing is, all of the tutorials I've seen online are contradicting each other, some connect the RX and TX pins in reverse to the Arduino, some don't, some specify other pins on the board, some don't bother with the ENABLE pin entirely, some don't use a voltage divider, some connect VCC pin to the 3,3V instead of the 5V, some even skip the AT-Command setup entirely!

One last detail I feel like I should mention, **there's a red light that blinks on and off every two seconds**, I believe that means the module is read to receive commands but I've seen contradicting information about this as well so I'm not sure.

I want to know what I'm doing wrong, and what's the right way to do this?

  [1]: https://i.stack.imgur.com/IIk7l.png
  [2]: https://arduino.stackexchange.com/a/53794/73186

body:
You have seen contradictory statements, because there are many variables here, that might be different for each of the tutorials.

> some connect the RX and TX pins in reverse to the Arduino, some don't, some specify other pins on the board

There are basically 2 ways to communicate between the Serial Monitor and the HC-05:

- You can connect the HC-05 directly to the USB Serial chip on the Arduino board, thus you would communicate directly with the HC-05. In that case the `TX` and `RX` pins are used, since they are connected to the USB Serial chip. But the labels `TX` and `RX` are referring to the Arduinos chip (Atmega328p at the Arduino Uno). Since serial connections need to be connected alternating (RX to TX and TX to RX), the pin labeled `TX` leads to the `RX` pin of the USB Serial chip and vice versa.

    Thus you would connect TX of HC-05 to the TX pin on the Arduino and RX of HC-05 (through the voltage divider) to the RX pin on the Arduino. Also you should program the Arduino with an empty sketch before doing that, so that the Arduino does not interfere in the Serial communication with its own Serial usage.

- Or you can use a `SoftwareSerial` interface and let the Arduino code translate between the devices. The Arduino received from the PC and sends the data to the HC-05. Also it receives from the HC-05 and sends that data to the PC. This is what you were trying. But you absolutely need to specify a different set of pins for the `SoftwareSerial` interface, than 0 and 1. These pins are doing the hardware Serial interface, which is connected to the PC. So change these pin numbers (for example to 2 and 3).

    In fact: Whenever you see a code for Uno, Nano or Mega using `SoftwareSerial` on pins 0 and 1, you can be sure, that it is garbage.

>  I connect my Arduino to my PC, upload the code, connect my module, set the serial monitor's baud rate to 38400 and...a bunch of gibberish appear on screen

Even when you change the pins as described above, your code still uses 9600 baud for the connection to the PC. When you set the Serial Monitor to 38400 while the code uses 9600 baud for that interface, you will get just gibberish. Either change your Serial Monitor to 9600 baud or change your code to `Serial.begin(38400)`. The last option is better, since that makes sure, that you are using the same baudrate for both interfaces.

> some don't bother with the ENABLE pin entirely

The ENABLE pin seems to have a pulldown resistor on the HC-05 board, which pulls it to ground, when nothing is connected. Ground means data mode, HIGH command mode. So when they don't connect anything, they want to stay in data mode. Though this also depends on if the specific HC-05 board has a pulldown or pullup resistor there. Pulldown is more likely, but since there is no one single producer of these modules, you cannot be sure. Since you want to get into AT mode, you should use command mode and connect it to 3.3V. For normal operation it would go to ground. Though you can also connect it to a digital output pin of the Arduino and let the code decide in which mode the module should be.

> some don't use a voltage divider

The chip on the HC-05 board is a 3.3V device. The actual breakout boards, that can be bought everywhere, mostly only add a voltage regulator from 5V to 3.3V, an LED for status display and break out the necessary pins. The data pins are mostly directly connected to the chip. There are many resources, that claim the HC-05 to be 5V tolerant, but also many that antagonize that. To be sure not to destroy the HC-05, you should also use a voltage divider.

> some connect VCC pin to the 3,3V instead of the 5V

This is only done, when the used board does not have a 5V to 3.3V voltage regulator. Depends on the exact board, that you own.

> some even skip the AT-Command setup entirely!

When they don't need to configure the HC-05 in a special way, why would they go into command mode. That might be different for you.


message:
nuttx hex too large

I have a teensy 4.1, and I am trying to install NUTTX the Real Time Operating System ( RTOS ). Teensy is a supported platform.
I am trying install nuttx compiled from source, and upload it using the [teensy loader program][1]. my current issue is that the hex file is too large. the file size is 229Kb, which shouldn't be an issue where the flash size for a teensy 4.1 is 8MB.

 I have been following the steps on these websites:
this one where [Nuttx is installed on a teensy 3][2], and the documentation for [nuttx on their website][3]

any tips or recommendations to install nuttx on a teensy 4.1 would be greatly appreciated.

[![nutt.hex file too large][4]][4]

  [1]: https://www.pjrc.com/teensy/loader_linux.html
  [2]: https://acassis.wordpress.com/2016/04/16/running-nuttx-on-teensy-3-1/
  [3]: https://nuttx.apache.org/docs/latest/quickstart/compiling.html
  [4]: https://i.stack.imgur.com/gqszO.png

body:
OK, so I pressed the reset button and the teensy loader program reset, and reloaded the hex file. Now it lists as I would expect it to, using 1% of the flash space. and uploads without error. [![enter image description here][1]][1]

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


message:
PWM and Analog Signal Quality

I'm converting a 0-5v PWM signal to an analog signal using an LM358D. I've connected the output to an oscilloscope to look at the signal but I'm not really sure what I'm looking at. The PWM looks ok but I'm unsure of the analog signal.

Here's some images, please let me know what you think.

Both pics are at 50% signal strength. The oscilloscope is set to defaults, simply connected the probe.

Thanks

![Text](https://i.ibb.co/PmJqFQ2/CAM02299.jpg)

![Text](https://i.ibb.co/P5pr78T/CAM02304.jpg)

**EDIT:**

Here's the schematic for the PWM to analog converter. The cap is a tantalum. The dip switch changes the analog from 5v to 10v, the signal looks the same on both and is correct voltage so seems to be ok?

![Text](https://i.ibb.co/w73sThS/pwm-to-analog.png)

body:
Something like this should work:

[![PWM to analog circuit][1]][1]

With this code on a Uno:

    void setup () { }

    void loop () {
      analogWrite (3, analogRead (A0) / 4);
    }

For slightly more details see [my post about doing that](http://www.gammon.com.au/forum/bbshowpost.php?id=11395).

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


body:
> The PWM looks ok but I'm unsure of the analog signal.

The “analog signal” looks like the PWM smoothed by a first-order
low-pass filter. It still has some oscillations, 584 mV
peak-to-peak. If you can tolerate that, then it's perfectly fine. If
not, then increase the time constant of your filter.

A first-order low-pass filter behaves, in its stop band, like an
integrator. Thus, a square signal is turned into a triangle. You are
seeing exactly the expected behavior.

> The oscilloscope is set to defaults

There are no “default” settings in the oscilloscope. You probably used
the “autoset” button instead. This button tries to find some settings
that let you see _something_ on the screen. I mean, some kind of signal,
not just straight line. If the signal is almost flat, the autoset will
increase the gain until you can see it is not flat. In this case, it
increased the gain by a factor 10 (200 mV / division instead of
2 V used previously). It also added a negative offset in order to
avoid the trace going out of the screen. See the small pentagon on the
far left with a “1” inside? On the first picture this tells you where
the zero (the reference potential) is relative to your signal. On the
second picture, the polygon pointing at the bottom of the chart tells
you the zero is off-scale.

If you want to really appreciate the smoothing action of the filter, you
have to look at its input (the PWM signal) and its output (the “analog”
signal) using the exact same settings. Connect the input, hit “autoset”,
and look. Then connect the output, _do not_ change the settings (do not
hit “autoset”) and look at the output.

Better yet: forget the autoset button, adjust the settings manually and
mind their values.

Better yet: as you have a two channel scope, display _both_ signals
simultaneously, using the exact same settings on both channels.