text:
I am trying to read input from 5th PIN of PORT B?
In a nutshell i want to read a PORTB 5th pin without using digitalRead API ( i am trying to learn baremetal using arduino-uno-r3)
Just to Learn How internal register works i did not used digitalRead API, instead i have used DDRB register to set the 5 bit of DDRB as Low indicating PORTB 5th pin is in input mode then i am using an if statment to check if 5th bit of PINB is high or low my expection was that when i connect arduino pin 13 to 5v  if statment will become TRUE.
void setup() {
  // put your setup code here, to run once:
  DDRB = DDRB & ~(1<<5);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(PINB & (1<<5)){
     Serial.println("Got data");
    }
}

When i executed above code i am constantly getting if as TRUE

Do you use an external pullup or pulldown resistor?

your code is operating on the 6th bit ... bits are numbered 0 to 7, so 5th bit is bit 4

I have not used any pull up resistor and i am sure PINB 5th bit is 13 pin of aurdino

No, digital 13 is PB5, i.e. the 6th bit. The 1st bit is PB0, the 2nd bit is PB1, etc.

If nothing is connected to the pin then it can read either high or low.  Google “floating pin”.  If you’re expecting it to read low when not connected to anything then you’re thinking wrong.

@EdgarBonet so what should i change in code

@Delta_G then what is the point of low and high if pin is always (floating ) high

http://www.electronoobs.com/images/Arduino/tut_31/arduino_uno_scheamtic.png PB5 IS 13TH PIN ON ARDUINO i think i am correct

It's not 13th pin, it's pin “digital 13”. Not the same.

The point is that if the pin is tied to a voltage it will read that voltage.  If it is unconnected then what voltage is on the pin?  If you answer zero then you need to go and study basic electronics some more.  A pin should read LOW when it is connected to ground and HIGH when connected to 5V.  If it is unconnected then you don't know what the voltage level at the pin is.  It can pick up any stray noise and read anything.

The point is, "Don't try to read a pin that isn't connected to anything."

There seem to be several, separate issues in your question.
One is a simple matter of language. In English, “1st” is an abbreviation
for “first”, which is an ordinal adjective applied to an item in a list
meaning that there is no other item before it in that list. In the same
vein, “5th” means “fifth”, which applies to the item that has exactly
four items before it. For instance, the list of pins of port B is {PB0,
PB1, PB2, PB3, PB4, PB5}. PB0 is the first in the list, and PB4 is the
fifth. The fact the first item bears the number 0 makes this confusing.
Thus, I recommend avoiding ordinal adjectives altogether and instead
calling the pins by their names, like “digital 13” (Arduino naming) or
“PB5” (AVR naming).
The second issue, and probably your main concern, is about the floating
input pin. You cannot expect a reliable reading from a floating input. I
will not try to explain why, as the issue has been discussed ad nauseam
here and elsewhere. Just do a Web search. The simplest solution is to
use the built-in pull-up resistor and externally connect a push button
between the pin and ground. You will read LOW whenever the button is
pressed:
void setup() {
    pinMode(13, INPUT_PULLUP);
    Serial.begin(9600);
}

void loop() {
    if (digitalRead(13) == HIGH)
        Serial.println("HIGH");
    else
        Serial.println("LOW");
}

The last point is about going bare metal and learning how to use the I/O
registers directly. A small warning first: you have to keep in mind that
this is board-specific. You tagged your question with both “arduino-uno”
and “arduino-mega”, but these boards have different pin mappings
(digital 13 is PB7 on the Mega). The general way of using the DDRx,
PORTx and PINx registers is the same across all AVR chips, but is not
portable to Arduinos based on a different architecture.
So let's assume this is intended to work only on an Uno, Nano, or
other board based on an ATmega328P.
Judging from the example code you show, you seem to
already understand pretty well how these registers work. There is no
problem in your code, beside the fact that it requires an external
pull-up. If you want to enable the internal pull-up, you have to set the
appropriate bit in PORTB. This can seem confusing, as the same register
is used for pull-up control (when the pin is in input mode) and for
output control (when the pin is an output). Essentially, each GPIO pin
has four distinct electrical states which are controlled by to I/O bits:
│ DDRxn │ PORTxn │ state        │
├───────┼────────┼──────────────┤
│   0   │    0   │ INPUT        │
│   0   │    1   │ INPUT_PULLUP │
│   1   │    0   │ OUTPUT LOW   │
│   1   │    1   │ OUTPUT HIGH  │
└───────┴────────┴──────────────┘

The example program above can be translated to low-level AVR style as
follows:
void setup() {
    DDRB &= ~_BV(PB5);  // input mode
    PORTB |= _BV(PB5);  // enable pullup
    Serial.begin(9600);
}

void loop() {
    if (PINB & _BV(PB5))
        Serial.println("HIGH");
    else
        Serial.println("LOW");
}

Nicely put @edgar.  I might add a comment (as the OP did say he/she wanted to do bare metal programming) that different Arduinos board can contain different processors.  And  what works here in this answer is for a specific processor.  And that other processors can and most often work very differently.

@st2000: Good point. Edited the answer.


text:
Bluetooth: sync time from an NTP server via Internet connection shared with Android phone
I saw that it is possible to sync time from an NTP server over WiFi. I have the HC-06 Bluetooth module and an Android phone that can share its Internet connection with Arduino via Bluetooth. Would it be possible to sync time/date using this infrastructure? And if yes - how (which libraries, etc..)? Has anybody done it already and there is a tutorial on that?

you can;t use Bluetooth tethering with HC-06

No, not really. It is possible, but not easily like you want it to be. The HC-06 is a Bluetooth-Serial bridge. In the Bluetooth protocol there are many types of interfaces, that a client device might expose to the master. A Bluetooth mouse exposes a HID interface, a headset exposes a corresponding audio interface and the HC-06 exposes a pure Serial interface. Thus the HC-06 does not support what ever interface is used for tethering.
Ways, that may make it possible:

Change the firmware of the HC-06 for exposing the correct interface and interact with it. For this you need to know how to reprogram the HC-06 and how exactly bluetooth works. I guess this is over your current level.
Write an app for your Andriod smartphone, which plays the Serial-Internet bridge on the phone. The app would translate between Serial and Internet, involving your own protocol on the Serial interface. Easiest, when you just make a specialized app for syncing time, so that it does not have to do any other communication.

And at that point it is just too much work to go either way. It is unlikely, that you find libraries or any code for this, since it just doesn't make much sense. Instead you could move from an Arduino to an ESP, which can directly connect to the WiFi network in question and thus get directly the time from the internet, without tethering. That is way easier and you can use the many libraries, that already exist for that problem.

I try not to expose WiFi link on my phone (in order to save battery), so I would prefer Bluetooth. Is the above mentioned tethering possible on Nano 33 BLE? And if yes - how will look the code?

@user1876484, BLE doesn't support tethering. Tethering is a function of classic Bluetooth. and Nano 33 BLE supports only BLE

source: Stack Exchange

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

sort: votes


text:
Arduino serial coming up with weird characters
I am trying to create a basic snake game using the arduino UNO along with the MAX72XX module, the LCD module and the analog joystick module. I am wanting to program my program using object orientated programming. I have no experience with C++ so I am struggling quite a bit to understand why the serial comes up with unusual characters whenever I am trying to print off variable values. The serial is able to print text, but whenever I try to print variable values the unusual characters come up. I had tried changing the baud to a higher one and that makes no difference. The two variables that I am trying to print off both have an integer data type. I have tried using Serial.write, Serial.print and Serial.println, none of these seem to work. Here is the code if it helps solve the problem:
#include "LedControl.h"
#include <LiquidCrystal.h>
LedControl lc=LedControl(12,10,11,1);
LiquidCrystal lcd(8, 13, 3, 5, 6, 7);

class Snake_body
{

  public:

    int following_direction;
    int x;
    int y;
    int previous_x;
    int previous_y;
    bool enabled;
    Snake_body()
    {
      this->enabled = false;
    }

    void configure(int x_value, int y_value)
    {
      this->enabled = true;
      this->following_direction = 1;
      this->x = x_value;
      this->y = y_value;
      this->previous_y = y_value;
      this->previous_x = x_value;
    }

};

class Power_up
{
  private:

  public:
    virtual void init()
    {
      this->x = 0;
      this->y = 0;
    }

    int x;
    int y;
};

Snake_body *snake[64];//this is the snake array that contains the snake objects

int snakes_length;

Power_up *power_up;//define the power up object

int score;

void setup() {

  Serial.begin(9600);

  lcd.begin(16, 2);

  snakes_length = 1;

  for(int z = 1; z < 64; z++)
  {
    snake[z] = new Snake_body();//create 63 un-enabled snake objects
  }

  snake[0] = new Snake_body();//the 1st snake object is defined
  snake[0]->configure(0,0);//here it is initialised
  power_up = new Power_up();//create the power_up object

  lc.shutdown(0,false);
  lc.setIntensity(0,8);
  lc.clearDisplay(0);
  lcd.setCursor(0, 0);
  score = 0;
  lcd.print("score: ");
  lcd.setCursor(6, 0);
  lcd.print(score);
  pinMode(2, INPUT);
  digitalWrite(2, HIGH);

  power_up->x = random(0, 8);
  power_up->y = random(0, 8);
}

int snake_direction;

void loop()
{
  int x_axis = analogRead(A0);
  int y_axis = analogRead(A1);
  int switcher = digitalRead(2);

   if(x_axis <= 400) //&& x < 7)//each of the if statements are for the direction of the snake head (snake[0])
   {
     snake[0]->following_direction = 0;
     //x += 1;
     //Serial->println("right");
   }

   else if(x_axis >= 600) //&& x > 0)
   {
     snake[0]->following_direction = 1;
     //x -= 1;
     //Serial->println("left");
   }

   else if(y_axis <= 400) //&& y > 0)
   {
     snake[0]->following_direction = 2;
     //y -= 1;
     //Serial->println("up");
   }

   else if(y_axis >= 600) //&& y < 7)
   {
     snake[0]->following_direction = 3;
     //y += 1;
     //Serial->println("down");
   }

  if(snake[0]->following_direction == 0 && snake[0]->x < 7)//used for snake movement
  {
    snake[0]->previous_x = snake[0]->x;
    snake[0]->x += 1;
  }

  else if(snake[0]->following_direction == 1 && snake[0]->x > 0)//used for snake movement
  {
    snake[0]->previous_x = snake[0]->x;
    snake[0]->x -= 1;
  }

  else if(snake[0]->following_direction == 2 && snake[0]->y > 0)//used for snake movement
  {
    snake[0]->previous_y = snake[0]->y;
    snake[0]->y -= 1;
  }

  else if(snake[0]->following_direction == 3 && snake[0]->y < 7)//used for snake movement
  {
    snake[0]->previous_y = snake[0]->y;
    snake[0]->y += 1;
  }

  if(snake[0]->x == power_up->x && snake[0]->y == power_up->y)//used for collision with power up
  {
    score += 1;
    lcd.setCursor(6,0);
    lcd.print(score);

    power_up->x = random(0, 8);
    power_up->y = random(0, 8);

    for(int j = 0; j < 64; j++)
    {
      if(snake[j]->enabled == false)//enables the next un-enabled snake object in the array
      {
         //Serial.println(true);
         Snake_body *snake[j];

         //next_snake_body = new Snake_body();
         //Snake_body next_snake_body;
         snake[j] = new Snake_body();
         snake[j]->configure(snake[j-1]->previous_x, snake[j-1]->previous_y);
         //Serial.print("x: " + snake[j-1]->previous_x);
         //Serial.print("y: " + snake[j-1]->previous_y);
         snake[j]->following_direction = NULL;
         break;
      }
    }
  }

  for(int i = 1; i < 64; i++)
  {
    if(snake[i]->enabled == true)//updates each snake object in the array
    {

      snake[i]->x = snake[i-1]->previous_x;
      snake[i]->y = snake[i-1]->previous_y;
    }
  }

  lc.setLed(0,power_up->x,power_up->y,true);//draws the power up
  for(int w = 0; w < 64; w++)
  {
    if(snake[w]->enabled == true)//draws each snake object that is enabled
    {
      Serial.print("x: " + snake[w]->x);
      Serial.print("y: " + snake[w]->y);
      lc.setLed(0,snake[w]->x,snake[w]->y,true);
    }
  }

  /*Serial->print("x: ");
  Serial->print(snake->x);
  Serial->println();

  Serial->print("y: ");
  Serial->print(snake->y);
  Serial->println();*/

  delay(100);

  lc.clearDisplay(0);
}

the weird characters that show up are characters like this:

with the follow picture y is just simply text to show which axis it is, the weird characters are the integer y axis value of the snake object that is being looked at.

Make a copy of your sketch and cut out everything but printing one text message and one variable value. Do you still have a problem? Add back a little bit at a time until the problem reappears. What you just added back is the cause.

everything can be important information when debugging code, including the weird characters ... please add the weird character printout to your post

There are some weird statements in the code, like the line Snake_body *snake[j];.. this does nothing and looks like a variable declaration, I'd remove that. Also in the beginning you snake[z] = new Snake_body(); but don't initialize the values (like y, x)  in them via a constructor or initialize() function -- those will be random then and possibly garbage. You calso call Serial->print(snake->x); but snake is an 64-element array of Snake pointers, so that won't work. You need an index here.

Oh, and you also have a memory leak when you snake[j] = new Snake_body();. There already is a Snake_body element in there and you've overwritten the pointer to it with a newly allocated object without delete-ing the previous on -- reevaluate whether you really need to allocate a new object here of want to modify the existing one. If the latter, cleanup the memory.

You are using quite a bit of dynamic memory allocation. Note that this is a bad idea on an Arduino in 99% of cases. You can easily fill up all RAM without knowing beforehand and even when you correctly delete objects, that aren't needed anymore, you are getting your heap fragmented

@MaximilianGerhardt Serial->print(snake->x); was something I comment out and don't need anymore in my code. I forgot to take it out. Additionally, each object that I have created is needed because these are the body parts of the snake. Also, I am not very experienced with C++, so it took along time to get this code to where it is now.

@chrisl All the snake objects are needed, each time a new one is defined this is another part of the snake

Sure every part is needed, but you're initially filling all 64 elements of the array with new Snake_body objects and then overwrite the pointer to that object with snake[j] = new Snake_body(); i.e. another Snake_body object, that's a memory leak (https://www.geeksforgeeks.org/memory-leak-in-c-and-how-to-avoid-it/). You should be able to do this with all static allocation and no new / dynamic memory, just a static array of 64 Snake_body objects.

@MaximilianGerhardt Ok, I now see where you are going with this. What the for loop in setup does is that it just puts a Snake_body object in each space in the array and then, once the power up is touched the for loop will go through the snake array until an object which has not been enabled is found and then that object will then be configured and initialised.

@MaximilianGerhardt look at the code (I have commented what each part of the code does)

@jsotola the characters always change each time but I have posted an example above in the question of what similar characters come up.

@MaximilianGerhardt the problem is that I needed to do this because I needed something comparable so that I could find an empty space in the array. Do you know how I could possibly find an empty space in the array without having to have a RAM memory leak

If you want to mark an empty space, why not make this a member in your field element structure? Then you can have an always-there 64 field array with just different attributes in them. Maybe it's better to think of the play field as generic tiles which have attributes like whether a snake part is on them or a powerup, and then save extra info like the head and teal of the snake to move it / expand it.

@MaximilianGerhardt I am not 100% clear of what you said.

@MaximilianGerhardt Would it potentially work if each object at the beginning is null except snake[0]. Then to find an empty object you would go through the array until you find an element in the array with a NULL value then this element with a null value becomes an object. Could that potentially work

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


text:
Calculating Amp/Hrs of a solar panel
I am interested in calculating the amp/hour output of a solar panel using an Arduino. I am confident I can get the voltage (with a voltage divider) & the amperage (with an ACS712). My question is about the math of calculating Amp*hour.
Here is my plan:

My plan is to pull the voltage and amperage every second.
I would then add this amp*second value to a variable. I would also increment another variable for each second.
I would then be able to get an average or total of Ampseconds from these 2 variables. I could also divide the ampsecond by 3600 if I wanted Amp*Hour.

Is it too much a stretch to poll the amperage every second and call it amp/second? How can I make this more accurate?

and why do you measure the voltage?

Just one minor comment: It's Amp hours (Ah) and Amp seconds, not Amp/Hours. Otherwise your method for calculation seems correct. I would not  expect very accurate results though. You could use the voltage in the same way to calculate Watt Hours.

I was in the process of editing your answer, then decided against it. I'll just say it here instead: there's no such thing as amp/hour as a useful measurement. What you mean is amps*hours, or Ah (https://en.wikipedia.org/wiki/Ampere_hour). Also, change the word "pull" to poll. Those are two completely different English words, and what you mean is poll, or "ask repeatedly", not "pull", or "exert a force towards something", or "draw or haul towards you".

@Juraj I mentioned I have the voltage if by chance it was needed.

How to make your own coulomb counter (Amp*hours [Ahr] meter, or Watts*hours [Whr] energy meter) with an Arduino
Quick summary:
Jump straight down to the "Full coulomb counter example in code" section if you just want the final answer.
Details
There are a lot of misunderstandings here, but here is the gist of it.
What you want to do is a perfect application of an Arduino. No need to buy a coulomb counter, instead, you should make one with your Arduino.

I would then add this amp/second value to a variable.

First correction, it's an amp*second, NOT an amp/second. You are multiplying amps by the number of seconds that current value existed.
amp*seconds / 3600 = amp*hours. Read about that here: https://en.wikipedia.org/wiki/Ampere_hour. Multiply that by the voltage over that same time period and you've got amps*hours*volts = (amps*volts)*hours = Watts*hours = units of energy! Remember, your house electricity it purchased in units of kilowatt hours, which is kilowatts*hours, or kWhr. And in engineering units a joule is  the standard unit of energy, and it is simply Watts*seconds. So, you can convert kWhr to joules like this, where units are in square brackets [].
Joules = kWhr * 1000 [Whr/kWhr] * 3600 [sec/hr] = [Watts*sec] = [Joules]

So, 1 kWhr x 1000 x 3600 = 3600000 Joules = 3600kJ

I would also increment another variable for each second.

That doesn't make any sense. Don't do that. You've already captured the seconds by adding your new bit of amps*seconds to your old sum of it.
DO account for voltage too! What you're really after is energy, which can be expressed in units of joules or kWhr, as already described above.

Is it too much a stretch to poll the amperage every second and call it amp*second?

(my corrections in bold)
No, absolutely not! That's exactly what an amp*second is! It's the current, amps, times the number of seconds that current existed. That's a coulomb counter!
A. Making the coulomb counter as good as possible

How can I make this more accurate?

This is the part where the engineer and programmer (you) determines the quality of the result.

Don't assume 1 second elapsed because you told it to. Measure it for each and every measurement!
The smaller the time interval, the more accurate, since it allows you to capture the small current fluctuations, so use a smaller time slice than 1 second. I'd start with 10ms.
Measure voltage AND current AND actual time elapsed on this loop as close to the same time as possible.
Do NOT use blocking techniques, such as delay() or delayMicroseconds().
What you're doing when you're multiplying a new amp reading x seconds, and adding it to the previous sum is called numerical integration. You're simply numerically integrating, or summing, the area under the Amp (y-axis)-time (x-axis) curve, or, if you're doing what I'm saying to do intead: the Watt (y-axis)-time (x-axis) curve, where the area under the curve is the total energy collected. Don't do rectangular integration, do trapezoidal integration following the trapezoidal rule! It's more accurate!
Calibrate your clock! An Arduino's clock can be off by a couple percent. Figure out how much it's off by comparing its clock output over, say, 10 minutes, and comparing it to a better clock source, say...an internet time server displaying the atomic clock in Colorado or wherever it is. Then, multiply each measurement by a scaling factor to fix it!
On the same lines as above, ideally you'd also compensate in real-time for temperature, as the clock frequency drifts with temperature.
Calibrate the voltage measurement.
Calibrate the current measurement.

B. Extra: when is trapezoidal integration most beneficial?
You might call the following list my "5 hypotheses about the benefits of trapezoidal integration".
The merits of trapezoidal integration can be argued, and it's probably not as important as I originally made it sound, but it is super easy to implement, so why not!? Also, it is most important when:

The time sampling rate is super low.
The rate of change of readings (ie: their derivative, or slope) is super high.
The readings consistently have a rising slope (rectangular integration _under_estimates the area in this case) OR a consistently falling slope (rectangular integration _over_estimates in this case).
When you care about real-time readings in this instant, not just overall trends or averages. This is because trapezoidal integration instantly removes overestimation and underestimation error which can accumulate over short periods but then "de-accumulates", or is negated, over long periods, when the opposite slope occurs in the data.
[This may apply only when there is jitter in the sample rate--see @Edgar Bonet's comment here] When the readings consistently rise at a different rate than they fall, as this results in asymmetric accumulation of error. This means that the rectangular integration error accumulated by the values rising distance delta_y will NOT be fully negated by error in the opposite direction when the values fall distance delta_y. Therefore, even over long periods, rather than seeing the error negated, it will accumulate more and more over time. [Note: I'd need to analytically/numerically play with this hypothesis for a while to prove it conclusively to myself, but I'm pretty sure it is correct].

Full coulomb counter example in code:
This code is now in my eRCaGuy_hello_world repo here: coulomb_counter_with_cooperative_multitasking_macro.ino.
Here's a full coulomb counter example in code. You just need to implement a few functions to read samples and do calibrations is all.
I'm borrowing the timestamp-based cooperative multitasking part of this code from my answer about cooperative multitasking here, so go check it out for more information on that.
As written, this code compiles, but I haven't wired anything up or tested it. Here's the compilation output:

Sketch uses 3750 bytes (12%) of program storage space. Maximum is 30720 bytes.
Global variables use 262 bytes (12%) of dynamic memory, leaving 1786 bytes for local variables. Maximum is 2048 bytes.

coulomb_counter_with_cooperative_multitasking_macro.ino:
Jump to the bottom for the setup() and loop() functions. They are both really short.
/// Coulomb counter example
/// By Gabriel Staples
/// See: https://arduino.stackexchange.com/questions/75932/calculating-amp-hrs-of-a-solar-panel/75937#75937

/// @brief      A function-like macro to get a certain set of events to run at a desired, fixed
///             interval period or frequency.
/// @details    This is a timestamp-based time polling technique frequently used in bare-metal
///             programming as a basic means of achieving cooperative multi-tasking. Note
///             that getting the timing details right is difficult, hence one reason this macro
///             is so useful. The other reason is that this maro significantly reduces the number of
///             lines of code you need to write to introduce a new timestamp-based cooperative
///             task. The technique used herein achieves a perfect desired period (or freq)
///             on average, as it centers the jitter inherent in any polling technique around
///             the desired time delta set-point, rather than always lagging as many other
///             approaches do.
///
///             USAGE EX:
///             ```
///             // Create a task timer to run at 500 Hz (every 2000 us, or 2 ms; 1/0.002 sec = 500 Hz)
///             const uint32_t PERIOD_US = 2000; // 2000 us pd --> 500 Hz freq
///             bool time_to_run;
///             uint32_t actual_period_us;
///             CREATE_TASK_TIMER(PERIOD_US, time_to_run, actual_period_us);
///             if (time_to_run)
///             {
///                 run_task_2();
///
///                 // OR, if `run_task_2()` needs the actual period that just occurred, for
///                 // whatever reason, you may pass it in to your `run_task_2()` function:
///                 run_task_2(actual_period_us);
///
///                 // OR, just do all your code right here instead of in `run_task_2()`
///             }
///             ```
///
///             Source: Gabriel Staples
///             https://stackoverflow.com/questions/50028821/best-way-to-read-from-a-sensors-that-doesnt-have-interrupt-pin-and-require-some/50032992#50032992
/// @param[in]  period_desired_us  (uint32_t) The desired delta time period, in microseconds;
///                             note: pd = 1/freq; the type must be `uint32_t`.
/// @param[out] time_to_run     (bool) A `bool` whose scope will enter *into* the brace-based scope block
///                             below; used as an *output* flag to the caller: this variable will
///                             be set to true if it is time to run your code, according to the
///                             timestamps, and will be set to false otherwise.
/// @param[out] actual_period_us  (uint32_t) The actual period, in us, since the last time it was
///                             time to run--ie: since the last time `time_to_run` was set to true.
/// @return     NA--this is not a true function
#define CREATE_TASK_TIMER(period_desired_us, time_to_run, actual_period_us)                                            \
{ /* Use scoping braces to allow multiple calls of this macro all in one outer scope while */                          \
  /* allowing each variable created below to be treated as unique to its own scope */                                  \
    time_to_run = false;                                                                                \
                                                                                \
    /* set the desired run pd / freq */                                                                                \
    const uint32_t PERIOD_DESIRED_US = period_desired_us;                                                              \
    static uint32_t t_start_us = micros();                                                                             \
    uint32_t t_now_us = micros();                                                                                \
    uint32_t period_us = t_now_us - t_start_us;                                                                        \
    actual_period_us = period_us;                                                                                \
                                                                                \
    /* See if it's time to run this Task */                                                                            \
    if (period_us >= PERIOD_DESIRED_US)                                                                                \
    {                                                                                \
        /* 1. Add PERIOD_DESIRED_US to t_start_us rather than setting t_start_us to t_now_us (which many */            \
        /* people do) in order to ***avoid introducing artificial jitter into the timing!*** */                        \
        t_start_us += PERIOD_DESIRED_US;                                                                               \
        /* 2. Handle edge case where it's already time to run again because just completing one of the main */         \
        /* "scheduler" loops in the main() function takes longer than PERIOD_DESIRED_US; in other words, here */       \
        /* we are seeing that t_start_us is lagging too far behind (more than one PERIOD_DESIRED_US time width */      \
        /* from t_now_us), so we are "fast-forwarding" t_start_us up to the point where it is exactly */               \
        /* 1 PERIOD_DESIRED_US time width back now, thereby causing this task to instantly run again the */            \
        /* next time it is called (trying as hard as we can to run at the specified frequency) while */                \
        /* at the same time protecting t_start_us from lagging farther and farther behind, as that would */            \
        /* eventually cause buggy and incorrect behavior when the (unsigned) timestamps start to roll over */          \
        /* back to zero. */                                                                                \
        period_us = t_now_us - t_start_us; /* calculate new time delta with newly-updated t_start_us */                \
        if (period_us >= PERIOD_DESIRED_US)                                                                            \
        {                                                                                \
            t_start_us = t_now_us - PERIOD_DESIRED_US;                                                                 \
        }                                                                                \
                                                                                \
        time_to_run = true;                                                                                \
    }                                                                                \
}

// Convert microseconds to seconds
#define US_TO_SEC(us) ((us)/1000000UL)
// Convert Joules to KWh (Kilowatt*hours)
#define JOULES_TO_KWHRS(joules) ((joules)/3600/1000)

/// @brief      Obtain a corrected time measurement from a raw time measurement.
/// @details    Assuming you have done experiments to determine your microcontroller (mcu)
///             clock's error, you can correct for it with this function. Pass in a time
///             measurement the mcu has timed directly, and get back a corrected value.
/// @param[in]  raw_sec     A raw time measurement, in seconds
/// @return     A corrected time measurement, in seconds
float do_time_correction(float raw_sec)
{
    // You determine the correct calibration constant. Perhaps it is 0.9813, or perhaps it is
    // 1.19.... You will need to determine this for each individual mcu.
    constexpr float TIME_CORRECTION_CONST = 1.0; // default: 1.0
    float corrected_sec = raw_sec*TIME_CORRECTION_CONST;
    return corrected_sec;
}

/// @brief      Obtain a new instantaneous (at this moment) current reading, in Amps
/// @param      None
/// @return     Current, in Amps
float get_current()
{
    // you implement this
}

/// @brief      Obtain a new instantaneous (at this moment) voltage reading, in Volts
/// @param      None
/// @return     Voltage, in Volts
float get_voltage()
{
    // you implement this
}

/// @brief      Run the coulomb counter task to sum the total energy received from the solar panels
/// @param[out] total_energy_joules_p  (optional) A pointer to a float to receive back the total
///                         energy value acquired, in Joules (Watts*sec). Pass in `nullptr` to not
///                         receive back this value. Note that the previously-cached value is
///                         passed out in the event it's not time to calculate a new value.
///                         The return value of this function will indicate whether a new value
///                         or cached value is passed out here.
/// @param[in]  reset_sum   (optional) pass in true to reset the internally-stored "total energy
///                         acquired" value during this call (prior to performing the latest
///                         power_watts_avg calculation, if it is time for that).
/// @return     true if a new total_energy_joules value was just calculated and passed back via the
///             pointer above, or false if an old, cached value was passed out instead since it
///             wasn't time to obtain and calculate a new value.
bool run_coulomb_counter(float* total_energy_joules_p = nullptr, bool reset_sum = false)
{
    // Set this task to run at 100 Hz
    constexpr uint32_t PERIOD_DESIRED_US = 10000; // 10000us = 10ms, or 100Hz run freq

    static float total_energy_joules = 0;

    if (reset_sum)
    {
        total_energy_joules = 0;
    }

    bool time_to_run = false;
    uint32_t actual_period_us;
    CREATE_TASK_TIMER(PERIOD_DESIRED_US, time_to_run, actual_period_us);
    if (time_to_run)
    {
        // Time to obtain new samples and perform some numerical integration to obtain the total
        // energy received.

        // the previous power calculation, in watts; required for trapezoidal integration
        static float power_watts_old = 0;

        // take new samples, & calculate power from those samples
        float current_amps = get_current();
        float voltage = get_voltage();
        float power_watts = current_amps*voltage;

        float actual_period_sec = US_TO_SEC((float)actual_period_us);
        actual_period_sec = do_time_correction(actual_period_sec);

        // Perform trapezoidal integration to obtain the "area under the curve", which is equal to
        // the energy in joules. Imagine a plot where the y-axis is power and the x-axis is time. If
        // you split the x-axis up into segments of width PERIOD_DESIRED_US, then the trapezoidal
        // area under the curve, within each of those time segments, is equal to time_delta x
        // (power_old + power)/2. This is the energy (Joules) obtained during that time period.
        float power_watts_avg = (power_watts + power_watts_old)/2;
        power_watts_old = power_watts; // prepare for next iteration
        float energy_joules = actual_period_sec*power_watts_avg;

        total_energy_joules += energy_joules;
    }

    if (total_energy_joules_p != nullptr)
    {
        // output this value back to the user
        *total_energy_joules_p = total_energy_joules;
    }

    return time_to_run;
}

void setup()
{
    // do whatever you need to here
    Serial.begin(115200);
}

void loop()
{
    // Energy, in Joules, or Watt*seconds. To convert to Watt*hours, simply divide by 3600 [sec/hr]
    float total_energy_joules;
    bool new_measurements_made = run_coulomb_counter(&total_energy_joules);

    // Let's do an event-based print where we print the latest total_energy_joules value at a rate
    // of 2 Hz, which is typical for digital displays showing information expected to be read by
    // us slow humans. Since the run_coulomb_counter() task is running at 100 Hz, that means we
    // need to print the latest value every 50 runs.
    if (new_measurements_made)
    {
        static uint16_t run_count = 0;
        run_count++;
        if (run_count % 50 == 0)
        {
            float total_energy_kwh = JOULES_TO_KWHRS(total_energy_joules);
            Serial.print("total energy received (J) = ");
            Serial.print(total_energy_joules);
            Serial.print("; (kWh) = ");
            Serial.println(total_energy_kwh);
        }
    }
}

References:

My own answer about generic, timestamp-based cooperative multitasking: Stack Overflow: How to do high-resolution, timestamp-based, non-blocking, single-threaded cooperative multi-tasking

See also:

[my answer] Numerical derivation and integration in code for physics, robotics, gaming, and controls

So how will the OP measure current? A high current, low value resistor in-line with the current flow, and using the Arduino ot measure the voltage crop over the resistor?

That would work, but he mentioned he had this instead: ACS712.

I'll post sample code for the whole coulomb counter thing later too.

Also, measuring those types of low voltages over a resistor requires either oversampling or an op-amp, so the ACS712 is easier for sure.

Trapezoidal vs. rectangular doesn't make much of a difference: it is only a factor 1/2 on the first and last data points. It would be relevant if the integration interval was known with a precision much better than the sampling period (a common case in some engineering contexts), but it is not relevant for a real-time display, especially if sampling at 10 ms intervals and monitoring the result using human eyes.

The merits of trapezoidal integration can be argued, and it's probably not as important as I originally made it sound, but it is super easy to implement, so why not!? Also, it is most important when: 1) the time sampling rate is super low, 2) the rate of change of readings is super high, 3) the readings consistently have a rising slope (rectangular integration underestimates here) OR a consistent falling slope (rectangular overestimates here), and 4) when you care about real-time readings in this instant, not just overall trends or averages.

Also, I wasn't thinking this data would just be looked at with the human eye: I planned for it to be logged too, so you might as well do it right when doing it right is so easy (trapezoidal integration is super simple).

Code posted. I just did the whole coulomb counter.

With a constant sampling rate, your hypothesis 5 is wrong, as rectangular and trapezoidal only differ by the weights of the first and last samples. However, if the sampling rate is unsteady, and correlated with the signal derivative (e.g. faster sampling when the signal rises), then rectangular integration would indeed accumulate errors. Lacking this correlation, the error introduced by the sampling jitter into the rectangular integrator would “wander” (i.e. random walk) as √t. Trapezoidal definitely copes better with very high-jitter sampling.

I wonder why the downvote just now. If you're the downvoter, I'd like to know how the answer is inadequate and where it goes wrong.

I just UP-voted this answer. No idea why somebody would down-vote it. Very thorough and easy to understand. I’d have to study it a lot harder than I have time now to understand your #5 about trapezoidal integration vs. rectangular. As you say, though, it’s easy, so why not?

You want a device called a "coulomb counter". Such a device measures the total current  that flows through it.
I've seen some for Arduino. I believe SparkFun sells one. From a quick search it looks like theirs might be too low voltage for a large solar panel though.

Would I be able to pull the amperage faster to get an equivalent output or is this a fool's errand? Thanks for the tip of coulomb counter. LTC4150 seems cheap and simple to use.

A coulomb counter measures amp/hours of current directly. What is the max voltage of your solar panel? Assuming it can handle the voltage & amount of current you need to measure, it should be perfect for your needs.

I don't like this answer, because it ignores the fact that an Arduino IS a coulomb counter if used correctly, but I won't downvote it because this answer isn't incorrect per se. @RonSper, an Arduino can act as a coulomb counter just fine. It is not a fool's errand, it is exactly what I'd do.

In case you're interested, as I think it's a pretty cool use-case for Arduino, I just did a full implementation of the coulomb counter algorithm from scratch, in code, in my answer.

There are a number of good choices for a sampling device. Some like the INA2221 can do simultaneous I & V at a higher sample rate sampling and accumulate or average the results to produce a low rate data stream better suited to a processor with limited resources without sacrificing anything.
If the idea is to test the output of a solar panel the terminal voltage isn't entirely irrelevant. Panels aren't always maximally illuminated.
If this concept is tied to battery charging I think there's a dimension missing from the concept guiding the approach - the charge acceptance of a storage cell is not a constant. The implicit use for this is to monitor the battery state of charge in order to either disconnect the charger entirely or change to charge balancing and or float modes.
Simply relying on Amp-hours_out = constant * Amp-Hours_in would need to set the constant at the maximum value to avoid trying to drive current at a high rate into fully charged cells. That charger relies on a long low rate charge completion and balancing phase to avoid gradually walking the state of charge down to a fractional charge with maximum acceptance. The available hours of sunlight tend to limit the time available for charge balancing, and the battery's available capacity is set by the cell with the lowest state of charge, so the idea is to get as close to 100% as possible on the cell with the highest state of charge before the charge rate has to drop to avoid damaging cells.
The details are battery technology dependent, but if the idea is to know the state of charge of a battery, then a more complex formula for charge acceptance may produce a more satisfying result.


text:
antenna of the HC-06 bluetooth module
Does the Bluetooth module HC-06 contains a built in antenna similar to HC-05 ?
and if so, then what is the benefit from using antenna?

Sure it also has a build in antenna. Mainly the HC-06 is just a HC-05 with different firmware. What do you mean with "benefit from using antenna"? As it is build in, you don't have a choice. Also every RF device needs some kind of antenna, or it just won't work

thank you @chrisl !


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 can arduino read a frequency higher than 16Mhz?
I will like to understand how does Arduino measure a frequency. Also how does my voltmeter can measure a frequency as well. Since I am a beginner on using microcontroler I would read a frequency like this:
void loop()
{
    while(digitalRead(myPin)==HIGH)
    {
       // pin is high
    }
    // measure time using millis (this is the time the pin was high)

    while(digitalRead(myPin)==LOW)
    {
       // pin is low
    }
    // measure time using millis (this is the time the pin was low)

}

With this code it makes sense to me how to measure a frequency and a duty cycle. The problem with this code is that it will probably be very slow and I it will probably read frequencies up to 100Hz and less.
So my questions are:

How can arduino read frequencies higher than 100Hz? How does it achieve that?
I Googled arduino's frequency and it shows to be 16MHz. That means arudino can read frequencies up to 16Mhz? Ethernet cables specifically CAT5 has a frequency of 100MHz. That means that it sends signals 100,000,000 in one second! How could Arduino send that many signals in one second if I where to buy a Ethernet shield such as this one?

you can use a digital counter IC to scale down the frequency into something Arduino can handle. Feeding a square wave to an 8-bit counter will make bit 8 oscillate at exactly 1/256th the frequency of the square wave.

How can arduino read frequencies higher than 100Hz? How does it achieve that?

Interrupts (if you want to do it in software) or a magical piece of hardware called the Input Compare peripheral that is built into most MCUs.

I Googled arduino's frequency and it shows to be 16MHz. That means arudino can read frequencies up to 16Mhz?

No, that is the speed the CPU operates at. The maximum frequency signal it can read is usually below that (for SPI it's half that, 8MHz, for example).

Ethernet cables specifically CAT5 has a frequency of 100MHz. That means that it sends signals 100,000,000 in one second! How could Arduino send that many signals in one second if I where to buy a Ethernet shield such as this one?

It doesn't. The shield does. The Arduino just tells the shield what to do, and the chip on the shield does it.

I would not use millis() to measure the period of a signal unless my
program had to deal with extremely low frequencies. And by extremely low
I mean below 1 mHz (one millihertz). For frequencies above
1 mHz, the pseudo-code you show would work just as well or better
using micros().
As the frequency goes up, you will start to look at more fancy options
for measuring it. You could for example count the rising edges from an
interrupt and measure the duration of many (not just one) periods with
micros(). This should work up to a few hundred kHz. For faster
frequencies you can use a hardware timer configured as a counter, and
measure the time it takes to overflow. This should be good for
frequencies up to almost half the CPU frequency (8 MHz).
And for the Ethernet signals, see Majenko's answer.


text:
Trying to show g++ (linter-gcc for Atom) where to find Arduino libs
I'm trying to use Atom as an IDE for arduino and arduino-based boards.
I'm using arduino-cli for compilation and avrdude for upload, and now I'm trying to use linter-gcc for linting.
g++ is running and the linter seems to be working ok, but it's can't find built in libs.  I've added:
"C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\*"

to my GCC include paths, I've also tried copying the lib sources to my working directory, but I'm still getting (e.g.):
SPI.h: No such file or directory

Any ideas why gcc isn't seeing SPI.h?

If you are using Atom, why not just download Platform.io running on Atom as your Arduino IDE? It saves you all the trouble of using arduino-cli

TBH I don't want all the weight of Platform.io - I have my toolchain well established with avrdude etc and to my knowledge the platform.io environment is really set up for serial programming of prototype boards like Arduinos rather than my ICSP programming and fuse-setting of mostly custom short-run boards.


text:
Writing to flash memory fails with Optiboot
I am having some issue writing to flash memory on Arduino Uno.
I burned the optiboot bootloader that ships with the IDE 1.8.3 to the chip, then uploaded the test_dospm sketch to write content to flash memory but appears to reset the device instead.
Any idea why this might be happening?

The bootloader which ships with Arduino IDE is version 4 which was already in the Uno from factory. To use the do_spm function you need Optiboot 8 build with this support enabled. It is not enabled in the default builds, because it doesn't fit in the usual Optiboot size for Uno.
The hex file of the bootloader is here. Simply replace the hex file in AVR boards package with this one.

I can add more details or even build and test the bootloader and provide boards.txt settings since I have this on my TODO list.

Thanks @Juraj, that would be helpful! I am currently diving in the source code/makefile to see what are the option I need to enable to build the bootloader and you were right about the do_spm not being enabled by default.

@FallaCoulibaly, I discovered that do_spm is in the normal build of Optiboot8. BIGBOOT is not required. I modified the answer.

Thanks, that did the trick

but if somebody ever needs the big version of Optiboot including my copy_flash_pages function, here it is https://github.com/jandrassy/my_boards. about copy_flash_pages: https://github.com/Optiboot/optiboot/pull/269


text:
How to pass a changing value to a graphic display using Arduino?
I am using an EA DOGM132-5 graphic display, they also have provided a library for Arduino, so everything is nice and easy. The library has a function for easily passing a string to the LCD.
void dog_7565R::string(byte column, byte page, const byte *font_adress, const char *str)
{
unsigned int pos_array;                                         //Postion of character data in memory array
byte x, y, column_cnt, width_max;                               //temporary column and page adress, couloumn_cnt tand width_max are used to stay inside display area
byte start_code, last_code, width, page_height, bytes_p_char;   //font information, needed for calculation
const char *string;

start_code   = pgm_read_byte(&font_adress[2]);  //get first defined character
last_code    = pgm_read_byte(&font_adress[3]);  //get last defined character
width        = pgm_read_byte(&font_adress[4]);  //width in pixel of one char
page_height  = pgm_read_byte(&font_adress[6]);  //page count per char
bytes_p_char = pgm_read_byte(&font_adress[7]);  //bytes per char

if(type != DOGM132 && page_height + page > 8) //stay inside display area
        page_height = 8 - page;
  else  if(type == DOGM132 && page_height + page > 4)
    page_height = 4 - page;

//The string is displayed character after character. If the font has more then one page,
//the top page is printed first, then the next page and so on
for(y = 0; y < page_height; y++)
{
    position(column, page+y); //set startpositon and page
    column_cnt = column; //store column for display last column check
    string = str;             //temporary pointer to the beginning of the string to print
    digitalWrite(p_a0, HIGH);
    digitalWrite(p_cs, LOW);
    while(*string != 0)
    {
        if((byte)*string < start_code || (byte)*string > last_code) //make sure data is valid
            string++;
        else
        {
            //calculate positon of ascii character in font array
            //bytes for header + (ascii - startcode) * bytes per char)
            pos_array = 8 + (unsigned int)(*string++ - start_code) * bytes_p_char;
            pos_array += y*width; //get the dot pattern for the part of the char to print

    if(type != DOGM132 && column_cnt + width > 128) //stay inside display area
                width_max = 128-column_cnt;
    else if(type == DOGM132 && column_cnt + width > 132)
       width_max = 132-column_cnt;
            else
                width_max = width;

            for(x=0; x < width_max; x++) //print the whole string
            {
                spi_out(pgm_read_byte(&font_adress[pos_array+x]));
                //spi_out(pgm_read_byte(&font_adress[pos_array+x])); //double width font (bold)
            }
        }
    }
    digitalWrite(p_cs, HIGH);
}
}

So I just use the function in the sketch with the variables I want and I can easily show a string, but I want to show a changing value for example a temperature reading Tc.
int ThermistorPin = 0;
int Vo;
float R1 = 10000;
float logR2, R2, T, Tc, Tf;
float c1 = 1.009249522e-03, c2 = 2.378405444e-04, c3 = 2.019202697e-07;

Vo = analogRead(ThermistorPin);
R2 = R1 * (1023.0 / (float)Vo - 1.0);
logR2 = log(R2);
T = (1.0 / (c1 + c2*logR2 + c3*logR2*logR2*logR2));
Tc = T - 273.15;

But the string function doesn't support variables. Can someone help me to adjust the string function to take variables or perhaps suggest a better way altogether?

You didn't mentioned how you convert the floating point value Tc to  a string before passing it to dog_7565R::string, but if you are using sprintf(), by default Arduino has the sprintf() support for floating point turn off, there is a way to turn it on if you are using Platform.io IDE, but it will not work for Arduino IDE.
One workaround is to use the dtostrf() function available in the avr-libc that is accessible in Arduino:
dtostrf(floatvar, StringLengthIncDecimalPoint, numVarsAfterDecimal, charbuf);

The dtostrf() converts a float to a c string.
float Tc = T - 273.15;
char floatString[6];
dtostrf(Tc, 4, 2, floatString);

This will turn a value like 32.15 into a string "32.15".

dtostrf() is deprecated, which is why I did not include it in my answer.

Thank you, the dtostrf() function works for me, perhaps later I will find a different solution, but for the time being I have just what I wanted!

@selectstriker2 I'm not aware that dtrostrf() is deprecated? It certainly didn't marked as deprecated on avr-libs documentation, and it is even implemented in ARM version of ArduinoCore-samd for backward compatibility reason.

https://github.com/arduino/ArduinoCore-API/issues/103 and https://github.com/arduino/ArduinoCore-API/tree/master/api/deprecated-avr-comp/avr

@selectstriker2 I think you misunderstood it, when you use those functions, it used to have to explicitly write #include <avr/xxx.h> to use it, it no longer the case. What Arduino did is to include those as part of Arduino Core-API that all platforms must compliant and implemented as its core, e.g. ESP32/8266 or STM32, See https://github.com/arduino/ArduinoCore-avr/commit/06df3bb3ed3c342c448eda2a1e02a5346daebcb0, it also marked "deprecated" those files, the word "deprecated"  is misleading, it just relocated.

That would make more sense. I haven't worked with Arduino in a while and anything I searched for recently said that it had been deprecated.

You have to first convert the floating point value to a string, then pass the resulting string to the dog_7565R::string() function.
It looks like the standard sprintf() provided by Arduino does not support the %f format for floats, so you may have to find another way to convert it or write your own conversion function.


text:
How to calibrate Mpu6050 using library?
I am using i2cdev library
Code:(i did not know this code is correct or not)
#include <Arduino.h>
#include <MPU6050.h>
#include <kalman.h>
#include <stdint.h>

#define ACCELLSB  2048
#define GYROLSB   16.4

#define CONSOLE
#define CALIBRATE

#ifdef  CALIBRATE
int16_t Accel_X_offset;
int16_t Accel_Y_offset;
int16_t Accel_Z_offset;

int16_t Gyro_X_offset;
int16_t Gyro_Y_offset;
int16_t Gyro_Z_offset;
#endif

MPU6050 mpu6050;

Kalman  AngleX;
Kalman  AngleY;

void setup()
{
   mpu6050.initialize();
   mpu6050.setFullScaleAccelRange(MPU6050_ACCEL_FS_16);
   mpu6050.setFullScaleGyroRange(MPU6050_GYRO_FS_2000);

   #ifdef CALIBRATE
   mpu6050.CalibrateAccel();
   mpu6050.CalibrateGyro();

   Accel_X_offset = mpu6050.getXAccelOffset();
   Accel_Y_offset = mpu6050.getYAccelOffset();
   Accel_Z_offset = mpu6050.getZAccelOffset();

   Gyro_X_offset  = mpu6050.getXGyroOffset();
   Gyro_Y_offset  = mpu6050.getYGyroOffset();
   Gyro_Z_offset  = mpu6050.getZGyroOffset();
   #endif

   int16_t AccelX, AccelY, AccelZ;
   int16_t GyroX, GyroY, GyroZ;

   mpu6050.getMotion6(&AccelX,&AccelY,&AccelZ,&GyroX,&GyroY,&GyroZ);

   // I am going to use this values in kalman filter
   #ifdef CALIBRATE
   AccelX -= Accel_X_offset;
   AccelY -= Accel_Y_offset;
   AccelZ -= Accel_Z_offset;

   GyroX  -= Gyro_X_offset;
   GyroY  -= Gyro_Y_offset;
   GyroZ  -= Gyro_Z_offset;
   #endif
}

void loop()
{

}

What is the correct way to calibrate mpu6050(Correct me what i am wrong or this is correct)?
Thanks.

I personally suggest you MPU6050_tockn library.https://github.com/tockn/MPU6050_tockn
If you use calcGyroOffsets() in setup(), it will calculate calibration of the gyroscope, and the value of the gyroscope will calibrated.
#include <MPU6050_tockn>
#include <Wire.h>

MPU6050 mpu6050(Wire);

void setup(){
  Wire.begin();
  mpu6050.begin();
  mpu6050.calcGyroOffsets();
}

If you use calcGyroOffsets(true) in setup(), you can see state of calculating calibration in serial monitor.
#include <MPU6050_tockn>
#include <Wire.h>

MPU6050 mpu6050(Wire);

void setup(){
  Serial.begin(9600);
  Wire.begin();
  mpu6050.begin();
  mpu6050.calcGyroOffsets(true);
}

Serial monitor:
Calculate gyro offsets
DO NOT MOVE MPU6050.....
Done!
X : 1.45
Y : 1.23
Z : -1.32
Program will start after 3 seconds

If you know offsets of gyroscope, you can set them by setGyroOffsets(), and you don't have to execute calcGyroOffsets(), so you can launch program quickly.
#include <MPU6050_tockn>
#include <Wire.h>

MPU6050 mpu6050(Wire);

void setup(){
  Serial.begin(9600);
  Wire.begin();
  mpu6050.begin();
  mpu6050.setGyroOffsets(1.45, 1.23, -1.32);
}

But if want to do it with Kalman filter goto https://github.com/jarzebski/Arduino-KalmanFilter/blob/master/KalmanFilter_MPU6050/KalmanFilter_MPU6050.ino It will guide you.

Thanks for your response in MPU6050_tockn library complementary filter is used but i want to use kalman filter so can you explain how to calibrate using this library?

I just edited answer for that. But it is using KalmanFilter.h not kalman.h


text:
Vary the Speed of Motor
I am trying to control the speed of motor through VFD using 4-20mA signal.
I generate the 4-20mA signal using Arduino.I use low pas filter to obtain the voltages from Arduino PWM pins as shown in the circuit.
Their is continuous deviation at the output.But the deviation is very small.
Example:
when Input is 1V(from 20% PWM in Arduino Code)--> Then output continuous to vary between 3mA to 4mA.
when Input is 5V(from 100% PWM in Arduino Code)--> Then output continuous to vary  between 19mA to 20mA
Can I implement this circuit practically with VFD?
Will this deviation create problem for VFD to control the speed?
Will this very fast continuous deviation is dangerous for

The sawtooth pattern you're showing looks like what I would expect from incomplete filtering of the PWM signal from the Arduino.
I don't know if the variation is going to affect your motor controller or not.
I suggest using a different low pass filter with a much lower pass frequency. That will slow down the response to changes in speed slightly, but produce smoother output. I'd suggest lowering the pass frequency of your filter by 10X or more.
(The good news is that you want to filter the hell out of your PWM signal. You want it to only pass like 10Hz or so. Using a very low cut-off frequency for your filter will get rid of that sawtooth. The result of that would be an output voltage that would be slower to respond, but that should be fine. If your motor takes 1/10th of a second to adjust speeds, is that a problem in your application?)

No its not the problem.I used a low cutt-off frequency and get rid off saw-tooth wave.But their is still very very minor variations! Is their is any 8-bit ADC module which would give 100% pure DC. Although I achieved almost 95% accuracy.Thanks for Help!

A DAC, not a ADC (digital to analog converter, not analog to digital converter) would probably give better results, but then you'd either need 8 digital pins, or a DAC that uses a serial interface like I2C. A quick search on "I2C DAC" does show a number of options. It looks like there is even an Adafruit breakout ready-made for use in Arduino projects.

Yes, I got it.Thanks

The fact is that the low-speed PWM from an Arduino is noisy as hell, and needs a lot of filtering. That's what you're facing. By lowering the cutoff frequency of your filter you should be fine. You aren't trying to create a complex waveform. You just need to vary the speed of a motor, so the fairly slow-changing signal you get out of a heavily filtered PWM output should be fine for this application.


text:
LED goes off in nodemcu If I turn on other LED
I developed an android app to control a robot using nodemcu. I have added some buttons to on/off or blink some LEDs. It works fine but, if I on the one LED or drive the robot, the other LEDs goes off. What I want is the LEDs should be off only if I press the off button for that respective LED.
My code for nodemcu -
#define RIGHT_MOTOR_1  15       // L298N in1 motors Right           GPIO15(D8)
#define RIGHT_MOTOR_2  13       // L298N in2 motors Right           GPIO13(D7)
#define LEFT_MOTOR_1   2        // L298N in3 motors Left            GPIO2(D4)
#define LEFT_MOTOR_2   0        // L298N in4 motors Left            GPIO0(D3)

#define FRONT_LED    16        //Front LED        GPIO14(D0)
#define REAR_LED_1   5         //Rear LED        GPIO12(D1)
#define REAR_LED_2   4         //Rear LED        GPIO12(D2)

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

String command;

const char* ssid = "NodeMCU";
const char* password = "10101010";

ESP8266WebServer server(80);

void setup() {

  pinMode(RIGHT_MOTOR_1, OUTPUT);
  pinMode(RIGHT_MOTOR_2, OUTPUT);
  pinMode(LEFT_MOTOR_1, OUTPUT);
  pinMode(LEFT_MOTOR_2, OUTPUT);
  pinMode(FRONT_LED, OUTPUT);
  pinMode(REAR_LED_1, OUTPUT);
  pinMode(REAR_LED_2, OUTPUT);

  Serial.begin(74880);

  // Connecting WiFi
  WiFi.mode(WIFI_AP);
  WiFi.softAP(ssid, password);

  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);

  // Starting WEB-server
  server.on ( "/", HTTP_handleRoot );
  server.onNotFound ( HTTP_handleRoot );
  server.begin();
}

//LED Logic
void frontLEDon(){
  digitalWrite(FRONT_LED, HIGH);
}

void frontLEDoff(){
  digitalWrite(FRONT_LED, LOW);
}

void frontLEDblink(){
    digitalWrite(FRONT_LED, HIGH);
    delay(500);
    digitalWrite(FRONT_LED, LOW);
    delay(500);
}

void rearLEDon(){
  digitalWrite(REAR_LED_1, HIGH);
  digitalWrite(REAR_LED_2, HIGH);
}

void rearLEDoff(){
  digitalWrite(REAR_LED_1, LOW);
  digitalWrite(REAR_LED_2, LOW);
}

void rearLEDblink(){
    digitalWrite(REAR_LED_1, HIGH);
    delay(50);
    digitalWrite(REAR_LED_1, LOW);
    delay(50);
    digitalWrite(REAR_LED_1, HIGH);
    delay(50);
    digitalWrite(REAR_LED_1, LOW);
    delay(50);
    digitalWrite(REAR_LED_2, HIGH);
    delay(50);
    digitalWrite(REAR_LED_2, LOW);
    delay(50);
    digitalWrite(REAR_LED_2, HIGH);
    delay(50);
    digitalWrite(REAR_LED_2, LOW);
    delay(50);
}

void forward(){
  digitalWrite(RIGHT_MOTOR_1, LOW);
  digitalWrite(RIGHT_MOTOR_2, HIGH);
  digitalWrite(LEFT_MOTOR_1, LOW);
  digitalWrite(LEFT_MOTOR_2, HIGH);
}

void backward(){
  digitalWrite(RIGHT_MOTOR_1, HIGH);
  digitalWrite(RIGHT_MOTOR_2, LOW);
  digitalWrite(LEFT_MOTOR_1, HIGH);
  digitalWrite(LEFT_MOTOR_2, LOW);
}

void right(){
  digitalWrite(RIGHT_MOTOR_1, HIGH);
  digitalWrite(RIGHT_MOTOR_2, LOW);
  digitalWrite(LEFT_MOTOR_1, LOW);
  digitalWrite(LEFT_MOTOR_2, HIGH);
}

void left(){
  digitalWrite(RIGHT_MOTOR_1, LOW);
  digitalWrite(RIGHT_MOTOR_2, HIGH);
  digitalWrite(LEFT_MOTOR_1, HIGH);
  digitalWrite(LEFT_MOTOR_2, LOW);
}

void robotStop(){
  digitalWrite(RIGHT_MOTOR_1, LOW);
  digitalWrite(RIGHT_MOTOR_2, LOW);
  digitalWrite(LEFT_MOTOR_1, LOW);
  digitalWrite(LEFT_MOTOR_2, LOW);
}

void loop(){
      server.handleClient();
      command = server.arg("State");

      if(command == "Forward"){
        forward();
        frontLEDon();
      }
      if(command == "Backward"){
        backward();
        rearLEDon();
      }
      if(command == "Left"){
        left();
      }
      if(command == "Right"){
        right();
      }
      if(command == "Stop"){
        robotStop();
      }
      if(command == "FrontLEDon"){
        frontLEDon();
      }
      if(command == "FrontLEDblink"){
        frontLEDblink();
      }
      if(command == "FrontLEDoff"){
        frontLEDoff();
      }
      if(command == "RearLEDon"){
        rearLEDon();
      }
      if(command == "RearLEDblink"){
        rearLEDblink();
      }
      if(command == "RearLEDoff"){
        rearLEDoff();
      }
}

void HTTP_handleRoot(void) {
  if( server.hasArg("State") ){
       Serial.println(server.arg("State"));
  }
  server.send ( 200, "text/html", "" );
  delay(1);
}

the android app may be the cause


text:
How can i send data to phpmyadmin database? using esp8266 nodemcu and max30100
i want to send data from my sensor to database phpmyadmin. but i only get zero values. please help me thank you.
void loop()
{
  pox.update();
  BPM = pox.getHeartRate();
  SpO2 = pox.getSpO2();
 // Sending_To_phpmyadmindatabase(BPM);

  if (millis() - tsLastReport > REPORTING_PERIOD_MS) {
    Serial.print("BPM: ");
    Serial.println(BPM);
    Serial.print("SpO2: ");
    Serial.print(SpO2);
    Serial.println("%");
    Serial.println("*********************************");
    Serial.println();
    tsLastReport = millis();
    delay(0);
    }
    Sending_To_phpmyadmindatabase(BPM);
}

void Sending_To_phpmyadmindatabase(float BPM){
  if (client.connect(server_addr,80)) {
    Serial.println("connected");
    Serial.print("GET /pulse.php?BPM=12");
    client.print("GET /pulse.php?pox.getHeartRate="+String(BPM,1));
    Serial.println("pox.getHeartRate!");
    client.println("pulse=");
    client.println(BPM);
   // Serial.print("GET /vsmonitor/connect.php?SpO2=12");
   // client.print("GET /vsmonitor/connect.php?SpO2="+String(SpO2,1));
   // Serial.println("SpO2!");
    //client.println("o2_sat=");
    //client.println(SpO2);
    client.print(" ");
    client.println(" HTTP/1.1");
    client.println("Host: 192.168.15.4");
    client.println(server_addr);
    client.println("Connection: close");
    client.println();
  }
  else {
    Serial.println("--> connection failed\n");
  }
  Serial.println();
  delay(5000);
}

so, where is the problem? ... you have a bunch of Serial.print() functions ... why did you not say what is being printed?

your question is like i want to boil water from a well, but i can't ... several scenarios are possible ... no water in well, no bucket to carry water, no pot to boil water, no  stove, no gas for fire, no electricity .... i think that you get the idea

the problem starts when i call the void Sending_To_phpmyadmindatabase(BPM);. i get zero values. example BPM 0.0 in serial monitor. and in database is 0

Sending_To_phpmyadmindatabase(BPM); slowers down m output i dont know why, it works perfectl when i remove the Sending_To_phpmyadmindatabase(BPM);.

remove ln from the second url parameter prints. and what should client.print(" "); do?

@CodeGorilla, do some research into how HTTP GET requests work. They're really useful. Don't be fooled by the name "GET". A GET request "gets" a URL from the web server, receiving data in return or just a simple acknowledgement, but also offering the opportunity of sending data from the client as part of the URL parameters (like ?parameter1=value1&parameter2=value2 etc.). It's often the simplest way of sending small amounts of data to a web server.


text:
cannot find esp8266 via boardmanager
i'm using arduino ide 1.8.12 opened preferences window and did enter
http://arduino.esp8266.com/stable/package_esp8266com_index.json, https://arduino.esp8266.com/stable/package_esp8266com_index.json
(all comma separated) into the Additional Board Manager URLs field. then i opened the boardmanager (Strg+Shift+I) and enter 'esp' in the search field. BUT I CAN'T FIND "esp8266 by ESP8266 Community". it's not listed. WHAT CAN I DO NOW ?
additive : is there a way to include a locally available json file in the arduino as a library?
the file
    package_esp8266com_index.json
is in the directory
    C: \ Users \ [user] \ AppData \ Local \ Arduino15
thanks in advance

did you restart the IDE?


text:
Issues with reading numbers from serial port
I've built 2 motor drivers for a robotics project and need to set positions that I want the motors to move to, and read that using the arduino. The arduino then uses a rotary encoder to implement a closed loop PID controller and move the motor the set point. My code wasn't working so I started troubleshooting and found out that my setpoint was getting reset to 0 automatically!
The only thin that changes the setpoint was the serial read so I made a smaller sketch for troubleshooting which is this:
volatile long setpoint;

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

void loop() {
  if (Serial.available()){
    setpoint = Serial.parseInt();
    Serial.print("Set to: ");
    Serial.println(setpoint);
  }
}

The result was quite odd, it sets the value correctly but resets back to 0 without me sending any new commands!
I tried updating the IDE to 1.8.12, tried old and new arduinos (with old and new bootloader) but all had the same result. Here is a demo video showing the weird reset to 0 problem:
https://streamable.com/kfgv61
I tried changing the buadrate higher or lower but that also didn't fix anything. Any ideas on what I'm doing wrong?

The problem here is that Serial.parseInt() stops when it sees the
newline, but it does not consume that newline, which is left in the
input buffer. Thus, at the next loop iteration, Serial.available()
returns true because of this newline and, unless you send another value
fast enough, Serial.parseInt() times out and returns zero.
The easy fix is to consume that newline yourself:
void loop() {
  if (Serial.available()){
    setpoint = Serial.parseInt();
    if (Serial.peek() == '\n') Serial.read();  // consume LF
    Serial.print("Set to: ");
    Serial.println(setpoint);
  }
}

I personally would not use Serial.parseInt() at all, and would buffer
the data myself until I see the '\n'. This way there are
no surprises with timeouts being read as zero.


text:
Button example: resistor vs wire
I am playing with this basic example:
Arduino: Button

There're a lot of existing questions about why to connect button to the ground. I get the idea more or less. Is done to avoid "noise" during reading the input value.
However, what I don't understand is why to use resistor instead of a wire? If I remove resistor and put the wire instead the example stops working. Could someone explain me this?

If you remove the resistor and put a wire then when you press the button you have a dead short to ground.  That's sometimes a little more exciting as it tends to cause smoke and sometimes even fire.  But it tends to be a one-shot experiment with most Arduino.

There are no existing questions about why to put the resistor there.  It's all well known and been done that way for decades stuff.  Without it the pin is floating when the button isn't pressed.  It isn't connected to 5V and it isn't connected to ground.  So it reads whatever voltage it wants based on the noise it picks up.  With the resistor, when the button isn't pressed it is connected to ground and therefore reads LOW reliably.  It's no mystery and there's no debate about it anywhere except among those who don't know what they talk about.


text:
Placing decoupling capacitors when building an Arduino PCB with Atmega328-PU
I have previously asked this question:
Custom build of arduino on a pcb
And thanks to the answer by Majenco I have learned that my circuit works a lot better when adding a capacitor. For example I am using the NRF24L01 and it is much more stable when using a capacitor. I am placing the capacitor for now next to the power supply like this:

Right now I am running this on a breadboard. The Atmega328 chip is very cheap compared to the arduino uno board; therefore, I will like to continue building my projects based on the atmega328P-PU chip.
Anyways before printing the PCB based on the Atmega328P-PU chip, where should I place the capacitors in order to reduce the most noise? The capacitors are very cheap and making one good design will enable me for all my future designs to be based from this one.
From researching on the internet I see a lot of different examples. Everyone uses different capacitance sizes. For example I have found this:

I got that from this link: https://www.autodesk.com/products/eagle/blog/what-are-decoupling-capacitors/
On other places they say to place the capacitance closest to the pins such as from this video. If that is true should I just place one capacitor on pins 7 and 8. Lastly the other capacitor on pins 20 and 22?
I do not mind soldering extra pins knowing my circuit will have the best performance.

There is a reason that many chip has VCC and GND next to each other or nearby. You should place the capacitors close to those pins, for both VCC and AVCC. Read the datasheet as it provide much more information.

The Autodesk link explains it very well.
You should place small/fast decoupling capacitors (0.1uF) close to the power pins of your on-board ICs to deal with local spikes in power consumption of those devices.
Place a larger/slower decoupling capacitor (1uF or larger, depending on many factors such as distance of the power supply from the board and expected power consumption) somewhere on the board to deal with varying loads and ripples in your power supply.
This has been common practice at least since I’ve started with electronics about 40 years ago (and probably much longer).


text:
How can I connect an ESP8266-01 to a shift register?
I am connecting this shift register to my ESP8266-01 for more GPIO options.
It appears there is a GPIO 16, but it's tied to a RESET pin.
I checked both datasheets, the ESP8266 datasheet, and I also checked the datasheet for the shift register for more information on what kinds of pins can be hooked to each of the input pins.
I am also thinking whether it's viable to connect one of the other available pins of the ESP8266 and use it for this connection with the shift register (either RX or TX).

My understanding is that I need to connect three pins of the ESP8266 directly to the shift register for its latch, clock, and serial pin.
I am also wondering if I can connect the serial pin of the ESP8266 to the serial pin of the shift register?

buy an esp-12 or a dev board like Wemos D1 mini

It cannot be expanded to more gpio?

It can, but, why complicate it? it is the same esp8266 only more pins are accessible on esp-12. the esp-01 is for use as serial WiFi adapter.

It’s to have use of it now and in the future. I think gpio 16 can be used. Just must be disconnect during sketch upload. Confirmation on this? Going to test later and update . Happy to accept answers

Ahh, interesting. Use as serial WiFi adapter. Exactly as I intend to use it for a separate project.

io 16 is not accessible on esp-01. esp-01 has RX, TX, io 0 and io 2

You have several options. Your drawing shows a 74HC595 which is a serial in parallel output. You need a minimum of two pins to operate it, one for clock and another for data. Adding a third for reset will make it much easier to use. You can use any GPIO pins you like but be cognisant of any other uses those pins may be performing in your system such as boot etc.
The part also has SPI, this will directly interface to the shift register. You can cascade them to as many deep as you want. The SPI operates concurrently input and output at the same time. You actually have to send something to get something, that is what cycles the clock. There technically is no limit to the number of devices but there are practical limitations. Since the data transfer is only one way on a pin you can easily buffer it. This generally is one of the fastest I/O you can get.
The second which only requires is I2C which is a synchronous buss that directly addresses the peripheral devices. Originally it had 7 address bits giving you 127 seperate devices you can access. Each device can have as many individual locations/registers as it needs but normally only one address. A lot of chips have this built in and have a preassigned address or address range. For example there are FRAM chips that are 32K x 8 bits at a single address.
There are a lot more options available but I mentioned these because modules that implement these functions are inexpensive and readily available. You can look up "SPI" and "I2" to get a lot more information. Good luck and enjoy your project.


text:
How do I use a SMD crystal with 4 pins?
I am running my arduino project with the atmega328 chip like this:

I have purchased by mistake this crystal:

The reason why I purchased by mistake that crystal was because it has this description:

16MHz ±10ppm 22pF 60Ω SMD-3225 SMD Crystal Resonators RoHS

I thought that it contained the 22pF ceramic capacitors inside. But latter I learned that I still the 22pf ceramic capacitors. (Please correct me if I am wrong)
Anyways how can I use that crystal? I only know how to connect the 2 pin crystal. Since this crystal has 4 pins now I am confused.
To me it makes sense to connect it like this:

Connect pins 9 and 10 from atmega --TO--> pins 1 and 3 from the crystal.
Connect pins 2 and 4 from crystal --TO--> Ground
Connect the 22pf ceramic capacitors to pins 1 and 3 from crystal and ground like in the first diagram.

this is a nice question. Once for a project I stumbled upon this problem too.
The way you described the connection should work perfectly fine.

To me it makes sense to connect it like this:
  Connect pins 9 and 10 from atmega --TO--> pins 1 and 3 from the crystal.
  Connect pins 2 and 4 from crystal --TO--> Ground
  Connect the 22pf ceramic capacitors to pins 1 and 3 from crystal and ground like in the first diagram.

Keep it going and greetings from Switzerland.


text:
Time synchronization of GPS based Wireless Network
I am working on an ARDUINO based wireless network. In this network, each node or device is having its own GPS module. Each GPS module has to get location data and have to send to a single base-station. Let say we have 10 nodes in our network. A specific time(let say 1 sec) is assigned to each node when it can receive location and send it to the base-station (everything to be done in that 1 sec allocated time). So, all nodes will be done sending the data to the station and now the 2nd cycle repeats and so on.
For experiment purpose, I have created two nodes and connected LEDs each one. I am getting time from GPS module using tinygps library. To verify the time synchronization, I have programmed MCU in such a way that it turns ON the LED for 50 ms after every 10 sec. Uploaded the same code on both devices.
If both devices are sync then LEDs will TURN ON and OFF at the same time. But that's is not the case. LEDs of both devices are turning ON and OFF with a huge difference of time (almost 4 to 5 sec). Which shows that GPS times are not synchronized.
Following is the code:
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
/*
   This sample code demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
   It requires the use of SoftwareSerial, and assumes that you have a
   4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
*/
static const int RXPin = 4, TXPin = 3;
static const uint32_t GPSBaud = 9600;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

const int LEDPIN = 13;
void setup()
{
  Serial.begin(9600);
  ss.begin(GPSBaud);

  Serial.println(F("FullExample.ino"));
  Serial.println(F("An extensive example of many interesting TinyGPS++ features"));
  Serial.print(F("Testing TinyGPS++ library v. ")); Serial.println(TinyGPSPlus::libraryVersion());
  Serial.println(F("by Mikal Hart"));
  Serial.println();
  Serial.println(F("Sats HDOP  Latitude   Longitude   Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum"));
  Serial.println(F("           (deg)      (deg)       Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail"));
  Serial.println(F("----------------------------------------------------------------------------------------------------------------------------------------"));

  pinMode(LEDPIN,OUTPUT);
  digitalWrite(LEDPIN,LOW);
}

unsigned double interval = 50;
bool pinState = LOW;
unsigned double startmillis;
void loop()
{
  static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;

  printDateTime(gps.date, gps.time);
  double sec = gps.time.second();

    while(1){

      if(millis()-startmillis >= interval){
            // 50 milli seconds passed
            digitalWrite(LEDPIN,LOW);
            Serial.println("50 millis passed.");
            smartDelay(1000);
          }
          else{
             // Still in loop. Turn ON LED
             digitalWrite(LEDPIN,HIGH);
          }

          }

  smartDelay(0);

  if (millis() > 5000 && gps.charsProcessed() < 10)
    Serial.println(F("No GPS data received: check wiring"));
}

// This custom version of delay() ensures that the gps object
// is being "fed".
static void smartDelay(unsigned long ms)
{
  unsigned long start = millis();
  do
  {
    while (ss.available())
      gps.encode(ss.read());
  } while (millis() - start < ms);
}

static void printFloat(float val, bool valid, int len, int prec)
{
  if (!valid)
  {
    while (len-- > 1)
      Serial.print('*');
    Serial.print(' ');
  }
  else
  {
    Serial.print(val, prec);
    int vi = abs((int)val);
    int flen = prec + (val < 0.0 ? 2 : 1); // . and -
    flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
    for (int i=flen; i<len; ++i)
      Serial.print(' ');
  }
  smartDelay(0);
}

static void printInt(unsigned long val, bool valid, int len)
{
  char sz[32] = "*****************";
  if (valid)
    sprintf(sz, "%ld", val);
  sz[len] = 0;
  for (int i=strlen(sz); i<len; ++i)
    sz[i] = ' ';
  if (len > 0)
    sz[len-1] = ' ';
  Serial.print(sz);
  smartDelay(0);
}

static void printDateTime(TinyGPSDate &d, TinyGPSTime &t)
{
  if (!d.isValid())
  {
    Serial.print(F("********** "));
  }
  else
  {
    char sz[32];
    sprintf(sz, "%02d/%02d/%02d ", d.month(), d.day(), d.year());
    Serial.print(sz);
  }

  if (!t.isValid())
  {
    Serial.print(F("******** "));
  }
  else
  {
    char sz[32];
    sprintf(sz, "%02d:%02d:%02d ", t.hour(), t.minute(), t.second());
    Serial.print(sz);
  }

  printInt(d.age(), d.isValid(), 5);
  smartDelay(0);
}

static void printStr(const char *str, int len)
{
  int slen = strlen(str);
  for (int i=0; i<len; ++i)
    Serial.print(i<slen ? str[i] : ' ');
  smartDelay(0);
}

After a bit research, I found the following paper which is very helpful to solve my problem:

https://www.frontiersin.org/articles/10.3389/fbuil.2018.00082/full

The problem is, they have not provided the code anywhere which I can use for my problem.
Please let me know what should I do to synchronize the GPS time for two devices and then, in the long run, for a network.

Your question is unclear, but somehow I doubt that your problem will be solved with the techniques and software described in that paper. How do you know (for example) that your two units are taking a time reading at the same time? Please try to be more specific.

I am getting the time readings from GPS continue-sly. At every 10th sec (10th means 10, then 20 then 30 sec), program turns ON the LED for 50 ms. Same program is burnt on both devices.
I hope that makes it more clearer.

Start by removing from the code everything you do not need, so that you get a minimal example. Why the infinite while(1) loop? Why did you put unreachable code after that loop? Why don't you ever set startmillis?

I am breaking the while(1) loop after it reaches the condition. startmillis stores the millis when condition of 10 sec is met. I am breaking that loop when difference between millis from when the timer started and when 50 ms have been passed after that.

The mentioned paper solves my problem but I am not getting any code.


text:
LCD1602A displaying blocks
I am having an issue with the LCD1602A and Arduino Uno. I have followed a tutorial on youtube that has got the device working, however the LCD is only displaying white blocks in all 16 segments of the top row.

Pin Out
LCD

VSS -> GND on Breadboard
VDD ->  5V on Breadboard
V0  -> Connected to 5K potentiometer
RS  -> Pin 1 on Arduino Uno
RW  -> GND on Breadboard
E   -> Pin 2 on Arduino Uno
D0  -> Not Connected
D1  -> Not Connected
D2  -> Not Connected
D3  -> Not Connected
D4  -> Pin 7 on Arduino
D5  -> Pin 6 on Arduino
D6  -> Pin 5 on Arduino
D7  -> Pin 4 on Arduino
A   ->  5V on Breadboard
K   -> GND on Breadboard

Code
#include <LiquidCrystal.h>
LiquidCrystal lcd(1, 2, 4, 5, 6, 7); // Creates an LC object. Parameters: (rs, enable, d4, d5, d6, d7)
void setup() {
 lcd.begin(16,2); // Initializes the interface to the LCD screen, and specifies the dimensions (width and height) of the display }
}
void loop() {
 lcd.print("Arduino"); // Prints "Arduino" on the LCD
 delay(3000); // 3 seconds delay
 lcd.setCursor(2,1); // Sets the location at which subsequent text written to the LCD will be displayed
 lcd.print("12345");
 delay(3000);
 lcd.clear(); // Clears the display
 lcd.blink(); //Displays the blinking LCD cursor
 delay(4000);
 lcd.setCursor(7,1);
 delay(3000);
 lcd.noBlink(); // Turns off the blinking LCD cursor
 lcd.cursor(); // Displays an underscore (line) at the position to which the next character will be written
 delay(4000);
 lcd.noCursor(); // Hides the LCD cursor
 lcd.clear(); // Clears the LCD screen
}

Now the program compiles and uploads OK the potentiometer dims the blocks perfectly fine.
However it is supposed to print Arduino and 12345 and I am unsure why.
What am I missing?
Thanks

Check your contrast Settings.

Checked contrast settings using potentiometer no luck. These only dim the blocks.

Your pin out text does not match the pin assigment in the lcd() line.
Should be LiquidCrystal lcd(1,2,7,6,5,4), e.g., your data wires are flipped.

Thanks for your help.


text:
Trying to draw a bitmap to an LED matrix only draws the left half
I'm EXTREMELY new to Arduino and fairly new to programming as a whole, but I thought it would be fun to try and write a program that draws arbitrary 1-bit bitmaps to an LED matrix using the Adafruit RGBMatrixPanel library. I'm trying to draw this image to the screen:

But it conks out after 16 pixels each row...

Below is my code in full. It seems like the bit mask only works for the first 16 columns, but I can't seem to figure out why it stops at that point. I'm using an Arduino Nano, if that helps.
#define CLK  8
#define OE   9
#define LAT 10
#define A   A0
#define B   A1
#define C   A2

RGBmatrixPanel matrix(A, B, C, CLK, LAT, OE, false);
unsigned long int pixelGrid[] = {
  0x00000000,
  0x31CEFDCE,
  0x78CCFCCC,
  0x78CC84CC,
  0x78CC04CC,
  0x78CC04CC,
  0x78CC24CC,
  0x78783CFC,
  0x783024FC,
  0x303004CC,
  0x303004CC,
  0x303004CC,
  0x003084CC,
  0x3030FCCC,
  0x3078FDCE,
  0x00000000
};
unsigned long int bitMask = 0x00000001;
void setup() {
  matrix.begin();
  uint8_t r=0, g=0, b=0;

  for(uint8_t y=0; y<16; y++) {
    unsigned long data = pixelGrid[y]; // select row of bits from image
      for (byte x = 0; x <32; x++) { //iterate through columns
        if (data & (bitMask << x)) {// works!
          r = 1; // set LED to ON
        }
        else {
          r = 0; // LED is OFF
        }
      matrix.drawPixel(x, y, matrix.Color333(r, g, b));
    }
  }
}

void loop() {
}

Here's the part of the code that's probably messing up, isolated:
for (byte x = 0; x <32; x++) {
        if (data & (1 << x)) {
          r = 1;
        }
        else {
          r = 0;
        }

Thanks for your help!
Edit: Changing the data variable from int to long to avoid it being truncated lead adds another column of pixels, but it kind of looks like they're all squished into column 16 for some reason:
Note: I tried drawing a rectangle from (0,0) to (31, 15) to make sure that all the LEDs worked, and I was able to do that.
Edit 2: Instead of the bitmask being 1, I made it so that:
unsigned long int bitMask = 0x00000001;
// ...
 if (data & (bitMask << x)) { // works!
          r = 1; // set LED to ON
        }
        else {
          r = 0; // LED is OFF
        }

I'm guessing regular numbers default to 16-bit unsigned ints.
The issue is fixed, woo! I edited the big code block to match.

I'd try exchanging the x and y coordinates in matrix.drawPixel(x, y, matrix.Color333(r, g, b)); to see if the data is layed out in landscape and not in portrait.

Changing the x/y coordinates rotates the image 90 degrees, as expected: https://i.imgur.com/GXzS4LG.png It's a 32x16 panel, so I unfortunately can't check if it goes down any lower.

'pixelGrid[]' are longs but your temp inside the for() loop, 'data', is an int. Thus, it gets only half the data. Easy mistake to make (and they can be so hard to spot when you know perfectly well what you meant... :)
Update:

By switching the int to long, I've successfully unlocked a seventeenth
  column! Unfortunately, it looks like all the pixels are bunched up in
  that seventeenth column.

Another error of the same kind (I missed it the first time around):
Change (1 << x) to (1L << x). The original expression is calculated as int and the result is widened in the assignment to 'data' (and I think there was compiler bug int the code that did that, besides). The corrected expression is calculated as a long in the first place, which is what I think you intended.
Update 2:
From your question Edit 2:

I'm guessing regular numbers default to 16-bit unsigned ints.

You are correct - ints of unspecified size default to 16-bits in the Arduino gcc compiler used by the Arduino IDE (and just about everywhere else in the Arduino domain that I know of). The language standard leaves the compiler writer free to choose the size of an int that best fits the target-machine's architecture. 16-bits is the most common, but by no means the only - size implemented in most compilers. For this reason, most compilers' pre-processors implement specific-sized data types, and application writers - you & I - are advised to use these wherever data-size matters. For the Arduino's gcc compiler, there are predefined types such as int8_t (signed 8-bit int), uint32_t (unsigned long int), etc.
int is an ok "I don't care, just as long as it works" option. When you do care - specify.
(If my answer helped you, please upvote it or select as best answer. The latter has the important function on this site of marking the question as "completed" so it doesn't keep re-appearing as an unanswered question.)

By switching the int to long, I've successfully unlocked a seventeenth column! Unfortunately, it looks like all the pixels are bunched up in that seventeenth column...https://i.imgur.com/tgpcnH3.png

perhaps you edit your question? Both code, and error description...

Marked you as best answer just now. Thank you for all your help!


text:
USB disconnects when using a capacitor
I'm currently working with some WS2812B LEDs and tried out adding a capacitor to be safe from voltage spikes (was recommended by Adafruit). I noticed that a soon as I connect a capacitor between 5V and ground that the USB is disconnect from the PC (Windows Usb disconnect sound plays). I wondered why and tried another setup. This time just the capacitor between 5V and ground. Nothing else. According to my knownledge this isn't a short (capacitor is intact) and therefor this setup should be valid. Again the same thing happens: USB disconnects...
I really don't know why this happens but want to understand it. The capacitor I use is rated 16V 1000 mF (electrolytic in case this is relevant). The capacitor is also connected the right polarity. What forces the USB to disconnect (and let Windows play the USB disconnect sound). Am I may damaging the USB Port somehow and therefor a disconnect is forced as a security measurement?
Oh yeah... Using an Arduino Uno R3 made by Elegoo.
Hope you can help me out,
Tmirror

put the capacitor on the other end of the LED strip; it does more good there anyway by smoothing the borderline low voltage situations at the end (possibly buying you several more stable pixels), and it uses the strip's intrinsic resistance to limit inrush current spikes. That said, you still might need a smaller capacitor if you want to power over USB and avoid the protection mechanisms. You might also try a powered USB hub; those are often a lot more forgiving than built-in ports, which are better protected because blowing a built-in really sucks...

The USB specifications allow a maximum of 10uF total capacitance on the USB power lines. By putting 1000uF you have given it 100x more than is allowed.
This causes a massive inrush current and the USB host (your computer) sees it as a short circuit, so it shuts off the power in a panic to protect itself.
A capacitor does have a role to play in helping to remove power supply noise caused by power-hungry and noisy devices like WS2812B LEDs, but just slapping it across the power supply pins isn't going to really help.
Instead you should increase the impedance of the power supply to the noisy device(s) and use a capacitor to reduce the impedance again. This will help to preferentially draw current from the capacitor to supply the LEDs while smoothing out the draw from the main supply over time.
A simple circuit is to use a resistor with a capacitor:

simulate this circuit – Schematic created using CircuitLab
The values I show there for the resistor and capacitor are pretty random. The smaller the resistor the more demand will be put on the power supply. The bigger the resistor the more demand will be put on the capacitor. If the resistor is too big the capacitor won't be able to store enough power to run the LEDs, and too much voltage will be dropped across  it. If the capacitor is too small it won't be able to store enough power to run the LEDs. Tuning those values depends very much on the amount of noise there is and the current draw of the LEDs.
You must also make sure the resistor can handle the amount of power dissipated by the current flowing through it.

If we'd need a 10R (or greater) to limit current to the official 500ma @5v, we can only fully turn on 2 rgb LEDs before 1.2v is lost through the resistor and the blue LEDs and ws2812b start having issues with undervoltage...

@dandavis Like I said, the values I show are random. Choose suitable values depending on the situation.

Sure, but unless the situation is "power a strip of 2 LEDs", there's no values that work...

If you draw 400mA through a 0.25Ω resistor it will drop just 0.1V. https://uk.farnell.com/multicomp/mcknp0w2j025ka10/res-0r25-5-500mw-axial-wirewound/dp/1903673