# Question
Title: Why doesn't Serial.read() read multiple character?
I used multiple of Serial.read() and Serial.parseInt() to get characters and a number ( like "xy123" ) on an Arduino UNO. Then I checked the result on Serial monitor.

Unfortunately I couldn't get the character with second Serial.read().

Here's the code:

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

void loop(){
  if (Serial.available() >0) {

    // I want to reacive the characters like "xy123"
    char input1 = Serial.read();
    char input2 = Serial.read();
    int value = Serial.parseInt();

    Serial.println(input1); // ok
    Serial.println(input2); // * no good * (-1)
    Serial.println(value);  // ok

    // Writing some codes with input1 ,input2 and value ...
  }
// I don't want to use delay().
}

```

How do I get the second character?

Thanks.

# Answer
```
  if (Serial.available() >0) {

```

This is like saying "I won't go into that room until there is at least one dog in there". Someone tells you there is a dog there. You go into the room and say "Hey, why aren't there **two** dogs there?".

If you want to read two bytes one approach is to wait until they are available:

```
  if (Serial.available() >= 2) {

```
> 3 votes

# Answer
You did not read the second character, because the character did not arrive yet. Wait until it is available. `read` doesn't wait. `parseInt` has the waiting build-in.

You can wait for the second character by reading the two characters with the waiting function `readBytes`. It will wait a second for the next character.

```
char buff[2];
if (Serial.readBytes(buff, 2) == 2) {
  char input1 = buff[0];
  char input2 = buff[1];
...

```

If you send only one character, readBytes will wait one second for the next and the returns that one char was read.
> 2 votes

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


# Question
Title: How to install your own library with Arduino IDE 1.8.5?
I'm struggling a bit with Arduino language + its IDE not being 100% real C++. I wrote my own I2C library for a sensor but can't get the IDE's compiler to recognise it. I'm using Ubuntu 18.04.

I get `no such file or directory` for all of these things I've tried:

* Include the `.h` file by absolute and relative path in the `.ino` code
* Put `.cpp` \+ `.h` files in ~/Arduino/libraries
* Put `.cpp` \+ `.h` files in ~/sketchbook/libraries
* Put `.cpp` \+ `.h` files in ~/sketchbook/libraries/mylibrary
* Put `.cpp` \+ `.h` files in ~/sketchbook/libraries/mylibrary and try to "install" the library in the IDE (Sketch -\> Include library -\> Manage libraries; it's not listed)

I'm following the official guide here. Any ideas on how to get the compiler to recognise my library?

# Answer
> 3 votes
You need to:

1. Create the folder ~/Arduino/libraries/MyLibrary
2. Place the library files in there named as:
    * ~/Arduino/libraries/MyLibrary/MyLibrary.h
    * ~/Arduino/libraries/MyLibrary/MyLibrary.cpp
3. **Restart the IDE if it is running**
4. Use `#include <MyLibrary.h>` in your sketch

This is assuming your sketchbook is set to ~/Arduino - change that to wherever the sketchbook is set to (check in Preferences for that location).

Note that in Linux capitalisation is *important*. The filesystem is case sensitive, and the name of your folder should have the same name and capitalisation as the name of your header file.

---
Tags: arduino-ide, library
---


title: 1.54 e-ink without driver

text:
# Question
Title: 1.54 e-ink without driver
i wan’t to know if is possible to use this raw e-ink display with arduino. if it’s possible to directly connect cables from this ribbon cable to arduino without any driver pcb and control it with 3 or 4 wire SPI. the pinout of the display is on the 6th page

# Answer
Kind of yes and kind of no.

It requires external circuitry, but that circuitry isn't a "driver board" in the traditional sense.

An e-Ink display requires high voltages to charge the electrostatic cells. Traditionally that would be provided using an external "driver" circuit - a *boost* voltage converter.

However this display has that boost converter built in - though it doesn't have *all* the components, because they just won't fit.

You need to provide the diodes, switching MOSFET, and inductor, etc as shown on page 18 of the datasheet. Nothing less will do.
> 1 votes

---
Tags: spi, display, wires
---


# Question
Title: Arduino - Calculating the time for which a Pushbutton is pressed and held without being released
I'm working on a project that requires calculating the time for which a pushbutton is kept pressed without being released. Is there a code snippet that i can use for this particular need ?

# Answer
There is a library called "Debounce", which you can find here: playground.arduino.cc. Based on that library, here is a simple sketch that displays the amount of time a button is pressed.

```
// Connect one end of a N.O. push button switch to GND and the other
// end to pin 4 of the Arduino.
// NOTE: If the button is held down for less than the debounce delay
//       time, the elapsed time will display the debounce delay time.
#include <Debounce.h>
const byte SWITCH = 4;
unsigned long startTime = 0;
unsigned long endTime = 0;
unsigned long elapsedTime = 0;
const byte debounceDelayTime = 50;

Debounce debouncer = Debounce(debounceDelayTime, SWITCH);

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

void loop(){
  if(debouncer.update()){
    if(debouncer.read() == 0){
      startTime = millis();
      Serial.println("Button Pressed");
    }
    else if(debouncer.read() == 1){
      endTime = millis();
      Serial.println("Button Released");
      elapsedTime = endTime - startTime;
      Serial.print("Button Held Down For ");
      Serial.print(elapsedTime);
      Serial.println(" ms.");
    }
  }
}

```
> 1 votes

---
Tags: arduino-uno, button, time
---


# Question
Title: Servos not working properly with joystick
So, I was working with a project in which I used a joystick module to control two servos at the same time. The joystick controls the servos in a way that when the joystick is moved along x-axis, both servos move in the same direction but when joystick moves in y-axis, the servos move in different directions. I have this program:

```
#include <Servo.h>
Servo servo1;
Servo servo2;
int joyx = 0;
int joyy = 5;
int joyval;
int joyvalx;
int joyvaly;
void setup() {
    Serial.begin(9600);
    servo1.attach(3);
    servo2.attach(5);

}

void loop() {
    Serial.println(joyvalx + "," + joyvaly);
    int x = analogRead(joyx);
    int y = analogRead(joyy);
    if(x != joyvalx){
        joyval = map(x, 0, 1023, 0, 180);
        servo1.write(joyval);
        servo2.write(joyval);
    }
    if (y != joyvaly){
        joyval = map(y, 0, 1023, 0, 180);
        servo1.write(joyval);
        servo2.write(1023-joyval);
    }
}

```

However, the servos don't seem to work properly. One servo works fine but the other just gets stuck. Also, if I use the code for only one direction (x-axis or y-axis) by removing the code for the other, then both servos work good. I can't understand the problem. If anyone does, please help me.

# Answer
The problem, as jsotola pointed out, is that your code writes totally different values to the servos very fast. You don't combine the two values from the joystick, but just overwrite the previous servo value. So this cannot work.

As I interpret your description, you want the x axis to move both servos the same amount in the same direction (in unity), while the y axis determines the difference of position between them. If you move the y axis to one side, the first servo will go a bit clockwise, while the other goes a bit counter-clockwise. When you then move the x axis, both servos will move to the corresponding direction, while maintaining their position difference.

It is better to first write a formula, how you will calculate each servo position from the given joystick values. The above behavior can be described with these formulas:

```
servo_1_value = mapped_x + mapped_y;
servo_2_value = mapped_x - mapped_y;

```

Now you have to map the joystick values correspondingly:

```
mapped_x = map(x, 0, 1023, 0, 180);
mapped_y = map(y, 0, 1023, -90, 90);

```

Note, that you should change the parameters for mapping `y` to the values you need. In the above code they are set to the maximum (meaning that moving the y axis to either end will effectively disable the x axis, since the servo cannot move past 0 or 180 degrees).

You don't really need to check, if the value changed. But if you really want to, you should check the calculated values for each servo separately. Something like this:

```
if(servo_1_value != old_servo_1_value){
    servo1.write(servo_1_value);
}
if(servo_2_value != old_servo_2_value){
    servo2.write(servo_2_value);
}

```

But you don't really need to check for a change here.
> 2 votes

---
Tags: arduino-uno, servo, joystick
---


# Question
Title: Arduino reads string from another Arduino only if the string is in a loop why?
In my setup I have connected two arduino's Serially. An Arduino Mega is the on that is sending the string and a Arduino Uno is the one receiving it.

* Arduino Mega : RX1(19),TX1(18) - Serial1
* Arduino Uno : RX(10),TX(11) - using SoftwareSerial
* Gnd is connecetd on both boards

When I send a single string from the mega to Uno multiple times(In void loop) I receive the string sent infinite number of times on the Uno which is to be expected:

**Arduino Mega - Single string sent multiple no. of times**

```
void setup()
{
  Serial1.begin(9600);
}
void loop()
{
  Serial1.println("e2e4");
  delay(100);
}

```

Now I want to only send the string a single time, so I inserted an exit(0) or an infinite loop after the delay that is always true.

**Arduino Mega - Single string sent only one time**

```
void setup()
{
  Serial1.begin(9600);
}
void loop()
{
  Serial1.println("e2e4");
  delay(100);
  while(true);
}

```

**Arduino UNO - code is same for both cases**

```
#include <SoftwareSerial.h>
SoftwareSerial s(10, 11);
void setup()
{
  delay(200);
  Serial.begin(9600);
  s.begin(9600);
  while (!Serial) ;  // wait for Arduino Serial Monitor
}
void loop()
{
  if(s.available()>0)
  {
     Serial.print("\nrec\n");
     delay(100);
     String b = s.readStringUntil('\n');
     delay(100);
     Serial.print(b);
     delay(40);
  }

```

}

Note : Arduino uno is receiving the string using : readStringUntil('\n')

But when I send the string only once I receive nothing on the Arduino Uno, can anyone help me figure out why this is happening

**What I want to know is why the uno receives the string only when it's sent an infinite number of times and not when it is sent 1 time.**

**EDIT (July 8)**

Still haven't got a solution that I'm looking for, if anyone needs any extra information to help me out please mention it to me.

**EDIT (July 8-9)**

Sorry it's my fault for writing Tx1 as 19 and Rx1 as 18 although I did not make the same mistake in the code. When I pressed the reset button on the mega the string was received on the uno side.How did this happen? Until now, after I uploaded the code in both the arduino's I opened the serial monitor of the port connected to Uno and I did not receive the string.

Why do I need to reset the mega in order to send the string , shouldn't it work when the serial monitor is opened?

Also I need the mega to send the string automatically without any forced/physical reset is that possible?

I'm asking this because sending a string is part of a larger code where values get updated as time goes by,and a reset will reset all the values to their original state which I don't want happening.

# Answer
exit(0) is not the command to use, it is used to completely stop the program, although I'm not sure what happens exactly for an Arduino sketch.

To stop a loop (and continue, normally a break statement is used. This works inside a while or for loop and the sketch continues after the while or for loop where the break statement is executed.

Note, you also can start at the beginning of the while or for loop with the continue statement.
> 1 votes

# Answer
try putting a delay in the arduino mega code to make sure the uno is completely setup before it starts sending the data. I can see some delays in the uno code, so its possible that the arduino uno is not yet ready when the data is sent. Add a large delay, say 2000 to make sure uno is ready. Also there are neater ways to do this instead of just putting an infinite loop, unless the only goal of your program is just to send one string. You can use a flag that to disable sending.

```
bool isSent = true;

void loop()
{
  if(isSent)
   {
     isSent = false;    // set to false so we will never send again.
     Serial1.println("e2e4");
   }
}

```
> 1 votes

# Answer
`exit` turns off interrupts which will stop the serial output. I suggest something simpler like `while (true);`
> 0 votes

# Answer
> Until now, after I uploaded the code in both the arduino's I opened the serial monitor of the port connected to Uno and I did not receive the string.
>
> Why do I need to reset the mega in order to send the string , shouldn't it work when the serial monitor is opened?

Clearly there is a timing issue. When you open the serial monitor it resets the Arduino (in this case, I assume the Uno). So, the Uno resets, however the Mega doesn't reset because you didn't open the serial monitor there. Manually resetting the Mega forces it to send the data again (it would have sent it earlier when powered on).

In normal operation, of course you don't need to reset the Mega just to force a string "to be sent once". You have already proved that you can send a string many times, and sending a string once is clearly a subset of that situation. Sending n times is just (sending once) times n.

Your test setup, which requires powering both Arduinos at the same time, and then opening the serial monitor which resets one, but not the other, is what is confusing you. It is not that you can't send strings whenever you want, in normal operation.
> 0 votes

---
Tags: arduino-uno, arduino-mega, serial-data
---


title: Error handling strings and chars

text:
# Question
Title: Error handling strings and chars
I'm having an error in buffers that handle strings and I can not figure out what the problem is. The example below shows what is happening. Can someone help me?

```
void setup() {
   char* ss1 = "";
   char* ss2 = "";
   String txt = "";

   Serial.begin(115200);

   txt = "1234560001a";
   txt.toCharArray(ss1, txt.length());

   Serial.printf("\n\n");
   Serial.printf("ss1 = %s\n", ss1); // It prints "1234560001" whithout last char "a"

   // Force incorrectly "ss1" to be equal to "ss2" and still removes the last character.
   txt = "abcdef";
   txt.toCharArray(ss2, txt.length());

   Serial.printf("ss1 = %s\n", ss1); // It prints "abcde" whithout last char "f"
   Serial.printf("ss2 = %s\n", ss2); // It prints "abcde" too
}

```

# Answer
`toCharArray` is alias for `getBytes`. `getBytes` is documented as "Copies the String’s characters to the **supplied** buffer." You did not allocate the memory for the copied characters.

the right use of 'getBytes' and 'toCharArray' is

```
char buffer[BUFF_SIZE];
str.getBytes(buffer, sizeof[buffer]);

```

note: `getBytes` functions sets the terminating zero of the c-string in buffer
> 1 votes

# Answer
About the problem with losing the last character:

As already said in the comments, the `toCharArray()` method is only an alias for the `getBytes()` method of string objects. We can see it's implementation in the IDEs folder under `hardware/arduino/avr/cores/arduino/WString.cpp`:

```
void String::getBytes(unsigned char *buf, unsigned int bufsize, unsigned int index) const
{
    if (!bufsize || !buf) return;
    if (index >= len) {
        buf[0] = 0;
        return;
    }
    unsigned int n = bufsize - 1;
    if (n > len - index) n = len - index;
    strncpy((char *)buf, buffer + index, n);
    buf[n] = 0;
}

```

We give the length as parameter, which is then reduced by 1. The function `strncpy()`, that is used here, will only copy `n = bufsize - 1` bytes. In the end, the `n`th byte will be set to `0` as the terminating null character.

This means, that the length, that we give as parameter, already includes the space for the null character. But the method `String::length()` will not include the null character in length calculation (in most cases this is not wanted). So you can simply add 1 to the length before giving it to `toCharArray()`.

About the overwriting problem:

As stated in this question's answer and in several other discussions about C/C++ (for example here), string literals are meant to be immutable. The mentioned sources say, it is different, if you define a string variable as

```
char *str = "test";

```

or

```
char str[] = "test";

```

In the second case a normal mutable array is created. In the first case the string will be placed in read only memory. From your problem I read, that on Arduino this is placed in RAM, thus technically mutable. But the compiler thinks of it as immutable. A common optimization, when dealing with immutable strings, is to let every used string literal with the same content be saved at the same memory address.

In your code you are initializing 2 strings with only the terminating null character in them. The compiler thinks "Oh, wait, these two string literals are immutable and equal, so I can save memory by only saving it once and let both pointers point to this memory address". When writing to the strings in Arduino the behavior doesn't seem to be defined. As the Arduino cannot throw an exception it will most likely do the write. Since both pointers are pointing to the same memory address, they show both the same content. Also, when writing a string longer than the initialized value, memory space outside from the original string will be written. If other variables are saved there, they will get overwritten. This is the reason, by you should always explicitely allocate the memory (static or dynamic) for a string, until another function does it for you. When using a dynamic allocation of memory, you should also consider heap fragmentation, which can easily lead to strange behavior.

If you turn on verbose output for compilation, the compiler also warns you, that you try to convert a constant string literal to a non-constant char pointer:

```
sketch_jul09a.ino:3:15: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

```

To conclude, you should not declare string variables like this. If you have a variable string buffer with initialized values, you should use

```
char str[]="test";

```

If you want to define a constant string, use the keyword `const`:

```
const char *str = "test";

```

Then writing to it will result in a compiler error, so that you sense, if you are doing this.
> 0 votes

---
Tags: string, buffer
---


# Question
Title: Integrating Java program with arduino mega is it possible?
I have just written a java algorithm to get a chess move when a chess move is inputted in SAN notation the algorithm used : Monte Carlo. Is it possible to integrate this program with an Arduino mega and How?

My mega will be getting inputs from a sensory board and I want to send these inputs to the java program without using any additional board.

**Note:<br>By integrate I mean that the Java program should run in the Arduino mega itself**

Can anyone suggest a solution?

# Answer
> 2 votes
There is a project called uJ by Dmitry Grinberg that enables you to do that, somehow. It has been tested on AVR devices too, not your particular one however. Knowing AVRs, that shouldn't be a stopper at all.

That said, I don't think it's a very good idea. The overhead of the JVM may only let you handle some 'slow' signals, unless you heavily rely on peripherals and wit to do stuff. Though in your particular application, that shouldn't be that much of an issue.

Instead of having the trouble of running a JVM and such, you may just as well rewrite the code in C/C++ or whatever, even for increased efficiency. There may also be some Java to C transpilers, I haven't looked, wary of the dragons.

However, if you eventually decide against that and instead choose to talk to the microcontroller over serial or something else, there is the dreadful excellent RxTx library for Java that works pretty fine after all, or the Firmata library.

---
Tags: arduino-mega, java
---


# Question
Title: How to find the index of the maximum value in an array?
Say we have an array named `myMeasurements`

```
int myMeasurements[9]={3,4,8,12,7,2,1,67,8};

```

**How can I find the index of the maximum element of this array?**

For example the MATLAB code would be:

```
myMeasurements = [3,4,8,12,7,2,1,67,8];
[maxValue,Index] = max(myMeasurements);

```

where `maxValue` is returned as 67 whereas the `Index` is returned as 8.

For the record, I am using Teensy 3.2 and I program it with the Arduino IDE using the Teensyduino add-on.

# Answer
> 3 votes
First of all, do you really need int values for the measurements or not? If not, and you have numbers between 0 and 255, switch the values to byte, your microcontroller will thank you.

Then, there is a problem with the other answers, which is... The variables cannot be left uninitialized!!! You can use this code to get the info you need:

(I also put the size of myMeasurements in a const variable.. You can thank me later for this)

```
const byte maxMeasurements = 9;
int myMeasurements[maxMeasurements ]={3,4,8,12,7,2,1,67,8};

byte maxIndex = 0;
int maxValue = myMeasurements[maxIndex];

for(byte i = 1; i < maxMeasurements; i++)
{
    if(myMeasurements[i] > maxValue) {
        maxValue = myMeasurements[i];
        maxIndex = i;
    }
}

```

# Answer
> 0 votes
```
int myMeasurements[9] = {3,4,8,12,7,2,1,67,8};
int maxI = 0;
for(int i = 1;i < 9;i++)
    if(myMeasurements[i] > myMeasurements[maxI])
       maxI = i;

```

# Answer
> -1 votes
Arduino forum has discussed finding the index once you know which value's index you want. Solution was arrived at by traversing the array by value you were looking for.
For your requirement, you will have to
(1) find the maxValue first and then
(2) find the position(index) of that maxValue using the code they have discussed here : https://forum.arduino.cc/index.php?topic=121116.0

# Answer
> -1 votes
The code given by Jakub Krnáč gets a slight change which will give the index of the max value. Here is the changed code:

```
int myMeasurements[9]={3,4,8,12,7,2,1,67,8};
int max,current, maxI;
for(int i = 0;i < 9;i++){
    current = myMeasurements[i];
    if(current > max){
        max = current;
        maxI = i;
    }
}

```

---
Tags: arduino-ide, array, teensy
---


# Question
Title: Touch Sensor - Determining Pressing/Hold Length and Modifying Program Flow Accordingly
The code below is used for controlling a relay with an Arduino. Pressing the touch sensor connects and disconnects the relay.

If the user presses/touches/holds their finger on the touch sensor for longer than two seconds, how do I adjust the program to do something other than connecting or disconnecting the relay?

```
#define TouchSensor 9 // Pin for capactitive touch sensor

int relay = 2;

boolean currentState = LOW;
boolean lastState = LOW;
boolean RelayState = LOW;

void setup() {
  Serial.begin(9600);
  pinMode(relay, OUTPUT);
  pinMode(TouchSensor, INPUT);
}

void loop() {
  currentState = digitalRead(TouchSensor);
    if (currentState == HIGH && lastState == LOW){
    Serial.println("pressed");
    delay(1);

    if (RelayState == HIGH){
      digitalWrite(relay, LOW);
      RelayState = LOW;
    } else {
      digitalWrite(relay, HIGH);
      RelayState = HIGH;
    }
  }
  lastState = currentState;
}

```

# Answer
> 1 votes
You have to determine, how long a the sensor was pressed until released. When it is released you can take the corresponding steps. If the press was shorter than say 1.5s, you can switch the relay. Else you can do something else.

There are many ways to achieve this. You can program it yourself by using the `millis()` function. You would have to set a timestamp, when the state of the sensor changes to high, then wait for it to go low and substract the timestamp from the current value of `millis()`. This would give you the duration of press, which you can use in a corresponding `if`-statement.

Or you can use the `Debounce` library for it, which makes it a bit simpler (not a lot, but you should consider debouncing depending on the type of sensor you use). Look at the answer from VE7JRO to this question. The `debouncer.update()` function checks, if the state of the button changed. If so and the value was LOW (in your case this would has to be changed to HIGH), a timestamp is set with the value of `millis()`. When an update with LOW occurs, the time difference between the two events is calculated and the corresponding action are taken. I will add the code from the answer for reference here:

```
// Connect one end of a N.O. push button switch to GND and the other
// end to pin 4 of the Arduino.
// NOTE: If the button is held down for less than the debounce delay
//       time, the elapsed time will display the debounce delay time.
#include <Debounce.h>
const byte SWITCH = 4;
unsigned long startTime = 0;
unsigned long endTime = 0;
unsigned long elapsedTime = 0;
const byte debounceDelayTime = 50;

Debounce debouncer = Debounce(debounceDelayTime, SWITCH);

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

void loop(){
  if(debouncer.update()){
    if(debouncer.read() == 0){
      startTime = millis();
      Serial.println("Button Pressed");
    }
    else if(debouncer.read() == 1){
      endTime = millis();
      Serial.println("Button Released");
      elapsedTime = endTime - startTime;
      Serial.print("Button Held Down For ");
      Serial.print(elapsedTime);
      Serial.println(" ms.");
    }
  }
}

```

# Answer
> 1 votes
This sketch uses a millis() timer to add the concept of time to debouncing a button with the Bounce2 Library, (This library may be included with the current version of the Arduino IDE). This sketch **does not** contain any code to turn a relay on and off.

```
// Connect one end of a N.O. push button switch to GND
// and the other end to pin 4 of the Arduino.
#include <Bounce2.h>

byte buttonState = 0;
byte lastButtonState = 0;
const byte buttonPin = 4;
const byte debouncerInterval = 50;         // Time in ms.
unsigned long buttonHeldThreshold = 2000;  // Time in ms.
unsigned long buttonPressTimeStamp;

Bounce debouncer = Bounce();

void setup(){
  Serial.begin(9600);
  pinMode(buttonPin, INPUT_PULLUP);
  debouncer.attach(buttonPin);
  debouncer.interval(debouncerInterval);
}

void loop(){

  if(debouncer.update()){

    if(debouncer.read() == 0){
      buttonState = 1;
      buttonPressTimeStamp = millis();
      Serial.println("Button Pressed");
    }
    else if(debouncer.read() == 1){
      buttonState = 0;
      Serial.println("Button Released");
    }
  }

  if(buttonState == 1){
    if(millis() - buttonPressTimeStamp >= buttonHeldThreshold){
      buttonState = 2;
      Serial.println("Button Held for 2+ seconds");
    }
  }

  // Print out the contents of the buttonState variable only when it changes.
  if(buttonState != lastButtonState){
    Serial.print("Button state = ");
    Serial.println(buttonState);
    Serial.println();
    lastButtonState = buttonState;
  }
}

```

Keep in mind that this library has `debouncer.rose()` and `debouncer.fell()` functions that may be helpful to you. It's always a good idea to look at the \*.h and \*.cpp files in the libraries you install. There may be several functions that are not demonstrated in the library's examples. Sometimes the author(s) use code comments in the library which can help you to trouble shoot any issues that may arise.

# Answer
> 1 votes
For this kind of scenario "activation" of the button is *never* done when it is pressed. Yes, under "normal" circumstances you press a button, a circuit is made, and something happens.

However, if you need more than just that simple operation you never do anything just when it's pressed.

For example, if you click on a link on a web page, nothing really happens when you press the mouse button. Yes, the link is "selected", but that's all. Nothing active happens until you *release* the mouse button. It's the act of "press-then-release" that constitutes a "click" - and then only if the release happens within a certain time after the press.

That allows such other options to happen, such as "press-drag-release" for drag and drop, or "press-wait-release" for selecting without activating, etc.

So for your scenario you have two desired "triggering" options:

* press-release
* press-hold

As long as the "release" of the "press-release" happens in a shorter time than the "hold" time of the "press-hold" you can differentiate between them.

So your methodology would look something like this:

* Button pressed - record the time
* Either:
    + Button released and time elapsed \< 2 seconds, or
    + Time elapsed \>= 2 seconds

As code that may look something along the lines of:

```
static uint32_t ts = 0;
static uint8_t buttonState = HIGH;

uint8_t buttonValue = digitalRead(ButtonPin);

if (buttonValue != buttonState) { // The state has changed.
    buttonState = buttonValue; // Record it
    if (buttonState == LOW) { // Button has been pressed
        ts = millis(); // Record the time
    } else if (ts > 0) { // Released - ts must have been set by a press
        if (millis() - ts < 2000) { // Less than 2 seconds have passed
            // Run your "press" routine
            ts = 0; // Clear our time stamp.
        }
    }
} else if (ts > 0) { // It hasn't changed state, but was pressed
    if (buttonState == LOW) { // It's held in. Not strictly necessary but can't hurt
        if (millis() - ts >= 2000) { // 2 seconds have passed
            // Run your "hold" routine
            ts = 0; // Clear our time stamp.
        }
    }
}

```

The time stamp variable `ts` is both used to record the time the button was pressed and also as a flag to indicate that we are currently in an "unactivated" state. That is, for the "held" state to indicate whether or not we still need to run our "held" routine or not. Without that check, after 2 seconds of holding the button the "held" routine would keep running over and over and over again until the button is released. It's kind of like implementing a "forced" release of the button after it has triggered the "held" routine. After that first triggering of "held" we no longer care what is done with the button. We ignore everything until the next time it is pressed when we set `ts` again.

---
Tags: arduino-uno, sensors, relay
---


title: Power management circuit

text:
# Question
Title: Power management circuit
i'd like to have a esp-01 powered on and controlled with a push button only. so imagine the device is off, the user press the momentary push button. in the setup the esp8266 turn on a mosfet or something similar to give himself power using another line. the user release the button and the device is on. i want to be able to understand long button press and double press and similar stuff too. even when device is already powered on. so i need to have a pin attached to the button somehow this is what i have till now, thanks to a very skillfull friend of mine

the vcc is 5 v and pin tollerance is only 3v

it must be completely off when not pressed for long battery duration

# Answer
You need to isolate your button from the logic output using a diode. For example:

simulate this circuit – Schematic created using CircuitLab

In this method M1's gate is normally pulled up by R2. It can either be pulled down by M2 (switched by the "HOLD" signal) or by the switch via D1.

The BTN input is pulled up by R1, and can be pulled down by the switch. M2 can't pull it down because the diode is reverse biased and blocks current trying to flow from BTN via M2 to ground.

R3 is just a pull-down on the gate of M2 to keep it off when HOLD is floating (the power is off).

If you need to interface the 5V "BTN" signal with a lower voltage-tolerant input pin just use a couple of resistors as a voltage divider to reduce the voltage to within the proper levels for the pin.
> 1 votes

---
Tags: arduino-uno, esp8266, button, battery
---


title: Reading and sending with Arduino?

text:
# Question
Title: Reading and sending with Arduino?
I am using Arduino in an IOT application where I have to read impulses coming from a sensor and send a mean value of these impulses without missing any impulse while sending the value so is it possible to achieve such operation knowing that Arduino is a single core chip.

I read about `Protothreading` libraries but it may miss an impulse during the check phase so I want to know if there is another solution

# Answer
> 0 votes
Although the Arduino only has one CPU core and can only execute one program instruction at a time, it's not limited to only doing one *thing* at a time.

An MCU is a complex device with lots and lots of *peripheral* devices built into it. The CPU is only one small block of the overall device.

Much of a program is merely instructions telling the peripherals how to perform.

For instance, when sending data through Serial the CPU doesn't say "Send this bit. Now wait. Now send this bit. Now wait again" - instead it just says "Here's this byte to send. Now go and send it and tell me when you're done". The UART peripheral then sends the byte by itself with no further input from the CPU leaving the CPU free to do other things.

Then there's the Timer peripherals. The CPU sets them up to count from a clock source, and do different things depending on different events, like a specific number is reached in the counting, etc. The CPU has no need to go "Count up one. Count up one. Count up one." - it just goes "Count up from 0 using this clock source and tell me when you reach 100" (for example).

Similarly, there are "External Interrupts". The CPU doesn't need to sit watching an IO pin all the time, going "Have you changed yet? Have you changed yet? Have you changed yet?" - it just goes "Tell me when you have changed" and the CPU goes off to do other things.

Of course, all these things have caveats. The biggest is that if the CPU is doing something very timing critical, such as "bit banging" serial data manually through a GPIO pin (for example with SoftwareSerial) it can be set to ignore all these interrupt signals from the peripherals. That means, if you're using an "External Interrupt" to count pulses, and you have to use SoftwareSerial to communicate, it's possible that SoftwareSerial's sending or receiving routines could cause the detection of a pulse to be either delayed (not really a problem) or to be missed completely.

So you don't want to use SoftwareSerial if it can be avoided if you want to use External Interrupts for this kind of operation.

The other option is to use a timer. I mentioned that they just count up from 0 (or they can count down, too) using a configurable clock source. That counting happens completely independently of the CPU, and carries on regardless of whether interrupts are enabled or disabled. And the great new is that most timers can be configured (depending on which Arduino you use) to use an external signal as the clock source for the counting.

That means you can configure a timer to count your pulses for you regardless of what the CPU is doing. All you have to do is every so often (how often depends on how frequently your pulses arrive - the timer has a limit on how many it can count before it overflows) ask the timer for what it has counted up to and reset its count to 0. That could be done as part of your "sending" routine. Get the count, reset it to 0, and send the results.

---
Tags: arduino-uno
---


# Question
Title: Problems with serial communication from Arduino to Bluetooth HC-05
I just purchased some HC-05 Bluetooth devices and I have followed the directions to put the devices in AT command mode by holding EN HIGH when the HC-05 powers up. When I do this the HC-05 goes into the "slow blink" to indicate it is in command mode. However, when I send it "AT" I get odd characters in the response.

Note that when I type "AT" I get exactly 4 characters back. They are just not the "OK" characters I expect. I also verified that the Arduino IDE serial console is sending both NL and CR characters.

BTW, here is the Mel Patrick HC-05 authored setup program I am running:

https://raw.githubusercontent.com/dmccreary/coderdojo-robots/master/src/bluetooth-remote/hc-05-setup/hc-05-setup.ino

It has been suggested that the data from the HC-05 is only going up to 3.3v and that might be the cause of the problem, since the Arduino is looking for a 0-5 volt signal.

I also note that when I remove the TDX line from the HC-05 that no responses come back. So I suspect that it is getting the "AT" fine through the RTX from the Arduino to the HC-05. It is just some problem in the return data format.

Is there a simple transistor circuit I can hookup to shift the levels back to 0 to 5 volts from the 0 to 3.3 volts?

I am also using an Arduino Nano if that makes any difference.

Thanks - Dan

# Answer
If you use software serial for Bluetooth, you need to set the baud rate and the default baud rate of HC-05 is 38400.

You can change this baud to the desired with AT command.
> 1 votes

# Answer
Try setting your baud at 38400. Connect Tx-\>Tx & Rx-\>Rx when configuring your module. Tx-\>Rx & Rx-\>Tx during execution.
> 0 votes

# Answer
> Is there a simple transistor circuit I can hookup to shift the levels back to 0 to 5 volts from the 0 to 3.3 volts?

Yes there are level shifting circuits you can use, resistor dividers and all that stuff, but you will be better off using a proper level shifting circuit, something like this:

Level Shifter

I believe there is something to do with the speed of switching between high and low and getting crisp rise and falls of the signal.
> 0 votes

# Answer
Set Baud rate to 38400 in serial monitor.

If you have Arduino UNO with removable Atmega328p - then remove the chip and connect TX of HC05 to TX of Arduino and RX to RX.

Most of the HC05 works perfectly with 5V system (I have one here hooked up to 5V and RX,TX connected directly ( without level shifter) but it's not recommended.
> 0 votes

# Answer
If you are indeed receiving something after the AT command, that means you have the baudrate wrong. Change it from the serial monitor to 38400 or something else.
> 0 votes

# Answer
My experience with these units...

1. BAUD rate varies so try them all.
2. Some expect chars in caps and some don't care
3. Some expect a question mark after the command and some don't e.g AT?
4. Some require CR and some don't.
5. Some only stay in AT mode for a second on boot and thus I found I had to set it up in steps, e.g write program to set PIN, then another to set NAME and so on..

Reason for this is that many clones do not have full software and commands installed.
> 0 votes

---
Tags: serial, bluetooth, arduino-nano, voltage-level, hc-05
---


# Question
Title: Digital Comparator with ATTiny85 doesn't behave as expected
Here is my schematic:

I've removed the resistors from the LEDs to make it smaller. The 1 and 2 on the left are outputs from the arduino (which supplies the VCC and ground).

These 1 and 2 are HIGH or LOW and I want the leds to turn on according to this table:

```
┌───────┬────────────────────┐
│ INPUT │ OUTPUT             │
├───┬───┼──────┬──────┬──────┤
│ A │ B │ Led1 │ Led2 │ Led3 │
├───┼───┼──────┼──────┼──────┤
│ 0 │ 0 │ 1    │ 0    │ 0    │
│ 1 │ 0 │ 0    │ 1    │ 0    │
│ 0 │ 1 │ 0    │ 0    │ 1    │
│ 1 │ 1 │ 1    │ 0    │ 0    │
└───┴───┴──────┴──────┴──────┘

```

And this is the code I am using with the ATTiny85

```
const int pinA = PB3;
const int pinB = PB4;
const int pinOut1 = PB2;
const int pinOut2 = PB1;
const int pinOut3 = PB0;

void setup() {
    pinMode(pinA, INPUT);
    pinMode(pinB, INPUT);
    pinMode(pinOut1, OUTPUT);
    pinMode(pinOut2, OUTPUT);
    pinMode(pinOut3, OUTPUT);

    int a = digitalRead(pinA);
    int b = digitalRead(pinB);

    if (a == b) {
        digitalWrite(pinOut3, HIGH);
    }
    else if (a == HIGH) {
        digitalWrite(pinOut1, HIGH);
    }
    else {
        digitalWrite(pinOut2, HIGH);
    }
}

```

With this set up, I get this output:

```
┌───────┬────────────────────┐
│ INPUT │ OUTPUT             │
├───┬───┼──────┬──────┬──────┤
│ A │ B │ Led1 │ Led2 │ Led3 │
├───┼───┼──────┼──────┼──────┤
│ 0 │ 0 │ 1    │ 0    │ 0    │
│ 1 │ 0 │ 0    │ 1    │ 0    │
│ 0 │ 1 │ 1    │ 0    │ 0    │ <- See the difference
│ 1 │ 1 │ 1    │ 0    │ 0    │
└───┴───┴──────┴──────┴──────┘

```

I think it has something to do with the fact that the ATTiny gets powered on if you supply 5v to one of the input pins too and not to VCC.

And yes, I keep restarting the board (by pulling out the VCC pin and seeing the led turn off).

I've also tried connecting A and B to VCC and ground both in all possible positions. Here I noticed that connecting A (or B) to 5v (of the arduino) while VCC is not connected, the board will turn on.

I hope this is enough info.

# Answer
> 2 votes
You have to assign the status of all output pins in each of your "if statement" conditions. Think of it like 'if that happens, I want x, y, & z to be ON, and a, b, & c to be Off'. Unchanging the HIGH status of one output will remain that output HIGH for all conditions. Output pins never change their statuses untill they have an order "your code" to do this. Also you have to replace your code inside a loop function to repeat your code without the need to manually reset your ATTiny.

Assuming LED1 = pinOut1, LED2 = pinOut2, LED3 = pinOut3. You have to replace "if conditions" in your code by the following:

```
while( 1 ){
    int a = digitalRead(PinA);
    int b = digitalRead(PinB);

    if ( a == b ) {
        digitalwrite (pinOut1 , HIGH);
        digitalwrite(pinOut2,LOW) ;
        digitalwrite (pinOut3, LOW);
    }
    else if ( a == HIGH ) {
        digitalwrite(pinOut2,HIGH) ;
        digitalwrite(pinOut1,LOW) ;
        digitalwrite(pinOut3,LOW);
    }
    else if ( b == HIGH ) {
        digitalwrite(pinOut3,HIGH) ;
        digitalwrite(pinOut1,LOW) ;
    digitalwrite(pinOut2,LOW);
    }
}

```

Also according to your application speed requirements, you can add a delay of about 300 ms before reading your digital inputs to allow the user to change the status of these digital inputs.

# Answer
> 1 votes
I see nothing wrong in your code, except a terrible design decision that forces you to reset the ATtiny every time you want to change its inputs. I guess, then, that the problem is in the way you *use* it. For example, let's say you are testing the lines of the table one by one. Once you are done with the second line and decide to move to the third, let's say that you:

1. power-cycle the ATtiny
2. set its A input to `LOW`
3. set its B input to `HIGH`.

The ATtiny could very well be reading its inputs right between the steps 2 and 3 above. It would then see both inputs `LOW` and do what it is supposed to do in that case. This is called a *race condition*, and usually leads to bugs that are very hard to find.

The right way to use *this particular program* is to never remove the power and:

1. set the new inputs
2. pulse the RESET pin of the ATtiny `LOW` for a few microseconds.

Of course, it would be way better to have a sensible design that doesn't force you to reset. C.f. Ahmed M.Zahran's answer. For this kind of trivial problem (just a truth table implementation) I prefer to implement the solution in plain C:

```
#include <avr/io.h>

static const uint8_t truth_table[] = {1, 2, 4, 1};

int main(void)
{
    DDRB = 0x7;  // PB0..PB2 as outputs
    for (;;) {
        uint8_t input = (PINB >> 3) & 0x3;  // the 2 input bits
        PORTB = truth_table[input];  // send output to the LEDs
    }
}

```

If you are worried about power, put the ATtiny to sleep and wake it up on a pin change interrupt. But be sure to have the simple version working *first*, before you worry about power saving and sleep modes.

# Answer
> 0 votes
> I think it has something to do with the fact that the ATTiny gets powered on if you supply 5v to one of the input pins too and not to VCC.
>
> And yes, I keep restarting the board (by pulling out the VCC pin and seeing the led turn off).
>
> Here I noticed that connecting A (or B) to 5v (of the arduino) while VCC is not connected, the board will turn on.

All of the above is roughly translated into "I am frying my chip and don't know why it does not work".

Look at "absolute maximum ratings" in datasheet:

"Voltage on any Pin except RESET with respect to Ground -0.5V to **VCC+0.5V**"

In short, you need to power MCU up **before** applying voltage to input pins. That is why it is so surprising that you do not have a loop in your main().

---
Tags: attiny, attiny85
---


# Question
Title: Arduino Fried? Power is being delivered to Arduino but COM not found
When i connect my arduino nano to windows 10; the arduino nano is powered on (the "POW" led is on and not blinking; none of the others are on) but it doesn't show up on my computer. It used to but I think I may have shorted it.

Oddly, I get a measurement of 5V coming from digital pins 2,3,4 if connected through USB or 12V if I connect external power source to V\_in. These are the pins that were on before what I believe was a short. Can someone tell me what is the component that is damage and whether it is possible to fix. Thanks!

# Answer
> 1 votes
If you were powering from 12V and shorted the 5V to GND then yes, it is all dead. The regulator will have stopped regulating. 12V will have then been sent to every component on the board. The USB chip, the main MCU, the 5V regulator - all will be toast.

You *could* repair it by replacing almost every component on the board, but when they're so cheap, why would you bother?

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


# Question
Title: What precision can I expect by syncronising DS3231 with PC serial?
The point here is to syncronise a DS3231 module (on an Arduino) via serial port with NTP time by computer.

The problem here is that I'd like to know how much time is taken by the serial and I2C transmission, because if the PC sends the time at a time `t1` and transmit it to the Arduino, the Arduino decodes it and sends it to the DS3231, the time `t1` is received at a time `t2` greater than `t1`.

```
PC (t1) => Serial(t1+x) => Arduino(t1+x+y) => I2C(t1+x+y+z) => DS3231(t2=t1+x+y+z)

```
* `t1` -\> NTP time recorded by PC
* `x` -\> Time taken by serial transmission
* `y` -\> Time taken by arduino buffering/processing
* `z` -\> Time taken by I2C transmission at 100kHz
* `t2` -\> Time when message is received by DS3231

Is it negligible for a precision at millisecond?

I found a table on Wikipedia that displays time per bit per baudrate. I am planning to use a baudrate of 57600.

I tested offset using a simple echo program available here at 300 baud:

```
String buff="";

void setup() {
  // put your setup code here, to run once:
Serial.begin(300);
}

void loop() {
  if(Serial.available())
  {
    while(Serial.available())
    {
      buff += char(Serial.read());
    }
    Serial.print(buff);
    buff = "";
  }
}

```

# Answer
I second the general idea of Dmitry Grigoryev’s answer: your best option is to measure a round-trip time and use half of that as an estimate of the one-way time. Otherwise you will have too many unknowns. For example, you don't know how long your OS takes to process the outgoing message and send it through USB to the USB/serial bridge inside the Arduino. As an optimization, I would send the time information and the synchronization strobe as two separate messages, with the latter being a single byte. This way the latency of the synchronization strobe (the only latency that matters) is minimized.

## Latency of serial communication

I did some research to try to nail this one down. At 57600 bits/s, the theoretical time per bit is about 17.4 µs, as stated in the Wikipedia article you linked to. In practice, the actual time can be rounded more or less depending on the UART capabilities and the clock speed. You did not specify what Arduino you are using. In the following, I will assume an AVR-based Arduino clocked at 16 MHz, which is presumably the most common.

The UART in the AVR constrains the bit time to be a multiple of 8 CPU cycles, i.e. 0.5 µs when running at 16 MHz. The closest you can get to the ideal timing is therefore 17.5 µs. However, the Arduino core library has a hard coded compatibility exception which, in this very specific case, sets the bit duration to 17 µs instead. Since you are presumably configuring the port at /8N1, which is the default, the time per byte is then 170 µs (1 start bit, 8 data bits and 1 stop bit).

Actually, when transmitting a single byte, the transmission time is slightly less than that. The UART can report the byte as received as soon as it is done taking the required three samples of the stop bit, which happens slightly after the *middle* of that stop bit. The theoretical time it takes to transmit a single byte is then about 9.56 times the single-bit duration, or about 162.56 µs at 57600/8N1.

I did a simple loopback test with the TX and the RX of my Uno shorted together. I used a timer to time the execution of the following code:

```
Serial.write('.');
while (!Serial.available()) continue;

```

The result was 182.38 µs, or about 10.73 bit durations. A fraction of this time is taken by the execution of `Serial.write()` and `Serial.available()`. In order to get closer to a bare hardware latency, I also timed a low-level version of the two lines above:

```
UDR0 = '.';
while (!bit_is_set(UCSR0A, RXC0)) continue;

```

This has to be run with interrupts disabled. The execution time was now between 164.19 and 164.81 µs, i.e. 9.66 to 9.69 bits durations.

## Alternative approach

As a final note, I would recommend you consider buying a GPS module with a 1PPS output. This 1PPS is a 1 Hz logic signal with the rising edges tightly aligned to the start of the UTC seconds. You typically get an accuracy in the tens of *nanoseconds*. Since this is just a logic signal that you can easily compare with the 1 Hz output of your RTC module, you get rid of all the latency issues that come with computers (your NTP client), or data links (USB, serial, I2C).
> 2 votes

# Answer
Transmission time will certainly not be negligible. To estimate it, you could use the roundtrip delay calculation, which is (roughly) how the NTP protocol is implemented in the first place.

* at PC time T1, PC sends current time T1 to Arduino via UART
* Arduino sets the time T1 in DS3231 via I2C
* Arduino reads the time T2 from DS3231 via I2C
* Arduino sends the time T2 to PC via UART. This happens at time T3 from PC's point of view.

Now the PC can estimate the half-roundtrip delay R as (T3-T2)/2. See the following chart which denotes current time form POW of PC and RTC

```
        |--UART--|--I2C--|--------|--I2C--|--UART--|
PC      T1              T1+R     T2+R           T3=T2+2R
DS3231  -                T1       T2              T2+R

```

Next, at time T4, the PC sends the value (T4+R) via UART. This will result in DS3231 to be set to (T4+R), which happens exactly R time after T4, so that both clocks are now set to the same value.

Estimation of R can be repeated several times. In this case you can calculate the standard deviation which tells you how much "jitter" your clocks have.
> 2 votes

---
Tags: serial, time, ds3231-alarms
---


# Question
Title: DC motor with L289N driver cannot set RPM lower than 130
My setup is using an Uno r3, and the motor driver is an L289N.

I am going to set it to run at a lower RPM, but when adjusting `enA` or `enB` to set to below 130, it won't spin.

```
// connect motor controller pins to Arduino digital pins
// motor one
int enA = 2;
int enB = 7;
int in3 = 5;
int in4 = 6;
int in1 = 3;
int in2 = 4;

void setup()
{
  // set all the motor control pins to outputs
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
}
void demoOne()
{
  analogWrite(enB, 130);
  // turn on motor B
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  delay(500);
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  delay(5000);
  // this function will run the motors in both directions at a fixed speed
  // turn on motor A
  // set speed to 200 out of possible range 0~255
  analogWrite(enA, 130);
  // turn on motor B
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  // set speed to 200 out of possible range 0~255
  delay(100); //this function to set masa untuk rotation
  // now change motor directions
  // now turn off motor
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
  delay(5000);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  delay(200);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
  delay(5000);
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  delay(200);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
  delay(5000);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  delay(100);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
  delay(5000);

  analogWrite(enB, 130);
  // turn on motor B
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  delay(400);
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  delay(5000);
}

void loop()
{
  demoOne();
  delay(3000);

}

```

# Answer
Looks like you are controlling two motor outputs via the H-bridge, where the logic inputs are `in1,in2` and `in3,in4`. First of all, you need

```
pinMode(in1,OUTPUT);
pinmode(in2,OUTPUT);

```

One reason why the motors may not spin for analogWrite value less than 130 is that, coincidentally, the voltage output is too low and motor stalls. Test this two ways: does (1) changing the motor supply voltage or (2) changing the argument of `analogWrite` actually change the speed?

If no, it may be that `pinMode(enA,OUTPUT);` sets the output as digital and should be removed. In that case a number less than 128 gets interpreted as a logic 0 and the motor will not spin.

P.S. your code can be neatened up using port syntax and bitwise operators.

```
digitalWrite(in1,HIGH);
digitalWrite(in2,LOW);

```

can be written on a single line with

```
PORTD |= _BV(in1);

```

Also

```
digitalWrite(in1,LOW);
digitalWrite(in2,LOW);

```

becomes

```
PORTD &= ~(_BV(in1) | _BV(in2));

```
> 1 votes

# Answer
On an Uno, `D2` and `D7` (`enA` and `enB`) do not have true PWM (analogWrite) capabilities- they will be 100% on at values of 128 or higher, and off at 127 and lower.

You will need to use 3, 5, 6, 9, 10 or 11 for PWM (i.e. your `enA` and `enB`) on the Uno.

See Arduino Reference - analogWrite() for more info on PWM pin availability on Arduino boards.
> 0 votes

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


# Question
Title: Schematic interpretation, where to put resister?
I'm new to schematics, trying to figure out where to put a resistor (no instructions other than the schematic)

I'm told I need: 10K variable Resistor x 1, 4.7K Resistor x 1, 100 Resistor x 1

But I only see where to put the 10k resistor (I added a blue circle around the 10k). Can someone show me (describe, illustrate) where to put the others?

And where there's the triangles for +5V or AGND, do I put something there (purple circles)??

Thanks!

Here is a link from the project I'm trying to build https://bestengineeringprojects.com/arduino-weighing-machine-using-hx711/

# Answer
> 0 votes
The 4.7kOhm resistor is shown in the second image (They simply didn't want to scramble the big image). It shows, that the pin between the resistor and the button has to be connected to pin D10 of the Arduino:

The 100 Ohm resistor isn't shown in the image, too. But in the text it says:

> Note: Cathode and Anode pin of LCD (pin 15 and pin 16) is not shown in circuit diagram. Connect +5 volt to pin 15 with current limiting resistor (generally 100-ohm) and pin 16 of LCD to ground.

Pins 15 and 16 are not shown in the diagram, but the text gives all necessary information. Connect pin 15 of LCD to the 100 Ohm resistor and this resistor to 5V power source. And then connect pin 16 of LCD to ground.

---

The two other symbols, that you circled, are used as indicator of the power source. Normally all pins, which are marked with +5V (triangle) are connected together to the 5V power source. The triangle consisting of 3 horizontal lines marks ground. Normally all grounds are connected together to the ground pin of the power source.

So these symbols are used, so that you don't have to draw all the lines for connecting the power lines together.

# Answer
> 0 votes
Neither are shown in that schematic, as described in the text.

> ***Calibration Circuit:*** The weight calibration circuit is shown in figure 2. \[...\]
>
> \[A schematic that includes a 4.7kohm resistor\]

...

> Note: Cathode and Anode pin of LCD (pin 15 and pin 16) is not shown in circuit diagram. Connect +5 volt to pin 15 with current limiting resistor (generally 100-ohm) and pin 16 of LCD to ground.

---
Tags: power, pins, electronics, resistor
---


# Question
Title: How can I differentiate between multiple circuits?
I'm building a puzzle for an escape room. I want to give the user 6 wires and 6 terminals, then confirm that they've connected the correct wires to the correct terminals (one-to-one).

My first (successful) attempt to implement this puzzle was to connect the wires to 6 PWM analog outputs set to different levels, and connect the terminals to 6 analog input pins. By time-averaging the readings on the input pins, I was able to determine which wire(s) are connected to which terminals, if any.

I currently have no resistors in the circuits.

As the puzzle is currently designed, it's possible for the user to do weird things like:

* Connect multiple wires to the same terminal.
* Connect multiple wires together, without connecting them to any terminal.
* Touch multiple exposed wires and/or terminals.

My questions boil down to two:

* Is my current approach dangerous, either for the Arduino or my users, and are there recommended precautions I should take?
* Is there a better (safer or simpler or more robust) way to implement the puzzle?

I'm a software engineer, but a complete noob when it comes to *real* electronics and Arduino, so please feel free to assume I know nothing.

# Answer
> 4 votes
First, let's consider the logic of your program. You have two groups of pins: 6 pins connected to the wires and 6 pins connected to the terminals. The first thing I would do is forget that these are two different groups. Consider you just have 12 pins that the user has to connect in a specific fashion. This way most “weird things” the user could do, like connecting wires together, are not a special case anymore. They are just another invalid combination. Now what you have to do is, for every pair of pins among those 12, determine whether or not they are connected together. If any pair is connected that shouldn't be, you have an invalid combination. If any pair is not connected while it should be, it's again an invalid combination. If every pair is the expected state (either connected or not connected), then the user did solve the puzzle.

Now, for the hardware side. A simple way to know whether two pins are connected together is to set one of them to `INPUT_PULLUP` and the other one to `OUTPUT` `LOW`. This second pin should be the *only* one accessible to the user that outputs a `LOW`. All other exposed pins should be set as either `INPUT` or `INPUT_PULLUP`. Now, if the first pin reads `LOW`, you know have a connection. If it reads `HIGH` the two pins are not connected together.

Here is an example program demonstrating that principle. It loops over the 66 possible pairs to check whether they are connected or not. You just have to replace the inner `if` with your code that validates the combination.

```
const int PIN_COUNT = 12;
const uint8_t pins[PIN_COUNT] = {...};

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

    // Set all pins to INPUT_PULLUP.
    for (int i = 0; i < PIN_COUNT; i++)
        pinMode(pins[i], INPUT_PULLUP);
}

void loop() {
    // Loop over all pin pairs (pins[i], pins[j]).
    // Set pins[i] to OUTPUT LOW, then read pins[j].
    for (int i = 0; i < PIN_COUNT - 1; i++) {
        pinMode(pins[i], OUTPUT);
        digitalWrite(pins[i], LOW);
        for (int j = i+1; j < PIN_COUNT; j++) {
            if (digitalRead(pins[j]) == LOW) {
                Serial.print("pins ");
                Serial.print(pins[i]);
                Serial.print(" and ");
                Serial.print(pins[j]);
                Serial.println(" are connected together.");
            }
        }
        pinMode(pins[i], INPUT_PULLUP);
    }
}

```

As for the safety, you should be fine as long as the users do not have access to any low-impedance ground or voltage source. In particular, the GND and 5V pins should not be user-accessible. For extra protection, you could put a 1 kΩ resistor in series with each pin, but then all the pins that are not actively being tested should be set to `INPUT` rather than `INPUT_PULLUP`, otherwise multiple pullups in parallel may start to compete with the series resistor.

# Answer
> 3 votes
I would also connect the terminals to the 6 analog input pins and have 6 unique voltages, one per wire. The Arduino will only provide the output when the 6 wires are placed on the correct terminals. In other words, that is when the Arduino sees the correct analog voltage on the respective pins.

I personally would add a RC Low pass filter to the output of the PWMs. More information here. Your PWM output would go into the Vin and the then the Vout would go to your wire (ie the analog input). One filter per channel.

The RC filter will protect the Arduino from shorts to +ve, Gnd and the other pins as well as providing a bit of protection from static. It will also simplify your code.

At the moment you are having to implement fancy code to average out the voltage on those analog pins. The RC filter would essentially make that code not needed.

To calculate the value of the resistor and capacitor you need: There is a very good article over at All About Circuits that goes into this subject in detail.

To calculate the value we need to know the frequency:

> The frequency of the PWM signal on most pins is approximately 490 Hz. On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz. \- Arduino Analog Write

I used http://sim.okawa-denshi.jp/en/PWMtool.php to calculate the values of R & C needed with a very low ripple ( \< 60mV ) using common values. I based my calculations around the 490Hz as the lower frequencies perform worst with low pass filters.

I suggest you use values of `R = 10k` and `C = 4.7uF`. You can play with these values until you get the output you desire.

One last thing I would consider is to put some protection on the terminals that connect to the analog pins. This could be a small resistance in series, or a 5.1V zener in parallel (the pin may already have this?) or some capacitance in parallel.

---

**EDIT:**
I have just had a brainwave - You don't need to use the PWM's to output the different analog values - you could use a voltage divider circuit instead. No RC filter needed. For example:

simulate this circuit – Schematic created using CircuitLab

---

**Edit #2:**

> Jonathan Wrote:
> The only minor downside I'm noticing is that if the user has two wires connected to the same terminal, it affects all the voltages read across the other terminals, **making it hard to give the user incremental feedback** on how many wires are correctly connected.

This can easily be solved by providing 6 individual voltage divider networks, as shown below. Notice how each voltage divider has a different ratio.

simulate this circuit

---
Tags: analogread, analogwrite, safety
---


# Question
Title: Arduino code to run 2 thing simultaneously
I am making a project for my college in which I need to measure the rpm of the motor and show the real-time clock on the 128x64 GLCD simultaneously but when I run the project it only shows one thing at a time. is there any method to show both of them simultaneously I am not putting any code because I just compile my hall sensor separately and rtc code separately

# Answer
Arduino Microprocessors are mostly single core devices and thus are unable to do more than one thing at a time. The trick is to write code efficiently so it looks like several things are happening at the same time but in reality they just happen very quickly. The LCD only needs to show time every second and displaying RPM every second should be enough so to get both to happen within a second should be possible.
> 4 votes

---
Tags: timers, display
---


# Question
Title: Need help with understanding the CapacitiveSensor circuit diagram
Hey guys I need help with understanding the circuit diagram from this link: https://playground.arduino.cc/Main/CapacitiveSensor?from=Main.CapSense

As of now, this is the schematic I drew from what I understand:

I know it is wrong since they make use of 2 capacitors, but I do not know where should the other capacitor be connected to.

# Answer
The other capacitor shown in the article is the ambient capacitance (that is, the capacitance between the pin and the things around it). There is no actual capacitor.

What it is saying is that there is a RC circuit (the supplied resistor and the capacitance in the air) which will change the charging time of the RC circuit as the capacitance changes, when you move your hand near it.

---

From a comment:

> and the other capacitor with a value of 20-400pF

Yes, it **does** say that:

> Adding small capacitor (20 - 400 pF) in parallel with the body capacitance, is highly desirable too, as it stabilizes the sensed readings.

However that doesn't make any sense to me. How do you add a capacitor in parallel with your body? Do you carry one around with really long wires? And how do you hold it? I would ignore that part.
> 1 votes

# Answer
This question appears to get posted every week! There is NOT 2 capacitors. The Csensed capacitor in dotted lines is the capacitance added when you touch the plate. The Cpin capacitor is suggested to stabilise the readings and is not required. So in the circuit NO capacitors are used. All you need is a high value resistor between the Send Pin and Receive Pin and put your plate on the Receive Pin.
> 0 votes

---
Tags: hardware, electronics
---


# Question
Title: Error in finding frequency of an input signal
Here is my code to find the frequency of an input rectangular wave at pin 8 of the Arduino Uno board.

```
const uint16_t freqPin = PB0;
const uint16_t load = 0;
unsigned long int count=0;
unsigned int value=0;

void setup()
{
Serial.begin(9600);
DDRB = 0x00;
TCCR1A = 0;
TCCR1B = TCCR1B & B11111000 | B00000111;
TCNT1 = load;
TIMSK1 |= (1<<ICIE1);
TIMSK1 |= (1<<TOIE1);
sei();
}

void loop()
{
}

ISR(TIMER1_OVF_vect){

  count++;
}
ISR(TIMER1_CAPT_vect){
  value = TCNT1;
  TCNT1 = load;
  Serial.println(count);
  Serial.println(value);
}

```

The output is

```
0
0
0
0
0

```

Why the output is showing zeroes only. why is this happening ? Can someone explain?
Thanks in advance.

# Answer
There are a few ways to measure the frequency of the incoming signal. Here are ideas based on the assumption that's all you want, rather than to use specific pins of the Arduino:

* Use timer interrupts and `digitalRead(8);` (or faster `(PINB & _BV(0))`) to sample when the signal is high or low. Transfer the data off Arduino, e.g. to a PC, then do a Fourier transform (Matlab, Mathematica, Excel, whatever you like). Alternatively, calculate the frequency on-board. This way it is possible to measure frequencies up to several tens of kHz, with a precision of few Hz.
* Use `attachInterrupt()` on either digital pins 2 or 3. Count the number of rising edges of the square wave within a given time period. You can use the timer if you need accuracy, but the method will not be as good as Fourier transform.
> 1 votes

---
Tags: arduino-uno, digital
---


# Question
Title: How to map 6 bytes of raw data to long long type?
I'm trying to solve some problems for a contest, and I have a problem with it. I have to implement a function that has 3 arguments like this:

```
void foo(unsigned char* A, unsigned char* B, unsigned char* C);

```

And what comes in, is 6 bytes of data. I have to convert these 6 bytes of data to integer data (maybe long long). The problem is, I don't know how to map the bytes in the right order.

I'm using an Arduino Uno board.

Please help me with it.

# Answer
> 3 votes
The trick is to use a `union` data type and get full control of the mapping. The issue of data representation and endian is now under your control:

```
uint64_t foo(uint8_t* A, uint8_t* B, uint8_t* C)
{
  union {
    uint64_t X;
    struct {
      uint8_t A[2];
      uint8_t B[2];
      uint8_t C[2];
      uint8_t D[2];
    };
  } map;
#if defined(MSB_ORDER)
  for (int i = 0, j = 1; i < 2; i++, j--) {
    map.A[i] = 0;
    map.B[i] = C[j];
    map.C[i] = B[j];
    map.D[i] = A[j];
  }
#else
  for (int i = 0; i < 2; i++) {
    map.A[i] = A[i];
    map.B[i] = B[i];
    map.C[i] = C[i];
    map.D[i] = 0;
  }
#endif
  return map.X;
}

void setup()
{
  Serial.begin(9600);
  while (!Serial);
  uint8_t a[] = { 0x12, 0x34 };
  uint8_t b[] = { 0x56, 0x78 };
  uint8_t c[] = { 0x9a, 0xbc };
  uint64_t res = foo(a, b, c);
  Serial.print((uint32_t) (res >> 32), HEX);
  Serial.print((uint32_t) res, HEX);
}

void loop()
{
}

```

Cheers!

# Answer
> 1 votes
```
uint64_t foo(uint8_t* A, uint8_t* B, uint8_t* C)
{
    uint64_t aux = 0;
    aux = A[0];
    aux <<= 8;
    aux |= A[1];
    aux <<= 8;
    aux |= B[0];
    aux <<= 8;
    aux |= B[1];
    aux <<= 8;
    aux |= C[0];
    aux <<= 8;
    aux |= C[1];
    return aux;
}

```

following sample code:

```
  uint8_t a[] = { 0x12, 0x34 };
  uint8_t b[] = { 0x56, 0x78 };
  uint8_t c[] = { 0x9a, 0xbc };

  uint64_t result = foo(a, b, c);

  std::cout << std::hex << result;

```

returns `123456789abc`, try the code here, excluding the std::out part, the same code will run on arduino without any problem

# Answer
> 0 votes
When passing data to functions you do this...

```
foo(a,b,c);

```

You then extract the variables or data passed to the function like..

```
void foo(unsigned char* A, unsigned char* B, unsigned char* C) {
    A = whatever;
    B = whatever;
    C = whatever;
}

```

---
Tags: data-type, byte-order
---


# Question
Title: Reed Sensor matrix for chess board query
NOTE: This is not a question that has been answered previously in similar questions. I am using an arduino Mega

I have gone through Bergers Blog(schematic is in this link), but have been breaking my head on the logic of your sensor matrix, I have been breaking my head for the past few days on this one thing.

1. Initially he set all rows to HIGH then reset the 1st row to LOW to scan the reed sensors, let's assume that all the sensors in the 1st and 2nd row are closed.

My question is that since the 1st row is set to LOW won't it get shorted because the second row is initially set to HIGH?

Also, I used the same matrix as berger but instead I enabled the internal Pull up pins of all the 8 input pins, but yet again I faced the same problem of getting a short , since if a row 1 is set to LOW and row 2 is initially set to HIGH then One sensor in row 1 is closed and a reed sensor in row 2 below the sensor mentioned in row 1 is also closed. Then won't we get a short and random values show on the arduino.

# Answer
Almost all switch matrix keyboards use normally open / momentary contact switches. Consider this when discussing switch matrix behavior. Your initial (text) description is of a switch matrix only comprising of switches. For such a matrix, only one switch may be closed at any given moment. This is to prevent aliasing. A conditions where multiple simultaneous switch closures cause the incorrect key to be detected. And, in some cases, prevents harmful shorts.

Adding a forward biased diode to every switch in a matrix prevents harmful shorts. For a design where one row is driven high and all other rows are driven low, closing two switches in a single column can directly connect the row driven high with a row driven low in a switch matrix only comprising of switches. However, if a normally forward biased diode is placed in series with both of these closed switches, only the diode connected to the row driven high would be forward biased. The diode connected to the row driven low would be reversed biased preventing the harmful short.

Using diodes on every switch is costly. Most computer keyboard do not use this approach. Instead they use clever circuitry and layouts to prevent shorts and improve their perceived performance. In reality, almost all computer keyboard have an n-key-roll-over limit. A point at which the keyboard fails to detect or distinguish a new pressed key while other keys are already pressed.

For a graphic example of the behavior of a forward and reversed biased diode consider this image from allaboutcircuits.com where the diode on the left is in forward biased and the diode on the right is in reversed bias:
> 2 votes

# Answer
Mega has 70 inputs, 86 if you use a '2560 in a full breakout board. I offer a couple of form factors to access all pins at http://www.crossroadsfencing.com/BobuinoRev17

Chess board will always have multiple pieces in multiple rows and multiple columsns pressed until near the end of the game. I'd wire up each square individually, make life a lot easier. Read ports 8 pins at a time, 8 reads to have all 64 squares read.
> 0 votes

---
Tags: arduino-mega, programming
---


title: Powering Atmega328P-Pu externally

text:
# Question
Title: Powering Atmega328P-Pu externally
Please I'm new to Arduino and I need assistance. I'm working on a project which makes use of the ultrasonic sensor to make a certain pin high if a certain distance is attained. When I used the USB port to power it up it worked fine. When I use external power(tried two different 9V microphone battery) it's not giving desired result. Now I want to try using just the Atmega328P on the board externally(separately from the Arduino).

**Questions**

1. What could be the cause of the malfunction when I use external 9V battery
2. what voltage should I connect to the VCC of the Atmega cos I'm scared of damaging it.
3. Am I going to power the ultrasonic sensor with an entirely different source from the VCC or I can tap from that same VCC source.
4. Any other information I need to know using the ATmega on its own

# Answer
> 1 votes
**1.8 - 5.5V (max)**

The datasheet (http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P\_Summary.pdf) will tell you that input Voltage is: 1.8 - 5.5V

That's max of 5.5V so don't use 9V battery without a voltage divider. To power the chip all you need is voltage to Pin 7 and GND to PIN 8.

**16Mhz Crystal Most Likely Required**

However, to get it to work after removing the chip from an Arduino Uno board you will also need a 16Mhz Crystal on pins 9 & 10. You will also need two 22pF capacitors on pins 9 & 10, each connected to ground.

I've written this all up with pictures at my blog: http://raddev.us/arduino/post/2018/07/03/arduino-uno-using-your-atmega328p-u-as-stand-alone

Your final circuit will look something like the following (from my blog article):

Without the Crystal you will most likely find that your sketches don't seem to run.

**Note**: The red LED is connected just as a blink test (more on that in the article).

# Answer
> 1 votes
What you need is a voltage regulator! There are many options to choose from linear regulators to buck (or boost) DC-DC converter. You can buy them from various sources as well.

> What could be the cause of the malfunction when I use external 9V battery?

The ATMega can only handle 5V maximum, using 9V will either destroy it or engage protection circuitry that will prevent the chip from operating and being damaged.

> What voltage should I connect to the VCC of the Atmega?.

Most of the time an ATMega is powered with 5V, but depending on the clock frequency they can operate at lower voltages, the datasheet will have the details.

> Am I going to power the ultrasonic sensor with an entirely different source from the VCC or I can tap from that same VCC source?

With the appropriate choice of powersupply you can power both the AVR chip and your sensor with the same power supply.

> Any other information I need to know using the ATmega on its own?

The datasheet will contain all you need to know, but if you want to use the Arduino tool chain you will need to:

* Use an external crystal
* Burn the Arduino (or AvrDUDE) bootloader

---
Tags: sensors, atmega328, electronics
---


# Question
Title: Arduino SD count files and open last, How to?
I am trying to count files. I have one hidden file from Windows10 so i am doing "-1" but I want to open the last file and can't work out how, any help? Please, Thanks

```
#include <SD.h>
int entryCount = 0;
File root;
int total = 0;
int Lfile = 0;
void setup()
{
  Serial.begin(9600);
  pinMode(10, OUTPUT);
  SD.begin(4);
  root = SD.open("/");
  printDirectory(root, 0);
  root.close();
  Serial.println();
  Serial.print(total-1);
  Lfile = total-1;

  File dataFile = SD.open(Lfile);
  // if the file is available, write to it:
  if (dataFile) {
    while (dataFile.available()) {
      Serial.write(dataFile.read());
    }
    dataFile.close();
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.println();
    Serial.println("error opening last file");
  }
}

void loop()
{
  // nothing happens after setup finishes.
}

void printDirectory(File dir, int numTabs)
{
  while (true)
  {
    File entry = dir.openNextFile();
    if (! entry)
    {
      if (numTabs == 0)
      return;
    }
    for (uint8_t i = 0; i < numTabs; i++)
      Serial.print('\t');
    Serial.println(entry.name());
    total = entryCount;

    Serial.print(entryCount++);

    Serial.print('\t');

    entry.close();

  }
}

```

# Answer
> 1 votes
Consider using the exist() method found in the SD.h library you already are including in your program. Assuming you will create no more than 99 files and the last file created will have the highest 2 digit value as part of its name, test for the existence of the file log99.txt. If not found, decrement the 2 digit number and test for the existence of file log98.txt. Repeat this process until you find the newest file created.

---
Tags: sd-card, sd.h
---


title: Serial data showing up weird

text:
# Question
Title: Serial data showing up weird
I have a simple sketch that prints out "Hello World" to the serial, but I'm getting a bunch of gibberish instead.

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

void loop() {
    Serial.println("Hello World");
    delay(1000);
}

```

Why isn't it printing "Hello World" like the code says?

# Answer
> 10 votes
The board and terminal are probably not using the same baud rate. Check the bottom right corner of the Arduino Serial Terminal and make sure it is set to 9600.

# Serial Data

Serial communication works by sending the entire data stream one bit at a time. This is in contrast to the standard parallel port which sends one byte at a time. Both devices need to know at what speed the data is being sent. Furthermore, both devices need to be operating at the same speed. This is called the baud rate.

# Baud Rate

Baud really just means pulses per second. In the context of serial communication, it means how many bits are transmitted per second. One of the most common values is 9600, but there are other common ones which are factors or multiples of 9600. It doesn't really matter, though, as long as both devices operate at the same speed.

If I'm sending you messages faster than you are getting them, you lose data. If I am sending you messages slower than you are receiving them, you get nonsense mixed in with what I sent you.

# Data, Parity, Stop bits

If you look at the documentation for `begin()`, you'll see it can take two parameters:

```
Serial.begin(speed)
Serial.begin(speed, config)

```

Hopefully you understand speed now, it is the bits per second at which the Arduino will communicate.

The second parameter, `config`, lets you configure some other things about the serial data transmission. These are the Data, Parity, and Stop bits. You'll see on the page it has values like `5N1`, `6N1` and `SERIAL_8N1 (the default)`

The first number represents how many data bits. The second character tells you what kind of parity bit there is. `E` for even parity, `O` for odd parity, or `N` for no parity. The third number tells you how many stop bits.

So really, with 8N1, we have 10 bits being sent for each 8 bits of "your" data. 1 start bit, 8 data bits, and 1 stop bit.

Anyway, both sides need to agree on this information as well as the speed. The Arduino Serial Terminal doesn't give you the option of changing these settings, but others do, so you'll need to be sure all of these configuration settings are the same.

More info on wiki: Asynchronous serial communication

# Answer
> 2 votes
Sachleen's answer (above) says:

```
The board and terminal are probably not using the same baud rate.
Check the bottom right corner of the Arduino Serial Terminal
and make sure it is set to 9600.

```

If this number is 9600, and you still get garbled data, check the output you obtained when uploading the code. It should read something like:

```
Sketch uses 2754 bytes (8%) of program storage space. Maximum is 30720 bytes.
Global variables use 195 bytes (9%) of dynamic memory, leaving 1853 bytes for local variables. Maximum is 2048 bytes.
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM5 -b57600 -D -Uflash:w:C:\Users\Owner\AppData\Local\Temp\arduino_build_457862/LockCode.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

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

         Using Port                    : COM5
         Using Programmer              : arduino
         Overriding Baud Rate          : 57600

```

This bottom line (of what I have posted) says what your device's default baudrate is. For me, I changed `Serial.begin(9600);` --\> `Serial.begin(57600);` and checked that the bottom right corner of my Arduino Serial Terminal read 57600.

After I ran this, and it worked, I was able to switch back to 9600 and get non-garbled data. Arduino seems to be finicky...

# Answer
> 0 votes
I spent half an hour trying to solve that, and it was my Arduino Pro Mini that is **3.3V** and I had selected 5V in the Arduino IDE (on PC). Serial print never works like that even with same baud rate defined.

**Select the correct board** in the Arduino IDE.

To be clear, the correct processor (voltage/clock speed) under the **Tools** tab has to be selected.

---
Tags: serial
---


# Question
Title: How to connect an ESP8266 using an ESP-01 adapter to an Arduino Uno?
I am pretty new to Arduino programming and wanted to learn how to connect an ESP8266 generic WiFi module to an Arduino Uno using the ESP-01 Adapter shown in the image below.

I tried doing it on my own while connecting the Vcc, GND, Tx and Rx pins of the adapter to the 5V, GND, Tx and Rx of the Arduino Uno respectively but was getting the following error while trying to upload the sketch:

> warning espcomm\_sync failed
>
> error espcomm\_open failed
>
> error espcomm\_upload\_mem failed

To the best of my knowledge there is no tutorial on the internet that explains about the above mentioned adapter and its interfacing with the wifi module in detail. It would be a great help if someone could please guide me through the process so as to convert my Arduino into a server.

# Answer
Recommended tutorial

you can't flash an esp-01 module with this adapter, unless you find a way to connect io 0 to ground in this setup

I have this type of adapter with esp8266 glued. I can't recommend this type of adapter boards. Easier is to use a development board like Wemos or NodeMCU with on-board USB adapter. And they are cheap.

The adapter has the esp-01 2x6 header J2 but the io 0 and io 2 pins were not connected on my version. I patched io 0 to JP2 header to be able to flash the module. On the picture you see a paperclip jumper connecting GPIO0 to ground.
> 4 votes

# Answer
> ...connecting the Vcc, GND, Tx and Rx pins of the adapter to the 5V, GND, Tx and Rx of the Arduino Uno respectively...

At least one issue is the serial connections. Rx and Tx need to be cross-connected with whichever Arduino pins you are connecting to the ESP. Using the Arduino's built-in UART, Arduino pin #s 0 and 1, cannot work for uploading (to either board) since those pins are used to communicate with your PC.

If you are trying to upload to the Arduino, try removing the ESP adapter board during the upload. Even with that, communicating at run-time from the Arduino to the ESP (with it plugged back in, of course) may run into interference from the Arduino's 16U2 chip (serial \<-\> USB processor) which is hard-wired to those pins. And if it does work at run-time, you will have to forego serial communication to/from your PC, which uses those same pins.

The alternative is to use the SoftwareSerial library in your code, which will let you select two other Arduino pins as a second "software UART" to communicate to/from the ESP. This route come with it's own initial-setup complexities - you'll first have to change your ESP's default baud rate to 9600, about the maximum that SoftwareSerial can reliably receive. See my post about how to do this. To implement it, you'll need a short sketch that continuously tests Arduino's terminal for an available character and sends any to the ESP, and likewise tests the SoftwareSerial and sends to the Arduino's terminal.
> -1 votes

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


# Question
Title: I can't upload my program to Arduino Uno
I've not used my Arduino for about 2 months. Before this time it worked fine, but now when I want to upload my program I get this error:

> Couldn't find a Board on the selected port. Check that you have the correct port selected. If it is correct, try pressing the board's reset button after initiating the upload.

I reset immediately after uploading but it doesn't work.What else should I do? I'm using Ubuntu and the Arduino IDE.

# Answer
Checks:

* Check if the board has power (probably it will).
* Check if the board is shown at the ports in the IDE (i.e. COM3: Arduino Uno).
* Check if you put the correct board in the IDE (e.g. Uno, Mega etc.).
* Check if you have multiple versions of the IDE running.
* Check if you have multiple IDEs installed.
* Check if you don't have the RX pin used while uploading a sketch.

Try the following:

* Use a different USB port on your computer
* Use a different USB cable
* Reinstall the Arduino IDE
> 3 votes

# Answer
I struggled with a failure to upload the `Blink` program, with LED between #13 pin (+) and GND lead.

My solution was found by choosing other serial ports by stepping through the Serial Port options under the **Tools** menu

Selecting the correct port brought my new board to life!
> 0 votes

---
Tags: arduino-uno, uploading
---


# Question
Title: Pulse counter to measure flow-rate: 0 Pulse issues
I am using a Netafim M-Series flow meter interfaced with a UC-32 Arduino. The goal of this is to create a pulse counter than in turn will allow us to determine flow rate in the meter. (1 US gallon per pulse for this model.)

I am using a relatively simple program to test my wiring and the flow meter's connection to the UC-32. I will include it here:

```
int pin = 30;
volatile unsigned int pulse;
const int pulses_per_litre = 450;

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

  pinMode(pin, INPUT);
  attachInterrupt(0, count_pulse, RISING);
}

void loop()
{
  pulse = 0;
  interrupts();
  delay(1000);
  noInterrupts();

  Serial.print("Pulses per second: ");
  Serial.println(pulse);
}

void count_pulse()
{
  pulse++;
}

```

Code was obtained by a source online, since I will make my own to match my specific needs later on. The problem is, no matter how much I modify this code, I receive 0 pulses (even when blowing air into the meter). I have therefore narrowed down the problem to wiring.

I am using a small breadboard with a 1 kOhm Resistor. The flow meter requires 12v input that is supplied by a barrel jack power supply into the UC-32. I will show an image of my circuit. From what I can see, this should be working, but I feel like I'm sort of going insane looking over and over this circuit so I wanted to get an outside opinion.

Sorry about the large sizes images, but to me, it is a simple circuit that should work. I could be very wrong. Does anyone with perhaps experience with this sort of flow meter see any problems with my code/circuit?

# Answer
Fixed, wow. Sometimes typing out your problem helps answer the question. Resistor position was wrong, and adjusting the Vin wire.
> 1 votes

---
Tags: hardware, resistor, software
---


# Question
Title: Updating Server using ESp8266 with Direction Button Pressed IN
I've connected a 5-way tactile switch to a ESP8266 module and am using the Arduino IDE to create an automatically updating web server that displays the direction that the button is pressed in when pressed. Currently the webpage displays the first direction that the button was pressed in but does not update the page after I press the button several more times. Below is my code:

```
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

//ssid and password info, ommitted here for obvious reasons

int upPin = 5;
int leftPin = 4;
int centerPin = 0;
int rightPin = 2;
int downPin = 14;

ESP8266WebServer server ( 80 );

void handleRoot() {
    server.send(200, "text/html", "<html>\
  <head>\
    <meta http-equiv='refresh' content='1'/>\
  </head>\
  <body>\
  </body>\
</html>");   // Send HTTP status 200 (Ok) and send some text to the
browser/client
}

void setup(){
 Serial.begin ( 115200 );
 WiFi.mode ( WIFI_STA );
 WiFi.begin ( ssid, password );

 server.on ( "/", handleRoot );
 server.on ("/", button );
 server.begin();

void loop(void){
  server.handleClient();
  button();
}

void button(){
  if (digitalRead(rightPin) == LOW)
  {
    server.send(200, "text/html", "<p>*RIGHT#</p>");
    delay(10);
  }

  if (digitalRead(leftPin) == LOW)
  {
    server.send(200, "text/html", "<p>*LEFT#</p>");
    delay(10);
  }

  if (digitalRead(upPin) == LOW)
  {
    server.send(200, "text/html", "<p>*UP#</p>");
    delay(10);
  }

  if (digitalRead(downPin) == LOW)
  {
    server.send(200, "text/html", "<p>*DOWN#</p>");
    delay(10);
  }

  if (digitalRead(centerPin) == LOW)
  {
    server.send(200, "text/html", "<p>*CENTER#</p>");
    delay(10);
  }

}

```

# Answer
> 1 votes
I changed the code so that the button function runs with "/" and took out the server.on("/", handleRoot) line, thanks to @Juraj. *Sigh*

---
Tags: esp8266, arduino-ide, web-server
---


# Question
Title: Help - Atmega328p, converting a PWM servo code from pin9 to pin6
I found a working code that uses pin9 (PB1) on my Arduino for controlling a Servo, but in my project, an ultrasonic sensor is already using that pin/timer. I want to convert the code to use pin6 (PD6), changed the registers according to the atmega's datasheet, but it doesn't work. Need help :/

The code should allow me to turn a servo using a potentiometer.

```
#define F_CPU 16000000 //16MHz
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include <stdlib.h>

#define PWM_PRESCALLER 64
#define ICR_MAX (long double)F_CPU/PWM_PRESCALLER/50
#define OCR_MIN (float)ICR_MAX/37.5 // /8.75
#define OCR_MAX (float)ICR_MAX/8.7 // 37.5

volatile unsigned long adc_val=0;
volatile unsigned long counter=0;
unsigned long curr_adc=0;

ISR (ADC_vect)
{
adc_val += ADC;
counter++;
}

int main(void)
{
    DDRD |= (1<<DDD6);
    ICR1 = ICR_MAX;
    OCR0A = OCR_MIN;
    TCCR0A = (1 << COM1A1) | (1<<WGM00) | (1<<WGM01);
    TCCR0B = (1<<WGM02) | (1<<CS01) | (1<<CS00);
    ADMUX = (1 << REFS0);
    ADCSRA = (1 << ADEN)|(1 << ADATE)|(1 << ADIE)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);

    sei();
    ADCSRA |= (1<<ADSC);

    while(1)
    {
        if(counter >= 1000)
        {
            cli();
            unsigned long round_val = round(adc_val / counter);
            adc_val=0;
            counter=0;
            if(abs(round_val - curr_adc) > 1)
            {
                curr_adc = round_val;
            }
            long double ocr = OCR_MIN + ((long double)curr_adc * (OCR_MAX - OCR_MIN)/1024);

            OCR0A = (int)round(ocr);
            sei();
        }
    }
}

```

# Answer
PORTB bit 6 is controlled with TIMER0 while PORTB bit 1 is controlled with TIMER1. Therefore you need to change the timer variables appropriately. One mistake in your code is that you leave ICR1. It should be OCRA if you want to use TIMER0.
> 1 votes

# Answer
I agree with Nick Gammon's comment that it is a lot easier using the Arduino Platform and use `AnalogRead()` function in conjunction with the servo library.

Having said that, you have chosen to write the program from scratch as many others prefer to do for one reason or another. I wanted to pass on the 2 web pages that I always go to when I am playing with the PWM frequencies and setup.
> -1 votes

---
Tags: servo, pwm, avr
---