text:
How to read response from server using an Ethernet shield?
I want to control a relay by reading values from MySQL. I'm using an Arduino and an Ethernet shield. So far, I can get the response from server and get the value. I just need the value 10110110, but I get a response in the serial monitor like this:
HTTP/1.1 200 OK
Date: Sun, 02 Jul 2017 07:53:29 GMT
Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1
X-Powered-By: PHP/5.3.1
Content-Length: 13
Content-Type: text/html

<10110110>

How to remove this long response and get the value 10110110?

@ChrisStratton - With respect, please review the edits, to see who made what changes. This was a suggested edit, made by someone else, that I reviewed, accepted and improved the edit. Should I have rejected the edit?

@Golckz Could you please provide more information. Tell us about the specifics. Make sure your question is clear.

What code have you used? Could you post it? What is the specific command that you use to request the value from the database?

There are, obviously, a great number of ways that this can be achieved. The simple brute force way would be to have a series of if statements, looking for a sequence of eight consecutive 0s and/or 1s, and loop through the string containing the response.
Or you could loop through the response, using strcmp(), similar to what is described here: how to do like a grep in a sketch?
However, a more intelligent method would be to use pattern matching and regular expressions.
From New regular expression library released, Nick has provided a Regexp library. It uses Lua for the expression syntax, see string.find, for more details.
I am still playing with this code, but your sketch would need something like this:
#include <Regexp.h>
void setup ()
{
  Serial.begin (115200);
  Serial.println ();

  unsigned int index = 0;
  char buf [100];

  MatchState ms;
  ms.Target ("HTTP/1.1 200 OK\
Date: Sun, 02 Jul 2017 07:53:29 GMT\
Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1\
X-Powered-By: PHP/5.3.1\
Content-Length: 13\
Content-Type: text/html\
\
\
<10110110>");  // what to search

  while (true){
    char result = ms.Match ("^<([01][01][01][01][01][01][01][01])", 0);  // look for an eight bit binary digit
    if (result == REGEXP_MATCHED)
    {
      Serial.println ("-----");
      Serial.print ("Matched on: ");
      Serial.println (ms.GetMatch (buf));
      Serial.println ("Captures:");
      for (int j = 0; j < ms.level; j++)
         Serial.println (ms.GetCapture (buf, j));
      // move past matching string
      index = ms.MatchStart + ms.MatchLength;
    }  // end of match
    else
      break;  // no match or regexp error

  } // end of while

}  // end of setup

void loop () {}

This code assumes that you are looking for a line beginning with < and captures an eight digit binary thereafter - as determined by the expression within the inner (), in the line:
    char result = ms.Match ("^<([01][01][01][01][01][01][01][01])", 0);  // look for an eight bit binary digit

So, it should output:
-----
Matched on: <10110110
Captures: 10110110
-----

Obviously, instead of just outputting the captured binary digits to the serial monitor, you need to save them for your relay control.

For neatness, you could replace
 ms.Target ("HTTP/1.1 200 OK\
Date: Sun, 02 Jul 2017 07:53:29 GMT\
Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1\
X-Powered-By: PHP/5.3.1\
Content-Length: 13\
Content-Type: text/html\
\
\
<10110110>");  // what to search

with
  char * str = "HTTP/1.1 200 OK\
    Date: Sun, 02 Jul 2017 07:53:29 GMT\
    Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1\
    X-Powered-By: PHP/5.3.1\
    Content-Length: 13\
    Content-Type: text/html\
    \
    \
    <10110110>";

  ms.Target (str);

Note the use of the backslashes at the ends of the lines. I've included them here, in order to get the test sketch to compile. You probably will not need them as you would be receiving the response from the server, and not providing an example string for testing.

Here is a working version, along with multiple test strings (input_str) and example match strings (match_str):
#include <Regexp.h>
void setup ()
{
  Serial.begin (9600);
//  Serial.begin (115200);
  Serial.println ();

  unsigned int index = 0;
  char buf [100];

// Simple test pair
//  char * input_str = "RGB:123";
//  char * match_str = "(%a)";

// Simulated MySQL responses
// Most basic
//  char * input_str = "<10110110>";
// Over two lines
//  char * input_str = "http\\n<10110110>";
// Full response
  char * input_str = "HTTP/1.1 200 OK\
    Date: Sun, 02 Jul 2017 07:53:29 GMT\
    Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1\
    X-Powered-By: PHP/5.3.1\
    Content-Length: 13\
    Content-Type: text/html\
    \
    \
    <10110110>";
// Full response with newlines
//  char * input_str = "HTTP/1.1 200 OK\\n\
    Date: Sun, 02 Jul 2017 07:53:29 GMT\\n\
    Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1\\n\
    X-Powered-By: PHP/5.3.1\\n\
    Content-Length: 13\\n\
    Content-Type: text/html\\n\
    \\n\
    \\n\
    <10110110>";
// Shorter version of full MySQL response with newlines
//  char * input_str = "Content-Type: text/html\\n\
    \\n\
    \\n\
    <10110110>";
// Shorter version of full MySQL response with newlines with no preceeding spaces
//  char * input_str = "Content-Type: text/html\\n\
\\n\
\\n\
<10110110>";

// Match strings for MySQL response, containing an eight bit binary number
// Match at beginning of line
//  char * match_str = "^<([01][01][01][01][01][01][01][01])";
// Match at beginning of line with multiple newline characters
  char * match_str = "[\n]*<([01][01][01][01][01][01][01][01])";
// Match at beginning of line with zero or one newline characters
//  char * match_str = "[\n]?<([01][01][01][01][01][01][01][01])";
// Match at anywhere
//  char * match_str = "<([01][01][01][01][01][01][01][01])";

  MatchState ms;

  while (true){
    char result = ms.Match (match_str, 0);

    if (result == REGEXP_MATCHED)
    {
      Serial.println ("-----");
      Serial.print ("Matched on: ");
      Serial.println (ms.GetMatch (buf));
      Serial.println ("Captures:");
      for (int j = 0; j < ms.level; j++)
         Serial.println (ms.GetCapture (buf, j));
      // move past matching string
      index = ms.MatchStart + ms.MatchLength;
    }  // end of match
    else
      break;  // no match or regexp error

  } // end of while

}  // end of setup

void loop () {}

For the match_str line,
char * match_str = "[\n]*<([01][01][01][01][01][01][01][01])";

you may or may not need the caret (^) to match at the start of the line, and the [\n]* or [\n]?. See which combination works for you.

This is far more complicated than needed.  Review the HTTP protocol, and what it says about body vs header.

OK @ChrisStratton, thanks for your input. Maybe you would like to post your own answer, with your solution?

I think it is a really great answer. you could utilize this response for a wide range of similar problems, and there is a great amount of detail.

@jOh, Thanks. Yes, it is a most versatile library


text:
Adafruit ESP32 device working on OSX 10.13 but not on OSX 10.11 on older machine
I'm new to Arduino - just got an ESP32-based Adafruit Feather HUZZAH32. I got it up and running on my Macbook Air (High Sierra) with no problem, following the instructions at this page linked from the Adafruit page on the HUZZAH32:
https://github.com/espressif/arduino-esp32/blob/master/docs/arduino-ide/mac.md (dead link)
Basically, install the Arduino IDE, install the Espressif stuff using a big shell command, and install the driver for the CP2104 USB->UART bridge.
It worked like a charm on the Macbook Air, no problem. But it was a different story when I went to install it on my 2009 vintage Mac Pro running El Capitan. Everything seemed to install ok, and the Arduino IDE runs and shows "Adafruit ESP32 Feather" (under Tools->Board).
However, when I try to upload a sketch (the "Blink" built-in example), it compiles ok but seems to hang while uploading, eventually finishing after about 5 minutes.  But the sketch isn't there, the one I previously uploaded from the HighSierra machine still executing.
Furthermore, it does weird things to the Mac: the System Profiler (About This Mac) no longer runs (shown as "Not Responding" in Activity Monitor), even after I've quit the IDE; occasionally I can't even seem to quit the IDE; and next time my computer sleeps, it can't be woken up (I have to restart with the power button).   Another thing: when I start the upload, the kernel-task (PID 0) starts using over 100% of the CPU (from Activity Monitor).
Maybe it's a version compatability issue with the Espressif uploader?   Or maybe I screwed up with the CP2104 driver, first installing the one here, CP210x USB to UART Bridge VCP Drivers, as pointed to by the How-To at Adafruit, and when things did not work, and the uninstall shell script for the driver failed too, I just deleted what seemed to be the relevant files before then installing the "legacy" driver, which also did not work.
Looked at some of the debugging stuff here ... The CP2104 driver shows up under USB in System Profiler, and both cu.SLAB_USBtoUART and tty.SLAB_USBtoUART show up under /dev (in Terminal).   So nothing seems wrong there.
Here is a screen grab (with verbose output for upload selected):
Archiving built core (caching) in:
 /var/folders/qr/2l7_tnqx0m34h2sfbp218ykw0000gp/T/arduino_cache_759917/core/core_espressif_esp32_featheresp32_FlashFreq_80,UploadSpeed_921600,DebugLevel_none_4423141e818963094868f9e8ffa4e8ec.a

Sketch uses 136741 bytes (10%) of program storage space. Maximum is 1310720 bytes.

Global variables use 10908 bytes (3%) of dynamic memory, leaving 284004 bytes for local variables. Maximum is 294912 bytes.

/Volumes/MainHD/Users/jge/Documents/Arduino/hardware/espressif/esp32/tools/esptool --chip esp32 --port /dev/cu.SLAB_USBtoUART --baud 921600 --before default_reset --after hard_reset write_flash -z --flash_mode dio --flash_freq 80m --flash_size detect 0xe000 /Volumes/MainHD/Users/jge/Documents/Arduino/hardware/espressif/esp32/tools/partitions/boot_app0.bin 0x1000 /Volumes/MainHD/Users/jge/Documents/Arduino/hardware/espressif/esp32/tools/sdk/bin/bootloader_dio_80m.bin 0x10000 /var/folders/qr/2l7_tnqx0m34h2sfbp218ykw0000gp/T/arduino_build_212318/Blink.ino.bin 0x8000 /var/folders/qr/2l7_tnqx0m34h2sfbp218ykw0000gp/T/arduino_build_212318/Blink.ino.partitions.bin

It just seems to be a very long command line to run esptool, and then... nothing.
I'm at a loss - I've asked at Adafruit forums: trouble getting HUZZAH32 working on Mac
... and filed an "issue" at the Github page too: upload hangs on older Mac configuration (Mac Pro 4,1 w/ El Capitan) #983
In short, this Github issue says that the thing works fine on the USB ports on the rear of my Apple monitor, but hangs (as described in OP) on the ones on the front of the Mac Pro tower as well as the ones on the rear of the tower (including the one into which the monitor was plugged).

Is the difference USB 3.0 vs USB 2.0?

Yes, I think it may have to do with power, because I've run into some weird behavior, that seems power related, when I try to turn on wifi. And it's not the CP210X drivers, because it works on some ports and not others.  My machine only has USB 2.0 ports, and of course USB 3.0 can provide more power.   I'm going to buy an AC-powered USB hub and see if that works better.

The first link appears to have died, unfortunately. The guide appears to have been moved - could you please verify that this is now the link to the same guide that you followed: https://docs.espressif.com/projects/arduino-esp32/en/latest/installing.html#macos. In addition, I have found that older versions of OS X do not work well with CH34x or CP210x USB interfaces (when they are used on an Arduino clone), the drivers just aren't there (not built-in to the OS).

source: Stack Exchange

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

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

sort: votes


text:
Reading text line by line from SD
Why does the following code return this error?  How can I make this work?

Error: exit status 1 invalid conversion from 'const char*' to 'char'
  [-fpermissive]

#include "FS.h"
#include "SD.h"
#include "SPI.h"

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

  if (!SD.begin(33)) {
    Serial.println("Card Mount Failed");
  } else {
    Serial.println("Card Mount Succeeded");
  }

  File offline = SD.open("/offlineLog.txt", FILE_READ);

  while (offline.available()) {
    String line = offline.readStringUntil("\n");
    Serial.println(line);
  }
}

The docs say that stream.readStringUntil returns a string...

The error has nothing to do with what readStringUntil returns. It has to do with what parameters it accepts.
The function expects a single character to look for. Instead you are passing it a string (C string) containing one character.
In C you represent a string (char *) using "", and a single character (char) using ''.
Since readStringUntil expects a char, not a char *, you need to use '':
String line = offline.readStringUntil('\n');

Thank you!  I wish that error message was more descriptive.

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


text:
Why does current flow along a wire instead of a resistor right next to it?
I am having trouble understanding exactly what is going on in a circuit where when a button is pressed an LED goes on. Also, I have the Arduino UNO.
The schematic can be seen at:
2:36 of this video: Arduino Tutorials: Control a LED with a Button.

So, the part that I don’t understand is, how come when the button is clicked and the current can pass through, the current doesn’t go through the pull down resistor and instead goes along the input wire?

I’m a beginner but do understand concepts like voltage, amps, resistors, Ohm’s law, etc. So answers don’t have to be super simple, but simple enough that I can understand them. Thanks!

You may have the arduino, but the question is off topic.  Please ask the question at Electrical Engineering SE.

The input pin has a very high resistance, so that nearly no current is flowing into it. Effectively the microcontroller is doing a voltage measurement. It measures the voltage over the pulldown resistor.

Some current is flowing though the pull-down resistor, but the power supply has no problem producing this little bit of current, so the voltage before the pull-down resistor will remain a stable 5 Volt. So the voltage at the Arduino input will be 5Volt while the button is pressed. Once the button is released any "stray" voltage will flow though the resistor, so the voltage at the input pin will become 0 Volt

Please, can you forget everything that you "learned" from that video. The explanation in that video is wrong and confusing. The way the video explains how the current flows is utter nonsense. You can start with the arduino examples, they are in the menu of the arduino program and also online: https://www.arduino.cc/en/Tutorial/BuiltInExamples Start for example with "Button" in section "2. Digital".

So, the part that I don’t understand is, how come when the button is clicked and the current can pass through, the current doesn’t go through the pull down resistor and instead goes along the input wire?

Simple: It does go through the pull down resistor. But  it also goes down the "input" wire.
For simplicity you can imagine that the input is simply a very large resistor. Say, 1MΩ.
The circuit can then be simplified as:

simulate this circuit – Schematic created using CircuitLab
Contrary to popular belief, current does not take the path of least resistance. It takes all possible paths. The quantity of current through each path is proportional to the resistance of the paths.
In this example we have two paths - one with 10kΩ and one with 1MΩ.  That's a ratio of 1:100, and the current will be split accordingly.
You can calculate the current that flows through each resistor simple using Ohm's Law because the wires and switch are (in an ideal world) just not there. The 5V is directly connected across each of the resistors.
So for the 10kΩ resistor the current through is is:
     V      5
I = --- = ----- = 0.0005 = 500µA
     R    10000

And for the 1MΩ it is of course 100x smaller (I'll let you do the maths for that if you want to check), so 5µA.
The full current that the circuit takes is 505µA, with it split between the two resistors.
With the Arduino instead of the 1MΩ resistor it's exactly the same (though the current values may vary somewhat).  500µA flows through the 10kΩ resistor, and "some tiny current" flows through the Arduino.
However, with all that said, the Arduino really doesn't care about the current. All it cares about is the voltage. With the button pressed both the input and the 10kΩ resistor are connected directly to the 5V supply - so the Arduino reads that as "HIGH". When you release the button the input is now connected to ground through the 10kΩ resistor, but there's no current to flow, so there's no voltage across the resistor (the voltage across a resistor is proportional to the current flowing through the resistor - Ohm's Law), so it's as if the input is connected directly to ground - and the Arduino reads that as "LOW".
To be more technically accurate the input of the Arduino is actually more akin to a tiny capacitor.  When you apply 5V to the input it charges that capacitor up. Once it reaches 60% of 5V the Arduino recognises it as a "HIGH" signal.
When you release the button that capacitor is then connected to ground through the resistor, and it discharges through that resistor. Once it drops to 30% of 5V the Arduino sees it as being "LOW".
If you don't have the pull-down resistor, when you remove the 5V from the input that capacitor is still charged. So the Arduino still sees it as a HIGH. The charge in the capacitor will slowly bleed away until it's low enough to be seen as low.
But, (and it's a big but), the capacitor is very sensitive and can be charged up again by ambient energy around the place (radio waves, static electricity, etc). It can harvest enough energy from the environment to get back up to the 60% of 5V and be seen as "HIGH" again. This is known as "Floating", and is something you do not want in your circuit. The input "flaps around" between HIGH and LOW with no control.  Which is why the pull-down resistor is absolutely essential.

I have one question about this answer, doesn’t the voltage drop across the LED or resistors or something like that, I just watched a video and it made me confused about this answer.

LEDs are a special case. They are in the "non linear" category, and you shouldn't worry about them at the moment. As for "voltage drop", yes, and it is. In simple terms: Ohm's Law has three variables. At any one time two of those variables are fixed, and you are calculating the third. In the circuit above the voltage is fixed and the resistance is fixed - so the current is what you would calculate. The voltage is 5V simply because it is 5V. The resistance is 10kΩ because it's a 10kΩ resistor. The combination of those two values causes 500µA to flow. ... cont ...

Of course, if you knew that there was 500µA flowing through a 10kΩ resistor then you could calculate that there was 5V being dropped across it.  The 5V in the circuit above is called a constant voltage supply. That is because it is always 5V (unless you overload it of course). The current that the supply gives out varies depending on the load (the values of the resistors in this example).

So, you are saying that the reason that it doesn’t drop is only because we already know that there are 5V? Could you please explain, sorry, I’m really trying to wrap my head around all of this.

It does drop. One side of the resistor is 5V. The other side is 0V (ground). The difference is 5V, and that is what is "dropped" across the resistor. The fact that the 5V is fixed in stone means that the current is determined by the resistance and the voltage in the formula I=V/R.

I promise I’ll try not ask another question, I’m really sorry. But how do you know that there are 0V on the other side of the resistor. Sorry. Is there a place I can understand this or figure out what is going on?

Because that is "ground" - a point in the circuit which we have chosen to measure all voltages against. The "reference" point of the circuit. "Ground" isn't anything special - it's simply a place we pick in the circuit to be that reference point. Typically it's the point of lowest potential, such as the - terminal of a battery, etc. Since "GND" has already been designated by the power supply that's connected (USB, for example), we just pick that as our refrerence point.  The 5V is not "5V" - it's "5V with respect to ground".

The "bottom" of the resistor is connected direct to ground. Ground is 0V different to Ground (how can something be different to itself?), so that point is 0V. The 5V is 5V higher than the potential at the ground point, so we say that is 5V with respect to ground. Since everything is always "with respect to ground" we never say "with respect to ground" and just take it as read.

To put it another way: A 9V battery isn't "9V" because the + terminal has 9V at it. It's 9V because the + terminal has 9V more potential than the - terminal. It only becomes 9V when you take that - terminal as the reference point. You could just as well take the + terminal as the reference point - at which moment the battery becomes a "-9V" battery, becuase the - terminal has 9V less potential than the + terminal. It's all relative. So when we pick a "ground" reference it makes sens to use one that gives the power supply a meaningful value.

I think we had a misunderstanding, I’m wondering why the voltage isn’t dropping across the resistors and 5V is still going into the input?

5V is dropping across the resistors. You have 5V (with respect to ground) on the top of it, and 0V (with respect to ground) at the bottom of it. That's 5V from one side to the other. Ergo 5V "dropped". But that doesn't mean that the top of the resistor will no longer be 5V. It has to be, for there to be 5V across the resistor.

Ok, this is the final part, I have done the math to clear up my question. Using the math shown here https://youtu.be/hqHvRCCsWU8 I made the resistance of the input wire be V(little r2, no way to format here) and assuming this is about 1 million ohms, and the 10k ohm wire be V(little r2, again no way to format here). Then doing the math I get that 4.95 volts are going into the input wire and .0495 volts are dropping across the 10k oh right resistor. Is this correct? If it is it is what I was trying to say and why I was questioning the fact that you said 5V went into the input wire.

No, that is not correct. You are looking at tutorial for series resistors. This is parallel resistors. There can be nothing but 5V going to the input, since the input is directly connected to 5V.

Oh! Thanks so much, one more thing, though if there is a 1 million ohm resistor (basically) at the input and the voltage drops to 0 (parallel circuit) then if the voltage is zero how does the arduino read that as HIGH? @Majenko

The voltage at the input is NOT zero. It is 5 Volts. It is zero at GROUND. The input is not connected to ground. It is connected to 5V.

Let us continue this discussion in chat.

the answer is within the question,
Electrons will quite happily travel along a wire until they hit resistence as in a resistor.
where there is less resistence too flow that is the path they will take.
The path of least resistence you might say.

That seems misleading, because the current will not flow only through the path with the least resistance. Instead the current is divided between all paths relative to their resistance.

agreed but at that level of understanding it seemed a fair answer

Sorry Jamie, but you are sending a beginner down the wrong path.

ok but please construct a clearer more concise answer

@Jot he's sending the user down the path of least resistance...


text:
Arduino Mega 2560 and servo motor in Proteus
Can I get help to connect Arduino Mega 2560 and servo motor in Proteus 7.8
correctly because I tried this connection, in the image below, with sweep.ino.hex in the Arduino software examples but did not work!

What didn't work exactly?

servo motor didn't work exactly !


text:
Need help with wire connections and code
I am currently working on a keypad door lock mechanism (Similar to this project, Keypad door lock).
The issues with the code I have is that the keypad attached to my board does not allow me to type the full password. Only the first value displayed on the LCD screen moves but no value is excepted. Also the buttons used to open and close the servo motor do not operate as intended.
Fritzing diagram

Photo of breadboard

Below is the code I currently have:
//LCD config
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 20, 4);

#include <Servo.h>
#include <Keypad.h>

//Variables
int mot_min = 90;   //min servo angle  (set yours)
int mot_max = 180; //Max servo angle   (set yours)
int character = 0;
int activated = 0;
char Str[16] = {' ', ' ', ' ', ' ', ' ', ' ', '-', '*', '*', '*', ' ', ' ', ' ', ' ', ' ', ' '};
//               0    1    2    3    4    5    6    7    8    9    10   11  12    13   14  15

//Pins
Servo myservo;
int buzzer = 11;   //pin for the buzzer beep
int external = 12; //pin to inside open
int internal = 13; //pin to inside close

//Keypad config
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
//define the cymbols on the buttons of the keypads
char hexaKeys[ROWS][COLS] = {
  {'1', '4', '7', '*'},
  {'2', '5', '8', '0'},
  {'3', '6', '9', '#'},
  {'A', 'B', 'C', 'D'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad

//initialize an instance of class NewKeypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

void setup() {
  myservo.attach(10); //attach the servo to pin D10
  pinMode(buzzer, OUTPUT);
  pinMode(external, INPUT);
  pinMode(internal, INPUT);
  //Init the screen and print the first text
  lcd.init();
  lcd.backlight();
  lcd.clear();
  lcd.print("    PASSWORD");
  lcd.setCursor(0, 1);
  lcd.print("      -***     ");
  //put the servo in the close position first
  myservo.write(mot_min);

}

void loop() {
  ///////////////EMERGENCY OPEN/CLOSE/////////
  if (digitalRead(external) == LOW) // if (digitalRead(external))
  {
    myservo.write(mot_max);
    lcd.clear();
    lcd.setCursor(2, 0);
    lcd.print("INSIDE  OPEN");
    activated = 2;
    analogWrite(buzzer, 240);
    delay(250);
    analogWrite(buzzer, 200);
    delay(250);
    analogWrite(buzzer, 180);
    delay(250);
    analogWrite(buzzer, 250);
    delay(250);
    analogWrite(buzzer, LOW);

    lcd.clear();
    lcd.setCursor(4, 0);
    lcd.print("WELLCOME");

    lcd.setCursor(2, 1);
    lcd.print("ELECTRONOOBS");

    lcd.clear();
    lcd.setCursor(3, 0);
    lcd.print("DOOR  OPEN");
    lcd.setCursor(2, 1);
    lcd.print("ELECTRONOOBS");
    delay(500);

  }

  if (digitalRead(internal) == LOW) // if (digitalRead(internal))
  {
    myservo.write(mot_min);
    activated = 0;
    character = 0;
    Str[6] = '-';
    Str[7] = '*';
    Str[8] = '*';
    Str[9] = '*';
    Str[10] = ' ';
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("    PASSWORD");
    lcd.setCursor(0, 1);
    lcd.print(Str);
  }

  ///////////////KEYPAD OPEN/CLOSE////////////
  char customKey = customKeypad.getKey(); //this function reads the presed key

  if (customKey != NULL) { // if (customKey)

    if (character == 0)
    {
      Serial.println(customKey);
      Str[6] = customKey;
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("    PASSWORD");
      lcd.setCursor(0, 1);
      lcd.print(Str);

    }

    if (character == 1)
    {
      Serial.println(customKey);
      Str[7] = customKey;
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("    PASSWORD");
      lcd.setCursor(0, 1);
      lcd.print(Str);

    }

    if (character == 2) {
      {
        Serial.println(customKey);
        Str[8] = customKey;
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("    PASSWORD");
        lcd.setCursor(0, 1);
        lcd.print(Str);

      }

      if (character == 3)
      {
        Serial.println(customKey);
        Str[9] = customKey;
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("    PASSWORD");
        lcd.setCursor(0, 1);
        lcd.print(Str);

      }

      if (character == 4)
      {
        Serial.println(customKey);
        Str[10] = customKey;
        activated = 1;

      }
      character = character + 1;
    }

    if (activated == 1)
    {
      /*Change your password below!!!
        Change each of Str[6], Str[7], Str[8], Str[9]*/

      // if (Str[10] = 'A' && ...)
      if (Str[10] == 'A' && character == 5 && Str[6] == '3' && Str[7] == '0' && Str[8] == '0' && Str[9] == '7' )
      {
        myservo.write(mot_max);
        lcd.clear();
        lcd.setCursor(4, 0);
        lcd.print("ACCEPTED");
        activated = 2;
        analogWrite(buzzer, 240);
        delay(250);
        analogWrite(buzzer, 200);
        delay(250);
        analogWrite(buzzer, 180);
        delay(250);
        analogWrite(buzzer, 250);
        delay(250);
        analogWrite(buzzer, LOW);
        delay(1000);

        lcd.clear();
        lcd.setCursor(4, 0);
        lcd.print("WELLCOME");
        delay(500);
        lcd.setCursor(2, 1);
        lcd.print("ELECTRONOOBS");
        delay(1000);

        lcd.clear();
        lcd.setCursor(3, 0);
        lcd.print("DOOR  OPEN");
        lcd.setCursor(2, 1);
        lcd.print("ELECTRONOOBS");

      }
      else
      {
        lcd.clear();
        lcd.setCursor(1, 0);
        lcd.print("PASSWORD ERROR");
        lcd.setCursor(3, 1);
        lcd.print("TRY  AGAIN");
        analogWrite(buzzer, 150);
        delay(3000);
        analogWrite(buzzer, LOW);
        character = 0;
        Str[6] = '-';
        Str[7] = '*';
        Str[8] = '*';
        Str[9] = '*';
        Str[10] = ' ';
        activated = 0;
        lcd.clear();
        lcd.setCursor(4, 0);
        lcd.print("PASSWORD");
        lcd.setCursor(0, 1);
        lcd.print(Str);
      }
    }
    if (activated == 2)
    {
      if (customKey == 'B' )
      {
        myservo.write(mot_min);
        activated = 0;
        character = 0;
        Str[6] = '-';
        Str[7] = '*';
        Str[8] = '*';
        Str[9] = '*';
        Str[10] = ' ';
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("    PASSWORD");
        lcd.setCursor(0, 1);
        lcd.print(Str);

      }
    }
  }
}

To re-iterate, With this code now the LCD screen displays PASSWORD but when I enter the password into the keypad only the first number changes value and it does not move to the second value.

you have not described any problems and you have not asked any questions .... voting to close as unclear what you're asking ..... please update your post .... include a description of expected behavior, observed behavior and any errors that you get

This is the issue I'm having (https://youtu.be/aWixfn1pe3A).

needs more re-callable subroutines. a lot more...

You would appear to have an excess of { here:
if (character ==2) {
{    <<<< Remove this

and then remove the excess } at the end of the code.
It would seem that this is affecting the logic of your code, as you've ended up inadvertently grouping some ifs within another if.

To avoid this type of situation, you need to be much more consistent with your code style (i.e. formatting/indentation).
Either use:
if (character ==2) {

or
if (character ==2)
{

but don't mix them. Otherwise you'll end up in a right old muddle.
If you keep your coding style consistent, then you'll see, in a flash, something that is out of place - merely by quickly scrolling through the code.

In addition, use the Tools ► Auto Format menu item in the Arduino IDE to correctly format your code and make it easy to read.

Changed the code with your suggestion but still receiving similar output issue.

As it is compiling, it is most likely a logical error within your code. I strongly suggest that you tidy the code, as the indentation is all over the place, and nigh impossible to follow.  If you indent it correctly then you'll see whether the if statements are grouped correctly and follow logical sequences. The indentation has become significantly worse since your last edit. You have, inexplicably, removed the indentation on large sections of the code

I apologize for the indentation but if it helps a very similar code that I'm using is on (http://www.electronoobs.com/eng_arduino_tut11.php). Thanks for the feedback.

Unfortunately, I could no longer follow your code, with the indentation removed, and gave up. Sorry. Good luck. :-)

I've correctly formatted your code for you, please check the edit that I made to your question, in order to see how you should have improved it. Cheers :-) Note that I have not changed the code, nor corrected it, as it would change the nature of your question.  Hopefully now people can easily work out what's wrong with the code and will post an answer.


text:
What precision can I expect by syncronising DS3231 with PC serial?
The point here is to syncronise a DS3231 module (on an Arduino) via serial port with NTP time by computer.
The problem here is that I'd like to know how much time is taken by the serial and I2C transmission, because if the PC sends the time at a time t1 and transmit it to the Arduino, the Arduino decodes it and sends it to the DS3231, the time t1 is received at a time t2 greater than t1.
PC (t1) => Serial(t1+x) => Arduino(t1+x+y) => I2C(t1+x+y+z) => DS3231(t2=t1+x+y+z)

t1 -> NTP time recorded by PC
x  -> Time taken by serial transmission
y  -> Time taken by arduino buffering/processing
z  -> Time taken by I2C transmission at 100kHz
t2 -> Time when message is received by DS3231

Is it negligible for a precision at millisecond?
I found a table on Wikipedia that displays time per bit per baudrate. I am planning to use a baudrate of 57600.
I tested offset using a simple echo program available here at 300 baud:
String buff="";

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

void loop() {
  if(Serial.available())
  {
    while(Serial.available())
    {
      buff += char(Serial.read());
    }
    Serial.print(buff);
    buff = "";
  }
}

What Arduino are you using?

I am using an arduino Uno or Nano with an ATMega238P

How is it "faster than expected"? What are you sending, and how are you measuring / calculating how fast it should be?

How is the exact baud rate relevant to time synchronization? You have an NTP client, you are not going to use the serial port itself as a time source, are you? Please, clarify your question and clearly state what you are trying to achieve.

@EdgarBonet I think the concern is that the PC has time X and transmits it at X. The Arduino finishes receiving that stated time at Y - the difference between X and Y being the time taken to do the transfer through serial. If you know Y-X then you can add (Y-X) to X to get the time when the transfer has completed.

@Majenko yes, that's what I'm trying to ask, sorry for not being clear.

@Majenko I've done a simple echo programm that reads from serial and returns the message at 300bauds
So, according to wikipedia, it takes ~3ms to transmit a single bit at 300 bauds, if I transmit 22 characters, the time will be 2228*3 = 1056ms or ~1s to send and read the data back (that's what I get by testing it, so I was wrong in my question sry for that)
In my case I have 35 characters to transmit ; 7.4 micro seconds per bit at 57600 bauds ; so the time taken to send will be 7.4 * 35 * 8 = 2072 so that's 2ms offset.
Sorry for asking a question that I was able to answer by myself...

8N1 is 10 bits not 8 bits. One start bit, eight data bits, and one stop bit. And then there may be gaps between each byte as well. And then of course there is buffering in the Arduino to throw into the mix.

Add the explanation of "faster than expected to your question". The question should stand by itself without needing to search the comments for missing info. "Sorry for asking a question that I was able to answer by myself" That's no problem, just write an answer to your question to help others who have the same question. In fact, this is encouraged on Stack Exchange.

@Majenko If I understand correctly, I have to add 2 more bits to each byte to get an idea of the transfer time, that would do 7.4 * 35 * (8+2) ~ 2.6ms offset

@per1234 the "faster than expected" was a mistake from me, I belived that the serial transmited data faster than it should, but I was wrong.
Btw thanks to everyone trying to help me :)

I second the general idea of Dmitry Grigoryev’s answer: your best option
is to measure a round-trip time and use half of that as an estimate of
the one-way time. Otherwise you will have too many unknowns. For
example, you don't know how long your OS takes to process the outgoing
message and send it through USB to the USB/serial bridge inside the
Arduino. As an optimization, I would send the time information and the
synchronization strobe as two separate messages, with the latter being a
single byte. This way the latency of the synchronization strobe (the
only latency that matters) is minimized.
Latency of serial communication
I did some research to try to nail this one down. At 57600 bits/s,
the theoretical time per bit is about 17.4 µs, as stated in the
Wikipedia article you linked to. In practice, the actual time can be
rounded more or less depending on the UART capabilities and the clock
speed. You did not specify what Arduino you are using. In the following,
I will assume an AVR-based Arduino clocked at 16 MHz, which is
presumably the most common.
The UART in the AVR constrains the bit time to be a multiple of
8 CPU cycles, i.e. 0.5 µs when running at 16 MHz. The
closest you can get to the ideal timing is therefore 17.5 µs.
However, the Arduino core library has a hard coded compatibility
exception which, in this very specific case, sets the bit
duration to 17 µs instead. Since you are presumably configuring the
port at /8N1, which is the default, the time per byte is then
170 µs (1 start bit, 8 data bits and 1 stop bit).
Actually, when transmitting a single byte, the transmission time is
slightly less than that. The UART can report the byte as received as
soon as it is done taking the required three samples of the stop bit,
which happens slightly after the middle of that stop bit. The
theoretical time it takes to transmit a single byte is then about
9.56 times the single-bit duration, or about 162.56 µs at
57600/8N1.
I did a simple loopback test with the TX and the RX of my Uno shorted
together. I used a timer to time the execution of the following code:
Serial.write('.');
while (!Serial.available()) continue;

The result was 182.38 µs, or about 10.73 bit durations. A
fraction of this time is taken by the execution of Serial.write() and
Serial.available(). In order to get closer to a bare hardware latency,
I also timed a low-level version of the two lines above:
UDR0 = '.';
while (!bit_is_set(UCSR0A, RXC0)) continue;

This has to be run with interrupts disabled. The execution time was now
between 164.19 and 164.81 µs, i.e. 9.66 to 9.69 bits
durations.
Alternative approach
As a final note, I would recommend you consider buying a GPS module with
a 1PPS output. This 1PPS is a 1 Hz logic signal with the rising
edges tightly aligned to the start of the UTC seconds. You typically get
an accuracy in the tens of nanoseconds. Since this is just a logic
signal that you can easily compare with the 1 Hz output of your RTC
module, you get rid of all the latency issues that come with computers
(your NTP client), or data links (USB, serial, I2C).

Thank you for the answer :) ; gps utc time sync might also be a good option for precise time syncronisation

Transmission time will certainly not be negligible. To estimate it, you could use the roundtrip delay calculation, which is (roughly) how the NTP protocol is implemented in the first place.

at PC time T1, PC sends current time T1 to Arduino via UART
Arduino sets the time T1 in DS3231 via I2C
Arduino reads the time T2 from DS3231 via I2C
Arduino sends the time T2 to PC via UART. This happens at time T3 from PC's point of view.

Now the PC can estimate the half-roundtrip delay R as (T3-T2)/2. See the following chart which denotes current time form POW of PC and RTC
        |--UART--|--I2C--|--------|--I2C--|--UART--|
PC      T1              T1+R     T2+R           T3=T2+2R
DS3231  -                T1       T2              T2+R

Next, at time T4, the PC sends the value (T4+R) via UART. This will result in  DS3231 to be set to (T4+R), which happens exactly R time after T4, so that both clocks are now set to the same value.
Estimation of R can be repeated several times. In this case you can calculate the standard deviation which tells you how much "jitter" your clocks have.

This is the way I'll go for my project, I think it is a cheap way to get a correct precision of a millisecond :)


text:
How does Arduino memorize the last bytes from Bluetooth HC-05?
I have made a home automation project.
Description: Light on, off through HC-05 Bluetooth module and my Android app. The problem is when the power is gone, the system stops, that's OK. After that, when the power comes back, the system remains off, as because of no storage of the value.
Please any one help me, that how to store Bluetooth data on EEPROM on Arduino. My simple code looks like...
#include <EEPROM.h>
#define ledPin 7
int state = 0;

void setup() {
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
  Serial.begin(9600); // Default communication rate of the Bluetooth module
}

void loop() {

  if(Serial.available() > 0){ // Checks whether data is comming from the serial port
    state = Serial.read(); // Reads the data from the serial port
  }

  if (state == '0') {
    digitalWrite(ledPin, LOW); // Turn LED OFF
    Serial.println("LED: OFF"); // Send back, to the phone, the String "LED: ON"
    state = 0;
  }
  else if (state == '1') {
    digitalWrite(ledPin, HIGH);
    Serial.println("LED: ON");;
    state = 0;
  }
}

Don't shout next time! Also format the code correctly.

Have you tried to use the EEPROM examples from the Arduino IDE? There is a library for using the EEPROM. Do you have any specific problem with it?

Sir you didn't used EEPROM functions, you just initialized them. For example

EEPROM.read();
EEPROM.write();

if you use these function then your issue will be solved out..


text:
Using arduino mega is making my cnc claw buggy. Help
I have three nema 23 steppers with one 8 channel relay(all the pins used) powering two dc motors and 4 IR sensors for feedback on the machine.
The problem is my machine is working fine for only 2 to 3 minutes until it just resets itself in the middle of the routine and crashes my whole system.
I am using 1/2 step microstepping with TB6600 stepper driver.
Also my arduino is mega 2560, maybe thats the problem I don't know about.

Here I am attaching the code
const int dirPin1=2;
const int stepPin1=3;
const int dirPin2=4;
const int stepPin2=5;
const int dirPin3=6;
const int stepPin3=7;
int del=1;
void setup() {
 pinMode(2,OUTPUT);
 pinMode(3,OUTPUT);
 pinMode(4,OUTPUT);
 pinMode(5,OUTPUT);
 pinMode(6,OUTPUT);
 pinMode(7,OUTPUT);
 pinMode(8,OUTPUT);
pinMode(9,OUTPUT);
pinMode(10,OUTPUT);
pinMode(11,OUTPUT);
pinMode(12,OUTPUT);
pinMode(13,OUTPUT);
pinMode(14,OUTPUT);
pinMode(15,OUTPUT);
pinMode(16,INPUT);
pinMode(17,INPUT);
pinMode(18,INPUT);
pinMode(19,INPUT);
digitalWrite(8,HIGH);
digitalWrite(9,HIGH);
digitalWrite(10,HIGH);
digitalWrite(11,HIGH);
digitalWrite(12,HIGH);
digitalWrite(13,HIGH);
digitalWrite(14,HIGH);
digitalWrite(15,HIGH);

}
void picker_up(){
  digitalWrite(8,HIGH);
  digitalWrite(9,HIGH);
  digitalWrite(10,LOW);
  digitalWrite(11,LOW);
  delay(570);
  digitalWrite(8,HIGH);
  digitalWrite(9,HIGH);
  digitalWrite(10,HIGH);
  digitalWrite(11,HIGH);
  delay(100);
}
void picker_down(){
  digitalWrite(8,LOW);
  digitalWrite(8,LOW);
  digitalWrite(10,HIGH);
  digitalWrite(11,HIGH);
  delay(320);
  digitalWrite(8,HIGH);
  digitalWrite(9,HIGH);
  digitalWrite(10,HIGH);
  digitalWrite(11,HIGH);
  delay(100);
}
void claw_close(){
  digitalWrite(12,LOW);
  digitalWrite(13,LOW);
  digitalWrite(14,HIGH);
  digitalWrite(15,HIGH);
  delay(100);
  digitalWrite(12,HIGH);
  digitalWrite(13,HIGH);
  digitalWrite(14,HIGH);
  digitalWrite(15,HIGH);
  delay(100);
}
void claw_open(){
  digitalWrite(12,HIGH);
  digitalWrite(13,HIGH);
  digitalWrite(14,LOW);
  digitalWrite(15,LOW);
  delay(100);
  digitalWrite(12,HIGH);
  digitalWrite(13,HIGH);
  digitalWrite(14,HIGH);
  digitalWrite(15,HIGH);
  delay(100);
}

void loop() {
  // put your main code here, to run repeatedly:
digitalWrite(dirPin1,HIGH);
digitalWrite(dirPin2,HIGH);
digitalWrite(dirPin3,LOW);
for(int i=0;i<=1200;i++){
  digitalWrite(stepPin1,HIGH);
  digitalWrite(stepPin2,HIGH);
  digitalWrite(stepPin3,HIGH);
  delay(del);
  digitalWrite(stepPin1,LOW);
  digitalWrite(stepPin2,LOW);
  digitalWrite(stepPin3,LOW);
  delay(del);
}
for(int i=1;i<=400;i++){
  digitalWrite(stepPin1,HIGH);
  delay(del);
  digitalWrite(stepPin1,LOW);
  delay(del);
}
delay(1000);
picker_down();
claw_open();
claw_close();
picker_up();
delay(2000);
digitalWrite(dirPin1,LOW);
digitalWrite(dirPin2,LOW);
digitalWrite(dirPin3,HIGH);
for(int i=1;i<=400;i++){
  digitalWrite(stepPin1,HIGH);
  delay(del);
  digitalWrite(stepPin1,LOW);
  delay(del);
}
for(int i=0;i<=1200;i++){
  digitalWrite(stepPin1,HIGH);
  digitalWrite(stepPin2,HIGH);
  digitalWrite(stepPin3,HIGH);
  delay(del);
  digitalWrite(stepPin1,LOW);
  digitalWrite(stepPin2,LOW);
  digitalWrite(stepPin3,LOW);
  delay(del);
}
delay(2000);
}

I am not getting why this is happening. Or do I need some more electronic components  included in the machine and I know I could have used mosfets to control the motors but I am just way too lazy.
I used uno before this and it used to work fine, so should I just go back to using it?
Also I have modified the code to be compatible with the uno again so please bare with the pin numbers.

I don't believe there's any reasonable way to answer the question with the information provided. It could be literally anything. I would not recommend doing stepper driving "by hand" when there are libraries available. At the very least you'd need to include a schematic.

I'm going out on a limb here with no schematic, but a common reason for resetting is low voltage caused by too much current draw. "I know I could have used mosfets to control the motors but I am just way to lazy." suggests a possible cause. Are your motors powered through the Arduino?

I am using external power sources for everything even the relay is not powered by the arduino mega

add some debugging code

Still not much to go on (this is a block diagram, not a schematic). Since there's essentially no code other than digital writes, I would suspect an electrical problem.

I actually thought of using a stepper motor library but the library accelstepper blocks every other actuator to make the stepper rotate which means my two motors that are running together will not work.
@DaveNewton

Non AccelStepper is not blocking. You just have to use it right by setting the target position and then execute the run function of the corresponding accelstepper objects very regularily and fast, so that they don't miss a step. Actually the library is meant for that. It also has a blocking function, but more for completeness and special situations. The non-blocking way is actually the intended way of use

I actually kind of figured out the problem on my own till now and it is related to using the relay to power my motors as arduino is not able to handle the relay switching so I am using a slave arduino to not mess up the the system.

If you solved the problem ypu can write an answer to your own question. That way your oearninga might help others in the future

Ok so first of all I ditched the 12 volt and 5 volt motor(this one was a hacked tower pro servo) and used two pneumatic cylinders as I happen to have compression engines in my firm to make the actuator. While now its more rugged but better. I also had solved the problem I asked about, this was done by using a slave arduino nano so I just made the use of serial communication to fire the relay subroutine onto the nano this way even if my relay throw some errors nothing would go wrong with my system. Also another mistake I did was power up the relay and motor together.


text:
Serial and I2C not working together
I have very peculier problem. When I run this code SSD1306 fails to initialize. Output at serial console is:
20:26:33.194 -> MPU6050 OLED demo
20:26:33.532 -> SSD1306 allocation failed
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_MPU6050.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_Sensor.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3D ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32

Adafruit_MPU6050 mpu;
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

int count =0;

void setup() {

  Serial.begin(9600);
  while (!Serial);
  Serial.println("MPU6050 OLED demo");

  if (!mpu.begin()) {
    Serial.println("Sensor init failed");
    while (1)
      yield();
  }
  Serial.println("Found a MPU-6050 sensor");

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) { // Address 0x3C for 128x32
    Serial.println(F("SSD1306 allocation failed"));
    for (;;)
      ; // Don't proceed, loop forever
  }

  display.display();
  delay(500); // Pause for 2 seconds
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setRotation(0);
}

void loop() {
  sensors_event_t a, g, temp;
  mpu.getEvent(&a, &g, &temp);

  display.clearDisplay();
  display.setCursor(0, 0);

  display.println("Accelerometer - m/s^2");
  display.print(a.acceleration.x, 1);
  display.print(", ");
  display.print(a.acceleration.y, 1);
  display.print(", ");
  display.print(a.acceleration.z, 1);
  display.println("");

  display.println("Gyroscope - rps");
  display.print(g.gyro.x, 1);
  display.print(", ");
  display.print(g.gyro.y, 1);
  display.print(", ");
  display.print(g.gyro.z, 1);
  display.println("");
  display.display();
  delay(100);
}

But when I run this code, without displaying gyro everything runs fine. Adafruit logo is displayed and then followed by regular accelerometer data.
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_MPU6050.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_Sensor.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3D ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32

Adafruit_MPU6050 mpu;
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

int count =0;

void setup() {

  //Serial.begin(9600);
  //while (!Serial);
  //Serial.println("MPU6050 OLED demo");

  if (!mpu.begin()) {
    //Serial.println("Sensor init failed");
    while (1)
      yield();
  }
  //Serial.println("Found a MPU-6050 sensor");

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) { // Address 0x3C for 128x32
    Serial.println(F("SSD1306 allocation failed"));
    for (;;)
      ; // Don't proceed, loop forever
  }

  display.display();
  delay(500); // Pause for 2 seconds
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setRotation(0);
}

void loop() {
  sensors_event_t a, g, temp;
  mpu.getEvent(&a, &g, &temp);

  display.clearDisplay();
  display.setCursor(0, 0);

  display.println("Accelerometer - m/s^2");
  display.print(a.acceleration.x, 1);
  display.print(", ");
  display.print(a.acceleration.y, 1);
  display.print(", ");
  display.print(a.acceleration.z, 1);
  display.println("");

  display.println("Gyroscope - rps");
  display.print(g.gyro.x, 1);
  display.print(", ");
  display.print(g.gyro.y, 1);
  display.print(", ");
  display.print(g.gyro.z, 1);
  display.println("");
  display.display();
  delay(100);
}

Now, while debugging when I disable Serial logs and comment all Serial.print then the above code runs properly, logo is displayed, accelerometer and gyro both the data are displayed on OLED properly.
Compiler Log for non-working code is:
Sketch uses 21980 bytes (71%) of program storage space. Maximum is 30720 bytes.
Global variables use 761 bytes (37%) of dynamic memory, leaving 1287 bytes for local variables. Maximum is 2048 bytes.
The setup I am using as Arduino Nano, MPU6050 connected over I2C (address 0x68), SSD1306 based 0.96" 128x64 display over I2C (address 0x3D). I am using A4 and A5 pin of Arduino Nano as I2C. Both device are connected over same bus. I am using breadboard for testing.
PS: Both the code compiles without error or warning

Where is the difference between those sketches?

Made the corrections, I made mistake while copying pasting the comments

The SSD1306 uses a lot of RAM. Pretty much all your RAM.  Serial also uses quite  a bit of RAM.  The two struggle to work together.
There is a special "text only" SSD1306 library that uses considerably less RAM: https://github.com/greiman/SSD1306Ascii

Thank you Majenko...
It was low RAM problem.
SSD1306 takes 1K, with MPU6050 the and serial print which I have included the remaining RAM is 5 bytes only, hence the initialization issue.
I followed simple guideline to reduce RAM footprint
Read this thread https://stackoverflow.com/questions/8649174/checking-memory-footprint-in-arduino
Code to print available SRAM.
Serial.print(availableMemory());

// free RAM check for debugging. SRAM for ATmega328p = 2048Kb.
int availableMemory() {
    // Use 1024 with ATmega168
    int size = 2048;
    byte *buf;
    while ((buf = (byte *) malloc(--size)) == NULL);
        free(buf);
    return size;
}


text:
What happens if we connect GND and +5v?
What will happen if I by mistakenly connect GND and +5v of an Arduino Nano? Is there any protection for it? Or will it get short and fry out something?

You'll probably fry the voltage regulator, I don't believe it's protected.

How to check whether its fried

The Magic Smoke™ will escape.

Actually, I have really burned my Arduino Nano and What should I do I don't know

And my CH340G was smelling

Throw it away and get a real one.

if you're handy with SMD work, you can swap out a blown regulator or diode on an MCU

One more thing I programmed it to behave as a voltage regulator and I was saying it send data to my PC Now when I plug it with a battery first the tx and led get really high for a sec and then tx stays on for sometime then it stops and then the led starts blinking very fast and after a few secs it gets dim

It maybe the Ch340g or the diode

I think I burned my CH340G because yesterday when I plugged it into my computer there was Hardware named Ch340g in the coms but after issue it isn't there and even it was even smelling quite a bit !

Depending on how you are powering your board different things will happen.

If you are powering through USB from a PC the PC should, according to the USB standard, detect an over-current situation and disconnect the power from the port. However some don't, in which case see point 2.
If you are powering through USB from a USB power supply (phone charger, etc) the charger's output voltage will drop to near zero and the current will hit maximum for the supply. This may or may not damage the supply, but either way it's not a nice thing to do.
If you are powering from a small external battery (say a 9V PP3 battery) things will start to get hot. The voltage regulator will most likely overheat, the battery may overheat, but not much damage should occur - a small PP3 battery can't provide much current.
If you are powering from a large external battery (e.g., Li-Ion cells) or an external power supply, things will get more nasty. The on-board regulator will overheat. If it isn't thermally protected (genuine Arduinos should be, but cheap Chinese clones may not be) then it will fail and you will find smoke coming out of the regulator. At this point the regulator is dead. If the board contains a polarity protection diode that may fail in the same way (I have seen these blow clean off the board before). Physical damage (blackening and blistering) may occur to the PCB as well.

So all in all shorting +5V to GND is never a good idea.

According to this image and this datasheet, that nano's voltage regulator is internally limited.
That means it will heat up and shut down if over-loaded. Of course, your nano could use a less-effective regulator and simply smoke away. It's also possible that the 5205 would not clamp in time to prevent damage on an instant dead-short. Generally, i've found the arduino boards to be fairly resilient, compared to other MCUs, so you can probably get away with it at least a time or two.
Dead shorting is never a good idea even if you can get away with it because there can be incremental (as opposed to catastrophic) damage. You might cause instability in the regulator, and you might limit it's ability to limit volts. Those problems might not be revealed instantly, but instead at the worst (unexpected) time.
EDIT:
based on your edit, it sounds like your "FTDI" is fried, but not necessarily your MCU.

I think I burned my CH340G because yesterday when I plugged it into my computer there was Hardware named Ch340g in the coms but after issue it isn't there and even it was even smelling quite a bit !

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


text:
Programming Micro controllers using Arduino ISP
Can I burn my Arduino Code into this:
http://www.microchip.com/wwwproducts/en/ATSAM3A4C
or something similar by just using just the Arduino ISP?

Arduino ISP is meant to program AVR microcontrollers. AFAIK, almost every AVR can be programmed this way, but other microcontroller families (ARM, PIC...) will most probably not work.

Page does nog exist (404).
Also, to run actual Arduino code on it, you'll most likely have to port the Arduino library, if this hasn't been done before.
You may opt for something as easy as a teensy 3.2, they probably meet your requirements and work well in combination with Arduino.
Or fetch one of the newer Arduino models that have comparable microcontrollers
If you still want an M3 (without development board?) you'll be entering a somewhat advanced usecase, in which you probably don't even want to rely on or use Arduino. There are far better IDE's.

Can you go to that website please.

I want to use that chip using the Arduino ISP

Ah okay, is that chip mounted on a board/PCB? Or are you simply looking for something like the due https://www.arduino.cc/en/Main/arduinoBoardDue which has a cortex m3

On a adapter board.

Hmm, the datasheet doesn't mention ICSP,  I don't think it's compatible, since ARM based boards are mich different.

So with what kind of boards do you think I can use.

Can we do something like this

Read the section about bootloader ROM on this chip.

I don't know about that chip I think this one also can be done as some of the other chips can be programmed using the Arduino ISP  I think it can be even done for this one. This one uses an AVR ISP Programmer while we are using the Arduino one but as they have similar working It is maybe possible. For example this one


text:
How does Arduino WiFi Shield connect to Blynk and How can I use ESP Module to connect to blynk?
I was actually quite impressed how easily Blynk gets connected to Arduino. So I had a doubt how does Arduino WiFi Shield allow Arduino Uno to connect to blynk ? And my second doubt is how can I use the ESP boards to connect to blynk using Windows10 ( for steps ) ?
Thank You.

how does Arduino WiFi Shield allow Arduino Uno to connect to blynk

Blynk is just a web service. The WiFi shield connects your board to the internet and sends data to that web service. The Blynk app is just an interface to that web service.

how can I use the ESP boards to connect to blynk using Windows10?

That makes no sense. You can connect an MCU to Blynk through something like an ESP8266 board (or program the ESP8266 board directly to communicate with Blynk). It is merely a network interface.
Windows 10 is not an MCU, and you already have an internet connection on it. If you want to communicate with Blynk from Windows 10 I suggest you look at the documents to see if there is an API you can use from your own programs, or a web interface you can view in your browser of choice.
Windows 10 and ESP8266 are two completely alien concepts.

authors: Мадияр Даниялов


text:
How to use the HC-05 properly?
It all started when I was working on my Arduino project, which involves an Arduino Nano, an HC05 module and a bunch of sensors (DHT 11, soil moisture and LDR) with Blynk App. Everything worked as it should (compiled properly) but there was no transfer of data (HC05 was paired).
At that time before pairing, the HC05 was blinking rapidly and after pairing it was blinking twice rapidly every 5 seconds. Note I connected everything as the example said... (You know HC05s TX RX to HW Serial Pins vice-versa).
So later I tried again with everything stripped out (took out all sensors and just the barebones sketch) and added the button widget in the app to control the Nano's onboard LED). Again everything worked as it should but there was no connection between the HW and the Blynk APP (it was not switching on the LED).
Then I tried with an another Bluetooth app and it didn't work as it should. Then I got to know something's wrong with the board itself. So I tried to boot it into AT command mode with this Guide. But it wasn't accepting any commands (NO replies).
So what do I do?
NOTE: I didn't get any relevant question so sorry for that. And do you need anything else?
Edit: It worked. I dont really know how. I think there was maybe a problem with the voltage divider but not sure. Thanks for your time and answers.

Maybe you use the wrong baudrate with your hardware serial. Your tutorial states, that 38400 baud is the default, but I found other sources (HC-05), that say the default is 9600 baud (which is also true for my HC-06 modules). Try 9600 baud and if it still doesn't work try some other standard baudrates.

I tried 9600 also....

This worked perfect for me HC-05
Try it out.

Did it work out?

Try enetering AT mode and change the default baudrate for HC-05. Maybe use some higher baudrate, it improves communication. Also, check if you’re doing the serial reading properly.


text:
Distance Readings Getting Manipulated When Calling Unrelated Function
I'm using a Lidar Lite v3 to measure the distance from one object to another. I pass the results to the serial monitor to see what that distance is. It appears that when I call an unrelated function, the distance that's being printed seems to be roughly subtracted by 512.
To describe exactly what I mean, this is my function:
int pulseWidth = pulseIn(monitorPin, HIGH); //begin measurement of time
int distanceConverted = (pulseWidth / 10); // 10usec = 1 cm of distance
Serial.println(distanceConverted); // Print the distance

and it gives me an output of this (which is correct):
780 cm
787 cm
790 cm
794 cm
782 cm
787 cm
790 cm
786 cm
790 cm
780 cm
788 cm
784 cm

I'm using these distances to control LED lights and a speaker, and call this function to do so:
void lights(int distanceConverted)
{
    if (distanceConverted < 1000 && distanceConverted > 500)
    {
      digitalWrite(yellowLEDPin, HIGH);
      delay(20);
      tone(8, 35000, 250);
    }

    else if (distanceConverted <= 500)
    {
      digitalWrite(redLEDPin, HIGH);
      delay(20);
      tone(8, 40000, 250);
    }
}

However, when this is called (and I call the function after I print the distance values), these are the results I get:
268 cm
267 cm
266 cm
267 cm
269 cm
267 cm
265 cm
267 cm
266 cm
266 cm
267 cm
264 cm
269 cm

When I try to account for this and multiply by three, my values become even more off and seem to be multiplied by ten:
int distanceConverted = (pulseWidth / 10)*3; // 10usec = 1 cm of distance

New Values:
2640 cm
2673 cm
2634 cm
2649 cm
2592 cm
2619 cm
2631 cm
2628 cm
2631 cm
2673 cm
2634 cm

At first I thought it might have been the delays within the lights() function manipulating the readings, but even after commenting them out I still get the same results. I don't know how the function could be throwing my values off.
Edit: I noticed at when the program is first looping, the 512 gets subtracted after the first time I run through the lights() function.
761 cm <- first value from sensor, correct
312 cm
308 cm
308 cm
309 cm
308 cm
307 cm
307 cm
309 cm
308 cm
308 cm

When I comment out the tone() function, that seems to fix my problem. Could that function be overwriting a bit in the memory register causing it to subtract 512 from my distanceConverted variable?

Messing up a single bit in a register seems quite far fetched to me. Could you also post this tone function - as you seem to indicate it being the culprit?

Tone is a standard arduino function.

The tone function uses timer interrupts to toggle a GPIO pin to make noise. That's quite intense from a CPU point of view and is most likely skewing the timing of the pulseIn function.
I would suggest not using tone if you can help it. Maybe change the frequency of a PWM output to something suitable and use analowWrite to create a 50% duty square wave.
Also learning how to use the Input Capture peripheral of the MCU (read the datasheet) will enable you to perform asynchronous sampling of your pulses and obtain much more accurate results.


text:
Cannot bootload again after changing the board?
We are so tired and would like to get help with this. We are trying to bootload using the arduino Uno.
We have an atmega 328p smd , that we are trying to bootload. We have connected all the right pins, added to the boards.txt the  "Atmega328 on a breadboard(8mhz internal clock)".
Then I have chosen from the "board" menu, this option (internal clock), and uploaded the program. it worked .
Later, I wanted to try and bootload for external clock so I chose from the boards menu the pro mini with 5v board.(is it wrong?)
Not only that I got an error, now, I can't bootload the internal clock again !!
Why can't we bootload again? Did we damage something? Can it be reset again?
How can you bootload for external 16Mhz ??
error :
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again

When burnt the Pro Mini bootloader did it work?

Check This out my problem have been solved.
https://www.youtube.com/watch?v=IYi815scN2A&ab_channel=LearnItAllAcademy

Please check capacitor value it must be in between 18pF to 20pF(The capacitors used for crystal)

Not only that I got an error, now, I can't bootload the internal clock again !

You need an external clock source, such as a crystal and two capacitors. Once you switch the fuses to the external clock it won't work any more unless you have such a clock.
I have a bootloader uploader sketch that also provides a clock signal if you need it.


text:
how do I power my motor shield without an arduino uno?
I want to power my motor shield without my UNO. I have connected the +ve and -ve terminals resulting in lighting up of the LED.
Is there any way to control the motors in this arrangement from the Arduino?

Welcome!
I'm not sure I understand what you are asking because what you are trying to do doesn't make much sense.
The motors connected to the motor shield are controlled by the output pins of the Arduino that the motor shield is plugged in to.
You could run jumper leads from an separate Arduino into your unplugged motor shield, but that's just extending what you already have.  You really do need some form of controller, not necessary a microprocessor, otherwise how can you go forwards and backwards?
Is the problem you have put the Arduino into a plastic case and you can't plug the motor shield in any more?  If so get a set of long male to female connectors (they look like the Arduino connectors) and use them as extensions.
Is the problem you have a different format of board and can't plug it in? If so use the wires method to form the correct connections.
I hope that answers your question, if not please try and explain what I'm misunderstanding.

Thanks a lot for that answer and yes my problem actually is I cant plug in the motor shield directly. so i wanted to know is it necessary to connect all the pins or only some of them will do the work

Right - Order some connectors something like (http://www.hobbytronics.co.uk/arduino-header-10pin?utm_source=google&utm_medium=googleshopping&utm_campaign=googlebase&gclid=CJym0NK4nc0CFeIp0wodDAoKMQ) you need two different lengths.  OR connect ribbon cables/wires from the Arduino to the Shield and that should sort it out.

Which all pins should i connect ??

Only some of them do the work but you would need to look it up in your datasheet for the shield because they can be different.  You also have to remember to connect the grounds together on your two supplies (only -ve not +ve!!) otherwise things won't work.  Whats the shield make and model?

I have a motor shield with L293D micro-controller

Thanks a lot I will check out the datasheet and try to figure out. Thanks a lot

Since you have not revealed exactly WHICH motor shield you are asking about, nobody can answer your question. It depends on exactly how YOUR motor shield is designed.  It does not benefit you to withhold the identity of the board you are asking about. It makes it impossible for us to help you.

I have a motor shield by DK electronics


text:
QuadCopter PID using MPU6050
I am using Arduino Uno, with PID library and Jeff Rowberg library for MPU6050 i.e I2Cdev.h, MPU6050_6Axis_MotionApps20.h.
There is one PID for each axis i.e Pitch and Roll, I am getting output that wobbles and is unstable. I don't know whether my code is wrong or something else.
Errors which I feel are:

I am using Esc.write(), I know Microseconds should be used but it feels very light, even it doesn't wobble.
Kalman Filter not used, but I am getting the pitch, roll, yaw.
PID library (By Brett Beauregard) not suitable for Quadcopter.
else if (mpuIntStatus & 0x02) // wait for correc available data length, should be a VERY short wait
         while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
This statement in loop making loop slow, it's written in its comment and maybe it making pid compute upset

Please look at code.
#ifdef OUTPUT_READABLE_YAWPITCHROLL
        // display Euler angles in degrees
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
        yaw = ypr[0] * 180/M_PI;
        pitch = ypr[1] * 180/M_PI;
        roll = ypr[2] * 180/M_PI;

        Input = pitch;
        RInput = roll;
        myPID.SetTunings(Kp,Ki,Kd);
        myPIDR.SetTunings(RKp,RKi,RKd);

        //Sample Time is 10 for both PID.

             myPID.Compute();
              myPIDR.Compute();

        if(armed == 1) {
          int m1 = throttle.toInt() + Output;
          int m2 = throttle.toInt() + ROutput;
          int m3 = throttle.toInt() - Output;
          int m4 = throttle.toInt() - ROutput;

 int angle1 = map(m1, 0, 100, 0, 180);
 ESC1.write(angle1); //FRONT PITCH+
 int angle2 = map(m2, 0, 100, 0, 180);
 ESC2.write(angle2); //LEFT ROLL+
 int angle3 = map(m3, 0, 100, 0, 180);
 ESC3.write(angle3); //BACK PITCH-
 int angle4 = map(m4, 0, 100, 0, 180);
 ESC4.write(angle4); //RIGHT ROLL-
        }
    #endif

Kp = 0.25, Ki = 0.04, Kd = 0.05 |
RKp = 0.25, RKi = 0.04, RKd = 0.05
From testing: if I shake my Quadcopter fast by hand it behaves like PID is activated and works as wanted, but suddenly after a couple of seconds again feel loose, may be PID compute become upset

Quadcopters usually use 2-PID loops per axis, a rate loop and an angle loop.
Your quadcopter needs to be very aggressive about its rate of rotation but relatively relaxed about how quickly it returns its angle to the center so it doesn't overshoot. With a single PID it will either be too slow to correct or overshoot and oscillate with no "usable" range of tunings in-between, because in order for its outputs to be strong enough to control the quad it will necessarily be too aggressive to smoothly align with the center position. There is a lot of math that explains why this cannot be achieved with a single loop more rigorously if you care to look into it.
So try setting it up with a PitchAngle PID whose output is the setpoint of a PitchRate PID loop whose output goes to the motors, and similarly with the Roll.
That is only one possible problem though, there is a huge number of things that could be wrong. Are your pitch and roll measurements angles to the horizon or euler angles? how fast is your loop running? Are oscillations induced by the motors causing your accelerometer reading/attitude filter combo to be unusable? Are the PID parameters correct? Is the accelerometer's bias calibrated? Is the gyro drift calibrated? Are all you ESC's calibrated the same way?


text:
ESP8266 reset problem
I am trying some AT commands with ESP8266 but it resets continously when it stop resetting, i can't get any response from ESP8266.
Example :
AT

OK
AT+CWMODE=1

OK
AT+CIPMODE=0

OK
AT+CIPMUX=1

OK
AT+CWJAP="..",".."

 ets Jan  8 2013,rst cause:4, boot mode:(3,1)

wdt reset
load 0x40100000, len 612, room 16
tail 4
chksum 0x12
load 0x3ffe8000, len 788, room 4
tail 0
chksum 0x50
load 0x3ffe8314, len 264, room 8
tail 0
chksum 0x4a
csum 0x4a

2nd boot version : 1.1
  SPI Speed      : 40MHz
  SPI Mode       : QIO
  SPI Flash Size : 4Mbit
jump to run user1

sd
ready

 ets Jan  8 2013,rst cause:4, boot mode:(3,1)

wdt reset
load 0x40100000, len 612, room 16
tail 4
chksum 0x12
load 0x3ffe8000, len 788, room 4
tail 0
chksum 0x50
load 0x3ffe8314, len 264, room 8
tail 0
chksum 0x4a
csum 0x4a

2nd boot version : 1.1
  SPI Speed      : 40MHz
  SPI Mode       : QIO
  SPI Flash Size : 4Mbit
jump to run user1

sd
ready

I have upgraded my firmware and I tried GPIO0 and GPIO2 are active but it still does not response fine. It worked yesterday but today it is working like crazy..

What power source are you using?

Arduino's power source

Which Arduino?  (if it's not a genuine Arduino please provide a link not just the model).

It is arduino uno aliexpress clone

Where is the link?

Arduino için UNO R3 MEGA328P CH340 CH340G UNO R3   USB KABLOSU
http://s.aliexpress.com/EZNfmaa

That link doesn't get me anywhere useful.

Try this please, http://tr.aliexpress.com/item/high-quality-UNO-R3-MEGA328P-CH340-CH340G-for-Arduino-UNO-R3-NO-USB-CABLE/32394695799.html?spm=2114.010208.3.39.Zxfgbq&ws_ab_test=searchweb201556_9,searchweb201602_5_10017_10034_10021_507_10022_10020_10018_10019,searchweb201603_7&btsid=2d1749bf-72f9-478f-bfc6-2c8c15b51787

Wild surmise, because with no schematic or BOM it's impossible to say, but I would guess the 3.3V regulator isn't up to the job. On a genuine Arduino you have 150mA to play with. On that board it's anyone's guess.

yes . I had the same problem and the capacitor is solved the problem

Arduino can not provide enough current for ESP8266 operations. Use external 3.3V power supply, I would recommend 500ma. Also don't forget to put a small cap between vcc and ground. 100uf should do it.

Okay i will try but why sometimes esp8266 works fine, sometimes doesnt work i cant understand it. Can it be broken too ?

not likely, in extreme cases yes but its more probable that its current issue . If you can issue AT commands, the module itself is fine. Acording to ESP8266 power consumption chart, in transmit mode it takes +100ma, Arduino 3.3v pin can output about 50ma. So, everything is fine until you try to connect or turn on the wifi radio. At that time there is not enough current for ESP to properly function and it resets. Once reset it once again uses less current and could reboot and present itself as nothing happened. That could be whats misleading you.

I had the same problem. My esp8266 is powered by FTDI USB to serial module. Since this module can provide a limited amount of current to 3.3V. I use to get frequent reset.
I resolved it by adding a 1000ufd electrolyte capacitor near the power connection of the esp8266 module. And issue resolved like never been there.
I am sure that can also be done by a smaller capacitor. Try with 470 or 220ufd.
enjoy
Rauf


text:
ESP8266 - Sending a software Reset Command
I have an ESP8266 running an Arduino code to control a dual relay device ( Up, Down, Off ), both from a physical switch and MQTT commands. After mounting the device in place I have no access in case of a need to reset ( just as a precaution ).
My workaround:
1) condition: function that on 4 detection of 4 repeated UP button presses - it should send a reboot signal.
2) the reboot signal is :
void sendReset() {
  Serial.println("Sending Reset command");
  Serial.println(1/0);
}

sendReset function actually reboots the device and boot occurs as needed, BUT - is doing it this way is a valid solution ? does boot process actually boots all services and freeing/ memory or any other.... AS NEEDED ?
Guy

1/0 is an exception (divide by zero). esp8266 arduino core has soft reset: ESP.reset(). Calling this function you get a valid reset.
Note to software reset. esp8266 has a bug. If software reset (or exception) is executed in program started right after the flashing, the board goes back to flashing mode because the flashing flag is still active. Perhaps you noticed that after flashing the bootloader doesn't reset the board, but executes the flashed code.

Hi! Yes I know it is an exception, but it causes a reset. Does an Arduino board has also a reset function?

read the answer, please

I read your answer before it was edited ( 1st paragraph only ). Thanks for additional information. My question in the comment was a generelized question regarding Arduino boards ( Nano for example ) it it has also a reset command.

Nano? you write the code for esp8266. yes there is a reset solution for AVR too. with watchdog

Yes ! my code is for esp8266 and the reset command is intended for this code, but I wanted to know if such command exists for Arduino boards. thank you

not one general. different Arduino cores have different solutions for reset. SAMD has NVIC_SystemReset()

In case of serial upload, you need to power off and back on the port, in order to execute again sendReset to work as needed. What is the workaround in causes of OTA, that powering off is not an option ?

OTA makes ESP.reset(). it is good. (it doesn't work only at first reset after serial upload)


text:
How to define and use a list/array of chars using `Serial.print`
I wish to define a list of months names and access it when printing a report.
Array was defined as follows:
const char months []=
{'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'};
for (int i=0; i<=11; i++) {

                                 Serial.print(months[i]);
                        }

Tries:
I was looking for help under Arrays in Arduino documentation didn't give, as far as I found, any explanation for such case, but arrays of int
Appreciate any help.

I just want to point out that Arduino uses C++. Straightforward questions like this, about how to create and access arrays can be answered by doing a C++ tutorial. There is nothing particularly special about the fact that the code is running on an Arduino.

@NickGammon - thank you for your answer. I'm aware of that, but still I did not find any explanation for such case.

Very good. I try to define and access this list without any success - I suggest for future questions you are more explicit about the problem. I see that I can actually define the array the way you did it without error, but I can see that you would have problems printing it because you used single quotes rather than double quotes. It helps to explain what "without success" actually means. If I said "I tried to bake a cake, without success" how would you advise me? A different recipe? A different technique? A better oven? Better ingredients?

I'll rewrite it.

@NickGammon - question is now re-written. Hope it is more undrestandable and not "off-topic"

Very good. I see that there are vote(s) to re-open the question. Most of the moderation here is done by community members, so we'll see what happens to it.

You are almost there:

Use a char* instead of char, a char can only contain one character
Use " instead of ' (Thanks Juraj)

Then you get:
const char* months[] =
 {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

Just fixed :-), found this computer has Arduino installed

The timelib uses progmem and a single string for short names and multiplies the index with 3: https://github.com/PaulStoffregen/Time/blob/master/DateStrings.cpp

@Jot that's also possible, than you just need a function to retrieve the three characters; btw, I didn't see any different in using PROGMEM in my code, maybe it helps if it is just one string (would save 48 bytes).

const char* regards[] ={"Thank", "you","very","much!!"};

@Guy.D You're welcome


text:
Is it possible that function will get a parameter that can be int OR char?
I'm trying to create a function that enters a key/value into a JSON file.
But, since value can be an int or char, I don't want to create 2 functions for each type.
Is there a way ?
void setValue(char *key, char* value){
        StaticJsonDocument<512> tempJDOC;
        tempJDOC[key]=value;
}

EDIT1
#ifndef myJSON_h
#define myJSON_h

#include "Arduino.h"
#include <ArduinoJson.h>
#include "FS.h"

class myJSON
{
private:
bool _useSerial=false;
char _filename[30];

public:
char *ver="myJSON_v1.1";
myJSON(char *filename, bool useserial=false);

bool file_exists();
bool file_remove();
bool format ();
bool FS_ok();

void saveJSON2file(JsonDocument& _doc);
void readJSON_file(JsonDocument& _doc);

void printJSON(JsonDocument& _doc);
void PrettyprintJSON(JsonDocument& _doc);

const char *getValue (char *key);

template <class T>
void setValue(const char *key, T value);
//void setValue(const char *key, char *value);

};
#endif

EDIT2
#ifndef myJSON_h
#define myJSON_h

#include "Arduino.h"
#include <ArduinoJson.h>
#include "FS.h"

#define LOG_LENGTH 4
#define DOC_SIZE 512

template <class T> // . <---- line added
class myJSON
{
private:
bool _useSerial=false;
char _filename[30];

public:
char *ver="myJSON_v1.1";
myJSON(char *filename, bool useserial=false);

bool file_exists();
bool file_remove();
bool format ();
bool FS_ok();

void saveJSON2file(JsonDocument& _doc);
void readJSON_file(JsonDocument& _doc);

void printJSON(JsonDocument& _doc);
void PrettyprintJSON(JsonDocument& _doc);

const char *getValue (const char *key);
void removeValue(const char *key);
// void setValue(const char *key, char *value); <--- comment out
void updateArray(char* array_key, int val);
void printFile();
void setValue(const char *key, T value); <---- Added

};
#endif

and in .cpp file :
void myJSON::setValue(const char *key, T value){
        StaticJsonDocument<512> tempJDOC;
        myJSON::readJSON_file(tempJDOC);
        tempJDOC[key]=value;
        myJSON::saveJSON2file(tempJDOC);
        myJSON::PrettyprintJSON(tempJDOC);
}

how will the code that calls the function decide if it's setting a number or a string?

Um... The title and the text of your question refers to char parameter. The code seems to suggest that you are actually talking about char * parameter. So, what is it? char or char *? These are two very different things. You have to edit your question and clarify that.

@AnT - you are right, but it is commented out at this point since as juraj and edgar suggested to use template - so I don't need to use int nor char

If you needed to pass either int or char you wouldn't need to do anything at all. You don't need any "templates". Just one int version of the function by itself would cover all cases, including char, since in C and C++ char is just a small integer type. So, again, why are you asking this question? What is the problem with char that triggered it? Again, the code you provided implies that you need char * (or, better, const char *). Not char, but const char *. You need to reflect it in your question, since currently neither the question not the accepted answer make sense.

And when you use template, you are using int or const char *, albeit you are doing it implicitly. The compiler does it for you. But again, it is a matter of int and const char *, not a matter of int and char as you stated in your question. char is completely irrelevant here.

my intention using this function is to be able to set and int or char values into a JSON that saves at the end to file. What @Juraj and Edgar suggested, to use templates, solved that.

"Solved" what problem? What is the original problem? In your question you are talking about writing two functions - for int and char - and call this a problem you want to solve. But why didn't you just simply use one function - int version - for both types? No templates necessary. Why did you decide that there is a "problem" here in the first place?

In C++ you can create a template function. (The ArduinoJson [] operator is a template too.)
#include <ArduinoJson.h>

StaticJsonDocument<512> tempJDOC;

template <typename T>
void setValue(const char *key, T value){
  tempJDOC[key] = value;
}

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

  setValue("a", 5);
  setValue("b", "xyz");

  serializeJson(tempJDOC, Serial);
}

void loop() {
}

the compiler will create function based on this template for every different type you use as second parameter in your sketch

When trying to take such function and put it inside a library ( using template as noted here ), i get an error. how can it be done?

by "put it inside a library", you mean using it as class's method?

a method that uses template inside a class

add the code of the class to the Question. is it a class with separate .h and .cpp files? do you have the template<> part of function declaration in .h too?

pasted .h file inside my Q

why did you use ? it should be template <typename T>

I try to follow example 2 in : https://www.programiz.com/cpp-programming/templates

see EDIT2 in my Q

you want a class with a template function, not a template class https://stackoverflow.com/questions/972152/how-to-create-a-template-function-within-a-class-c

Yes I know... this is the closest I could find

The short answer is “no, it's not possible”. You will have to use two
different functions. These two functions can share the same name, using
function overloading. You can even have the compiler
write these functions for you, based on a template you provide, as shown
in Juraj's answer. These language features help provide the illusion of
there being a single function. But it's just an illusion, albeit a
useful one that helps with program readability. At the fundamental
level, you still have two different functions.

Edgar - thank you for explaining and usefull link. But I do not understand how Juraj's answer ( using template ) creates/ duplicates the function for other types

@Guy.D: Do a search for “C++ templates”. In short, every time you call setValue() with a new value type, the compiler creates a new version of the setValue() function suitable for that specific type.

I have in my answer: "the compiler will create function based on this template for every different type you use as second parameter in your sketch"

@EdgarBonet I use you link to try to implement this function inside a lib I make ( called myJSON, as you can see in edit 1 and edit 2 ). I'll appreciate your help once more


text:
Serial Port configuration with asio C++ library
I've made a small interface using the asio C++ library to open serial ports and do I/O from/to them.
It works with my Arduino Uno and other hardware as well (industrial weighing machines), but I only specify the port and baud rate.
The following code is run in the client application, which runs both on my Windows 10 Student Edition x86_64 machine, and on old 32 bit  Win XP machines that communicate with the weighing machines:
/*this is inside a constructor*/
/*iosvc gets passed by reference, port_ is a member variable of type asio::serial_port,
 npuerto is the name of the port (e.g. "COM3") */

port_(iosvc_, npuerto),

/*...*/

port_.set_option(asio::serial_port_base::baud_rate(baudios));

The Arduino is programmed to do a serial echo of whatever is sent to it, for testing purposes. This is the echo code:
void setup() {
  Serial.begin(9600);
}

void loop()
{
  while(Serial.available())
  {
    Serial.write(Serial.read());
  }
}

It works fine with my Arduino until I unplug it and plug it back in. After replugging it all the values returned are garbage, specifically some sort of '?' character inside a black box, don't know the bit value though, but it's constant. The problem gets fixed when I open an arduino IDE Serial Port monitor.
If I close it, and once again use my own software to open up the serial port, all the values are fine.
From this I concluded that the Arduino IDE Serial Port monitor is doing something when it opens up the port that I'm not doing.
Any clues? Flow control? Handshake?
Thanks

Which "Arduino" are you using? For example, is it an Uno, with a separate USB-Serial interface between the USB port and the serial interface on the MCU, or is it something like a Leonardo, with on-board USB support on the microcontroller? The "unplug it and plug it back in" behaviour is rather different between the two.

It is an UNO, and the garbage values are the exact number of characters that I send it, e.g. if I send "Hello", I'll get "?????" where the '?' character is the same I described above. Like a black box with a '?' inside.

If it's the exact same number of characters, that leads me to guess that the bps rate is properly matched and you have some problem with corruption of the data. I suspect that the '?' in a black box is not actually a particular value but an "I don't want to interpret this" value. Anyway, can you update the question to have a copy of your "echo" program code, mention the host PC platform (Win, Linux, etc.) you're using, and what program (that's not the monitor) you're using to view the serial port traffic?

What bugs me is that the Arduino Serial Monitor does something which "fixes" the serial port. As if it aligned some values or something. My custom program will work fine after using the Monitor at least once if the Arduino gets reset. It works fine with the weighing machines, which are in a textile factory, so I guess the code is OK. Those machines are connected through an old fashioned serial port connector though.

Could it be related to handshake protocol? I don't know much about it.

Tweak the question to make it quite clear that the first code sample is running on a PC under Windows 10. (This took me surprisingly long to figure out!)

Can you include all the other calls you make related to setting up the serial port along with asio::serial_port_base::baud_rate(baudios)? Ideally, split that out into a separate function (that takes parameters such as baud rate) that you know is the only thing doing this setup.
As I mentioned in the comment, getting back the right number of chararacters but incorrect characters looks as if the baud rate is correct but something else is wrong. The first thing that comes to mind is the bits/parity/stop bits settings. Typically you want to be using 8 bits, no parity, often referred to as "8N1".