text:
Please Correct my Delay Code without using delay();
This is my loop()function:
if(Serial.read() == 't') {
  tarestate = true;
}

while(tarestate == true) {
  timeNowTare = mills();
  if(mills() - timeNowTare >= 3000) {
    Serial.println("Tare");
  }
  tareState = false;
}

Where tareStare is a boolean, timeNowTare is a long.
I need to print on serial:

Tare

three seconds after I enter "t" into serial.
With everything I have tried to date, the program either stops or tares immediately after entering “t”.
EDIT: Thanks to everyone who responded with answers.
The solution was simply to move the timeNowTare = true; declaration up to the Serial.read() if statement. I also changed the while loop to an if statement because it seemed to make my code run quicker.

the only place you initialise timeNowTare is just before you use it ... so, that will never be > 3000 ... perhaps timeNowTare = mills(); inside the first if

Please use the answer box to make an answer. Comments are for clarifying the question. Thanks! :)

not easy on a mobile device - plus was giving the OP a chance at an "aha" moment and fixing the code by themselves :p

Move timeNowTare = millis(); inside first if:
if (Serial.read() == 't') {
  tareState = true;
  timeNowTare = millis();
}

and tareState = false inside second if:
while (tareState) {
  if (millis() - timeNowTare >= 3000) {
    Serial.println(F("Tare"));
    tareState = false;
  }
}

The easiest solution is to just use delay():
if (Serial.read() == 't') {
    delay(3000);
    Serial.println(F("Tare"));
}

What? You said “no delay()”? OK, then just write your own
implementation of delay() and inline it in place of the actual call to
delay():
if (Serial.read() == 't') {
    uint32_t timeNowTare = millis();
    while (millis() - timeNowTare < 3000) continue;  // wait
    Serial.println(F("Tare"));
}

This seems to be more or less what you attempted. You write a while
loop that blocks the program for three seconds. It is also what leoc7's
answer does.
However, doing so is completely foolish. Why would you write your own
version of delay() when the Arduino core provides you with a well
tested one? Why would you want to avoid the standard delay() in the
first place?
It turns out there is a very good reason to avoid delay(). The reason
is that delay() blocks your program for the entire delay duration.
If your code needs to be responsive to some external inputs (as any non
trivial program at some point needs), this means within that time window
the program will be completely unresponsive. The bad thing about
delay() is not the implementation (there is no point in replacing it
with your own), it's the fact that it blocks your program. If you
replace delay() by your own blocking code you have won nothing.
The real solution is to think in terms of a finite state machine. Either
the program is running in “tare mode” or not. The possible state
transitions are:

upon reading a 't' on the serial port, you enter tare mode and take
note of the current time
if you are already in tare mode and three seconds have elapsed since
you entered that mode, then you print out "Tare" and exit tare mode.

Here is a straight forward implementation of such state machine:
static bool tare_mode = false;
static uint32_t tare_start_time;  // meaningful only in tare_mode
if (Serial.read() == 't') {
    tare_mode = true;
    tare_start_time = millis();
}
if (tare_mode && millis() - tare_start_time >= 3000) {
    Serial.println(F("Tare"));
    tare_mode = false;
}

Now you can add more code to loop() and this extra code will never be
blocked by your “tare” feature.


text:
Arduino IDE 1.8.8 built in 1.2.1 Temboo Library?
I am weirded about the built-in "latest Temboo library" with the latest Arduino IDE; when a previous older code says to download the latest Temboo version < 2?
(which I found this: https://temboo.com/download)
http://wirebeings.com/arduino-intruder-alarm.html
I am using Arduino Uno or Arduino Leonardo + an iDuino Yun shield to recreate the experiment above.
I keep getting errors like this:
No matching function for call to 'TembooChoreo::TembooChoreo()'? TembooChoreo SendSMSChoreo; Error Help
Arduino: 1.8.8 (Windows 10), Board: "Arduino Leonardo"
Build options changed, rebuilding all
In file included from C:\Users\user\Documents\Arduino\intruderAlarmTest\intruderAlarmTest.ino:6:0:
E:\arduino\arduino-1.8.8\libraries\Temboo\src/Temboo.h:86:43: error: expected identifier before '(' token
#define TEMBOO_ERROR_ACCOUNT_MISSING      (201)
                                       ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:264:13: note: in expansion of macro 'TEMBOO_ERROR_ACCOUNT_MISSING'
         TEMBOO_ERROR_ACCOUNT_MISSING       = 201,

         ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/Temboo.h:86:43: error: expected '}' before '(' token
#define TEMBOO_ERROR_ACCOUNT_MISSING      (201)
                                       ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:264:13: note: in expansion of macro 'TEMBOO_ERROR_ACCOUNT_MISSING'
         TEMBOO_ERROR_ACCOUNT_MISSING       = 201,

         ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/Temboo.h:86:44: error: expected unqualified-id before numeric constant
#define TEMBOO_ERROR_ACCOUNT_MISSING      (201)
                                        ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:264:13: note: in expansion of macro 'TEMBOO_ERROR_ACCOUNT_MISSING'
         TEMBOO_ERROR_ACCOUNT_MISSING       = 201,

         ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/Temboo.h:86:44: error: expected ')' before numeric constant
#define TEMBOO_ERROR_ACCOUNT_MISSING      (201)
                                        ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:264:13: note: in expansion of macro 'TEMBOO_ERROR_ACCOUNT_MISSING'
         TEMBOO_ERROR_ACCOUNT_MISSING       = 201,

         ^

In file included from C:\Users\user\Documents\Arduino\intruderAlarmTest\intruderAlarmTest.ino:7:0:
E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h: In member function 'char* TembooCoAPChoreo::getResponseData()':
E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:247:41: error: 'm_respData' was not declared in this scope
     char* getResponseData() {return m_respData;}

                                     ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h: In member function 'char* TembooCoAPChoreo::getHTTPResponseCode()':
E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:248:45: error: 'm_httpCodeStr' was not declared in this scope
     char* getHTTPResponseCode() {return m_httpCodeStr;}

                                         ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h: At global scope:
E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:277:5: error: expected unqualified-id before 'protected'
 protected:

 ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:280:27: error: 'm_client' declared as reference but not initialized
     TembooCoAPClient& m_client;

                       ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:311:5: error: expected unqualified-id before 'protected'
 protected:

 ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:314:1: error: expected declaration before '}' token
};
^
exit status 1
Error compiling for board Arduino Leonardo.
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
Update:
I found that   by adding #include TembooYunShield.h
and TembooYunShieldChoreo  SendSMSChoreo;
instead of TembooChereo SendSMSChoreo;
fixes most of the errors
except the @Temboo and @Twilio problem.

Sounds like they made a mess of it. Just delete it and download the official latest version of the library manually.

yeah how, I don't even understand there are different programming languages that I extracted from .zip or .jar. to raw folders and files and replaced my older Temboo with it.
but it still doesn't work, I can't make https://temboo.com/download seem to work so I stick with the built in latest 1.2.1 Temboo library from Arduino 1.8.8.

Can anyone help me with this temboo? Who is really knowledgable with this?

https://arduino.meta.stackexchange.com/users/84/jfpoilpret
https://stackexchange.com/users/2147199/cormac-driver
Please, any of you kind sirs help me regarding the temboo latest version issue? to be uploaded to arduino-1.8.8\libraries\Temboo?
anyone?

The problem appears to be because you are compiling for the Leonardo. If I compile for the Yun the examples work. If I compile for the Leonardo they fail with the messages you see.

I think the problem is that if you compile for the Yun it assumes a connection through the Yun and works. If you compile for anything else you have to give it details of your internet connection (WiFi shield, Ethernet shield, etc) and work in a completely different way. Since you have a Yun shield you would have to compile it for a Yun. Theoretically there should be no difference between a Yun and a Leonardo + Yun shield.

source: Stack Exchange

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

sort: votes


text:
How to assign text stored in a local file to a string at compile time
I'm developing a program that uses the HTML server in the WiFi101 library.
My hardware does not have SD card storage so all source html needs to be stored as strings in the sketch at compile time.  To aid in development I want to keep my html files separate from the sketch and include them at compile time.
Is there a way to use #include in the Arduino IDE and assign the included file to a string/char array constant?  If so can the path to the included file be relative to the sketch's path?
Notes:
Similar question on Stack overflow:
https://stackoverflow.com/questions/410980/include-a-text-file-in-a-c-program-as-a-char
Edit:
There are lots of great answers here to solve this in a more robust fashion. The correct thing to do is setup a proper build system.  If I were to set this up I'd be temped to try something like Gulp since you could easily minify/lint your web content.
As this is a small project I ended up just running the HTML through a minifier service and copy/pasted into strings.

look at the toneMelody example in the IDE

Check this. Not sure it is easy to adapt that to the Arduino IDE though.

No way for what you want in the Arduino IDE. UECIDE supports it though... - although UECIDE doesn't support the SAMD boards yet.

on SAMD Arduino architecture you could use FlashStorage instead of SD card

This will probably not work with the Arduino IDE. If you are willing to
go through a Makefile-based workflow, you can install this generic
Arduino Makefile, which should make things easier.
With that Makefile installed in /usr/share/arduino/Arduino.mk, the
following test worked on an Arduino Uno. It is based on the objcopy
trick from the article Embedding of binary data into
programs.
Project's Makefile:
BOARD_TAG    = uno
MONITOR_PORT = /dev/ttyACM0
OTHER_OBJS   = text.o

include /usr/share/arduino/Arduino.mk

text.o: text.txt
    avr-objcopy -I binary -O elf32-avr -B avr:5 $< $@

text.txt:
Hello, World!

include-blob.ino
extern "C" const uint8_t _binary_text_txt_start[];
extern "C" const uint8_t _binary_text_txt_size;

void setup() {
    Serial.begin(9600);
    Serial.write(_binary_text_txt_start, (size_t) &_binary_text_txt_size);
}

void loop(){}

The program just prints “Hello, World!”, but if you modify text.txt and
retype make, it will print whatever you had in this file. Please note
that the text is not NUL-terminated, so you have to use the
_binary_*_size symbol to know its size.

I found another way to include a literal file (html, css, or other) and assign it to a constant string without resorting to make files:
Add one line of code on top of your html (css, js, etc) file, and another at the bottom, and save it with an extra .h extension. Then include that file in de Arduino IDE.
This could easily be done by a (manually executed) script, every time those files are changed.
const char *indexHtml = R"====( // added by script
<html> <!-- original .html file -->
.
.
.
</html> <!-- end .html -->
)===="; // added by script

The variable name can be derived from the original filename. The result is saved with an extra .h extension. In the .ino (or .cpp) you can then include this file:
#include index.html.h

This will compile in the Arduino IDE.

C++ has 'raw string literals'. You can put a constant string, without escaping special characters, into the source code between an opening and closing 'tag'. You can choose the tag to be something that is not in the raw string. In following example the tag is =====.
const char* s1 = R"=====(Hello
"World")=====";

is same as
const char* s2 = "Hello\n\"World\"";

This way you can put your large strings into separate .h files and include them. On AVR use PROGMEM to save RAM.

How does that help you include the contents of a file into that string literal?

@Majenko, the h file is The File then.

But the h file isn't the file. The .html file is the file. The OP doesn't want to have to manually convert that .html file into a header file for inclusion (and I can understand that if there are lots of HTML files that he wants to edit often).

@Majenko, this is an option if he doesn't want to use a SD card or other file system

An easy way to do this is to write a C program to convert your files that you want included into your source into a form that looks like:
byte file_001[] = { 0x00, 0x01, 0x02, 0x04, 0x0A, 0x00, 0x01, 0x02, 0x04, 0x0A,
                    0x01, 0x01, 0x02, 0x04, 0x0A, 0x00, 0x01, 0x02, 0x04, 0x0C,

                    ...

                    0x03, 0x01, 0x02, 0x04, 0x0A, 0x00, 0x01, 0x02, 0x04, 0x0C };

The converted file can contain binary data without issue instead of just ASCII.
You can then access the file directly using:   file_001[index]

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


text:
Can a Lithium Polymer battery charging circuit on Arduino boards also charge Lithium Lion batteries?
I have a project that the form factor of 18650 batteries works well for. The board I'm using is a esp32 based board with built in battery charging:
https://www.amazon.com/gp/product/B072HBW53G/ref=ppx_yo_dt_b_asin_title_o00_s02?ie=UTF8&psc=1

I've heard that the flatpack type Lithium Polymer batteries have built in over charge circuitry. Is this generally true?
Can I directly charge a 18650 battery from Arduino type boards that have built in battery charging functionality?

EDIT:  So from looking at the battery circuit schematic from the Wemos link and the board itself it uses a TP4054 "Standalone Linear Li-lon Battery Charger with Thermal Regulation in SOT".  And since I can confirm the board works with 3.7V batteries and my 18650 is a 3.7V type I think I'm good.
EDIT:  Found info on this board:
http://www.raspberrypiwiki.com/index.php/WEMOS_ESP32_Board_with_OLED
Also by "Arduino type" boards I mean any popular micro controller board that has a battery charging function such as the Adafruit feather boards.
EDIT:  To clarify:
Reading here Li Poly and Li Ion batteries are essentially the same
https://scottiestech.info/2015/06/21/lithium-polymer-vs-lithium-ion-batteries-whats-the-deal/
I believe the board is a Wemos D32 with an attached display though I can't find any specific info on this exact board.
https://wiki.wemos.cc/products:d32:d32#technical_specs
I basically want to know if I can charge a Lithium Ion battery with this type of board.  As this is potentially a safety concern I wanted to ask some experts.

The question in your title doesn't match the rest. The title ask about LiPo but the text asks about 18650s which are not LiPo. The answer to the question in your title is not if the built in charger is made for LiPo batteries and has overcharge protection. Can you add links to the actual schematics and specs for your board? My understanding is that LiPo and regulat LiOn charging have different requirements. What do you mean by Arduino type boards? The answers really come down to getting more specs for your board to tell what kind of charging it can do well.

Thanks for the feedback, I changed the title to something hopefully more descriptive and added some info.

I have the Lolin D32 pro, and my understanding of this document on TP4054 http://igotalongdomainname.com/data/uploads/tp4054-42pdf.pdf seems it have overcharge protection at least. Also since it claims it works with 3.7V batteries which is nominal voltage, it should work with the higher than 3.7V actual voltage that 18650 batteries have when fully charged. Also just for the record you can buy charge protection circuit boards for 18650 cells. https://www.youtube.com/watch?v=1rg3ZWxBNUE  Do you have a jst connector to connect your 18650 cell to the board? If you try it, please update the post.

There are Lead based, Nickel-based and Lithium-based batteries (there are actually more, but these ones are the most popular). Each need a different charger, but since lithium polymer and lithium ion are in the same group, it should work but I don't have the option to test it out for you.
Q1: Not every battery has a built in over- and undercharge function. Some do, some don't. To find out if yours does, if the internet can't help, tear it apart (be extremely careful about it).
Q2: Depends what you mean by " built in battery charging functionality". If that includes the over- and undercharge functionality, then it will work (tested).
Looking at the board (https://wiki.wemos.cc/products:d32:d32#technical_specs) it seems doable.
The most important thing is to check, if the supported voltage of the li ion battery equals the supported voltage of the li polymer battery that can be charged with the li polymer charger. Since it says 3.7V on the data sheet, don't get a li ion battery with 3.7V+


text:
Help choosing servo motor for Arduino crane
I'm building an automated Arduino crane where the base material is PVC pipes. The arm consists of the picking mechanism and other sensors, so the total arm might come to about 2-3 Kg (I haven't built it yet).
Can you please suggest to me an appropriate make/model of servo motor which I can purchase (preferably from India only)?

It really depends on where you are placing the servo, how much peak load & at what kind if distance from the servo.
These Corona servos are capable of lifting 2-3Kg at a distance of 2cm from the servo centre. (look at the torque entry on the specification sheet)

Thanks, I actually went ahead using a normal 10 RPM motor and stopped it when an object was detected. It is quite accurate

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


text:
Arduino : distance measurement between fixed points
I am creating a moving robot which needs to know its exact position on the map(known before, start point also known). My ideas were :

GPS : this is not accurate enough for me, does not work indoors
Acc + GYRO + Compass(Magnetometer): MPU-9150 : from that values I could compute the position but as small errors are continuously added after a while it becomes very inaccurate

Finally my idea is to put some fixed points into the area and robot can periodically check where they are and compute its position accurate.
Although I did some googlin' I could not find any appropriate sensor pair to do this. My idea is:

one(more if no other option) sensor on robot covering 360 degrees
few fixed points which sends a signal; each different one - let's say : I am the point one. I am the point two etc.
sensor on a robot is receiving those signals and give me some meaningful value e.g. time from which I can compute the distance from each of the fixed point.
10+ meters maximum range is fine for me
must be cheap (less than 30$ for all)

Questions:

Do you have any idea of such sensor pair ?
Or other solution which would fit to my needs?

Bonus:
* The best would be if the fixed points were passive and just reflected the signal sends from robot - but I have no clue if such a thing exist :-)
Thanks in advance for any answers/comments.

Could you place some black and white pattern on the floor? If so, some photo-reflective sensors on the bottom of the robot could be used to detect where in the no-repeating pattern it is positioned. It could even detect rough orientation.

Seems to me you are looking for some kinda of SLAM thing. Depending on your knowledge in control theory and your precision goals you can go from simple rotary encoders on wheels to multiple sensor fusion like Extended Kalman filters (example videos). Probably the most precise thing you can have is sensor fusion with LIDAR (can be achieved precisions like 1cm), however the price range is way to far from described.
I would start with a small approach and go from there depending on the results I'd get:

rotary encoders (easy to calibrate and can be precise enough as a starting point)
9DOF IMU (use a Extended Kalman filter or similar to make an AHRS correction). And in this part I have many advices. You have suggested MPU-9150. I'm not familiar with it but looking at datasheet it seems very good, specially because gyro comes factory calibrated. In past I've used razor IMU / GY-85 (adlx345 + ITG3200 + HMC5883L) and gyro was very precise and low noise. Hope Invesense used the same sensor in MPU . First in hardware: Acc are easy to calibrate just use gravity. Gyros are easy to calibrate but hard to do. Why, because it may be hard to get something that spins at constant RPM and know that value. But as I've said, according to datasheet, MPU comes factory calibrated. Magnetometers calibration can be a bit tricky. Bottom line is you get readings from various points of your robot  in 3D space. you plot all and you will get an ellipsoid. Then you find a transformation equation that maps the ellipsoid into a perfect sphere take a look this article. Your concerns about Angle random walk can be minimized with kalman filter and similar. This page provides much great information and examples in how to make a good AHRS. Mr. Madgwick wrote a really nice algorithm that implements the IMU  filter and have it also written in C (nice for Arduino).

After integrate all things with Kalman and see the results, if things are not good enough, you can add more sensor and provide a better estimation for example: sonars, rangefinders, landmarks with image processing and as suggested also, RSSI and triangulation.
These links might help you in finding your way:

Introduction to Kalman Filters and SLAM
Indoor Location Tracking using Received Signal Strength Indicator

I've been working on this also, and have not found a 100% satisfactory solution. Some ideas I've been throwing around include:

Using an optical mouse to measure ground distance more accurately. This also subject to cumulative errors.
Some sort of radio transmitters
A pulse from a magnet, with a compass - these can be highly directional, and could possibly be strength-based, too.
I read about one robot competition which had a fixed, overhead camera, picking up infrared LEDs; this is processed by a computer, which would then send the data back (e.g. for bluetooth) to the robot.
The same infrared camera trick, but reversed: a camera pointing up, looking for fixed constelation of infrared LEDs on the ceiling - I would expect this to require more processing than an Arduino has, possibly a raspberry pi could do the trick?

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


text:
To know the state of USB (Serial) connection (connected or not connected)
if (Serial.available()) {
        digitalWrite(7, HIGH);
} else {
        digitalWrite(7, LOW);
}

It doesn't seem to be so simple.
My testing LED turns on when the USB connection with another program is established, but it doesn't turn off (LOW) when that program exits.

Cross posted on Arduino Forum and a second time.

How about having the other program send data to Arduino and Arduino knowing the connection is lost when new data isn't received? I have no idea what Arduino code would do that but just an idea.

That sounds simple enough.
const unsigned long MESSAGE_TIMEOUT = 10UL * 1000;  // 10 seconds

void setup ()
  {
  Serial.begin (115200);
  while (!Serial) ;  // wait for Serial to become active
  Serial.println ("Starting");

  }  // end of setup

unsigned long lastMessage;

void processInput ()
  {
  while (Serial.available ())
    {
    char c = Serial.read ();
    // do something with the data
    }  // end of while loop
  }  // end of processInput

void loop ()
  {
  if (Serial.available ())
    {
    lastMessage = millis ();  // remember when we last got input
    processInput ();  // now handle the input
    }

  if (millis () - lastMessage >= MESSAGE_TIMEOUT)
    {
    // we don't seem to be receiving data
    }

  }  // end of loop

And an issue on the Python side... http://arduino.stackexchange.com/questions/16220/pyserial-serial-write-doesnt-work

The problem here is twofold.
Firstly, on Arduinos that don't have a direct USB connection, (i.e., boards like the Uno, Mega, etc that use a separate chip to manage the USB connection) you have no way of knowing if the USB is open or not.  That information simply isn't there. The main chip just receives UART serial data (not USB data) as it arrives and that is that.
Secondly, even on the boards that have a direct USB connection (Leonardo, etc) there is no proper way to know if the port has been opened or not.  The CDC/ACM protocol simply doesn't have that kind of information (a bit short sighted of them really).  The closest you can do is monitor the DTR and/or RTS signals that are encapsulated in the USB data stream.  It is down to the host operating system (and maybe even your own program) to exert those signals properly, so isn't foolproof even then.
To check the status of those lines in your sketch you can examine the boolean operator of the Serial object:
if (Serial) {
  // I am connected
} else {
  // I am not connected
}

But as I say that can only work on boards like the Leonard - the other indirect boards think they are always connected, since there is no such thing as a connection in UART terminology, only data.

How about having the other program send data to Arduino and Arduino knowing the connection is lost when new data isn't received? I have no idea what Arduino code would do that but just an idea.

That method is known as keepalive.

"method" as in a function, or technique? Any example somewhere?

Technique.  How you do it depends on what you are doing serial-wise at the moment.

I'm lighting a LED when there's a USB connection between a PC program ans Arduino.

That's very interesting. It doesn't give even the slightest hint what you are doing. Ask a new question. Describe your sex al data flow and protocol. Ask how you might best implement a keepalive system in it.

There's no need for a new question. This is a simple question, I need to know the state (connected/not connected) of USB connection between a PC program and Arduino and tell the state by flashing a LED. What more do you want? There's either an answer to the question or there isnt.

I have given you the answer to that. Now you are asking about how to work around the fact that there is no way of knowing. The amount of extra information you will have to provide in order to get an answer to that will change the current question beyond recognition and will invalidate this and any other answer. This is not open to discussion. If you want information about something other than what you asked then you ask another question providing in detail what has been asked for. Comments are for clarification of the existing question not for asking new ones.

There is no way of knowing? Then why did you say "That method is known as keepalive"? when I thought of some way? There either is no way or there is some way. Can you answer that, here or in a new post (which I feel will be marked s dublicate).

That has nothing to do with knowing if it is connected or not - it is merely a method of determining if the connection is alive and working. The two are very different and require completely different ways of thinking. Just ask the new question. I am not discussing this any more.

What is the difference between "connected" and "alive and working"? I'll need to know that to ask the question properly. Maybe I even asked the wrong question to begin with by using the wrong term.

The difference is the difference between "is" and "was". You know the term (keepalive) and what you need to tell us (your existing serial protocol, what your programs do and how that pertains to the serial).

"The difference is the difference between "is" and "was"". That wasnt clear at all...

Go ask the question.


text:
Arduino with seven segment
Can anyone help me regarding the output of this program?
What is the function of Num_Write?
Here is the code below:
int num_array[10][7] = { { 1,1,1,1,1,1,0 }, // 0
{ 0,1,1,0,0,0,0 }, // 1
{ 1,1,0,1,1,0,1 }, // 2
{ 1,1,1,1,0,0,1 }, // 3
{ 0,1,1,0,0,1,1 }, // 4
{ 1,0,1,1,0,1,1 }, // 5
{ 1,0,1,1,1,1,1 }, // 6
{ 1,1,1,0,0,0,0 }, // 7
{ 1,1,1,1,1,1,1 }, // 8
{ 1,1,1,0,0,1,1 }}; // 9

void Num_Write(int);

void setup() {
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
}

void loop() {
  for (int counter = 10; counter > 0; --counter) {
    delay(1000);
    Num_Write(counter-1);
  }
  delay(3000);
}

void Num_Write(int number) {
  int pin= 2;
  for (int j=0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}

The 2 dimensional array is holding the HIGH and LOW signal for each number to display in 7-segment. function "loop" is running through the first dimension to get the number from array, the function "Num_Write" actually is then setting the display segments from the second dimansion of the array. So all is just to display numbers 0 - 9 in a 7-segment display element

Urgh - obviously written by someone that really doesn't have a clue...  140 bytes of RAM to store what could be in 10 bytes of flash...

@FuaZe Const binary patterns is exactly what I use for this kind of thing.

Num_Write will map the output pins to display a number on the 7-segment display.
Please note that the schematic below is not the best, nor the proper way to connect a 7 segment display. It's intended to show the connection for illustrating purposes, not for actual wiring. Each segment lead should have it's own resistor. Also, depending on if you have a Common Anode or Common Cathode 7 segment, wiring will differ.

When the number 0 is being displayed (check in the num_array) all segments are lit, except for the last segment (segment G).
void Num_Write(int number) {                 //Write a number to the 7-segment display.
  int pin= 2;                                //Take the starting (output) pin.
  for (int j=0; j < 7; j++) {                //Loop through all the segments of the given number.
    digitalWrite(pin, num_array[number][j]); //Write the output pin according to the pattern in the "num_array" for the given number.
    pin++;                                   //Go to the next pin.
  }
}

So by looping through the pins, and looping through the array (while setting the pins) we can display a number on the 7 segment display.
Extra:
The output will be somewhat like this, but then reversed (9 to 0) and withouth the A, B, C, D, E and F.

I know you probably didn't draw the schematic there, but you want to watch that resistor usage - a single resistor on the COM pin is very bad - you should mention that in your answer, or find a better schematic.

@Majenko, it does work though? ;D
But yeah, I should add that indeed. It could draw too much power when you light up all segments at the same time? Or basically have different light intensities if you have more or less segments on.

The latter - plus the segments may light up at different intensities. In a worst case scenario you may even get a cascade failure and destroy your LED display.  You need one resistor per segment to set the current through that individual segment.

Yup, also added that there is a difference in common anode and common cathode wiring.

Forgive my newbieness: what's a cascade failure?

@bot3663369 I didn't really know either. Though: https://en.wikipedia.org/wiki/Cascading_failure will be helpfull. I believe he means that if the resistor fails, all the segments won't light either. If you have a resistor for every segment, only the segment connected to the failing resistor won't light up. Or that if one LED fails it might make the others fail somehow.

I think single resistor configuration has its merits too. (1) The power draw will be the same as long as one or more of the segments are lit. This means less power as more segments are lit, but even with 1/7 or 1/8 of the brightness, the difference can still be very subtle depending on the selected resistor value. (2) The parts count is significantly less as the number of digits increase. For example, a 4 digit will require 4 resistors instead of 28/32 resistors. (3) As for the cascading failure: the resistor has to be replaced regardless of how many segments has failed.


text:
Calculate battery (18650 Li-ion) voltage using ESP8266-12E
i am trying to calculate the battery voltage using ESP-12E module. I am using a voltage divider circuit to calculate the same. Here is how my circuit looks like:

And here is how my code looks like:
float volt =0.0;
float temp=0.0;
float r1=320000.0;
float r2=100000.0;

void setup(){
    Serial.begin(115200);
    Serial.println(String(VoltageCalculator()).c_str());
}

float VoltageCalculator(){
  for (int thisReading = 0; thisReading < numReadings; thisReading++) {
    readings[thisReading] = 0;
  }
  Serial.println(analogRead(A0));
  for(int i = 0;i<=10; i++){
    total = total - readings[readIndex];
    // read from the sensor:
    readings[readIndex] = analogRead(A0);
    // add the reading to the total:
    total = total + readings[readIndex];
    // advance to the next position in the array:
    readIndex = readIndex + 1;

    // if we're at the end of the array...
    if (readIndex >= numReadings) {
      // ...wrap around to the beginning:
      readIndex = 0;
    }

    // calculate the average:
    float analogvalue = total / numReadings;

    //  int analogvalue = analogRead(A0);
    temp = (analogvalue * 3.3) / 1024.0;
    volt = temp / (r2/(r1+r2));
  }

  if(DEBUG_ENABLE){
    Serial.println();
    Serial.print("Actual Voltage : ");
    Serial.print(volt);
    Serial.println();
  }

  float volt_percent;

  if(volt == 3.1){
    volt_percent = 0;
  } else{
    float volt_diff = volt - 3.1;
    volt_percent = (volt_diff/1.1)*100;
    if(DEBUG_ENABLE){
      Serial.println();
      Serial.print("Voltage percentage : ");
      Serial.print(volt_percent);
      Serial.println();
    }
  }
  return volt_percent;
}

When i use this circuit with NodeMCU it works very fine, but when it comes to ESP-12E module it do not show the proper voltage. on Serial.println(analogRead(A0)); always shows 1024.
Any suggestions why this is happening and how can i do this to achieve the most accurate value?

Everything was correct and my circuit is also good. The only difference i found is to this below line:
temp = (analogvalue * 3.3) / 1024.0;
Which should be
temp = (analogvalue * 1.0) / 1024.0;
We are multiplying because we are referencing the voltage from voltage divider circuit as 1 volt.
After doing this, i am getting the exact values battery voltage which then i convert to percentage.
Thank you!


text:
Send data from one NodeMCU to another NodeMCU using Serial Communication
i am using NodeMCU (ESP8266) to communicate with another NodeMCU (ESP8266) using Serial Communication. Because i am using ESP-NOW to communicate and ESP-NOW and WiFi can not work together very well so trying with this serial communication option.
Here is how i connected the pins:
   Slave ->   Master
    D1    ->   D2
    D2    ->   D1
    GND   ->   GND

Here is how my sketch looks like:
Sender.ino
#include <Wire.h>

void setup() {
  Serial.begin(115200);
  Wire.begin(D1, D2); /* join i2c bus with SDA=D1 and SCL=D2 of NodeMCU */
}

void loop() {
  // put your main code here, to run repeatedly:
   Wire.beginTransmission(5); /* begin with device address 8 */
   Wire.write("Hello ESP 2");  /* sends hello string */
   Wire.endTransmission();    /* stop transmitting */

   Wire.requestFrom(5, 4); /* request & read data of size 13 from slave */
   while(Wire.available()){
      char c = Wire.read();
    Serial.print(c);
   }
   Serial.println();
   delay(1000);
}

Receiver.ino
#include <Wire.h>

void setup() {
 Wire.begin(5);
 Wire.onReceive(receiveEvent); /* register receive event */
 Serial.begin(115200);           /* start serial for debug */
}

void loop() {
 delay(100);
}

// function that executes whenever data is received from master
void receiveEvent(int howMany) {
 while (0 <Wire.available()) {
    char c = Wire.read();      /* receive byte as a character */
    Serial.print(c);           /* print the character */
  }
 Serial.println();             /* to newline */
}

But the communication is not working at all, not sure where i am wrong. It can code wise or may be via connection wise or it might be possible that NodeMCU to NodeMCU connection is not possible at all!
Thank you!

Your code does not reflect your hardware setup. I2C (Wire) communication over SDA/SCL pins is not the same as serial communication over crossed RX/TX pins. First you should decide what you really want. Serial communication or I2C. Then search the internet for examples. As you already use Serial for debugging (SerialMonitor?), you might want to use I2C to connect the two ESPs together. But that's not that easy, I2C uses a special electrical trasmission mode. You can not simply connect the  pin pairs crossed to each other. You also must not use the same address for both devices.

You also used Wire.begin(D2,D3) for Sender and  Wire.begin(5) for Receiver. I suspect that's wrong.

@Juraj actually i have send send data to my MQTT server connected in my LAN network. Which need wifi access and with ESP-NOW i can not do both.

@Peter can you suggest how can i fix this?

esp8266 Wire library doesn't work as slave

@Juraj Ohk so i want to send data from one nodemcu to another, with wired connection how can i do that! Any suggestions?

use only one esp8266 if they are so close to each other

@Juraj The problem seems to be, that the OP wants to use ESP-Now, which from the description sounds like a different 2.4GHz protocol by espressif, that also uses the Wifi hardware. So the first NodeMCU cannot connect to the Wifi network, since its already occupied by the ESP-Now protocol.

@chrisl, thank you. now I understand. the solution is to use only WiFi

As already stated, your code uses the I2C interface (via the Wire library) and not the Serial interface (which is an Arduino term for UART). They work fundamentally different.
As you only communicate between 2 devices, which you both can program yourself. I would ditch the I2C interface. It doesn't give you any advantage here, but some disadvantages (for example, that you can't have real bidirectional communication, as the slave cannot do anything by its own, only, if the master asks for it).
Instead you should use a Serial (UART) interface. As the NodeMCU only has 1 full hardware Serial interface, which you already use for debugging, you could use the ESPSoftwareSerial library to create an extra Serial interface via software. It has limitations (in how many interfaces can listen at a time and how fast the communication can go), but most likely this will solve your problem. Also Serial is easier for beginners, than I2C.

So can you please suggest what is much better to process faster and easy to do communication two way?

Also is there any example you can suggest with code and wire diagram for nodemcu to nodemcu so i can have better understanding


text:
Arduino MEGA - How to send and receive data asynchronously?
i am newbie to this so i hope i can explain my problem clearly;
Arduino MEGA connected to PC via USB port.
I am using an encoder to trigger function to send data to pc, data is a simple string "A01" or "A02" when i turn encoder to opposite direction, when arduino sends that string to serial port PC answers with another string from serial and its something like "MCPHDGxxx" and arduino does if serial available gets the string and filter it to get and show that number on my 7-segment display.
(xxx is a number between 000 and 359, and that number changes on PC screen when arduino send "A01" or "A02" string to PC)
When i don't send display data from PC to arduino, encoder function works as intended, changes numbers up and down rapidly on PC screen but when i try to send that "number" data to Arduino from serial port number on the PC screen changes so slowly like 1 point up/down per 2 sec even if i turn encoder continuously. Seems like receiving data from PC blocking my send data function until it's done.
Is it possible to make it work asynchronously?
Here is my sketch:
#include "DigitLedDisplay.h"
 #define outputA 24
 #define outputB 25

 int aState;
 int aLastState;
 unsigned long lastButtonPress = 0;
 long finalMCPHDGLong;
 String ReceivedSerialString;

 DigitLedDisplay ld = DigitLedDisplay(21, 22, 23);

 void setup() {
   pinMode (outputA,INPUT);
   pinMode (outputB,INPUT);

   Serial.begin (115200);
   // Reads the initial state of the outputA
   aLastState = digitalRead(outputA);

     /* Set the brightness min:1, max:15 */
  ld.setBright(10);

  /* Set the digit count */
  ld.setDigitLimit(8);

 }

 void loop() {
   aState = digitalRead(outputA); // Reads the "current" state of the outputA
   // If the previous and the current state of the outputA are different, that means a Pulse has occured
   if (aState != aLastState){
     // If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
     if (digitalRead(outputB) != aState) {
       if (millis() - lastButtonPress > 25) {
         Serial.println("A01");
        }

        // Remember last button press event
        lastButtonPress = millis();

     } else {
       if (millis() - lastButtonPress > 25) {
         Serial.println("A02");
        }

        // Remember last button press event
          lastButtonPress = millis();

     }

   }
   aLastState = aState;

    while (Serial.available() > 0){
      ReceivedSerialString = Serial.readString();
      if (ReceivedSerialString.substring(0,6) == "MCPHDG"){
        String value = ReceivedSerialString.substring(6,9);
          long val = value.toInt();
          finalMCPHDGLong = val;
          if((finalMCPHDGLong <= 99)){
              ld.printDigit(0,7);
            }if((finalMCPHDGLong <= 9)){
              ld.printDigit(0,6);
            }
          ld.printDigit(val, 5);
      }
    }
 }

Seems like receiving data from PC blocking my send data function until it's done.

You may be saying the same thing, but I'd put it that it's waiting for more data to arrive that isn't going to.

Is it possible to make it work asynchronously?

Depending on how you're defining "asynchronously" that may be unnecessary.
while (Serial.available() > 0){
  if (ReceivedSerialString.substring(0,6) == "MCPHDG"){
    String value = ReceivedSerialString.substring(6,9);

There's a lot that could be said about using String and conversion to int and choosing a simple message format and so forth, but I'll elide most of that. Finding a good approach to what you're doing would require understanding a lot more about what you're doing and why. But, taking your code and question as written, the main thing is that readString() here is terminating based on the value of Serial.setTimeout(), which by default is 1000 or 1 second.  So you are spending a lot of time doing nothing following receipt of your command from the PC. So during that 1 second you are not tending to the "encoder".
You could play with setTimeout, but it would be better to avoid a timeout altogether by not attempting to read when there's no more command to be read. If this protocol you're using is line-oriented then you have a terminator you can use in the form of '\r' or '\n'. This can be done with Serial.readStringUntil(whatever_your_terminator_is); If you have both '\r' and '\n' you will need to read other part of the termination sequence and then throw it away. Either it will come in as part of the read string or it will not and you will need to do a second read to discard it. There are more sophisticated ways to go about this, but that maybe sufficient for what you're doing.
When it comes to not blocking (or significant blocking) of serial reads, you have to assure that the data is there to be read. Either because you know it's sent (and are willing to trust that it was received okay). Or you use Serial.setTimeout with a 0 or sufficiently small number, .read() indicates no data with a negative return value, or by checking .available(), and it all of these cases deciding what to do when you have not received everything, or everything... yet. Doing it well, manually, is a bit of a pain.
For writing/printing to serial there's a counterpart .availableForWrite() which
you can use to determine ahead of time whether or not you're going to be stuck in waiting (in .print()/.println()/.write()) for the serial data to go out, in turn not tending to the encoder. Basically you can choose where and how to throttle your writing to serial so as not overly interfere checking the encoder rather than causing throttle to happen within Serial.write. With the way your code is currently written, with events coming in at the rate they apparently are (according to your debouncing code) this is probably not currently a problem for you. But it's worth keeping in mind if you begin handling events at a higher rate. Placing a character in the outbound serial buffer is significantly faster than waiting for space for a character to become available in the serial buffer.

Serial.setTimeout(25) solved the problem. Also other advices helped a lot, thanks.

Is not easy, but you can implement two modification.
The first one is handling encoder via interrupt, the second one, is change the while to an if, with the while you force the code to loop inside the while serial aviable loosing eventually encoders state change, to avoid this, you shuold take continusly the strings coming from PC and create a command queue and proces it cycle by cicle, unfortunatly arduino mega is single processor, so it can't handle different process at the same time.
You should olso to consider, and run a benckmark to test how much is the refresh rate of your display


text:
Arduino Leonardo on Win 8.1 COM port disappeared
I've been using an Arduino Leonardo on my Windows machine for a few days now without too much trouble but today the COM port disappeared. I've been able to successfully send sketches to the arduino and execute them so everything was working until recently. When I look in Device manager on the control panel there is no com port listed for the arduino. If I reset the device then a com port shows up briefly with "Arduino Leonardo BootLoader" but after a few seconds that disappears. I've tried USB2.0 and USB 3.0 ports on my PC and a different cable but to no avail. I don't have anything listed under "Other Devices" and I'm out of ideas for what could be the trouble.
I'm trying to get it recognised now as just the leonardo with nothing connected to any pin. Any ideas of what to try?

Strange, it's resolved itself/I resolved it. I don't know whether what I did was actually responsible for solving this but I'm back in business:
* I reset the board so that the bootloader appeared as a com port
* I set the arduino IDE to use the port that appeared for the bootloader
* I uploaded a simple sketch and pressed reset during the "upload phase" so that the port appeared during the upload
* the upload completed successfully and the arduino was back in the com port list
I'd still be interested to understand what I did that caused the problem in the first place but I suppose something was corrupted on the board?

Probably you had a sketck witch was messing with serial, like you forgot Serial.begin() or the while needed by it, also this reset is needed on the uno when write too much on serial.

You could be right. I have a button press to trigger some actions and I'd been monitoring the button status using a serial write. It could be I was hammering that method call or had messed something up around the serial comms.


text:
What bytes do I send to the MAX7221 to light an LED (in an led Matrix)?
Datasheets

LED Matrix (p2): https://www.circuitspecialists.com/products/pdf/M105057CHR1.pdf
MAX7221: https://www.sparkfun.com/datasheets/Components/General/COM-09622-MAX7219-MAX7221.pdf

Convention

(Row, Col) Designates an LED at a particular row and column, following the convention set by the datasheet
{Anode, Cathode} Designates a anode/cathode pair to light an LED in the array
Assume that I've connected:
SEG_DP to pin 13
SEG_A to 3
SEG_B to 11
SEG_C to 10
SEG_D to 6
DIG_0 to 9
DIG_1 to 14
...
DIG_6 to 2

Question:
Suppose I'm interested in lighting (1,1). By the convention, I would have to source current to pin 13 and sink current from pin 9. What two bytes should I send to the MAX7221 to achieve this?
My Attempt:
I think it should be 0x01 and 0x80 (0000|0001|1000|0000) with MSB (D15 as it is referred to in the datasheet for MAX7221) on the far left. Code I tried using is below as an image. I checked the signals with a logic analyzer and verified that the SPI protocol was followed (I forgot to take a screenshot but I will provide one when I get a chance). The LED array did not behave as I had anticipated. All LEDs in the matrix were lit!

What about using a library? http://playground.arduino.cc/Main/LEDMatrix has a few. Even if you prefer to write your own code you should be able to find a few hints there.

Add a delay after setting the SS low. Also specify try adding PI.setDataMode(SPI_MODE0); and/or SPI.setClockDivider(SPI_CLOCK_DIV8);

can you explain the clock divider function? For reference, the MAX runs at 10Mhz and the MCU that I'm using (Arduino Uno) runs at 16Mhz


text:
Combine Code Arduino GSM Shield and Adafruit GPS Shield
I have a problem to combine both code for Arduino GSM Shield and Adafruit Ultime GPS Shield. I already change my code to the basic one like examples. I think i found the problem. The problem is when i want to do get request to the url/web.
Here is the link to the Adafruit Ultimate GPS Shield.
Adafruit Library
Adafruit Ultimate GPS Shield Info
My code base on example of Arduino GSM Library (GSM Web Client) and Adafruit GPS Library (Parsing)
This is the code that make my code not working. If i put the code i do not receive any data at serial.

 // if you get a connection, report back via serial:
 if (client.connect(server, port))
 {
    Serial.println("connected");
   // Make a HTTP request:
   client.print("GET ");
   client.print(path);
   client.println(" HTTP/1.1");
   client.print("Host: ");
   client.println(server);
   client.println("Connection: close");
   client.println();
 }
 else
 {
  // if you didn't get a connection to the server:
  Serial.println("connection failed");
 }

This is the basic code that working so far

// ********************************************
//   GPS Library
// ********************************************
#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>
#include <stdlib.h>

// ********************************************
//   GSM Library
// ********************************************
#include <GSM.h>

// ********************************************
//   Sim Card Pin Number if available
// ********************************************
#define PINNUMBER ""

// ********************************************
//   Set Up APN data for GPRS Connection
// ********************************************
#define GPRS_APN       "Maxis" // replace your GPRS APN
#define GPRS_LOGIN     "maxis"    // replace with your GPRS login
#define GPRS_PASSWORD  "wap" // replace with your GPRS password

// ********************************************
//   Initialize GSM Library
// ********************************************
GSMClient client;
GPRS gprs;
GSM gsmAccess;

// ********************************************
//   Setup Arduino to browse URL/web through GPRS
//   The code below will setup path like:
//   http://arella.com.my/urltomysql.php?firstname=Muhammad&lastname=Faiz
//   When Arduino browse the web, it will submit firstname:Muhammad
//   and lastname:Faiz into database. I want to store GPS data into database       later
// ********************************************
char server[] = "arella.com.my";
char path[] = "/urltomysql.php?firstname=Muhammad&lastname=Faiz";
int port = 80; // port 80 is the default for HTTP

// ********************************************
//  Set Adafruit GPS to use software serial on pin
//  D9 & D10 on Arduino. Use Jumper Wire from D7,D8 to D9,D10
// ********************************************
SoftwareSerial mySerial(10, 9);
Adafruit_GPS GPS(&mySerial);

// Set GPSECHO to 'false' to turn off echoing the GPS data to the Serial console
// Set to 'true' if you want to debug and listen to the raw GPS sentences.
#define GPSECHO  false

// this keeps track of whether we're using the interrupt
// off by default!
boolean usingInterrupt = false;
void useInterrupt(boolean); // Func prototype keeps Arduino 0023 happy

//***********************************************
// convert NMEA GPS Format to Google Map Format
//***********************************************
int degLatInt, degLongInt;
float minLatFloat, minLongFloat, googleMapsLat, googleMapsLong;
char* lat_str = new char[10];
char* long_str = new char[10];
char degLatString[5], degLongString[5];

void setup()
{
   Serial.begin(115200);
   gsmAccess.begin(PINNUMBER);
   gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD);

   boolean notConnected = true;
   while(notConnected)
   {
      if((gsmAccess.begin(PINNUMBER)==GSM_READY) &
         (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))
         notConnected = false;
      else
      {
         Serial.println("Not connected");
         delay(1000);
      }
   }
   // If i enable the code below, my code not working.
   /* if (client.connect(server, port))
      {
      Serial.println("connected");
      // Make a HTTP request:
      client.print("GET ");
      client.print(path);
      client.println(" HTTP/1.1");
      client.print("Host: ");
      client.println(server);
      client.println("Connection: close");
      client.println();
  } */

 //***********************************************
 // Setup Adafruit GPS Shield
 //***********************************************
 // connect at 115200 so we can read the GPS fast enough and echo without  dropping chars
 // also spit it out

 Serial.println("Adafruit GPS library basic test!");

 // 9600 NMEA is the default baud rate for Adafruit MTK GPS's- some use 4800
 GPS.begin(9600);

 // uncomment this line to turn on RMC (recommended minimum) and GGA (fix     data) including altitude
 GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
 // uncomment this line to turn on only the "minimum recommended" data
 //GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCONLY);
 // For parsing data, we don't suggest using anything but either RMC only or RMC+GGA since
 // the parser doesn't care about other sentences at this time

 // Set the update rate
 GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);   // 1 Hz update rate
 // For the parsing code to work nicely and have time to sort thru the data, and
 // print it out we don't suggest using anything higher than 1 Hz

 // Request updates on antenna status, comment out to keep quiet
 GPS.sendCommand(PGCMD_ANTENNA);

 // the nice thing about this code is you can have a timer0 interrupt go off
 // every 1 millisecond, and read data from the GPS for you. that makes the
 // loop code a heck of a lot easier!
 useInterrupt(true);

   delay(1000);
}

// Interrupt is called once a millisecond, looks for any new GPS data, and stores it
SIGNAL(TIMER0_COMPA_vect) {
   char c = GPS.read();
   // if you want to debug, this is a good time to do it!
   #ifdef UDR0
   if (GPSECHO)
   if (c) UDR0 = c;
   // writing direct to UDR0 is much much faster than Serial.print
   // but only one character can be written at a time.
   #endif
}

void useInterrupt(boolean v) {
   if (v)
   {
      // Timer0 is already used for millis() - we'll just interrupt somewhere
      // in the middle and call the "Compare A" function above
      OCR0A = 0xAF;
      TIMSK0 |= _BV(OCIE0A);
      usingInterrupt = true;
   } else
   {
      // do not call the interrupt function COMPA anymore
      TIMSK0 &= ~_BV(OCIE0A);
      usingInterrupt = false;
   }
}

uint32_t timer = millis();

void loop()                     // run over and over again
{
   // if a sentence is received, we can check the checksum, parse it...
   if (GPS.newNMEAreceived()) {
   // a tricky thing here is if we print the NMEA sentence, or data
   // we end up not listening and catching other sentences!
   // so be very wary if using OUTPUT_ALLDATA and trytng to print out data
   //Serial.println(GPS.lastNMEA());   // this also sets the newNMEAreceived()  flag to false

   if (!GPS.parse(GPS.lastNMEA()))   // this also sets the newNMEAreceived() flag  to false
      return;  // we can fail to parse a sentence in which case we should just wait for another
   }

   // if millis() or timer wraps around, we'll just reset it
   if (timer > millis())  timer = millis();
   // approximately every 2 seconds or so, print out the current stats
   if (millis() - timer > 5000) {
      timer = millis(); // reset the timer

      Serial.print("\nTime: ");
      Serial.print(GPS.hour+8, DEC); Serial.print(':');
      Serial.print(GPS.minute, DEC); Serial.print(':');
      Serial.print(GPS.seconds, DEC); Serial.print('.');
      Serial.println(GPS.milliseconds);
      Serial.print("Date: ");
      Serial.print(GPS.day, DEC); Serial.print('/');
      Serial.print(GPS.month, DEC); Serial.print("/20");
      Serial.println(GPS.year, DEC);
      Serial.print("Fix: "); Serial.print((int)GPS.fix);
      Serial.print(" quality: "); Serial.println((int)GPS.fixquality);
      if (GPS.fix) {
         /////////// Latitude /////////////
         // Convert NMEA Latitude to String
         dtostrf(GPS.latitude, 7, 4, lat_str); //convert GPS.latitude from float to String. 7 - means 8 characters long ; 4 - means 4 decimal point

         // Get Degree substring from latitude String
        strncpy(degLatString, lat_str, 1); // Get Degree from Full Latitude String. Example 311.7799 - Get 3

        // Get Minutes substring from latitude String
        char* minLatString = lat_str + 1; // Move pointer up 1 position. Example 311.7799 will move to 11.7799

        // Convert Deg String to int
        degLatInt = atoi(degLatString);

        // COnvert Min String to float
        minLatFloat = atof(minLatString);

        //Convert NMEA latitude to Google Maps latitude
        googleMapsLat = degLatInt + (minLatFloat / 60);
        Serial.print("Google Map Latitude: ");
        Serial.println(googleMapsLat, 4);

        //////////// Longitude /////////////
        // Convert NMEA Longitude to String
        dtostrf(GPS.longitude, 8, 4, long_str); //convert GPS.latitude from float to String. 8 - means 9 characters long ; 4 - means 4 decimal point

        // Get Degree substring from latitude String
        strncpy(degLongString, long_str, 3); // Get Degree from Full Latitude String. Example 10141.91699 - Get 141

        // Get Minutes substring from latitude String
        char* minLongString = long_str + 3; // Move pointer up 3 position. Example 10141.9169 will move to 41.7799

        // Convert Deg String to int
        degLongInt = atoi(degLongString);

        // COnvert Min String to float
        minLongFloat = atof(minLongString);

        //Convert NMEA latitude to Google Maps latitude
        googleMapsLong = degLongInt + (minLongFloat / 60);
        Serial.print("Google Map Longitude: ");
        Serial.println(googleMapsLong, 4);

        Serial.print("Speed (KM): "); Serial.println(GPS.speed * 1.85);
      }
   }
}

I'm working on the same project (with the same hardware) and I have an identical problem.
Seems like an HTTP request blows up your serial monitor, but is not true in my view.
In fact, if you use the TinyGPS++ library will not have this problem anymore.
Take as reference the GsmWebClient example, you can add a few lines of code.
This is all you need for parse with tinyGPS:
#include <AltSoftSerial.h>

#include <TinyGPS++.h>

TinyGPSPlus gps;

AltSoftSerial ss;

//Add this to your sketch, in loop() or setup()

ss.begin(9600);

while (ss.available() > 0)

    if (gps.encode(ss.read())) {
        gps.location.lat(); //return latitude as a double
        gps.location.lng(); //return longitude as a double
}

Does that code fix the issue?

Thanks penguin for editing!
This is not a real fix for the error, it's a bypass.. I think the problem is given by AdafruiGPS lib, and everything is solved using TinyGPS. This code is all you need for get the coordinates with the new library.


text:
Arduino ADC read bad value
I have an Arduino device and I'm trying to read two voltages. The first one is the Arduino Vcc by using the bandgap value 1.1V (this requires raw access to registers since it's not implemented in analogRead). The other one is checking the battery voltage using the badgap as a reference. I want both of them because I'm doing a study on the battery life when using a step-up converter.
I'm using these pieces of code:
// Read bandgap with Vcc as reference - this will give use the Vcc
ADMUX = DEFAULT << 6 | 14;
delayMicroseconds(250);
bitSet(ADCSRA, ADSC);
while(bit_is_set(ADCSRA, ADSC))
    ;
word x = ADC;
Serial.println(x);

// Read A1 with 1.1V bandgap as reference - this will give battery voltage
ADMUX = INTERNAL << 6 | 1;
delayMicroseconds(250);
bitSet(ADCSRA, ADSC);
while(bit_is_set(ADCSRA, ADSC))
    ;
word x = ADC;
Serial.println(x);

The problem that I have is that separately they seem to work well, however when using them together the first piece of code ruins the reading for the second one. The culprit is the line ADMUX = DEFAULT << 6 | 14. This sets up the default reference (chip voltage) and reads channel 14 (which is the 1.1V). I can't figure out why after using this line changing back with ADMUX = INTERNAL << 6 | 1 doesn't work.

Did you try taking the reading twice? The datasheet says: “The first ADC conversion result after switching reference voltage source may be inaccurate, and the user is advised to discard this result.”

Yes, I ran them in a loop and get consistent results. The first one read correctly, but then the second one won't work. If the first one is commented, the second one works OK.

Actually you are right, I didn't understand your comment clearly the first time. I loop both reads one after another so it doesn't help. Looping the second one gets to the right value after a while (~5 ms) so I need to read once then wait 5 ms and read again. Please put your comment in an answer so I can accept it.

The datasheet says:

The first ADC conversion result after switching reference voltage
  source may be inaccurate, and the user is advised to discard this
  result.

Then you could try to take each reading twice, looping over four ADC
readings:

Read bandgap with Vcc as reference, discard the value.
Re-take the same, keep the value.
Read A1 with 1.1V bandgap as reference, discard the value.
Re-take the same, keep the value.

I also want to add this as reference - I found some more info in this thread: http://forum.arduino.cc/index.php?topic=22922.0 which confirmed my suspicion that the Aref capacitor discharge time might be messing up with the reads. They got values very close to my 5 ms wait time.


text:
How to count steps of a stepper motor with AccelStepper?
I want to turn on my motor and count how many total rounds it has until my limit switch is switched on. After that, I want to count rounds counterclockwise until another limit switch is pushed. For this, I'm using AccelStepper and ezButton lib.
Here is my code:
      if ((limitSwitch_XV.getState() == LOW) && (limitSwitch_XE.getState() == LOW) && rightDirectionX) {
        while (1) {
          stepper1.step(-1);
          stageSizeX++;
        }
      }

But here I've got an error which says that I can't use int in step(): 'virtual void AccelStepper::step(long int)' is protected within this context stepper1.step(1);
So how can I count the steps and go step by step to the given direction until I reach the limit switch with AccelStepper?

Why do you need to control every step yourself? You could also set it to a specific speed, and then in a loop call stepper1.run() and also check for the limit switch. As soon as the limit switch is activated you can stop the motor and read out the position. The difference in position between before and after is the number of steps traveled.

can you give me an example for it?

and also how can I change the direction then?

You get that error, because the step() method is protected in the AccelStepper class. It is not meant for calling by the user. AccelStepper instead wants you to state, what kind of movement you want (moving a specific distance/to a specific point/with a specific speed) and then frequently call the AccelStepper.run() method (or AccelStepper.runSpeed()), which will then execute the steps, when it is time to do so based on your planned movement.

If you want to solve your problem you have basically two ways to do this:

With AccelStepper: Set the stepper to run at a specific speed in the correct direction, then in a loop calling stepper1.runSpped() and testing your limitswitch with digitalRead(). So something along the lines of:
  stepper1.setCurrentPosition(0);
  stepper1.setSpeed(20); // Change speed according to your needs, negative values let the motor rotate in the other direction
  while(limitSwitch_XV.getState() == HIGH){ // Assuming, that limit switch is not pressed when HIGH
      stepper1.runSpeed();
  }
  int revolutions = stepper1.currentPosition() / steps_per_revolution;

or without AccelStepper: Depending on your stepper driver you can use a less sophisticated stepper library (like Arduinos Stepper library) or just control the stepper directly with digitalWrite() calls (to the Dir pin and to the Pulse pin). In that case you can do each step yourself, after each checking for the limit switch with digitalRead(). Something along the lines (I assume a stepper driver with dir pin and pulse pin, not one with multiple phase pins):
  digitalWrite(dir_pin, direction); // provide HIGH or LOW here depending on wanted direction
  int pos = 0;
  while(limitSwitch_XV.getState() == HIGH){
      digitalWrite(pulse_pin, HIGH);
      delayMicroseconds(10);
      digitalWrite(pulse_pin, LOW);
      pos++;
      delayMicroseconds(50); // Change this value according to the wanted speed
  }
  int revolutions = pos / steps_per_revolution;

Note, that both code snippets are totally untested and you need to build the surrounding code yourself. They only highlight the principle.

What is here steps_per_revolution?

You wanted to know the number of revolutions until you hit the limit switch. For converting traveled steps to number of revolutions you need the number of steps per revolution. That's a value, that is specific to your motor and driver configuration.


text:
I need help with creating a menu using u8g2 library
I want to make a project with a (Nokia 5110) display using u8g2 library.
Here I have the code for my program:
#include <Arduino.h>
#include <U8g2lib.h>
#include <TM1637Display.h>
#include <EEPROM.h>

#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif

#define LED_PIN 5
#define BUTTON_PIN 6
#define BUZZ_PIN 7
#define BUTTON_L 2
#define BUTTON_R 3
#define BUTTON_START 4

//48x84 disp.
U8G2_PCD8544_84X48_F_4W_SW_SPI u8g2(U8G2_R2, 13, 11, 10, 12, 8); //rotate, clk, DIN, CE, DC, RST //

byte lastButtonState = 0;
byte ledState;
float cpu_gauge = 0.0;
char buffer[40];
int move = 7;
float cpu_gauge_step = 0.5;
byte eeprom_led;

void set_led(){
  if( digitalRead(LED_PIN) == 1 ) ledState = 1;
      if( digitalRead(LED_PIN) == 0 ) ledState = 0;}

void backlight(){
byte buttonState = digitalRead(BUTTON_PIN);  //monitor button state
  if (buttonState != lastButtonState) {  //check if not equal
    lastButtonState = buttonState;       //if prev. true, make equal
      if (buttonState == HIGH) {
        ledState = (ledState == HIGH) ? LOW : HIGH;
          digitalWrite(LED_PIN, ledState);    }}}

void status_bar(){
  if (cpu_gauge > cpu_gauge_step*1) u8g2.drawBox(2,13,6,8); //x, y , size in x, size in y
    if (cpu_gauge > cpu_gauge_step*2) u8g2.drawBox(2 + 1*move,13,6,8);
      if (cpu_gauge > cpu_gauge_step*3) u8g2.drawBox(2 + 2*move,13,6,8);
        if (cpu_gauge > cpu_gauge_step*4) u8g2.drawBox(2 + 3*move,13,6,8);
          if (cpu_gauge > cpu_gauge_step*5) u8g2.drawBox(2 + 4*move,13,6,8);
            if (cpu_gauge > cpu_gauge_step*6) u8g2.drawBox(2 + 5*move,13,6,8);
              if (cpu_gauge > cpu_gauge_step*7) u8g2.drawBox(2 + 6*move,13,6,8);
                if (cpu_gauge > cpu_gauge_step*8) u8g2.drawBox(2 + 7*move,13,6,8);
                  if (cpu_gauge > cpu_gauge_step*9) u8g2.drawBox(2 + 8*move,13,6,8);
                    if (cpu_gauge >= cpu_gauge_step*10) u8g2.drawBox(2 + 9*move,13,6,8);
}

void setup(void) {
  pinMode(LED_PIN, OUTPUT);
    pinMode(BUTTON_PIN, INPUT);
      pinMode(BUZZ_PIN, OUTPUT);
       pinMode(BUTTON_L, INPUT);
        pinMode(BUTTON_R, INPUT);
          pinMode(A7, INPUT);
            pinMode(BUTTON_START, INPUT);
              eeprom_led = EEPROM.read(0);
                digitalWrite(LED_PIN, eeprom_led);
                  set_led(); //sets the led state to 1 or 0 depending on digital write
            Serial.begin(9600);
            u8g2.begin();

}

void loop(void) {

    EEPROM.update(0,ledState);
    /*pomiar = EEPROM[ 0 ];
    delay(2500);//
    Serial.println(pomiar);//
    Serial.println(cpu_gauge);
    int pomiar = digitalRead(BUTTON_START);
    Serial.println(pomiar);*/

  backlight();
  cpu_gauge = analogRead(A7) * (5.0/1022);

  u8g2.firstPage();
  do {
  u8g2.drawRFrame(0,12,74,10,3); //pos X,Y  length, width, corner
  status_bar();

  u8g2.setFont(u8g2_font_busdisplay8x5_tr);
    u8g2.setCursor(0,8);
      char pomiar_str[5];
        dtostrf(cpu_gauge,0,2, pomiar_str);
          sprintf(buffer, "LOAD: %sV", pomiar_str);
            u8g2.print(buffer);

  u8g2.setCursor(0,36);
    u8g2.print("bckgrnd_tsks:");
      u8g2.setCursor(48,48);
        sprintf(buffer, "led: %d", ledState);
          u8g2.print(buffer);
            u8g2.drawStr(0,48,"buzz:");

  if (cpu_gauge > 4.80){
    digitalWrite(7,1);
      u8g2.setCursor(0,48);
        u8g2.setFont(u8g2_font_busdisplay8x5_tr);
          u8g2.setFont(u8g2_font_open_iconic_play_1x_t);
          u8g2.drawGlyph(27, 48, 0x0040);}
  else
    digitalWrite(7,0);

  } while ( u8g2.nextPage() );}

I have succesfully made a program, that:
-Has a pushbutton, to turn off, and on the backlight with each press
-Writes to the EEPROM the state of the LED, and reads it at startup
-Displays an analogRead value, from the potentiometer and also displays a progress bar of the given value
-Displays the state of the backlight
-Turns on the buzzer, if the analogRead value exceedes some value
-Displays an indicator, if the buzzer is turned on
Now, let's assume that what this program does, is called option "A", and A in this example works all the time, because there is nothing else.
I want to create a menu, that would have option A, B, C, D. Assume that formatting and pushbutton actions, doesn't matter for now.
A: Is what was described before.
B: Clock. Just display a clock.
C: Stopwatch.
D: Setting the time.
I see two ways of creating such menu.
1: Is to build a selectable/scrollable menu that would have labels, and by choosing, and pressing a button, we would enter desired function.
2: Ditch the selectable menu. One pushbutton will switch from option A to D. Something like a casio watch.
I'd prefer the second option, I think it'll be easier to do
What I don't understand, is the U8G2 reference manual.
I don't really understand the concept of the buffer, sendBuffer, userInterfaceSelectionList, and some more stuff, that I can't name for now.
My understanding is, that i have to make some array, of functions.
Like:
Array [] = {default_display();, clock();, stopwatch();, setting();)

And with a button, I'd go thru this array like so:
Array = 0;
 If (digitalRead(some_button_pin) == High){
  Array + 1;}
If (Array > 3){
 Array = 0;}

And in those funtions, it would have implemented options, like the backlight turned on, or something else, whatever,
Now I don't know if that makes any sense. If it's transferable into code.
I don't know if I need to clear the display, and how do I do that only once before entering the option. How do I make it, so that all the variables related to clock, the stopwatch still work even if I'm not displaying it. I'm honestly lost, and I just need guidance with this, becuase I have only had C for 1 semester at Electrical Engineering. I'm not a programist, but I really want to make it work, but it just isn't explained in the way like I don't know, pulldown resistors, where you can make some assumptions, and with them explain how something works. No, it looks like this:
void u8g2_SetBufferPtr(u8g2_t *u8g2, uint8_t *buf)

And yeah, I just don't know how do I go around it, how do I navigate in it. Thank you for any help.

your code is very badly formatted ... for example, the if statements inside void status_bar() function are not nested, they should all be indented the same amount ... same with the program lines in the setup() function

I'm sorry, I wasn't teached/haven't studied coding ethics, in sense of formatting. Code was easily readable to me, and I could easily find the parts I needed :)
Next time I will use Autoformatting before posting

btw why do you use software SPI for the display?

Because it's a 5110 display, and it only supports SPI communication, as far as I know

I have figured it out.
First thing that has to be said. If you're used to creating function definitions before the setup, you can't do that with u8g2 library. You can create function definitions after calling u8g2.begin in setup. Now there are two ways how you can do it, in the "Casio watch" fashion, but first create a varaible that will read how many times you've clicked, and store that somewhere, and add a condition, that will revert it to 1 after some amount of clicks.
1st way: Create a switch case, where the variable will be your switch, and in the cases (x to n) write what you want, graphics, text, whatever. Now the problem that I've had, is that when I've pasted the same code, and changed only some minor text, the whole thing glitched. It went through 1 and 2, normally, and then everything from case 3 and 4 was merged toghether, and case 4 was empty, and so was the screen. I couldn't fix it, so I came up with the second approach. Create as many IF conditions, as you have menu option. So it goes like this:
If (menu_counter == 1){ //your input to the screen// }
And so for the rest. As far as I have tested this, it works, even if the code is the same for both IF statements. Now I'd have to implement the menu selection list on top. Leaving the answer to my own question, hopefully someone will find it useful.


text:
Using multiple ultrasonic sensors simultanously with the same trigger
I want to use three ultrasonic sensors together and would prefer to use as few pins as possible, so I was thinking of using one trigger for all 3 sensors. The sensors will have an angle of 90 degrees between them. I was wondering if this would still cause false readings? Since they are a large angle (and some distance) apart?

I think this isn't really answerable, since it greatly depends on your environment. You might get stray reflections into the other sensors. I suggest you just try it out.

If you're using the usual HC-SR04 sensor you should check if there's an ECHO pulse without a prior TRIG pulse output at all. (Otherwise, you can feed all TRIG pins from the same Arduino OUTPUT pin). And keep in mind that pulseIn blocks, so you cannot use it to  get multiple more or less simultaneous signals.

I was looking into this a while back using HC-SR04 sensors and did have some issues with bad (well, strange) readings. but I was just fiddling around with it and haven't gone back to it.
That being said, if you connect the triggers together, but the echo lines individually, and put at least 60ms delay between triggering and reading each sensor, then it might work for your application.
This thread briefly touches on how the time it takes for a ping to decay is part of the issue.
https://forum.arduino.cc/t/multiple-ultrasonic-sensors-close-together/410358
My understanding of it suggests that if you send out a ping in multiple directions, the ping going right echoes off a surface, then echoes off a surface on the left side, which returns to the sensor on the other side, so the sensor might receive a lot of noise.
The datasheet on the HC-SR04 indicates that the cycle time of a single measurement should be 60ms, so a trigger signal doesn't align with an echo...
https://forum.arduino.cc/uploads/short-url/961oW5W0LoHZ6t5XOP40HryBlZK.pdf
In any case, these sensors are cheap and I find that throwing a few bits on a proto board and testing experimenting with them is the best way to learn.
Start with two sensors opposing each other with a surface at 2 inches in front of one, and at 4 inches from the other. trigger them together, see if you can get a clean read from either one. Experiment with different distances to objects (like within an inch on each side, etc). Then repeat the process with a third at the front, and with surface objects at odd angles.
I hope this is helpful, if not encouraging at least :)


text:
How to use multiple PN532 over i2c bus(es) and SPI?
I am working on a project that involves 3 PN532_modules to an ESP32, which sends the Tag_ID over BLE.
Plan A was to use One module on i2c_1, second on I2C_2 and third over SPI.
The SPI one works as expected.
Though I am having issues with using 2 I2c Buses using the same Adafruit Library. Exact issues are-

Unreliable reading while using 2 different i2c buses
Sometimes the SPI bus freezes after scanning a Tag on one of i2c connected readers.
My code is here

#include <Arduino.h>

#include <Wire.h>
//#include <Adafruit_PN532_2.h>
#include <Adafruit_PN532.h>

#define SDA_1 (21)
#define SCL_1 (22)
#define SDA_2   (33)
#define SCL_2   (32)

Adafruit_PN531 nfc1(SDA_1, SCL_1);
Adafruit_PN532 nfc2(SDA_2, SCL_2);

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

  nfc1.begin();
  nfc2.begin();

  uint32_t versiondata_1 = nfc1.getFirmwareVersion();
  if (! versiondata_1) {
    while (1); // halt
  }
Serial.println(versiondata_1);

  uint32_t versiondata_2 = nfc2.getFirmwareVersion();
  if (! versiondata_2) {
    while (1); // halt
  }
Serial.println(versiondata_2);
}

void loop(void) {

  uint8_t success_1;
  uint8_t uid_1[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
  uint8_t uidLength_1;                        // Length of the UID (4 or 7 bytes

  uint8_t success_2;
  uint8_t uid_2[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
  uint8_t uidLength_2;                        // Length of the UID (4 or 7 bytes

  success_1 = nfc1.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid_1, &uidLength_1);
  delay(10);

  success_2 = nfc2.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid_2, &uidLength_2);
  delay(10);

  if (success_1)
  {
    Serial.println(success_1);
    Serial.print(" UID_1 Value: ");
    nfc1.PrintHex(uid_1, uidLength_1);
    Serial.println("");
  }
  delay(10);

  if (success_2)
  {
    Serial.print(" UID_2 Value: ");
    nfc2.PrintHex(uid_2, uidLength_2);
    Serial.println("");
  }
  delay(10);

}

Why not simply use SPI for all 3 instances of this chip ? You need the 3 basic shared SPI bus pins  SCK, MISO and MOSI. Each chip needs additionally one dedicated CS (Chip Select) pin. See https://learn.adafruit.com/adafruit-pn532-rfid-nfc/breakout-wiring (where this pin is called SSEL) and anyway you have said already that SPI works for you.

Both I2C and SPI is a bus architecture, meaning that multiple devices can share the same bus without needing separate wiring for each device as long as they have different address (in case of I2C) or have separate chip select (in case of SPI). All three can share the same I2C bus or SPI bus. Read I2C and SPI for more details.

@hcheung Thanks for answering, For I have discovered, they have FIxed i2c Address, so having them all on the same Bus isn't possible.  Also having 2 Different buses also doesn't quite solves the problem. As the problem is the Library having only one class for all 3 Interfaces(SPI, i2c and HSU).

Regards

As mentioned by 6v6gt, you could use the SPI with 3 wires sharing among all three devices for MOSI, MISO and SCK, with another 3 GPIO pins configured as CS for each of the board. Class is a footprint (library), you don't use the Class directly, you create an instance of the Class for each board.


text:
Buzzer keeps buzzing even though the sensor doesn't detect anything
through the code that I've listed below, the idea was to have a sensor that detects objects in different ranges, if they're quite close, a light strip will turn on yellow with no buzzer. If they're very close, the light strip will turn red and buzzer will buzz rapidly. However in our case, the buzzer keeps buzzing constantly even though there's no object in the vicinity of the sensor.
Below are our code for the input:
#include <Adafruit_NeoPixel.h>

#define TRIGGER_PIN_LEFT 8
#define ECHO_PIN_LEFT 9
#define TRIGGER_PIN_RIGHT 4
#define ECHO_PIN_RIGHT 5
#define NUM_PIXELS 8
#define POTENTIOMETER_PIN A0
#define PIEZO_PIN 10
#define TILT_PIN 6

Adafruit_NeoPixel strip1(NUM_PIXELS, 3, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel strip2(NUM_PIXELS, 2, NEO_GRB + NEO_KHZ800);

void setup() {
  pinMode(TRIGGER_PIN_LEFT, OUTPUT);
  pinMode(ECHO_PIN_LEFT, INPUT);
  pinMode(TRIGGER_PIN_RIGHT, OUTPUT);
  pinMode(ECHO_PIN_RIGHT, INPUT);
  pinMode(PIEZO_PIN, OUTPUT);
  pinMode(TILT_PIN, INPUT);
  strip1.begin();
  strip1.show();
  strip2.begin();
  strip2.show();
  Serial.begin(9600);
}

void loop() {
  long duration1, distance1, duration2, distance2;
  int speed = analogRead(POTENTIOMETER_PIN);
  int tilt = digitalRead(TILT_PIN);

  digitalWrite(TRIGGER_PIN_LEFT, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGGER_PIN_LEFT, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGER_PIN_LEFT, LOW);
  duration1 = pulseIn(ECHO_PIN_LEFT, HIGH);
  distance1 = (duration1/2) / 29.1;

  digitalWrite(TRIGGER_PIN_RIGHT, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGGER_PIN_RIGHT, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGER_PIN_RIGHT, LOW);
  duration2 = pulseIn(ECHO_PIN_RIGHT, HIGH);
  distance2 = (duration2/2) / 29.1;

  if (distance1 < 200 && distance1 > 50 && tilt == LOW) {
    for(int i=0; i<NUM_PIXELS; i++) {
      strip1.setPixelColor(i, 255, 255, 0);
    }
    strip1.show();
  } else if (distance1 < 200 && distance1 > 50 && tilt == HIGH) {
    for(int i=0; i<NUM_PIXELS; i++) {
      strip1.setPixelColor(i, 255, 0, 0);
    }
    strip1.show();
    tone(PIEZO_PIN, 500);
    delay(100);
    noTone(PIEZO_PIN);
    delay(100);
  } else if (distance1 < 50 && speed > 100) {
    for(int i=0; i<NUM_PIXELS; i++) {
      strip1.setPixelColor(i, 255, 0, 0);
    }
    strip1.show();
    tone(PIEZO_PIN, 500);
    delay(100);
    noTone(PIEZO_PIN);
    delay(500);
  } else {
    for(int i=0; i<NUM_PIXELS; i++) {
      strip1.setPixelColor(i, 0, 0, 0);
    }
    strip1.show();
  }

  if (distance2 < 200 && distance2 > 50 && tilt == LOW) {
    for(int i=0; i<NUM_PIXELS; i++) {
      strip2.setPixelColor(i, 255, 255, 0);
    }
    strip2.show();
  } else if (distance2 < 200 && distance2 > 50&& tilt == HIGH) {
    for(int i=0; i<NUM_PIXELS; i++) {
      strip2.setPixelColor(i, 255, 0, 0);
    }
    strip2.show();
    tone(PIEZO_PIN, 500);
    delay(100);
    noTone(PIEZO_PIN);
    delay(100);
  } else if (distance2 < 50 && speed > 100) {
    for(int i=0; i<NUM_PIXELS; i++) {
      strip2.setPixelColor(i, 255, 0, 0);
    }
    strip2.show();
    tone(PIEZO_PIN, 500);
    delay(100);
    noTone(PIEZO_PIN);
    delay(500);
  } else {
    for(int i=0; i<NUM_PIXELS; i++) {
      strip2.setPixelColor(i, 0, 0, 0);
    }
    strip2.show();
  }
  Serial.print("Tilt=");
  Serial.println(tilt);
}

Put a Serial.print( ) debug statement after each tone() statement so you know which one is being incorrectly executed. Or maybe you already know from the colour of LED display.


text:
I develop an earthquake detector but when it detects a movement, the alarm doesn't stop from ringing
This is the code that I used. Actually, I use to code: for Arduino sofware and processing IDE software.
Arduino Source Code/Program:
#include<LiquidCrystal.h> // lcd Header
LiquidCrystal lcd(7,6,5,4,3,2); // pins for LCD Connection

#define buzzer 12 // buzzer pin
#define led 13 //led pin

#define x A0 // x_out pin of Accelerometer
#define y A1 // y_out pin of Accelerometer
#define z A2 // z_out pin of Accelerometer

/*variables*/
int xsample=0;
int ysample=0;
int zsample=0;
long start;
int buz=0;

/*Macros*/
#define samples 50
#define maxVal 20 // max change limit
#define minVal -20 // min change limit
#define buzTime 5000 // buzzer on time

void setup()
{
    lcd.begin(16,2); //initializing lcd
    Serial.begin(9600); // initializing serial
    delay(1000);
    lcd.print("EarthQuake ");
    lcd.setCursor(0,1);
    lcd.print("Detector ");
    delay(2000);
    lcd.clear();
    lcd.print("Calibrating.....");
    lcd.setCursor(0,1);
    lcd.print("Please wait...");
    pinMode(buzzer, OUTPUT);
    pinMode(led, OUTPUT);
    buz=0;
    digitalWrite(buzzer, buz);
    digitalWrite(led, buz);
    for(int i=0;i<samples;i++) // taking samples for calibration
    {
        xsample+=analogRead(x);
        ysample+=analogRead(y);
        zsample+=analogRead(z);
    }

    xsample/=samples; // taking avg for x
    ysample/=samples; // taking avg for y
    zsample/=samples; // taking avg for z

    delay(3000);
    lcd.clear();
    lcd.print("Calibrated");
    delay(1000);
    lcd.clear();
    lcd.print("Device Ready");
    delay(1000);
    lcd.clear();
    lcd.print(" X Y Z ");
}

void loop()
{
    int value1=analogRead(x); // reading x out
    int value2=analogRead(y); //reading y out
    int value3=analogRead(z); //reading z out

    int xValue=xsample-value1; // finding change in x
    int yValue=ysample-value2; // finding change in y
    int zValue=zsample-value3; // finding change in z

    /*displying change in x,y and z axis values over lcd*/
    lcd.setCursor(0,1);
    lcd.print(xValue);
    lcd.setCursor(6,1);
    lcd.print(yValue);
    lcd.setCursor(12,1);
    lcd.print(zValue);
    delay(100);

    /* comparing change with predefined limits*/
    if(xValue < minVal || xValue > maxVal || yValue < minVal
            || yValue > maxVal || zValue < minVal || zValue > maxVal)
    {
        if(buz == 0)
            start=millis(); // timer start
        buz=1; // buzzer / led flag activated
    }
    else if(buz == 1) // buzzer flag activated then alerting earthquake
    {
        lcd.setCursor(0,0);
        lcd.print("Earthquake Alert ");
        if(millis()>= start+buzTime)
            buz=0;
    }
    else
    {
        lcd.clear();
        lcd.print(" X Y Z ");
    }

    digitalWrite(buzzer, buz); // buzzer on and off command
    digitalWrite(led, buz); // led on and off command

    /*sending values to processing for plot over the graph*/
    Serial.print("x=");
    Serial.println(xValue);
    Serial.print("y=");
    Serial.println(yValue);
    Serial.print("z=");
    Serial.println(zValue);
    Serial.println(" $");
}

Processing IDE Code/Program:
import processing.serial.*;
PFont f6,f8,f12,f10;
PFont f24;
Serial myPort; // The serial port
int xPos = 0; // horizontal position of the graph
float y1=0;
float y2=0;
float y3=0;

void setup ()
{
    // set the window size: and Font size
    f6 = createFont("Arial",6,true);
    f8 = createFont("Arial",8,true);
    f10 = createFont("Arial",10,true);
    f12 = createFont("Arial",12,true);
    f24 = createFont("Arial",24,true);
    size(1200, 700);

    // List all the available serial ports
    println(Serial.list());
    myPort = new Serial(this, "COM10", 9600);
    println(myPort);
    myPort.bufferUntil('\n');
    background(80);
}

void draw ()
{
    serial();
}

void serial()
{
    String inString = myPort.readStringUntil('$'); // reading incomming date from serial
    if (inString != null)
    {
        // extracting all required values of all three axis:
        int l1=inString.indexOf("x=")+2;
        String temp1=inString.substring(l1,l1+3);
        l1=inString.indexOf("y=")+2;
        String temp2=inString.substring(l1,l1+3);
        l1=inString.indexOf("z=")+2;
        String temp3=inString.substring(l1,l1+3);

        //mapping x, y and z value with graph dimensions
        float inByte1 = float(temp1+(char)9);
        inByte1 = map(inByte1, -80,80, 0, height-80);
        float inByte2 = float(temp2+(char)9);
        inByte2 = map(inByte2,-80,80, 0, height-80);
        float inByte3 = float(temp3+(char)9);
        inByte3 = map(inByte3,-80,80, 0, height-80);
        float x=map(xPos,0,1120,40,width-40);

        //ploting graph window, unit
        strokeWeight(2);
        stroke(175);
        Line(0,0,0,100);
        textFont(f24);
        fill(0,00,255);
        textAlign(RIGHT);
        xmargin("EarthQuake Graph (SESMIOGRAPH)",200,100);

        fill(100);
        strokeWeight(100);
        line(1050,80,1200,80);

        strokeWeight(1);
        textAlign(RIGHT);
        fill(0,0,255);
        String temp="X:"+temp1;
        Text(temp,100,95);

        fill(0,255,0);
        temp="Y:"+temp2;
        Text(temp,100,92);

        fill(255,0,0);;
        temp="Z:"+temp3;
        Text(temp,100,89);

        //ploting x y and z values over graph
        strokeWeight(2);
        int shift=40;

        stroke(0,0,255);
        if(y1 == 0)
            y1=height-inByte1-shift;
        line(x, y1, x+2, height-inByte1-shift) ;
        y1=height-inByte1-shift;

        stroke(0,255,0);
        if(y2 == 0)
            y2=height-inByte2-shift;
        line(x, y2, x+2, height-inByte2-shift) ;
        y2=height-inByte2-shift;

        stroke(255,0,0);
        if(y2 == 0)
            y3=height-inByte3-shift;
        line(x, y3, x+2, height-inByte3-shift) ;
        y3=height-inByte3-shift;

        xPos+=1;

        if (x >= width-30) // go back to begining
        {
            xPos = 0;
            background(80);
        }
    }
}

void Line(int x1, int y1, int x2, int y2)
{
    float xx1=map(x1,0,100,40,width-40);
    float xx2=map(x2,0,100,40,width-40);
    float yy1=map(y1,0,100,height-40,40);
    float yy2=map(y2,0,100,height-40,40);

    line(xx1,yy1,xx2,yy2);
    xx2=map(100,0,100,40,width-40);
    yy2=map(0,0,100,height-40,40);
    line(xx1,yy1,xx2,yy2);

    strokeWeight(1);
    for(int i=1;i<21;i++)
    {
        yy2=map(i*10,0,200,height-40,40);
        yy1=yy2;
        line(xx1,yy1,xx2,yy2);
    }
    yy2=map(100,0,100,height-40,40);
    yy1=map(0,0,100,height-40,40);
    for(int i=1;i<41;i++)
    {
        xx1=map(i*5,0,200,40,width-40);
        xx2=map(i*5,0,200,40,width-40);
        line(xx1,yy1,xx2,yy2);
    }

    textAlign(RIGHT); // 100 degree
    // result+=yy1;
    fill(255);
    strokeWeight(1);
    textFont(f12);
    for(int i=-10;i<11;i++)
    {
        String result="";
        result+=5*i;
        ymargin(result, x1,y1);
        y1+=5;
    }

    x1=0;
    y1=0;
    strokeWeight(1);
    textFont(f10);
    for(int i=0;i<41;i++)
    {
        String result="";
        result+=28*3*i;
        xmargin(result, x1,y1);
        x1+=5;
    }

    textAlign(RIGHT);
    textAlign(RIGHT);
}

void ymargin(String value, int x1, int y1)
{
    float xx1=map(x1,0,100,40,width-40);
    float yy1=map(y1,0,100,height-40,40);
    text(value,xx1-5,yy1+5);
}

void xmargin(String value, int x1, int y1)
{
    float xx1=map(x1,0,200,40,width-40);
    float yy1=map(y1,0,100,height-25,25);
    text(value,xx1+7,yy1);
}

void Text(String value, int x1, int y1)
{
    float xx1=map(x1,0,100,40,width-40);
    float yy1=map(y1,0,100,height-25,25);
    text(value,xx1,yy1);
}

I cannot see anything in your code that could be a cause for this
behavior. So maybe the cause is outside the code.
How do you simulate an earthquake? I guess you manually move the sensor
somehow. It may well happen that, after moving it, it doesn't settle in
exactly the same orientation it was before. When this happens, the
acceleration of gravity will be in a slightly different direction, and
your calibration will not be valid anymore. You can check for this
condition by watching the displayed values: if they settle to something
almost constant but large (more than 20 in absolute value), then that is
what is happening.
If this is the case, a possible solution would be to redo the
calibration a couple of seconds after detecting an earthquake. I would
suggest a technique that is, in my view, more elegant: calibrate
continuously, i.e. update the calibration every few microseconds.
The idea is that, instead of computing a set of offsets once and for
all, you low-pass-filter the raw readings and use these smoothed
readings as offsets. When you subtract the offsets from the readings,
you are implementing in essence a high-pass filter.
Here is a tentative implementation of this idea. I made the readings
periodic in order to have some control on the time constant of the
filter. In practice, you would have to adapt the time constant to the
requirements of your experiment:
// Constants to be adjusted, times are in microseconds.
const uint32_t readingPeriod   = 10e3;  // 10e3 us = 10 ms
const float filterTimeConstant = 10e6;  // 10e6 us = 10 s
const float filterConstant = readingPeriod / filterTimeConstant;

// Periodically updated filtered accelerations.
float accelX, accelY, accelZ;

// Internal state of the filter.
uint32_t lastTimeReading = 0;
float offsetX, offsetY, offsetZ;

// Call this from setup()
void initializeOffsets() {
    offsetX = analogRead(x);
    offsetY = analogRead(y);
    offsetZ = analogRead(z);
}

// Call this from loop()
void updateAccelerations() {
    // Take the readings only every readingPeriod us.
    if (micros() - lastTimeReading < readingPeriod)
        return;
    lastTimeReading += readingPeriod;

    // Read the sensors.
    int readingX = analogRead(x);
    int readingY = analogRead(y);
    int readingZ = analogRead(z);

    // Update the offsets.
    offsetX += filterConstant * (readingX - offsetX);
    offsetY += filterConstant * (readingY - offsetY);
    offsetZ += filterConstant * (readingZ - offsetZ);

    // Update the filtered accelerations.
    accelX = readingX - offsetX;
    accelY = readingY - offsetY;
    accelZ = readingZ - offsetZ;
}

Thank you so much. I will try your suggestion.

What part of my code should I put your code?

@ChristianMarasigan: It's written in the comments. Please don't just copy-paste this without understanding at least the general principle. Look at the comments. If something does not make sense, ask.

I would convert the outputs to Integers from Double and see if it's still 'ringing'.
The description suggests it is creating a feedback loop (critically damped) and you have to set a lower limit of those values that also shut the device down.
So, if you are currently reading precision of < 0.00001 ( in any axis) add a break in the program.
Big old guess but good luck.

Thank you. I will try it.

Just a guess, but is the vibration from the buzzer sufficiently strong to trigger the accelerometer? If so, once the buzzer sounds after detecting an earthquake, it might just keep triggering itself.
To fix this, you probably need to take some sample accelerometer readings to see how strong the buzzer vibrations are compared to the signal from an earthquake. You could then look to change your calibration or try to filter out the signal from the buzzer.
Alternatively, you might need to physically isolate the buzzer from the accelerometer.