# Question
Title: HC-SR04 distance measuring without delay?
I am using the HC-SR04 ultra sound sensor for Arduino. I have used the following code to calculate distance and it works perfectly.

```
  long duration;
  digitalWrite(trigger, LOW);
  delayMicroseconds(2);
  digitalWrite(trigger, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigger, LOW);
  duration = pulseIn(echo, HIGH);
  distance = (duration/2) / 29.1;

```

However I want to use three more of these sensors, for a total of four. This block of code will be called every time I want to find the distance of one of the sensors. I am worried however that `delayMicroseconds()` pauses the entire program and that I cannot perform other tasks in while the sensors are working (e.g. driving wheels, it's a robot). The following code is object oriented for each sensor.

```
class distSensor{
   int trigPin;
   int echoPin;
   int distance;

   //Will be used in timer
   unsigned long previousMillis;

   public:
   distSensor(int tPin,int ePin){
   trigPin = tPin;
   echoPin = ePin;

   pinMode(trigPin, OUTPUT);
   pinMode(echoPin, INPUT);

   previousMillis = 0;
 }

 int calculateDistance(){

  //records time since program start
  unsigned long currentMillis = millis();

  long duration;
  digitalWrite(trigPin, LOW);

  //check if the previous time the method was called is greater than the interval of 2
  if(currentMillis - previousMillis > 2){
    digitalWrite(trigPin, HIGH);
    previousMillis = currentMillis;
  }

  //check if distance between current time and previous time it was called is greater than interval of 10.
  if(currentMillis - previousMillis > 10){
      digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  }
  return distance;
 }
};

```

In the `calculateDistance()` method I am trying to do the same thing as the first code but without `delay()` and instead a timer. But when I run the program it does not work and distance is read as 0. Can anyone help me rewrite the HC-SR04 code from the start that doesn't delay the whole program?

# Answer
> 2 votes
`delay()` causes the processor to do nothing but wait. You need to switch to `millis()`.

In your code, you need to "grab" the current time using `millis()` and store it in a variable. Add the number of milliseconds that you want to wait to this variable - you will have to consider the case where this value will overflow for a complete solution. Then, in your code, you need to create an infinite loop where you check what `millis()` returns. When your stored value and `millis()` match, it is time to execute the code that would normally come after the `delay()` call.

Here, Arduino Playground - How and Why to avoid delay(), `delay()` and `millis()` are discussed in detail.

So that this answer will cover your question, consider placing all your events which need to be timed into this one infinite loop. Also, consider keeping independent variables, one for each timed event, such that different events are timed independently.

# Answer
> 1 votes
```
enter code here
#define ECHO 5        // Pin received echo pulse
#define TRIGGER 6     // Pin sends shot pulse

int distance; // the distance in cms
unsigned long previousMicros = 0; // will sotre last time TRIGGER was updated
long OnTime = 10; //microseconds of on-time
long OffTime = 2; //microseconds of off-time
unsigned long previousMillis = 0; //will store last time viewTime was updated
int triggerState = LOW; // triggerState used to set it up
long duration;
void setup()
{
  Serial.begin(9600);
  pinMode(ECHO, INPUT);
  pinMode(TRIGGER, OUTPUT);
}

void loop()
{
  // check to see if it's time to change the state of the TRIGGER
  unsigned long currentMicros = micros();
  if((triggerState == LOW) && (currentMicros - previousMicros >= OffTime))
   {
     triggerState = HIGH; // turn it on
     previousMicros = currentMicros; // remember the time
     digitalWrite(TRIGGER, triggerState); // update the actual trigger
   }
   else if((triggerState == HIGH) && (currentMicros - previousMicros >= OnTime))
   {
     triggerState = LOW; // turn it off
     previousMicros = currentMicros; // remember the time
     digitalWrite(TRIGGER, triggerState); // update the actual trigger
   }

duration = pulseIn(ECHO,HIGH  );
Serial.println(distance);
distance = ((duration*0.034)/2);
Serial.print("distance: ");

}

```

**this will run your code without delay but the problem is you will get a zero every time resulting from pulseIn() which from there on I dont know how to fix it yet**

# Answer
> 0 votes
```
unsigned long currentMillis = micros();
digitalWrite(Trig, LOW);

if (currentMillis - previousMillis > 4) {
  digitalWrite(Trig, HIGH);
  previousMillis = currentMillis;
}

if (currentMillis - previousMillis > 12) {
  digitalWrite(Trig, LOW);
  previousMillis = currentMillis;
}

impulseTime = pulseIn(Echo, HIGH);
distance_sm = impulseTime / 58; // convert to centimeters
distance = distance_sm;

```

---
Tags: arduino-mega, hc-sr04
---


# Question
Title: What is the best way to assign pins to an LED Cube?
I have made an LED cube that is a 3x3x3 design and was wondering if there is way to make a function in the Arduino IDE where each the layers of LEDs can be represented by a list with 1 being on and 0 being off: `{1, 0, 1, 0, 1, 0, 0, 1, 0}` with the first number of the list being the first column, then the second column, etc. and the same for the rows which would be something like `{0, 1, 0}`. Does this make sense? If so, is there an idea for a function that could take these inputs and transform them into digitalWrite outputs? I am using an Arduino Nano for this, with pins 2, 3, 4, 5, 6, 7, 8, 9, and 11 used for the columns with A0, A1, and A2 being the rows of the cube.

# Answer
Well, learning bit manipulations and using three `uint16_t` (as 9 bits won't fit into `uint8_t`) to store state for a whole cube is much better. Then you hust have to setup timer `ISR` and each time it fires just display one "floor". The multiplexing can be done even in loop, but it's usualy flickering as you can't do almost perfect timing as in the `ISR`.

And for example, I was using two `2x4x4` segments to build up `4x4x4` cube and single `MAX7219` to drive it, so I don't have to handle whole multiplexing and so.

My another aproach was using individually addressable LEDs like `WS2812B`, so I needed only one pin to drive it all. Or by using `ARM` and `DMA` transfers, I could drive 8 or 16 lines simultaneously.
> 1 votes

---
Tags: arduino-nano, led
---


# Question
Title: Adafruit ImageReader Library 2.3.5 added several library dependencies
Why has Adafruit ImageReader Library v2.3.5 recently added six dependencies on other libraries for hardware I'm not using?

I used the v2.3.2 of the Adafruit ImageReader Library successfully two months ago. An example sketch worked fine with my ILI9341 3.2" display and its SD card.

Now there is an updated v2.3.5 available but the library manager wants to add six more "dependency" libraries: \- Adafruit ST7735 and ST7789 Library \- Adafruit seeswaw Library \- Adafruit HX8357 Library \- Adafruit SSD1351 library \- Adafruit SSD1331 OLED Driver Library for Arduino \- Adafruit EPD

As far as I know, the ILI9341 uses none of the hardware that corresponds to the six libraries it's trying to drag in. I don't want unneeded dependencies and don't want the code bloat.

If I don't accept the additional libraries, my sketch fails to compile. The error message is "C:\Users\barry\Documents\Arduino\libraries\Adafruit\_ImageReader\_Library\Adafruit\_ImageReader\_EPD.h:18:10: fatal error: Adafruit\_EPD.h: No such file or directory"

However, EPD code is for "e-paper displays" which does not apply to my ILI9341 which is a TFT display. I don't think EPD code should be a real dependency.

Kindly redirect me if there's a better place to ask.

# Answer
> 0 votes
If you don't use the functions of the ImageReader library, which use the additional libraries, your compiled code will not contain code from the additional libraries.

The Adafruit ImageReader library may have functions which use other libraries and the libraries are required for compilation. But at linking the compiled units which are not used by your code and even parts of the compiled units which are not used by your code are not put in the resulting hex or bin file.

---
Tags: library, display
---


# Question
Title: How to detect button presses with a 74HC595 shift register?
Is there a way I can have my arduino uno differentiate between pushbuttons that are wired through a shift register and detect when each are pressed or not? I found this tutorial for the 74HC165 but I'm not sure it's applicable to the 74HC595.

# Answer
> 1 votes
The 74HC595 is a *deserializer* while the 74HC165 is a *serializer*. This means the former consumes a serial datastream and provides all data bits in parallel on dedicated data lines. While the latter consumes parallel data and converts it to a serial datastream.

To scan buttons you want to have parallel input data, where each switch is attached to a single data line. Then you serialize the data to reduce the amount of required Arduino inputs. This method is well explained in the mentioned tutorial.

As the 74HC595 is a deserializer it is not really applicable here. Instead you could use it to drive multiple outputs through a serial interface (see https://www.arduino.cc/en/tutorial/ShiftOut as an example).

---
Tags: arduino-uno, button, shift-register
---


title: stray \342 in program

text:
# Question
Title: stray \342 in program
When I try to compile my code it says "stray '\342' in program

My code:

```
#include <IRremote2.h>
#include <IRremoteInt.h>

#define pinIN 11

uint32_t val;
uint32_t prev;
int fre = 0;

IRrecv remote(pinIN);
decode_results result;

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

  remote.enableIRIn();
  pinMode(2, OUTPUT);
}

void loop() {
  if (remote.decode(&result)) {
    val = result.value;
    if (val == 0xFFFFFFFF) {
      val = prev;
    }
    prev = val;
    detekceKlaves();

    remote.resume();
  }
}

void detekceKlaves() {

  switch (val, HEX) {

    case 0x807FB24D:
      Serial.println("Stisknuto PLAY");
      tone(2, fre);
      break;
    case 0x807FB04F:
      Serial.println("Stisknuto STOP");
      noTone(2);
      break;
    case 0x807F18E7:
      Serial.println("Stisknuto VOL+");
      fre += 10;
      break;
    case 0x807F906F:
      Serial.println("Stisknuto VOL-");
      fre -= 10;
      break;
    case 0x807F9867:
      Serial.println("Stisknuto OFF/ON");
      fre = 0;
      break;
    default:
      Serial.println("Stisknuta jina klavesa");

  }
}

```

Error code:

```
Arduino: 1.8.10 (Windows 10), Board: "Arduino Uno"

irTEST:43:20: error: stray '\342' in program

     case 0x807FB24D:

                    ^

irTEST:43:21: error: stray '\200' in program

     case 0x807FB24D:

                     ^

irTEST:43:22: error: stray '\254' in program

     case 0x807FB24D:

                      ^

irTEST:47:10: error: stray '\342' in program

     case 0x807FB04F:

          ^

irTEST:47:11: error: stray '\200' in program

     case 0x807FB04F:

           ^

irTEST:47:12: error: stray '\255' in program

     case 0x807FB04F:

            ^

irTEST:47:23: error: stray '\342' in program

     case 0x807FB04F:

                       ^

irTEST:47:24: error: stray '\200' in program

     case 0x807FB04F:

                        ^

irTEST:47:25: error: stray '\254' in program

     case 0x807FB04F:

                         ^

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino: In function 'void detekceKlaves()':

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino:43:5: warning: overflow in implicit constant conversion [-Woverflow]

     case 0x807FB24D:

     ^~~~

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino:47:5: warning: overflow in implicit constant conversion [-Woverflow]

     case 0x807FB04F:

     ^~~~

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino:51:5: warning: overflow in implicit constant conversion [-Woverflow]

     case 0x807F18E7:

     ^~~~

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino:55:5: warning: overflow in implicit constant conversion [-Woverflow]

     case 0x807F906F:

     ^~~~

C:\Users\maxim\Documents\Arduino\irTEST\irTEST.ino:59:5: warning: overflow in implicit constant conversion [-Woverflow]

     case 0x807F9867:

     ^~~~

Multiple libraries were found for "IRremote2.h"
 Used: C:\Users\maxim\Documents\Arduino\libraries\IRremote2
exit status 1
stray '\342' in program

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

```

Please help

# Answer
If I copy your provided code in a vim-editor you can see some strange characters. `<202c>`

```
switch (val, HEX) {
  4
  5     case 0x807FB24D<202c>:
  6       Serial.println("Stisknuto PLAY");
  7       tone(2, fre);
  8       break;
  9     case <202d>0x807FB04F<202c>:

```

I've removed them for you:

```
#include <IRremote2.h>
#include <IRremoteInt.h>

#define pinIN 11

uint32_t val;
uint32_t prev;
int fre = 0;

IRrecv remote(pinIN);
decode_results result;

void setup()
{
  Serial.begin(9600);
  remote.enableIRIn();
  pinMode(2, OUTPUT);
}

void loop()
{
  if (remote.decode(&result))
  {
    val = result.value;
    if (val == 0xFFFFFFFF)
    {
      val = prev;
    }
    prev = val;
    detekceKlaves();
    remote.resume();
  }
}

void detekceKlaves()
{
  switch (val, HEX)
  {
    case 0x807FB24D:
      Serial.println("Stisknuto PLAY");
      tone(2, fre);
      break;
    case 0x807FB04F:
      Serial.println("Stisknuto STOP");
      noTone(2);
      break;
    case 0x807F18E7:
      Serial.println("Stisknuto VOL+");
      fre += 10;
      break;
    case 0x807F906F:
      Serial.println("Stisknuto VOL-");
      fre -= 10;
      break;
    case 0x807F9867:
      Serial.println("Stisknuto OFF/ON");
      fre = 0;
      break;
    default:
      Serial.println("Stisknuta jina klavesa");
  }
}

```
> 1 votes

---
Tags: arduino-uno
---


title: Arduino problem

text:
# Question
Title: Arduino problem
I'am making a temperature monitor using an IC2 Interface and a dht11 sensor connected to an arduino uno, it works great when it´s plugged to the computer but whenever i plug it to a 9v battery the humidity goes to "0" and the temperature to "2", it only works when i resend the code through the ide to the arduino.

What could be the problem?

Code :

```
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
DHT dht;

void setup()
{
  lcd.begin(16,2);
  lcd.clear();
  dht.setup(7); // Pino 7

}

void loop(){

  float humidade = dht.getHumidity();
  float temperatura = dht.getTemperature();

  lcd.setCursor(0,0);
  lcd.print("Humidade: ");
  lcd.print(humidade);
  lcd.print("%");

  lcd.setCursor(0,1);
  lcd.print("Temp: ");
  lcd.print(temperatura);
  lcd.print("C");

  delay(1000);

}

```

# Answer
Fixed it by clicking the red button on the arduino uno.
> 0 votes

# Answer
The 9v sort of "cube shaped" batteries have a notoriously limited current output, resulting in falling voltage as the current demand rises. The Arduino's voltage regulator is not very effecient either, plus the battery gives only 2v of "headroom" over the minimum Vin voltage of 7v. Your system is probably starving. Try a different source.
> 1 votes

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


# Question
Title: Use of progmem in ESP8266 vs AVR and also how to handle large dynamic strings
This is a somewhat tricky question dealing with implementation and best-practices of the ESP8266. I'd ideally hope that it's answered by people with in-depth knowledge on the problem.

As you are hopefully aware, the Arduino (AVR) platform requires the use of the PROGMEM or F() instructions to avoid copying all strings to RAM. The ESP8266 platform also provides a PROGMEM instruction, but is memory-mapped.

I thus have several questions about what the PROGMEM instruction actually does on the ESP8266.

For the next few questions, until otherwise marked, I am referring to character-array-style C strings, not the Arduino String type.

1. Storage of constant strings: If I were to declare a string (global, for now) on the ESP8266, would it be read from flash only when it's accessed, or will it always take up RAM (like it would on the AVR. Assume that in this case I do NOT declare it as PROGMEM; I wish to find out what the default behavior is on the ESP8266)?
2. Local Constant Strings: What happens with strings that are used inside a function? I am fairly sure that they ALSO exist in RAM, at least in AVR. Does the ESP8266 do this too, or does it (potentially) store it in flash until it is read (it is fine if it ends up inside a cache somewhere, as long as it can be evicted if needed)?
3. Use of String(F("mystring")): If I wrap a PROGMEM string in this manner, does this truly convert the string into a RAM-based string only when this line is reached, or does this for some reason initialize the String() early (and consume the RAM anyway)? Do the systems differ in this behavior?
4. If I define several instances of the above (as in, the identical wrapped string shown above appears several times, perhaps in different functions), do all of them point to the SAME F() instance (since they are identical) or does it get duplicated since it's part of code rather than a referenced variable? On ESP8266? On AVR?
5. On the ESP8266, I discovered that the server.on() function for the built-in webserver read F()'d constant strings just fine, but failed to work once the file grew beyond the size of the RAM. It was clearly *stored* correctly, but it could not be *read*. I thus conjecture that the method was making a local copy to RAM, even if the file was stored in Flash. There was also a on\_P version that worked after that point (I believe I used PSTR rather than F at this point as well, since -- correct me if I am wrong -- the two are not compatible). Is this the real point of PROGMEM on ESP8266? That the data **is** only stored in Flash, but it also tells the function reading it to make as few copies as possible or chunk it?

---

I am also curious what happens with large strings that *aren't* constant. The web server can return data that was passed via querystring, for instance, which in my case can be quite large. If I copy that data to a string (and then into a function), does it pass the heap pointer directly, or does each String make a new copy? I am concerned about fragmentation or other fun ways of running out of RAM even if one copy should in theory fit.

Does doing something like `bool myFunction(String &str){...}` help? Some sort of way to actually ensure that it's the same string, rather than copying (and can I do `String &myStr=server.arg(...)` -- is a return value different from an assignment)? It's confusing for me, since strings are clearly passed by value, despite being a complex datatype with dynamic memory somewhere in there. So, did they override the assignment operator (and/or the one that handles reference passing, since I think there's more than one) to duplicate the string as pass-by-value of a basic type would normally do, or do they share pointers (and thus memory) as a *class* passed-by-value would normally do?

# Answer
On the ESP8266 flash is a very special case. Because the ESP8266 itself does not have any flash, but instead uses an external SPI-connected flash chip, accessing it is not an easy or technically obvious operation.

Reading from the flash chip is slow. Very very slow (by comparison to reading RAM). Because of this where possible certain things are copied into RAM. Also, there are different sections of RAM that are dedicated to different purposes.

* `dram0` \- This is your "Data" RAM. It's where your variables and such are stored (80kB total).
* `iram1` \- Instruction RAM. It's here that interrupt routines need to be stored for rapid execution (32kB).
* `icache` \- Instruction cache. 16kB of data that is cached when reading from the flash chip. Executed code usually gets copied here.

Normally when you execute code the block of code that the instructions you are executing are copied from flash into the `icache` memory block and then executed. This is reasonably fast (reasonably in that there may be brief delays while copying the data from flash, but fast when actually executing. I don't know how efficient the cache is, whether it's split into different blocks that are loaded in the background by the memory controller as needed, but it seems to be a pretty efficient system that is used in practice).

Because of this disassociation of the CPU and flash string constants, unless specified otherwise, will be copied into `dram0` during startup. This makes it very fast and simple to get at the data. Anything that you don't specify as `PROGMEM` will get copied into `dram0`. Note that you don't get all 80kB of the RAM to play with since the SDK uses a portion of it. You only get about 50kB at most (station mode - softap mode will use more).

Now... what *does* `PROGMEM` do on the ESP8266 then? Well, it adds an *attribute* to the definition that tells the linker to place the data in a specific section in flash (`.irom.text.<filename>.<line>.<number>`). This prevents it being copied into `dram0` at startup.

So how do you get at it? That's where the `*_P` variants of the string functions (and certain overloaded functions in the Arduino core) come into play.

The whole of the flash chip is mapped (or can be, depending on register settings) into the ESP8266's memory map (address 0x40200000). Which means that it's possible to get directly at the data. However since this access doesn't go through the `icache` RAM block it's slow. Very very slow. About 12x slower by some accounts. Also because data can be in different locations within the chip the addresses of your string data can't be directly hard coded. There has to be some form of "it's over there" redirection when reading the data (for example if you use OTA updates you get two distinct blocks of flash where your code can be stored - the currently executing code and the previously executing version). The `*_P` variants of the string functions take that into account and look up where in flash the current code is located before reading from it.

So to summarise: Not using `PROGMEM` gives you fast access to your string data at the cost of RAM, and limits the size of the data you can use. Using `PROGMEM` removes the size restriction, doesn't use RAM, but is considerably slower.

To specifically answer your questions:

1. The string data gets copied to RAM at startup.
2. The string data gets copied to RAM at startup.
3. The string data gets loaded from flash (using `*_P` variants of functions) when the `String` object is constructed (RAM is allocated on the heap at that moment in time). The RAM is freed when the `String` object is destroyed (goes out of scope).
4. The compiler has recently had an update that will deduplicate constant PROGMEM strings.
5. As mentioned above `*_P` copies directly from flash and is slow, but has no size limitation.
> 2 votes

---
Tags: esp8266, arduino-ide, avr, progmem
---


# Question
Title: RF24 library commands, channel, and address
I'm trying to use the RF24 library for wireless communication. However, it appeared that this library does not have "help" option. There was a keywords file but it did not explain what it does. I found couple of examples online, and in the library, but id did not explain things quite in detail.

Could you explain to me how those command works, and weather there's any help file for the library?

Especially, I have a question about the channel and address used in the library.

**A.** Does address take character or number as input? The official example in the library used

```
byte addresses[][6] = {"1Node","2Node"};

```

But I also say some example use

```
byte addresses[][6] = {"00001","00002"};

```

The byte command was suppose to be a 8-bit unsigned number, from 0 to 255, but why they used string " " as input?

I found a sentence in RF24.h file: Addresses are assigned via a byte array, default is 5 byte address lengths. But why they wrote *byte addresses\[\]\[6\]* instead of *byte addresses\[\]\[5\]*?

**B.** From some other video I learned that RF24 have channel and address for communication, where channel can take value from 0 to 125; pin/port take value from 0,1-5; and the address.

```
setChannel  KEYWORD2

```

The pin was explained in RF24.h. However,

1. Can one open multiple channel at once?
2. If one use the same addresses in multiple channel at once, can the address being distinguished, or were they treated as the same address?
3. Is channel-pin/port(while writing)-address a tree structure?

**C.** Can one open up more pin/port in transmitting and writing?

```
  openWritingPipe   KEYWORD2
  openReadingPipe   KEYWORD2

```

# Answer
> A. Does address take character or number as input?

The address is 5 bytes. In this library it is provided as an array. In C a string is merely an array of bytes. So it is possible to represent an array of bytes as a simple string. Internally the two representations:

```
byte address[] = "123ab";

```

and

```
byte address[] = { '1', '2', '3', 'a', 'b' };

```

and even:

```
byte address[] = { 0x49, 0x50, 0x51, 0x97, 0x98 };

```

are all identical, except that the first one adds an extra `0x00` to the end of it to mark the end of the string (which the library completely ignores).

> B. From some other video I learned that RF24 have channel and address for communication, where channel can take value from 0 to 125; pin/port take value from 0,1-5; and the address.

It's helpful here that you have some understanding of basic radio communication terminology.

When you say that a device works at X frequency you are generally only referring to the "frequency band" that the device operates within (2.4GHz in this case). The device doesn't work *at* 2.4GHz - only "in the 2.4GHz band". That frequency band is then divided up into channels. Each channel is a specific frequency. Just like your television has channels you select one specific channel (and thus frequency) to tune into and communicate on.

Channel numbers are just used because it's far far easier to remember "channel 21" instead of 471.25MHz, for example.

For two devices to be able to communicate they both need to be tuned to the same frequency, and hence the same channel.

The "address" is more like the address your computer has on the network. Within the channel frequency you can have multiple devices communicating. The address identifies exactly which of the devices you want to send data to or are receiving data from.

> C. Can one open up more pin/port in transmitting and writing?

The nRF24L01 internally uses *pipes* as a method of separating data from different devices into distinct feeds that you can read from. It is merely for convenience. You can open up to 6 pipes at once, each one receiving from a different address. All pipes are in the same channel though since you can only tune to one channel at a time.

By the way - the `keywords.txt` file exists solely for the IDE to do highlighting of certain words. It's not meant for a human to read when working out how to use a library.
> 3 votes

---
Tags: nrf24l01+, wireless, bytes
---


title: Using serial communication in .c-files

text:
# Question
Title: Using serial communication in .c-files
I am currently trying to connect my Arduino Uno to my computer and let them communicate via UART. I started using a project from Github (here), which I'm trying to modify to get the next step via UART. Because of that, I'm not able to switch programming languages and also need to override the bootloader.

However, I can't get the serial connection to work.

```
#include "Joystick.h"
#include <avr/io.h>
#include <util/delay.h>
#include <Arduino.h>

```

These are the `#include` statements at the top, but `<Arduino.h>` can't be found...

If I remove these statements, `Serial` can't be found (from the `main`-Method: `Serial.begin(9600);`)

It's my first time to program with C, did I overlook a stupid mistake? Thanks for any help...

# Answer
I would consider using HoodLoader2 instead of that LUFA project. If you can't do that, you can compile parts of the Arduino Core together with the LUFA project.

The main steps:

* Add the necessary Arduino source files to the `SRC` variable in the Makefile.
* Add the Arduino core folder to the include path by appending to the `CC_FLAGS` and `CXX_FLAGS` variables.
* Move the main function to a new `main.cpp` file and add it to the Makefile `SRC` as well.
* Include the `Joystick.h` file in your main file in an `extern "C"` block.
* Include the `HardwareSerial.h` file in your main file as well.

My files after these changes:

**Makefile**

```
# Set the MCU accordingly to your device (e.g. at90usb1286 for a Teensy 2.0++, or atmega16u2 for an Arduino UNO R3)
MCU          = atmega16u2
ARCH         = AVR8
F_CPU        = 16000000
F_USB        = $(F_CPU)
OPTIMIZATION = s
TARGET       = Joystick
SRC          = $(TARGET).c Descriptors.c main.cpp $(LUFA_SRC_USB)
LUFA_PATH    = ./lufa/LUFA
CC_FLAGS     = -DUSE_LUFA_CONFIG_HEADER -IConfig/
LD_FLAGS     =

ARDUINO_PATH = ${HOME}/.arduino15/packages/arduino/hardware/avr/1.8.1/cores/arduino
SRC         += $(ARDUINO_PATH)/HardwareSerial.cpp
SRC         += $(ARDUINO_PATH)/HardwareSerial1.cpp
SRC         += $(ARDUINO_PATH)/Print.cpp
CXX_FLAGS   += -I$(ARDUINO_PATH) -I./HoodLoader2/avr/variants/HoodLoader2
CC_FLAGS    += -I$(ARDUINO_PATH) -I./HoodLoader2/avr/variants/HoodLoader2

...

```

**main.cpp**

```
extern "C" {
#include "Joystick.h"
}

#include <HardwareSerial.h>

// Main entry point.
int main(void) {
    // We'll start by performing hardware and peripheral setup.
    SetupHardware();
    // We'll then enable global interrupts for our use.
    GlobalInterruptEnable();
    // Initialize the UART
    Serial1.begin(115200);
    Serial1.println(F("Hello, world"));
    // Once that's done, we'll enter an infinite loop.
    for (;;)
    {
        // We need to run our task to process and deliver data for our IN and OUT endpoints.
        HID_Task();
        // We also need to run the main USB management task.
        USB_USBTask();
    }
}

```

**Joystick.c**
Deleted the `main` function.

To get it to compile after these changes:

```
# (inside of the snowball-thrower folder)
git submodule add https://github.com/NicoHood/HoodLoader2.git HoodLoader2
make

```

This compiles without problems for me, but I have no idea if it actually works.

**Edit**:

You'll notice that the program uses more RAM than the ATmeg16U2 has available. You could solve this by moving the `step` array to `PROGMEM`, or by shrinking the Serial buffers.

```
avr-size --mcu=atmega16u2 --format=avr Joystick.elf
AVR Memory Usage
----------------
Device: atmega16u2

Program:    5076 bytes (31.0% Full)
(.text + .data + .bootloader)

Data:        527 bytes (102.9% Full)
(.data + .bss + .noinit)

 [INFO]    : Finished building project "Joystick".

```
> 0 votes

---
Tags: arduino-uno, serial, programming
---


# Question
Title: L298N Motor Driver - Code issuing "expected primary-expression before '=' token"
Programming Questions / L298N Driver - Code Issuing - " expected primary-expression before '=' token" Today at 07:20 pm Hello Arduino Community,

*Code is shown at bottom - please read below*

I've been working on a little project that uses the L298N Dual Motor Driver to run a single motor.

Using this link I set up my project (disregard Using the L298N with PIC Section) :

https://www.teachmemicro.com/use-l298n-motor-driver/.

1. I connected my wires and checked them and their connections for any problems.
2. I am using 1 motor instead of two
3. I am using two 'C' Duracell Alkaline Batteries, connected them together in a series circuit. I've tested the batteries and they run my Small Round Electric Motor with 12000 RPM + 3 to 6V DC perfectly when I don't connect the battery and motor to the L298N Driver.
4. The two, 'C' batteries are 1.5 volts each (connecting them together in series give me 3 volts)
5. I am connecting my arduino uno to a newly purchase laptop - I've compiled codes from this computer that have worked fine.

I copied and pasted the code from the website at the link at the top. I checked device manager and chose the correct port with the correct board, so I am starting to believe there is something wrong with the code on the website.

Once I compile the program, errors pop up stating, "expected primary-expression before '=' token" for every line of code that has a #defined variable (mentioned on the top lines of the program).

It would be helpful to please comment your thoughts and solutions for this issue.

Please see link at the top for code.

Thank you.

# Answer
> 0 votes
Definitions via `#define` don't use equal signs. The following is wrong

```
#define EN = 1

```

Instead it should be

```
#define EN 1

```

---
Tags: arduino-uno, programming, l298n
---


title: Press On Hold Off Power Switch

text:
# Question
Title: Press On Hold Off Power Switch
Hi everyone I am hoping someone here can help me. I am trying to make an arduino turn my project on and off.Using a relay. I am looking for it to act like a computer power button. A short press to turn on and them stay on and a long press (say 5 sec) to turn off and then stay off till button is pressed again. I would like it so that the project can not be accidentally turned off Can anyone please help. Thanks

# Answer
Here is a test sketch that I wrote for a different question. The other question's requirement was for a short press (minimum 100ms) to turn on an LED, and a long press (1 second) would turn it off. With a slight modification of this sketch, it may work for you. You will need to install the `Bounce2` library.

```
// Press and hold button for 100 ms to turn LED ON.
// Press and hold button for 1000 ms to turn LED OFF.
#include <Bounce2.h>

byte buttonState = 0;
const byte ledPin = 3;
const byte buttonPin = 2;
const unsigned long debouncerInterval = 50;
unsigned long buttonPressedTime = 0;
unsigned long currentMillis = 0;

Bounce debouncer = Bounce();

void setup(){
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
  debouncer.attach(buttonPin, INPUT_PULLUP);
  debouncer.interval(debouncerInterval);
}

void loop(){

  // Get the current time.
  currentMillis = millis();

  // Check if button was pressed or released.
  if(debouncer.update()){

    // Pressed.
    if(debouncer.read() == 0){
      if(buttonState == 0){
        buttonState = 1;
        buttonPressedTime = currentMillis;
      }
    }

    // Released.
    else{
      buttonState = 0;
    }
  }

  // Turn the LED ON or OFF.
  if(buttonState == 1){
    if(currentMillis - buttonPressedTime >= 1000){
      digitalWrite(ledPin, LOW);
      buttonState = 0;
    }
    else if(currentMillis - buttonPressedTime >= 100){
      digitalWrite(ledPin, HIGH);
    }
  }
}

```
> 0 votes

# Answer
To clarify the problem, do you want to control ON OFF using Arduino? It is very simple. Please read this simple tutorial, and modify it according to your needs.
> 0 votes

---
Tags: power, button
---


# Question
Title: Is there some hardware that can be used to upload sketch source code via USB flash disk (Automatically By plugging it in)
Well am asking this basically to know if it is possible to create a bootable flash drive that automatically uploads any source code onto the arduino just like creating a bootable flash drive when installing windows operating system on a computer. I will be happy to get some cool responses that would be helpful thanks.

# Answer
There is a solution with SD card and SD bootloader. You put a bin file on SD card, insert it into the SD adapter and power up the Arduino. The bootloader loads the bin file to flash memory.

I use 'avr\_boot' SD bootloader by Zevero. It reads a file named firmware.bin from SD card if present and loads it into flash.

To generate a bin file for Arduino AVR boards add to platform.txt

```
recipe.objcopy.bin.pattern="{compiler.path}{compiler.elf2hex.cmd}" -O binary {compiler.elf2hex.extra_flags} "{build.path}/{build.project_name}.elf" "{build.path}/{build.project_name}.bin"

```

I use this with the ArduinoOTA library which uploads the bin file from IDE to the SD card over network and then resets the MCU for the bootloader to apply the bin.

btw: the ArduinoOTA library can use the upper half of the flash memory too to store the uploaded bin and then activate a modified Optiboot to copy the bin to run location and reset the MCU.

UPDATE 2022: new advanced example for my ArduinoOTA library: load hex from SD card
> 3 votes

# Answer
There is no specific piece of hardware that does what you ask.

There are various options though:

1. Write a new bootloader that uses the USB Host Shield to load data from a USB MSD device then flash it to the internal flash of the MCU (hard to do if you don't know low-level programming)
2. Use an embedded Linux computer (Raspberry Pi, etc) to run `avrdude` and flash your Arduino like it's a connected to a computer
3. Use an Arduino that has a Linux portion to it (such as the venerable Arduino Yun) or a shield that provides a similar function (Dragino Yun Shield) to flash the AVR chip from Linux
4. Don't use an Arduino at all, but use an embedded Linux computer for everything.
> 1 votes

---
Tags: arduino-mega, sd-card, bootloader, hardware
---


# Question
Title: Unable to find arduino on device manager
I have just got a new Arduino robot for Christmas and I have plugged my robot into my computer and I have read the instructions from the manual that the robot was provided with and told me to go to the device manager in the control panel and look under unknown devices, unfortunately I was unable to find it. However I looked under ports and I found that there were 3 ports, I eventually found out that if I took the Arduino plug in and out of my PC that port COM5 was the Arduino, the problem I am having now is to know how to get this port to recognise my Arduino

one error that always comes up when trying to upload the code onto COM5 is this:

```
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xa1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xa1

```

This is what the arduino looks like

Link for where I brought the arduino kit from: https://www.amazon.co.uk/ELEGOO-Tracking-Ultrasonic-Intelligent-Educational/dp/B01M6YHRJ4/ref=sr\_1\_1\_sspa?keywords=elegoo+robot&qid=1577982862&sr=8-1-spons&psc=1&spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUEyVjVXTk9VMDlUTTg1JmVuY3J5cHRlZElkPUEwMjc4NjYwOEVGNEoxM1Y0QzIwJmVuY3J5cHRlZEFkSWQ9QTA4OTA1NzAzTTNBVFJMV09aVjJRJndpZGdldE5hbWU9c3BfYXRmJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==

This is what shows up on the arduino IDE when I select COM5 (which should be my arduino)

# Answer
> 1 votes
It seems your computer recognize the serial port of the Arduino device, but doesn't know how to 'talk to it'.

In most USB to TTL devices (that are included in Arduino and ESP8266 boards) you need to install their driver (like CH341 driver) BEFORE you plug in your device.

Please try to find/identify the 'USB to Serial' chip you have on the board, and install its drivers.

Good Luck!

---
Tags: arduino-uno, windows
---


# Question
Title: Arduino stops sending/receiving data over Serialport after random time
I got a C# WPF application wich communcates with my arduino uno over serial port. Everything works fine for 3 to 20 seconds then i can not send or receive anything from/to the arduino.

What im trying to archieve: Connected a arduino uno to an optical sensor of a mouse to read from its registers, now i want to process the data on my pc.

I tried using another arduino uno and also some other mouse optical sensor, wich did not change anything. Opening and closing the serialport after each communication did not work for me. I have seen a few questions here on stack exchange, i looked through everyone but they could not help me. `Serial.flush()` seems to be not working, or its some kind of overflow i cant figure out.

I would really appreciate it if someone could explain me what the root of this problem is.

For completeness, here is my C# code:

```
 public class SerialCommunication
    {
        public SerialPort serialPort = new SerialPort();

        public SerialCommunication()
        {
            string[] ports = SerialPort.GetPortNames();
            if (ports.Count() == 1)
            {
                MessageBox.Show("No serialport is available");
                return;
            }
            serialPort.PortName = ports[1];
            serialPort.BaudRate = 115200;
            serialPort.Parity = Parity.None;
            serialPort.DataBits = 8;
            serialPort.Handshake = Handshake.None;
            serialPort.StopBits = StopBits.One;
            serialPort.NewLine = "\r\n";
            serialPort.WriteTimeout = 2000;
            serialPort.ReadTimeout = -1;

            serialPort.Open();
        }
    }

public partial class MainWindow : Window
    {
        public static readonly object _lock = new object();

        private SerialCommunication serialCommunication = new SerialCommunication();

        public MainWindow()
        {
            InitializeComponent();
            GetWindow(this).KeyDown += HandelKeyDown;

            serialCommunication.serialPort.DataReceived += (sender, args) =>
            {
                string bufferstring = ((SerialPort)sender).ReadLine();
                OnMessageReceived(bufferstring);
                //serialCommunication.serialPort.DiscardOutBuffer();
                //serialCommunication.serialPort.DiscardInBuffer();
                //Thread.Sleep(3);
                //byte[] buffer = new byte[15];
                //((SerialPort)sender).Read(buffer, 0, buffer.Length);
                //string bufferstring = Encoding.UTF8.GetString(buffer);
            };
            serialCommunication.serialPort.WriteLine("OK");
        }

        private void OnMessageReceived(string message)
        {
            if (message.Length != 15 || message.Contains('O') || message.Contains('K') || message.Contains('\n') || message.Contains('\r'))
            {
                serialCommunication.serialPort.DiscardInBuffer();
                serialCommunication.serialPort.DiscardOutBuffer();
                serialCommunication.serialPort.WriteLine("OK");
                return;
            }

            //Format: "y: 0x%02X,x: 0x%02X"
            string x = message.Substring(3, 4);
            string y = message.Substring(11, 4);

            int offsetX = (Convert.ToInt32(x, 16) - 128);
            int offsetY = (Convert.ToInt32(y, 16) - 128);

            // the next three lines only visualize the received data but do not change it
            MoveX(offsetX / 50);
            MoveY(offsetY / 50);
            ShowMessage(message);
            Thread.Sleep(2);
            serialCommunication.serialPort.WriteLine("OK");
        }
}

```

Foto of how the application and data it receives look like:

Here is my arduino code:

```
#include <Arduino.h>

// 5v
#define POWER 13
// Serial I/O
#define SDIO 11
// Serial clock
#define SCK 12

// Registers
#define DELTAY 0x02
#define DELTAX 0x03

#define serialInputBufferSize 16
char dataBuffer[serialInputBufferSize];
unsigned short inputBufferLength = 0;

bool sendPosition = true;

char tmp[16];

void InitMouse()
{
  digitalWrite(SCK, HIGH);
  delayMicroseconds(5);
  digitalWrite(SCK, LOW);
  delayMicroseconds(1);
  digitalWrite(SCK, HIGH);

  // Wait for the serial transaction timer to time out:
  delay(1000);
}

byte readRegister(byte addr)
{
  byte r = 0;

  // Set the dataline to output
  pinMode(SDIO, OUTPUT);
  for (int i = 7; i >= 0; i--)
  {
    digitalWrite(SCK, LOW);
    digitalWrite(SDIO, addr & (1 << i));
    digitalWrite(SCK, HIGH);
  }

  // Switch the dataline from output to input
  pinMode(SDIO, INPUT);
  // The datasheet mentions to wait at least 100 µsec
  // when switching from write to read operations.
  // This is needed for the chip to prepare the data
  delayMicroseconds(110);

  // Clock trough the register and read its data
  for (int i = 7; i >= 0; i--)
  {
    digitalWrite(SCK, LOW);
    digitalWrite(SCK, HIGH);
    r |= (digitalRead(SDIO) << i);
  }

  // Delay at the end guarantees >100 µsec before next transaction
  delayMicroseconds(110);

  return r;
}

byte y = 0;
byte x = 0;

void WaitForMovementThenSendPositionOffset()
{
  x = 0;
  y = 0;

  while (((y == 0 && x == 0) || x == NULL || y == NULL) && sendPosition)
  {
    delay(1); // kann eigentlich weg
    y = readRegister(DELTAY);
    x = readRegister(DELTAX);
  }

  if (sprintf(tmp, "y: 0x%02X,x: 0x%02X", y, x) > 0)
  {
    tmp[16] = 0;
    if (!Serial.println(tmp))
    {
      // Serial.end();
      // Serial.begin(9600);
      // Serial.begin(115200);
      Serial.flush();
    }

    sendPosition = false;
  }
}

void serialEvent()
{
  sendPosition = false;

  // Read serial data into the buffer
  while (Serial.available())
  {
    dataBuffer[inputBufferLength++] = Serial.read();
  }

  Serial.flush();

  if (strstr(dataBuffer, "OK"))
  {
    sendPosition = true;
    WaitForMovementThenSendPositionOffset();
  }
}

void setup()
{
  pinMode(SCK, OUTPUT);
  pinMode(SDIO, INPUT);
  pinMode(POWER, OUTPUT);

  digitalWrite(POWER, HIGH);

  Serial.setTimeout(1000);
  // Serial.begin(9600);
  Serial.begin(115200);

  InitMouse();
}

void loop()
{
}

```

# Answer
The problem was in the serialEvent() method. I did not rest the bufferindex where i red the received message so it allways stayed there until the arduino ran out of memory and also i did not gave the arduino enough time to receive the message so i added `delay(1)` there.

Here is my updated code:

```
void serialEvent()
{
  inputBufferLength = 0;
  sendPosition = false;
  delay(1);
  // Read serial data into the buffer
  while (Serial.available())
  {
    if (inputBufferLength < serialInputBufferSize)
    {
      dataBuffer[inputBufferLength++] = Serial.read();
    }
    else
    {
      Serial.read();
    }
  }

  Serial.flush();

  if (strstr(dataBuffer, "OK"))
  {
    sendPosition = true;
    WaitForMovementThenSendPositionOffset();
  }
}

```
> 0 votes

# Answer
Every time you receives data, it tries to read a full line (SerialPort.ReadLine()). If there's not a full line available, it will block the current thread until there is or until it times out.

These calls will stack up and eventually cause the application to fail.
> 0 votes

---
Tags: arduino-uno, serial, c, c#
---


# Question
Title: Need to "Extend" a Arduino Digital Signal
Here's the scenario: We have 1 arduino uno accepting DMX and converting that to a signal that is being sent out digitally (PIN 3). The digital signal then goes to several IR LED senders that control 3,200 IR, color-changing candles. I've recently added some more senders, and now some of the senders are not working (even some that were working before). I assume this is because the digital signal has been weakened due to me splitting it so many times.

I'd like to add another arduino to control half of the IR senders. I obviously already have a cable running to every device, but I know of a perfect place to "interject" the new arduino. Is this possible? Can the second arduino essentially "repeat" or decode and re-encode the digital signal? If so, what pins am I looking at and will I need any special code?

Thanks for the help!

# Answer
> 1 votes
The scenario you are referring to - connecting one output to many devices - is called the *fan-out*. Yes, a GPIO pin has a limited amount of *drive* which limits the number of devices in the *fan-out*.

There are two problems that are caused by excess fan-out:

1. Excess current draw from resistive loads
2. Excess capacitance from logic loads

The former is evident when you have too many LEDs connected directly to an output (with resistors, of course). The combined current draw of the LEDs exceeds the current the IO pin can provide and either damage the pin or the LEDs go dimmer than would be desired.

The latter is more evident when working with communication signals. The excess capacitance imposed by each gate attached to the output causes a low-pass filter effect which can filter out high-frequency signals or corrupt the waveforms by removing higher frequency components and "curving off" the nice clean square waves.

In normal logic systems it's common to use *line drivers* or *buffers* to allow the connection of more devices to a single signal. Devices such as the 74HC244, which is 8 buffers in one chip, are commonly employed. You can connect the inputs of all 8 buffers to one Arduino output, and each output from the buffer mirrors the input exactly and can connect to more devices than an Arduino can (each output has an extra 10mA steady-state drive capacity than the Arduino).

And yes, you can even connect the output of one buffer to the inputs of other buffers to give even more capacity.

simulate this circuit – Schematic created using CircuitLab

# Answer
> 0 votes
The buffer is a good idea, each pin on an arduino can deliver 20ma, but then the chip can over heat, and you can't drive every output to 20ma, so the buffer chip is the way to go. Just consider the speed of the buffer when you are sending data. There are many chips that can do it, and many that might not be able to do it. So look at the speed of the chip from input to output. Then again, the arduino may not be able to keep up. So consider a PIC, some PIC's are really fast compared to an arduino.

---
Tags: digital, network
---


# Question
Title: How can I upload a sketch remotely from a distant location onto an arduino that is power by a battery
Of course after developing a success full embedded product the next step would be making upgrades to compete favorably with new products in the market. Well making upgrades would require making adjustments in the sketch and Uploading it onto already made prototypes to cub the costs involved in by the hardware of a remotely located prototype. How can one upload a sketch from his location on to the prototype without going there psychically to upload through the port?

# Answer
> 1 votes
Battery powered devices need a system where the device checks over Internet connection (WiFi, mobile) if a new firmware bin file is available on a specific location on a server. If the bin file is available the device can download it and apply.

One option how to apply the new bin is to use SD card and SD bootloader (Zevero avr\_boot) The sketch saves the downloaded file on SD card and resets the MCU. The SD bootloader then loads the binary from the SD card to flash.

Other option if enough free flash memory is available is to use the InternalStorage object from ArduinoOTA library. It uses the upper half of the flash memory to store the uploaded bin and then activates a modified Optiboot to copy the bin to run location and reset the MCU.

# Answer
> 0 votes
First you have to establish communication between Arduino and your computer. This communication could be wire (ex. LAN) or wireless.

Like Juraj said, you could use ArduinoOTA with an additional WiFi or Ethernet module on your Arduino, as long as arduino is connected to the network and you know its address. I haven't tried it yet, so I don't know its reliability. Even so, it helps your problem

---
Tags: arduino-mega, sketch, hardware, prototype
---


# Question
Title: How to create an array from serial.read?
I'm working on a audio-reactive lightinstallation with 16 LED lights. In Max MSP I analyse my audio and split the frequencies in 16 'parts'. I store these parts in a message of 16 ints, either 1 or 0 (on of off). Every time a new frequency is detected the message updates and puts out a new int from 16 numbers (for exampe 1000100100110101).

I receive this number in my serial monitor of my Arduino Uno. I want to put this 'incomingValues' in an array so I can check if a number/frequency is 0 or 1. When it's 1 I can turn on my relay/ light. The 'incomingValues' is changing quite quickly but that shouldn't be a problem right?

I tried multiple things to create an array and update this every time a new serial message is coming in but I'm not used to work with Arduino so I could need some help.

Thanks! :)

Here is my code:

```
int counter;
int incomingValues = 0;
int lights[16];

void setup() {
  Serial.begin(9600);
  counter = 0;
  pinMode(13, OUTPUT);
}

void loop() {

  boolean newValue = false;

  while (Serial.available() > 0) {

    incomingValues = Serial.read();
    Serial.print(incomingValues);
    counter = counter + 1;

    newValue = true;
  }

  if (newValue) {
//    delay(50);
//    lights[counter] = incomingValues;
//
//
//    Serial.print(lights[0]);
//
//    for (int i = 0 ; i < 16 ; i ++) {
//      Serial.print(lights[i]);
//    }
//    Serial.println("");
//    newValue = false;
  }

  if (counter > 15) {
    counter = 0;
    Serial.print("\n");
  }

  if (incomingValues == 1) {
    digitalWrite(13, HIGH);
  } else if (incomingValues == 0) {
    digitalWrite(13, LOW);
  }
}

```

# Answer
If you are able to send the message as 16 chars, followed by a newline, then here is a test sketch that might work for you. Use the Serial Monitor to send the `1000100100110101` data. Please ensure you have the Serial Monitor set to send a `Newline Only`.

```
// Valid input data from serial is 16 chars followed by a newline.
// 1000100100110101
const byte bufferSize = 17;
char inputBuffer[bufferSize + 1];

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

void loop(){

  if(Serial.available() > 0){
    byte bytesRead = Serial.readBytesUntil('\n', inputBuffer, bufferSize);
    if(bytesRead == 16){
      for(byte i = 0; i < 16; i++){
        if(inputBuffer[i] == '1'){
          Serial.print("on ");
        }
        else{
          Serial.print("off ");
        }
      }
      Serial.println();
    }
    else{
      Serial.println("Invalid data length.");
    }
  }
}

```
> 0 votes

# Answer
Thanks @VE7JRO, it does the job :)

```
const byte bufferSize = 16;
char inputBuffer[bufferSize + 1];
int myDelay = 20;

void setup(){
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);

}

void loop(){

  if(Serial.available() > 0){
    byte bytesRead = Serial.readBytesUntil('\n', inputBuffer, bufferSize);
    if(bytesRead == 16){
      for(byte i = 0; i < 16; i++){
        if(inputBuffer[0] == 1){
          digitalWrite(13, HIGH);
          delay(myDelay);
        }
        else{
          digitalWrite(13, LOW);
        }
        if(inputBuffer[1] == 1){
          digitalWrite(12, HIGH);
          delay(myDelay);
        }
        else{
          digitalWrite(12, LOW);
        }
      }
      Serial.println();
    }
    else{
      Serial.println("Invalid data length.");
    }
  }
}

```
> 0 votes

---
Tags: serial, array
---


# Question
Title: When using an Arduino as an ISP, is the capacitor required or not?
Looking at Arduino as ISP and Arduino Bootloaders, it is stated

> The 10 µF electrolytic capacitor connected to RESET and GND of the programming board is needed only for the boards that have an interface between the microcontroller and the computer's USB, like Mega, Uno, Mini, Nano. Boards like Leonardo, Esplora and Micro, with the USB directly managed by the microcontroller, don't need the capacitor.

Some of the Fritzing diagrams show the electrolytic capacitor connected between the `RESET` and `GND` pins:

But it is not shown in *all* of the images on that page.

Nor it is shown in this image from Nick Gammon's Atmega bootloader programmer (see original image):

So, is the capacitor *really* needed, when using a Mega or Uno as an ISP, and if so, why exactly?

---

I was wondering after having written this answer to the question How to install new ATMEGA firmware via the ISP pins? for a 3D Printer control board.

# Answer
The purpose of the capacitor is to prevent the "master" Arduino (the Mega in the first image above) from resetting when the serial port is opened. If that board resets, then programming fails.

There are many ways of preventing that reset - some more permanent than others - but the capacitor trick is one of the simplest.

So yes, you do need the capacitor unless you have made other modifications to prevent the reset.

I think the purpose of the second image is more to illustrate how to use the ICSP headers and where to connect the target's reset pin on the master. It is to be seen as complementary to the first image.

---

Edit:

It seems what you are using is *not* Arduino As ISP, but instead something written by Nick Gammon that acts as a standalone programmer. The rules for Arduino As ISP do not apply in this case. Since you are not programming via the master Arduino (as you would with Arduino As ISP) there is no need to prevent the master from resetting.

---

Here's a little history about the auto-reset system:

Originally, when the Arduino used the FT232, the DRT signal would reliably reset it automatically. The operating system (all operating systems) would automatically assert DTR when the port was opened, and all was well.

Then, out of the blue, and without telling anyone, Future Tech removed that auto-DTR asserting from the FT232 driver for Windows. Since Windows doesn't control DTR for you, but leaves it up to the driver or the software (and all other operating systems automatically control DTR for you - Windows *has* to do the opposite of everyone else - it's in their remit...!) all of a sudden the boards stopped resetting properly for programming.

So Arduino added specific reset code into the IDE to get around the problem (interestingly enough: if you watch the DTR pin on Linux you see it being asserted multiple times when programming - both the OS and the IDE are toggling it).

But then Arduino moved to the ATmega8U2 (and later the ATmega16U2) chip which uses the standard CDC/ACM instead of the custom FT232 driver. Now the auto DTR assertion was working again, but they kept the manual assertion in the IDE to cope with older boards in Windows.

I guess they didn't put the DTR assertion workaround in the bootloader programming code since you don't really want DTR asserted at that point anyway.

So if you have an FT232-based Arduino and are running Windows I guess there is no need for the capacitor, since DTR won't be asserted by the OS.

However in Linux and OS X, regardless of the USB chip, you will need the capacitor, since it will *always* assert DTR.

But then along came China and threw the CH340G into the works. Now we have a third option, with dodgy drivers from who knows where. And who has the slightest clue what they do? Do they assert DTR for you? Your guess is as good as mine. If it doesn't, then you won't need the capacitor. If it does, then you will.

It's all such a mess now thanks to too many options and combinations. It's simpler just to have the capacitor regardless, since it won't stop it working if it's not actually needed in your specific configuration.
> 3 votes

# Answer
If you're using Nick Gammon's programmer, the RESET signal to the target board comes from the Arduino programmer - from Pin 10. Read his instructions: https://www.gammon.com.au/bootloader

You modify the 6 pin cable as shown on his website.
> 2 votes

---
Tags: arduino-uno, arduino-mega, isp
---


# Question
Title: WiFi problem on Mega + WiFi R3 ATmega2560 + ESP8266
I've got 2 "Mega + WiFi R3 ATmega2560 + ESP8266" (link) and both have same issue when trying to use the ESP chip.

Hope someone can point me toward something else to try in order to get them working properly.

**Context**

I'm able to flash the ESP chip using Arduino IDE or PlatformIO. Dip switch need to be : 5, 6 and 7 ON to flash, and only 5 and 6 to debug through serial.

I've tried using different boards (Generic ESP8266 module, Wemos D1 R2 & mini, Node MCU) as well as different flash mode (DIO, QIO), crystal frequency (26 Mhz, 40 Mhz), CPU frequency (80 Mhz, 160 Mhz)

They all flash correctly without any error and I can get my serial output.

It's written ESP8266EX on the ESP chip. And I've tried with or without an antenna plugged on the board.

**Problem**

The problem I got on both of them is huge instability when using wifi. I cannot connect to them when they are in AP mode, they drop immediately.. And I cannot connect to or see my own wifi network from the Mega's ESP.

The same script and flashing config used on *other ESPs* devices work as expected (see **\[output other ESP board\]** below). I've tried on WeMos and NodeMCU devices.

But with the mega+wifi, it only see between 0 and 2 access point that are at a greater distance and weaker signal than my own wifi (**\[output mega+wifi\]** below).

**Question**

I don't have any clue on what can cause such a different result on device from same family (ESP/espressif). As if there was some sort of setting that need to be changed on those ESPs.

Any help or insight would be truly appreciated.

**\[code\]**

```
#include "ESP8266WiFi.h"

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

  // Set WiFi to station mode and disconnect from an AP if it was previously connected
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);

  Serial.println("Setup done");
}

void loop() {
  Serial.println("scan start");

  // WiFi.scanNetworks will return the number of networks found
  int n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n == 0)
    Serial.println("no networks found");
  else
  {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i)
    {
      // Print SSID and RSSI for each network found
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(WiFi.SSID(i));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");
      Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
      delay(10);
    }
  }
  Serial.println("");

  // Wait a bit before scanning again
  delay(5000);
}

```

**\[output other ESP board\]**

```
scandone
scan done
8 networks found
1: 412 Precondition Failed (-67)*
2: VIDEOTRON1547 (-90)*
3: BELL275 (-94)*
4: BELL558 (-72)*
5: C-PC_Network (-88)*
6: BELL387 (-90)*
7: EBOX-4229 (-94)*
8: VIDEOTRON6825 (-80)*

scan start
scandone
scan done
11 networks found
1: 412 Precondition Failed (-63)*
2: VIDEOTRON1547 (-88)*
3: BELL681 (-90)*
4: BELL275 (-90)*
5: VIDEOTRON0442 (-90)*
6: BELL558 (-71)*
7: BELL602 (-90)*
8: IKA COIFFURE (-90)*
9: C-PC_Network (-87)*
10: EBOX-4229 (-87)*
11: BELL387 (-90)*

scan start
scandone
scan done
7 networks found
1: 412 Precondition Failed (-65)*
2: BELL681 (-88)*
3: VIDEOTRON1547 (-88)*
4: EBOX-4229 (-88)*
5: BELL387 (-87)*
6: BELL558 (-71)*
7: dlink-Ares (-75)*

```

**\[output mega+wifi\]**

```
SDK:2.2.1(cfd48f3)/Core:2.4.1/lwIP:2.0.3(STABLE-2_0_3_RELEASE/glue:arduino-2.4.1)
bcn 0
del if1
usl
mode : sta(2c:3a:e8:26:36:13)
add if0
wifi evt: 8
Setup done
scan start
scandone
scan done
1 networks found
1: BELL558 (-69)*

scan start
scandone
scan done
1 networks found
1: BELL387 (-88)*

scan start
scandone
scan done
no networks found

scan start
scandone
scan done
1 networks found
1: BELL387 (-87)*

```

**\[erasing flash\]**

```
PS \tool-esptoolpy> python .\esptool.py -p COM10 erase_flash
esptool.py v2.3.1
Connecting....
Detecting chip type... ESP8266
Chip is ESP8266EX
Features: WiFi
Uploading stub...
Running stub...
Stub running...
Erasing flash (this may take a while)...
Chip erase completed successfully in 14.2s
Hard resetting via RTS pin...

```

# Answer
I had this problem. On Robotdyn D1 mini the esp8266 flash erase did help. On Robotdyn D1 R2 only the flashing of the AT firmware with Espressif Flash Download Tool restored the esp8266. After then the sketches from IDE had working WiFi.

There are some settings of the Espressif basic esp8266 libraries (SDK) saved on flash and there is some incompatibility between SDK versions. The Flash Download Tool creates right esp settings binary and flashes it to right address on flash.
> 1 votes

# Answer
You state you "cannot connect to them when they are in AP mode" but I do not see AP configured in your code.

```
// ESP AP Server
// password can be blank
// must be min 8 chars or will not work
const char *APName = "MYESP8266";
const char *APPass = "MYPASS123";
// start the access point server
WiFi.softAP(APName, APPass);
// define web link functions
webServer.on("/", doRoot);
// start server
webServer.begin();

// In LOOP
// keep checking to see if someone connects to device
webServer.handleClient();

```

Regarding the mega-wifi-r3-atmega2560-esp8266 I am unsure how these work, is the code being flashed to the ESP chip or to the Arduino chip and ESP is in AT mode?
> 0 votes

# Answer
If you've come upon this page because the ESP8266 on your (WeMos) Mega wifi won't connect to your router (etc), check the age/security of your router: Wifi stopped connecting (Wemos D1 Mini)

This line of code that allowed connecting with my old router: WiFi.enableInsecureWEP();

which also highlights that I should upgrade it...
> 0 votes

---
Tags: arduino-mega, esp8266, wifi
---


# Question
Title: Read battery voltage from battery which is powering arduino
I have a 5V arduino pro micro. I want to power it with a 3.7V lipo.

* Should I use a step up module to convert it to 5V?

I also want to measure the voltage of the battery.

* How can I do this?

Because I read that the power source also the reference voltage is so I cant measure it with an analog pin right?

I also use a lipo charging module to charge the battery.

Thanks for helping!

# Answer
> 2 votes
You can read the Arduino's supply voltage see here How to measure the supply voltage of Arduino without using an analog pin Alternatively use the internal 1.1V reference and a suitable voltage divider to read the lipo's voltage

# Answer
> 0 votes
Yes, you should use a boost converter to convert the 3.7V from your battery to the 5V that the Arduino requires.

As I understand it, measuring voltage to determine charge level does not work well with lithium chemistry batteries since they hold a nearly constant voltage until they are almost completely depleted. Generally lithium batteries include a chip that measures current in and out and lets you query their charge level.

---
Tags: voltage-level, arduino-pro-micro, lipo
---


# Question
Title: Attiny85 simple analog and digital output problem
I'm just lighting up an LED through a TIP31C, pin 0 goes through a 560kohm resistor to the tip's input pin pin 1 goes through a 750 ohm resistor to the tip's input pin ^i'm not sure this information is really relevant

The reason I am doing this is so i can sleep the attiny85 while having pin 0 set to HIGH to have the led at a very low brightness, kind of like a standby function

```
void setup() {

}

void loop() {
  digitalWrite(0, HIGH);//works ONLY the first time
  delay(500);
  digitalWrite(0, LOW);
  delay(500);

  analogWrite(1, 15);//always works
  delay(500);
  analogWrite(1, 0);
  delay(500);
  /*it's like as soon as i've used an analogWrite, i can no
    longer output with digitalWrite
  */

  //pinMode(0, OUTPUT);//didn't help
  digitalWrite(0, HIGH);//never works
  delay(500);
  digitalWrite(0, LOW);
  delay(500);
}

```

# Answer
There are a number of issues here:

1. You state you have a 560kohm resistor, this is too high a value. With 5V it will restrict the current to 8.9uA.

* This is too low to drive the LED, which probably requires up to 20mA (5V / 0.02A = 250Ohm at least)
    * This is also too low for for the base of the transistor (I'm not completely sure if my understanding of transistor gain is correct, but I think if you feed 1mA into the base of the TIP31C, it's gain of 25 will allow upto 25mA between the collector and emitter.) Based on this, 5V / 0.001A = 5kOhm.
2. You do need `pinMode(0, OUTPUT);` and `pinMode(A1, OUTPUT);` in setup. It will work, except you won't notice the effect with your 560kOhm resistor.
3. You also need to check the pins of the atTiny85.

As you can see, the only analog outputs are on physical pins 2, 3 and 7. You need to refer to these (for connection to pin 7) as:

```
pinMode(A1, OUTPUT);
analogWrite(A1, 15);

```

Below is a rough idea of what the schematic should look like

simulate this circuit – Schematic created using CircuitLab

And below is an (untested) example of the code:

```
void setup() {
  pinMode(A1, OUTPUT);
}

void loop() {
  analogWrite(A1, 15);
  delay(500);
  analogWrite(A1, 0);
  delay(500);
}

```
> 1 votes

---
Tags: sleep, analogwrite, attiny85, digitalwrite
---


# Question
Title: i can't work toggle for my small project
i build my small project from a few component as this photo after finish code and project . i work run for Proteus and then the project not run perfectly because my code need toggle for data entered . i cant work toggle for data .i want help .please

this my code arduino

```
#define CLK 10
#define CLKI 9
#define LD 8
#define SO 11
#define SER 12

byte ledstates;
byte copy=0;
int rec=0;
unsigned long bt_leds_timestamp=0;
byte bt_leds_activated=0;

void setup(){
Serial.begin(9600);
pinMode(CLK,OUTPUT);
pinMode(CLKI,OUTPUT);
pinMode(LD,OUTPUT);
pinMode(SO,INPUT);
pinMode(SER,OUTPUT);
}

void loop(){
if (Serial.available()>0){
message();
}
if(bt_leds_activated && millis()-bt_leds_timestamp > 2000){
ledstates &= ~bt_leds_activated;
shift_out(ledstates);
bt_leds_activated = 0;
}
shift_In();
shift_out(ledstates);
}

void message(){
if(Serial.available()){      // Send data only when you receive data:
char data = Serial.read();        //Read   the incoming data & store into data
Serial.print(data);          //Print Value inside data in Serial monitor

switch (data){
  case 'A' :
    bt_leds_activated |= 1;
    break;
  case 'B' :
    bt_leds_activated |= 2;
    break;
  case 'C' :
    bt_leds_activated |= 4;
    break;
  case 'D' :
    bt_leds_activated |= 8;
    break;
  case 'E' :
    bt_leds_activated |= 16;
    break;
  case 'F' :
    bt_leds_activated |= 32 ;
    break;
  case 'G' :
    bt_leds_activated |= 64;
    break;
  case 'H' :
    bt_leds_activated |= 128;
    break;
  default   : return; }
  }
  ledstates |= bt_leds_activated;
  shift_out(ledstates);
  bt_leds_timestamp = millis();

  }

  void shift_out (byte copy){
  digitalWrite(LD, LOW);
  shiftOut(SER,CLK,MSBFIRST,copy);
  digitalWrite(LD, HIGH);
  delay(100);
  }

  void shift_In(){
  digitalWrite(CLKI,HIGH);
  digitalWrite(LD,HIGH);
  digitalWrite(LD,LOW);
  digitalWrite(LD,HIGH);
  digitalWrite(CLK,HIGH);
  digitalWrite(CLKI,LOW);
  byte buttonstates = shiftIn(SO,CLK,MSBFIRST); //read button states in a local variable
  digitalWrite(CLKI,HIGH);
  for(int i=0;i<8;i++){ // loop through all 8 bits of the buttonstates
    if(!(copy & (1<<i)) && (buttonstates & (1<<i))){ // check if old button state (in copy) is zero and new buttonstate is 1 (for the currently check bit)
        ledstates ^= 1<<i; // toggle the corresponding bit in the ledstates variable (will be shifted out later in the loop() function)
    }
  }
  copy = buttonstates;
  delay(10); // delay for debouncing
   }

```

# Answer
Currently you are shifting in the button states and directly shifting them out again to the LEDs. Thus the state of the LEDs follows exactly the state of the buttons.

As jsotola explained in the comments, you need to seperate what you get as input (buttons and serial) from what you set as output. For this you need 1 or more variables to hold the state of the LEDs (your output) and the state of each input (for example each button). The last is what you have in the `copy` variable. It resembles the state of the buttons input. Now create a new variable `byte ledstates;`. The `shift_out()` function has to be called with this variable instead of with `copy`.

Now that input and output are seperated, you can look at the desired behavior for the input. As 1 button press (pressing and releasing) should toggle the state of the corresponding LED, you have to look for a LOW-to-HIGH transition. A common way is to save the current state of the buttons in a variable. Then, in the next execution of `shift_in()` you can check, if the previous state (as saved in the variable) and the new measured state do a LOW-to-HIGH transition (previously LOW, now HIGH). This is a button press, that you can use to toggle the corresponding LED bit in the newly created `ledstates` variable. Save the new measured state in the `copy` variable. (Btw: You should rename the `copy` variable to something more describing)

Also you need to consider a mechanism, that you haven't had to bother with the previous code: Button bouncing. A mechanical switch or button will not make one single clean transition, when being pressed. The mechanical contact will bounce a bit, resulting in very fast HIGH-LOW transitions, until the button is settled. If you don't consider that in your program, you will get many transitions and thus toggling the LED many times with only one button press. There are many ways to tackle this (and all of them can be easily googled). I would go with the "don't sense any further transitions after the first for a fixed time" way. This can be done by a simple `delay()` call at the end of your `shift_in()` function (not so elegant with some caveats) or by using `millis()` to create a non-blocking timeout (in the best case for each button individually) (Look at the `BlinkWithoutDelay` example, that comes with the Arduino IDE. It is worth learning this principle).

So you have something like this (not the full code, just some hints):

```
byte copy;
byte ledstates;

void loop(){
    if (Serial.available()>0){
        message();
    }
    shift_In();
    shift_out(ledstates);
}

void shift_in(){
    digitalWrite(CLKI,HIGH);
    digitalWrite(LD,HIGH);
    digitalWrite(LD,LOW);
    digitalWrite(LD,HIGH);
    digitalWrite(CLK,HIGH);
    digitalWrite(CLKI,LOW);
    byte buttonstates = shiftIn(SO,CLK,MSBFIRST); //read button states in a local variable
    digitalWrite(CLKI,HIGH);
    for(int i=0;i<8;i++){ // loop through all 8 bits of the buttonstates
        if(!(copy & (1<<i)) && (buttonstates & (1<<i))){ // check if old button state (in copy) is zero and new buttonstate is 1 (for the currently check bit)
            ledstates ^= 1<<i; // toggle the corresponding bit in the ledstates variable (will be shifted out later in the loop() function)
        }
    }
    copy = buttonstates;
    delay(10); // delay for debouncing
}

```

---

As mentioned above we have seperated input and output. Now it is easy to also implement a fitting bluetooth control. You want the corresponding light go on on serial input (through bluetooth) and go out after a specific time automatically. For such a thing using `millis()` with a timestamp is the best option. First we take the `message()` function. We define 2 variables at the global scope (outside of any function at the start of the program) to hold the timestamp of our last serial communication and a byte to hold the LEDs, that where activated via serial. In the `message()` function we now set the corresponding bit in this last variable. If the serial data was not valid, we simply return from the function (this makes the code shorter). At the end of the function we ensure, that every LED that was set in our variable gets also set in our `ledstates` variable, which then will be shifted out. And lastly we save a timestamp with the `millis()` function, which returns the number of milliseconds since the startup.

```
unsigned long bt_leds_timestamp=0;
byte bt_leds_activated=0;

void message(){
  if(Serial.available()){      // Send data                   only when you receive data:
    char data = Serial.read();        //Read   the incoming data & store into data
    Serial.print(data);          //Print Value inside data in Serial monitor

    switch (data){
      case 'A' :
        bt_leds_activated |= 1;
        break;
      case 'B' :
        bt_leds_activated |= 2;
        break;
      case 'C' :
        bt_leds_activated |= 4;
        break;
      case 'D' :
        bt_leds_activated |= 8;
        break;
      case 'E' :
        bt_leds_activated |= 16;
        break;
      case 'F' :
        bt_leds_activated |= 32 ;
        break;
      case 'G' :
        bt_leds_activated |= 64;
        break;
      case 'H' :
        bt_leds_activated |= 128;
        break;
      default   : return; }
  }
  ledstates |= bt_leds_activated;
  shift_out(ledstates);
  bt_leds_timestamp = millis();
}

```

Now the corresponding LEDs get turned on, but not off. So we need to put the following code in the main `loop()` function:

```
if(bt_leds_activated && millis()-bt_leds_timestamp > 2000){
  ledstates &= ~bt_leds_activated;
  shift_out(ledstates);
  bt_leds_activated = 0;
}

```

This code checks, if any LED was activated via bluetooth (the first part of the if condition evaluates to true, if `bt_leds_activated` is different than zero) and if a certain time (here 2s aka 2000ms) has passed since the timestamp was taken. When the time has come, then the LED bits from `bt_leds_activated`, which we set earlier`are cleared in`ledstates`to turn the LEDs off. Then this is shifted out to set the actual state of the LEDs for us to see. Finally we reset`bt\_leds\_activated\` to zero, since we don't have any more LEDs to turn of automatically, until new data arrives.

This has 1 caveat: When you send new data over bluetooth within these 2s, the timeout for the LEDs previously activated via bluetooth will also be resetted, so that they will light longer. The way around that is to use 1 timestamp for each LED, but I thought this as to complicated for now. Don't want this, you can implement that part yourself just like I did with all of them together.

Note: I haven't tested this code in any way.
> 1 votes

---
Tags: arduino-uno, c++, led, bluetooth, shift-register
---


title: My millis() code doesn't work

text:
# Question
Title: My millis() code doesn't work
I am doing a project with bluetooth and an LED. I wrote a code which supposed to turn on an LED after it receives a byte of value 1 after 5 seconds, unless it receive another byte of value 1 (which make it need to wait another 5 seconds) so that if it receive the byte periodically, the LED doesnt turn on, and only turn on if byte value sending is stopped/bluetooth disconnected. I wrote this code and it doesn't seem to work. It doesn't even turn on the LED after 5 seconds. Can you help me spot the mistake here?

```
unsigned long timebetween=5000;
unsigned long lastreceivedtime;
int value;
bool timerReady = false;

void setup() {
  pinMode (11,OUTPUT);
  Serial.begin(9600);
}

void loop() {
  unsigned long currentMillis = millis();
  if( Serial.available() >0){
    value = Serial.read();
  }
  if ( value ==1 ){
    lastreceivedtime = currentMillis;
    timerReady = true;
  }

  if(timerReady) {
    if((unsigned long)(currentMillis - lastreceivedtime) >= timebetween){
      digitalWrite(11, HIGH);
      delay(90);
    }
  }
}

```

# Answer
I don't think anything in your code is going to work. First, you are asking the serial.Read to return an integer if it is working. You might want to change that to a Boolean.

Second, You are asking for a 1 and only a 1 to make your next if statement true. If the serial.Read is working the chance it will only return a one, I think is very low

Third, On the IF statement for setting timerReady. You will set that at a new number each time the program runs through, with the 90ms delay in the last IF statement, it looks like your timer will reset at about every 95-100ms

Fourth, I think your last 2 IF statements are wrong, I think you want

```
if(timerReady==true) {
    if((currentMillis - lastreceivedtime) >= timebetween){
      digitalWrite(11, HIGH);
      delay(90);

```

If you do get this working you might need to set the Boolean back to false and move pin 11 to low at some point.
> 1 votes

---
Tags: programming, bluetooth, millis
---