# Question
Title: Super fast UART transimission return error
The code was based on Fahad Mirza's very helpful example here Send structure through Serial

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?

# Answer
> 1 votes
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:

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

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

---
Tags: serial, uart, serial-data, speed, chipkit
---


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

Example:

```
tft.print(F(mediaTotPg[1]));

```

This do not work because mediaTotPg is a Integer Array and the errors returned are:

" **#define F(string\_literal) (reinterpret\_cast(PSTR(string\_literal)))** "

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

# Answer
> 1 votes
For a constant array of integers you need to use PROGMEM and the various `pgm_read_*()` functions.

You can read more, and find examples, on the Arduino PROGMEM manual page.

# Answer
> 1 votes
`F()` puts the constant string literal in the flash part of your device. This way it does not use the RAM space otherwise needed.

But your `mediaTotPg` array is most probably (you didn't say anything about it) a non-`const` variable, and can't be put in flash memory.

If the values to be shown are in fact `const`, you need to put them in the flash memory. As Majenko's answer points out in short, you need to use the PROGMEM section for the values, as described on the Arduino PROGMEM page.

The answer to your question is: **No, it is not possible to use the macro `F()` with *any type* of variable that is not `const`, and it is not possible to use it for *any other type* than a string literal.**

---
Tags: programming, flash, atmega2560
---


# Question
Title: 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

""

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.

# Answer
> 0 votes
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, where I explained this in more detail.

# Answer
> -1 votes
Before giving pointers to your question; First I will start to recommend to avoid using i2C for these kind of things and recommend UART (Serial) which is much better for communication between multiple mcu's.
The UART) Serial Gives you a stack (memory of received data) meaning that you receive data when processing other functions and act on them in arduinos' own time. UART is more then fast enough for things like this and enables longer distances then few cm, its more resilient to interference
UART (Serial) uses fewer ports and most ports can be converted into Software Serial
You will find many libraries which deal with communication even encryption over Serial
If you use write() rather then print you don't have to convert the data.
if you use correct input on your arduino, you can even read the data as it comes from your PC and much more
Anyway, to your question Most of the data communications tend to have a starting byte and the ending byte to package the pocket among common ones is 00-Start and 0xFF as end.
Now assuming that we only have one slave and single priority level etc we don't need to be too much of smartasess for package header... next I would define Process as it will let you chose the function that then can receive then next details as variables.
This option means that you will have to number the operations from 1 not 0
Major benefit is that as different function may take different number of variables (for example one only states on off, while other states vector distance) you will not have to decide on a packet length, but simply deal with any number of variables (within reason)

---
Tags: i2c, esp32
---


# Question
Title: PWM fans causing temp sensor erroneus values (interference?)
I am learning Arduino programming and my current project for real use is to connect 10-17 PC chassis PWM fans to be temperature controlled by the arduino.

So, I have connected the fans exactly as in the picture. Taken from https://www.racedepartment.com/threads/easy-diy-wind-simulator-for-assetto-corsa.133999/

The temperature sensor is a TMP36 (included in the official Arduino beginner's kit). It is connected to +5V and GND on the Arduino Uno R3. Middle pin is the output and is connected to A0 on the Uno.

Temperature readings seem to work well up until the point the fans start spinning. When they do, the output pin on the TMP36 sensor outputs junk values. Such as 0V or 700mV and it fluctuates up and down if I try probing it with a multimeter. When fans some to a stop however, the output once again stabilizes to a fairly correct value.

I am no expert in electronics interference, but electric motors I suppose cause some electrical noise? I had hoped that PC Chassis fans would already have electric components inside the hub to prevent such though... Currently I am trying to run 2 fans at the same time but I wish to use 10-17 later once this works.

The fans I am using are Arctic 92mm PWM Rev 02.

I have checked the datasheet (https://www.arduino.cc/en/uploads/Main/TemperatureSensor.pdf) for TMP36 (TO-92 package type) and tried adding a ceramic 0.1µF capacitor between +5V and GND and also add resistor of varying values to the output pin. I believe I got some stabilization out of it but not enough. Especially when the fans start spinnig faster than 20% duty cycle on pwm it starts to flip out.

I have tried to disconnect power to fans to check if PWM signal may cause it too, but this is not the case as the TMP36 remain stable with PWM on but fans disconnected.

Can someone please help me with explaining what is probably going on and how I can mitigate the problem in a preferably easy way? Do I need to add diodes, capacitors, resistors? Where? Or should I change to a different temperature sensor (which)?

Thankful for help!

# Answer
In case anyone has the same problem, I solved it. Turns out is was a bad PSU. Buying a new, higher quality one made everything work. So the issue was high ripple I suspect, or at least high enough when applying some load (which is why I noticed that things got worse after the fans started spinning at greater than 20% duty cycle) for the temperature sensor to flip out.
> 1 votes

---
Tags: arduino-uno, pwm, temperature-sensor
---


# Question
Title: 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):

I just received the one without this blue plate and pins:

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!

# Answer
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). This datasheet 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 votes

---
Tags: bluetooth, pins, hc-06
---


title: While loop not breaking

text:
# Question
Title: While loop not breaking
I'm trying to build a circuit that buzzes until a button is pressed, or it buzzes 5 times:

```
void alarm()
{
  int AlarmState = 0; //Just to get while loop going
  int count = 1;
  while(AlarmState==0)
  {
    int count = 1;
    AlarmState = digitalRead(alarmStop);
    digitalWrite(buzz,HIGH);
    AlarmState = digitalRead(alarmStop);
    delay(500);
    AlarmState = digitalRead(alarmStop);
    digitalWrite(buzz,LOW);
    AlarmState = digitalRead(alarmStop);
    delay(500);
    count++;
    if(count>=5){
       break;
    }
  }

```

I put a bunch of digitalRead's so it has a better chance of catching the button press while the loop is going, there's a better way to do that I'm sure but it's not my main concern right now.

This is part of a larger project, but I hope I've posted only the necessary code. The function runs, but does not break after `count` equals 5. Why?

# Answer
Try This One its Simple:

```
void alarm()
{
  int count = 0;
  while ( digitalRead(alarmStop) && (count++ <5))
  {
    //A
    digitalWrite(buzz, HIGH);
    delay(500);
    digitalWrite(buzz, LOW);
    delay(500);
  }
}

```

But, There is a logical problem with this Code. Lets say that your code is at point A (metioned in comment) and at same time button is pressed. Now This code above will, still buzz and then stop.

To avoid This try using interrupts. To use interrupts on Arduino I prefer This Library. Download Here. Extract this and inside you will find a folder Named **PinChangeInt**. Copy This whole folder to your **Documents\Arduino\libraries** folder. Now, restart Arduino IDE and copy paste this code:

```
#include <PinChangeInt.h>

int buzz = 3;

bool alarmStatus = false;
#define PIN3 4
void pin3func() {
  digitalWrite(buzz, LOW);
  alarmStatus = true;
}

void setup() {
  pinMode(PIN3, INPUT); digitalWrite(PIN3, HIGH);
  PCintPort::attachInterrupt(PIN3, &pin3func, CHANGE);
}

int count = 0;
void loop() {
  if (count < 5)
  {
    if (!alarmStatus)
    {
      digitalWrite(buzz, HIGH);
    }
    delay(500);
    digitalWrite(buzz, LOW);
    delay(500);
  }
}

```

Because, of unavailability of hardware, I haven't tested this code. But, I hope It will work.
> 0 votes

# Answer
The problem with your code is your using `delay()`. This is a function that should most of the time be avoided for one simple reason: when the Arduino is executing the `delay()` instruction, it does *nothing* but wait. This means, among other things, that it cannot be reactive to user input. As outlined by ARK in his answer, interrupts could be used to overcome this problem. But you actually do not need them: the standard way to avoid delays is to use instead the `millis()` function to control timings. This approach is well described in the Blink without delay Arduino tutorial.

Here is how you can apply this technique to your `alarm()` function: In a nutshell, you can think of `delay()` to be roughly equivalent to this:

```
void naiveDelay(uint32_t ms)
{
    uint32_t start = millis();
    while (millis() - start < ms) {
        // do nothing
    }
}

```

The problem here is the “do nothing” part. You do not want your program to do nothing, you want it to monitor the “alarm stop” button. So the simple solution to your problem is to replace `delay()` by the code above, and then change it so that it monitors the button instead of doing nothing. Then you get something like this:

```
void alarm()
{
    for (int count = 0; count < 5; count++) {

        // start the buzzer
        digitalWrite(buzz, HIGH);

        // first delay
        uint32_t start = millis();
        while (millis() - start < 500) {
            if (digitalRead(alarmStop) == HIGH) {
                digitalWrite(buzz, LOW);  // stop the buzzer
                return;
            }
        }

        // stop the buzzer
        digitalWrite(buzz, LOW);

        // second delay
        start = millis();
        while (millis() - start < 500) {
            if (digitalRead(alarmStop) == HIGH) {
                return;  // buzzer already off
            }
        }
    }
}

```
> 0 votes

# Answer
I think the main problem with the code not breaking within the `while()` statement is what @ott pointed out above.

To expand on the exact problem, note that you have defined two different `count` variables in your code. Each has a different scope.

As soon as you enter the alarm function, you define an `int count` variable and initialize it. Then, when you enter the `while ()` statement, you define a second `int count` variable and initialize it. These are NOT the same variable. This second variable is the one being used and unfortunately, is reinitialized each time through the loop. It will always have a value of 1 so your test for it becoming greater than or equal to 5 will never test true. Thus no break.

If you comment out the second `int count` line, your loop should then work and break as expected. it should look like this:

```
  while(AlarmState==0)
  {
  //  int count = 1;
    AlarmState = digitalRead(alarmStop);

```

Others have pointed out other improvements that can be made to the code but the two variables of the same name with different scopes appear to be the specific cause of the `while()` not breaking.
> 0 votes

# Answer
```
void alarm()
{
  int AlarmState = 0;
  int count = 1;
  while(AlarmState==0) //Your count == 2, then while starts over again and you redefine you count to 1, so thats becomes infinite loop
  {
    int count = 1; //Here you initialize "count" second time
    AlarmState = digitalRead(alarmStop);
    digitalWrite(buzz,HIGH);
    AlarmState = digitalRead(alarmStop);
    delay(500);
    AlarmState = digitalRead(alarmStop);
    digitalWrite(buzz,LOW);
    AlarmState = digitalRead(alarmStop);
    delay(500);
    count++; //Now you incrementing count value, 1+1 = 2, go back to "while" and read
    if(count>=5){
       break;
    }
  }

```
> 0 votes

---
Tags: programming, c++, sketch
---


title: Resetting Arduino UNO code (newbie)

text:
# Question
Title: 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.

# Answer
> 0 votes
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).

# Answer
> 0 votes
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.

---
Tags: arduino-uno, reset
---


# Question
Title: 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?

# Answer
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.
> 0 votes

# Answer
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:

Just as an example, the README of 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.
> 2 votes

# Answer
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.
> 1 votes

---
Tags: serial
---


# Question
Title: 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.

# Answer
> 1 votes
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.

# Answer
> 1 votes
You defined DHT as dht. So you'll have to replace those DHT with dht and you'll be good to go.

---
Tags: esp8266, thingspeak
---


# Question
Title: Why is Toolchain Not Updated with Arduino IDE Install on Mac
I have not been doing any Arduino work for about a year. The last time I ran the Arduino IDE was in the previous version of MacOS. Now that I have updated to the latest MacOS Version Catalina (10.15.2) I discovered that the IDE will not compile because the avr-g++ compiler is 32 bit and will not execute on the *now* 64-bit required MacOS.

So I did the obvious thing. I went to the arduino.cc web site and downloaded the latest version of Arduino IDE thinking that this should solve the problem. I updated to version 1.8.11 of the IDE but the 32-bit problem persisted.

I finally decided that the IDE was updating (new Arduino IDE app) but that the avr toolchain was not being updated. To force this update, I deleted the entire avr toolchain from my ~/Library folder. Now, re-running the IDE is all it took: It discovered the toolchain missing and re-installed and installed with the correct 64 bit binaries (which were part of the new Arduino App all the time).

Perplexing -- why was the toolchain not updated with the install? Is it a requirement to delete the existing toolchain before doing a new install of the Arduino App?

# Answer
> 1 votes
The boards packages maintained by Boards Manager and associated tools are installed in .arduino15 folder. The AVR boards package bundled with IDE is only used when there is no AVR boards package version in the .arduino15 folder.

To locate the .arduino15 folder open Preferences in IDE and there at the bottom of the window is displayed the location of the preferences file with full path to .arduino15 folder.

The content of .arduino15 folder is not changed with IDE update.

---
Tags: arduino-ide, mac-os, avr-toolchain
---


# Question
Title: 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")

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:

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

# Answer
> 1 votes
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)

```

---
Tags: arduino-uno, python
---


# Question
Title: Is there an Adafruit function to invert the colors of my screen for Arduino language?
I am trying to invert the color of my OLED display screen once a button is pushed. I have the button situation figured out but I can not find a function that inverts the color. I am using these two libraries to handle my screen on the Arduino IDE.

Adafruit\_GFX.h, Adafruit\_SSD1306.h

Any help would be much appreciated.

# Answer
> 3 votes
There is a function that invert the colors of your screen, you can pick either black on white or white on black, I have tried it and I have quite experience with your display, I think you should try this piece of code.

At the beginning of your Arduino code be sure that you declared the object using the same name.

```
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

```

To invert the display

```
display.invertDisplay(true);

```

To return the display again

```
display.invertDisplay(false);

```

As you said that you want a button to invert the display you might use this code I made

```
if(digitalRead(BUTTON_PIN)){
    display.invertDisplay(true);
}
else{
    display.invertDisplay(false);
}

```

Or you might use **Interrupts** for better performance depending on your code.

As you couldn't find on the internet, I am student and I learn alot from the internet, to for example search for such a function in an Arduino library, try searching it's documentation or it's page on GitHub then afterwards see the function you want through the pages, but don't just search the function directly it will **sometimes** won't work as they are not that popular.

As a last thing Here is the documents where I got the function with it's parameters from.

I hope I've helped you out. any edits in the answer is well appreciated, as I am a student.

---
Tags: arduino-nano, led, adafruit, functions
---


# Question
Title: Where are the traces connected to RESET-EN leading?
Once again, I am following this schematic, and I am confused as to where RESET-EN connects:

This is how I have it mocked up it Fritzing, but I feel like this is incorrect:

# Answer
This is the DTR output of the ATmega16u2 which is connected to RESET pin of the ATmega2560 for reset by avrdude over DTR signal before upload of the sketch. There is a trace by default. Cutting the trace disables the auto-reset. Soldering a bridge on RESET-EN pads re-enables the auto-reset.

the schematics part you quoted in question misses the long unconnected line for the RESET label. It leads here:
> 2 votes

---
Tags: arduino-mega
---


# Question
Title: Multiple I2C sensors with the same address
I am trying to find the simplest way to connect multiple (preferably around 10-20) IMU sensors to one controller. There are two constraints: sampling at 60Hz and reasonably simple wiring as I want to put it on clothes.

I am totally new to the Arduino world, please let me know what other details I should provide.

It seems that just having multiple IMUs on the I2C bus would work great, but they usually all come with the same address.

So, the solutions I found so far:

* Using several different IMUs from different companies - hard to find 20 of them
* Using a multiplexer - requires star-like wiring topology.
* Using multiple controllers - inefficient and doesn't seem right.

For now, the solution with a multiplexer seems to me the most reasonable, but is there any other way I am missing? Can I somehow produce IMUs with, say, 16 different addresses and wire them all together to one I2C?

Thanks for your help!

# Answer
> 13 votes
If you're using MPU6050 IMUs, there's an easy trick: put them all on the I2C bus, and connect each IMU's `AD0` pin to a separate digital pin on the Arduino\[\*\]. When you want to read from a specific IMU, set all `AD0`s to `HIGH`, except the one you want to read to `LOW`. All the IMUs with `AD0` set to `HIGH` with have an I2C address of 0x69, whereas the only one on `LOW` will have an address of 0x68.

If you want to read them all, you just go through a loop and set the one you want to `LOW`, the others to `HIGH`, and you're set.

\[\*\] If you want 20 IMUs, you'd better get a Mega, or, even better, a Maple. Small form factor, quite a bit of oomph, lots of pins and flash, and some clones cost next to nothing; eg Itead sells Maple clones for 6 bucks. ElecFreaks sells them for 9 bucks. You could use the 16 pins at the bottom for the `AD0`s.

This trick works with any kind of I2C device that has a customizable address scheme through one or more pins. I do that with AT24Cxx EEPROMS, which have a 0x50-57 address range. When you want to have more than eight chips, setting all but one to 0x50 and one to 0x51 solves the problem pronto.

Reference: https://github.com/PaulStoffregen/FreeIMU\_original/blob/master/documents/PS-MPU-6000A-00v3.4.pdf

# Answer
> 3 votes
You can also get I2C Multiplexers such as the TCA9545A that can split one I2C line into 4 buses. I have connected up to 9 MPU9150 on one line with that.

# Answer
> 1 votes
Another way is to use a **software emulation of the I2C interface** so that any of the digital I/O pins may act as an I2C pin. One well-written library you can use for this is **`SoftWire`** by Steven Marple. It can be installed via the Arduino Library Manager or directly from its GitHub repository here.

With this, you can select arbitrary pairs of pins to act as SDA and SCL for each I2C device and then you can communicate with each device individually.

Note that with this method, you need two digital pins for each I2C device. In that sense, I believe @dda's answer is the best in regard to these IMUs in question.

---
Tags: sensors, i2c, multiplexer
---


# Question
Title: Using Capacitive Sensing Library with a 74HC4067 multiplexer
I'm trying to use the Capacitive Sensing Library by Paul Badger in conjunction with one or more 74HC4067 multiplexers to achieve a lot of capacitive touch inputs. I came across this youtube video where the poster seems to have accomplished what I'm trying but I can't seem to replicate this.

Here is the setup I'm using with an arduino nano, some 1MΩ resistors and a CD74HC4067 breakout :

Here is my Arduino code :

```
#include <CapacitiveSensor.h>

#define muxS0Pin 7
#define muxS1Pin 6
#define muxS2Pin 5
#define muxS3Pin 4
#define muxSignalPin 3
#define muxEnPin 8
#define capSenseSendPin 2
#define sampleRate 5

int touch[4] = {};

CapacitiveSensor capSense = CapacitiveSensor( capSenseSendPin, muxSignalPin );

void setup() {
    digitalWrite( muxEnPin, LOW );
    Serial.begin( 115200 );
}

void loop(){
    byte touchIndex = 0;
    for ( byte channel = 0; channel < 4; ++channel ) {
        digitalWrite( muxS0Pin, ( channel & 1 ) >> 0 );
        digitalWrite( muxS1Pin, ( channel & 2 ) >> 1 );
        digitalWrite( muxS2Pin, ( channel & 4 ) >> 2 );
        digitalWrite( muxS3Pin, ( channel & 8 ) >> 3 );
        touch[touchIndex] = capSense.capacitiveSensor( sampleRate );
        ++touchIndex;
    }
    for ( byte i = 0; i < 10; ++i ) {
        Serial.print( touch[i] );
        Serial.print("\t");
    }
    Serial.println();
}

```

This example attempts only four capacitive touch pads but eventually I plan to use all 16 and then another multiplexer, but right now I'm stuck on getting anything, I seem to be getting some readings on touching the last pad but it's not what I expect to see, and it affects all the reading.

I've successfully got a version of this running without a multiplexer just on ten IO pins and it worked great. I also got the multiplexer running fine in a separate example with 16 push buttons.

Could the problem be due to pad charge times or the send-recieve capsense signals getting stopped in the multiplexer?

Any and all help would be appreciated.

# Answer
This is way late, but for anyone who runs across this, here was my solution. The two main thing is explicitly using analog input pins (which could be quantized to digital values in the software, and making sure you have resitors on each channel being sensed. Also, ground the EN pin on the multiplexer

```
#include <CapacitiveSensor.h>

#define muxS0Pin 9  // I used these rather than 4-7
#define muxS1Pin 10
#define muxS2Pin 11
#define muxS3Pin 12

#define muxSignalPin A0      // explicitly set ro analog
#define capSenseSendPin A2   //

#define sampleRate 10
#define n_inputs 16

int touch[n_inputs] = {};

CapacitiveSensor capSense = CapacitiveSensor( capSenseSendPin, muxSignalPin );

int readMux(int channel) {
  int controlPin[] = {muxS0Pin, muxS1Pin, muxS2Pin, muxS3Pin};

  int muxChannel[16][4] = {
    {0, 0, 0, 0}, //channel 0
    {1, 0, 0, 0}, //channel 1
    {0, 1, 0, 0}, //channel 2
    {1, 1, 0, 0}, //channel 3
    {0, 0, 1, 0}, //channel 4
    {1, 0, 1, 0}, //channel 5
    {0, 1, 1, 0}, //channel 6
    {1, 1, 1, 0}, //channel 7
    {0, 0, 0, 1}, //channel 8
    {1, 0, 0, 1}, //channel 9
    {0, 1, 0, 1}, //channel 10
    {1, 1, 0, 1}, //channel 11
    {0, 0, 1, 1}, //channel 12
    {1, 0, 1, 1}, //channel 13
    {0, 1, 1, 1}, //channel 14
    {1, 1, 1, 1} //channel 15
  };

  //loop through the 4 contol pins
  for (int k = 0; k < 4; k ++) {
    digitalWrite(controlPin[k], muxChannel[channel][k]);
  }
  //read the value at the SIG pin
  return capSense.capacitiveSensor( sampleRate );
}

void setup() {
  // Very important to set control pins to output mode
  pinMode(muxS0Pin, OUTPUT);
  pinMode(muxS1Pin, OUTPUT);
  pinMode(muxS2Pin, OUTPUT);
  pinMode(muxS3Pin, OUTPUT);

  digitalWrite(muxS0Pin, LOW);
  digitalWrite(muxS1Pin, LOW);
  digitalWrite(muxS2Pin, LOW);
  digitalWrite(muxS3Pin, LOW);
  Serial.begin( 9600 );
}

void loop() {
  byte touchIndex = 0;
  for ( byte channel = 0; channel < n_inputs; ++channel ) {
    Serial.print( readMux(channel));
    Serial.print("\t");
  }
  Serial.println();
}

```
> 1 votes

---
Tags: sensors, arduino-nano, library, resistor, multiplexer
---


title: Using an external header file

text:
# Question
Title: Using an external header file
I have a project that is part of a larger repository, and shares header files with non-Arduino C programs.

I know that it's possible to use these headers by copying them to the libraries folder, or the sketch folder, but I would rather use them with a relative path (which seems to not work), so I can avoid copying files around for every repository clone or update.

Is there a solution that doesn't involve moving/copying the header file?

EDIT: Although there is no full solution for this question, I have since found that using the PlatformIO IDE instead solves the problem.

# Answer
> 4 votes
You can use header files with an absolute name, like:

```
#include "c:\Temp\x.h"

```

Another way that might help is to make the include path like:

```
#include "q:\x.h"

```

And use Windows to map driver letter Q to the path you need.

# Answer
> 3 votes
I tried to do this, and looked into it, a few years ago, but it doesn't appear to be possible to do what you want to do. This guy was having the same issue, #include statement with relative path.

Seems like either Michel's suggestion or copying them (which *is* a pain) will work, from Can I include a header file that is not a library?:

> If the include file is part of a single Sketch, instructions are here... http://www.arduino.cc/en/Hacking/BuildProcess \[new link\]
>
> If the include file is meant to be shared by multiple Sketches then...
>
> * Close the Arduino IDE
> * Navigate to the `{Arduino}\hardware\libraries` directory
> * Create a subdirectory. I suggest something like `MyCommon`.
> * In the new subdirectory, create a header file. I suggest something like `MyCommon.h`.
> * Open the new header file, edit it as you wish, and save it
> * Open the Arduino IDE
> * Create or open a Sketch
> * Add a `#include` to the top of the Sketch that references your new include file

---

This is ***why*** relative paths are not supported, from Re: how to include header file from previous folder?

> Enable verbose mode when compiling. Navigate to the Testing.cpp file that is created from the Testing .ino file. Go up one level. Do you see the files you are trying to include?

and from Re: how to include header file from previous folder? (emphasis is mine)

> The reason for having you go look at the something like/AppData/Local/Temp/build/sketch folder was to make you think about what the build process is doing, and maybe think that you could google Arduino + Build to get more details.
>
> The IDE copies your sketch, and stuff #included by your sketch to a build directory.
>
> If you #include , the file header.h, and everything else in the directory it is in, will be copied to the build directory, too.
>
> If you #include "header.h", the file header.h, and everything else in the directory it is in, will be copied to the build directory, too.
>
> The difference between \<\> and "" is where the header.h file is looked for. "" looks in the current directory. \<\> looks in the library directories.
>
> If the token between the \<\> or the "" is not found in the appropriate folder, you are not told that; nothing gets copied, though.
>
> But, **that explains why relative names are useless**. A sketch directory might contain a file called header.h. It will not contain a file called ..\header.h, because ..\header is NOT a valid file name.
>
> Note that I did NOT say that ..\header.h is not a valid NAME. I said that it is not a valid FILE NAME.
>
> Only file names between the \<\> or "" are possible, as far as the IDE is concerned.
>
> If you do not like that, you are free to not use the IDE.

Finally from Re: How to specify a path to a specific header file?

> The Arduino system has some severe limitations in its ability to work sensibly with the file system - can be a real PITA.

# Answer
> 0 votes
BTW, If you create multiple libraries in **libraries** folder, you can use relative reference path i.e in all Header files, you can use `#include "..\mylib2\xxxx.h`.

---
Tags: c
---


# Question
Title: make servo stay at the current position when attach() is called
I use a small *SG90* servo with arduino. When I call `attach()` servo moves to its default position or whatever I set with `write()` before it.

I’d like to make servo stay at the current position when I call `attach()` in `setup()`.

How can I achieve it?

I believe I can simply store last position in `EEPROM`. It’ll help a little. However, I’m afraid that EEPROM won’t last long.

# Answer
> 1 votes
You can't read the servo's position, so your sketch has no chance to know the *real current* position.

And you found that you have to set up the initial value of the servo "driver" to the one your sketch thinks is the last known position of the servo.

So your problem boils down to these questions: "How do I store a value during power-down times?" This leads to the common solution of storing the value in the EEPROM. This is a well-known and widely accepted solution, but you already found a problem: "How could a value be stored in the EEPROM without over-stressing it?"

You need to look up the guaranteed number of write cycles for a EEPROM cell. Then you need to think about the rate you would like to save the value. Divide the values and you know how long this will work. However, in reality the EEPROM will have much better endurance.

Some ideas how to "get better":

* Reduce the rate of saving. I see at least two factors: The refresh rate of the servo controlling pulse is just 50 Hz. And a servo will move between (extreme) positions only a few times per second. There might be no need to save more than once per second, or even slower, depending on your application.
* Don't save if the value has not changed. Well, this should be done already at the driver level of the EEPROM. It won't hurt to read its documentation and/or its source code.
* Use an as large as possible array to store the value. You will store a marker for "invalid" in all but one cell, and only this cell holds the real value. This will put the "load" of two writes per save on the EEPROM, but distribution over more than two cells will lower the average load. If you select an all-1s value as "invalid", it is actually just the same value as the erased value of the EEPROM, which is necessary the next time anyway.
* Add a circuit that detects the power loss *before the CPU stops*. This is the most chosen solution, but only usable when the hardware can do it. You need just a few milliseconds to save the value, look up the documentation. If you implement an ISR that catches the coming power loss, save the value and await the end.

---
Tags: servo
---


# Question
Title: 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:

```
#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?

# Answer
> 1 votes
OK so here is my solution.

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

```
#pragma once
#include <Arduino.h>

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

```

In `SafeSerial.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:

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

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

```

and in `setup()`:

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

# Answer
> 2 votes
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.

---
Tags: serial, arduino-leonardo
---


# Question
Title: What pins to use to externally power an Arduino Fio (without battery)
I need to power an enclosed Arduino Fio project with 12V. The intention is not to attach a battery because there is no need as this is a fixed installation with a 12V DC available (for a pair of relays which will be controlled by the Fio).

My question is what Pins should I use. The Fio page (https://www.arduino.cc/en/Main/ArduinoBoardFio) on the Arduino web site says...

Input Voltage 3.35 -12 V Input Voltage for Charge 3.7 - 7 V

Unfortunately, there is no indication what pins these specs refer to. I assume that the "Input Voltage for Charge" refers to the mini-USB port and unlike other Arduino boards, there is no Vin pin to supply the board externally. Looking at the board layout on the same web page, I think the only possible option is via the two pins in parallel to the battery port which I suppose are then going into the voltage regulator on the board.

Any comments or suggestions? Has anyone done something similar?

# Answer
I used the external switch input JP7-1 for 12v, any GND hole, and make sure the switch is off. This bypasses the charge circuit which doesn't like 12v.
> 1 votes

---
Tags: power
---


title: Clock frequency VS cycle time

text:
# Question
Title: Clock frequency VS cycle time
I am considering switching from Arduino Pro Mini 5V 16MHz to Arduino Pro Mini 3.3V 8Mhz for some project because I would like to run it with a 4.5V input power.

Will the switch from 16 to 8Mhz double the cycle time of my loop() function ?

Edit -- adding precision: My loop function is simple: it's reading a couple of sensors with analogRead and setting a few pins to HIGH or LOW. It does not use delay().

Thanks.

# Answer
> 3 votes
The execution time of your `loop()` will be slightly longer when the CPU runs at 8 MHz v.s. 16 MHz, but I don't expect the difference to be significant. CPU-bound functions, such as `digitalWrite()`, will run at half the speed. These functions, however, are quite fast. In contrast, `analogRead()` is slow, as it takes roughly 110 µs to execute, so this is likely where your `loop()` spends most of its time.

The execution time of `analogRead()` does not depend significantly on the CPU speed. This function spends most of its time waiting from the analog-to-digital converter to do its conversion. When the CPU is clocked at either 1, 2, 4, 8 or 16 MHz, the Arduino core sets the ADC prescaler so that the ADC is clocked at 125 kHz. This means the conversion time will be the same irrespective of the CPU frequency.

**Note**: You may just use your Arduino Pro Mini 5V 16MHz. This board is based on the ATmega328P microcontroller, which is rated for frequencies up to 20 MHz when the supply voltage is between 4.5 and 5.5 V. According to the datasheet (see freq-Vcc graph), it should safely run at 16 MHz for any supply voltage between 3.78 and 5.5 V.

# Answer
> 0 votes
It depends.

The `loop` function is handled like a while loop. This means, when the `loop` function finishes, some framework code is executed (very small) and the `loop` function is called again etc.

However, there are some calls that do not depend on the clock speed, the best example is the `delay` function, but also if you made your own check using e.g. `millis` this will not depend high likely on the clock speed.

Beyond that, there can be peripheral calls which are not related to the clock speed (although internally in libraries timing functions as above are used to manage this), but you don't see them when used from a library.

---
Tags: arduino-pro-mini, frequency
---


# Question
Title: 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?

# Answer
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

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
3. Follow This tutorial from Digispark 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 to enable the Arduino IDE to program your Digispark clone directly from USB.
> 3 votes

# Answer
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 and try the driver they provide.
> 0 votes

---
Tags: power
---


title: ATmega328P-PU blink example not working

text:
# Question
Title: ATmega328P-PU blink example not working
I moved from an Arduino to a bare ATmega328P-PU (to save energy). First I wanted to start a blink-script to verify that it's all working. For this I flashed the bootloader and uploaded the blink-script on the microprocessor. On the arduino the internal pin was successfully blinking. Then I unmounted the ATmega and put it into a breadboard.

I wired everything up. The LED to GND and pin 13, on the other side I put in 5V from a battery, and GND of course. Between the LED and GND I added 220 Ohm and surprisingly if I power it over battery inside the Arduino the internal LED blinks but my own LED (the one with 220 ohms) does not. If I power the arduino over USB both of them blink.

Do you have any ideas on how I can fix this?

# Answer
> 2 votes
This might help you alot

The ATMega328 is 8bit AVR microcontroller with a wide variety of things, in order for this IC to work it's essential to have a "Clock Source".as default of Arduino UNO it uses a 16MHz Crystal oscillator with two 22pF capacitors in order to generate the clock signal so, if you took the ATMega328 from the Arduino and put it in a breadboard you should connect these components in order it to work as well as pulling up RESET pin to VCC.

The Atmega328 has a lot of internal calibrated oscillators, from them are 8MHz and 1MHz and alot more, but in order to them to work you need to configure them first by setting up things called "high fuses and low fuses" these control alot of things in the microcontroller from them they determine the clock source.

As how to burn the bootloader to set fuses is not the topic of the question, I won't come to details about it.

---
Tags: atmega328, wires, prototype
---


title: Arduino Firebase ESP8266 Connection

text:
# Question
Title: Arduino Firebase ESP8266 Connection
I am working on a project that needs data to be stored in cloud db so that I can access the data in a mobile application. For database I have considered Firebase. I am following the following link. But when i try to install the libraries i am getting `No such file or directory found` errors for `memory`, `queue`, `Firebase.h`, `vector`, `functional`, `utilities` (not all but different packages shows different errors). I tried downloading different packages from github. But still had the errors. Where can I find the correct working program? Thanks in advance.

# Answer
> 1 votes
The usual Firebase library for esp8266 is https://github.com/FirebaseExtended/firebase-arduino.

And there is some new Firebase library in Library Manager in IDE. The "More info" link leads to https://github.com/mobizt/Firebase-ESP8266

---
Tags: arduino-uno, esp8266
---


# Question
Title: Adjust time calculation after Timer0 frequency change
I have an Arduino Nano with an 328P and need all 6 PWM pins.

Thus, I had to adjust the prescaler and WGM Mode of Timer0.

It is now in phase correct PWM mode with a prescaler of 1.

```
TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM00);
TCCR0B = _BV(CS00);

```

Now I need a working time calculation for other libraries, but since Timer0 had that duty everything is out of order now.

I tried adjusting the wiring.c

```
// the prescaler is set so that timer0 ticks every 64 clock cycles, and the
// the overflow handler is called every 256 ticks.
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))

```

to this

```
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(1 * 510))

```

But it's like I didn't change anything. (tested other settings that **were changed** so it was compiled anew )

Whole Code:

```
void setup() {

  // Set Timer 0, 1 and 2
  // Register A: Output A and B to non-inverted PWM and PWM mode to phase correct.
  // Register B: Pre Scaler to 1.
  TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM00);
  TCCR0B = _BV(CS00);

  TCCR1A = _BV(COM1A1) | _BV(COM1B1) | _BV(WGM10);
  TCCR1B = _BV(CS10);

  TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM20);
  TCCR2B = _BV(CS20);

  pinMode(8, OUTPUT);

}
void loop() {

  digitalWrite(8, LOW);
  delay(65000);
  digitalWrite(8, HIGH);
  delay(65000);

}

```

# Answer
> 4 votes
Fixing the timekeeping functions with your PWM settings is not so simple. You should at least try to rewrite `ISR(TIMER0_OVF_vect)`, `micros()`, and probably `delay()`. Here is why:

First, there is a rounding problem. Time is kept using two global variables:

```
volatile unsigned long timer0_millis;
static unsigned char timer0_fract;

```

The first one is what `millis()` returns. The second one keeps track of how much time has passed since the last full millisecond, and it does so in units of 8 µs. The two variables are incremented by `ISR(TIMER0_OVF_vect)` like this:

```
m += MILLIS_INC;  // temporary copy of timer0_millis
f += FRACT_INC;   // temporary copy of timer0_fract

```

On a normal Uno configuration, the ISR is called every 1024 µs. Then `MILLIS_INC` is 1 and `FRACT_INC` is 3. With your timer configuration, the ISR is called every 31.875 µs (510 cycles), then `MILLIS_INC` should be 0 and `FRACT_INC` should be 3.984375. But since we are dealing with integers, it will be rounded down to 3, and your `millis()` will tick about 25% too slow.

A simple fix would be to

```
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(1 * 512))

```

in order for `FRACT_INC` to be 4 and `millis()` to be 0.4% too fast. Or you could make `timer0_fract` a 16-bit variable and have it count clock cycles, just to avoid this error. Either option should fix `millis()`, but you still have a problem with `micros()`.

`micros()` works by reading both `timer0_overflow_count` (incremented by 1 in the ISR) and the actual counter value. Since your counter is now going alternatively up and down, it will be harder to compute a microsecond count from these readings. Maybe you could take two consecutive readings of the counter, just to know whether it is going up or down...

And then there is `delay()`, which relies on `micros()`. If you fix `micros()`, `delay()` should work fine. If not, You could rewrite `delay()` to use `millis()` instead, which should be easy but you will loose some accuracy.

# Answer
> 0 votes
You have set `MICROSECONDS_PER_TIMER0_OVERFLOW` to a proper value, however, this is only ever used by `MILLIS_INC`, which in turn is only ever used by `millis()`. This means that the other timing functions, such as `micros()`, `delay()`, `delayMicroseconds()` break when timer0 is changed. This is kind of a bug, and it may be fixed in a future version, but for now, the Arduino libraries are expecting you to leave timer0 alone. The best workaround is to only use `millis()` for your timing critical functions.

# Answer
> 0 votes
THIS IS AN INCOMPLETE ANSWER - Edgar knows what he's talking about, listen to him

I am currently working with this same thing but in an ATMega2560. This website helped me understand the millis() function better. The timer overflows every 510 counts (see datasheet, pg 123 for the atmega2560). I believe it is 510 and not 512 because it counts up and down, but does not repeat a count at the top or bottom - for example if you count starting from 1 up to 10 and then back down (without repeating 10) you will have counted 19 times, not 20. This counter starts at 0, counts to 255, and then back to 0, triggering an overflow before hitting 0 again. This is is 256 (count up including 0 and 255) + 254 (count down, not including 255 or 0) = 510. I wrote a python script to visualize the effect of these changes and trying to account for them. This counts to 10 million, so it takes time to run, but by the end, even with scaling, the error if simply adjusting millis() after the fact could be ~7 seconds.

```
#! /usr/bin/env python
import numpy as np

realT = np.zeros(10000000)
timer0_millis = np.zeros(10000000)
timer0_fract = np.zeros(10000000)
i=0

for i in range (1,10000000):
    timer0_millis[i] = timer0_millis[i-1] + 1
    timer0_fract[i] = timer0_fract[i-1] + 3
    realT[i] = i*31875
    if timer0_fract[i-1] >= 125:
        timer0_fract[i] = timer0_fract[i-1] - 125
        timer0_millis[i] = timer0_millis[i-1] + 1

adjusted = timer0_millis*510/(256*64)

print "after 100 timer interrupts millis() will read %d, actual millis is %.6f, adjusted millis is %.6f" % (timer0_millis[99], realT[99]/1000000, adjusted[99])
print "after 1000 timer interrupts millis() will read %d, actual millis is %.6f, adjusted millis is %.6f" % (timer0_millis[999], realT[999]/1000000, adjusted[999])
print "after 10000 timer interrupts millis() will read %d, actual millis is %.6f, adjusted millis is %.6f" % (timer0_millis[9999], realT[9999]/1000000, adjusted[9999])
print "after 100000 timer interrupts millis() will read %d, actual millis is %.6f, adjusted millis is %.6f" % (timer0_millis[99999], realT[99999]/1000000, adjusted[99999])
print "after 1000000 timer interrupts millis() will read %d, actual millis is %.6f, adjusted millis is %.6f" % (timer0_millis[999999], realT[999999]/1000000, adjusted[999999])
print "after 10000000 timer interrupts millis() will read %d, actual millis is %.6f, adjusted millis is %.6f" % (timer0_millis[9999999], realT[9999999]/1000000, adjusted[9999999])

```

# Answer
> 0 votes
Thanks to Edgar's answer and Nebsie's explaination on how the counter exactly works I could come up with my own implementation of how to rectify delay and micros() that - so far - seems to work fine on my Arduino Uno.

I'm not saying that this is the most precise implementation, especially I have my doubts on micros() if for example an timer overflow occours between reading t1 and t2, but it is one that so far for me works well.

First thing - according to Edgar's recommendation I defined:

```
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(1 * 512))

```

However this doesn't affect timing of micros() or delay().

Function micros() I changed to read two times from TCNT0 - to determine whether it is counting upwards or downwards. This is done with the "if (t1 \> t2)" clause. The overflow count "m" is multiplied by 510, because the counter elapses after 510 steps. Then the calculated counter value "t" is added to this, divided by the number of clocks per Microsecond. (Note: Prescaler = 1, therefore no further multplication).

```
unsigned long micros() {
    unsigned long m;
    uint8_t oldSREG = SREG, t1, t2;
    uint16_t t;

    cli();
    m = timer0_overflow_count;
#if defined(TCNT0)
    t1 = TCNT0;
#elif defined(TCNT0L)
    t1 = TCNT0L;
#else
    #error TIMER 0 not defined
#endif

#if defined(TCNT0)
    t2 = TCNT0;
#elif defined(TCNT0L)
    t2 = TCNT0L;
#else
    #error TIMER 0 not defined
#endif

    if (t1 >= t2) {
        t = 510 - t2;       // counter running backwards
    } else {
        t = t2;             // counter running upwards
    }

#ifdef TIFR0
    if ((TIFR0 & _BV(TOV0)) && (t2 > 1))        // if overflow flag is set -> increase m
        m++;
#else
    if ((TIFR & _BV(TOV0)) && (t2 > 1))
        m++;
#endif

    SREG = oldSREG;

    return ((m * 510) + t)  / clockCyclesPerMicrosecond();
}

```

HOWEVER - this seems to work fine but I had issues to begin with (before editing this again). Due to the counter running much faster, every 268 seconds the unsigned long datatype of micros() overflows and starts from zero again. This led to an unwanted lockup of delay(), especially if long delay times, like in my case delays of one second per loop iterations are used. Therefore I also had to add an overflow detection to the delay() function in arduino wiring.c.

If the overflow occurs, timing might not be very precise. But since this is once overy 268 seconds it may be acceptable. So far with this change the delay function works fine again on my side.

```
void delay(unsigned long ms)
{
    uint32_t start = micros();
    uint32_t elapsed = 0;

    while (ms > 0) {
        yield();
        while ( ms > 0 && (micros() - 1000) >= (start + elapsed)) {
            ms--;
            elapsed += 1000;
        }
        if( start > micros() ) {    // overflow detected
            start = micros();       // reset start
            elapsed = 0;            // reset elapsed
        }
    }
}

```

---
Tags: pwm, timers, millis
---


# Question
Title: how to get serial data to wait until a certain length is reached
I have a code that loops through 2 different serial inputs on the arduino mega, and sends them to serial constantly:

```
int RFIDResetPin = 13;

void setup()
{
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial2.begin(9600);
  pinMode(RFIDResetPin, OUTPUT);
  digitalWrite(RFIDResetPin, HIGH);
}

void loop() {

  char tagString1[13];
  int index = 0;
  boolean reading1 = false;
  boolean reading2 = false;
  ///////////////////////////////////////
  //this reads from the reader installed
  //on serial1, which is pin 19
  //////////////////////////////////////
  while (Serial1.available() > 0) {

    int readByte1 = Serial1.read(); //read next available byte

    if (readByte1 == 2) reading1 = true;
    if (readByte1 == 3) reading1 = false;

    if (reading1 && readByte1 != 2 && readByte1 != 10 && readByte1 != 13) {
      tagString1[index] = readByte1;
      index++;
    }
  }
  Serial.println(String("Reader 7: ") + tagString1); //the tag itself

delay(1);
  clearTag(tagString1); //Clear the char of all value
  resetReader(); //reset the RFID reader
  //////////////////////////////////////////////////
  // This bit reads from serial2, located on pin 17
  /////////////////////////////////////////////////
  while (Serial2.available() > 0) {

    int readByte2 = Serial2.read();

    if (readByte2 == 2) reading2 = true;
    if (readByte2 == 3) reading2 = false;

    if (reading2 && readByte2 != 2 && readByte2 != 10 && readByte2 != 13) {
      tagString1[index] = readByte2;
      index++;
    }
  }
  Serial.println(String("Reader 8: ") + tagString1);

  clearTag(tagString1);
  resetReader();
}

void resetReader() {
  ///////////////////////////////////
  //Reset the RFID reader to read again.
  ///////////////////////////////////
  digitalWrite(RFIDResetPin, LOW);
  digitalWrite(RFIDResetPin, HIGH);
  delay(150);
}

void clearTag(char one[]) {
  ///////////////////////////////////
  //clear the char array by filling with null – ASCII 0
  //Will think same tag has been read otherwise
  ///////////////////////////////////
  for (int i = 0; i < strlen(one); i++) {
    one[i] = 0;
  }
}

```

when not scanning anything, the serial monitor outputs this:

```
Reader 1:
Reader 2:
Reader 1:
Reader 2:

```

When I scan a tag, lets say on reader 1, I get this:

```
Reader 1: 000004f5
Reader 2:
Reader 1: 000004f5
Reader 2:

```

it is not possible to scan more than a single scanner at a time. Is it possible to get the first line to wait until a certain number of characters have been scanned (indicating a tag has been scanned), and then output to the serial monitor?After that initial run, the code will loop as I showed above. any help is appreciated.

# Answer
I would use a programming concept called a state machine. For example an integer variable called State could be used to track the current status which could for example be WAITING\_FOR\_DATA or RECEIVING\_DATA or DATA\_COMPLETE and only print when DATA\_COMPLETE. I'm sure there are plenty of examples you could find with an appropriate search.
> 2 votes

# Answer
1.prefer using Serial.readStringUntil(); OR Serial.readString() that way its much easy to manipulate.

2.use a static variable in loop function which stores the string or use a global variable to save char array tagString1 before going in println function same goes with the second reader that way the println will show the previous scan until a new scan is not done.

3.print both the tagstrings in the end of the code one after another
> 1 votes

---
Tags: serial, arduino-mega, rfid
---


# Question
Title: How to print stack trace and register dumps on arduino serial monitor?
I want to debug my ESP32 module which is giving an exception using ESP32 exception decoder, but for that, I would need to have access to my stack trace to paste it. But currently, my arduino serial monitor does not print the stack trace. (as shown below)

But I would need stack trace to be printed, like in the below image to debug my exception. How can I print it on the serial monitor?

# Answer
> 0 votes
Got the required trace logs at the output. All I had to do was enable PSRAM in tools.

---
Tags: arduino-uno, arduino-ide, esp32, debug
---


title: Blank output in serial monitor

text:
# Question
Title: Blank output in serial monitor
So my SIM900 GSM Shield is working fine with Netlight LED blinking and Status LED solid light, after I upload the code nothing happens about *mySerial()* in my serial monitor. Can I take your time for you to check this code out? I wonder if the problem lies here.

```
#include<SoftwareSerial.h>

//Create software serial object to communicate with SIM900
SoftwareSerial mySerial(7, 8); //SIM900 Tx & Rx is connected to Arduino #7 & #8

/*void SIM900power()
{
  pinMode(9, OUTPUT);
  digitalWrite(9,LOW);
  delay(1000);
  digitalWrite(9,HIGH);
  delay(2000);
  digitalWrite(9,LOW);
  delay(3000);
}*/
void setup() {
  // put your setup code here, to run once:
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);
  //Begin serial communication with Arduino and SIM900
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Handshaking with SIM900
  updateSerial();
  mySerial.println("AT+CSQ"); //Signal quality test, value range is 0-31 , 31 is the best
  updateSerial();
  mySerial.println("AT+CCID"); //Read SIM information to confirm whether the SIM is plugged
  updateSerial();
  mySerial.println("AT+CREG?"); //Check whether it has registered in the network
  updateSerial();
  mySerial.println("AT+COPS?"); // Check that you're connected to the network;
  updateSerial();
}

void loop() {
  // put your main code here, to run repeatedly:
  updateSerial();
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

```

Output:

# Answer
> 0 votes
Step 1) Check RX TX connections Step 2) Change your baud rate to 115200. Turn off your arduino. Turn off gsm. Start your gsm first and then your arduino.

or Step 3) Upload Software Serial code and just send "AT" without quotes using serial monitor. If your connections are correct you should get reply as AT. Also make sure to set the baud rates to 115200. Most of the GSM modules have default baud rate at 115200 or have auto baud adjustment enabled but need to be power cycled.

---
Tags: arduino-uno, gsm
---


# Question
Title: Which board has the highest max current via 3.3v pin?
Is there any arduino board which can deliver 600-800ma via 3.3v pin? Maybe the Arduino due or the nano 33 ble?

# Answer
> 2 votes
Your USB will output only 500mA or max to max 1A in some cases. Even if your board is rated for higher output you will be restricted by your source. First step is to increase your source. Secondly check which 3.3V regulator is present on which board and check the datasheet of the regulator to get information about it. Either ways you can externally add a high current 3.3V regulator and connect it to your 3.3V pin on the arduino. As voltages are equal no current will flow between them. But remember your source needs to output the higher current first

---
Tags: current, board
---


# Question
Title: Grbl on Arduino Uno (Elegoo) with DM542 + nema24 stepper motor not working
i've already searched and tried for a quite depressing amount of hours, but am not able to solve this problem:

The parts are the following: \- Elegoo Arduino Uno, on wich i flashed GRBL \- 24v Power Supply (wich powers the stepper motor(s) \- Nema24 3nm stepper motor \- A DM542 Driver \- bCNC (exe-build on win7 and win10)

Now, i connected one stepper-driver and stepper-motor as x-axis to the arduino. The wiring is as following: \- 5v from arduino to the three + Pins (ENA, DIR and PUL) \- Pin 2 to PUL, Pin 5 to DIR, Pin 8 to ENA \- 24V go to + and ground port of the driver, the 4 motor-wires are wired accordingly to the driver

I downloaded GRBL from Github and flashed it to the Arduino (i can run grbl-commands from the serial monitor inside the arduino ide, grbl is unlocked), connected everything and opened up bCNC, searched for the arduino on com-port, wich is shown correctly, and connected wich works fine (in the main screen "connected" shows up). However when i try to move the x-axis under the control-panel in bcnc, nothing moves, on the screen the numbers change correctly and i get an ok in the logs, but the motor does not move a bit. I double checked the wiring and tried to write a little program in arduino ide to move the stepper motor without grbl (deleted grbl, wrote a little program wich manually set the intervals ecc), without changing the wiring, that worked... How can i debug this? Any suggestions?

Thanks in advance!

# Answer
> 1 votes
As you wrote, that you connected the positive pins of ENA, DIR and PUL to 5V, I guess you use the common anode connection scheme from the DM542's datasheet (the driver seems to have optocouplers for the inputs). That would mean the inputs are active low (a Pulse would be a transition from HIGH to LOW and then back to HIGH).

GRBL v1.1 has by default an active high pulse signal:

> By default, a step signal starts at normal-low and goes high upon a step pulse event. After a step pulse time set by $0, the pin resets to low, until the next step pulse event.

(from the GRBL github wiki). I guess, this is the problem. Please try to set GRBL for inverting the pulse signal with `$2` (you may well find a corresponding setting inside bCNC.

Be sure, that GRBL is outputting the signals, that your driver is expecting in your connection scheme.

---
Tags: arduino-uno, stepper-motor
---