# Question
Title: Getting different numbers after sending an unsigned int 8-9 times between Arduinos via Serial
I am trying to transfer `unsigned int` values between 2 Arduinos. When sending `61805` for the first 8-9 times, I am getting 61805. But after then after these numbers: 61937 28013 61937.

Sender's code:

```
unsigned int s = 0;

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

void loop()
{
  s = 61805;
  Serial.write(highByte(s)) ;
  Serial.write(lowByte(s));
}

```

Receiver's code:

```
unsigned int upperByte, lowerByte, r=0,p=0;

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

void loop ()
{
  if (Serial.available() > 1)
  {
    upperByte = Serial.read();
    lowerByte = Serial.read();
  }

  r = (upperByte << 8) + lowerByte;
  Serial.println(r);
}

```

# Answer
There's no flow control on the Uno and Nano serial and you are sending fast enough that bytes are being dropped, and there's no way your protocol or lack of one demarcates separate messages (separate numbers).

This will become more clear if you write your numbers in hexadecimal:

| Dec | Hex |
| --- | --- |
| 61805 | 0xf16d |
| 61937 | 0xf1f1 |
| 28013 | 0x6d6d |
| 61937 | 0xf1f1 |

Adding a delay between messages can serve to separate the messages if the receiving side makes use of a timeout and can prevent the receiving side from being overwhelmed with data.

If you don't want to use time to slow down and separate your data, you can change what is sent instead. One idea is to have the receiver actively request data when it's ready to receive some. The receiver should expect only entire messages between requests, and if anything gets garbled, it can just read whatever data has come in and throw it out before the next request.

Your messages can also be separated by some characters that aren't part of the messages themselves. A common way to do that is just to encode your numbers as separate text lines, the line terminator `\n` serving as the separator between messages.

I have not tested these yet, but here are some very minimal modifications to your code that approach having a protocol with fewer of these problems:

Sender:

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

void loop() {
  // await message request
  while(Serial.read() != '.') {
  }

  //
  const unsigned int s = 61805;
  Serial.write(highByte(s)) ;
  Serial.write(lowByte(s));
}

```

Receiver:

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

void loop () {
  // request message
  Serial.write('.');

  // await two-byte response
  const unsigned long request_sent = millis();
  while (Serial.available() < 2 && millis() - request_sent < 1000) {
  }

  if (Serial.available() != 0) {
    if (Serial.available() == 2) {
      // two byte response receive
      const unsigned upperByte = Serial.read();
      const unsigned lowerByte = Serial.read();
      const unsigned r = (upperByte << 8) + lowerByte;
      Serial.println(r);
    }  else {
      // Something went wrong, too or too few bytes received;
      // throw them out and start over.
      delay(100);
      while (Serial.read() != -1) {}
    }
  }
}

```

It's a long way from doing it properly, but it should behave at least better than what you started with. There's a lot to designing even simple protocols. Typically there are start and end frame bytes, a checksum or CRC, a message number counter, etc.
> 2 votes

# Answer
This line of the receiver's code:

```
Serial.println(r);

```

is transmitting 7 bytes (5 digits, CR and LF). At 9600/8N1, each byte takes 1.04 ms, so the whole message is transmitted in 7.28 ms. In the meantime, the sender is sending 2-byte messages at full speed (no pause between the bytes). The receiver thus gets a new message every 2.08 ms.

So, this receiver is given a new message to relay every 2.08 ms, and it needs 7.28 ms to relay each message. Something has to give...

The reason it works in the beginning is that the receiver has a buffer where it stores the bytes that have been received, and another one for the bytes that have been made ready for transmission. As long as there is room in those buffers, everything works fine. The transmit buffer fill-up first, as it gets 7 bytes to transmit every 2.08 ms. Once it's full, `Serial.println()` becomes a *blocking* function: it has to wait for the buffer to have enough room. Your `loop()` then slows down to match the speed of the transmission, which means you do not read the receive buffer often enough. Then the receive buffer fills up, and you start loosing bytes.
> 0 votes

---
Tags: arduino-uno, arduino-nano
---


# Question
Title: This website in Arduino lists language references like functions and structures. What makes structures there different from functions?
https://www.arduino.cc/reference/en/

**Language Reference**

Arduino programming language can be divided in three main parts: functions, values (variables and constants), and structure.

**functions**

For controlling the Arduino board and performing computations.

**variables**

Arduino data types and constants.

**structure**

The elements of Arduino (C++) code.

I find it really confusing that they had to separate the structures but also call them functions in their descriptions. I kind of want to get a visualization or organization of the different language references present in Arduino, but this just confuses me. Are structures in the website also functions, and mainly syntax can be classified into functions and variables? Can someone present a organization of language references that doesn't involve terminologies being mixed up?

# Answer
What the website names "Structures" are code building-blocks for the programs you write. The main part there are conditional (if-else) and loop instructions (for, while) as well as mathematical operators. You use these constructs *within* your functions to control program flow or compute results. Functions, on the other hand, are sub-programs you can call to have certain tasks done. They might be pre-defined (such as the ones described on the language reference page) or written by yourself.

Now there are two exceptions to this rule, and maybe that's what's a bit confusing in the documentation: The functions `setup()` and `loop()`. These are functions, but make up the structure of your program. They are the main building blocks of an Arduino sketch, and that's probably why they're mentioned under "Structures".
> 2 votes

---
Tags: functions
---


# Question
Title: 5V pin out, 8 pins and micropython/circuitpython support: does such a board exist?
For a project, I am looking for a board to connect eight different neopixel-strips to, on eight different data pins. Because of the great length between the board and the first pixels of these strips, I'd like to have a board that operates on 5V instead of 3.3V. Then, the software that I have written to manage the LEDs is made in (micro)python. Finally, for simplicity's sake, I'd like to run this complete project on a single board without too many external components.

So, I have found 5V boards with enough pins, like the Arduino Mega. I have also found boards with enough pins and support for micropython or circuitpython, like the ESP32 or Arduino Zero.

However, I haven't quite found a board that matches all my requirements. The Arduino Mega doesn't support Python (or does it?) and the ESP32 and Arduino Zero operate at 3.3V, not 5V.

Of course, an ESP32 with a level shifter (as shown on https://github.com/Aircoookie/WLED/wiki) would work, but is there perhaps a board out there that fits all my requirements our of the box?

**Edit**: It seems I misunderstood some things about the hardware - sorry, I'm a software guy, not really a hardware guy :-) I fixed the question above as not to confuse future readers.

# Answer
> 1 votes
Both your "requirements" for the board are non-requirements.

* You do not need PWM pins to drive Neopixel strips. The Neopixel uses its own custom protocol that has nothing at all to do with PWM.
* Your board only communicates with the *first* Neopixel. That one then communicates with the second, which then communicates with the third, etc. The length of the strip is completely irrelevant to what voltage you might want to drive it with.

You only care about having enough general IO pins and if the IO voltage is suitable to communicate with one Neopixel.

According to the WS2812B datasheet VIH is 0.7Vdd, which if you are powering the strips from 5V means 0.7 * 5 = 3.5V. However I think that is an overestimation and they are erring on the side of caution there, since I regularly drive WS2812B strips from a 3.3V microcontroller with no problems whatsoever (after all it's only 0.2V difference).

So just use your favourite 3.3V microcontroller that can run micropython and, if you really want to, drop the power supply voltage to the strips a fraction with a diode.

---
Tags: arduino-mega, esp32, python, arduino-zero
---


# Question
Title: ESP8266 ESP-01s Not Responding, No LED Blinking, Overheating
I have an ESP-01s that I want to use as a shield so my Arduino Uno project could communicate with my Blynk app through wi-fi. I used this video as reference.

This is the sketch. It is just the ESP8266\_Shield example from the Blynk library.

```
#define BLYNK_PRINT Serial

#include <ESP8266_Lib.h>
#include <BlynkSimpleShieldEsp8266.h>

char auth[] = "-------";

char ssid[] = "-------";
char pass[] = "-------";

#include <SoftwareSerial.h>
SoftwareSerial EspSerial(2,3); // RX, TX

// Your ESP8266 baud rate:
#define ESP8266_BAUD 115200

ESP8266 wifi(&EspSerial);

void setup()
{
  // Debug console
  Serial.begin(9600);

  delay(10);

  // Set ESP8266 baud rate
  EspSerial.begin(ESP8266_BAUD);
  delay(10);

  Blynk.begin(auth, wifi, ssid, pass);
}

void loop()
{
  Blynk.run();
}

```

This is the schematic:

What happens:

1. The moment the Arduino is connected, the Blue LED flashes for a split second then all LEDs will remain off. No red led, no blue led, really just off.
2. The ESP-01s becomes very hot to the touch
3. Tried speaking to the ESP-01s through the Serial Monitor with BareMinimum example @115200 baud rate (Many Sources say that this is the default baud rate of the recent boards) however no response whatsoever.
4. Running the code above will get this error:

What I've done:

1. Tried using the HW-131 Breadboard Power Supply to supply the 3.3V (Common GND with Arduin) of the ESP-01s because I read that the ESP-01 could need more current than the Arduino Uno could provide. Still the same effect, no LEDs blinking, (even more) hot to touch, not responding to AT commands.
2. Attempted to follow a video on how to flash the ESP-01s but when I tried to run the flasher, it could not communicate with the ESP-01s.
3. Switching Rx Tx ESP-01s but no luck.
4. Added a 10k ohm resistor from 3.3V to the Vcc and EN pins of the ESP-01s. Not heating up anymore but still no response.

I really thought this is a power problem but could it be the ESP-01s itself is defective?

This is what the ESP-01s look like

# Answer
> 2 votes
The ESP8266 is (highly likely) dead. The overheating is the giveaway.

Because you haven't mentioned it, please measure the 3.3V coming out of the Arduino with a multimeter. Unlikely to be the issue but it is easy to check.

You will need to buy a new ESP8266 and connect it up and give it a try with a fresh board. If all is good with the new board then the first thing you will notice is that there is no overheating. (If there is overheating, then you need to check your wiring.)

I notice that quite a lot of people add a 10K pull up resistor between the 3.3V line and the Enable pin. It certainly won't hurt to add a 100 ohm resistor between the Tx pin and D2 of the Arduino as a current limiting resistor, just in case.

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


# Question
Title: Fail uploading any sketch to ATtiny85 USB
I have a Digistump's ATtiny85 (probably a clone ), which fails uploading any sketch, saying: `Warning: device with unknown new version of Micronucleus detected. This tool doesn't know how to upload to this new device. Updates may be available.` I'm using Ubuntu 20.04 and Arduino IDE 1.8.13.

I used these guides:

1. Digistump's troubleshooting for linux
2. Kovo's blog

After using these guides, finally I stop getting this error, but when trying to upload the firmware ( last line at Kovo's ), I get this error:

```
`guy@desktop:~/tmp/micronucleus/upgrade$ ~/.arduino15/packages/digistump/tools/micronucleus/2.0a4/launcher -cdigispark  --timeout 60 -Uflash:w:~/tmp/micronucleus/upgrade/t85_default.hex:i
Running Digispark Uploader...
Plug in device now... (will timeout in 60 seconds)
> Please plug in the device (will time out in 60 seconds) ...
> Device is found!
connecting: 16% complete
connecting: 22% complete
connecting: 28% complete
connecting: 33% complete
> Device has firmware version 2.4
> Device signature: 0x1e930b
> Available space for user applications: 6522 bytes
> Suggested sleep time between sending pages: 7ms
> Whole page count: 102  page size: 64
> Erase function sleep duration: 714ms
parsing: 50% complete
> Program file is 1594 bytes too big for the bootloader!

```

Did someone encounter this ?

# Answer
> -1 votes
from Daves Comment

need to download `upgrade-t85.hex` (which is not `t85_default.hex`) from link

---
Tags: attiny
---


# Question
Title: How can I break the loop if it hasn't finished in 10 seconds?
Currently I am using OneButton.h library to code my push button project.

When I press button1, it will loop for 10sec and print TRIG, and after that it will break the loop.

However, now I want to program it where when I pressed button1, it will jump to `void(singleclick)` function, but right now, during the 4th seconds (anytime before 10th sec) , I pressed other button, thus Arduino will break the 10sec loop and run other function.

Thus, I need help how to make sure Arduino actively read other button and when pressed, it will break the current loop/function to other related functions.

```
#include <OneButton.h>

OneButton button1(2, true);
OneButton button2(3, true);
OneButton button3(4, true);
OneButton button4(5, true);

int led1=12;
int led2=11;
int led3=10;
int led4=9;

int flag;

unsigned long mode;

void setup()
{

  Serial.begin(9600);
  pinMode(led1,OUTPUT);
  pinMode(led2,OUTPUT);
  pinMode(led3,OUTPUT);
  pinMode(led4,OUTPUT);

  button1.attachClick(singleclick1);
  button1.attachLongPressStop(longclick);

  button2.attachClick(singleclick2);
  button3.attachClick(singleclick3);
  button4.attachClick(singleclick4);

   digitalWrite(led1,HIGH);
   digitalWrite(led2,HIGH);
   digitalWrite(led3,HIGH);
   digitalWrite(led4,HIGH);

}

void loop()
{
  button1.tick();
  delay(20);

  button2.tick();
  delay(20);

  button3.tick();
  delay(20);

  button4.tick();
  delay(20);

  Serial.println("No button");

}

void singleclick1()
{
   mode=millis();

   flag=1;

   while(flag==1)
   {
     Serial.println("button1");
     digitalWrite(led1,HIGH);
     digitalWrite(led2,LOW);
     digitalWrite(led3,LOW);
     digitalWrite(led4,LOW);

     if(millis()-mode>5000)
     {
      Serial.println("TRIG");
      flag=0;

      button2.tick();
      delay(20);

      button3.tick();
      delay(20);

      button4.tick();
      delay(20);

      return;
     }
   }
}

void singleclick2()
{
   Serial.println("button2");
   digitalWrite(led1,LOW);
   digitalWrite(led2,HIGH);
   digitalWrite(led3,LOW);
   digitalWrite(led4,LOW);
}

```

# Answer
> 3 votes
This is just a rough, incomplete and untested code.

```
void singleclick1() { startTimer = true; }      // this only sets a flag

void singleclick2() { runTimer   = false;}      // this only clears a flag

void loop() {

   button1.tick();
   button2.tick();

   if startTimer {                 // this occurs once every click 1

      mode        = millis();
      runTimer    = true;
      startTimer  = false;         // run this block only once every click 1

      digitalWrite(led1, HIGH);
      digitalWrite(led2, LOW );
      digitalWrite(led3, LOW );
      digitalWrite(led4, LOW );
   }

   unsigned long currentMillis = millis();

   if (currentMillis - mode > 10000) {
      runTimer = false;                      // 10 second timer expired
   }

   if (runTimer) {

      Serial.println("TRIG");

   }
   else {
      // optional stuff to do
   }
}

```

---
Tags: arduino-uno
---


title: Can you create an array for functions?

text:
# Question
Title: Can you create an array for functions?
Let's say I want to create 10 functions, named Function1, Function2 until 10. Each function is used if a certain variable is equal to its number. Rather than using individual functions, I was wondering if its possible to use some sort of array concept for functions when it comes to naming? I tried reading about it and saw pointers but I honestly didn't understand what I saw about it because I'm not that adept to the language yet.

# Answer
Here's an example of how to do it:

**jump\_table.ino**

```
int func1(int arg)  { return arg + 1; }
int func2(int arg)  { return arg + 2; }
int func3(int arg)  { return arg + 3; }
int func4(int arg)  { return arg + 4; }
int func5(int arg)  { return arg + 5; }
int func6(int arg)  { return arg + 6; }
int func7(int arg)  { return arg + 7; }
int func8(int arg)  { return arg + 8; }
int func9(int arg)  { return arg + 9; }
int func10(int arg) { return arg + 10; }

int (*jump_table[10])(int) = { func1, func2, func3, func4, func5,
                               func6, func7, func8, func9, func10 };

void setup() {
}

void loop() {
  int index = 2;
  int argument = 42;
  int result = (*jump_table[index])(argument);
  // result is 45
}

```

All functions stored in the array must have the same signature. This simply means that they must return the same type (e.g. `int`) and have the same arguments (a single `int` in the example above).

---

You can do the same with *static* class methods (but not instance methods). For example you could use `MyClass::myStaticMethod` in the array above but not `MyClass::myInstanceMethod` nor `instance.myInstanceMethod`:

```
class MyClass {
public:
  static int myStaticMethod(int foo)   { return foo + 17; }
  int        myInstanceMethod(int bar) { return bar + 17; }
}

MyClass instance;

```

There's a similar question over on stackoverflow.
> 4 votes

---
Tags: array, pointer, functions
---


title: Where to go after Arduino?

text:
# Question
Title: Where to go after Arduino?
I apologise in advance if this question is not right for this Stack or if it has been answered before but here goes. I have been learning C/C++ using the Arduino Uno and have gotten the hang of it now (I have knowledge of other programming languages so it wasn't too difficult to get in the rhythm). I was wondering how I would go about creating a standalone solution if I wanted to display information on four or five displays similar to These. I would pull data from a network to display on them too so I would also need to accommodate an ethernet or WiFi shield.

I appreciate any help or pointers in the right direction that can get me started on my journey to creating some custom embedded systems (if that is indeed what I am describing).

# Answer
> 2 votes
You can use an ESP8266 or ESP32. This makes it easy to transmit data via WiFi. You can also use the Raspberry Pi, which is much more powerful.

# Answer
> 2 votes
There are a lot of much more powerful boards available (especially if you move from ATmega to ARM). I'm partial to the Teensy boards myself but Adafruit also makes some nice ARM-based boards. For example, I'm currently developing a multi-user, Arduino-compatible Unix-ish OS on one of the latter (48MHz ARM, 256kB flash, 32kB SRAM) and it runs great. Honestly, controlling 5 non-graphical LCDs over I²C is should be easily doable on an Uno but if you need more power there are lots of options available.

(No affiliation to either of those companies)

# Answer
> 1 votes
Uno's major limitation is it's 2KB of RAM. If your project can live within that, an Uno can host it.

The display you pointed to is an I2C device and can be bussed, so Uno pin count won't be a limitation. Current might be, and you may need to power the displays independently of the Uno.

The ESP-01 module makes a good Wifi accessory which you can build onto a proto-shield or wire separately. If your Uno is powered at 5v as most are, you'll need to provide 3.3v power to the ESP, and a voltage divider on the ESP's receive pin to reduce the serial input from the Uno to 3.3v.

Update:
Upon re-reading, your title suggests you *want* to move on from an Uno, and you've mentioned a stand-alone solution.

There are many more capable boards available. Arduino Mega is one which would be an easy, almost trivial, transition up from Uno, in flash memory, RAM, and available I/O.

If by "stand-alone" you meant "roll your own", there are any number of how-to projects on the web for rolling your own Atmega 328p-based clone of an Uno.

The direction you take really depends on your project needs and/or your personal preference.

---
Tags: programming, breadboard, custom
---


title: Stable amplitude of amplified signal

text:
# Question
Title: Stable amplitude of amplified signal
Is there any circuit with opamp where can be (by arduino) set constant output amplitude which doesn't depend on input signals amplitude?

# Answer
Just a word of advice about AGC in general. There is almost always an issue of attack (how fast the AGC reacts to a sudden increase in signal) and release (how fast it reacts to a decrease). In most AGC cases you will need to make compromises on these two settings to avoid poor behavior from the AGC... it's not a drop-in solution with pre-determined optimum settings for every purpose. Depending on the program material, you can get obnoxious artifacts like breathing and pumping for speech and music. ACG is much better at slow drifting things like signal fade. I just want you know what you might be getting into...
> 2 votes

---
Tags: arduino-uno, arduino-nano, analog, op-amp
---


# Question
Title: I have five pushbuttons that refer to a specific pin number. I need an efficient code to set the variable for the pin with state 1. What can I use?
There are 5 push buttons each which correspond to a certain pin let us use 1 to 5 for an example. I want to set a variable, ActiveButton which will be set equal to the the only pin in the one state.

We make use of the concept that there can only be one active push button which means the pin of that would have a state of 1 and the rest would be 0. The long method for this would be to use if else and digitalRead(pin) == 1 for everything but that would be so long on code. I've considered using do while or while loops to stop until it reaches the push button with a state of 1, but I was wondering if there was a more efficient code. I was also thinking if there was something that made use of an array?

Though the idea of like having a simple array return the index which results to a corresponding value, like lets say Array\[3\] ==1 among all the indices from 0 to 4 feels easy to conceptualize, I believe this can be really taxing on the code and might not be able to be done in a short way.

I've also thought of possibly using switch case, where the variable would be the high state and the case values would be the digitalRead for each pin? But that would be wrong probably because I'm not sure but you can't set the switch variable to be a constant. It would be something like

switch (1)

case digitalRead(1):

case digitalRead(2):

# Answer
> 1 votes
> There are 5 push buttons each which correspond to a certain pin let us use 1 to 5 for an example. I want to set a variable, ActiveButton which will be set equal to the the only pin in the one state.

Here is a short snippet of what I think, that you want. This is quite a long shot, since your question is not clear enough.

```
int ActiveButton = -1; // Initialize ActiveButton with -1 (no button is active)
int button_pins[] = {1, 2, 3, 4, 5}; //Array with pin numbers of the buttons

void loop(){
    for(int i=0;i < sizeof(button_pins)/sizeof(button_pins[0]); i++){
        if(digitalRead(button_pins[i])){ //if the i-th button was pressed
            ActiveButton = button_pins[i]; // assign i-th button pin number to variable
            break; // Break, since we have found our pressed button, ignore all following pins
        }
    }
}

```

This will assign the pin number of the pressed button to the variable. The condition in the for loop

```
sizeof(button_pins)/sizeof(button_pins[0])

```

will make the code loop over all elements of the `button_pins` array. `sizeof(button_pins)` returns the number of bytes in the `button_pins` array. Then we divide through the number of bytes in the first element to get the number of elements in the array.

---
Tags: pins
---


# Question
Title: I have three pushbuttons where only one can be pushed at a time and want to set a variable for this. How?
Basically I have three push buttons that correspond to pins 1 to 3 and want to set an efficient code that sets a certain variable into the index whose digitalRead is equal to one. Let us assume that only one button can be pressed at a time.

```
void loop()
    {
    if(digitalRead(1) == 1)
        {
        Variable = 1;
        }
    if(digitalRead(2) == 1)
        {
        Variable = 2;
        }
    if(digitalRead(3) == 1)
        {
        Variable = 3;
        }
    }

```

Is there are more efficient way to do this, like for example using other loops?

I can't wrap around my head with doing this concept using the other loops such as for, do while, while and switch because the nature of the idea feels so unconventional for their uses.

# Answer
If you can only have one button pushed at a time, you can only end up with at most one of the if statements evaluate to true. In your code, you check button 2 and 3, even if button 1 is pressed. Your code can be a bit faster if you do this:

```
if(digitalRead(1) == 1)
{
  Variable = 1;
}
else if(digitalRead(2) == 1)
{
  Variable = 2;
}
else if(digitalRead(3) == 1)
{
  Variable = 3;
}

```
> 1 votes

---
Tags: loop
---


# Question
Title: How do I print multiple variables in a string?
Say I have some variables that I want to print out to the terminal, what's the easiest way to print them in a string?

Currently I do something like this:

```
Serial.print("Var 1:");Serial.println(var1);
Serial.print(" Var 2:");Serial.println(var2);
Serial.print(" Var 3:");Serial.println(var3);

```

Is there a better way to do this?

# Answer
`ardprintf` is a function that I hacked together which simulates `printf` over the serial connection. This function (given at the bottom) can be pasted in the beginning of the files where the function is needed. It should not create any conflicts.

It can be called similar to `printf`. See it in action in this example:

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

void loop()
{
  int l=2;
  char *j = "test";
  long k = 123456789;
  char s = 'g';
  float f = 2.3;

  ardprintf("test %d %l %c %s %f", l, k, s, j, f);

  delay(5000);

}

```

The output as expected is:

```
test 2 123456789 g test 2.30

```

---

The function prototype is:

```
int ardprintf(char *, ...);

```

It returns the number of arguments detected in the function call.

This is the function definition:

```
#ifndef ARDPRINTF
#define ARDPRINTF
#define ARDBUFFER 16
#include <stdarg.h>
#include <Arduino.h>

int ardprintf(char *str, ...)
{
  int i, count=0, j=0, flag=0;
  char temp[ARDBUFFER+1];
  for(i=0; str[i]!='\0';i++)  if(str[i]=='%')  count++;

  va_list argv;
  va_start(argv, count);
  for(i=0,j=0; str[i]!='\0';i++)
  {
    if(str[i]=='%')
    {
      temp[j] = '\0';
      Serial.print(temp);
      j=0;
      temp[0] = '\0';

      switch(str[++i])
      {
        case 'd': Serial.print(va_arg(argv, int));
                  break;
        case 'l': Serial.print(va_arg(argv, long));
                  break;
        case 'f': Serial.print(va_arg(argv, double));
                  break;
        case 'c': Serial.print((char)va_arg(argv, int));
                  break;
        case 's': Serial.print(va_arg(argv, char *));
                  break;
        default:  ;
      };
    }
    else
    {
      temp[j] = str[i];
      j = (j+1)%ARDBUFFER;
      if(j==0)
      {
        temp[ARDBUFFER] = '\0';
        Serial.print(temp);
        temp[0]='\0';
      }
    }
  };
  Serial.println();
  return count + 1;
}
#undef ARDBUFFER
#endif

```

\**To print the `%` character, use `%%`.\*

---

Now, available on Github gists.
> 39 votes

# Answer
I wouldn't normally put two answers to a question, but I only just found this today, where you can use printf without any buffer.

```
// Function that printf and related will use to print
int serial_putchar(char c, FILE* f) {
    if (c == '\n') serial_putchar('\r', f);
    return Serial.write(c) == 1? 0 : 1;
}

FILE serial_stdout;

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

    // Set up stdout
    fdev_setup_stream(&serial_stdout, serial_putchar, NULL, _FDEV_SETUP_WRITE);
    stdout = &serial_stdout;

    printf("My favorite number is %6d!\n", 12);
}

void loop() {
  static long counter = 0;
  if (millis()%300==0){
    printf("millis(): %ld\tcounter: %ld (%02X)\n", millis(), counter, counter++);
    delay(1);
  }
}

```

This still has the floating point limitation.

I thought I would do a little testing on this, and it works quite well. I added a better test to the loop with formatted output.
> 16 votes

# Answer
I only use this for debugging but:

```
int a = 10;
int b = 20;
Serial.println("a = " + String(a) + " and b = " + String(b));

```
> 9 votes

# Answer
This is probably not better, just different. You can use the **String** object for output. These objects allow concatenation and support automatic typecasting.

```
Serial.begin(9600);
String label = "Var";
const byte nValues = 3;
int var[nValues] = {36, 72, 49};

for (int i = 0; i < nValues; i++) {
    String stuff = label + i + ": ";
    Serial.println(stuff + var[i]);
}

```
> 5 votes

# Answer
I usually used Tabs to make things line up better in the Serial. Having things line up like I do allow the arduino to fire as fast as possible while being able to notice certain changes in the variables.

Try something like this:

```
Serial.println("Var 1:\tVar 2tVar 3:");
Serial.print("\t");
Serial.print(var1);
Serial.print("\t");
Serial.print(var2);
Serial.print("\t");
Serial.print(var3);
Serial.println();

```

Or something like this:

```
Serial.print("Var 1:");Serial.println(var1);
Serial.print("\tVar 2:");Serial.println(var2);
Serial.print("\tVar 3:");Serial.println(var3);

```
> 4 votes

# Answer
I am newbie in Arduino world, but I recently found that this is just a regular C++ (without exceptions and probably polymorphism). But you still can enjoy templates. So my solution is to use following templates:

```
void myprint(void)
{
  Serial.println("");
}

template<typename ...Args>
void myprint(const uint64_t & val, Args && ...args)
{
  serialPrintUint64(val);
  myprint(args...);
}

template<typename T, typename ...Args>
void myprint(const T & t, Args && ...args)
{
  Serial.print(t);
  myprint(args...);
}

....

// somewhere in your code
myprint("type: ", results.decode_type,
        "\t value: ", results.value,
        "\t addr: ", results.address,
        "\t cmd: ", results.command);

```

Nice thing here is that it does not use any extra memory and extra processing here.
> 3 votes

# Answer
> One possible solution is:
>
> `Serial.println((String)"Var 1:" + var1 + " Var 2:" + var2 + " Var 3:" + var3);`

The above solution from Iain increases code size.
> 3 votes

# Answer
I usually (painfully) stick with multiple lines of `Serial.print` but when it becomes convoluted I go back to `sprintf`. It's annoying in that you have to have an available buffer for it.

Usage is as simple (??) as:

```
char buffer[35]; // you have to be aware of how long your data can be
                 // not forgetting unprintable and null term chars
sprintf(buffer,"var1:%i\tvar2:%i\tvar3:%i",var1,var2,var3);
Serial.println(buffer);

```

A word of warning though, it doesn't (by default) support floating types.
> 2 votes

# Answer
The usage will depend of the data type of your variables.

If they are `int`, it would be `%d` or `%i` If they are `string`, it would be `%s`

**Wrapper for printf**

You can change the limit based on your requirements

```
#include <stdarg.h>
void p(char *fmt, ... ){
    char buf[128]; // resulting string limited to 128 chars
    va_list args;
    va_start (args, fmt );
    vsnprintf(buf, 128, fmt, args);
    va_end (args);
    Serial.print(buf); // Output result to Serial
}

```

Source: https://playground.arduino.cc/Main/Printf

Usage examples:

```
p("Var 1:%s\nVar 2:%s\nVar 3:%s\n", var1, var2, var3); // strings
p("Var 1:%d\nVar 2:%d\nVar 3:%d\n", var1, var2, var3); // numbers

```

**ESP8266**

Its built-in in `Serial` class of the framework. No need for additional library or function.

```
// strings
Serial.printf("Var 1:%s\nVar 2:%s\nVar 3:%s\n", var1, var2, var3);
// numbers
Serial.printf("Var 1:%d\nVar 2:%d\nVar 3:%d\n", var1, var2, var3);

```

---

More details about formatting tips on the printf format reference page : http://www.cplusplus.com/reference/cstdio/printf/

`\n` is the escape sequence for the line feed.

> Escape sequences are used to represent certain special characters within string literals and character literals.

Source: http://en.cppreference.com/w/cpp/language/escape

**\[EDIT\]** \- As @Juraj mentioned, it's not available on most of the AVR modules. So I added ESP8266 mention and a printf wrapper for common AVR modules
> 2 votes

# Answer
Using `Streaming.h`, in place of

```
Serial.print("Var 1:");Serial.println(var1);
Serial.print(" Var 2:");Serial.println(var2);
Serial.print(" Var 3:");Serial.println(var3);

```

one can write

```
Serial << "Var 1:" << var1) << " Var 2:" << var2 << " Var 3:" << var3 << endl;

```

The definition of `<<` in `Streaming.h` in effect translates that into a series of ordinary `Serial.print()` calls. That is, `<<` is syntactic sugar, implemented without increasing code size.

If you don't have `Streaming.h` installed, get `Streaming5.zip` from arduiniana.org. Unzip it in your libraries directory, for example in `~/sketchbook/libraries`. Add the line `#include <Streaming.h>` within sketches where you use `<<` as a stream operator.

Base-conversion specifiers \_HEX, \_DEC, \_OCT, and \_BIN are provided, as well as a \_FLOAT function (with number of decimal places) and `endl`. For example, to print latitude and longitude values in a form like "Your coordinates are -23.123, 135.4567” one could write:

```
Serial << "Your coordinates are " << _FLOAT(latitude,3) << ", " << _FLOAT(longitude,4) << endl;

```

This could also be written as

```
Serial << F("Your coordinates are ") << _FLOAT(latitude,3) << ", " << _FLOAT(longitude,4) << endl;

```

which would keep the longer string in PROGMEM instead of bringing it into RAM.

Note, `Streaming.h` doesn't build any strings as such; it just delivers the text of its `<<`-arguments to a stream. A PString class at arduiniana can build strings from stream inputs, if strings instead of streamed output are desired or needed.
> 1 votes

# Answer
From http://playground.arduino.cc/Main/Printf I observed this is working fine on my mega2560

That's all it just worked, no need for vsnprintf\_P or PROGMEM ...

```
#include "Arduino.h"
void local_printf(const char *format, ...)
{
static char line[80];
va_list args;
va_start(args, format);
int len = vsnprintf(line, sizeof(line), format, args);
va_end(args);
for (char *p = &line[0]; *p; p++) {
    if (*p == '\n') {
        Serial.write('\r');
    }
    Serial.write(*p);
}
if (len >= sizeof(line))
    Serial.write('$');
}

void setup()
{
Serial.begin(115200);
local_printf("%s:%d: %s\n", __FILE__, __LINE__, __PRETTY_FUNCTION__);
}

void loop()
{
static int count=0;
local_printf("%s:%d: %s %d\n", __FILE__, __LINE__, __PRETTY_FUNCTION__, count++);
delay(1*1000);
}

// src/main.c:24: void setup()
// src/main.c:30: void loop() 0
// src/main.c:30: void loop() 1

```
> 0 votes

# Answer
I've been using PrintEx for years, and it works great. See enter link description here
> 0 votes

---
Tags: serial, string, terminal
---


# Question
Title: Are there any alternatives to Tinkercad Circuits that is PC application based instead of web app based?
I have been using Tinkercad's Circuits web application to create my Arduino circuits and apply my Arduino code (c++) for testing.

Despite the amazing product they have and the fact it's free, I find myself very disappointed at times. Don't get me wrong, Tinkercad has a bunch of great products that I use all the time (like "3d Designs"). I just feel like "Circuits" needs work or maybe even a different dirrection.

I have been dealing with some of the following issues...

1. **An extremely slow interface creating my circuit:**

I have seen it do a bunch of random things that could use some TLC in the interface. Sometimes objects get stuck and you have to disconnect them from everything before you can move them. Sometimes using a breadboard, objects that seem connected to a pinhole does not make a connection and need to be connected to the breadboard using a wire. There are a bunch of little quarks I see. None are a show stopper and I can work around them but the slow interface makes me hate dealing with a web app. It makes me really want a PC app instead.
2. **The lack of support updating the Arduino compiler:**

It's a very old version and they are not in a hurry to upgrade it. I have contacted support a bunch about issues with the compiler not compiling code that works perfectly fine in the Arduino IDE. Classes need to be defined in a specific way, enums need to be defined in an old way that makes the source look ugly etc. Also, I have let them know when debugging it's about impossible to find out where your bug is because it does not tell you a line number it had a problem on. It tries to highlight the line with little success in my tests. I have suggested to them that maybe they could introduce a new option to choose the compiler version to use for each project this way old designs do not break etc. I didn't get any feedback on the feedback I submitted. So I guess that is a no go.
3. **The simulation time:**

This is the worst offender by far! This is the main reason I want to look for different software to replace Tinkercad Circuits. When simulating code on my circuit design the simulation runs in milliseconds (NOT real-time). I have my code set to do something in 15 seconds. Seems like it will happen in no time... NOPE! I have to wait about 15 minutes to see the results!!

So back to my original question... Is there a PC application out there that does the same thing as Tinkercad Circuits? I want to be able to design an Andrino circuit and then test code with it.

# Answer
I work with the wokwi Arduino simulator

* It is faster
* It uses the latest Arduino IDE for compilation
* It almost runs in real-time. For example, your job of 15 seconds might get executed at about the 17th or 20th second.

Please give it a try. here are some references

Links: https://wokwi.com and https://wokwi.com/arduino/libraries
> 4 votes

# Answer
I'll try to find such PC app, but I can't find anyone. When I give up to find such app, I wrote my own arduino emulator via qt. My app is include arduino app and compile them as part of the qt app. Thank's to #ifdef macros i'm change the arduino.h . My emulator is not let you add scheme elements, but add you advantage to watch pin states and sets values to them. You can correct your project and emulate your own functions and algorithms. There it is https://github.com/ravenclawprog/arduino\_mobil
> 2 votes

---
Tags: arduino-uno, ide
---


title: ICT Bill Accepter

text:
# Question
Title: ICT Bill Accepter
I have a ICT a6-15scp-usd4-ii. I have all of the wires for it. I dont have the gambling machine it came out of and it was laying around. Is it possible to make a Light come on when a bill is put in? Can it be wired to the arduino to act as a switch per-say? If more info is needed let me know. I will make a tutorial for this if it works.

# Answer
Go to ICT's website to download the Installation manual (one used for many different models), there is info on the pinout for every pin on your model, along with recommended I/O interface circuit.

I am using a different model, but from what I know, if your model is a "Pulse" model, which means that when a bill is accepted, there are pulses that you can captured (the pulse width is pre-set by toggle switches, and the number of pulses depends on the value of the bill).

What I would do is to use interrupt to listen to these pulses. When the interrupt triggers, light up your LED.
> 1 votes

# Answer
So I know this is an old post, but I have interfaced with a BV20, and noticed most of the ICT validator's have a "busy" line that is asserted whenever the unit is transporting, validating, or storing/stacking a bill. If you want to light something up when a bill is being handled, but not necessarily validated, that might be what you are looking for.
> 0 votes

# Answer
ICT a6-15scp-usd4-ii is a pulse/parallel bill acceptor. Here is the datasheet, the link in the comments is broken. A6 version uses pulse/parallel protocol (V6 version is MDB). The 110V version that you use has only pulse protocol.

Take care with the wiring, the acceptor uses dangerous 110VAC voltage.

I understand you want to make same kind of pay per time device like those used in kiddie rides machines.

There are many examples on the internet on connecting a pulse bill acceptor to Arduino. The theory is simple the bill acceptor has a PULSE output, usually in negative logic, high in idle, that send a low pulse for each monetary unit, 1 for 1$, 5 for 5$ and so on.

Sometimes, like in your case, the bill acceptor has an enable input through which you can enable or disable the acceptance. But in A6 110V this input must be connected to hot 110v lines so it's harder to handle through Arduino so you will need to use a relay or to leave-it active all the time by setting dip SW 8 to ON, see page 6 and page 9 in the manual.

**The electrical connections.**

See the connector pinout , page 5

The credit (pulse) output uses an optocoupler so it has two lines CREDIT\_RELAY\_COM (pin 1) on the above connector that must be connected to Arduino GND and CREDIT\_RELAY(N.O.) (pin 16) that must be connected to the digital input of Arduino that read the pulses, this digital input must have a pull-up resistor to 5V, it might be the built in pull-up activated by using pinMode(PIN, INPUT\_PULLUP) but better an external resistor 1k to 4.5k.

And, of course, the main power supply , pin 4 and pin 20 to main 110 voltage and don't forget the earth ground, pin 21 for safety.

**Bill acceptor dip switch settings**

See the page 6 of the manual. For the moment just put SW8 to ON (acceptor enabled) and all other to OFF (all bills enabled, one pulse one dollar, 50ms/50ms pulses)

**The Arduino source code**

To count the pulses from a pulse bill acceptor or coin acceptor there are many examples on the internet but I did one myself, very easy to use, find the source code here, that counts the pulses in background using timer1 interrupt. In this way the main loop is free for other tasks you need. You can strip the LCD part of the code if you don't use.

To work with ICT A6 you need to modify the some defines in the code: PULSE\_WIDTH to 50 form 100 and PULSE\_DELTA to at least 4 from 2 (because it's to small).

Connect Arduino A0 input to pin 16 (CREDIT RELAY) and to a pull-up resistor to 5V as I pointed above, and Arduino GND to pin 1 (CREDIT\_RELAY\_COM) and power the Arduino from some different source or through USB and the example should work now. Obviously the BILL\_ACCEPTOR\_ENABLE and BILL\_ACCEPTOR\_DISABLE macros will not work the acceptor is always enabled.

To actually make-it work as pay-per-time machine a suggestion of code will look like this:

```
unsigned long finish_time = 0;
#define MS_PER_DOLLAR 600000 //10 minutes
//add to setup
turn_off_the_light();// Switch a pin or something

void loop(){
  unsigned long temp_millis;
  unsigned long temp_credits;
  temp_millis = millis()
  temp_credits = read_and_clear_pulses();
  if (finish_time < temp_millis) finish_time = temp_millis;
  finish_time += tempcredits * MS_PER_DOLLAR;
  if (finish_time > temp_millis)
     turn_on_the_light();
  else
     turn_off_the_light();
// Do something else
}

```

If you use the device uninterrupted for more than 49 days you will have the millis rollover issue but you can find examples on the internet how to handle this.
> 0 votes

---
Tags: arduino-uno, serial, programming, c++, led
---


# Question
Title: Does HC-05 module buffers the data received?
I am using HC-05 bluetooth module for sending large data(80-100KByte) from my phone to arduino-uno. I had found that this module has a flash chip of 8Mbit (SST39VF800A) but the datasheet of HC-05 has nothing about buffering of the data to be transmitted or data received. I need clarity about the buffering of data so that I can change the data rate from the phone for better communication.

# Answer
I didn't find any help in any data-sheets I could find, either. So I'd suggest a simple experiment, sending increasingly large packets before the other side attempts to read anything, until some data goes missing. The packets don't even need to be very sophisticated if all you want to know is whether N\_received == N\_sent and for what maximum 'N'.

Update:

> All bytes were received correctly if there is no delay but with increasing delay in reading from HC-05 data was not fully received and with delay greater than 800ms only 63Bytes were received.

If you're collecting data as it arrives, then you can't measure the buffering. When you wait until all data has been set before you try to read any, the number of bytes you receive is the buffer size. It sounds like a 63 byte buffer, probably only what the HC-05's hardware UART can buffer, without using any of its memory to increase that.
> 1 votes

---
Tags: arduino-uno, hc-05
---


title: Arduino nano as HID Keyboard

text:
# Question
Title: Arduino nano as HID Keyboard
I'm a bit of a noob in the Arduino area but I found an Arduino nano I bought a long time ago sitting on my shelf and collecting dust, so I taught "why not make a project". I game a lot of racing games so I wanted to make a simple ignition button with it, but every time I tried to compile or verify it, it says

> *Keyboard not found. Does your sketch include the line #include "Keyboard.h*"

# Answer
> 14 votes
Get yourself a Arduino Leonardo, Micro or Pro Micro (or Due, Zero, M0). Those can emulate a keyboard.
Start with reading the Arduino Keyboard Mouse reference.

The Arduino Nano can not use the Arduino Keyboard Mouse library.

Since many years, there is a library called "V-USB" that requires some extra hardware and makes it possible for a ATmega328p microcontroller to act as an USB device. It is not something for a beginner.

A few years ago, Arduino has changed the way the USB is used. The NicoHood HID library makes use of the new possibilities. It makes it possible for example to have extended features for a USB keyboard, like the media keys.

For a normal keyboard and mouse, the Arduino Keyboard Mouse library will do. It will be perfect for a ignition button. But you have to buy one of those boards (Leonardo, and so on).

# Answer
> 3 votes
The solution to get a board that has built in USB support is not preferred for someone who just wants to use the boards they already have. It is possible to use a board that can communicate with your computer over serial, such as the Arduino Nano, to send data to a Python program which can then turn the input from the Arduino into keyboard presses, etc. using libraries.

For this approach, you would need to know python. The libraries to use are:

pyserial - communication with Arduino

pynput - control the computer's keyboard

threading (comes with python) - allow pyserial and pynput to work simultaneously

---
Tags: arduino-nano, keyboard
---


title: Arduino while loop with or condition

text:
# Question
Title: Arduino while loop with or condition
How do I write a program to wait (delay) until one out of two buttons pressed? I have written a program to wait until a single button is pressed. It's working fine. However, if I extend it to second button it's not working. Pls help on this.

1. `while (digitalRead(bt_Select) == HIGH) {}` -- working.
2. `while (digitalRead(bt_Select) == HIGH || digitalRead(bt_Reject) == HIGH) {}` -- Not working.

Complete code:

```
const int bt_Select = 2;
const int bt_Reject = 3;

void setup() {
  Serial.begin(9600);
  pinMode(bt_Select, INPUT_PULLUP);
  pinMode(bt_Reject, INPUT_PULLUP);
}

void loop() {
  Serial.println("Pl input:");

  while (digitalRead(bt_Select) == HIGH {} // This is the line I change

  if (digitalRead(bt_Select) == LOW) {
    Serial.println("Select Button pressed:");
    delay(250);
    Serial.println("");
  }

  if (digitalRead(bt_Reject) == LOW) {
    Serial.println("Reject Button pressed:");
    delay(250);
    Serial.println("");
  }
}

```

# Answer
`while (digitalRead(bt_Select)==HIGH||digitalRead(bt_Reject)==HIGH){}`

should be

`while (digitalRead(bt_Select)==HIGH&&digitalRead(bt_Reject)==HIGH){}`

The first loop would break only if you press both buttons at once. I believe you are trying to break if either button is pressed.
> 0 votes

---
Tags: programming, arduino-ide, button
---


# Question
Title: Can't Turn Off Internal I2C Pull-Ups on ESP32
I've designed a custom ESP32 board around the WROVER-IE module. To keep power low, I'm using a GPIO-controlled high-side FET to turn off unused peripherals when in deep sleep mode.

The issue: I've pulled up an SSD1306 I2C OLED to this AUX rail. It works great when the device is awake. On setup() I start the OLED via ssd1306.begin() and from that point on, the SCL and SDA pins (22, 21) are always tied to 3.3V until I reset the ESP32.

The I2C bus always being tied to 3.3 ends up bleeding through the pull-up resistors and into the AUX rail, resulting unwanted current draw when in sleep mode.

Is there any way to turn off the internal I2C pullups on the ESP32?

Things I've tried so far:

* Setting SDA, SCL as OUTPUT and writing LOW (does not work)
* Setting SDA, SCL as INPUT and/or writing LOW (does nothing)
* Calling `gpio_hold_dis(gpio_num_t(SDA));`(does nothing)

I'm now trying to dissect the esp32-hal-i2c.c lib but am not finding any fixes. Any help is greatly appreciated!

Edit, added diagram:

-N

# Answer
I have solved this problem. For anyone who would like to turn off the internal pullups on the I2C bus of the ESP32, you need to disable the entire driver before putting the device to sleep.

First, include the peripheral driver library from the IDF:

```
#include "driver/periph_ctrl.h"

```

Next, call the following before sleep:

```
rtc_gpio_isolate(gpio_num_t(SDA));
rtc_gpio_isolate(gpio_num_t(SCL));
periph_module_disable(PERIPH_I2C0_MODULE);
digitalWrite(SDA, 0);
digitalWrite(SCL, 0);

```

This will stop the ESP32 from pulling up pins 21 and 22 while in deep sleep. Calling display.begin() or wire.begin() will restartthe driver upon wake.
> 4 votes

---
Tags: i2c, esp32, pins, pull-up, ssd1306
---


# Question
Title: Arduino Yun not getting response from Azure API
I posted this on StackOverflow but figured I'd post it here too. Sorry in advance if thats not allowed.

I'm trying to get my Arduino Yun to talk to an API that I'm hosting on Azure. I would like to do more complex things in the future, but at the moment I'm just trying to make a GET request over wifi with a single integer as a parameter.

I'm basically just using the example found here with the url changed. The example works fine, so as far as I'm aware the issue isn't with my board, its with the interaction with Azure.

HttpClient.get() returns an int as a response (not the regular HTTP response codes, its unique for the library). I got 60 initially, and changing my API to accept http calls (instead of just https) fixed this and made me get a response of 0 instead. 0 is the same response that I get from the working Arduino example, but for some reason I'm not actually getting anything in the body of my response, as the client.available() loop is never entered.

The API works as intended when I go to the url in chrome, so the issue arises somewhere due to how the arduino and azure talk to each other, but I don't know enough about either to figure it out and nowhere that I look seems to point me in the right direction.

Any help would be greatly appreciated, thanks.

# Answer
> 2 votes
Found the problem, even though I set azure to accept http requests, it was still redirecting to https which the arduino couldn't handle. I've written a python script to offload the requests to the linux processor, and now it works.

---
Tags: arduino-yun, web-service
---


# Question
Title: How do I get more than 64 characters of message from serial
I am trying to make a moving message board using an Arduino Uno, HC-05 Bluetooth module and DMD board. Sending message to the DMD through the Bluetooth module can only give a not more than 62 character message. I need help in what to do to get up to 200 or more. Thanks.

# Answer
First: There is no such concept of a message on the Serial bus, unless you implement it yourself. On hardware level only individual bytes are transmitted, and you don't even know, when each byte will be transmitted exactly. Since there are only individual bytes in the first place, there is no limitation on how many bytes can be transmitted.

Yes, the `Serial` library has a limited buffer of 64 bytes, but as Majenko wrote it is not intended for buffering all bytes for one of your messages. It should only buffer the bytes, until the main sketch can read them from the buffer. On reading the bytes will be removed from the buffer, leasing buffer space for new characters.

The buffer size of the `Serial` library can be increased by changing the numbers in `HardwareSerial.h` in the following lines

```
#define SERIAL_TX_BUFFER_SIZE 64

#define SERIAL_RX_BUFFER_SIZE 64

```

But this is not really the solution to your problem. When first filling the buffer and then read the whole message you just arbitrarly constrain yourself to a insufficient solution.

Instead of waiting for all the messages bytes (and finally filling up the buffer) you should steadily check, if new bytes are available and then load them into your own buffer. You can use a delimiter byte to mark the end of a message, mostly "\n" (newline character) is used for this. Copy the bytes into your own buffer, until you read the delimiter byte. Then use the message as a whole for your application. Don't forget to clear your buffer afterwards.

The examples for the `Serial` library, especially the `SerialEvent` example show how to do this in your code.
> 2 votes

# Answer
The software from the transmitter can break the text you want to send into pieces of 62 characters in length and send them one by one. The receiver will save the most recent piece in a String and join it with a another String which will be storing the whole message. If you don't mind it being a little bit slower, then this is the solution for you
> 1 votes

---
Tags: wireless
---


# Question
Title: I can't turn on the motor by Arduino IoT Cloud
I'm trying to turn ON/OFF a DC motor from Arduino Iot Cloud. I have to turn it ON/OFF physically and through the cloud, physically it works well but from the cloud it does nothing. I'm using an Arduino MKR WiFi 1010, a L298N Dual full bridge,9V DC motor and a push buttom. Mi circuit is like this

My code is this

```
#include "thingProperties.h"
#include <FTDebouncer.h>

#define MOTOR_PIN 2
#define BUTTON_PIN 5

FTDebouncer buttons;

void setup() {
  pinMode(MOTOR_PIN, OUTPUT);
  buttons.addPin(BUTTON_PIN, LOW);
  buttons.init();

  setDebugMessageLevel(2);
  Serial.begin(9600);
  delay(1500);
  // Defined in thingProperties.h
  initProperties();
  // Connect to Arduino IoT Cloud
  ArduinoCloud.begin(ArduinoIoTPreferredConnection);
}

void loop() {
  buttons.update();
  ArduinoCloud.update();
  onMotorChange();
}

void onPinActivated(int pinNr) {
  // do something according to the _pinNR that is triggered. For instance:
  Serial.println(pinNr);
  toggle = !toggle;
}

void onPinDeactivated(int pinNr) {
  // do something according to the _pinNR that is triggered. For instance:
  Serial.println(pinNr);
}
void onMotorChange() {
  digitalWrite(MOTOR_PIN, toggle || motor);
  Serial.print("The motor is ");
  if (toggle) {
    Serial.println("ON");
  }
}

```

I tried with a LED and it worked very well, but with the motor doesn't. This is the code that Arduino creates when I add things to the board, the part of

> thingProperties.h

```
// Code generated by Arduino IoT Cloud, DO NOT EDIT.
#include <ArduinoIoTCloud.h>
#include <Arduino_ConnectionHandler.h>

// x-ed id
const char THING_ID[] = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

const char SSID[]     = SECRET_SSID;    // Network SSID (name)
const char PASS[]     = SECRET_PASS;    // Network password (use for WPA, or
use as
key for WEP)

void onMotorChange();

bool toggle;
bool motor;

void initProperties(){

ArduinoCloud.setThingId(THING_ID);
ArduinoCloud.addProperty(toggle, READ, ON_CHANGE, NULL);
ArduinoCloud.addProperty(motor, READWRITE, ON_CHANGE, onMotorChange);

}

WiFiConnectionHandler ArduinoIoTPreferredConnection(SSID, PASS);

```

Thanks for the help and suggestions. How should I connect the motor or what do I have to change in the code?

# Answer
The following code is an example. As I don't know the Arduino Cloud Thing configuration, and I don't have access to the cloud and the Hardware, the programm is just a guess making some commented assumptions.

There are many assuptions I made, and I can not rely on the schematics you showed me. Eventually you have to redesign the circuit/hardware setup. A L298N is a so called H-Bridge. That needs at least two control pins in1 and in2 connected to arduino outputs to define the direction of the motor. You only connected one of them to an output of the arduino. And one of them to the button and an input of the arduino. (If that part of the schematics is correct.)

If you press the button in1 gets HIGH but the in2 may also get HIGH because your program switches the motor pin to HIGH. That turns the motor off. If one pin is HIGH the other must be LOW to drive the motor. Some L298N modules also need a PWM signal at the enA pin. That sets the speed of the motor with the duty cycle of the PWA signal. Most modules have a pullup at enA and enB so per default the motors are configured for full speed.

```
#include "thingProperties.h"
#include <FTDebouncer.h>

#define MOTOR_PIN 2
#define BUTTON_PIN 5

FTDebouncer buttons;

void setup()
{
  pinMode(MOTOR_PIN, OUTPUT);

  // !!! PPK: Handler methods added
  buttons.addPin(BUTTON_PIN, LOW, onPinActivated, onPinDeactivated);

  buttons.init();

  setDebugMessageLevel(2);
  Serial.begin(9600);
  delay(1500);
  // Defined in thingProperties.h
  initProperties();
  // Connect to Arduino IoT Cloud
  ArduinoCloud.begin(ArduinoIoTPreferredConnection);
}

void loop()
{
  buttons.update();
  ArduinoCloud.update();
}

void onPinActivated(int pinNr)
{
  if ( pinNr == BUTTON_PIN )
  {
     toggle = !toggle;
     // this assumes that the toggle triggers a change for
     // the motor variable in arduino cloud. If not,
     // the motor variable will not be changed and my code does not work.
     // uncommenting the following line may help, in that case
     // motor = toggle;
  }
}

void onPinDeactivated(int pinNr)
{
  // Intentionally left empty, we only react to the rising edge.
}

void onMotorChange()
{
  digitalWrite( MOTOR_PIN, motor );
  Serial.print("The motor is ");
  if ( motor )
  {
    Serial.println("ON");
  }
  else
  {
    Serial.println("OFF");
  }
}

```
> 1 votes

---
Tags: arduino-ide, iot, mkr1010
---


# Question
Title: Arduino Mega Clone CH340G Capacitor Values
I'm making my own Arduino Mega board with ATmega2560-16AU and CH340G. Jump to the end of the post to find the real question.

I have already ordered a PCB before and it didn't work when I soldered everything in place. I have already asked why that board didn't work on another post here: Programming custom Arduino Mega with Arduino Uno

But I was not satisfied with the answers and started suspecting whether or not the capacitor values were right on my board.

I'm trying to make my own version of RobotDyn's Arduino Mega 2560 Pro so I tried taking the already programmed ch340g and soldering it on my own board and still failed. When I put a previously not programmed ch340g on the RobotDyn board and programmed it using Arduino UNO (Arduino as ISP) the board would work.

So now I ordered a new PCB but haven't ordered any of the passive components yet.

**If any of you could tell me where I could find the values from the schematic below I would really appreciate that.**

https://robotdyn.com/pub/media/0G-00005641==MEGA-PRO-CH340GATmega2560/DOCS/Schematic==0G-00005641==MEGA-PRO-CH340GATmega2560.pdf

# Answer
The values can be easy found for generic CH340g and ATmega2560 implementations:

C1,C2 = 100nF, C3,C4 = 22pf but depends on the crystal you use, all others excepting C12 are decoupling capacitors.

C12 has no sense where it's placed, it seems that the schematic is a bad combination of schematics, this capacitor should reset the board at power on but it breaks the reset pulse from CH340g so you cannot program the board without pressing manually the reset pushbutton. Don't place C12 at all.

Also place a short instead of R5 and R6 that are not in the CH340g manual (there is a special mention to connect the pins straight to USB bus), remove R8, is not needed for the same reason, R3 makes no sense, don't place-it.

R2,R4 = 1K, R7,R9 = 10K, R10,R11,R12,R13 = 1K, R14 = 10K , R15 = 1M.

Y1 = 12Mhz, Y2 = 16Mhz

A 22 ohm resistor is missing in your schematic between Y2 XTAL1 and ATMEGA XTAL2 but I don't think it's important.

I hope I didn't missed something

The bare minimum is to remove c12 and maybe R3 and check the values you used for R2, R4 against the above values.

If something would be wrong with CH340g the USB connection would fail but I see no mention about that in your post.
> 2 votes

---
Tags: arduino-mega, programming, bootloader, resistor, capacitors
---


# Question
Title: How can I read the data stored in EEPROM although is powered OFF based on the simple code I wrote?
I need help regarding on EEPROM library. Based on the code below, for every 2 sec, I want to store the int for `increase` where it will keep increasing by 1. Then, I upload to my Arduino Nano and open Serial Monitor to let it run for about 20 seconds. The serial monitor shows that `Increase Count:10`.

Then I unplug the Arduino Nano, closed the Serial Monitor, wait for 5 sec, then plug back to computer and turn on the Serial Monitor, then the Serial Monitor start to shows `Increase Count:1`, which indicated it start to recount again from 1,2,3,4.....

I thought that EEPROM will store the last number it counted which is 10, then when I unplug and plug back it should continue to count from 10, 11, 12, .......

So I would like to ask community whether my execution code and the method is correct or not. If not, can you advice me on how I can execute it correctly. Thank you in advance!

```
#include <EEPROM.h>

int addr=5;
int storagedata;
int increase;

void setup()
{
  storagedata=EEPROM.read(addr);
  Serial.begin(9600);

  timevalue=millis();
}

void loop()
{
  if (millis()-timevalue>=2000)
  {
    increase=increase+1;

    EEPROM.update(addr,increase);
    storagedata=EEPROM.read(addr);

    Serial.print("Increase Count:");
    Serial.println(storagedata);

    timevalue=millis();
  }
}

```

# Answer
> 7 votes
`increase` is a global variable and will implicitly initialized with the value zero. Then you are reading the EEPROM data into the variable `storagedata` in `setup()`. And then in `loop()` you are increasing `increase` from zero to one and write that to EEPROM. This value then gets read back into `storagedata`. So now `increase` and `storagedata` have the same value: one. So the counting begins on every reset at 1.

It is unclear, why you even have 2 variables for this. One would be enough (unless you want to test the EEPROM for some reason). **In `setup()` read the data into `increase`.** Then the counting starts with the number in EEPROM.

# Answer
> 5 votes
The problem is that you fail to initialize `increase` during `setup()`. The variable is undefined when the code enters the `loop()` function, even regardless of whether this is the first boot or not. You should change `storagedata` to a local variable in loop() and use `increase` to keep the value (or vice versa).

# Answer
> 0 votes
You never use the value you read in `setup()`. Go through your `loop()` function one line at a time:

```
// this does not use the value read in setup, variables are initialized to 0
// so the first time through this loop it will set 'increase' to 1
increase=increase+1;

// you are updating EEPROM with the value of 'increase' which is 1 the first
// time this is executed
EEPROM.update(addr,increase);

// you are reading the '1' that was just written into 'storagedata', you have
// never used the value you read in 'setup()' and have now overwritten it
storagedata=EEPROM.read(addr);

```

I'm not sure why you have two separate variables, but in `setup()` you just need to initialize `increase` as the value read from EEPROM:

```
storagedata=EEPROM.read(addr);
increase=storagedata; // start with stored value instead of default 0

```

---
Tags: arduino-uno, eeprom
---


# Question
Title: Why does a pull down resistor configuration not destroy the pin it's connected to?
I don't understand why a pull-down resistor connected to ground would prevent a pin connected to 5V through a button would not destroy the pin as the current does not need to go through the resistor to get to the pin. I've tried looking online but the question was never asked and I couldn't find any information that explained how it works.

I'm asking this in the context of something without internal resistors so it would have no protection against a short circuit/being connected straight to a source.

# Answer
> 5 votes
When you have a pin in INPUT mode it is *high impedance*. That means that to all intents and purposes, to the outside world, the pin is not connected to anything internally.

In reality it is, but that internal connection is of such a *high impedance* (i.e., resistance) that it is almost equivalent to an open circuit.

It's simplest to think of an input pin as a voltmeter. A pulldown resistor and button would look like this:

simulate this circuit – Schematic created using CircuitLab

When the button is opened the voltmeter reads zero, because one end is connected to ground, and the other end is connected to ground through the resistor.

However when you press the button the voltmeter reads the voltage across the resistor - that is, 5V - because one end is connected to ground and the other to 5V, with a resistor across it.

If you don't have the resistor then the voltmeter can't measure anything when the button isn't pressed - it's just waving around in the air without a clue what it's doing - and a wire waving around in the air is called an antenna...

The Arduino is that voltmeter. All it does is detect the voltage at the pin, it doesn't conduct any (or only a very very tiny amount of leakage) current through the pin.

Now the possibility of a short circuit comes when you set the pin to OUTPUT. If you drive the pin LOW then the pin is essentially connected to GND, and pressing the button will connect the 5V straight to GND through the LOW-driven IO pin.

# Answer
> 0 votes
A pullup or pulldown *wire* would destroy the pin because it would source or sink enough current to burn out the pin driver. But a pullup or pulldown *resistor* limits the current to a very small value (I = E/R = 5v/10000Ohm = .0005A or .5 ma, well within the pin driver's 20 ma limit.

---
Tags: resistor
---


title: Which one is IR led?

text:
# Question
Title: Which one is IR led?
I've ever been so confused in my life. I'm new to Arduino and electronics but I just can't figure it out which diode is IR transmitter/receiver or even if it is IR. I know that IR is not visible to human eye but I'm really clueless and I need help distinguishing them. I think the black one is a receiver but when I connect the white/transparent one it lights up so I guess It's not IR diode, right? How do I test them to see it anyways?

# Answer
If you connect one of these and you can see it light up with your naked eye then it is not an IR LED, it's a visible-light LED. It's also not an IR sensor.

If you want to see IR, point a digital camera (like in your phone) at it and apply power. The sensors in digital cameras almost always detect some IR, so you can see a faint light on the screen. To test this, point your phone at a TV remote and press the button. If you see a flashing light in your phone's screen, you know it can "see" IR (Most digital cameras have an IR filter to get rid of most of the IR going into the camera, but they generally allow enough IR through that if you point them directly at an IR LED you can usually see it, at least faintly.)

Note that you should be able to use a visible light LED as a light source for an IR photoresistor/photodiode/phototransistor, since visible light LEDs will also give off some IR. However, an IR LED will put out a WHOLE LOT more IR than a visible light LED at of the same power.

The black one is probably an IR receiver. The color of the lens probably blocks visible light but not IR.

All the IR LEDs I've seen have looked clear, but I could not see any visible light when I powered them up.
> 2 votes

# Answer
The dark coloured one is an IR photodiode. Osram SFH203-FA

Hope that hemps.

:)
> 1 votes

---
Tags: led, ir, infrared
---


title: NodeMCU and SDS011

text:
# Question
Title: NodeMCU and SDS011
today I connected the SDS011 to NodeMCU. I noticed that this only works when the sensor is connected to the voltage VU. If I connect the sensor to another pin for the voltage, it does not respond. Why is this so?

If I see it correctly, the reason must be that data is exchanged via RX and TX.

```
#include "SdsDustSensor.h"

int rxPin = 5; //d1
int txPin = 4; //d2
SdsDustSensor sds(rxPin, txPin);

void setup(){
  Serial.begin(9600);
  sds.begin();
  sds.setCustomWorkingPeriod(0);

}

void loop(){
PmResult pm = sds.readPm();
  if (pm.isOk()) {
     Serial.println(pm.pm25);
     Serial.println(pm.pm10);
  }

  delay(250);

}

```

# Answer
> 1 votes
The SDS011 needs 5 V powering and the VU pin is the 5 V from USB on the NodeMCU development board.

---
Tags: esp8266, sensors, nodemcu, softwareserial
---


title: Deactivate pushbuttons at initial stage

text:
# Question
Title: Deactivate pushbuttons at initial stage
Pl someone answer my question. I have 4 pushbuttons namely add/reject/start & finish. I want to

1.Deactivate add/reject buttons at initial stage until start button pressed & 2.Once add/reject activated, again should deactivate once finish button pressed & 3.Again if start button pressed, add/reject should be released.

with following code I able to do 2 & 3. However I still lack at 1.pl help on this.

```
const int bt_Select = 2; // #define BUTTON_PIN 2
const int bt_Reject = 3;
const int bt_Start = 7;
const int bt_Finish = 8;

boolean decision=false;

int bt_Select_state=0;
int bt_Reject_state=0;
int bt_Start_state;
int bt_Finish_state;

int selected;
int rejected;
int started;
int finished;

void setup() {
  // put your setup code here, to run once:
    Serial.begin(9600);
    pinMode(bt_Select, INPUT_PULLUP);
    pinMode(bt_Reject, INPUT_PULLUP);
    pinMode(bt_Finish, INPUT_PULLUP);
    pinMode(bt_Start, INPUT_PULLUP);
    Serial.println("Welcome to Nano");
    delay(1000);
  }
//========================================================================
      void loop() {

        started=bt_Start_pressed();
        selected =bt_Select_pressed();
        rejected=bt_Reject_pressed();
        finished=bt_Finish_pressed();
        decision=Stop_Main();

          int x=0;
          int Lx=0;

       if (selected&&decision){x=1;}
       if (rejected&&decision){x=2;}
        if (started&&decision){x=3;}

       if (x!=Lx){
        switch(x) {
          case 1:Serial.println("Selected");delay(250);Serial.print("");
                 break;
          case 2:Serial.println("Rejected");delay(250);Serial.print("");
                 break;
          case 3:Serial.println("Started");delay(250);Serial.print("");
                 break;

          /*case 3://do something when var equals 1
                 Serial.println("Removed");
                 break; */
             }//switch(x)
                 x=Lx;
      }//eof  if (x!=Lx)

      }
//====================================================================
      int bt_Select_pressed(){
         bt_Select_state=digitalRead(bt_Select);
           if (bt_Select_state == LOW){return 1;}
           else {return 0;}
      }
//====================================================================
      int bt_Reject_pressed(){
         bt_Reject_state=digitalRead(bt_Reject);
          if (bt_Reject_state == LOW){return 1;}
          else {return 0;}
           }
//====================================================================
    int bt_Start_pressed(){
         bt_Start_state=digitalRead(bt_Start);
          if (bt_Start_state == LOW){return 1;}
          else{return 0;}
            }
//====================================================================
      int bt_Finish_pressed(){
        bt_Finish_state=digitalRead(bt_Finish);
          if (bt_Finish_state == LOW){return 1;}
          else {return 0;}
      }
//=====================================================================

      boolean Stop_Main(){
        bt_Start_state=digitalRead(bt_Start);
        bt_Finish_state=digitalRead(bt_Finish);

        if (bt_Finish_state == LOW){decision=false;return decision;}
        if (bt_Start_state == LOW){decision=true; return decision;}

       // else if (bt_Start_state ==HIGH  && bt_Finish_state == HIGH){decision=false;return decision;}
          }

/*  boolean bt_Start_pressed(){
         bt_Start_state=digitalRead(bt_Start);
          if (bt_Start_state == LOW){started=true; return decision;}
          else{started=false; return decision;}
            }   */
    //===================

```

# Answer
> 1 votes
Keep a boolean that begins as `false`. Set it to `true` when the start button is pressed, and set it to `false` again when the finish button is pressed. Then you can read and respond to the `add` and `reject` buttons only if that boolean is `true`, and otherwise ignore them.

---
Tags: arduino-uno, arduino-mega, programming, arduino-ide
---


title: Detect if a display is connected

text:
# Question
Title: Detect if a display is connected
I want to detect wether a display is connected or not. This is the display: https://www.az-delivery.de/en/products/1-77-zoll-spi-tft-display

I read connecting a pin of the display with another pin with a pull up resistors. Unfortunetely nothing worked so far.

My microcontroller board is Arduino Mega.

# Answer
There is nothing immediately apparent on that display that can tell you if it's connected or not. If you had a full SPI interface (you are missing the MISO pin) you could query the display for the HWID, but alas not. And there's no pins at all that are outputs.

The only suggestion I can come up with is to connect a small (say 1Ω) resistor between the Arduino's 5V pin and the display's VCC / LEDA pins and use an analogue input to measure the voltage on the display side of it. When the display is disconnected it will give a 5V reading. When it's connected the reading will drop to a slightly lower voltage (depending on the current draw).

Schematic:

simulate this circuit – Schematic created using CircuitLab
> 0 votes

# Answer
As jsotola mentioned in his comment, pin 1 and pin 14 on the display are connected to each other (GND). You can connect pin 14 to an input pin with enabled INPUT\_PULLUP. If no display is connected, this pin will be pulled high by the pullup, thus the pin will read high. If the display is connected, the pin will read low.
> 2 votes

---
Tags: arduino-mega, display, pull-up
---


# Question
Title: Connect multiple Arduinos to ESP32's RTC?
> Depending on usage frequency, may get the occasional collision where both test for availability at the same time - if occurring too frequently, maybe add something simple like one arduino only does time updates on even seconds, the other on odd seconds.

https://forum.arduino.cc/index.php?topic=64049.0

I need events executed in the multiple receiving Arduino's to occur in sync (simultaneously). Is there a library or something, probably using the ESP32's RTC, to ensure events occur in sync?

Example system:

* ESP32 sender/master
* Arduino1 receiver controlling LEDs (Christmas lights)
* Arduino2 receiver controlling stepper motors (Mary figure)
* Arduino3 receiver controlling stepper motors (Joseph figure)

The issue is that they are sent data at different times by the user.

Say, the user selects settings for Mary. That data is sent to the ESP32, and then that data is sent to all the Arduinos, but only "gets into" the MaryArduino.

Then, the user selects settings for the lights. That data is sent to the ESP32, and then data is sent to all the Arduinos, but only "gets into the LightsAruino.

Etc.

However, I need everything to start at the same time.

The data is not simultaneously sent. It is sent one after the other, as slow as the user selects their settings. However, the sequence of events must simultaneously occur.

# Answer
Give the master a single signal wire that is connected to all of the slaves and that signal LOW while the master sends commands to each slave. Let each of the slave Arduinos simply store its message but not act on it while the signal wire is LOW.

When the slaves are supposed to start, raise the signal level to HIGH. Each slave Arduino now executes whatever command it had been sent. The RTC now only needs to be connected to the Master, which controls all of the timing.
> 1 votes

---
Tags: esp8266, esp32, rtc
---


title: Arduino IRremote stops working

text:
# Question
Title: Arduino IRremote stops working
I'm using a standard 38kHz receiver with Arduino-IRremote library and it works fine for a while but then it stops working. The loop function is running time after time as expected but at some point the library decode function starts returning false until I reset the board.

This example code works for me with any arduino nano or bare atmega328p at 8Mhz but for both of them it freezes after some receptions.

The code is the library example itself:

```
#include <IRremote.h>

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value
  }
  delay(100);
}

```

Some times this happens fast and other times it is after 20 or more receptions. I only added a led blink later to test if the board is frozen or is only the infrared that stops receiving and it was the second case.

# Answer
> 2 votes
I was having similar problem (but not the same ) And it was due to software serial pins which keep on filling the buffers of MCU.

Some times it happen that pwm pins keep on receiving data e.g. GPS also keep filling the buffer and due to that arduino freeze .

To solve this problem I open new dummy software serial port.( select any pins which is free ) and do listen to your software serial pins when you want to read it otherwise make dummy listen.

# Answer
> 1 votes
Arduino tutorials I've seen don't mention it but the datasheets from the ir receptors manufacturers advice to stabilize vcc with a resistor and a capacitor.

It seems without that the receptor fail to correctly report the received wave so the library may decode it wrong. In my case the problem started to happen when I added RGB leds controlled by PWM on the same (stabilized) power supply.

# Answer
> 0 votes
In short: The IRremote Library has bugs that lead to unresponsiveness of the board. There were some updates and now IRremote.h library 3.01 runs about a day with a FastLED.h WS1211 led stripe connected to it.

My approach to make it run reliable more than 24h with the latest library you could connect a digital pin to the reset pin on the Arduino. Then use `EVERY_N_HOURS` to occasionally pull that pin low.

The Software reset via timer (watchdog timer library) every 2 seconds f.e. worked occasionally but not reliable.

That should even make every 2USD board clone run as reliable as it could/hardware allows it.

Have fun :)

---
Tags: arduino-uno, library, arduino-nano, ir, remote-control
---


# Question
Title: What is the highest baud rate that can work between Android device and an Arduino connected to an HC05?
I see a lot of baud rates in the AT Command documentation for the HC05 however I am not sure what is the fastest that can work between the Arduino controlled embedded system and the Android phone. I also do not know of a way to change the baud rate of the Bluetooth communication in software. I am writing the application in Java with Android Studio IDE.

I read the documentation for HC05 and realize that it only operates with one Bluetooth profile. i.e the Serial Port Profile. The documentation says that this profile offers a maximum data-rate of 128000 bits/sec. However, the HC05 has a max baud rate option of 1382400 bits/sec. Why would this option be there if it is not possible to use? Can you please explain what I am missing and point me into the direction of some useful information? Thank you.

# Answer
The HC-05 may only have implemented baud rates up to 1382400, even though the protocol is spec'd for up to 128000.

If you're using Software Serial to talk to the HC-05 from an Uno, 9600 baud is about as fast as SoftwareSerial can keep up with incoming bytes (I've heard from some people that 19200 will work).

If you're using one of the UARTs on a Mega, you may be able to use the full rate implemented by the HC-05. An experiment would be in order...

Update:

> I did an experiment and found out that the maximum baud rate achievable between the HC05 (communicated with by SoftwareSerial on Arduino Nano) and the Android device is 115200.

I would guess you were transmitting from the Arduino? I've been able to transmit that fast with SoftwareSerial but its receiving ability is more limited. (This has enabled me to, f/ex, set an HC-05 or an ESP8266 to a slower baud-rate than it shipped with, by blindly transmitting an appropriate 'AT' command at the higher speed, then testing it at my intended speed to see if the command worked).
> 1 votes

---
Tags: serial, bluetooth, android, java
---


# Question
Title: Ardutester Millenium I2c Lcd Not Showing Anything!
Hiii Friends...., I am Trying to Build Components tester Using Arduino Specifically Atmega328p Chip . I Downloaded The Ardutester Millenium Code From Here .. https://create.arduino.cc/projecthub/plouc68000/ardutester-millenium-the-ultimate-uno-mega-versions-c81db4

Edited Makefile.h By Enabling i2c lcd Interface And Adding My I2c Lcd Adress ... But it wont work

I tried On Uno And Mega Also Serial Monitor Output seems ok But It Doesnt Display anything on 16\*2 lcd

Thanks ...... :)

Code is available at that page sir... Thanks for your reply

# Answer
The schematic you posted is not for I2C. You have a connection to the regular 2x16 LCD character display. For the I2C an SSD1306.
> 1 votes

---
Tags: arduino-uno, arduino-ide, atmega328, testing
---


# Question
Title: Is there a Arduino UI library that provides dialog box and button functionality at a minimum?
I have been looking at the Arduino TFT Library and it supports all the bits and pieces for making a simple display, but I am looking for something a little higher level that has primitive dialog box and button capability, and presumably, the ability to layer the display so I can push and pop display elements. Is there a higher level GUI library for Arduino TFT displays?

# Answer
> 1 votes
Take a look at this library. Will this do all that you want?

https://github.com/AndreiDegtiarev/AWind

I have not tried it yet but I would like to.

Edit:

I just remembered this https://github.com/ImpulseAdventure/GUIslice https://github.com/ImpulseAdventure/GUIslice/wiki

A lightweight GUI framework for embedded displays

The library supports creation of multiple pages of buttons, text, images, checkboxes, sliders and other graphics primitives. New UI / widget types can be created easily.

It works with many existing TFT libraries. There also is a drag & drop builder application. https://github.com/ImpulseAdventure/GUIslice-Builder

---
Tags: tft, ui
---


title: Rotating Servo Motor using Arduino

text:
# Question
Title: Rotating Servo Motor using Arduino
Using arduino, I'm trying to rotate a 360 servo that will move clockwise 5 seconds,pause and counterclockwise for 5 seconds and then completely stop. However, my servo just continuously keeps on rotating in one direction. Any suggestions will be helpful

# Answer
> 1 votes
you have not put your code here so i can not understand it properly.From what i understand you must have put your code for rotating the servo motor 5 times in void loop. Don't do that put loop for rotating servo 5 time in setup.

void loop run continuously so it must be rotating 5 time then again 5 time and so on.

---
Tags: arduino-uno, c++, servo, pwm, loop
---


title: Change character sequence

text:
# Question
Title: Change character sequence
I turn on the transmission of one key that works to open the door, but after a certain time I need to close the door, and for this I need to use the second key. I want to do without additional buttons, so it is required to emit key 1 when power is applied, and after 20 seconds, for example, switch and emit key 2. What is the most simple and correct way to do this? Apply a timer or emit key 1, for example 1000 times, and after overflow 1000, start emitting key 2.

This sketch only constantly sends the first key to the digital pin, without switching to the second. You need to figure out how you can switch to the second key.

```
const int KEY_LEN = 54; //Number of characters in the key
const char key1[KEY_LEN] = {"SSSSSS001101001001110001000000000000000000000011001010"}; // Open
const char key2[KEY_LEN] = {"SSSSSS001010111010000000000001000000000000010000000000"}; // Close

int Preamble = 1000; // Preamble duration in microseconds
int zero= 200; // Duration of zero in microseconds
int One= 440; // Duration of a unit in microseconds

const int LED_PIN = 13; // Used digital pin 13 of the arduino to connect the transmitter
void setup()
{
  pinMode(13, OUTPUT);
}

void loop()
{

    for (int n = 0; n < KEY_LEN; n++)
    {
      if (key1[n] == '1') //execute if bit value == 1
      {
        sendSignal(One);
      }

      else if (key1[n] == '0')//execute if bit value == 0
      {
        sendSignal(zero);
      }
      else
      {
        sendSignal(Preamble); // Стартовый импульс
      }

    }
  }

void sendSignal(int duration)
{
  digitalWrite(LED_PIN, HIGH);
  delayMicroseconds(duration);
  digitalWrite(LED_PIN, LOW);
  delayMicroseconds(duration);
}

```

# Answer
> 2 votes
I usually recommend against using `delay()`s, but if this system will only ever have to do what you've described, using `delay()`s is the simplest way to implement it.

I would suggest sending key-1, possibly several times, maybe a half second apart, delay for the 20 seconds you suggested, then send key-2, *definitely* several times for security.

---
Tags: pwm, code-optimization, keyboard
---


# Question
Title: Programming custom Arduino Mega with Arduino Uno
I'm making a custom board with AtMega2560-16AU as MCU and CH340G as bootloader (schematic can be seen in the picture). I have printed the custom PCB and soldered everything in place now I want to program the bootloader.

I connected my Arduino UNO with my custom board like shown in the fritzing schematic below. My custom pcb doesn't look like Arduino MEGA but the connections are the same.

I go to Arduino IDE and upload the ArduinoISP example (baudrate:115200) while choosing programmer as "Arduino as ISP".

And when I upload the example I get a response like this:

```
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 3
         Firmware Version: 4.4
         Vtarget         : 0.3 V
         Varef           : 0.3 V
         Oscillator      : 28.800 kHz
         SCK period      : 3.3 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: reading input file "C:\Users\ahmet\AppData\Local\Temp\arduino_build_251950/ArduinoISP.ino.hex"
avrdude: writing flash (4354 bytes):

Writing | ################################################## | 100% 0.68s

avrdude: 4354 bytes of flash written
avrdude: verifying flash memory against C:\Users\ahmet\AppData\Local\Temp\arduino_build_251950/ArduinoISP.ino.hex:
avrdude: load data flash data from input file C:\Users\ahmet\AppData\Local\Temp\arduino_build_251950/ArduinoISP.ino.hex:
avrdude: input file C:\Users\ahmet\AppData\Local\Temp\arduino_build_251950/ArduinoISP.ino.hex contains 4354 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.53s

avrdude: verifying ...
avrdude: 4354 bytes of flash verified

avrdude done.  Thank you.

```

As far as I know so far there's no problem.

And now I move to step 2 which now requires me to switch the board to ArduinoMega from tools. And click burn bootloader.

When I click burn bootloader I get a response like this:

```
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf"

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

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

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0xffffff (probably .avr8x_mega) (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Error while burning bootloader.
Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

```

Now when I clicked burn the bootloader I got a response saying invalid signature. So far I tried to:

1. Change baudrates and try the same steps.
2. Tried to change the avrdude.txt file. I tried to change the signature that was searched for which I couldn't change it because windows 10 wouldn't allow me even though I gave myself all the admin permissions.

So as a solution to this signature problem people have put an electrolytic capacitor that has 10nF or 10uF value between GND and RST pins of the programmer Arduino.

Also when I tried this for the first time I got a value different than "Off" for oscillator in the 2nd step.

So what should I do? Do I need to change my oscillator and try again or do I need that polarized 10uF capacitor?

Sorry for poorly formatting this post. Thank you so much for reading. Any answers would be appreciated.

# Answer
> 1 votes
I finally found the problem with this board. I had a 22pF capacitor between RST and GND on the board I had ordered.

You should not have a capacitor there or it should be 100nF, values such as 22pF or 10nF will cause the board to malfunction and therefore you can't burn the bootloader.

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