text:
Arduino Uno First Program
Please help with this error.
Arduino: 1.8.10 (Windows 10), Board: "Arduino Uno"
Sketch uses 882 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
avrdude: ser_open(): can't open device "\.\COM4": Access is denied.
Windows 10 Pro
Arduino UNO ATmeg 328P-PU
Have never been able to Upload a sketch.
Pin 13 and Orange LED blink at 1 second

Welcome to the Stack Exchange and on the Arduino World.
Just a note: Since yesterday there is a new version of Arduino IDE (the last version is now 1.8.11).
When you buy an Arduino, a default sketch is already present. This will blink your LED (pin13) with a 1 second interval. This just mean that your Arduino is working and has a bootloader.
To program it, you need to know which COM port is created for your Arduino module:

Press WIN-'R' (execute application)
Write devmgmt.msc

Check the COM port to see wich COM port was used for your Arduino.
This is the only cause, the message could appear if you use a standard USB-cable connected to your standard Arduino UNO board.

did you search for an existing answer?

Checked again and Arduino Uno is connected to Comport 4. And disabled Windows Defender Firewall. No success.

It seems that the port was already opened (as the question is now marked as duplicate).


text:
Missing buffers with serial communication
I am currently facing a problem with Serial communication with my arduino MEGA 2560.
My project is to collect data from an encoder. There are 2 signals : ACP and ARP. For 1 rotation, there are 16 384 ACPs (counter) and 1 ARP (reference).
I have to store the high level and length of EACH ACP and if there is an ARP. To receive these signals I created a little PCB with a dual line receiver (because At the output of the encoder I revceive differential signals).
To store these data, I use a buffer of bytes. I need 3 bytes to store both ACP length and high and 1 ARP (I store the data in an ISR, see code below) :
buff1[i] = char((arpNbr << 7) +  (acpPeriod >> 8));
i++;
buff1[i] = char(acpHigh);
i++;
buff1[i] = char(acpPeriod);
i++;

I use 2 circular buffers (when 1 is filled, I start wrinting into the other). As there are different speed rotation, the fastest one is 15 RPM (rotation per minute) so 1 ACP signal (1 period) last for 244 us and 4 s are needed for 1 rotation.
To collect the data, I directly use :
Serial.write(buff1, sizeof(buff1));
Here is the code I am using :
#include <eRCaGuy_Timer2_Counter.h> //To use timer in ISRs

//Constants
#define NO_DEFAULT_LED_PIN            40
#define DEFAULT_LED_PIN               42
#define WRITE_LED_PIN                 44
#define REC_IN_PROGRESS_LED_PIN       50
#define ACP_LED                       46
#define ARP_LED                       48
#define ACP_PIN                       20
#define ARP_PIN                       21
#define STOP_REC_BUTTON_PIN           28

#define SIZE                          800
#define BAUDSPEED                     230400

//Variables
boolean recordingEnded = false;
volatile boolean writing = false;
volatile unsigned short arpNbr = 0;
volatile unsigned short acpHigh = 0;
volatile unsigned short acpPeriod = 0;
volatile int i = 0;
volatile bool change_buffer = 0;

char buff1[3 * SIZE];
char buff2[3 * SIZE];

//Variables for interruption routines
volatile unsigned long acpHighUs = 0UL; volatile unsigned long acpPeriodUs0 = 0UL; volatile unsigned long acpPeriodUs1 = 0UL;

/**************************************************************************************/
/* Initialization                                                                     */
/**************************************************************************************/
void setup()
{
  Serial.begin(BAUDSPEED);

  //Setup LED pins
  pinMode(DEFAULT_LED_PIN, OUTPUT);
  pinMode(NO_DEFAULT_LED_PIN, OUTPUT);
  pinMode(SD_WRITE_LED_PIN, OUTPUT);
  pinMode(REC_IN_PROGRESS_LED_PIN, OUTPUT);
  pinMode(ACP_LED, OUTPUT);
  pinMode(ARP_LED, OUTPUT);

  //Setup ACP and ARP inputs
  pinMode(ACP_PIN, INPUT_PULLUP);
  pinMode(ARP_PIN, INPUT_PULLUP);

  //Setup the button
  pinMode(STOP_REC_BUTTON_PIN, INPUT_PULLUP);

  //Light ALL LEDs during initialisation
  digitalWrite(DEFAULT_LED_PIN, HIGH);
  digitalWrite(NO_DEFAULT_LED_PIN, HIGH);
  digitalWrite(SD_WRITE_LED_PIN, HIGH);
  digitalWrite(REC_IN_PROGRESS_LED_PIN, HIGH);
  digitalWrite(ACP_LED, HIGH);
  digitalWrite(ARP_LED, HIGH);
  delay(500);

  //Setup the timer
  timer2.setup();

  //Setup is done
  digitalWrite(NO_DEFAULT_LED_PIN, LOW);
  digitalWrite(SD_WRITE_LED_PIN, LOW);
  digitalWrite(ACP_LED, LOW);
  digitalWrite(ARP_LED, LOW);

  //Attach interruption at the end of the initialisation (recording starts...)
  attachInterrupt(digitalPinToInterrupt(ACP_PIN), acpRising, RISING);
  attachInterrupt(digitalPinToInterrupt(ARP_PIN), arpRising, RISING);
}

/**************************************************************************************/
/* Main loop                                                                          */
/**************************************************************************************/
void loop()
{
  //Check if the user stops the recording
  if (digitalRead(STOP_REC_BUTTON_PIN) == LOW && !recordingEnded )
  {
    noInterrupts();
    delay(500);

    //Switch off the recording LED
    digitalWrite(SD_WRITE_LED_PIN, LOW);
    digitalWrite(REC_IN_PROGRESS_LED_PIN, LOW);
    digitalWrite(ACP_LED, LOW);
    digitalWrite(ARP_LED, LOW);

    return;
  }

  //Check if the writing should be done
  if (writing && !recordingEnded)
  {
    digitalWrite(WRITE_LED_PIN, HIGH);

    if (change_buffer) {
       Serial.write(buff1, sizeof(buff1));
    }
    else {
       Serial.write(buff2, sizeof(buff2));
    }

    digitalWrite(WRITE_LED_PIN, LOW);
    writing = false;
  }
}

/**************************************************************************************/
/* This method is called at the beginning of each ACP.                                */
/**************************************************************************************/
void acpRising()
{
  digitalWrite(ACP_LED, HIGH);
  acpHighUs = timer2.get_count();
  acpPeriodUs1 = timer2.get_count() / 2 - acpPeriodUs0;
  acpPeriodUs0 = timer2.get_count() / 2;

  acpPeriod = acpPeriodUs1;

  attachInterrupt(digitalPinToInterrupt(ACP_PIN), acpFalling, FALLING);
}

/**************************************************************************************/
/* This method is called at the end of each ACP.                                      */
/**************************************************************************************/
void acpFalling()
{
  digitalWrite(ACP_LED, LOW);
  acpHighUs = (timer2.get_count() - acpHighUs) / 2;
  acpHigh = (unsigned short)acpHighUs;

  if (change_buffer) {
    buff1[i] = char((arpNbr << 7) +  (acpPeriod >> 8));
    i++;
    buff1[i] = char(acpHigh & 0xFF);
    i++;
    buff1[i] = char(acpPeriod & 0xFF);
    i++;

  }
  else  {
    buff2[i] = char((arpNbr << 7) +  (acpPeriod >> 8));
    i++;
    buff2[i] = char(acpHigh & 0xFF);
    i++;
    buff2[i] = char(acpPeriod & 0xFF);
    i++;
  }

  arpNbr = 0;

  if (i == 3 * SIZE) {
    i = 0;
    change_buffer = !change_buffer;
    writing = true;
  }

  attachInterrupt(digitalPinToInterrupt(ACP_PIN), acpRising, RISING);
}

/**************************************************************************************/
/* This method is called at the beginning of each ARP.                                */
/**************************************************************************************/
void arpRising()
{
  digitalWrite(ARP_LED, HIGH);
  arpNbr = 1;

  attachInterrupt(digitalPinToInterrupt(ARP_PIN), arpFalling, FALLING);
}

/**************************************************************************************/
/* This method is called at the end of each ARP.                                */
/**************************************************************************************/
void arpFalling() {
  digitalWrite(ARP_LED, LOW);
  attachInterrupt(digitalPinToInterrupt(ARP_PIN), arpRising, RISING);
}

Problem :
I use CoolTerm software to collect my data into a .txt file and analyse it with Hexed.it.
It seems like after a certain period, like 6-10 minutes, I loose a part of 1 buffer. I checked this beacause as I wrote above, I need 3 bytes for information and in Hexed.it, I saw that I had only 2 bytes at once, and after, data was correct.
After analysing in depth, I saw that there was a part of a buffer and a few more (1-2) which were missing. I managed to see this because there was not 16384x3 bytes between 2 ARP (reference signal of the encoder).
I checked all timings to see if I sent the buffer before it was filled but everything is fine...
I also tried other methods like :

Writing on a SD card;
Changing buffer size;
Changing baudrate;
Using polling method instead of ISRs.

But nothing concluant ...
EDIT:
It seems like my problem came from CoolTerm software after correcting my code. I now use RealTerm and I made a 1 night recording duration and every seems to be perfect. I don't have any data lost.

You attach interrupts quite often which I’d say is uncommon at least. I don‘t know what attachInterrupt() does in the background, but if it uses dynamic memory allocation I could imagine that calling it frequently might lead to problems.

Also you should not return from the main (loop) function on a uC. I don‘t know if it‘s legal, but it doesn‘t make much sense

@SimSon: 1. attachInterrupt() does no memory allocation. 2. loop() is not main(): returning from loop() is perfectly fine, and expected.

@EdgarBonet good to know! Will it be like while(1) loop(); in the end?

@SimSon: main() does indeed call loop() repeatedly.

What do you mean by “a part and other buffers are not transmitted”? Do you continue to receive data? Is the received data different from what you expect? If so, in what way is it different? Also, what is the typical frequency of the ACP signal?

@EdgarBonet Sorry for creating a new answer but I can't aswer to your pevious one. I can edit it but can't answer to it... Weird... So, for your answer 2. Writing passes to true in acpfalling ISR, after i = 0. 3. Thanks to have seen this. I am making a test to see if this is the problem... Hope it will resolve 4. I will have a look, thanks! 5. Using char *buff = change_buffer ? buff1 : buff2; won't take useless time ? I mean, if it just a matter of reading. Because, as far as I know, ISRs have to be as short as possible.

StackExchange sites are not forums. You don't post answers below answers, and so on, please take the [tour] (again). -- If you need some clarification, comment below the question or the answer that is unclear. -- If you have new information after reading a comment or an answer, edit your question. There is that little link on the left below your question.

@EdgarBonet I am trying to 'add a comment' to your comment to your comment but I can't. it tells me : 'You need to have 50 reputation to comment'. How can I handle this situation to answer your comment and not creating stupid answers all the time ?... Sorry for this answer ...

@Greg_B - You have 2 accounts with the same name, but 2 different IDs. If you can't comment, please edit the question with new information.

Not a direct answer to your questions, but after reading your code I
would like to give some comments:

You are not using “circular buffers”, you are double-buffering.
If you used a circular buffer, you would not need two of them.
recordingEnded is always false and thus serves no purpose.
When writing and change_buffer are both true, you should transmit
buff2, not buff1, as the ISR is now filling buff1.
There are too many globals. Variables that are used in a single
function should be local to the function. If you need the value to be
preserved between calls, qualify the variable as static.
The code that fills the buffers would be clearer, IMO, if you avoided
the repetition. E.g.

char *buff = change_buffer ? buff1 : buff2;
buff[i++] = (arpNbr << 7) | (acpPeriod >> 8);
buff[i++] = acpHigh & 0xFF;
buff[i++] = acpPeriod & 0xFF;

Note that buf[i++] is idiomatic C/C++.
Now, regarding your specific question, you mentioned in a comment that
“there were not 3x16384 bytes between 2 ARP”. This may well be a
consequence of issue 3: you are not sending the bytes in the correct
order, as at times (when Serial.write() runs ahead of the ISR) you may
be sending old data.

Edit: to answer the comment

char *buff = change_buffer ? buff1 : buff2; won't take useless time?

Not really. Testing change_buffer is something you have to do either
way. Assigning the buffer address to a local pointer is also done, under
the hood, by the compiler. In the best case, it optimizes your code to
something like:
register char *Z;
if (change_buffer)
  Z = buff1 + i;
else
  Z = buff2 + i;
Z[0] = (arpNbr << 7) | (acpPeriod >> 8);
Z[1] = acpHigh & 0xFF;
Z[2] = acpPeriod & 0xFF;
i += 3;

Using an explicit buff pointer gives a similar result, as the compiler
will allocate this to the CPU's Z register. Actually, you may get
shorter code, as the compiler may not entirely factor out the
repetition.

source: Stack Exchange

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

sort: votes


text:
stepper motor doesn't work but get no error message
So I work for a department that uses arduino to move a stepper motor for a wave machine and I am encountering a issue.  They gave me the code that they used to use but it doesn't move the motor and just makes this intermittent beeping noise.
My code is as follows:
int pulse_delay = 20;
int wave_period = 1000;

void setup() {
pinMode(8,OUTPUT);
pinMode(9,OUTPUT);
digitalWrite(8,LOW);
digitalWrite(9,LOW);
}

void loop() {
digitalWrite(9,HIGH);
delay(10000);
for (int i=0;i<wave_period;i++)
{
  digitalWrite(8,HIGH);
  delayMicroseconds(pulse_delay);
  digitalWrite(8,LOW);
  delayMicroseconds(pulse_delay);
}
digitalWrite(9,LOW);
for (int i=0;i<wave_period;i++)
{
  digitalWrite(8,HIGH);
  delayMicroseconds(pulse_delay);
  digitalWrite(8,LOW);
  delayMicroseconds(pulse_delay);
  }
}

I do not receive any error messages and the IDE just says upload complete.  We use a Arduino Mega board. I am pretty new to Arduino.
Edit:
Someone asked for pictures about how it was connected.  Sorry for the late response, had a family emergency.

The cable coming in from the bottom of first picture is from the stepper motor, as is the cable I'm holding but that is what I was told isn't necessary.

I guess I am asking if there is something missing from the code or if there is something I can add to it to see where the code stops.

motors need quite a bit of current (more than the GPIO pins can handle), can you describe how you connected the stepper?

It has 2.  One is I believe a HX2.54 5 pin cable.  The other I have no idea, it has a black base and 4 long prongs that stick out but I have been told they didn't need to use those.  I will try and ask my supervisor when they come back from teaching.

We also plug that cable into the arduino board and the board is what is plugged into an outlet.

Between the Arduino and the stepper motor there has to be a driver circuit. It controls the phases of the motor according to the pulses and the direction pin and provides the motor with the needed power. Please show an image of the circuit, where we can see how everything is connected

Ok, currently at my other department(I work for 2).  I will go back this afternoon to take a picture of the board and motor to post.

In your images I see more wires running between the Arduino and the (assumed) driver board (the green one at the bottom). As the driver board has good connectors and the connector from the motor seems to fit, I would guess, that the driver is connected correctly, but that the signals from the Arduino aren't what the motor driver expects. Can you tell us, what motor driver this is, so that we could look up a datasheet?

The only identification I can find on the green board is CDV524-K     TV8 1U54101 and what I guess is a date 2016/08 and its from Oriental Motor Co.

What are 8 and 9 plugged into on your stepper?
also define your baud rate based on the motor requirements.

void setup() {
pinMode(8,OUTPUT); < should be PUL
pinMode(9,OUTPUT); < should be ENA(maybe dir)
digitalWrite(8,LOW);
digitalWrite(9,LOW);
Serial.begin(115200);
}

void loop() {
digitalWrite(9,HIGH);
delay(10000);
for (int i=0;i<1000;i++)
{
  digitalWrite(8,HIGH);
  delayMicroseconds(20);
  digitalWrite(8,LOW);
  delayMicroseconds(20);
}
digitalWrite(9,LOW);
for (int i=0;i<1000;i++)
{
  digitalWrite(8,HIGH);
  delayMicroseconds(20);
  digitalWrite(8,LOW);
  delayMicroseconds(20);
  }
}

How does this answer the question? What has Serial and it's baudrate to do with the stepper motors? And the function Serial.begin() is with a lower case b.

You.. I tested this code (corrected the SMALLL typo) on a servo I have here and it worked... So? Did you do anything to try and help this person?

In the 9, LOW for loop I get a wave_period not declared error.

once again not adding value.

OK, then I guess I don't know what you want.  I posted pictures of what is plugged in and I tried your code.  Thanks for your help anyways.

@chas I didn't want to insult you, so if I did, sorry. Your working code is different from the non-working code of the OP only in the Serial.begin() line. Thus you propagate, that this line is the solution to the problem. I don't understand, how it could be, since the state of the Serial(UART) hardware should not effect any other digital outputs. If you know it otherwise, please explain, so that others can learn from it.

Here you can find the manual of your stepper driver.
Look at page in the section "CN3 (I/O signals)". Beside the pulse and directions, that you already set in your code, there are 2 more input signals defined: AWO will turn off the motor completely, if you provide a signal, CS changes the source of the step angle setting. As you don't configure any pins, other than pulse and direction, the other pins on the Arduino are set as input/high impedance. The state of these pins can float wildly depending on what noise is comming by. I don't know, if this really matters for this driver, but you should try to provide a valid state on all the input pins of the driver. For example a floating AWO pin might randomly disable and enable your motor very fast (which would at least fit with the described behavior). Set the corresponding pin on the Arduino as output (via pinMode()) and give them the state, that you want via digitalWrite() (I suggest LOW for AWO to enable the motors and HIGH for CS to get the basic step angle).
I cannot see on your images, if everything is connected to the driver, as it should (here a wiring diagram or a schematic would help). For now I assume, that the signal pins on the Arduino side are connected correctly.
The input signals of the driver are meant to be provided by a pair of twisted wires. This is done to minimize noise on the line. Thus all input signals have 2 pins: "+" and "-". Connect all "-" pins to ground and the "+" pins to the appropriate digital output pin on the Arduino.
If a have a oscilloscope or a logic analyzer, you can also monitor the ALM and TIM outputs of the driver. Maybe they are showing, what is going wrong.
Let us know, if this helps.

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


text:
SAM3X8E Maximum Serial Speed
Does somebody know which is the maximum serial speed one can achieve by using the Microchip SAM3X8E microprocessor with Serial Communication between other uC with a RS485 module?
The Arduino Due seems to be limited up to 115kbps, the USB (UOTGHS) should reach 1.5Mbps (low speed) without trouble, but I am not sure about the UART
From Microchip SAM3X8E Datasheet section 34.5.1 Baud Rate Generator, the UART baud rate should be the Master Clock MCK divided by 16, the maximum value given by setting the clock divisor UART_BRGR to 1, the minimum value after 0 (UART disabled).
Hence the Master Clock MCK should be around 84MHz (its Maximum Possible Clock?), and then the Maximum Baud Rate should be 5.25Mbps?
Is this right?
Thanks in advance

Quoting: "The maximum allowable baud rate is Master Clock divided by 16." from the SAM3X8 datasheet... However the maximum speed of RS485 bus transciever would be probably main bottleneck...

@KIIV Hence which is the MCK maximum value? Should it be 84MHz and then the maximum UART datarate should be 5.25Mbps?


text:
Servo Program Questions
Hi programming in arduino, I am trying to get a nested for loop inside a for loop with industrial servo which used PUL +- DIR+- (bought motor off amazon).
My goal is to get the puls delay to increase. I have a sensor attached that I want the servo to turn on when triggered.
So the sensor will get triggered and the the servo will start off fast and get slower up to 255 micros second delay.
example:
int sensor = 26;
int PUL = 23; //define Pulse pin
int DIR = 25; //define Direction pin

void setup() {
  pinMode(sensor, INPUT);
  Serial.begin(115200);
  pinMode (PUL, OUTPUT);
  pinMode (DIR, OUTPUT);
}

void loop() {
  int sen = digitalRead(sensor);
  if (sen == HIGH) {
    Serial.println("HIGH");
    delay(1000);
     for (int i=0; i<500; i++)
  {
      for( int x=0; x<255; x++){

    digitalWrite(DIR,LOW);
    digitalWrite(PUL,HIGH);
    Serial.print("i = ");
    Serial.println(i);
    Serial.print("x = ");
    Serial.println(x);
    delayMicroseconds(x);
    digitalWrite(PUL,LOW);
    delayMicroseconds(x);
  }}
  } else if (sen == LOW) {
    Serial.println("LOW");
    delay(1000);
    } else {
    Serial.println("ERROR");
  }
}

EDIT
I am trying to nest a FOR loop inside a FOR loop What I want to do is get x to increase with i until x is 255 then I will continue unit i reaches 500. Right now x goes 0-255 and then i increase by 1. I need the value of x to increase along side with i until 255
for (int i=0; i<500; i++) {
  for( int x=0; x<255; x++){
  digitalWrite(DIR,LOW);
  digitalWrite(PUL,HIGH);
  Serial.print("i = ");
  Serial.println(i);
  Serial.print("x = ");
  Serial.println(x);
  delayMicroseconds(x);
  digitalWrite(PUL,LOW);
  delayMicroseconds(x); }
}

it is unclear what you have, how it is connected and what you are trying to do exactly

Do you want i and x to increment at the same rate 0-255 then x to remain 255 while i increases to 500?
this should do what you want. i and x increase together until x reaches 255 then it wont increment.
int x=0;
for (int i=0; i<500; i++) {

  digitalWrite(DIR,LOW);
  digitalWrite(PUL,HIGH);
  Serial.print("i = ");
  Serial.println(i);
  Serial.print("x = ");
  Serial.println(x);
  delayMicroseconds(x);
  digitalWrite(PUL,LOW);
  delayMicroseconds(x); }

   if(x<=255){
        x++;
   }

}


text:
USB Power switch
Can an Arduino power a USB device like a tablet from one of it's pins or do I need a relay? I want to essentially have the Arduino turn on and off a USB charger. Thanks

USB is 5V, not 3.3V. Also, no. 40mA is nowhere near enough for a typical USB device.

do not use an arduino as a power supply

Any advice on how to do this then? Thanks

use a mosfet instead of a relay; simpler, cheaper, lower power waste. google mosfet as a switch

If you already have a 5V source then you can use a MOSFET as a switch to turn on/off the power to the tablet like this:

But if you want to turn on/off a USB charger that goes to an AC outlet, then you will need to control a relay to turn on/off the AC supply to the USB charger. You can use a relay module like this: https://www.amazon.com/Tolako-Arduino-Indicator-Channel-Official/dp/B00VRUAHLE


text:
Send structure through Serial
Suppose that one defined a data structure and wanted to send it through serial.
 struct Gyro_data_structure {
    char command_name[5];
    float gyro_X;
    float gyro_Y;
    float gyro_Z;
};

Gyro_data_structure Gyro_data;

int size_gyro=sizeof(struct Gyro_data_structure);

void setup() {
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}

void loop() {
  Gyro_data.command_name[0]='H';
  Gyro_data.gyro_X++;
  Serial.println(size_gyro);
  delay(500);
  Serial.write(Gyro_data,size_gyro);
}

However, it returned an error saying "no matching function for call to 'HardwareSerial:write(Gyro_data_structure&,int&)'". I googled and found Michaël Roy's answer here. However, it's not working: "can not convert ..."
How to send a structure through UART?

i would start with code that works and then make small changes to find out what works and what does not work .... use the code that you found as an example ... change your struct to all integers

@jsotola currently, non of them were working, the only thing I haven't tried was union. Right now I'm trying the bitwise operator, but apparently int is singed.

start with the exact same sketch as the link that you posted

@jsotola That's the question, it didn't work.

you can send the structure as binary only if the receiver has the exact same way of store binary data in a structure as the sender. basically it will work only if the receiver uses the same compiler

I tried the code from the link you posted and it worked:
struct Gyro_data_structure
{
    char command_name[6];
    int gyro_X;
    int gyro_Y;
    int gyro_Z;
};

struct Gyro_data_structure Gyro_data = {"Hello", 48, 49 , 50};

int size_gyro = sizeof(struct Gyro_data_structure);

void setup()
{
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}

void loop()
{
  send(&Gyro_data);
  Serial.println();
  delay(1000);
}

void send (const Gyro_data_structure* table)
{
  Serial.write((const char*)table, size_gyro);  // 2 bytes.
}

bool receive(Gyro_data_structure* table)
{
  return (Serial.readBytes((char*)table, sizeof(Gyro_data_structure)) == sizeof(Gyro_data_structure));
}

I changed the float type to int for easy representation. When you run the code the serial window will show: Hello012
Because Arduino IDE serial window shows ASCII characters. 0's ASCII value is 48 and so on.

Update
It depends on what you want from the read function. Let's break down what Michaël Roy's implementation is doing. First, he reads sizeof(Gyro_data_structure) number of serial bytes and put it in the variable that table points to:
Serial.readBytes((char*)table, sizeof(Gyro_data_structure))

The 2nd argument of readBytes() takes how many bytes you want to read. Also readBytes() return how many bytes it read. Let's say we stored that number in return_bytes. In the next part he did:
return (return_bytes == sizeof(Gyro_data_structure))

He is checking if the number of bytes readBytes() read is the same as the size of  Gyro_data_structure. If it is not, then return false.
This just tells you if you read more or less than what you are supposed to read. Regardless of true or false, the actual bytes that were read will be in the variable that you passed to the receive() function.
If you don't want the function to not return anything this is how it should be:
void receive(Gyro_data_structure* table)
{
  Serial.readBytes((char*)table, sizeof(Gyro_data_structure));
}

Thank you soooooo much !!!!! That was really helpful! However, could you explain just a little bit what happened there? (char*) and send(&Gyro_data); receive(&Gyro_data); I want to learn and adjust the code for better noise resistance.

send() takes a pointer of Gyro_data_structure. That's why in the loop()  send() uses the address of the declared variable (Gyro_data). When you want to send the address of any variable you use '&' in front of that variable. Now, the address points to the first variable of the structure, which is command_name[0]. Serial.write() starts printing one byte at a time from that variable until it reaches size_gyro.

could you explain a little bit of why receiving part used bool instead of void?  and isn't second input of Serial.readBytes just 1?(say, 12==12 )

@ShoutOutAndCalculate I updated my answer to reflect your comment.

First of all, you have to decide whether you want to send the data as
raw bytes (“binary data”) or as an ASCII text representation. Binary
tends to be more efficient: you can send a float with full precision
in only four bytes, whereas you would typically need 8 to 9 significant
digits to recover the full precision from an ASCII representation.
Binary is, however, harder to handle: some types have different binary
representations on your Arduino and your PC, and you may need to define
a protocol of sorts in order to get the framing right. ASCII is easier,
and you can usually use end-of-lines as a simple framing device. I
generally recommend using ASCII unless you really need the extra
efficiency of a binary protocol.
Sending as binary
You can easily send arbitrary binary data using the method
write(const uint8_t *buffer, size_t size) from the Serial object:
Gyro_data_structure Gyro_data = {"Gyro", 0.0, 4.0, 5.0};

void loop() {
    Gyro_data.gyro_X++;
    Serial.write((uint8_t *) &Gyro_data, sizeof Gyro_data);
    delay(200);
}

Here is an hex dump of the output:
0000  47 79 72 6f 00 00 00 80  3f 00 00 80 40 00 00 a0  |Gyro....?...@...|
0010  40 47 79 72 6f 00 00 00  00 40 00 00 80 40 00 00  |@Gyro....@...@..|
[...]

which can be parsed as follows:
47 79 72 6f 00 = {'G', 'y', 'r', 'o', '\0'}
00 00 80 3f    = 0x3f800000 = 1.0f
00 00 80 40    = 0x40800000 = 4.0f
00 00 a0 40    = 0x40a00000 = 5.0f

Note that the floats are sent in little-endian order: lest significant
byte first. The 32-bit hex numbers above are the binary representations
of the floats.
Sending as text
Serial.print() is intended to print a text representation of the data
you give it. But since it does not know how to represent a
Gyro_data_structure, you have to Serial.print() each data member in
turn, and then add some formatting around all that:
void print_gyro(const Gyro_data_structure &gyro) {
    Serial.print(F("Gyro{command = \""));
    Serial.print(gyro.command_name);
    Serial.print(F("\", X = "));
    Serial.print(gyro.gyro_X);
    Serial.print(F(", Y = "));
    Serial.print(gyro.gyro_Y);
    Serial.print(F(", Z = "));
    Serial.print(gyro.gyro_Z);
    Serial.print(F("}"));
}

void loop() {
    Gyro_data.gyro_X++;
    print_gyro(Gyro_data);
    Serial.println();
    delay(200);
}

The output is
Gyro{command = "Gyro", X = 1.00, Y = 4.00, Z = 5.00}
Gyro{command = "Gyro", X = 2.00, Y = 4.00, Z = 5.00}
[...]

Making your data printable
This is a variation on the previous technique. You can Serial.print()
your object directly, if you tell the Arduino core how to print this
type of objects. This is done by letting your class inherit from
Printable and implementing the virtual method printTo(). But then
the class is not an “aggregate” anymore, and thus needs an explicit
constructor:
struct Gyro_data_structure : Printable
{
    char command_name[5];
    float gyro_X;
    float gyro_Y;
    float gyro_Z;
    Gyro_data_structure(const char *name, float x, float y, float z)
    : gyro_X(x), gyro_Y(y), gyro_Z(z) {
        strncpy(command_name, name, 4);
        command_name[4] = '\0';
    }
    size_t printTo(Print& p) const {
        size_t count = 0;
        count += p.print(F("Gyro{command = \""));
        count += p.print(command_name);
        count += p.print(F("\", X = "));
        count += p.print(gyro_X);
        count += p.print(F(", Y = "));
        count += p.print(gyro_Y);
        count += p.print(F(", Z = "));
        count += p.print(gyro_Z);
        count += p.print(F("}"));
        return count;
    }
};

Gyro_data_structure Gyro_data("Gyro", 0.0, 5.0, 5.0);

void loop() {
    Gyro_data.gyro_X++;
    Serial.println(Gyro_data);
    delay(200);
}

The output is identical as before. The definition of the class gets a
little bit clumsier, but then you can very easily print to any serial
port (be it an UART or a software implementation), to an LCD... or
whatever understands print().


text:
Nested For Loop Controlling speed
I have a servo motor That I am trying to determine the delay speed in between pulses with a nested for loop. This issue is instead of running together like 0,0 1,1 2,2 its actually going up like 0,0 0,1 0,2. SO the first for loop i will only go up once all of the x for loop goes to its max 255.
What I want it to do is go up together until x reaches 255 and then it will stabilize there as I will countering to climb.
If any know anything about nested for loop I would appreciated (please only add valuable comment or help to this. I don't need pointless or dumb comments (talking about  jsotola and all he did was criticized my question)
 for (int i=0; i<500; i++)
  {
      for( int x=0; x<255; x++){

    digitalWrite(DIR,LOW);
    digitalWrite(PUL,HIGH);
    Serial.print("i = ");
    Serial.println(i);
    Serial.print("x = ");
    Serial.println(x);
    delayMicroseconds(x);
    digitalWrite(PUL,LOW);
    delayMicroseconds(x);
  }}

These are nested loops:
for (int i = 0; i < 500; i++) {
    for (int x = 0; x < 255; x++) {
        do_something_with(i, x);
    }
}

“Nested loops” means you have a loop within a loop: within each
iteration of the outer loop you get a full run of the inner loop. The
sequence of (i, x) pairs is:
(0, 0), (0, 1), (0, 2), ... (0, 254)
(1, 0), (1, 1), (1, 2), ... (1, 254)
...
(499, 0), (499, 1), ...     (499, 254)

What I want it to do is go up together until x reaches 255 and then it
  will stabilize there as I will countering to climb.

This sentence is not very clear. I assume you mean that you want the
following sequence of (i, x) pairs:
(0, 0), (1, 1), (2, 2), ... (255, 255),
(256, 255), (257, 255), ... (499, 255)

If this is what you want, you can more easily achieve it with a single
loop:
for (int i = 0; i < 500; i++) {
    int x = min(i, 255);
    do_something_with(i, x);
}

Thank you! I appreciate your help!
This worked.


text:
Using arduino uno and an adafruit shield to control 3 dc motors and a linear stepper motor
Hello I am currently doing a project at my university which requires me to order and program 4 motors using an arduino. I will be using an arduino uno and an adafruit motor shield. 2 of the dc motors will have an encoder for better motor control. While connecting the linear and one of the dc motors shouldn't be difficult, I am wondering how can I connect the two motors with encoders.
I was thinking to connect 1 dc motor and the stepper onto one shield and the encoder motors onto another since the shields can stack. Is this option possible or should I use some other method? I am fairly new to arduino and only had a little bit of experience with coding so any help and suggestions are welcome.

It looks like Adafruit motor shield can control 4 DC motors and 2 stepper motors. So one shield should be enough. https://www.adafruit.com/product/1438

Thanks for the reply. The adafruit motor shield has enough connections for either 4 dc motors or 2 stepper motors therefore the most I could connect would be 2 dc and 1 stepper. So at least 2 shields will be required. What I am unsure of is can I even connect encoded motors to the motor shield or will I need to order another board specifically to run them.

You are right, my bad. Looks like you will need two shields then. But you will need stackable header. The ones that come with the Adafruit Shield is not stackable. Something like this: https://www.amazon.com/Arduino-Stackable-Header-Kit-R3/dp/B00PCCWEJG/ref=dp_ob_title_ce


text:
Problem with Input from Serial Monitor
I have a piece of code as shown, and I wish to print the value I send using serial monitor along with a message: "Writing data to slave...".

But everytime I enter a character/number in the serial monitor(like 'a' as shown), the loop runs two times instead of just once. It seems like an extra character(somewhat invisible or null) is being sent along with the typed character.

If I use the condition (Serial.available()>1)  then the loop runs just once on sending one character.
Why is this so?

Please copy the code as text instead of bad screen dumps.

I suspect an end of line character is send (probably \n or \r, see comment of Edgar Bonet), or an end of string (0 character).
You can easily find it out by printing the integer value of the character:
char c = serial.read();
Serial.print((int) c);

Actually '\n' = 10 (a.k.a. LF, line feed, new line), not to be confused with '\r' = 13 (CR, carriage return). And yes, it's a '\n', as attested by the selection “Newline” on the drop-down menu at the bottom. The other options of this menu are “No line ending”, “Carriage return” and “Both NL and CR”. Note that the last options sends CR before LF.

@EdgarBonet Thanks for your clarification, I put a forward to your comment. It's always better to check the exact character(s) which ends a line.


text:
Send Arduino data to Database using ESP8266
My project is to receive data from Bluetooth (HC-05) sensor and storing it in the database. I have successfully received data from Bluetooth sensor and stored it in a String variable. Now i have to store this data to the database. I want to use the sensors as standalone (not connecting to the PC - operated on battery). Can I store the data to the database using ESP8266.

Since you mention you operate on a battery (standalone), what exactly do you mean by "the database"? Do you have online connectivity? Do you have any peripherals like an sdcard or other storage?
In case you don't have a permanent online connection, you would need to use some writable memory (like EEPROM) to store your data in some organized form. Since the ESP8266 doesn't seem to have any EEPROM built in, you would need to use its flash memory, like described in those answers.
A database could be as simple as a fixed length string list (essentially how string arrays look in memory). For example if the string data you want to save always has 32 bytes, you could just divide your available storage (e.g. 4096 bytes) to have a "database" wich can store 128 entries (4096/32). Your "database entries" will then be addressable in multiples of 32, you would find the 1st entry at byte 0, the 2nd at byte 32 and so on.
Once you are online, you could send the data out for further processing. Getting the data into a database can be as simple as a https request.

I am not using any memory. I am using Firebase as a database to store data. I have arduino uno, esp8266. I have created the project in firebase and copied the host name, key into the program. But when I try to upload the program to arduino I am receiving No such file or directory error for the following header files #include #include #include #include #include. I am following this link. How do i solve the issues.

Missing files most probably mean you didn't include a Library in your IDE. Check the comments in the link you've posted, the listed code looks a bit messed up, while not mentioning any #include<string> lines. Did you try the Examples directly from the firebase repository, or the much better library (from the linked electropeak source article)?


text:
Does the Arduino deteriorate after shorting the voltage regulator?
I mistakenly connected a 7.4V battery backwards to an Arduino Nano via the Vin pin. The Arduino still works (I can upload code) connecting it to the PC using the USB cable. Here's my question: will the Arduino deteriorate using this method or can I continue using it (I'm soon going to buy a new voltage regulator)?

Of course, if you can upload the code, you can continue to use it ;)
Even if the Arduino is cheap, it is really reliable. There are always some short circuit protections.
The Voltage Regulator (I think it is a simple LM1117) has a overcurrent protection too (see: http://www.ti.com/lit/ds/symlink/lm1117.pdf)
So, don't worry. You can continue, continue and continue to use it...
Edit: just a note: never drain more than 50mA on an output. This will destroy the pin on your Arduino.


text:
Serial monitor read value depending on delay
I am working on a small piece of code as shown:

When I enter character 'a' in the Serial Monitor and use a delay in between successive reads then the monitor gives out acceptable results(i.e 97 for character 'a' and 10 for new line) as shown:

Whereas if I do not include the delay, it seems like the microcontroller is not able to read the next value(i.e 10 for new line) immediately and just gives out a -1. And it is only after the loop is run again that we get to see the value 10 for new line(again with -1).

Is my observation correct? If yes, what causes this to occur?
EDIT: I am sorry for the improper format of displaying the code. I am adding the code as below:
#include <Wire.h>

void setup() {

  // Initialize I2C communications as Master
  Wire.begin();
  // Setup serial monitor
  Serial.begin(9600);
  Serial.println("I2C Master Demonstration");
}

void loop() {

  if(Serial.available()>0)
  {
    char c = Serial.read();
    Serial.print((int)c);
    delay(10);
    char d=Serial.read();
    Serial.print((int)d);
    Serial.println("Writing data to slave...");
}
}

please post the code text, not pictures of code ... you have been asked the same thing on your previous post

Ok i will consider it next time.... I thought that showing it graphically would make it easier to interpret!

it makes it very difficult to test your code to see if it even compiles

Are the downvotes just because of improper way of displaying the code? Or because of  the question itself?

possibly, you still show the pictures of the code ... if you remove the pictures and the downvotes get reversed, then you will have your answer

Yes, UART is much slower then the CPU and you run it on extremely slow baud rate. The CPU runs many loops before Serial.available() is again more then 0.
From reference of read() function:

Returns the first byte of incoming serial data available (or -1 if no data is available).

But why is  '-1' here? What does it indicate?

I enhanced the answer

the -1 works 100% correctly only for int data type ... int c = Serial.read(); ... the reason is that -1 is binary 11111111 as a byte (255 decimal) ... it is 1111111111111111 as an integer ... if you receive a valid byte of 255,  your code will see it as meaning no data ... if you receive it as an integer then your code will see it as data ... int 255 = binary 0000000011111111 .... your code receives bytes (char), so you could get into trouble with char(255)


text:
Is possible use Macro F() with Integer and Other types of variable?
i have a sketch that is using very memory RAM of my Atmega2560 (is a giant project), and i need use various "println" because i have a TFT screen and i need to show data on the screen to user see. So, i'm using macro F() to use less RAM memory (example: Serial.println("Hi Naruto-kun") to Serial.println(F("Hi Naruto-kun")). But, it only work if the data entered in F() were to Const String, when i need, by example, show a array of integers, nothing work.
Example:
tft.print(F(mediaTotPg[1]));

This do not work because mediaTotPg is a Integer Array and the errors returned are:
" #define F(string_literal) (reinterpret_cast(PSTR(string_literal))) "
Finally, is possible show integers not const with Macro F()?

For a constant array of integers you need to use PROGMEM and the various pgm_read_*() functions.
You can read more, and find examples, on the Arduino PROGMEM manual page.

Only const array?

Yes. You can't change things in PROGMEM, so it has to be const.  It doesn't have to be an array though, you could use single values, but that makes no sense since if they are const the compiler will optimise them out into inline literals anyway.

F() puts the constant string literal in the flash part of your device. This way it does not use the RAM space otherwise needed.
But your mediaTotPg array is most probably (you didn't say anything about it) a non-const variable, and can't be put in flash memory.
If the values to be shown are in fact const, you need to put them in the flash memory. As Majenko's answer points out in short, you need to use the PROGMEM section for the values, as described on the Arduino PROGMEM page.
The answer to your question is: No, it is not possible to use the macro F() with any type of variable that is not const, and it is not possible to use it for any other type than a string literal.


text:
Problem with counting inside INT0 ISR while in PowerDown
The issue that I have is in INT0 service in which it doesn't perform properly when MCU is set in PowerDown mode. I declared a global variable as "counter" and put it inside INT0 ISR but its value doesn't change.
To make sure that the issue is coming from the Sleeping of the MCU, I commented-out "sleepNow();" inside Loop(), at line 156, and un-commented the following 3 lines and everything was working as expected and variable "counter" was changing correctly. I think I haven't constructed the sleeping part properly, which has caused this issue. I tried to play with the code and searched Google, but I couldn't find that much help. I also looked at the following topics, but those didn't help me either:
Waking up async the Arduino while it's sleeping periodically
Send out a short signal every 10 seconds to an arduino
Use lowpower-libary and still use serial connection and other things
How do interrupts work on the Arduino Uno and similar boards?
My simplified code is here:
#include <SoftwareSerial.h>
#include <avr/sleep.h>
#include <avr/wdt.h>
#include <avr/power.h>

#define Voltage A7                 // Analog Pin A7 | ADC7 - QFN pin 22
#define En_V A0                  // Analog Pin A0 - PC0 -QFN pin 23 | Trigger pin to turn on MOSFETs
#define En_Sensors 9             // Digital Pin D9 - PB1 -QFN pin 13 | Trigger pin to turn on sensor
#define En_I2C2 3
#define En_Sigfox A1       // GPIO9 On Sigfox - It is Set to PULL UP by default in Sigfox module. Set to LOW for waking up

#define SF_rxPin 5     //Sigfox
#define SF_txPin 6     //Sigfox

boolean debug =  true;
SoftwareSerial Sigfox (SF_rxPin, SF_txPin);

///////////////////////Interrupt changes////
const int interruptPin = 2; // INT0 - PD2 | INT1 - PD3
const uint8_t LED = A2;
volatile uint8_t counter = 0;
volatile bool IntFlag = false;
volatile bool WdtFlag = false;
////////////////////////////////////////////
uint8_t MCU_Sleep_Cycle = 4;

void wakeUp()
{
    sleep_disable();
    detachInterrupt(0);// INT0 - PD2 | INT1 - PD3
    counter++;
    IntFlag = true;
}

ISR (WDT_vect)
{
  // WDIE & WDIF is cleared in hardware upon entering this ISR
  wdt_disable();
  WdtFlag = true;
}

void Sleep_Sigfox() {
  digitalWrite(En_Sigfox, HIGH);     // to go into DeepSleep mode
  setPowerMode(2);
}

void setup() {
  pinMode(Voltage, INPUT);
  pinMode(En_V, OUTPUT);
  pinMode(En_Sensors, OUTPUT);
  pinMode(En_I2C2, OUTPUT);
  pinMode(SF_rxPin, INPUT);
  pinMode(SF_txPin, OUTPUT);
  pinMode(En_Sigfox, OUTPUT);

  pinMode(interruptPin, INPUT_PULLUP);

  if (debug) {
    Serial.begin(9600);
  }
  Sigfox.begin(9600);
  delay(3 * 500);
  analogReference(EXTERNAL);
  digitalWrite(En_I2C2, LOW);
  if (debug) {
    Serial.println(F("Hello"));
  }

  digitalWrite(En_Sensors, LOW);
  Sleep_Sigfox();
  delay(2 * 1000);

  attachInterrupt(0, wakeUp, LOW);
}

uint8_t volt() {
  uint16_t tmp = 0;
  float v1, tmp2, tmp3;
  uint8_t v;
  delay(2 * 100);
  tmp = analogRead(Voltage); //A7
  if (tmp > 0) {
    v1 = tmp * 3.3 / 1023;
    tmp2 = v1 * 840 / 33; //10*(51+33)/33;  to represent in 10*V, (51+33)/33 is a HW Voltage divider.
    tmp3 = round(tmp2);
    v = tmp3;
  }
  else {
    v = 0;
  }
  return (v);
}

void loop() {
  //delay(2 * 500);

  if (WdtFlag) {
    wdt_reset();

    if (debug) {
      Serial.println(F("\nI woke up"));
      //Serial.print("IntFlag: ");
      //Serial.println(IntFlag);
      Serial.print(F("WdtFlag: "));
      Serial.println(WdtFlag);
      Serial.print(F("counter: "));
      Serial.println(counter);
      delay(500);
    }

    uint8_t rs = 0;
    uint8_t v = 0;
    char to_be_sent[12];
    memset(to_be_sent, 0, sizeof(to_be_sent));
    digitalWrite(En_V, HIGH);

    delay(300);

    v = volt();
    rs = counter;
    sprintf(to_be_sent,  "%2X%02X", v, rs);
    digitalWrite(En_V, LOW);

    if (debug) {
      Serial.print(F("Volt*10: "));
      Serial.println(v);
      Serial.print(F("RS-count: "));
      Serial.print(rs);
      Serial.println(F("\n"));
      delay(1000);
    }

    ///////////////////////////////// Send Values here
    delay(1 * 50);
    if (debug) {
      Serial.print(F("Sending Message: "));
      Serial.println(to_be_sent);
      delay(20);
    }
    counter = 0;
  }

  if (debug) {

    Serial.print(F("MCU is going into DeepSleep for "));
    Serial.print(MCU_Sleep_Cycle);
    Serial.println(F(" cycles."));
    delay(40);
  }
  for (uint8_t i = 0; i < MCU_Sleep_Cycle ; i++) { //15 cycles = 2min | 6 cycles = 48sec
    if (debug) {
      Serial.print(F("."));
      delay(10);
    }
    sleepNow();
    //WdtFlag=true;
    //attachInterrupt(0, wakeUp, LOW);
    //delay(2*1000);
  }

}

String setPowerMode(uint8_t mode) {
  //0: Software reset
  //1: sleep, send a break to wake up
  //2: deep_sleep, toggle GPIO0 or Reset_N to wake up

  if (debug) {
    Serial.print("Sigfox Power mode: " + String(mode) + "\t");
    //Serial.print(res);
    switch (mode) {
      case 0: Serial.println(F("Soft reset is done.\n")); break;
      case 1: Serial.println(F("Module is in sleep mode. zZzZ\n")); break;
      case 2: Serial.println(F("Module is in DeepSleep mode. zZzZ\n")); break;
    }
    delay(500);
  }

  Sigfox.print("AT$P=");
  Sigfox.print(mode);
  Sigfox.print("\r");
  //String res = getData();
  //return res;
}

void sleepNow() {
  //cli();   //disable interrupts
  EIFR |= (1 << INTF0); // Clearing INTF0 by setting this bit up. Int0 flag cleared.
  EIMSK |= (1 << INT0); //enable INT0

  byte adcsra_save = ADCSRA; //ADC backup
  byte WDTCSR_save = WDTCSR; //WDT backup

  WdtFlag = false;
  IntFlag = false;

  sleep_enable();          // enables the sleep bit in the mcucr register. so sleep is possible. just a safety pin
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here
  ADCSRA &= ~(1 << 7); //clear bit 7 of register ADCSRA and disable ADC
  sleep_bod_disable();
  //power_all_disable ();   // turn off all modules
  sei();//enable interrupts
  attachInterrupt(0, wakeUp, LOW); //when pin 2 gets LOW, run function wakeUp() // INT0 - PD2 | INT1 - PD3
  wdt_enable(WDTO_8S);
  WDTCSR |= (1 << WDIE);
  //sleep_mode();// here the device is actually put to sleep. THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
  sleep_cpu ();

  sleep_disable();
  //power_all_enable ();   // turn on all modules
  sei();
  ADCSRA |= (1 << 7); //Set bit 7 and Enable ADC
  ADCSRA = adcsra_save;  // Config ADC again as before
}

What MCU is used?
The MCU is an ATMEGA328P running on 3.3V at 8MHz
What I want to do?
I would like to put the MCU into deep sleep mode for a fixed period (e.g. 15 minutes, though in the code above I have reduced time to less than a minute), but monitor the number of times the external interrupt is happening. At the end of 15 minutes, when the MCU wakes up, I would like to get the interrupt count total from variable "counter", which should have been incremented by the INT0 ISR, once per external interrupt.
What is the issue?
The issue is that the variable "counter" is not increasing when the MCU is in sleep mode. When the MCU sleeps, the power consumption goes down. The WDT is also working. The interrupt INT0 wakes up the MCU, but value of the counter is not incrementing. I suspect that after the INT0 ISR executes, an MCU reset is happening, reinitializing the "counter" variable -- so that might be the reason why counter keeps staying at zero.
What did I do?
I tried to run the code while the MCU is not sleeping and in that case, variable "counter" works well. So, I suspect my sleeping instructions may not be correct. To do this, I commented line 156, sleepNow();, and un-commented lines 157-159 at the end of main void Loop(){}. Please see attached picture.
What do I expect?
I expect that, while MCU is in sleep mode, it can count the number of external interrupts.
What IDE, compiler and platform am I using?
Arduino IDE adjusted for board Arduino pro mini 3.3V - Windows 8 64bit
But the board that I have is not a genuine Arduino board. I just use the Arduino IDE adjusted for Arduino pro mini since it has the same settings and compilation is easier for me.
Thanks

i do not have time to examine your code in detail, but i see counter = 0; inside the loop() block

@jsotola that part is after reading and printing its value. Moreover, before reaching that line, its value will be copied to variable "rs".

perhaps the compiler has somehow optimized it out of existence ... what happens if you assign a value other than 0 at the variable declaration

@ jsotola, I already tried that one with not giving it an initial value in declaration and still it was zero in readings. After triggering external interrupt, MCU resets and everything starts from "Setup()" and it might be the reason that "counter" is zero. Triggering Ex.Int is not supposed to reset MCU. When I tried without putting MCU in PowerDown mode, everything is fine and external interrupt works as expected. The issue occurs when it is in PowerDown mode.

you may have to use an external counter


text:
Powering NodeMCU with battery and LDO; what if battery is empty?
I want to battery-power my NodeMCU. It will be mostly deep sleeping and waking up every 1-2 minutes.
I've seen the best way to power it with the least wasting of power is through a lithium battery.
So I've bought a 18650 rechargable battery and a MCP1700 LDO which will give me a constant 3.3 V, that will connect straight to the 3.3 V pin and bypass the NodeMCU's regulators, as I understand from here.
My question is: if all of the previous is correct, what will happen when the 18650 battery power fall below the 3.5 V (3.3 V + 0.2 V from MCP1700 dropout)? Will it stop automatically giving power at all? Will it provide less than 3.3 V and will it harm the NodeMCU?

google nodemcu brownout

does the cell have an integrated protection board? if so, then it will just cut-off.

If you battery come with flat head with exact 6.5cm long, it likely is an unprotected type without the built-in over-votage, under-voltage shut down circuit. You will need to get your own protection circuit. Even with the protection circuit, it is likely that cut-off will be around 3v instead of 3.5v. ESP8266 operates at 3.0v to 3.6v, so when your regulator input fall below 3.3v, it won't cut off with or without protection circuit, your regulator will not function properly as it is supposed to be.

If your regulator input voltage is lower than 3.3v, it will not shutdown, it simply unregulated. ESP8266 works between 3.0 to 3.6v, as it draw quite some current at power-up of the WiFi (170mA), it could cause the voltage drop to 3.0v, which will crash the ESP8266. To prevent this happen, make sure your MCP1700 output has a bigger capacitor than recommended 1uF on the datasheet.

As with any electronics, once you get outside of normal operating parameters, behaviour becomes undefined. It's up to you to avoid that.
The smartest thing to do is to employ a battery protection circuit or some means to shut down the system (or prevent it from waking up from deep sleep) before the voltage drops too low. This will also prevent your battery from damage by overdischarging it.
The ESP's minimum operating voltage according to its datasheet is 3.0V. Below that, behaviour is undefined but you can expect unreliable operation, crashes or even permanent damage. If you're writing to Flash memory when below the minimum voltage, the Flash might become corrupted (including the program the ESP is running).

I totally agree..i don't want in any case let esp work under 3v..so..from your answer i understand that the ldo i suggest does NOT provide you this safety..
Could you suggest a circuit that turn will power of the whole system if ldo output is less than 3V?

As far as I can see the MCP1700 does not have an undervoltage protection so I would expect the output voltage to gradually drop when the input falls below the LDO threshold. There are numerous Battery Protection boards available that could provide you with an automatic shutdown safety. You could also use the ADC of the ESP8266 to let it monitor its own supply voltage and take appropriate action.

i guess something based to TP4056 that will shutdown at a specific voltage?
about the ADC, so i connect LDO ground to esp ground, then batteries positive (LDO in) to a esp pin, and in this way "analogRead" my battery voltage?

TP4056 is a charging IC, it is not a voltage regulator. The TP4056 itself does not provide the protection circuitry, some of the TP4056 board has extra circuitry that come with a DW01A chip and 8205 dual-MOSFET to provide the battery over-charge (4.2v), over-discharge (below 3v) protection. You still need the MCP1700 regulator to get 3.3v.


text:
Accessing softwareserial.available in the arduino loop function always return 0 but in the setup function returns the available byte
I am working on an accident detection system using arduino, what i want to do is to store the recipient phonenumber received as an SMS in the arduino EEPROM, using Serial1.available() to check for bytes in the software serial within the loop() function always return 0, but using it in the setup() function work fine, i have tried my best to debug but am not getting, where could i be getting it wrong. the entire code is bellow:
#include<SoftwareSerial.h>
#include <EEPROM.h>
SoftwareSerial Serial1(2, 3); //make RX arduino line is pin 2, make TX arduino line is pin 3.
SoftwareSerial gps(10, 11);
#include<LiquidCrystal.h>
LiquidCrystal lcd(4, 5, 6, 7, 8, 9);

#define x A1
#define y A2
#define z A3

int xsample = 0;
int ysample = 0;
int zsample = 0;

#define samples 10

#define minVal -50
#define MaxVal 50

int i = 0, k = 0;
int  gps_status = 0;
float latitude = 0;
float logitude = 0;
String Speed = "";
String phoneNumber = "";
String gpsString = "";
char *test = "$GNRMC";

void initModule(String cmd, char *res, int t)
{
  while (1)
  {
    Serial.println(cmd);
    Serial1.println(cmd);
    delay(100);
    while (Serial1.available() > 0)
    {
      if (Serial1.find(res))
      {
        Serial.println(res);
        delay(t);
        return;
      }

      else
      {
        Serial.println("Error");
      }
    }
    delay(t);
  }
}

void writeString(char add, String data)
{
  int _size = data.length();
  int i;
  for (i = 0; i < _size; i++)
  {
    EEPROM.write(add + i, data[i]);
  }
  EEPROM.write(add + _size, '\0'); //Add termination null character for String Data

}

String read_String(char add)
{
  int i;
  char data[100]; //Max 100 Bytes
  int len = 0;
  unsigned char k;
  k = EEPROM.read(add);
  while (k != '\0' && len < 500) //Read until null character
  {
    k = EEPROM.read(add + len);
    data[len] = k;
    len++;
  }
  data[len] = '\0';
  delay(2000);
  return String(data);
}

void receive_store_phoneNumber() {
  String msg = Serial1.readString();
  Serial.println(msg);
  phoneNumber = msg.substring((msg.indexOf("***")) + 3);
  writeString(10, phoneNumber);
  lcd.clear();
  lcd.print("Phone num stored");
  delay(2000);
}

void setup()
{
  Serial1.begin(9600);
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.print("Accident Alert  ");
  lcd.setCursor(0, 1);
  lcd.print("     System     ");
  delay(2000);
  lcd.clear();
  lcd.print("Initializing");
  lcd.setCursor(0, 1);
  lcd.print("Please Wait...");
  delay(1000);

  Serial.println("Initializing....");
  initModule("AT", "OK", 1000);
  initModule("ATE1", "OK", 1000);
  initModule("AT+CPIN?", "READY", 1000);
  initModule("AT+CMGF=1", "OK", 1000);
  initModule("AT+CNMI=1,2,0,0,0", "OK", 1000);
  initModule("AT+CMGDA=\"DEL ALL\"", "OK", 1000);
  delay(200);
  Serial.println("Initialized Successfully");
  lcd.clear();
  lcd.print("Initialized");
  lcd.setCursor(0, 1);
  lcd.print("Successfully");
  delay(2000);
  lcd.clear();
  lcd.print("Callibrating ");
  lcd.setCursor(0, 1);
  lcd.print("Acceleromiter");
  for (int i = 0; i < samples; i++)
  {
    xsample += analogRead(x);
    ysample += analogRead(y);
    zsample += analogRead(z);
  }

  xsample /= samples;
  ysample /= samples;
  zsample /= samples;

  Serial.println(xsample);
  Serial.println(ysample);
  Serial.println(zsample);
  delay(1000);

  lcd.clear();
  lcd.print("Waiting For GPS");
  lcd.setCursor(0, 1);
  lcd.print("     Signal    ");
  delay(2000);
  gps.begin(9600);
  get_gps();
  show_coordinate();
  delay(2000);
  lcd.clear();
  lcd.print("GPS is Ready");
  delay(1000);
  //  writeString(10, "+2348132450841");
  lcd.clear();
  lcd.print("System Ready");
  Serial.println("System Ready..");

}

void loop()
{
  if (Serial1.available() > 0) {
    receive_store_phoneNumber();
  }

  int value1 = analogRead(x);
  int value2 = analogRead(y);
  int value3 = analogRead(z);

  int xValue = xsample - value1;
  int yValue = ysample - value2;
  int zValue = zsample - value3;

  Serial.print("x=");
  Serial.println(xValue);
  Serial.print("y=");
  Serial.println(yValue);
  Serial.print("z=");
  Serial.println(zValue);

  if (xValue < minVal || xValue > MaxVal  || yValue < minVal || yValue > MaxVal  || zValue < minVal || zValue > MaxVal)
  {
    get_gps();
    show_coordinate();
    lcd.clear();
    lcd.print("Sending SMS ");
    Serial.println("Sending SMS");
    delay(1000);
    lcd.clear();
    lcd.print(read_String(10));
    Send();
    Serial.println("SMS Sent");
    delay(2000);
    lcd.clear();
    lcd.print("System Ready");
  }
}

void gpsEvent()
{
  gpsString = "";
  while (1)
  {
    while (gps.available() > 0)          //Serial incoming data from GPS
    {
      char inChar = (char)gps.read();
      gpsString += inChar;                   //store incoming data from GPS to temparary string str[]
      i++;
      //     Serial.println("88888888888888888888888888888888888888888888");
      //     Serial.println(inChar);

      if (i < 7)
      {
        if (gpsString[i - 1] != test[i - 1])    //check for right string
        {
          i = 0;
          gpsString = "";
        }
      }
      if (inChar == '\r')
      {
        if (i > 60)
        {
          gps_status = 1;
          break;
        }
        else
        {
          i = 0;
        }
      }
    }
    if (gps_status)
      break;
  }
}

void get_gps()
{
  lcd.clear();
  lcd.print("Getting GPS Data");
  lcd.setCursor(0, 1);
  lcd.print("Please Wait.....");
  gps_status = 0;
  int x = 0;
  while (gps_status == 0)
  {
    gpsEvent();
    int str_lenth = i;
    coordinate2dec();
    i = 0; x = 0;
    str_lenth = 0;
  }
}

void show_coordinate()
{
  lcd.clear();
  lcd.print("Lat:");
  lcd.print(latitude);
  lcd.setCursor(0, 1);
  lcd.print("Log:");
  lcd.print(logitude);
  Serial.print("Latitude:");
  Serial.println(latitude);
  Serial.print("Longitude:");
  Serial.println(logitude);
  Serial.print("Speed(in knots)=");
  Serial.println(Speed);
  delay(2000);
  lcd.clear();
  lcd.print("Speed(Knots):");
  lcd.setCursor(0, 1);
  lcd.print(Speed);
}

void coordinate2dec()
{
  String lat_degree = "";
  for (i = 20; i <= 21; i++)
    lat_degree += gpsString[i];

  String lat_minut = "";
  for (i = 22; i <= 28; i++)
    lat_minut += gpsString[i];

  String log_degree = "";
  for (i = 32; i <= 34; i++)
    log_degree += gpsString[i];

  String log_minut = "";
  for (i = 35; i <= 41; i++)
    log_minut += gpsString[i];

  Speed = "";
  for (i = 45; i < 48; i++)   //extract longitude from string
    Speed += gpsString[i];

  float minut = lat_minut.toFloat();
  minut = minut / 60;
  float degree = lat_degree.toFloat();
  latitude = degree + minut;

  minut = log_minut.toFloat();
  minut = minut / 60;
  degree = log_degree.toFloat();
  logitude = degree + minut;
}

void Send()
{
  Serial1.println("AT");
  delay(500);
  serialPrint();
  Serial1.println("AT+CMGF=1");
  delay(500);
  serialPrint();
  Serial1.print("AT+CMGS=");
  Serial1.print('"');
  Serial1.print(read_String(10));    //mobile no. for SMS alert
  Serial1.println('"');
  delay(500);
  serialPrint();
  Serial1.print("Latitude:");
  Serial1.println(latitude);
  delay(500);
  serialPrint();
  Serial1.print(" longitude:");
  Serial1.println(logitude);
  delay(500);
  serialPrint();
  Serial1.print(" Speed:");
  Serial1.print(Speed);
  Serial1.println("Knots");
  delay(500);
  serialPrint();
  Serial1.print("http://maps.google.com/maps?&z=15&mrt=yp&t=k&q=");
  Serial1.print(latitude, 6);
  Serial1.print("+");              //28.612953, 77.231545   //28.612953,77.2293563
  Serial1.print(logitude, 6);
  Serial1.write(26);
  delay(2000);
  serialPrint();
}

void serialPrint()
{
  while (Serial1.available() > 0)
  {
    Serial.print(Serial1.read());
  }
}

only one SoftwareSerial instance can listen. it is set with listen(). https://www.arduino.cc/en/Reference/SoftwareSerialListen

how do i implement that in my code, am so frustrated already, i need hints please

As Juraj stated in the comments, you have 2 instances of SoftwareSerial, but only one of them can listen to it's receive pin at the same time (this is because they rely on the same interrupts to sample the pin). When you call gps.listen(), you set the gps interface to listen on it's receive pin. Serial1 (the second SoftwareSerial instance) will then no longer listen and thus will not receive anything. When you call Serial1.listen() it will be vice versa.
So you need to decide, on which interface you want to listen. For example you could try listening to the GPS all the time, and only switch to the other interface, if you want to send or receive an SMS (since the SIM module seems to be only controlled via AT commands, it will not send data spontaneously).
Or, as an alternative, you could switch to a bigger Arduino, which has more hardware serial interfaces, like the Arduino Mega. It has 4 hardware Serial interfaces and all of them are listening at the same time, since it is implemented in hardware, not in software.

I commented because I was sure this is a duplicate, but I had no time to search for it


text:
ESP8266 as ISP for Arduino Mega2560
I'm trying to use an ESP8266 Node MCU 1.0 (ESP-12E Module) as an ISP to program an Arduino Mega2560 over Wifi with no USB cable. (USB connected to ESP8266 module just for power).
I used the sketch 'Arduino_Wifi_AVRISP' from the Arduino IDE and modified the STASSID & STAPSK to match my wifi settings.
I followed the procedure found in this other post and was able to program the ESP8266 with success:
ESP8266 as ISP program for ATMega16
However, when I run the command line:
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude" -C"C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -c stk500v2 -p m2560 -P net:192.168.1.246:328 -Uflash:w:C:\Users\dom\AppData\Local\Temp\arduino_build_199262/blink.ino.hex:i

I get the following response:
avrdude: Version 6.3-20171130
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2014 Joerg Wunsch

     System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : net:192.168.1.246:328
     Using Programmer              : arduino
avrdude: ser_drain(): read error: The parameter is incorrect.

avrdude: ser_drain(): read error: The parameter is incorrect.

avrdude: ser_drain(): read error: The parameter is incorrect.

     AVR Part                      : ATmega2560
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    10     8    0 no       4096    8      0  9000  9000 0x00 0x00
       flash         65    10   256    0 yes    262144  256   1024  4500  4500 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : Arduino
     Description     : Arduino

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x14

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x10
     Hardware Version: 4744608
     Firmware Version: 0.2
     Topcard         : STK502
     Vtarget         : 1.8 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

avrdude: stk500_initialize(): (b) protocol error, expect=0x10, resp=0x01
avrdude: initialization failed, rc=-1
     Double check connections and try again, or use -F to override
     this check.

avrdude: stk500_disable(): protocol error, expect=0x14, resp=0x10

avrdude done.  Thank you.

Everything is connected as it is in the post previously mentioned. What could be causing me to get this issue?
Does it not use the "arduino" protocol for Arduino Mega2560?
Are the 3.3v pins just not sufficient to program the 5v Arduino?
As I mentioned, I'm only using USB to power the the ESP8266, not the Arduino so I don't damage the ESP pins.
Thank you.

see the avrdude command used by IDE (in the console).

When I compile the sketch I want to upload i get this avr command in the Arduino IDE console:
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude" -C"C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -patmega2560 -cwiring -PCOM4 -b115200 -D -Uflash:w:C:\Users\dom\AppData\Local\Temp\arduino_build_742925/blink.ino.hex:i

So i turned it into this to be able to program the Mega2560 thru the ESP8266 via Wifi over the CMD prompt:
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude" -C"C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -patmega2560 -cwiring -P net:192.168.1.246:328 -D -Uflash:w:C:\Users\dom\AppData\Local\Temp\arduino_build_742925/blink.ino.hex:i

And it returned this now:
     Using Port                    : net:192.168.1.246:328
     Using Programmer              : wiring

avrdude: ser_drain(): read error: The parameter is incorrect.
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

now I remembered. the "Arduino as ISP" has only stk500v1 protocol and avrdude uses stk500v2 "wiring" configuration for Mega.

do you know my ArduinoOTA library for Mega? https://github.com/jandrassy/ArduinoOTA


text:
help with an outlaw pinewood derby car
So I am trying to create a code for an outlaw pinewood derby car. It is using a brushless esc with reverse for a ducted fan. The car has a push button on the front along with headlight and brake light LED's.
My goal is to push the front button 5 times to activate the car, then place it against the gate (which will press the front button once again and keep it pressed until the gate falls and the race begins). Once the button is released I want the fan to turn on and push the car down the track. once a certain amount of time passes (enough time to cross the finish line, I will get this info once I get a chance to do some test runs, but for now let's say 1.5 secs) it will reverse the fan (to act as a brake) for another certain amount of time, as well as activate the brake lights. then turn off the fan completely.
A buddy and I have been trying to write a code for it but are at a loss.
Any suggestion or input would be greatly appreciated.
#include <Servo.h>                    //Use the Servo library for generating PWM
Servo ESC;                            //name the servo object, here ESC
int headLightLED = 7;                 // White LED headlights
int brakeLightLED = 15;               // Red LED tailights
int throttle = analogRead(A0);        //Read the voltage from POT
int DigitalPot = 6;                   //Digital potentiometer used to map ESC
int potValue = A0;                    // value from the analog pin
int MicroSwitch = 9;                  // Front momentary push button

void setup()
{
pinMode (headLightLED, OUTPUT);       // set headlights to output
pinMode (brakeLightLED, OUTPUT);      // set tailights to output
pinMode (DigitalPot, OUTPUT);         // Set digital potentiometer to output
pinMode (MicroSwitch, INPUT);         // set front switch to input
ESC.attach(10,1000,2000);             // Generate PWM in pin 10 of Arduino
delay (100);
ESC.write(10);                        // Activate ESC
delay(3000);                          // Wait for ESC to boot

throttle = map(throttle, 0, 1023, 0, 180); //Map the values of 0-1023 from pot to 0-180 bcs servo works only from 0-180

     delay(1000);
    digitalWrite(DigitalPot, LOW);       //Send mininum signal to A0
    analogRead (potValue);
    delay(1000);
    digitalWrite(DigitalPot, HIGH);    // Send Maximum signal to A0
    analogRead (potValue);
    delay(1000);
    digitalWrite(DigitalPot, LOW);       //  Return to zero throttle
    analogRead (potValue);
    delay(1000);
}

void loop()
{
    if (MicroSwitch == HIGH){
      int timeLapsed = millis();
    }else(MicroSwitch == LOW);
ESC.write(throttle);                   // based on the value of throttle generate PWM signal
 digitalWrite(throttle, 180);               // Full Speed
 delay(1500);
  digitalWrite(throttle, 0);                 // Full Reverse
  digitalWrite (brakeLightLED, HIGH);        // activate brake lights
  delay(1500);
  digitalWrite (throttle, 90);               // STOP
}

Welcome to Arduino:SE. You might find this post on our Meta site helpful: How to ask a good question for Arduino Stack Exchange.

are we supposed to guess what works and what does not work as intended?

You need to state what's wrong with your code/what you are struggling with. You also need to edit your question and find your indentation. As it is the code is just about impossible to follow.


text:
Is Arduino Mega useing one buffer or multiple buffers?
So Arduino Mega has Serial, Serial1, Serial2, Serial3.
However, does those Serial lines use the same buffer? or four independent ones? i.e. are they truly receive single independently, or actually some sort of software sharing? How will that affect the coding?

what problems have you encountered?

@jsotola Not yet, but I'm trying to use UART to do a fast control system with distributive components. So there would be lots of data in ms circles in multiple ports at once. Basically, I'm trying to use over flow of data to establish fast and reliable processing... and it's kind of good to know how that buffer was working.

makes sense to be proactive .... you could run a test by feeding the same data to all three ports and read the data at varying speeds from the three ports .... you could connect the three receive pins together .... read in random sized chunks

Actually there are 2 buffers per Serial hardware interface: The hardware buffer, that is 1 byte (per direction of data transfer). The Serial library then transfers this byte in an extra buffer (64 bytes big) from an ISR. Every hardware Serial interface (Serial and Serial1 to 3 on the Mega) has it's own hardware buffer.
Then the Serial library is implemented as a class. Every hardware Serial interface get's it's own instance of this class, including the 64 byte buffer.
So the hardware and the memory is completely seperated. The only thing, what they share, is the CPU time for servicing the interrupts, which is no problem, until you are doing somehting very wrong with interrupts.

Every instance of class HardwareSerial has own buffers. Here you can see it in source code. The instances are declared/definded at the end of the HardwareSerial.h/.cpp.


text:
HTTP Post data from Arduino uno using WiFi
Please help me to post data from arduino uno to a webpage using wifi(ESP-01) module. I try with AT commands it didn't give the response from my webpage

#include <SoftwareSerial.h>
#include <ArduinoJson.h>
#define DEBUG true

#define RX 10
#define TX 11
String WIFI_SSID = "*****";       // Your WiFi ssid
String PASSWORD = "*****";         // Password
//String DEVICE_SECRET_KEY  = "**";

//String PATH = "/v1/events";
//String PORT = "8000";
//String HOST = "http://10.**.***.66:8000/data";

String HOST = "10.**.240.**";
String PATH = "/data";
String PORT = "8000";

String response;
int countTrueCommand;
int countTimeCommand;
boolean found = false;

SoftwareSerial esp8266(RX, TX);
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();

void setup()
{
  Serial.begin(115200);
  esp8266.begin(115200);
  esp8266.println("AT");
  Serial.println(esp8266.read());
  sendCommandToESP8266("AT", 5, "OK");
   sendCommandToESP8266("AT+CWMODE=3", 5, "OK");
  sendCommandToESP8266("AT+CWJAP=\"" + WIFI_SSID + "\",\"" + PASSWORD + "\"", 20, "OK");
}

void loop()
{
  root["key"] =  "sdfsdfsd";
  String key;
  root.printTo(key);
  String postRequest =   "POST " + PATH  + " HTTP/1.1\r\n" +
                         "Host: " + HOST + "\r\n" +
                         "Accept: *" + "/" + "*\r\n" +
                         "Content-Length: " + key.length() + "\r\n" +
                         "Content-Type: application/json\r\n"
                         "\r\n" + key;
  Serial.print("pst:" + postRequest);
  sendCommandToESP8266("AT+CIPMUX=1", 5, "OK");
  sendCommandToESP8266("AT+CIPSTART=0,\"TCP\",\"" + HOST + "\"," + PORT, 15, "OK");
  String cipSend = "AT+CIPSEND=0," + String(postRequest.length());//GET /test.php?Data=2\r\nHost:192.168.1.13\r\n\r\n
  sendCommandToESP8266(cipSend, 4, ">");
  sendData(postRequest);

  while (esp8266.available())
  {
    if (esp8266.find("+IPD,"))
    {
//      String msg;
      esp8266.find("?");
//      msg = esp8266.readStringUntil(' ');
      response = esp8266.readStringUntil(' ');
      Serial.print(response);
      Serial.println();
    }
  }
  printResponse;

  //  sendCommandToESP8266("AT+CIPCLOSE=0", 5, "OK");
}

void sendCommandToESP8266(String command, int maxTime, char readReplay[]) {
  Serial.print(countTrueCommand);
  Serial.print(". at command => ");
  Serial.print(command);
  Serial.print(" ");
  while (countTimeCommand < (maxTime * 1))
  {
    esp8266.println(command);
    if (esp8266.find(readReplay))
    {
      found = true;
      break;
    }

    countTimeCommand++;
  }

  if (found == true)
  {
    Serial.println("Success");
    countTrueCommand++;
    countTimeCommand = 0;
  }

  if (found == false)
  {
    Serial.println("Fail");
    countTrueCommand = 0;
    countTimeCommand = 0;
  }

  found = false;
}

void sendData(String postRequest) {
  Serial.println(postRequest);
  Serial.println();
  esp8266.println(postRequest);
  delay(15000);
  countTrueCommand++;
}

void printResponse() {
  while (esp8266.available()) {
    Serial.println();
    Serial.println(esp8266.readStringUntil('\n'));
  }
}

Please help me to get the response from the webpage using this code.

SoftwareSerial doesn't work at 115200 baud. change the baud rate in AT firmware and for SoftwareSerial to 9600 baud.

@Juraj i try by changing the baud rate but still there is no response from my webpage

@Juraj Or please let me know that if there is any another way to post data from arduino uno by using wifi.(ESP01 module).   I see many programs that are using ethernet and anothehr wifi modules.

if you want something like Ethernet library you can use my WiFiEspAT library. but it requires to change the AT firmware in esp-01 to version 1.7 https://github.com/jandrassy/WiFiEspAT/blob/master/README.md

@Juraj can i use the above mentioned library with arduino uno and esp01?   Iam a beginner in arduino programming that's why asking about these questions.

the WiFiEspAT library handles the AT commands for you. the wiring is same has you have now

@Juraj I just want to know how to change the version of esp-01 to versio 1.7. Is esp-01 works when version is not changed?

with old AT firmware you can use the old WiFiEsp library.

@Juraj https://github.com/bportaluri/WiFiEsp/blob/master/examples/ConnectWPA/ConnectWPA.ino I try to use this code but it shows as wifi shield is not present.

set 9600 baud in AT firmware. the libraries are in Library Manager in IDE

@Juraj when i use the library   i got the below output on serial monitor.                                                                      [WiFiEsp] Initializing ESP module [WiFiEsp] >>> TIMEOUT >>> [WiFiEsp] >>> TIMEOUT >>> [WiFiEsp] >>> TIMEOUT >>> [WiFiEsp] >>> TIMEOUT >>> [WiFiEsp] >>> TIMEOUT >>> [WiFiEsp] Cannot initialize ESP module [WiFiEsp] >>> TIMEOUT >>> [WiFiEsp] No tag found WiFi shield not present

did you set the baud rate to 9600 baud in firmware and in sketch?

@juraj Sorry!! I forget to change the baud rate. Now wifi is getting connected using esp library. And can you please help me to post data from arduino using this library and how to get the response back from the server.

@juraj when i try to post data from arduino to webpage it will not sending the data and not connecting to server serial monitor shows as :
`Starting connection to server...
[WiFiEsp] Connecting to xxx.xx.xxx.xx
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] No tag found
Disconnecting from server...
`

Step 1) Upload software serial from example and send AT, you should get reply as AT OK if your connections are correct.
Step 2) Once your connections are correct and if you are uploading the given code then make sure you put your SSID, password, and Server IP which would be the three Strings: HOST, PATH and PORT.
You could alternatively check your server first by sending it a GET or POST using your browser or another software for testing API's(I personally use POSTMAN).
Proceed further once you perform these checks.

I tried this and still not getting response from the webpage. Also API have no problems when i check it.

Did you try the AT command check? Upload software serial and you can manually enter AT commands and check where you are going wrong.

I have 2 esp-01 modules with me. I think one of my esp is corrupted. But other one is working when check by AT command.

Now you can check each command that is being used via Software Serial. For example according to your code if u send "AT+CWMODE=3" u will get a reply OK. You can do a complete post request just using software serial by inputting commands one after the other. Its a good practice to do this as it will help you understand at what point your code is going wrong.

I tried by sending all the AT commands and i stop where AT+CIPSTART=0,"TCP","xx.xxx.xxx.xx","port" from this command i got error message. what can i do to make it correct?

Try this command AT+CIPSTART="TCP","192.168.3.116",8080 Change the server ip and port accordingly. The 0 indicates id of the connection in AT+CIPSTART=0,"TCP","xx.xxx.xxx.xx","port" . I found the id being used only for a UDP connection in the espressif at command example. I referred this link. Did you execute the AT commands in the sequence given in your question?

I check with the AT commands. But   AT+CIPSTART="TCP","192.168.3.116",8080 this command is not working. I didin't understand what the problem is. All the other commands before AT+CIPSTART is working with the module.


text:
Upload already compiled code on Linux CLI without arduino-cli
I have a sketch for an Arduino Nano. I'm compiling it on my build server and get these 3 files:

project.bin.elf
project.bin.hex
project.bin.with_bootloader.hex

Now I need to be able to upload/flash them onto the board (connected via a serial interface) without arduino-cli. Mainly because I can't install it via apt-get which means I'd have to start jumping through loops to be able to use it (stuff like keeping it up to date, installing, etc. on hundreds of devices).
So I was wondering if there are any tools in the debian repositories I can use to upload the compiled sketch and if so how.
I've been looking for a solution and came across several answers and topic but strangely enough all either use arduino-cli, other specialized tools or link to dead pages or pages that no longer contain the answer.
Examples:

How to compile, upload and monitor via the Linux command line?
Compiling sketch vi command line

avrdude is your friend.

upload Blink to Nano from IDE and then copy the avrdude command from IDE console and modify it to upload the project.bin.hex file

@Juraj do I see this command on the Windows version too? Alternatively could I get arduino-cli to output the command? Because I have test boards available I can install anything on. (I just can't get it on every board)

turn on verbose mode

Use avrdude.
The command format is simple, assuming you have installed it from the Linux repositories:
avrdude -carduino -patmega328p -P/dev/ttyUSB0 -b115200 -Uflash:w:/path/to/project.bin.hex:i

Depending on what bootloader is installed in your nano you may need to change the  baud rate (-b115200) to 57600. Also, of course, the USB device should be set to what your board actually identifies as.
The breakdown of the command is:
-c<programmer type>
-p<part name>
-P<port>
-b<baud rate>
-U<instruction>

The programmer type, part name and baud rate can all be gleaned from the boards.txt file in the AVR core files.  For example, for the Nano:
nano.upload.protocol=arduino
nano.menu.cpu.atmega328.upload.speed=115200
nano.menu.cpu.atmega328.build.mcu=atmega328p

relate to -c -b and -p respectively.  The instruction will always be the same, and means "Write to flash the following file in IHEX8 format".  "flash" is the destination memory, "w" is the write command, and ":i" at the end defines the expected file format.
On a Linux computer with avrdude installed you can find much more information with man avrdude.

That answers my question, but since SE is meant as an enciclopedia of sorts, I think it would be beneficial to explain how you figure out that command line call for other boards. (And also because I managed to find a similar call after some playing around and watching the processes in htop while trying to flash with arduino-cli)

@BrainStone Like that?

Excellent. Thank you very much

if you are unsure of the settings that you should use, then you can use the Arduino IDE to determine them .... in settings, turn on show verbose output during upload .... then upload any sketch .... in the status panel in the Arduino IDE you will see the correct avrdude command line .... something like E:\arduino-nightly\hardware\tools\avr/bin/avrdude -CE:\arduino-nightly\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\xxxxx\AppData\Local\Temp\build3bb8345d83cedc585b1cb6c2216554cb3.tmp/BasicSerial.ino.hex:i


text:
Is there any DS2482 I2C to 1-Wire bridge functional library?
Please let me know if you know any good library for DS2482 I2C to 1-Wire bridge.
I tried to use the DS2482_OneWire library  but I got errors when trying to run the library examples (Read_temp_sensors and Scan_1Wire_Bus):
Error for Read_temp_sensors:

Read_temp_sensors:2:10: fatal error: DallasTemperature.h: No such file or directory

Error for Scan_1Wire_Bus:

Scan_1Wire_Bus
C:\Users\myuser\Documents\Arduino\libraries\DS2482_OneWire-master\OneWire.cpp: In member function 'uint8_t OneWire::waitOnBusy()':
C:\Users\myuser\Documents\Arduino\libraries\DS2482_OneWire-master\OneWire.cpp:121:3: error: 'delayMicroseconds' was not declared in this scope
delayMicroseconds(20);
^~~~~~~~~~~~~~~~~
exit status 1 Error compiling for board Arduino Nano.**

Thank you.

Please take a look at this library, https://github.com/mikaelpatel/Arduino-OWI. It handles both DS2482 and GPIO implementation. https://github.com/mikaelpatel/Arduino-OWI/blob/master/examples/DS2482/DS18B20/DS18B20.ino

The documentation may be found here, https://mikaelpatel.github.io/Arduino-OWI/dc/dfe/Hardware_2OWI_8h.html and https://mikaelpatel.github.io/Arduino-TWI/d4/d53/classDS2482.html

Thank you very much!

I guess to solve the first error, you also need this library, which contains the DallasTemperature.h file. The file get's included, but is not contained in the DS2482 library. Unfortunately there is no clue for that in the readme of the library. The author didn't commit anything since 2014, so the development of the library can be considered dead from that side. Though some people have forked the library to make little changes.
And the solution to the second error is described in this issue of the DS2482 library (just adding an include of "Arduino.h" in the OneWire.cpp file).

Hello @chrisl, Thank you for your prompt answer. I don't know how to implement it: "// Constructor with no parameters for compatability with OneWire lib
OneWire::OneWire()"... ecc " I still get an error for the second issue: bool isAllZeros(const uint8_t* const scratchPad, const size_t length = 9);
   ^~~~~~~~~~   Maybe you can still help me...

Please include your current code into your question, then I can test this myself

Hello @chrisl. Thank's again for your time. Firstly I just want to run the examples included in the library. So the last error presented before was associated with Scan_1Wire_Bus.  Please let me know if you are able to run all the ex file. Thank you

I dowloaded the DS2482 library and also the Arduino-Temperature-Control library, as described in my answer. After adding include "Arduino.h" to the top of OneWire.cpp I could successfully compile the example sketch Scan_1Wire_Bus.ino` from the DS2482 library for the Arduino Nano. I use Arduino IDE 1.8.9

Hello @chrisl.Unfortunately,for me is still not working.If I install only 2 libraries that you recommend before I'm getting errors when I'm using #include <DallasTemperature.h>.If I install the OneWire library directly from Manage Library I will not receive errors for the inclusion of "DallasTemperature.h": but I'm getting new errors I think because both libraries (DS2482/OneWire) has the same name "OneWire ".Because of this the object defineded in DS2482 are not visible anymore (class OneWire'has no member named 'checkPresence') Please let me know if I'm doing something wrong now . Thank you

Then you have 2 options: You can delete the OneWire library and only keep the DS2482 one. Or you can rename the DS2482 OneWire class to a different name. For the second option you would need to rename it both in OneWire.h and OneWire.cpp


text:
Error compiling for Arduino Nano 33 BLE with LiquidCrystal library
I recently started coding in the Arduino IDE for the Arduino Nano 33 BLE I bought.
When I choose the Nano 33 BLE as my board, I get the following Error:
Arduino: 1.8.11 (Windows 10), Board: "Arduino Nano 33 BLE"

In file included from C:\Users\Niels\Documents\Arduino\libraries\LiquidCrystal\src\LiquidCrystal.cpp:1:0:

C:\Users\Niels\Documents\Arduino\libraries\LiquidCrystal\src\LiquidCrystal.h:45:36: error: expected class-name before '{' token

 class LiquidCrystal : public Print {

                                    ^

C:\Users\Niels\Documents\Arduino\libraries\LiquidCrystal\src\LiquidCrystal.h:86:9: error: 'Print' has not been declared

   using Print::write;

         ^~~~~

exit status 1
Error compiling for board Arduino Nano 33 BLE.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

I do not get this error when compiling for a normal Arduino nano board.
This is my code:
#include <Arduino_LSM9DS1.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(12,11,5,4,3,2);

//pins:
const int measurePin = 13, calibratePin = 14, xHighPin = 15, xLowPin = 16, yHighPin = 17, yLowPin = 18;

//constants:
const int interval = 10;
const float delta = 10;

//variables:
boolean measureSts = LOW, calibrateSts = LOW, xyOK = true;
int count = 0, timer = 0;
float measurements[100], current, x, y, z, xZero, yZero, zZero;

//programm:
void setup() {
  lcd.begin(16,2);

  pinMode(measurePin, INPUT);
  pinMode(calibratePin, INPUT);
  pinMode(xHighPin, OUTPUT);
  pinMode(xLowPin, OUTPUT);
  pinMode(yHighPin, OUTPUT);
  pinMode(yLowPin, OUTPUT);
}

void loop() {
  if ( IMU.accelerationAvailable() ) {
    IMU.readAcceleration(x, y, z);
    calibrate();
    checkXY();
    measure();
    current = z - zZero;
    printValues();
  }
  else lcd.print("--geen  sensor--");
}

void checkXY() {
  xyOK = true;
  if ( x < xZero - delta ) {
    xyOK = false;
    digitalWrite(xLowPin, HIGH);
    digitalWrite(xHighPin, LOW);
  }
  else if ( x > xZero + delta ) {
    xyOK = false;
    digitalWrite(xLowPin, LOW);
    digitalWrite(xHighPin, HIGH);
  }
  if ( y < yZero - delta ) {
    xyOK = false;
    digitalWrite(yLowPin, HIGH);
    digitalWrite(yHighPin, LOW);
  }
  else if ( y > yZero + delta ) {
    xyOK = false;
    digitalWrite(yLowPin, LOW);
    digitalWrite(yHighPin, HIGH);
  }
}

void measure(){
  if ( digitalRead(measurePin) == LOW && measureSts == HIGH && xyOK ) {
    measurements[count] = z - zZero;
    zZero = z;
    timer = interval;
    count++;
  }
  measureSts = digitalRead(measurePin);
}

void printValues() {
  if ( timer >= interval ) {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Meting: " + String(measurements[count]) + (char)223);
    lcd.setCursor(0,1);
    lcd.print("Huidig: " + String(current) + (char)223);
    timer = 0;
  }
  timer++;
}

void calibrate() {
  if ( digitalRead(calibratePin) == LOW && calibrateSts == true ) {
    xZero = x;
    yZero = y;
    lcd.setCursor(0,3);
    lcd.print("kalibreren");
    lcd.setCursor(1,4);
    lcd.print("voltooid");
    digitalWrite(xHighPin, HIGH);
    digitalWrite(xLowPin, HIGH);
    digitalWrite(yHighPin, HIGH);
    digitalWrite(yLowPin, HIGH);
    delay(100);
    lcd.clear();
    digitalWrite(xHighPin, LOW);
    digitalWrite(xLowPin, LOW);
    digitalWrite(yHighPin, LOW);
    digitalWrite(yLowPin, LOW);
  }
  calibrateSts = digitalRead(calibratePin);
}

For context: I am trying to create an angle-measuring device using the built-in accelerometer and a 2x16 LCD.
I hope someone can help me fixing this.
Thanks in advance.
-Niels

try in LiquidCrystal.h to replace #include <Print.h> with #include <Arduino.h> (I don't know what LiquidCrystal library do you use. there are many)

I replaced #include"Print.h" with #include"Arduino.h" as you said. Now it works. Thanks!

The Arduino core for Nano 33 BLE is based on Mbed and can be used in Mbed as library. To achieve this, the Arduino API classes in this core are put in a namespace arduino::. This causes problems for libraries which include individual includes of Arduino API historically copied into cores for different MCU architecture platforms. The Arduino.h file includes the API files in the right way so in this case replacing #include"Print.h" with #include <Arduino.h> in LiquidCrystal.h solves the compilation problem.


text:
LCD screen stops displaying after DC motor starts
LCD screen stops displaying after DC motor starts
I have 3 main components: LCD, thermal resistor, and a DC motor running a fan. The LCD displays the temperature reading from the thermal resistor and then after it hits a certain temperature the motor turns on.
A few seconds after the motor has been turned on the LCD will go blank (but still powered on). I tried connecting a 100uF electrolytic capacitor across between the logic supply pins on the LCD and a 0.47 µF ceramic between the motor terminals.
I did this because i'm assuming since the motor in operation (its commutator) produces voltage/ current "spikes" they can be coupled back through the common power supply. This could provide some immunity against them actually getting to the display driver and interfering with its operation.
What I did kind of helped, but I feel like I am missing something. Any suggestions?
(the link is to the picture of my circuit I quickly made online)

What is the voltage at the LCD and motor when the motor is running? Is the motor not simply overloading the Arduino's power supply?

Where did you draw this circuit online?

what happens if you disconnect the motor?

@ThomasWeller, google image search reveals     https://www.tinkercad.com

@StarCat LCD is at 4.82V and the motor is at 4.0V

@StarCat I tried connecting a 9v battery through the port to help aid the board, but I still get the same issue. I am thinking about just using a 5V relay to trigger the fan and just isolate the DC motor as a whole and see if that works

Those voltages don’t look too bad (but not great either). Does your program keep running and does the display return to normal after the motor has stopped? Isolating the motor sounds like a plan.

A brush DC electric motor and many other similar devices will produce random noise as well as uneven power demands and should be powered independently of logic circuits such as processors and LCDs.  It is very difficult to mediate noise sources and almost always better to remove them from where they are causing harm or unexpected results.
It is also important to power a project with a supply capable of providing more than the expected amperage during highest demand.  Many will calculate the highest amperage demand and select a power supply which is rated at double the amperage.
If you are using batteries, note that a 9 volt battery (which usually contains 6 cells) on average supplies about 500mAh.  Not much and likely not enough to run a motor with out momentarily dropping the voltage.  Where as a D-size battery supplies about 15000mAh.  Different battery chemistries change the mAh rating drastically.  500mAh and 15000mAh are about what one may expect from Alkaline batteries.
If using a USB power source, note that older USB ports are only obliged to supply 500mA at any given time.  If this current limit is exceeded, the voltage may drop under 5 volts.
There are many designs on the internet where the motor is powered from the Arduino.  This may be possible for smaller motors however you are having unexpected behavior.  Consider using one or more of the following suggestions to mitigate your problems:

Avoid low mAh batteries such as common 9 volt batteries.  Instead use a battery that can provide higher mAh like D Size cells.
Avoid powering noisy or current demanding devices directly from the Arduino.  Consider an independent power supply and use a common ground.
It may be possible to use a single power supply with good results if the power supply is rated at higher amperage than the peak total maximum amperage.