text:
LF: flexible scheduler/timer library
I'm working on a few arduino projects where I've needed a flexible scheduler and/or timer library and was wondering if anyone has a library they recommend?
Case 1:
I have a sensor that needs to collect observations every hour, but it has a specific  measurement sequence:

Power up/boot (takes about 15 seconds)
Warm-up for 60 seconds.
Observe (2 min), collect raw data, generate stats
Cool-down for 5 min.
Power off

In this case have a single micro-controller acting as a data-logger that is controlling multiple sensors and writing to an SD card.
Case 2:
I have an oven that needs to be controlled to a user-specified temperature profile (up say to 6 points of change), i.e.:

Turn on heater
Set temperature, 100C and hold for 2 min
Set temperature, 160C and hold for 15 min
Set temperature, 250C and hold for 1 hr
....
Set temperature, 100C and hold for 1 hr
Turn off heater

I'm familiar with non-blocking timers and (in the past) have cobbled together a few simple timers with millis() and some ulong variables. Alas, the complexity and debugging time rapidly grows with the number of dependent timers. Before I sit down and sketch out a class definition, I figured I'd ask what others are using.

You could use a RTC for more accurate timing.

You might want to take a look at Arduion_FreeRTOS which implement an FreeRTOS kernel under the Arduino environement.

Some libraries I find good (opinion-based):

TaskManagerIO: https://github.com/davetcc/TaskManagerIO

does a good job at managing events / scheduling things for a certain (system) time, or even repetitively.
with that you could e.g. use a scheduleFixedRate() API to call a function every 60 minutes. Then starts the power up (I assume asynchronously, by setting a pin or something), and just primes the scheduler with the scheduleOnce() API to call another function in 15 seconds. That target function then starts the warmup and schedules the next function / step for 60 seconds into the future, et cetera. It would express the flow very naturally.

If accurate timekeeping is needed so that it's really every hour, you might want to  use an external RTC module. Also depends on the microcontroller you're using, many have a builtin one that you can feed with a 32.768 kHz crystal and thus you don't need an external chip

library for the DS3231 / DS3232 RTC lets you set an alarm in the RTC: https://github.com/JChristensen/DS3232RTC/blob/master/alarm-primer.md
with that you can e.g. set an alarm for every 60 minutes and then execute your task.


text:
Arduino MPU6050 AD0 Tricks with offset setting gives corrupted data
I am currently experimenting with two MPU6050 which the AD0 is connected via PIN 7 and PIN 8 respectively, and if this is working, I plan to add another 2 more MPU6050 to it.
I am using i2cdevlib's MPU6050 library and what I did in a flow is:

Initialize one MPU6050 object
Set MPU6050 Object as 0x68 (LOW AD0)
Set all to HIGH, but one to LOW (to select the MPU6050)
Calculate offset and calibrate, store everything in array. (offsets and etc)
Repeat steps 3 to 4 unless all are calibrated.
Start to loop between two MPU, setting everything to HIGH and the one to be used as low.
Write the LOW's (current selected) MPU with offset that is stored in array, then getMotion6 (Raw data).
Write selected MPU to high, repeat from step 6 to step 7.

Everything is working, however when I am having a loop to collect data, it gives me corrupted data, the problem I find is in this function
void loop{
    for (int i = 7; i <= 8; i++) {
      pinMode(i, OUTPUT);

      digitalWrite( i, LOW);
      //      Serial.print("\nWriting pin: ");
      //      Serial.print(i);
      //      Serial.println(" to LOW");
      delay(2);
      int index = i - 7;
      Serial.print("Offsets:\t");
      Serial.print(ax_offset[index]);
      Serial.print("\t");
      Serial.print(ay_offset[index]);
      Serial.print("\t");
      Serial.print(az_offset[index]);
      Serial.print("\t");
      Serial.print(gx_offset[index]);
      Serial.print("\t");
      Serial.print(gy_offset[index]);
      Serial.print("\t");
      Serial.println(gz_offset[index]);

      accelgyro.setXAccelOffset(ax_offset[index]);
      accelgyro.setYAccelOffset(ay_offset[index]);
      accelgyro.setZAccelOffset(az_offset[index]);
      accelgyro.setXGyroOffset(gx_offset[index]);
      accelgyro.setYGyroOffset(gy_offset[index]);
      accelgyro.setZGyroOffset(gz_offset[index]);

      Serial.print(accelgyro.getXAccelOffset()); Serial.print("\t");
      Serial.print(accelgyro.getYAccelOffset()); Serial.print("\t");
      Serial.print(accelgyro.getZAccelOffset()); Serial.print("\t");
      Serial.print(accelgyro.getXGyroOffset()); Serial.print("\t");
      Serial.print(accelgyro.getYGyroOffset()); Serial.print("\t");
      Serial.print(accelgyro.getZGyroOffset()); Serial.println("\t");

      //      delay(1000);
      //      accelgyro.getMotion6(&ax[index], &ay[index], &az[index], &gx[index], &gy[index], &gz[index]);
      int ax, ay, az, gx, gy, gz;
      accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

      Serial.print("PIN ");
      Serial.print(i);
      Serial.print("'s data is:");
      Serial.print("aX:" ); Serial.print(ax); Serial.print("\t");
      Serial.print("aY:" ); Serial.print(ay); Serial.print("\t");
      Serial.print("aZ:" ); Serial.print(az); Serial.print("\t");

      Serial.print("gX:" ); Serial.print(gx); Serial.print("\t");
      Serial.print("gY:" ); Serial.print(gy); Serial.print("\t");
      Serial.print("gZ:" ); Serial.println(gz);

      pinMode(i, INPUT_PULLUP);
    }
}

The first few loops will return accurate data (as in, all the sensors are close 0 [no motion])
I am suspecting because there is a huge difference between both sensors and the getMotion6 is comparing with the old sensor, can that be the case?
Attached is the output of my sensors reading, untouched.

source: Stack Exchange

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

sort: votes


text:
External vs arduino power supply for servo motors?
I recently created a project that involves the control of three SG90 servo motors. I started off by controlling this through the 5V output pin of the Arduino Uno, with the Arduino powered through the barrel plug with a 9V mains power supply.
However, the servos couldn't perform the full 180° sweep, it would appear to be due to the high torque at the end of the motion for my application.
I then switched to powering the servos separately to the Arduino using four AA batteries in series. I now had no issues with the servos stalling and could perform the full sweep.
I am not sure why this is though?
Four AAs in series will result in 6V, which is not that different to the 5V Arduino output pin? And it seems the current is the issue with servo stalling? and surely the number of batteries makes no difference to this as connected in series it stays the same? Is the current of the AA battery just higher than the 5V Arduino output pin?
Any help would be greatly appreciated, I'd really like to have a better understanding of this.

How much current does each SG90 servo draw? How much current can the Uno 5V regulator provide?

@VE7JRO I'm unable to measure the current directly but from some measurements I found online it appears the typical current during operation of the servo is 100-250mA with a stall current of 360mA. It appears the voltage regulator can get up to 800mA if pushed to the limit. Please note all the sources I got these values from may be inaccurate.

Here's some info on the SG90: https://arduino.stackexchange.com/a/49755/37523  I'm not sure what type of voltage regulator on your particular Uno, but heres some info on that: https://arduino.stackexchange.com/a/43894/37523

For controlling more than one/two max servo you should use a motor shield (h-bridge) or something like a PCA9865 board with external power supply. You get funny effects with three servos attached to the UNO when trying to do syncronized sweeps or high torque at the same moment in all three servos. Invest in that hardware, if there is enough Amp (1.5A and up depending on the num of servos) you could use a single PSU for both.

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


text:
Updating mysql data using SIM900 and Arduino
Thanks in advance for your kind support.
I am not an expert but have little understanding of concepts and trying to integrate various things to get some useful projects for my purpose. I want to update the database (MySQL) on shared hosting using the SIM900A module and Arduino nano board. With help of examples shared on this platform and my understanding, I achieved a significant part of the same.  The following is the approach I have adopted and the current status:
I have put a PHP code on the server (shared hosting) to update the database once it received the GET request
I have also uploaded the code in the Arduino with proper connections for sending requests to the server.
Problems I am facing:
I am not able to update the data on my specific database, through the Arduino sent request. the same code is working with Thingspeak, My code is also working otherwise, as I have tested through web form request and URL request. I am not sure where is the problem.  I am also not getting any errors. The response to the AT request is "OK" only
Though I can update the Thingspeak channel, only till the command lesser than 61 characters, which are sent after the AT+CIPSEND command. There is no error, even if the request size increases, but data updated only till 61 characters (including \x1A character)
"I am wondering, is this the limit, that cannot be increased or there is some possibility to increase it."
I understand that the problem appears to be in approach and not in code, as the code is working in itself. However, please let me know, which code I need to share, as it is a multifile code on the web-editor

I have faced a similar issue. It happened due to an SSL issue. You can find all info about it here - https://stackoverflow.com/questions/62950561/sim800l-gsm-module-working-with-http-and-shows-error-with-https-why


text:
It is possible an Arduino generate 3d graphics on tft or vga
It is possible to an Arduino render 3d graphics like very low polygonal 3d models or generating lighting efects non realtime shadows or realtime shadows and reflections. Rendering like first 3d video game consoles.
Someone can ask why you don't use an Rasberry Pi. Beacuse Linux can be more complex. Also Rasberry Pi is a computer runs Linux .Linux is hard and some people can say you can install Windows but it doesn't give freedom as Arduino on Arduino you have more control on system.It doesn't run operating system but Rasberry pi runs and you needed write programs for it. You can't do much  anything ( at least i know) than Linux or Windows will allow.
My goal was running very basic 3d graphics on a Vga.
Theres no rule it can be like old dos games.Fake 3d effect like distorting sprites to look like 3d and rotate them move change coordinates change camera position like a 3d but it's actually generating fake depth.
Must camera position controllable . Like a video game.
Sprites,effects are completely pre rendered. Only realtime rendered thing was distorting sprites by camera position. Changing room (Square area will reset view that will make after another room it would show another room).
Is there a library can done that?
Your solution can be for another Arduinos.
Your solution can be Arduino dependent. Like only works for due,mega etc.
Theres a vga library for Due supports 256 colors your solution can use this library problary called DueVGA

Completely possible, and it had already been done. http://crawlingrobotfortress.blogspot.com/2015/12/better-3d-graphics-engine-on-arduino.html And there are even sources (check "examples" folder) https://github.com/michaelerule/Uno9341TFT

While there is no VGA library for Arduinos with AVR, there is one for ESP32: ESP32 VGA Library.
It makes heavy use of the Hardware capabilities like I2S that are not present in in Arduino.

VGA
I suggest you build the famous world's worst video card. It's a great project and you'll definitely learn something when building it.
That graphics card uses only 2 bit per base color, which is 6 bits in total, or 64 colors. The resolution of the graphics card is 100x75 pixels. An image can basically become as good as

That picture is still 100x75 = 7.5 kB in size. That means it does not fit into the 2 kB of RAM of an Arduino Uno.
To clock the graphics card, Ben Eater uses a 10 MHz crystal to get the timing right. That means, your Arduino needs to output one color at a speed of 10 MHz. That's clearly not feasible for an Arduino Uno running at 16 MHz.
However, an Arduino Uno is nothing without some hardware attached. You could try to calculate the 3D graphics on the Arduino and write the results into an EEPROM (just like Ben Eater's graphics card) and let the EEPROM handle the output of the colors. That way, you could certainly generate single images. The frame rate will definitely not be high.
But: your request is not far fetched. My first computer, an Apple IIe was running at 1 MHz speed - but at least it had 64 kB of RAM. It could do all sorts of stuff, although I can't remember a 3D game. Using an Arduino Due with 84 MHz and 96 kB of RAM should be a realistic approach - and probably the reason why DueVGA exists.
TFT
A TFT display already has its own memory, so you needn't worry about that aspect. People already did 3D rendering, although they were going through a lot of problems that I mentioned for VGA before. It requires a lot of optimization. A library is the ATmega328 Tiny 3D Engine.
With shading it seems to render up to 3 frames per second on an Arduino, which is likely not enough to for smooth interaction.
Raspberry Pi

Linux is hard

Some Linuxes are. Especially Kali Linux. But Raspbian is really a good OS for the Raspberry Pi. We are teaching internships Linux + Shell + Python in 1 week (like this project). It's enough to focus on the programming. Not much configuration needed.

You can't do much anything ( at least i know) than Linux or Windows will allow.

That might be true. However, I am developing software that runs on operating systems since 1996 and have never had the feeling that the operating system restricts me from doing something. In the opposite: the OS provides features that would be very hard to implement on my own.

Thanks but i saw some people really rendering 3D on Arduino: https://hackaday.com/2016/01/02/better-3d-graphics-on-the-arduino/ (TFT) Also i remember theres a library for noki a lcd's but i don't know but i can't find code for it. Even i do it. It just be distorting shapes for look like 3d. It  will not render as showed in article.

@IWantJustBasicCollisions the guy in that video is doing VERY advanced optimization and going to great, elaborate lengths to create seemingly impressive, but actually rather crude results. They are not really practical for a game. If you want to write video games, use a platform that has a built in video output with graphics support. Rolling that stuff yourself is really, REALLY hard, and the results are pretty limited.

You can definitely render 3D graphics on an Arduino-based MCU & TFT and I have done exactly that with Teensy.
It requires quite a bit of work to implement software rasterizer though and I'm not aware of an off-the-shelf 3D library you could use. I would think that someone has written a 3D graphics iib though, so might be good to scour GitHub if you don't want to write a rasterizer yourself.
There are plenty of different TFT options with both SPI (serial) and 8/16bit parallel interfaces you can use and have decent frame rate. E.g. with Teensy you can update a 320x240x16bpp screen over SPI at ~30fps. You can also pass SPI data transfer to DMA to free spending MCU cycles for it if your MCU supports it. With parallel interface you can bit bang the data to TFT faster and have potentially higher frame rate, but then you have to waste MCU cycles for the data transmission.
Newer Teensy models has plenty of RAM (1MB) for 3D rendering but it can be quite challenging to render 3D graphics on some MCU's with only few kilobytes of RAM. I'm using tiled rendering, which renders a frame in small tiles (e.g. 64x64px) and thus doesn't need to maintain the whole frame & depth buffers in memory. Because of this I was able to get the 3D renderer running on Teensy LC, which has only 8kb of RAM, but it's much slower and simpler 3D model. I also store the 3D assets (geometry, textures) in the MCU flash in format that can be directly used for rendering to save RAM.
You can also implement texture sampling on MCU, which opens possibility to implement various different effects, like sprites you mentioned.

On AVR based Arduinos: No, definitely not. It is possible to create a VGA signal, but only with very limited resolution and few colors (like 4 or so) and also a framerate, that will not be enough. Also they all have too few memory.
It might be possible on the Due (don't have much experience with it), but it is still a bad choice for a platform (also partly because the Due is in general such a bad designed board with no good documentation).

Is there a library can done that?

I don't think, that you will find any library doing all what you want. You might find libraries, that help you draw on the display, but you will do all the hard stuff (creating and loading sprites, distorting them, animating them) yourself. This is, because Arduino is a bad choice for such a project.
Also: In the title you mentioned TFT. I guess you meant one of the TFT display modules, that you can connect to Arduinos. Forget about that. They are connected over rather slow serial data interfaces (not meaning the Arduino Serial here, but serial interfaces like I2C or SPI). You won't get a sufficient frame rate with them.

I would oppose your arguments against the Raspberry Pi. Sure, it has an OS, but that also means, that it can make use of a variety of languages and frameworks. You are not bound to plain C/C++. You can use the language or framework, that best suites your needs. That can be a bit complex at first to find the right one. But thats, because your project is complex. What you are describing is a very complex task, when you cannot rely on others, that have already implemented the hard stuff (which would be the case for the Arduino).
Also a Raspberry Pi has plenty of RAM and plenty of storage space. It runs at high speed and is actually capable of outputting video with a good framerate.
Without wanting to offend you: I think, as you are asking this question here, you are not qualified enough yet to do such a project on an Arduino. There are insanely capable people out there (wouldn't count myself to them), who do incredible things with Arduinos by milking the very last drop of resources out of them. But they are doing it for the grind, not for having a functioning product at the end. I guess you want this to work good at the end, without needing you to work on it for many years. Then you are result-focused and should choose the correct platform for this. A computer (like the Pi) will be easier.

Rasberry Pi had lot of things but some of them are unnecessary.

Yes, but is that really a problem? Is the unused potential really a no-go for the project? You could say the same thing about an Arduino. It has a lot of peripherals build in (depending on type Timers, Comparators, ADCs, DACs, several communication interfaces, power management peripherals, ...). Almost no project uses all of them. But that's simply the difference between general purpose chips/boards (like all Arduinos or Raspberry Pis) and custom made chips for a single purpose. If (!) a fitting chip for your project exists, that really only has what you need, it will most likely be very expensive. Chips for a single very narrow purpose have a very narrow target group, thus are more expensive (simple economy here). Companies have formally nearly everytime designed their own chips for gaming consoles (which is way beyond your current scope), like PS1 or N64. Current gaming consoles rely often on modified standard hardware, also because it is cheaper. The really old gaming consoles used the generic electronical chips, which means, that you didn't have one single programmable chip. Instead lots of the logic was build into the electronic design.
So you will always have some excessive features, that are not used. Why would you want to remove them from the project, just for the fuzzy goal of not wasting features. It will make your project only more complex and expensive. You will gain nearly nothing from minimizing the resources. This is a hobby project, not for selling it.

In rasberry pi you just writing a computer program.You don't have much control like arduino

That depends on what type of control you mean. On a computer you are writing code on a higher level of abstraction. That also makes it easier to do complex things, since you can rely on the low level programming of others. What control do you want to have over the system, that you don't have on a computer like the Pi? Do you think, you can program better display drivers or graphic renderers, than all the other people? Then you can still do that on the Pi. A Pi also gives you control over the GPIO pins, which let's you do many hardware things, that you can also do on an Arduino.
Also Linux is open source. If you think, you need more low level interaction with the hardware (cannot think of a reason for needing it), then you can build your own OS, which gives you the needed freedom. Sure, that is very complex. But when you are able to use the low level programming, then you are also able to change the OS.

You seem to already have chosen the Arduino for your project. I, like others, have advised you to use a Pi instead to make it a lot easier and better. It is up to you, if you want to believe us or not. All in all I'm still not convinced, that you are able to pull that off on the Arduino platform, while still getting good results. You are simply not at that point of knowledge yet. You write confidently about the problems with an OS, while you don't seem to have a concept about the exact structure of these problems and how they impact you. We will not prevent you from doing it the hard way. Please for free to choose your own way.

You are right but Rasberry Pi like overkill . Also i don't want build a computer in my goal. Also on rasberry pi and other linux systems had very complex commands. Running 3D graphics on rasberry pi just making a video game for just a linux computer. Arduino feels more user friendly also i didn't used Linux i used in school on smart boards it's not a Linux Linux-Based os called Pardus can run some exe files if i remember correctly

I don't think, that a Pi is overkill. It is a good way to go for a beginner. You could use the Pi Zero, which is very small (smaller than an Arduino Uno). The commands can be less complex than on Arduino, because you don't need to do the nitty optimization stuff. But sure, I don't prevent you from doing it with Arduino. If you like the very steep learning curve, then it is good. Not just something I would recommend

In rasberry pi you just writing a computer program.You don't have much control like arduino(at least i know). It just a program runs on a rasberry pi. Rasberry Pi had lot of things but some of them are unnecessary. Is there another embeded system had 1 gb ram but doesn't run os like rasberry pi does. You have full control over system. Microcontroller or Microprocessor supports 1 gb of ram and rendering 3d (like ps1).I don't want os even it had os It just like MS-DOS. Linux or Windows. You still depending on os. If you just want special tasks run. Not like explorer.exe running background or etc

A Raspberry pi is not overkill. It's the right tool for the job. An Arduino is woefully under-powered to do ANY kind of graphics. It's too slow, has too little memory, and has too low I/O bandwidth. Most Arduinos don't even have enough RAM to display a single frame of VGA color graphics, never mind the memory needed to manipulate an array of vertexes and render it to full-screen color output. Then there is the fact that they don't have native floating point, and you really need specialized graphics hardware to do 3D graphics with a decent frame-rate. (Software floating point is SLOOOOOOOOOW.)

@IWantJustBasicCollisions I added some explanations to address directly some of your arguments. I don't think, that you are right. Though, as you already seem determined to stay on the Arduino framework, this is the last piece, that I will write for this question. You can choose the easy or the hard way as you like. Please decide yourself on what you want to do.

Actually you are right can i install dos like operating system. Linux or Windows like overkill. I just don't want os running and just a program popup draw 3d graphics etc. Even it was running os i want code it like arduino(arduino actually not an os justa program) i just want direct program and none of another programs don't run like explorer.exe does run on background etc. Even it will running linux only 3d application and critical system apps must run. Wallpaper desktop must invisible. Linux themes etc.  must gone. Like ps1. It just run programs for 3d rendering other programs wil not run

I disagree with your premise. If you use a high-end Arduino, like one of the ones based on an ARM processor, and you optimize the snot out of it, you might be able to generate crude VGA level graphics, and gin up some 3D looking images. But expect to spend a lot of time on very fussy timing code that requires a LOT of expertise to get right.
(An Arduino does not have any display driver at all.)
You want a device that can output video through hardware. A Raspberry Pi is a much, much better choice. Sure, it runs UNIX. UNIX isn't going to bite you. Roll up your sleeves and


text:
NeoPixel Gradient sweep function

I'm trying to create a function that takes two colours and creates a smooth gradient between them one colour at the beginning and one at the end
I just can't figure the math of mixing them evenly
I'm using neopixel library

I can think of two ways of doing this.
One is to use the H channel of the HSV colour space (as I show in the answer to this question. This would give you a smooth transition between two colours through the pre-defined spectrum of the hue range.
The second is to simply specify two colours and then mix them at different percentages depending on how far along the length you are.
For example, here's a (untested) small function that "mixes" two individual colour channels together and returns the result:
uint8_t mix(uint8_t a, uint8_t b, int pct, int range) {
    if (pct <= 0) return a;
    if (pct >= range) return b;
    return (((uint32_t)a * (range-pct)) / range) + (((uint32_t)b * pct) / range);
}

pct is the led number in your chain, and range is the total number of LEDs.
So you could (hypothetically):
uint8_t red1 = 0, green1 = 255, blue1 = 0;
uint8_t red2 = 255, green2 = 100, blue2 = 100;

for (int i = 0; i < 50; i++) {
    uint8_t red = mix(red1, red2, i, 50);
    uint8_t green = mix(green1, green2, i, 50);
    uint8_t blue = mix(blue1, blue2, i, 50);
    setLedColor(i, red, green, blue);
}

Very clever
However, only one LED lights up, sorry I can't debug it myself :<

My sketch: https://pastebin.com/0fYD6w3y

the sketch belongs in your question as text, not as a link ... please edit your question ... format the code properly using the {} button

The 50 in my example code is the number of LEDs. Obviously you need to tune that to the actual number of LEDs in your setup.

I tried both 8 leds and 50 and 7 counting from 0 but i think that even with more leds in sketch more than 1 led would light up

In the 2nd block of code on this answer, I believe all occurrences of 50 should be a reference to the variable holding the number of LEDs. Without it, you may not be notice the difference between the 8 LEDs depending on your initial color choices.
Also, and I think this may be your main issue -- I use a different NeoPixel library, but I would assume it is likely similar. After setting pixel values, I have to call strip.show() before the LEDs reflect the values I want.


text:
Detecting a finger snap(basically trying to replicate infinity gauntlet)
I am trying to make an infinity gauntlet. So it's obvious it should have a snap feature(which will switch of a light,motor or whatever). But I don't know how to go about sense this snap. I thought of two ideas: one detecting the snap sound but since I will be wearing a glove it can't be heard loudly, second is, trying to detect the pressure between thumb and middle finger and calculating velocity of middle finger during the snap. And I even found EMG sensor can be used but it's too costly so suggest me best way possible with proper explanation
P.S: This is my first ever Arduino project

How about a piezo sensor on the middle fingertip that detects the sharp blow of the finger snap? (plus some electronics to bring the signal into the right voltage range for a logic signal)

you could always simulate the finger snap by the use of an appropriate sound effect

i just checked to see how else you could detect a finger snap ..  some of the tendons on the inside of the wrist make a distinct motion ... perhaps a wrist band with integrated pressure sensors could pick up the tendon motion

"This is my first ever Arduino project". Good luck. Be open to "simpler" solutions, too. E.g. building a switch by touching thumb with another finger.


text:
How to fix "expected primary-expression before '%' token" error code?
I'm trying to use this code to get temperature and humidity values from DHT11 sensor and send it to Python and I need to write the temperature and humidity values in the same line. But I keep getting the error code

expected primary-expression before '%' token

How can I fix this?
#include <dht.h>
#include <stdio.h>
int a = 0;
int b = 0;
char buffer [64];

dht DHT;

#define DHT11_PIN 7

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

void loop(){
  a = DHT.temperature;
  b = DHT.humidity;
  int chk = DHT.read11(DHT11_PIN);
  sprintf(buffer, %d %d, a, b);
  Serial.print(buffer);
  delay(1000);
}

The error mentioned a line number.  Did you look at that line?

You are missing quotes on the second parameter of sprintf:
sprintf(buffer, "%d %d", a, b);

please don't answer syntax error questions. they are off-topic


text:
Plug in analog sensor into digital pin
If I take an Arduino (samd21, if it matters) and plug in an analog sensor/pot into a digital pin and then set that pin to be an input, would digitalRead(#) trigger HIGH and LOW at some threshold point?  Or does it not work at all?

I don't have the parts

According to SAMD21 the digital input pin detects HIGH if the voltage on pin is higher than 0.55 of supply voltage. So at 3.3 V it is 1.8 V.
The input pin detects LOW if the voltage is lower than 0.3 of supply voltage. It is 0.99 V at 3.3 V.
For voltages between these values (1 V to 1.8 V) the result can be HIGH or LOW.

Yes. If you read the datasheet you will find a set of voltage specifications. The ones you are interested in are VIH and VIL.
Most MCUs use a "Schmitt Trigger" for the inputs. This means that when the voltage rises above the HIGH threshold (VIH) the input switches to HIGH. When the voltage drops below the LOW threshold (VIL) the input switches to LOW.  This "hysteresis" provides a certain amount of noise rejection to give a clean digital input signal.


text:
Resuming Serial Connection after sleep on Arduino M0
For debugging purposes I want my serial connection to resume after sleep.  After running LowPower.sleep() from the <ArduinoLowPower.h> library, I don't get any new serial messages in the serial monitor.
Several factors seem to be at play (which I've listed at the bottom) and I've developed a partial solution but it's not great because it requires some long artificial delays of about 1 second after each sleep to resume the serial.  So to recap, my question is how I can get serial to work after sleeping the microcontroller without having to insert long delays.
For background, I am using an Adafruit Feather M0, which I think actually uses SerialUSB and automatically converts serial commands to that according to the guide, but I am not sure what any of that means.
Here's some stuff I looked into:

COM Port: One factor is that the Arduino disconnects from the my Windows 10 computer at sleep and reconnects when it wakes up sometimes on a different COM port.  Using the program Tera Term instead of the Arduino IDE Serial Monitor seems to keep it on the same COM port.

Serial Flush and End: As notes in my code example, both of these commands seem necessary before sleeping or else I won't receive new messages after sleep.

Delay: Seems that the arduino can send messages right after waking up that Tera Term wont see.  I have to put a delay of 1 full second after waking up or else I won't see the messages.

Here's some code I have tried.
#include <ArduinoLowPower.h>

void setup() {
  Serial.begin(115200);
  while(!Serial){delay(10);}
  Serial.println("start");
}

void loop() {

  Serial.println("");
  Serial.println("sleep");
  Serial.flush();  //if this line is commented out, only one cycle of "sleep" will show
  Serial.end();   //if this line is commented out, only one cycle of "sleep" will show
  //delay(2000);  //doesn't seem to fix anything so commented out
  LowPower.sleep(2000);
  delay(1000);  //at 750 misses some "awake" messages
  //Serial.begin(115200);  //this line doesn't appear to fix anything so commented out
  Serial.println("awake");

Output:
start

sleep
awake

sleep
awake

sleep
awake

while (!Serial);?

so i have a chance to open the serial on my computer before it goes nuts


text:
Switching 4.2V circuit with 3.3V Arduino GPIO
I am trying to learn about MOSFETs and see this p channel MOSFET and this tutorial.  I am trying to use a 3.3V arduino GPIO pin to control a load that is powered from a 4.2V battery in much the same configuration as the circuit drawn in that tutorial.  Most other tutorials I see say the Gate Voltage needs to be equal or greater than the Source Voltage, but the tutorial I cited describes that actually the Voltage between the Gate and Source just needs to be more negative than the Threshold Voltage.  The P channel mosfet I cited is Vthreshold -2V to -4.  So my question is whether this P channel MOSFET would allow me to use a 3.3V arduino GPIO to control whether that 4.2V source is closed or open to the drain/load.  Looking at how that tutorial does the math, it seems in my case the GPIO being off would mean Vgs is 0 - 4.2 = -4.2 and therefore the MOSFET is in the ON state.  If GPIO is on at 3.3V then Vgs is 3.3 - 4.2 = -0.9 and therefore the MOSFET is OFF.  However, the tutorial doesn't say what happens when Vgate < Vsource but by an amount less than the Vthreshold so I don't know if my math is right.
In sum my questions are:

Is my math and prediction of the MOSFET states correct when that 3.3V GPIO is on or off?
If not, is it because of some other quality in this MOSFET and a different P MOSFET would work?
I presume that if I keep out of the Vgs upper and lower bounds then I avoid issues where the MOSFET is in a partially on and partially off state, is that correct?
Is it just impossible to use P MOSFETS in this way?

Note:  My questions only pertain to P MOSFETs.  For my project (switching a 1-2A disco light toy), it has to be a high side switch and that's even besides the point because I am more importantly trying to understand how the P channel mosfets work.

The threshold voltage is only critical when switching high currents. What's your load circuit? Is it in the order of mA or A?

I have three cases.  One is <200mA, another is 1A, the last is <2A

The MOSFET you chose will probably fail. Using a 30V device on a 24V system is asking for problems. Go to a minimum of a 60V MOSFET and use a UIS, Avalanche rated one. R4 is very week for what you need to do, I would suggest something in the 10K range to swamp out any leakage in the Arduino. If the MOSFET is properly rated the flyback diode is not needed but make a space for it incase you have to sub a MOSFET. Putting C2 in parallel with C1 will help. I do this a lot with electrolytics. I double up each one the needed size when one fails you don't notice it. I would suggest a couple of 220nF caps across the motor but that is application dependent.

The OP says he's switching 4.2v not 24v

OOPS right answer wrong question.


text:
Construct char arrays within function
I'm pretty new to C++ / Arduino code, please bear with me. Following code currently gives me a Exception (28): epc1=0x40201287 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000000 depc=0x00000000.
I suspect that this is because I'm trying to use the pointer to a local variable char parsedString in drawMenu() which is probably destroyed after running renderMenu() and therefor I get a memory related exception(?). Is that correct?
Secondly, if that is true, I'm wondering if I'm just simply trying too hard to avoid global variables, I already got a ton. And creating for every single parsing variable in a function sounds like overkill. What would be the most efficient way to render my menu?
void drawMenu () {

  char* lines;
  renderMenu(lines);

  for (int i = 0; i < menuMaxLines; i++) {
    Serial.println(lines[i]);
  }
}

void renderMenu(char* &output) {

  // Get current menu items
  MenuItem * menuCurrentItems = getMenuItems();

  // Loop out the menu items at the current position (menuPosition), don't exceed the count of menuitems (menuCurrentItemCount) and don't exceed more then the desired lines (menuMaxLines)
  for (int i = menuPosition; i < menuCurrentItemCount && i < menuPosition + menuMaxLines; i++) {

    MenuItem menuItem = menuCurrentItems[i];
    char parsedString[menuMaxLines];

    // Prefix for the menulabel, when focussed
    if (menuFocussedItem == i) {
      strcat(parsedString, "> ");
    }
    else {
      strcat(parsedString, "  ");
    }

    char output[i - menuPosition][menuMaxWidth];
    strcpy(output[i - menuPosition], parsedString);
  }
}

In renderMenu() you are trying to create an array with the name output (which would hide the parameter of the function) with a variable size. That cannot work. Arrays created like this need sizes known at compile time. Otherwise you would need to use dynamic allocation (using new). Why aren't you just creating a simple char array inside of drawMenu()?

Also: because of the parameter of renderMenu() is hidden, the pointer lines is never set to anything valid. Thus printing the elements of it means reading from invalid memory location. There is just no array allocated behind that pointer

@chrisl, gcc can create an array on stack with a variable for size.

Thanks @chrisl, I value your help. I keep forgetting that arrays need to have a fixed size. So your saying that your first comment could be fixed by using char* lines[menuMaxLines] in drawMenu()? And your second question, I first trying to make that array of char arrays in the function but I was unable to return that and therefor went with the out var. Are you able to provide me with a solution to that?

@juraj, you assumed correctly. It’s a const int


text:
Char buffer for serial input: char str[2] vs char* str = (char*) malloc(2)
I am using software serials on my Arduino nano to read data from my esp01 in functionality testing for the software serial. I simply make the esp01 to send a string "OK" to an Arduino's software rx serial port (in this case pin 9) , and then the Arduino prints it on the monitor via its hardware serial (USB).
I've found that when I allocate space for the string in Arduino using char str[2], the message seems to be correct. However, with char* str = (char*)malloc(2), there appear to be an unkown character tai
ling the string "OK"
Below is the code I use
#include<SoftwareSerial.h>

SoftwareSerial s(9,10);
void setup() {
  pinMode(2,OUTPUT);
  Serial.begin(9600);
  s.begin(9600);      // link to esp01
}

void loop() {

  if(s.available() > 0){
    char txt[2];
    int indx = 0;

   // read input
    while(s.available() > 0 && indx <=SIZE-1){
        char buff;
        buff=  s.read();
        txt[indx] =  buff;
        Serial.println(indx);
        indx++;

    }
   // bink an LED for debugging
   if((String)txt == "OK"){
    digitalWrite(2,HIGH);
    delay(500);
    digitalWrite(2,LOW);
    delay(500);
   }

   //reset index
   if(indx ==2){

     Serial.println(txt);
     Serial.print("Size of string:");
     Serial.println(sizeof(txt));
    indx = 0;
   }
  } // if(s.available())

}

here is the print-out of the serial monitor

That tailing square is the myster for me.
Any help would be grateful!!
Boris

To store two characters you need three slots in the array.  You forgot about the null terminator to mark the end of the string.  So depending on where the array is in memory there may or may not be extra junk behind it that gets printed because the string isn’t terminated.

you need 3 positions. 'O 'K' '\0'

Re “while(s.available() > 0 && indx <=SIZE-1)”: where did you define SIZE?

First, a few general notes:

The difference between char str[2] and
char* str = (char*) malloc(2) is irrelevant to you problem. It
changes the place where the array is stored, the meaning of
sizeof str, and malloc() will blow up your RAM if you call it
repeatedly and forget to free().
In your code, sizeof(txt) is the constant 2: the actual size in
bytes of the array txt, irrespective of how much relevant data it
holds.
You want txt and indxto remember their contents across calls to
loop(). You should either make them global or qualify them as
static.
Avoid the String class if at all possible. Here, since you use it
only to compare two strings, you can use the traditional
strcmp() function instead.

Now, the bulk of my answer is just about expanding on what has already
been said about properly terminating strings.
A string is a variable-length list of characters. Whenever you are
dealing with a list that has a variable length, you need to somehow keep
track of this length. There are two common ways to do so:

either you store the length in a variable,
or you put a sentinel value (a value that would be invalid within
the list) after the last element to mark the end of the list.

Both methods are valid, and I am going to illustrate both of them below.
However, in the case of strings, the C++ language uses method 2,
with the ASCII “NUL” character (numeric value 0) as a sentinel.
Method 1:
void loop() {
  static char txt[2];
  static size_t indx = 0;

  while (s.available()) {
    // read input
    char c = s.read();
    txt[indx++] = c;

    // report
    Serial.print("Received: '");
    Serial.print(c);
    Serial.print("', string: \"");
    Serial.write(txt, indx);
    Serial.print("\", size: ");
    Serial.println(indx);
    if (indx == 2 && memcmp(txt, "OK", 2) == 0) {
      Serial.println("Correct message");
    }

    // reset index
    if (indx >= sizeof txt) {
      indx = 0;
    }
  } // if(s.available())
}

Some things to note:

The indx variable holds the length of the string. It also happens to
be the index of the next available cell in the txt array, if any.
The string is printed using the
write(const char *buffer, size_t size) method, which accepts a size
as a second argument. Unlike print(const char *), it doesn't depend
on the string being NUL-terminated.
In order to check that we received “OK”, we have to check for both the
correct length (indx == 2) and correct contents. The contents is
checked using the memcmp() function, which can compare arbitrary
byte arrays and, again, does not depend on NUL-termination.
An important loop invariant here is idx < sizeof txt. It is true at
initialization and is restored by the “reset index” section at the end
of the loop. The “read input” section depends on this invariant to not
overflow the buffer.

Method 2:
void loop() {
  static char txt[3];
  static size_t indx = 0;

  while (s.available()) {
    // read input
    char c = s.read();
    txt[indx++] = c;
    txt[indx] = '\0';

    // report
    Serial.print("Received: '");
    Serial.print(c);
    Serial.print("', string: \"");
    Serial.print(txt);
    Serial.print("\", size: ");
    Serial.println(indx);
    if (strcmp(txt, "OK") == 0) {
      Serial.println("Correct message");
    }

    // reset index
    if (indx >= sizeof txt - 1) {
      indx = 0;
      txt[indx] = '\0';
    }
  } // if(s.available())
}

Again, some notes:

This is actually an hybrid of methods 1 and 2, as the indx variable
is still used to keep track of where to insert the next incoming
character. This just happens to be more convenient and efficient than
putting that character into its own length-1 string and using
strcat().
The array is now one cell longer, to make room for the terminating
NUL.
There is another loop invariant now: correct string termination
(txt[indx] == '\0'). This invariant has to be enforced both on
reading and on resetting.
The string being NUL-terminated, it can now be printed with print()
and compared with strcmp(). The string literal "OK" is guaranteed
to be NUL-terminated by the compiler.

This second method is generally safer because there are a lot of
functions and methods in Arduino and C++ that expect strings to be
NUL-terminated. If your strings are not, you have to be extra careful to
not use any of these string-oriented functions.

As others have pointed out, C strings are null-terminated. So to hold 2 characters of content you need a 3-byte array. Your code that reads the chacters into the buffer also needs to be changed. (That code isn't adding the required terminating null.)
You should probably rewrite your code to use the strncat() function.


text:
Serial Hangs with multiple PN532 nfc reader and a TCA9548A
I am trying to use multiple PN532 reader. I have put all my readers on a multiplexer (TCA9548A).
The script works well, but when I move my tags on readers sometimes the serial says to me there is an error on reading tag like that : Read failed [number] or like Error. Failed read page [number] where [number] is a Integer.
And sometimes the serial completely hangs and not sends anything anymore, I have to reset the arduino by pressing the reset button.
Other information :
Arduino : My arduino is a Mega.
Here is my code :
#include <Wire.h>
#include <PN532_I2C.h>
#include <PN532.h>
#include <NfcAdapter.h>

#define TCAADDR 0x70

#define RST_PIN 2

PN532_I2C pn532_i2c(Wire);
NfcAdapter nfc = NfcAdapter(pn532_i2c);

int NB_NFC_READER = 4;

void tcaselect(uint8_t i)
{
  if (i > 7) return;
  Wire.beginTransmission(TCAADDR);
  Wire.write(1 << i);
  Wire.endTransmission();
}

void setup(void)
{
    while (!Serial);
    delay(250);

    Wire.begin();

    // Serial.begin(115200);
    Serial.begin(9600);

    //Serial.println("NDEF Reader");

    /**Initialisation des lecteurs NFC*/
    for(int i = 0 ; i < NB_NFC_READER ; i++)
    {
      //Serial.println("CONFIGURATION DU READER N° " + String(i));
      tcaselect(i);
      nfc.begin();
    }

    pinMode(RST_PIN, INPUT);
    digitalWrite(RST_PIN, HIGH);

    Serial.println("SETUP OK !");
}

void loop(void)
{
  String tag0;
  String tag1;
  String tag2;
  String tag3;

    for(int i = 0 ; i < NB_NFC_READER ; i++)
    {
      //Serial.println("FOR INDEX : " + String(i));
      tcaselect(i);
      if (nfc.tagPresent(100))
      {
          NfcTag tag = nfc.read();
          //tag.print();
          if(i == 0)
          {
            tag0 = tag.getUidString();
          }
          if(i == 1)
          {
            tag1 = tag.getUidString();
          }
          if(i == 2)
          {
            tag2 = tag.getUidString();
          }
          if(i == 3)
          {
            tag3 = tag.getUidString();
          }
          //Serial.println("LECTURE SUR LECTEUR " + tag.getUidString());
          delay(100);
      }
    }
    Serial.print("[");
    Serial.print("{\"tag0\":");Serial.print("\"");Serial.print(tag0);Serial.print("\"},");
    Serial.print("{\"tag1\":");Serial.print("\"");Serial.print(tag1);Serial.print("\"},");
    Serial.print("{\"tag2\":");Serial.print("\"");Serial.print(tag2);Serial.print("\"},");
    Serial.print("{\"tag3\":");Serial.print("\"");Serial.print(tag3);Serial.print("\"}");
    Serial.println("]");
}

Thank you for reading, I hope someone will find why the serial freeze like that.

Set debiggung to verbose in the IDE, maybe this reveals some more info. It's unlikely that the actual serial output of the atmega freezes. I guess, either the sketch hangs somewhere else or it is the software on the frontend failing


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

MAX30105 particleSensor;

#define MAX_BRIGHTNESS 255

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

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

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

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

void setup()
{

}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  }
  Serial.end();
}

void wait_for_Max30102()
{
delay(2000);
}

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

For Sensor 2:
#include <Wire.h>

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

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

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

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

int x,y,z, X;

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

uint16_t checkSum = 0;

void setup(){}

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

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

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

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

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

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

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

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

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

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

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

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

checkSum = x + y + z + X;

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

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

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

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

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

//Get pedometer.

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

      //delay(50);

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

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

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

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

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

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

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


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

My questions are:

whether this code is right, if not then point out my mistakes.
Solution of error shown in image.

please, no pictures of text .. not everyone is able to view images ... post the actual text

code is right? ... if it does what you expect, then yes .... otherwise no

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

Ok i am trying to make this code optimized.

@Nimra I think you have to find the right number of arrays being saved in memory and the right number of them saved in Flash, because you don't have that much space on the Flash left over either.

Arduino Mega has 8192 bytes of SRAM which will solve your problem.
Reduce the RAM usage (ref)

Look at this post, where I have implement the clock using a tft touch-enabled screen, with touch-enabled choice boxes for setting the time.  I used a Teensy 3.2, which handles the memory requirements nicely.  From the compile report
Compiling 'Teensy_LCDClockV4' for 'Teensy 3.2 / 3.1'
Using previously compiled file: C:\Users\Frank\AppData\Local\Temp\VMBuilds\Teensy_LCDClockV4\teensy31\Release\pch\Arduino.h.gch
Program size: 117,320 bytes (used 45% of a 262,144 byte maximum) (4.14 secs)
Minimum Memory Usage: 5936 bytes (9% of a 65536 byte maximum)

So you might have some trouble fitting it into a typical Arduino board


text:
Motor not working when using Nano 33 BLE and transistor because of low voltage
I'm a beginner using a new Arduino Nano 33 BLE to power a low voltage motor. I've tested that the motor can run using a standard 1.5V AA battery when connected directly, but I cannot get it to work when using the Nano to complete the circuit using a BC547 transistor.
I've attached a photo of my circuit that's as clear as I could get.

The 1.5V motor is attached on the orange wires, I couldn't fit it in the photo.
The code I've uploaded to the Nano is as follows:
int power = 1023;
int outPin = D10;

void setup() {

  pinMode(outPin, OUTPUT);
}

void loop() {
  digitalWrite(outPin, HIGH);
  delay(1000);
  digitalWrite(outPin, LOW);
  delay(1000);
}

When I complete the circuit with the AA battery, I can see the red LED, that's in series with the battery to the collector of the transistor, does light up but very dimly and so therefore the motor does not run either. I've also tried 2xAA and 4xAA batteries and that lights up the LED very brightly, but the motor still does not run. What could be wrong with this circuit?
Thanks!

So you have a transistor AND a LED in the circuit for the motor? The LED and the transistor will both get some of the voltage. I think the LED will dominate this. Please try without the LED

You have no series resistance for your LED.  This may not be a problem with a single AA battery, but it is a problem when you "also tried 2xAA and 4xAA".

I tried removing the LED and completing the circuit again but still no luck with a single AA.


text:
Arduino IDE not handling library code correctly?
The author of the PinChangeInt library and the EnableInterrupt library states at github:

When the PinChangeInt was in a .h and .cpp file, the Arduino IDE tried
  to compile it twice. I have a technique that you can use- #define
  LIBCALL_ENABLEINTERRUPT - that if you put it ahead of your #include in
  all files but the sketch, then you should be able to use the library
  without conflicts. If you know how to make it work in another way-
  remember, this is a library and will not compile in the same directory
  as the sketch and any other .h/.cpp/.ino files- then I'm all ears.

I came there, because both libraries failed to build with linker errors due to double definitions. So far so good. I split the PinChangeInt library in .h and .cpp myself and it compiled flawlessly. I did not try to split the other library yet because it looks like much work to me.
So now my question(s): Is GreyGnome right with his statement, that library code gets compiled twice when split in code and headers? And if so, what are the consequences? Memory waste? Runtime errors? What about the many other (working) libraries exhibiting separate code and header files?

I have no clue what he's on about. CPP files only get compiled once. Otherwise the whole Arduino system would fail miserably since most other libraries are split into CPP/H.

My guess is that he didn't split the files properly and ended up with duplicate references.

Ahem, so if I have some time again, I'll try to split this library too.

As I mentioned in your somewhat related thread the IDE does things in a reasonably understandable way:  Classes and objects: how many and which file types I actually need to use them?.

@NickGammon: I read that already. But how does this help me with that library? Do I have other means than rewriting it?

I just took a look at the library. He puts function definitions in the .h file. That will only work if it is included once in your project. All the definitions (the actual functions, not the prototypes) need to be moved into a .cpp file. Ditto for variables. It's not that much work to split it into two files.

I'm just hesitating to do it, cause I have to redo it each time when I want to incorporate an official update of this library. I tend to wait until the author is done with fixing all bugs and extenisons.

Header files are parsed by the preprocessor and the compiler wherever they are included.
There's nothing weird about that.
One can avoid multiple inclusions by using header guards.
That's pretty standard too.
I have not looked at the library, but, for example,  a typical error is to not declare variables as extern in the header and instead leave the real declaration in the header, which will lead to multiple instances, possibly clashing at link time.
Variables that are part of the library API should be declared as extern in the header and the real declaration should be done only in the .C/.CPP file.
Interrupts are an even more special case: the AVR gcc relies on very specific names to identify interrupt handlers and each of them can be present at most once.
So there are even more chances for having linker problems, if not declared correctly.

The problem is, that both libraries lack .c/.cpp files entirely. Hence the real declaration is in the header and it is not possiple to declare it extern. The compiler takes the header guards correctly. But the linker throws the double declaration errors afterwards.

Indeed, what should be done is to split the library into .h and .cpp, so that it can work in a sane way.
FWIW, though, using PCINT is trivial, if done without the library, assuming that you only care about one specific platform (say ATMega328p). The library bends backwards several times to cope with the different layout of AVR ports across various ATMega chips. But if all you care about is one chip, you can write much simpler code.

On my Interrupts I show how you can use pin-change interrupts in about 4 lines of code. My personal view is that if you are targeting a particular processor it is easier to just write those four lines. By the looks of it you have already spent a number of days to "save the effort" of writing those few lines. The problem is, that both libraries lack .c/.cpp files entirely. - so? Split the file into two files. ... it is not possiple to declare it extern - anything is possible.

To be fair, the library does more than what is accomplished by those 4 lines. Replicating the same functionality would take a similar amount of code. But it could be done without abusing the header.

To elaborate on your comment ~
An easy way to prevent multiple definitions from re-inclusion of the same header file is to ensure it's only defining things once.
e.g. my_header.h
#ifndef __MY_HEADER_H__
#define __MY_HEADER_H__

// some header code.

#endif //#ifndef __MY_HEADER_H__

When the header is first compiled, the definition of __MY_HEADER_H__ gets created by the compiler due to the 2nd line of the file.  On subsequent compiles, which are caused by including the same header in more files, the 1st line '#ifndef' conditional skips everything down to the '#endif'.
When you write (or split) C / C++ code, it's common to wrap the class and function definitions (which go in the .h header file) in these compilation control blocks, and then the .c/.cpp file only gets the function bodies.
e.g.: my_rgb.h ~
#ifndef __MY_RGB_H__
#define __MY_RGB_H__

#include <stdint.h>

uint32_t packRGB(uint8_t r, uint8_t g, uint8_t b);

class RGB
{
public:
    RGB(uint8_t r, uint8_t g, uint8_t b);

    void toGreyscale();

private:
    uint8_t red;
    uint8_t green;
    uint8_t blue;
};

#endif //#ifndef __MY_RGB_H__

and my_rgb.cpp
#include "my_rgb.h"

// Note: this would typically be a member function
// but is separate to show a standalone function definition.
uint32_t packRGB(uint8_t r, uint8_t g, uint8_t b)
{
    uint32_t packed;

    packed = (r << 24) | (r << 16) | b;

    return packed;
}

RGB:RGB(uint8_t r, uint8_t g, uint8_t b)
{
    red = r;
    green = g;
    blue = b;
}

void RGB::toGreyscale()
{
    uint8_t grey = 0.2126 * (float)r + 0.7152 * (float)g + 0.0722 * (float)b;
    r = g = b = grey;
}

Including the header file multiple times will give "redefinition" errors at compile time.  Including the same function multiple times will give double definitions at link time.
If you stick to this method of laying out .h and .c/.cpp files you will never have a problem with multiple definitions on your own files.  (Unless you re-define a library function by accident, etc.)
Of course it's ok (and quite common) to define short little functions in the header/.h file too. (The compiler typically generates these as inline code though.)  I'm not trying to explain the complete workings of headers & .C files, just presenting you a method which will always prevent multiple definition problems.

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


text:
Arduino Uno + NodeMCU serial to MQTT
I made a pool monitor with ORP + pH + temp sensor. I had everything working (apart from ORP sensor causing interference with pH sensor, but that is a different topic...) for the past couple days in a temporary enclosure. Today I moved the device into a new enclosure. After rewiring it stopped sending out the probe data via MQTT and I'm struggling figuring out why..
If I open the serial monitor for the NodeMCU I can see the data from the Arduino coming through -
{"ph":"11.44","orp":"-23411","temp":"-196.60"}
...

So, it would appear the serial link is working since I'm getting the data. When listening on my MQTT topic, I get a "hello world", so my MQTT and wifi connections appear to be okay. If I type something in the serial console, it DOES get picked up by the MQTT topic. It seems like there is something wrong with the loop sending out the data, but this is the same loop I had and same loop as other sketches? I've even tried a different sketch on the NodeMCU with no luck. I'm really having trouble understanding what went wrong here. Is there something incredibly obvious that I am just spacing out on here?
Arduino Host w/ probes
int id=99;
#include <SoftwareSerial.h>
#include "orp_grav.h"
#include <OneWire.h>
#include <DallasTemperature.h>

//ph configs
#define SensorPin 0            //pH meter Analog output to Arduino Analog Input 0
#define Offset -2.0            //deviation compensate
unsigned long int avgValue;     //Store the average value of the sensor feedback

//orp configs
Gravity_ORP ORP = Gravity_ORP(A1);
unsigned long int ORPavgValue;     //Store the average value of the sensor feedback

//TEMP CONFIGS, using 2.2k pull-up resistor
#define ONE_WIRE_BUS 5 // Data wire is plugged into digital pin 5 on the Arduino
OneWire oneWire(ONE_WIRE_BUS); // Setup a oneWire instance to communicate with any OneWire device
DallasTemperature sensors(&oneWire); // Pass oneWire reference to DallasTemperature library

//NodeMCU serial comm
SoftwareSerial sw(2, 3); // RX, TX

void setup() {
 Serial.begin(9600);
 Serial.println("Interfacfing arduino with nodemcu");
 sw.begin(9600);
 if(ORP.begin()){
    Serial.println("Loaded EEPROM");
  }
 sensors.begin();
}

void loop() {
  /////////////  PH LOOP /////////////
  int buf[10];                //buffer for read analog
  for(int i=0;i<10;i++)       //Get 10 sample value from the sensor for smooth the value
  {
    buf[i]=1024-analogRead(SensorPin);
    delay(10);
  }

  for(int i=0;i<9;i++)        //sort the analog from small to large
  {
    for(int j=i+1;j<10;j++)
    {
      if(buf[i]>buf[j])
      {
        int temp=buf[i];
        buf[i]=buf[j];
        buf[j]=temp;
      }
    }
  }
  avgValue=0;
  for(int i=2;i<8;i++)                      //take the average value of 6 center sample
    avgValue+=buf[i];

  float phValue=(float)avgValue*5.0/1024/6; //convert the analog into millivolt
  phValue=3.5*phValue+Offset;                      //convert the millivolt into pH value
////////////////////////////////////////////

  /////////// ORP LOOP ///////////
  int orpValue;
  int orp_buf[10];                //orp_buffer for read analog

  for(int i=0;i<10;i++)       //Get 10 sample value from the sensor for smooth the value
  {
    orp_buf[i]=(int)ORP.read_orp();
    delay(10);
  }

  for(int i=0;i<9;i++)        //sort the analog from small to large
  {
    for(int j=i+1;j<10;j++)
    {
      if(orp_buf[i]>orp_buf[j])
      {
        int temp=orp_buf[i];
        orp_buf[i]=orp_buf[j];
        orp_buf[j]=temp;
      }
    }
  }
  ORPavgValue=0;
  for(int i=2;i<8;i++)                      //take the average value of 6 center sample
    ORPavgValue+=orp_buf[i];
  orpValue = ORPavgValue/6;
 //////////////////////

 ///////////TEMP///////////
 sensors.requestTemperatures();
 float tempValue = (sensors.getTempCByIndex(0) * 9.0) / 5.0 + 32.0;
 //////////////////////

 //Console debug
 Serial.print(phValue);//offset
 Serial.print("\t");//
 Serial.print((orpValue));
 Serial.print("\t");//
 Serial.println((tempValue));

 sw.print("{");
 //
 sw.print("\"ph\":\"");
 sw.print(phValue);//offset
 sw.print("\",");

 sw.print("\"orp\":\"");
 sw.print(orpValue);//offset
 sw.print("\",");

 sw.print("\"temp\":\"");
 sw.print(tempValue);//offset
 //
 sw.print("\"}");
 delay(5000);
}

NodeMCU MQTT code
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.
const char* ssid = "SSID";
const char* password = "Password";
const char* mqtt_server = "192.168.1.208";
#define mqtt_port 1883
#define MQTT_USER "user"
#define MQTT_PASSWORD "password"
#define MQTT_SERIAL_PUBLISH_CH "hass/sensor/pool"

WiFiClient wifiClient;

PubSubClient client(wifiClient);

void setup_wifi() {
    delay(10);
    // We start by connecting to a WiFi network
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    randomSeed(micros());
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    client.publish("outTopic", "hello world");
    // Create a random client ID
    String clientId = "NodeMCUClient-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str(),MQTT_USER,MQTT_PASSWORD)) {
      Serial.println("connected");
      //Once connected, publish an announcement...
      client.publish("hass/sensor/pool", "hello world");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
void setup() {
  Serial.begin(9600);
  Serial.setTimeout(500);// Set time out for
  setup_wifi();
  client.setServer(mqtt_server, mqtt_port);
  reconnect();
}

void publishSerialData(char *serialData){
  if (!client.connected()) {
    reconnect();
  }
  client.publish(MQTT_SERIAL_PUBLISH_CH, serialData);
}
void loop() {
   client.loop();
   if (Serial.available() > 0) {
     char bfr[101];
     memset(bfr,0, 101);
     Serial.readBytesUntil( '\n',bfr,100);
     publishSerialData(bfr);
   }
 }


text:
Is Arduino Mega Hackable Over The Air
After reviewing similar topics I've decided to ask this question below in the Security Stackexchange forum about 11 days ago.
https://security.stackexchange.com/questions/235423/is-arduino-mega-hackable-over-the-air
No one gave an answer yet, perhaps I was wrong about the medium that's why I am also posting the question here.
I am collecting data (by reading input registers) from a machine by RS-485 protocol and Arduino Mega 2560 hardware.
I am also sending this data from Arduino Mega to a NodeMCU which is connected to the internet over WiFi.
I made 100% sure that no physical interference can be performed on the hardware I setup.
But since this machine, I collect data from is controllable (by writing holding registers) over RS-485 (I've tested it) I have to make sure that Arduino's software cannot be changed/re-programmed/flashed over the air by someone.
There is no other device than NodeMCU which is open to the Internet and can be the source of vulnerability. And the only physical connections between Arduino & NodeMCU ar TX3+RX3 pins and power+ground pins.
I do not really care if the data or WiFi password or cloud server credentials are stolen. The only thing I care about is that Arduino is not flashed over the air which can ultimately damage the machine I am taking data from. Do you think this setup is safe regarding the information I present to you?

I suggest you consult the ATmega datasheet. There you will find that the chip can only be flashed from within the boot loader region. This gives no 100% guarantee. But further down the datasheet you will find several fuses that you can evaluate. Some of them disable the boot loader. So unless your code addresses the boot loader region, you should be safe then. Also there is no way to inject code like in PC because of the Harvard Architecture.

the bootloader doens't listen on RX/TX3.
to start the bootloader reset is required
to communicate with the bootloader a serial programmer must have STK500 protocol or a telnet bridge for avrdude, which your NodeMCU sketch doesn't have

If your NodeMCU sketch has OTA, then the sketch could be updated to an avrdude telnet bridge. then reset would be needed to activate the bootloader. If your NodeMCU doesn't have a wire to Mega reset pin or you don't have a command in your Mega sketch to activate the reset, some serial overload of your Mega sketch could be a way.
But all this doesn't have an effect because the bootloader only listens at RX0