body:
As explained by theSealion in his answer, this may be due to the
different background tasks performed by the microcontroller. However, I
personally find that 1 ms looks excessive. My guess is that the
main culprit is the USB stack pushing all those bytes down the wire.

In order to check this, I wrote the following program. It measures a
histogram of the loop execution times and then prints it through the
serial port. Since the data is only printed _after_ the measurements are
done, the serial port does not do any work while the timings are being
measured.

```c++
const int HISTOGRAM_LENGTH = 512;

uint16_t histogram[HISTOGRAM_LENGTH];

void print_histogram() {
    Serial.println(F("t (us)  count"));
    Serial.println(F("-------------"));
    for (int i = 0; i < HISTOGRAM_LENGTH; i++) {
        if (histogram[i] == 0) continue;  // skip zeros
        Serial.print(i * 4);
        Serial.print('\t');
        Serial.println(histogram[i]);
    }
    Serial.println(F("-------------"));
    Serial.flush();
}

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

void loop() {
    static uint32_t last_time;
    uint32_t now = micros();
    uint32_t dt = now - last_time;
    uint32_t bin = dt / 4;  // resolution of micros() is 4 us
    if (bin >= HISTOGRAM_LENGTH)
        bin = HISTOGRAM_LENGTH - 1;
    if (++histogram[bin] == UINT16_MAX) {
        print_histogram();
        exit(0);
    }
    last_time = now;
}
```

These are the results when run on an Arduino Uno:

```text
t (us)  count
-------------
8       21888
12      65535
16      632
20      323
56      1
-------------
```

This shows that most loop iterations take 8–12 µs. Those iterations
that were interrupted took 16–20 µs. The outlier at 56 µs is
most likely the time between the program starting and the very first
iteration of `loop()`.

Here, the only interrupt source that affects the measurements is the
timer interrupt. It fired exactly 955 times during the measurement
period, which is consistent with the number of samples recorded at
16–20 µs. We can see from this data that the timer interrupt takes
roughly 8 µs to run, which is quite reasonable. Again, I would not
consider a 1 ms delay as reasonable.


sender: user

message:
Unconsistent time in arduino loop

I have this code:

[![enter image description here][1]][1]

-----------------------------------------------

The output looks like this:

[![output][2]][2]

Why are there non-periodically some extremely large values?

Thanks

  [1]: https://i.stack.imgur.com/p0XtM.png
  [2]: https://i.stack.imgur.com/mGbnf.png

sender: assistant

body:
> In addition, the original problem for this question was that I am
> driving a stepper motor and I need to communicate with Raspberry Pi
> using UART. The problem is that when I send some data about the motor
> to RPi and the motor is already spinning very fast, I often loose a
> step

Your stepper code has to run very consistently to maintain 3000 steps/sec without jitter or dropping steps. It must not have to wait for communication or any other task but be able to issue the next step command on-time. Some possible techniques to accomplish this:

- Don't post an entire message to the Pi but send only a few characters at a time, between steps.
- Talk to the Pi in shorter, tightly coded messages, and let the Pi expand them if it needs to.
- Use the highest baud rate the Uno & Pi can reliably use.
- Issue step commands in a timer-driven interrupt routine, with any stepper housekeeping done in the background, between step-commands.
- Use a faster processor.


message:
How to power Nodemcu using 12 volt AC to DC adapter?

I am trying to make a small project using Nodemcu. My project is WiFi controlled LED, 2 LED's will blink at the same time. I have successfully uploaded the code and it works fine using USB connection. But I want to power the Nodemcu using 12 volts 1.5 amps AC to DC adapter. I have checked it in web search but I have not found an understanding circuit. please help me out guys.

body:
You connect the + side of the adapter to VIN pin and the - side to GND.

You have to check the maximum voltage when using the VIN pin. Probably it means you 'waste' some power (but it's from a wall wart, so it should be ok). See the remark of Flyingfenix below for heating consequences.

See this link: [Power Related ESP-12E Development Board Pins][1], fragment 'Using a Wall Wart':

[![enter image description here][2]][2]

Examples: [Wall-Mount-AC-Adapters][3]

The current (1.5A) should be more than enough; the adapter's current should be higher than what is needed by the NodeMCU + circuit. So this is ok.

  [1]: http://henrysbench.capnfatz.com/henrys-bench/arduino-projects-tips-and-more/powering-the-esp-12e-nodemcu-development-board/
  [2]: https://i.stack.imgur.com/7PQpq.png
  [3]: https://nl.mouser.com/Power/Power-Supplies/Plug-In-AC-Adapters/Wall-Mount-AC-Adapters/_/N-brwlv?P=1yxt7f5


message:
esp8266 cant make more than one request at time

i am trying to make a get request, read that request and make another request with that read value. i havent shown it in this code but i want to make a request inside in a request. is it possible to make a request without ending one, if its, how do i do that?

here is the code :
```
#include <ESP8266WiFi.h>

#include <ESP8266HTTPClient.h>
#include <WiFiClientSecureBearSSL.h>

#define WIFI_SSID "ssid"
#define WIFI_PASSWORD "pw"

void conn();
void getreq();
void anothergetreq();

void setup() {
  conn();
  getreq();
}

void loop() {
}

void getreq() {
  std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
  client->setInsecure();
  HTTPClient http;

  http.begin(*client, "https://jsonplaceholder.typicode.com/users/1");

  int httpCode = http.GET();
  String payaload = http.getString();
  Serial.print("HTTP CODE: "); Serial.println(httpCode);
  Serial.print("PAYLOAD: "); Serial.println(payaload);
  //here i presume got the value from payload, and making another request with it
  anothergetreq("posts/1");
  http.end();

}
void anothergetreq(String p) {

  std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
  client->setInsecure();
  HTTPClient http;

  http.begin(*client, "https://jsonplaceholder.typicode.com/"+p);

  int httpCode = http.GET();
  String payaload = http.getString();

  Serial.print("HTTP CODE: "); Serial.println(httpCode);
  Serial.print("PAYLOAD: "); Serial.println(payaload);
  http.end();
}

void conn() {
  Serial.begin(9600);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();
}

```
here is the output:
```
Connected with IP: 192.168.1.100

HTTP CODE: 200
PAYLOAD: {
  "id": 1,
  "name": "Leanne Graham",
  "username": "Bret",
  "email": "Sincere@april.biz",
  "address": {
    "street": "Kulas Light",
    "suite": "Apt. 556",
    "city": "Gwenborough",
    "zipcode": "92998-3874",
    "geo": {
      "lat": "-37.3159",
      "lng": "81.1496"
    }
  },
  "phone": "1-770-736-8031 x56442",
  "website": "hildegard.org",
  "company": {
    "name": "Romaguera-Crona",
    "catchPhrase": "Multi-layered client-server neural-net",
    "bs": "harness real-time e-markets"
  }
}
HTTP CODE: -1
PAYLOAD:

```

body:
https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/readme.html#bearssl-client-secure-and-server-secure

> Secure clients and servers require siginificant amounts of additional
> memory and processing to enable their cryptographic algorithms. In
> general, only a single secure client or server connection at a time
> can be processed given the little RAM present on the ESP8266

you have two BearSSL::WiFiClientSecure instances at time. it is simple to change your code to first free the first SSL client object.


message:
What are these stray resistors on the Arduino Mega schematic?

I am using the Arduino Mega schematic found [here][1] and it's mostly clear, but there are a few resistors floating in the middle and I'm not quite sure what they're for or where they go:

[![enter image description here][2]][2]

Does anyone know what these are and where they go?

  [1]: https://www.arduino.cc/en/uploads/Main/arduino-mega2560_R3-sch.pdf
  [2]: https://i.stack.imgur.com/4IuP4.png

body:
Those are unused resistors in resistor arrays.  The arrays have 4 resistors side by side in a single package. Not all of the elements are always needed, but they have to be in the schematic anyway since they exist in real life.

[![enter image description here][1]][1]

* Elements A and D of Resistor Network 1 (RN1)
* Elements B and C of Resistor Network 2 (RN2)
* Element C of Resistor Network 3 (RN3)

  [1]: https://i.stack.imgur.com/3ffBJ.jpg


message:
Arduino UNO not showing up in USB devices on Ubuntu 18.04

I have an Arduino UNO (clone, not original) that was working fine until a couple of days ago. Now, it does not show up when I connect it to my laptop.

Things that I've troubleshouted:

1. USB cable is fine (tried with another Arduino).
2. USB ports are fine (tried with another Arduino).

3. Followed all the fixes and checks listed
    [here](https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board?newreg=3f52658e2bbc4b77969435f443c1bccf)
    and everything is successful.

4. I can upload sketches trough ICSP using a working Arduino.

5. I've tailed `syslog` while connecting and disconnecting the failing
    Arduino and nothing shows up (it does when using the "good one").

6. I've tried on a Windows 10 machine and it doesn't show up.

What else can I try?

body:
I can't comment yet but have you updated your board manger for UNO on unbunto?

tools > Board > Board Manger > Search UNO

Kind of dumb to have to do that but it happen to me before and this was the solution I did.


message:
Piezo buzzer not sounding well with ATmega328

I am using an ATmega328 to drive a 16x2 LCD, a LED, and a piezo buzzer. Piezo buzzer needs to buzz after every 5 seconds. But it doesn't make a nice sound it just gives out a faint buzz. Suspecting the buzzer to be faulty, I tested it separately from a 5V supply and it worked well. Then I put it back in the circuit and checked for the amount of current the whole circuit used. It was about 26mA when buzzer and LED were turned off, and 36mA with buzzer and LED ON. So no problem there. Additionally, the buzzer sometimes start sounding well too occasionally. This occurs after about half a minute the circuit is turned ON. This looks like that the buzzer is somewhat warming up before it can work properly. But this occurs occasionally.

I am using A0 Analog pin (or Pin no. 23 on ATmega328) for driving the Buzzer and giving 100Hz square wave to it.

What could possibly be the reason for this problem?

body:
Some buzzers are active buzzers and will self oscillate when powered.
Other buzzers requires an oscillating signal on their pins in order to make a sound.  If the buzzer works on 5v then its an active buzzer and you only need to feed it a HIGH signal to make it work. Don't try to feed it a 100hz square wave.


body:
If it works well with direct 5v supply and not from an Arduino pin, you probably need a transistor to drive the buzzer.

Here is an example how to drive a buzzer using a transistor:
https://www.maxphi.com/piezo-buzzer-interfacing-arduino-tutorial


message:
First Start Arduino Uno

When I started connecting my Arduino Uno for first project: LED to pin 13, resistor, breadboard, USB connected to Windows Laptop, the orange on-board LED flashes every second and the LED on the breadboard did the same.
What program is driving this?
I had NOT uploaded any program.
Please explain.

body:
It is a preloaded sketch and will be overwritten when you upload your first sketch into the Arduino.

Typically it's the Arduino Blink sketch which can be found here:

https://www.arduino.cc/en/Tutorial/Blink

Which has the following (functional) content:

    // the setup function runs once when you press reset or power the board
    void setup() {
      // initialize digital pin LED_BUILTIN as an output.
      pinMode(LED_BUILTIN, OUTPUT);
    }

    // the loop function runs over and over again forever
    void loop() {
      digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);                       // wait for a second
      digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);                       // wait for a second
    }


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

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


message:
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) :

<!-- language-all: lang-c++ -->

    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.

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

1. You are not using “circular buffers”, you are [double-buffering][].
   If you used a [circular buffer][], you would not need two of them.
2. `recordingEnded` is always `false` and thus serves no purpose.
3. When `writing` and `change_buffer` are both true, you should transmit
   `buff2`, not `buff1`, as the ISR is now filling `buff1`.
4. 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`.
5. The code that fills the buffers would be clearer, IMO, if you avoided
   the repetition. E.g.
   ```c++
   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:

```c++
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.

[double-buffering]: https://en.wikipedia.org/wiki/Multiple_buffering
[circular buffer]: https://en.wikipedia.org/wiki/Circular_buffer


message:
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 is the stepper motor cable][1]][1]

[![picture of whole board][2]][2]

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.

  [1]: https://i.stack.imgur.com/B74oD.jpg
  [2]: https://i.stack.imgur.com/QI4c2.jpg

body:
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);
  }
}
```


body:
[Here](https://www.orientalmotor.com/products/pdfs/opmanuals/HM-60128-8E.pdf) 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.


message:
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); }
    }

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

```C
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++;
   }

}
```


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

body:
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:
[![enter image description here][1]][1]

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

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/hPrtH.png

  [2]: https://i.stack.imgur.com/FEgKt.png


message:
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][1]. However, it's not working: "can not convert ..."

How to send a structure through UART?

  [1]: https://stackoverflow.com/questions/45600202/arduino-how-to-feed-a-struct-from-a-serial-read

body:
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));
    }


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

```c++
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:

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

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

```c++
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

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

```c++
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()`.


message:
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);
  }}
```

body:
These are nested loops:

```c++
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:

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

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

```c++
for (int i = 0; i < 500; i++) {
    int x = min(i, 255);
    do_something_with(i, x);
}
```


message:
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...".

![enter image description here](https://i.stack.imgur.com/dfiXB.jpg)

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.

![enter image description here](https://i.stack.imgur.com/QdYLC.jpg)

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

Why is this so?

body:
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);


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

body:
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](https://en.wikipedia.org/wiki/EEPROM)) to store your data in some [organized form](https://en.wikipedia.org/wiki/Database). 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](https://arduino.stackexchange.com/a/33503/37604).

A database could be as simple as a `fixed length string list` (essentially how [string arrays](https://stackoverflow.com/a/41552922) 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](https://www.instructables.com/id/Firebase-Integrate-With-ESP8266/) can be as simple as a [https request](https://firebase.google.com/docs/reference/rest/database).


message:
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)?

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


message:
Serial monitor read value depending on delay

I am working on a small piece of code as shown:
[![enter image description here][1]][1]

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:
[![enter image description here][2]][2]

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

[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/ZxfJs.jpg
  [2]: https://i.stack.imgur.com/FQChX.jpg
  [3]: https://i.stack.imgur.com/trOpK.jpg

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...");
}
}
~~~

body:
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][1]:
> Returns the first byte of incoming serial data available (or -1 if no data is available).

  [1]: https://www.arduino.cc/reference/en/language/functions/communication/serial/read/


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

``` c++
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<const __FlashStringHelper *>(PSTR(string_literal)))** "

Finally, is possible show integers not const with Macro F()?

body:
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](https://www.arduino.cc/reference/tr/language/variables/utilities/progmem/) manual page.


body:
`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][1] points out in short, you need to use the PROGMEM section for the values, as described on the [Arduino PROGMEM page][2].

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

  [1]: https://arduino.stackexchange.com/a/72159/60431
  [2]: https://www.arduino.cc/reference/tr/language/variables/utilities/progmem/


message:
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][1].

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?

  [1]: https://raw.githubusercontent.com/nodemcu/nodemcu-devkit/master/Documents/NODEMCU_DEVKIT_SCH.png

body:
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).


message:
Best way to send I2C commands between Arduino and ESP32

I made a board with an Arduino nano and a ESP32 Dev kit. I connected them via I2C with voltage adaptation. I'm using arduino IDE and the related library Wire.h.

I send messages as ascii chars or native bytes from the ESP32 (master) to the Arduino (slave) and all work fine.

I have to take a decision now. I have to implement a simple protocol to send command to the Arduino, in order to ask it do some tasks or in order to ask it to send some data to the esp32 (e.g. the speed of a motor or the state of some sensors and so on).

What I would ask is your suggestion if the simple protocol has to be managed as native bytes (the natural way I2C work) or as string (managed by mean of an array).
I try to explain.

In case of bytes I could send for example FF 0E14 01 to ask arduino to start the motor=FF at the speed=0E14 and direction=01. So the specific command is coded in the first byte.

What I miss is the need or not for a delimiter like "<" and ">" as used in case of string. In case of exchange of native bytes the value of "<" is "busy" in an integer and couldn't be distinguish by the parser. So what delimiter could I use?

On the other hand in case of strings I don't like the necessity to convert number "213" or "1529" in the relative integer. In case of the previous command I could send the string

"<S,3604,1>"

having in mind the first char as command and for this specific command "S" ("S" for example) parsing the following chars until the "," and convert it in a integer and last char as direction (as byte or as char the test is the same).

I don't know... what way do you suggest and in case of native bytes what delimiters?

Thanks.

body:
First, using a byte-value based protocol is the standard with I2C. There is no real reason to go to ASCII encoded data (The reason for doing this with Serial (UART) is normally, that the message is human readable at the PC. This is normally not the case with I2C, since only computers like the Raspberry Pi even have I2C interfaces).

About delimiters: They are only really needed for asynchronous data transfers (as UART)(to frame a full packet/message) or maybe, if you have an unknown transmission size. Both is not the case for I2C (it is a synchronous interface, that already implements transmission packages/message). You can look at the datasheet of any I2C sensor. The standard communication protocol is a command send by the master, then sending/receiving a specific number of bytes with a specific protocol, that defines, which bytes contains which information. Here you don't need a delimiter, because you already know, in what format the data will be send.

---

Let's take an example from your question: You want the Arduino to report the speed of your motor to the ESP. You implement the first byte of every master write transmission as a command, for example the decimal value `10` as command to report the motor speed. Then you terminate the master write transmission and request 1 byte from the Arduino (since you already know, that the motor speed has 1 byte). The Arduino knows through the command, that it should send the motor speed byte, and the ESP knows, that the byte received will be the 1 byte motor speed.

Now we define the command `11` to report the motor speed and the 3 bytes sensor value. The ESP sends `11` and then requests 4 bytes, as it knows, that the message will be 4 bytes long. The Arduino sends the data and the ESP knows, that the first byte will be the motor speed and the following 3 bytes the sensor value. No delimiter is needed, since the structure of your data is already defined through the implementation of your protocol. Start or end markers for a message are not needed, since I2C already works with distinct message/packets of data (a transmission is started with a START condition on the bus and ended with a STOP condition).

---

This solution is used for most I2C devices, since it is easier to implement at a low level. At the first glance for us humans it seems easier to use ASCII encoded and thus human readable data. But as you already mentioned, this makes it more complex for microcontrollers (writing parsers for ASCII data is more complex than using binary data on a fixed protocol). Keep in mind, that I2C means "Inter Integrated Circuit", so communication between integrated circuits, not communication between an integrated circuit and a human.

But in the end it is up to you to decide, which protocol you want to use.

---

As you might not know the concept yet: A **Finite State Machine (FSM)** is a good way to implement such a communication protocol on both sides. You define a state variable and based on this variable only the corresponding code is executed. You can change the state by changing the state variable.

For example on the Arduino (receiver side): First state could be the command state, where the Arduino waits for an I2C transmission. If a transmission was received, it will read it's first byte. Depending on this byte it will go into a different state, for example into the "Send motor speed" state. There it will prepare everything to send the motor speed to the master, should the master request data from the Arduino.

How to implement a FSM in detail is covered in many tutorials on the web and also in many questions on this side. You can see my answer to [this question][1], where I explained this in more detail.

  [1]: https://arduino.stackexchange.com/questions/63488/wanted-to-control-2-servos-with-serial-read/63491#63491


message:
Super fast UART transimission return error

The code was based on Fahad Mirza's very helpful example here https://arduino.stackexchange.com/questions/72138/send-structure-thorugh-serial/72141?noredirect=1#comment157377_72141

The **Sender**'s code now became

    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
      //Serial.begin(115200); // opens serial port, sets data rate to 9600 bps
      Serial.begin(250000);
    }

    void loop() {

      Gyro_data.command_name[0] = 'H';
      Gyro_data.command_name[2] = 'l';
      Gyro_data.gyro_X++;
      Gyro_data.gyro_Y=12;

      Serial.write('p');
      Serial.write('L');
      Serial.write(Gyro_data.command_name, sizeof(Gyro_data.command_name));

      Serial.write('m');
      Serial.write('x');

      send(&Gyro_data);
      delay(100); //---------------------the parameter played in this post
      //Serial.flush();
    }

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

The **Receiver**'s code

    struct Gyro_data_structure
    {
      char command_name[5];
      float gyro_X;
      float gyro_Y;
      float gyro_Z;
    };

    Gyro_data_structure  Gyro_data_received;
    int size_gyro = sizeof(struct Gyro_data_structure);

    void setup() {
      Serial.begin(9600);
      //Serial1.begin(9600);
      //Serial1.begin(115200);
      Serial1.begin(250000);
    }

    void loop() {

      //if(Serial1.available()>0)
      if(Serial1.available()>=size_gyro)//----------------worked very welll//------------------------
      {
          Serial.println(Serial1.available());

        //Serial1.findUntil('p','L');
        //Serial1.find('p');
        //Serial1.find('L');

      if ((Serial1.read() == 'p') && (Serial1.read() == 'L'))
      {
        Serial1.readBytes(Gyro_data_received.command_name, sizeof(Gyro_data_received.command_name));

        Serial.println("Received confirmation");
        Serial.println(Gyro_data_received.command_name[0]);
        Serial.println(Gyro_data_received.command_name[2]);

        if ((Serial1.read() == 'm') && (Serial1.read() == 'x')) {

          Serial.println("Gyro data received");
          receive2(&Gyro_data_received);

          Serial.println(Gyro_data_received.command_name[0]);
          Serial.println(Gyro_data_received.gyro_X);
          Serial.println(Gyro_data_received.gyro_Y);
        } else {
          Serial.println("Gyro data lost");
        }

      } else {

        Serial.println("No code confirmed");
        while(Serial1.peek()!='p'){
        Serial.print(Serial1.read()); //basically clean the receiver
        //Serial1.flush();
        }

      }

      }
    }

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

What it does is for sender send a 5 byte char array and a structure to receiver. If receiver received the "code", i.e. char 'p' 'L' and 'm' 'x' it read the incoming 5byte char array and structure. If the code was not confirmed, it clear the incoming bytes.

However, I encountered the following issue.

**First**, at receiver's code, one pay attention to

      if(Serial1.available()>0)
      if(Serial1.available()>=size_gyro)

the condition for which the receiver start to process the read() sequence.

However, at **speed(9600)**, I noticed that if one use

    if(Serial1.available()>0)

very often it start to read when Serial1.available()=1, and return incorrect numbers which got cleared out by

    Serial.println("No code confirmed");
    while(Serial1.peek()!='p'){
    Serial.print(Serial1.read()); //basically clean the receiver
    //Serial1.flush();
    }

But if one use

      if(Serial1.available()>=size_gyro)

as the condition to trigger the read(), it worked out very well. On the other hand, **if one increase the serial speed to, say 115200**, this does not matter, as they both return the correct result. Could you explain to me why this was the issue, please?

**Second**, please pay attention to

      send(&Gyro_data);
      delay(100);

At speed at or above 100, with nano board and mega board, this worked out fine. But if one wants to increase the transmission speed, change delay(100) to delay(20) in sender's code, the receiver's code returns error. This issue could not be resulted by change the wiring or increase the serial speed. Especially, the receiver's at part

      Serial.println(Serial1.available());

usually return a number of 62~63 when there's an error.

Could you explain to me where did those two questions come from? Were they because the chip set on Arduino? Especially, how to achieve a communication response under 20 ms?

body:
First, you got some logic wrong in the receiver: you have a test for
`Serial1.available()>=size_gyro` and, when this is true, you read
`size_gyro` + 9 bytes. You should change the test in order to only start
reading when you actually have `size_gyro+9` bytes available.

Then, note that `command_name` is transmitted twice: first as part of
the 9-byte preamble (between "pL" and "mx"), then as part of the
transmitted `Gyro_data_structure`. There is no point in doing so.

> at speed(9600), I noticed that if one use `if(Serial1.available()>0)`
> very often it start to read when Serial1.available()=1, and return
> incorrect numbers

This is expected: you wait for 1 byte to be available in the input
buffer, then you attempt to read the 9-byte preamble. One of your calls
to `Serial1.read()` is going to find the buffer empty, and it will then
return −1.

> But if one use `if(Serial1.available()>=size_gyro)` as the condition
> to trigger the read(), it worked out very well.

In other words, when you wait until 17 bytes are available before
reading the 9-byte preamble, you get at least the preamble right. Is
this surprising?

> if one increase the serial speed to, say 115200, this does not matter,
> as they both return the correct result

Your code takes some time to do the reading. At a fast enough baud rate,
the serial port receives the incoming bytes faster than your code reads
them, so you never run into an empty buffer.

> if one wants to increase the transmission speed, change delay(100) to
> delay(20) in sender's code, the receiver's code returns error

The sender is going too fast, and the receiver cannot cope with the data
rate.

> `Serial1.available()` usually returns a number of 62~63 when there's
> an error.

This means the receive buffer is full.

Note that the receiver would be way faster if it wasn't printing so
much. Upon receiving a correct transmission, it will `Serial.println()`
a bunch of messages that should total at least 64 bytes. Transmitting
those bytes at 9600 b/s takes more than 66.5 ms.

------------------------------------------------------------------------

**Edit**: proposed solution.

Your idea of prepending a “code” to the data structure in order to
identify a correct transmission is in the right track. This is a kind of
[format indicator][] commonly known as a “magic number” or a
“signature”. It does not ensure correct transmission with 100%
confidence, as the signature could be present by accident as part of the
data structure itself. But if the signature bytes are unlikely enough to
happen by accident, you have a pretty high confidence that wherever you
find the signature in the data stream it's the start of a new packet.
You can increase this confidence by making the signature longer, at the
cost of longer transmission times.

Now, for a matter of simplicity, I would not send the signature as two
disjoint parts. Common practice is to send it as one contiguous set of
bytes, at the very beginning of the packet. For example, I would send
your packets like so:

```c++
// 5-byte signature, including the terminating '\0'.
const uint8_t Gyro_signature[] = "Gyro";

void Gyro_send(const Gyro_data_structure &gyro) {
    Serial1.write(Gyro_signature, sizeof Gyro_signature);
    Serial1.write((uint8_t *) &gyro, sizeof gyro);
}
```

You may want to change the signature to something less likely to happen
by accident.

On the receiver side, when you expect the signature, you read from the
port one byte at a time while counting how many correct bytes you have
so far. The algorithm goes as follows:

1. let i = 0 be the number of correct bytes received so far
2. read an incoming byte
3. if that incoming byte is correct, increment i
4. otherwise, if we just got the first signature byte, reset i = 1
5. otherwise reset i = 0
6. unless we got the full signature, go to 2

This assumes that the first signature byte doesn't appear elsewhere
within the signature. Otherwise steps 4–5 would be more complex.

Here is a receiver function that implements this algorithm, then reads
the data structure:

```c++
void Gyro_receive(Gyro_data_structure &gyro) {

    // Read until we get a complete signature.
    int discarded = 0;
    for (size_t i = 0; i < sizeof Gyro_signature; ) {
        if (Serial1.available()) {
            char c = Serial1.read();
            if (c == Gyro_signature[i]) {  // correct byte
                i++;
            } else if (c == Gyro_signature[0]) {  // first byte
                discarded += i;
                i = 1;
            } else {
                discarded += i+1;
                i = 0;
            }
        }
    }
    if (discarded) {
        Serial.print("Discarded ");
        Serial.print(discarded);
        Serial.println(" bytes.");
    }

    // Wait for the data.
    while ((size_t) Serial1.available() < sizeof gyro)
        /* wait */;

    // Read it.
    Serial1.readBytes((char *) &gyro, sizeof gyro);
}
```

Note that this function is blocking. If you need a non-blocking version,
you should be able to easily convert the signature-checking part into a
finite state machine where `i` is the state variable.

[format indicator]: https://en.wikipedia.org/wiki/Magic_number_(programming)#Format_indicators


message:
Power Source for Arduino

So I have SIM900 Shield and Arduino Uno and they have both power jack, is it possible to power one of them using one power jack and connect it's power with another? If it is possible, I sincerely need the explanation.

I've research about the VIN pin of Arduino but I didnt quite get it and can't take the risk that I might fry the board since Im new here.

body:
It depends on what voltage the devices run at and what their current draw is from the power supply versus what voltage & current your power supply provides.

If everything runs at 3.3V or 5V and minimal amps then you're good to go.

Read the datasheet for each device and for your power supply.


message:
Digispark clone not recognised when plugged in

When I plug in my digispark clone the computer doesn't make any sounds or some kind of acknowledgement that it has been plugged in. Anyone know why this may be or is it just a dodgy clone?

body:
It sounds like a driver problem.

If you are on Windows, check your Device Manager and see if the new device is detected and has proper driver installed. If it is, you should see a COM port added when you attach the board.

There are different USB chips that manufacturers use (CH340G and FT232RL, as far as I know), and not all of them have their drivers already installed on Windows.

Check your board to see what chip it is, google for the drivers and the setup procedure for your OS.

You can also check [Digispark Installation Instructions][1] and try the driver they provide.

  [1]: https://digistump.com/wiki/digispark/tutorials/connecting


body:
The Digispark does not use a "standard" USB-to-Serial chip but is dependent on a special bootloader called "micronucleus" that makes it (sort of) act like a USB device.

Below is a description of the steps you need to perform for a Windows system and the Arduino IDE.

1. First, you will need to install a Windows driver for Micronucleus: [Zadig USB driver][4]

If your ATTiny is recognized by Windows after performing the driver installation, then all is fine and you can skip to step 4.

If Windows still does not recognize your Digispark clone, its ATTiny processor might not have come with micronucleus pre-programmed and you need to perform steps 2 and 3. Unfortunately this is for advanced users and might be difficult if you're inexperienced with electronics and/or Arduino.

2. [Download Micronucleus from Github][1]
3. Follow [This tutorial from Digispark][2] to install micronucleus on your ATTiny. You will need another Arduino (Uno, Nano, Mega, Mega2560, ... or clone) for that.
4. Then follow [This tutorial from Digistump][3] to enable the Arduino IDE to program your Digispark clone directly from USB.

  [1]: https://github.com/micronucleus/micronucleus
  [2]: https://learn.sparkfun.com/tutorials/how-to-install-an-attiny-bootloader-with-virtual-usb/install-micronucleus
  [3]: https://digistump.com/wiki/digispark/tutorials/connecting
  [4]: https://github.com/micronucleus/micronucleus/tree/master/windows_driver_installer


message:
Arduino Zero RTC alarm not running loop

Using an ATSAMD21 with the Arduino core, I'm running into an issue where the RTCZero alarm callback won't continue running the loop() function. If I schedule another alarm inside the callback, the second alarm will execute the loop() function after the callback is done. Every second time it works, every other time it doesn't.

Minimal example in which I expect the LED to change state every 2 seconds, which does not happen:

```
#include <RTCZero.h>
#include <time.h>

RTCZero rtc;

void setup()
{
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

  rtc.begin();
  rtc.attachInterrupt(alarmMatch);
  schedule_wake_up();
  rtc.enableAlarm(rtc.MATCH_HHMMSS);
}

void loop()
{
  digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
  schedule_wake_up();
  rtc.standbyMode();    // Sleep until next alarm match
}

void schedule_wake_up() {
  time_t wakeupTimestamp = rtc.getEpoch();
  wakeupTimestamp += 2;
  struct tm *wakeupTimeStruct = gmtime(&wakeupTimestamp);

  rtc.setAlarmSeconds( wakeupTimeStruct->tm_sec );
  rtc.setAlarmMinutes( wakeupTimeStruct->tm_min );
  rtc.setAlarmHours( wakeupTimeStruct->tm_hour );
}

void alarmMatch()
{
  // Do nothing, just wake up
}
```

* Arduino IDE 1.8.9
* RTCZero ver 1.6.0
* SAMD core ver 1.8.4 and 1.6.20 tried

body:
I ended up deleting my copy of RTCZero and installing a new one via the Arduino IDE library manager. This solved the issue.

The difference between my local copy and the upstream one is in the standbyMode() function. I had the following PR merged into my local copy of this function:
https://github.com/arduino-libraries/RTCZero/pull/46/files

After I installed the clean copy I went and replaced the standbyMode() function's content with the following:
https://github.com/arduino-libraries/ArduinoLowPower/blob/892594adbccf45b198fc067ea994048c76523936/src/samd/ArduinoLowPower.cpp#L18


message:
What happens to serial output when no-one is listening?

This question probably needs a better title but I'm having trouble thinking of one! Please feel free to edit or suggest one.

My target system is a pair of Arduino Leonardos linked by XBee radios. One is the coordinator and is expected to communicate with a host PC over the USB connection (virtual serial port). The coordinator parses commands and potentially forwards them on to the endpoint by radio. The endpoint replies to commands and can also generate output spontaneously. Both devices can also send diagnostic output to the USB/Serial port. The endpoint sends "heartbeat" messages every 8 seconds. If the coordinator misses 2 consecutive heartbeats then it'll reinitialize. If the endpoint sends a heartbeat and doesn't get a response within a couple of seconds, then it will also reinitialize.

This all seems to work pretty well, but I've noticed something odd. If I connect to both devices with a terminal emulator and just watch the output, everything is good and the system is stable for at least 14 hours (the longest I've tested it). I can see the heartbeat messages happening and the diagnostic output coming out. However, as soon as I disconnect one of the serial ports, things begin to fail. The XBee comms state machine appears to time out at both sides and goes into an endless re-initialization loop.

I'm struggling to think why this might be, but disconnecting one of the serial ports reliably causes the issue within 10 to 20 seconds (I think the "no heartbeat" timeout is being hit).

It seems like if nothing is listening to the serial port, something is getting jammed up. My understanding is that its OK to read from and write to a port that nothing is connected to, and that data will just fall into the bitbucket. Is this not the case? Why should disconnecting the client from the serial port jam everything up?

UPDATE: I've tested with this modified "blink" sketch:

```lang=cpp
#include <Arduino.h>

auto& host = Serial;

void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
  host.begin(115200);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
  host.print("Time ");
  host.println(millis());
}
```

With something (PuTTY) connected to the USB/serial port, I get a nice even mark-space ratio on the LED. As soon as I disconnect PuTTY, the 'off' period of the LED becomes about twice as long as the 'on' period, i.e. there is upwards of a second delay each time I write to the serial port. Is that normal?

body:
Theoretically, nothing should happen to serial data if nothing is listening.

* For a traditional UART the data is just sent regardless. It doesn't need someone listening for that to happen.  Like a light doesn't need someone to see it for it to be on.
* For USB CDC/ACM the data should be discarded even before it's attempted to be sent.

The latter, though, does rely on the host computer "playing ball" and cleanly closing the port properly.  On most operating systems that is handled by the OS and happens automatically. However on Windows it is handed off to the driver, and I guess the driver may even hand it off to the terminal software.

So in Windows there is a chance that when you disconnect your serial port it's not cleanly closing the connection and the USB thinks it's still connected, thus blocking waiting for the serial data to be collected.


body:
OK so here is my solution.

I made a wrapper class called `SafeSerial`. In `SafeSerial.h`:

```lang=cpp
#pragma once
#include <Arduino.h>

class SafeSerial : public Serial_
 {
 size_t write(const uint8_t* buffer, size_t size) override;
 };
```

In `SafeSerial.cpp`:

```lang=cpp
/*
 * SafeSerial implementation for Arduino Leonardo.
 * Overrides the Serial_::write() method and checks that there is enough room
 * in the output buffer. If not, the output is discarded.
 * The intent is to prevent serial output from blocking when no host is listening.
 * All other operations are handed off to the underlying Serial_ instance.
 */

#include "SafeSerial.h"

size_t SafeSerial::write(const uint8_t* buffer, size_t size)
 {
 /*
  * Check if we can write without blocking. If we need to block,
  * then we assume that the host has disconnected.
  */

 if (availableForWrite() < size)
  return 0;

 return Serial_::write(buffer, size);
 }
```

In my sketch, in global scope:

```lang=cpp
SafeSerial host;
```

Now, because I'm using `<ArduinoSTL>` and all my output goes via `std::cout`, I need to take some actions to correctly configure that library. This requires modifying the library code per the instructions in the `README.md` file to make it not default to the built-in `Serial` instance and to not create default instances of `cin` and `cout`. This now needs to be done in the sketch, so (again in global scope):

```lang=cpp
// cin and cout for ArduinoSTL
namespace std
 {
 ohserialstream cout(host);
 ihserialstream cin(host);
 }
```

and in `setup()`:

```lang=cpp
 host.begin(115200);
 // Connect cin and cout to our SafeSerial instance
 ArduinoSTL_Serial.connect(host);
```

...and finally, I have fully non-blocking Serial I/O even when the host has disconnected, at the risk of some possible data loss. However so far, in my application, data loss doesn't seem to be an issue as I only produce minimal terse output and generally only 1 line every few seconds.

Thank you all for your valuable input.


message:
Communication between Arduino and python: serial port sending empty data

Arduino code:

this code is provided communication between sensor gy-521 and arduino. I read data by the command "1", after 1000 samples arduino is waited for new command for read data.

Arduino code works well in arduino port.

    #include<Wire.h>
    const int MPU=0x68;
    int16_t AcX,AcY,AcZ;
    unsigned long time;
    bool allow = false;
    //int incom = 0;

    void setup(){
      Wire.begin();
      Wire.beginTransmission(MPU);
      Wire.write(0x6B);
      Wire.write(0);
      Wire.endTransmission(true);
      Serial.begin(19200);
      while (!Serial);// wait for serial port to connect. Needed for native USB port only
    }

    void loop(){
      if (allow){ //if allow == true, read data

        for (int i = 0; i < 1000; i++){
          Wire.beginTransmission(MPU);
          Wire.write(0x3B);
          Wire.endTransmission(false);
          Wire.requestFrom(MPU,12,true);
          AcX=Wire.read()<<8|Wire.read();
          AcY=Wire.read()<<8|Wire.read();
          AcZ=Wire.read()<<8|Wire.read();

          time = millis();
          Serial.print(time);Serial.print(",");Serial.print(AcX);Serial.print(",");Serial.print(AcY);Serial.print(",");Serial.println(AcZ);
          delay(0);
        }
        Serial.println(0); //see UPD.3
        allow = false;
      }
    }

    void serialEvent() {
      while (Serial.available()){ //wait for command
        int incom = Serial.read() - '0';
        Serial.println(incom);
        if (incom == 0){ //if 0 - stop
          allow = false;
          delay(100);
        }
        if (incom == 1){ //if 1 - read data
          allow = true;
          delay(100);
        }
      }
    }

Python code:

        def sensors(self):

            self.arduino_port_sensor.reset_input_buffer() #clear buffer

            self.arduino_port_sensor.write(str(1).encode()) #send command to arduino - read data

            main_array = []

            pbar = tqdm(total=self.time_observation) #just to see the progress

            while True:

                values = self.arduino_port_sensor.readline().decode().rstrip().replace(" ", "") #read data, some manipulation for cleaning
                main_array.append(values)

                pbar.update(1)

                if values == '': #if data is empty
                    print('!!!!')
                    continue
                if values == '0': #see UPD.3
                    break

            pbar.close()
            ...bla bla...

I call this function time to time, then in some step, arduino stops sending data -- it sends empty string.

It looks like:

PS. In this code I use 2 ports: for sensor and for motor, 2 different arduino. The principe of working second arduino with motor the same, but it works without any problem (I just send command with "action" to arduino with motor, and then receive answer "received back")

[![enter image description here][1]][1]

Question: what's wrong with python? how to fix this problem?

_______________
**UPD**

Initialization:

    arduino_port_sensor = serial.Serial('/dev/tty.usbmodem143101', 19200, timeout = 1)

**UPD.2**

It receive command - "1" - read data, the interruption occurs while reading data:

[![enter image description here][2]][2]

**UPD.3**

Also i changed the code of arduino -- added the "0" after loop.

**UPD.4**

If I recall this function after arduno stopped sending data, I get this:

[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/NML9X.png
  [2]: https://i.stack.imgur.com/m8Pmv.png
  [3]: https://i.stack.imgur.com/elCkj.png

body:
There can be different reasons for your issue. But from the update you added later, we can at least say that your Arduino sometimes doesn't receive the character "**1**". And when that happens, your Python gets stuck in the infinite loop of trying to read something from the serial port.

As your Arduino responds with "**1**" when it receives "**1**", you can base your application on that i.e. if Arduino doesn't respond with "**1**", keep sending "**1**".

I wrote a sample program based on your code. I removed the "**Wire**" part in the Arduino code as I don't have your sensor. I would urge you to test with this Arduino code to make sure that Your sensor is not blocking your Arduino. Wire read can be blocked forever depending on the IC you are trying to read (and if you don't have a timeout).

    int16_t AcX,AcY,AcZ;
    unsigned long time;
    bool allow = false;

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

    void loop()
    {
      if (allow) //if allow == true, read data
      {
        for(int i = 0; i < 10; i++)
        {
          AcX = 1;
          AcY = 2;
          AcZ = 3;

          time = millis();
          Serial.print(time); Serial.print(",");
          Serial.print(AcX);  Serial.print(",");
          Serial.print(AcY);  Serial.print(",");
          Serial.println(AcZ);
        }
        Serial.println('0');
        allow = false;
      }
    }

    void serialEvent()
    {
      while (Serial.available()) //wait for command
      {
        int incom = Serial.read() - '0';
        Serial.println(incom);
        if (incom == 0)          //if 0 - stop
        {
          allow = false;
          delay(100);
        }
        if (incom == 1)          //if 1 - read data
        {
          allow = true;
          delay(100);
        }
      }
    }

In the Python code, I checked if I received "**1**" from Arduino. If not I kept trying.

    import serial
    import time

    def sensors():
        # Clear receive buffer
        arduino_port_sensor.reset_input_buffer()

        while True:
            # Send command to arduino to send data
            arduino_port_sensor.write('1'.encode())

            # As arduino send LF and CR at the end, let's strip those from the end
            response = arduino_port_sensor.readline().rstrip(b'\r\n ').decode()

            # Arduino should respond with the cmd that it received,
            # if not, send cmd again
            if response == '1':
                # Arduino acknowledged
                break
            else:
                print('Did not receive 1. Retrying...')

        main_array = []

        while True:
            values = arduino_port_sensor.readline().rstrip(b'\r\n ').decode()

            if values == '':
                print('!!!!')
                # This should never happen, but if it does happen, try to read again
                continue
            elif values == '0':
                # print(main_array)
                # We are done receiveing packets
                break
            else:
                # We are still receiving packets
                main_array.append(values)

    arduino_port_sensor = serial.Serial('COM50', 19200, timeout=3)

    # Let PySerial get ready
    time.sleep(3)

    while True:
        sensors()
        time.sleep(1)


message:
Why am I getting "expected primary-expression before '.' token"?

I know this is a common question but the truth is every code is different. Sometimes it's hard to apply the concept to your code, it does not work. So please help me. What is wrong with this code? I got it from GitHub. I'm trying to compile it first before I can do a little modification, it sends temp and humidity data to ThingSpeak cloud servers.

    #include <DHT.h>  // Including library for dht
    #include <ESP8266WiFi.h>

    String api_key = "YOUR API KEY"; // Enter your Write API key from ThingSpeak
    const char *ssid = "YOUR WIFI SSID"; // replace with your wifi ssid and wpa2 key
    const char *pass = "YOUR WIFI PASSWORD";
    const char* server = "api.thingspeak.com";

    #define DHTPIN 1 // pin where the dht11 is connected
    DHT dht;

    WiFiClient client;

    void setup() {
      Serial.begin(115200);
      delay(10);
      pinMode(2, OUTPUT);
      digitalWrite(2, 0);
      Serial.println("Connecting to ");
      Serial.println(ssid);
      WiFi.begin(ssid, pass);
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.println("WiFi connected");
    }

    void loop() {
      int chk = DHT.read(DHTPIN);
      float hum = DHT.humidity;
      float temp = DHT.temperature;
      if (isnan(hum) || isnan(temp)) {
        Serial.println("Failed to read from DHT sensor!");
        return;
      }
      if (client.connect(server, 80)) {
        // "184.106.153.149" or api.thingspeak.com
        String data_to_send = api_key;
        data_to_send += "&field1=";
        data_to_send += hum;
        data_to_send += "&field2=";
        data_to_send += temp;
        data_to_send += "\r\n\r\n";
        client.print("POST /update HTTP/1.1\n");
        client.print("Host: api.thingspeak.com\n");
        client.print("Connection: close\n");
        client.print("X-THINGSPEAKAPIKEY: " + api_key + "\n");
        client.print("Content-Type: application/x-www-form-
        urlencoded\n");
        client.print("Content-Length: ");
        client.print(data_to_send.length());
        client.print("\n\n");
        client.print(data_to_send);
        delay(1000);
        Serial.print("Temperature: ");
        Serial.print(temp);
        Serial.print(" degrees Celcius, Humidity: ");
        Serial.print(hum);
        Serial.println("%. Send to Thingspeak.");
      }
      client.stop();
      Serial.println("Waiting...");
      // ThingSpeak needs minimum 15 sec delay between updates, I've set it to 30 seconds
      delay(10000);
    }

When I compile I get this error,

      Arduino: 1.8.10 (Windows 10), Board: "NodeMCU 1.0 (ESP-12E
      Module), 80 MHz, Flash,
      Legacy (new can return nullptr), All SSL ciphers (most
      compatible),
     4MB (FS:2MB OTA:~1019KB), 2, v2 Lower Memory, Disabled, None, Only Sketch, 115200"

        C:\Users\Agent 96\Desktop\thingspeak\thingspeak.ino: In function 'void loop()':

       thingspeak:37:20: error: expected primary-expression before '.' token

      int chk = DHT.read(DHTPIN);

                    ^

      thingspeak:38:22: error: expected primary-expression before '.' token

      float hum = DHT.humidity;

                      ^

      thingspeak:39:23: error: expected primary-expression before '.' token

      float temp = DHT.temperature;

                       ^

      Multiple libraries were found for "DHT.h"
      Used: C:\Users\Agent
      Not used: C:\Users\Agent
      Multiple libraries were found for "ESP8266WiFi.h"
      Used: C:\Users\Agent
      exit status 1
      expected primary-expression before '.' token

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

Please help, I'm kind of a beginner.

body:
Change three lines right after loop() to these:

      int chk = dht.read(DHTPIN);
      float hum = dht.humidity;
      float temp = dht.temperature;

Change '**DHT**' into lower case letters. DHT is the class and dht is the object of the DHT class.

Also you have multiple copy of these libraries: DHT.h and Esp8266WiFi.h. Check your cuurent directory where your Arduino code is and also **Documents->Arduino->Libraries** directory. These libraries should be in the  **Documents->Arduino->Libraries** directory.


body: You defined DHT as dht. So you'll have to replace those DHT with dht and you'll be good to go.


message:
How to connect HC-06 BT module without pins?

So, from one popular Chinese  store I ordered a HC-06 module that I received... and due to some mistake from a store, I received a HC-06 without connecting pins. So usually HC-06 looks like this (with blue plate underneath where 4 pins are available to solder or connect):
[![enter image description here][1]][1]

I just received the one without this blue plate and pins:
[![enter image description here][2]][2]

How do I connect it to Arduino if there are no pins? Where are usual GND, TX, RX pins (is this schematics correct?)? Is it okay if I just solder a wire to some of them without this blue under-plate?

Also do I need to add some resistors or other components if I connect wires directly to these half-circle pins?

Thank you!

  [1]: https://i.stack.imgur.com/mQcLQ.jpg
  [2]: https://i.stack.imgur.com/ZxTX5.jpg

body:
The small green PCB is the real HC-06 board. The blue board has 2 functions:

1. It breaks out the contact pads of the HC-06 to the bigger pins.

2. It has a voltage regulator on it so that you can provide it with 5V power, which then get's converted to 3.3V for the HC-06 (which is a 3.3V device).

The next steps depend on what Arduino board you have:

- If you have a 3.3V Arduino Board, you can directly connect the pads on the HC-06 (by soldering pins or wires to them) to the corresponding Arduino pins:

        Arduino <--> HC-06
          3.3V  <--> 3.3V
          GND   <--> GND
          TX    <--> RX
          RX    <--> TX

    Also you can connect a fitting LED to the LED pin. I spontaneously cannot find data about the max current of this pin. But I guess it is in the range of 10 to 20 mA. Use a corresponding combination of an LED and a resistor.

- If you have a 5V Arduino, you need to consider the voltage difference. On the Uno and Nano you have a 3.3V regulator on board. The regulator itself is rated for 150mA, but since it is not cooled, the limit is more like 50mA (see [this forum thread][1]). [This datasheet][2] of the HC-06 states, that it draws at max 30-40mA, so you can get away without an extra 3.3V regulator, just by connecting the both 3.3V pins on Arduino and HC-06. If the voltage regulator overheats despite being under 50mA, you need to buy an extra 3.3V voltage regulator, that can handle the current.

    Don't forget to use a voltage divider on the Arduino-TX --> HC-06 RX line to divide the Arduinos 5V down to 3.3V. This line isn't even regulated by the blue breakout board, so you would need this voltage divider either way.

    Ground connection and the LED are the same as in the first case.

So all in all you can still use the HC-06, just with a little bit less ease than with the blue breakout board.

  [1]: https://forum.arduino.cc/index.php?topic=104.0
  [2]: https://components101.com/sites/default/files/component_datasheet/HC06 Bluetooth Module Datasheet.pdf


message:
Inserting myself in serial communication

I am assigned on a project involving Arduino and Raspbery PI. I have plenty of experience with Arduino and 0 with Raspbery or Linux. Person working quit and there are some problems that need me to start debuging.

The project involves control of input and output by Arduino and a touch screen and SMS aplication in Raspbery. They comunicate with standard Serial port using USB.

I want to read that communication on my PC terminal. What would be the simplest way of inserting myself without modifying anything on Raspbery?

body:
If all you want to do is monitor what is going on then you can take a pair of USB to UART adaptors and connect the RX pin of each to the Arduino - one to the RX pin to see what the Arduino is receiving, and one to the TX pin to see what the Arduino is transmitting.

You then have to open both COM ports in separate applications (unless you can find an application that will allow you to open both together) to see what each channel has going through it.


body:
As st2000 stated in the comments, tapping on USB is a complex task and certainly not the way to go.

Maybe there is a program for Raspbian, that pipes the Serial data to 2 programs simultaneously. (I don't know one and that would be off topic here)

So your best way would be to tap the Serial (UART) communication between the USB-Serial chip (which translates USB to real serial UART) and the Atmega2560 (the main chip on the Arduino Mega). Reading Serial (UART) is a completely passive action. You don't disturb the communication with it; only if you try to send something from your tapping device. The Mega uses the first Serial interface for communication over USB, meaning that you need to tap the pin 0 and 1 (marked with TX and RX).

Now about the tapping device: You have multiple possibilities here. You could use the RX pins of 2 other Arduinos or of 2 USB to UART adaptors. But I would suggest to directly buy a logic analyser. That is a small USB device, that let's you plot digital signals (like the serial communication) on your PC. I use one with the software Pulseview. It can also analyse the digital signal for different communication protocols, for example UART. With the logic analyser you would reach your goal of tapping the serial communication, but you would also have a very capable tool for your future Arduino projects (you can analyse all sorts of digial signals with it). They are rather cheap (I got one with little clamps to attach it to a circuit for about 15€).

In the end, it's up to you to decide, which way you want to go and what you want to buy.


body:
You may be able to sniff the communication from the Raspberry Pi itself,
with no extra hardware. Assuming the program on the Pi can be configured
to use a serial port _other_ than `/dev/ttyACM0`, a sniffing
program could create a pseudo-terminal pair, then forward data back and
forth between `/dev/ttyACM0` and the master pseudo-terminal, while
logging everything. If you point your Pi application to the slave
pseudo-terminal, you have your man-in-the-middle logger:

    Arduino --(/dev/ttyACM0)-- logger --(pseudo-tty)-- application

The interesting thing about a slave pseudo-terminal is that, as far as
the application is concerned, it behaves _exactly_ like a regular serial
port.

There seem to be quite a few implementations if this idea. C.f. the
answers to these other stack exchange questions:

* [How can I monitor serial port traffic?](https://unix.stackexchange.com/questions/12359/how-can-i-monitor-serial-port-traffic)
* [Sniff serial port on Linux](https://serverfault.com/questions/112957/sniff-serial-port-on-linux)

Just as an example, the README of
[interceptty](https://github.com/geoffmeyers/interceptty) states:

> interceptty is designed to sit between a serial port (or other
> terminal device, or program, or socket, or something connected to a
> file descriptor) and a program which is communicating with that
> device, recording everything that goes back and forth between the two.
> It does this by opening the real device, creating a pseudo-tty, then
> forwarding everything between the two, recording whatever it sees.


message:
Resetting Arduino UNO code (newbie)

So today I started to learn Arduino uno. I have an LM35 temperature sensor and I got what I needed from it. Now it's just keep calculating till I plug it off.

I know there is a reset button. When I press it or hold it, it's closing and opening again to do the coding again. I want it to completely stop. Like when I first plug led was flashing to show arduino is connected.

And I know I can just upload another code. But I don't want that.

If it's possible please let me know.

body:
Actually, it already did something when you turned it on when you got it: it was blinking a LED. It did not mean it was connected. A microcontroller (or controller) always does something. Although you can consider an empty endless loop as 'nothing'.

And now you overwritten that sketch with your LM35 sketch.

However, you can put the Blink sketch again in your Arduino, and it can be found here:

https://www.arduino.cc/en/Tutorial/Blink

You don't need to connect the LED, it will use the built in LED.

If you don't want the Arduino to do anything, just switch it off (disconnect the power).


body:
When a microcontroller or a computer is powered on, it always does something. A program on a computer will return and the OS will run again. On a microcontroller there is no OS to return to, so every microcontroller program has an infinite loop.

The `void loop()` function of the Arduino framework is such an infinite loop. If you want your LM35 temperature code to be only run once, you can put it into the `void setup()` function, which is run once before going to `loop()`. When the `loop()` function is empty, the Arduino will do nothing after it returned from `setup()`.

Otherwise, if you want to put your code into `loop()` for whatever reason, you can insert an infinite loop whereever you want it:

    while(true);

This loops forever and does nothing. Your temperature code will only be executed on the next reset or power on.


message:
Power 5v from l298n to 5v pin arduino

im using the l298n module, and 3x 18650 batterys (near 12v total), and supplying 12v to the 12v pin of the l298 module. Can i use the 5v pin of the module to power the 5v pin of arduino? Or i need a second power supply just for the arduino? Any tips? [![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/90QoR.jpg

body:
The L298N is a chip, and the link you provided in the comments is to the chip, not to a full H-bridge module with voltage regulator and other components. We don't have any way to answer your question about your particular set-up without more info.

If the module you have uses a voltage regulator to provide clean 5V to its solid state chips, but does not use it to drive the motors, and it provides enough extra current to drive your Arduino then you might be able to get away with using it to feed your Arduino. If the H-bridge module uses the output of it's 5V regulator to drive the motors then I would not recommend using it to power your Arduino, since as the motor is switched on and off it will cause the voltage from the regulator to bobble. At the very least you would need a reservoir capacitor across the 5V rails near the Arduino to smooth out the 5V supply.


body: Power the arduino from your batteries via the Vin (barrel Jack) use the arduino to supply the 5V to the L298 module and connect all the grounds together. That should do it.