message:
How do i improve this Code? (or how to pass a Char String into a Function to behave like a Variable)

Sorry i am a beginner and amateur when it comes to coding, can somebody help me to make the code inside the loop() less "monkey-like" by using a proper function?

I have tried a lot and at some point i am running out of ideas about how to even phrase the question on google.

My main problem when writing a function for this case is that i don't know how to pass a variable into a function which has to be written out as part of a Variable but also as part of Char Strings if that makes sense.

If you look at the code inside the loop() i actually only had to pass the number to the function, like "3" to change some Variables and Char Strings accordingly. I would be able to solve the issue with those Char Strings but i am completely clueless how to handle the Variable (rmd3, rmd4...).

"3" as in:
Variable:        rmd3,    Char String      "rmd3 = 1",   Variable Value:  rotary_mode = 3   and Char String:     "rotary_mode = 3"

This is a simplified version of my code but boils down to where i am stuck at. It refers to a rotary selector i am using which has 6 Positions (rmd1 - rmd6). However if i knew how to solve this issue i could use it in many other situations as well.

```#include <Bounce.h>

Bounce rmd3 = Bounce(45,10);    //rotary selector on pos.3
Bounce rmd4 = Bounce(44,10);    //rotary selector on pos.4
int rotary_mode = 0;            //Rotary Mode

void setup() {
  Serial.begin(11520);
  pinMode(45, INPUT_PULLUP);   //pin of pos.3
  pinMode(44, INPUT_PULLUP);   //pin of pos.4
  }

void loop() {
             rmd3.update();
             if (rmd3.fallingEdge()) {
                Serial.print("rmd3 = 1");
                rotary_mode = 3;
                Serial.print("rotary_mode = 3");
             }
             if (rmd3.risingEdge()) {
                Serial.print("rmd3 = 0");
                rotary_mode = 0;
                Serial.print("rotary_mode = 0");
             }

             rmd4.update();
             if (rmd4.fallingEdge()) {
                Serial.print("rmd4 = 1");
                rotary_mode = 4;
                Serial.print("rotary_mode = 4");
             }
             if (rmd4.risingEdge()) {
                Serial.print("rmd4 = 0");
                rotary_mode = 0;
                Serial.print("rotary_mode = 0");
             }
}´´´

Pseudocode:

´´´void loop() {
int rmd_int;            //Mode numbers as int from 1 to 6
char rmd_char = [2];    //Mode numbers as char from "1" to "6"

              rmd3.update();
              rmd_int = 3;
              rmd_char = "3";
              void selected_mode(rmd_int, rmd_char);
}

void selected_mode(int rmd_int, char rmd_char ){
             if (rmd[rmd_int].fallingEdge()) {
                Serial.print("rmd[rmd_char] = 1");
                rotary_mode = [rmd_int];
                Serial.print("rotary_mode = [rmd_char]");
             }
             if (rmd[rmd_int].risingEdge()) {
                Serial.print("rmd[rmd_char] = 0");
                rotary_mode = 0;
                Serial.print("rotary_mode = 0");
             }
}```

body:
The question is somewhat confused, but I think I got what you mean. Your
code suffers from too much repetition. You only showed the handling of
two selectors, but you want to handle 6 of them. Repeating all the logic
6 times would make the code unwieldy and hard to maintain. So you
want to put the logic in a function and just call that function six
times.

> I actually only had to pass the number to the function, like "3" to
> change some Variables and Char Strings accordingly

You do not need to pass the number as a string: you can use
`Serial.print()` to format the number instead. And you do not need to
write a function either: you can just put a `for` loop inside the
`loop()` function:

```c++
const int rmd_count = 6;

Bounce rmd[rmd_count] = {
    Bounce(48, 10),  // rotary selector on pos. 0
    Bounce(47, 10),  // rotary selector on pos. 1
    Bounce(46, 10),  // rotary selector on pos. 2
    Bounce(45, 10),  // rotary selector on pos. 3
    Bounce(44, 10)   // rotary selector on pos. 4
    Bounce(43, 10)   // rotary selector on pos. 5
};

void loop() {
    for (int i = 0; i < rmd_count; i++) {
        rmd[i].update();
        if (rmd[i].fallingEdge()) {
            Serial.print("rmd[");
            Serial.print(i);
            Serial.println("] = 1");
            rotary_mode = i;
            Serial.print("rotary_mode = ");
            Serial.println(i);
        }
        if (rmd[i].risingEdge()) {
            Serial.print("rmd[");
            Serial.print(i);
            Serial.println("] = 0");
            rotary_mode = 0;
            Serial.println("rotary_mode = 0");
        }
    }
}
```

The key to using `for` loops is to structure your data in arrays,
instead of collections of variables named with numbers. Thus, instead of
`rmd3` you would use `rmd[3]`. Note that array indices start at zero.

Obviously, you could put the body of the `for` loop inside a function,
but at this point that would not help much in simplifying the code.

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

**Edit**: As a clarification, and per Delta\_G's suggestion, I'll try to
explain the difference between an array and a collection of variables.
Each variable you define is mapped by the compiler (technically, the
linker) to a memory area. You can think of the variable names as
convenient names assigned to those memory locations. If you write:

```c++
Bounce rmd0(48, 10), rmd1(47, 10), rmd2(46, 10), ...;
```

You get:

```text
      ┌───────┐        ┌───────┐        ┌───────┐
rmd0: |       |  rmd1: |       |  rmd2: |       |  ...
      └───────┘        └───────┘        └───────┘
```

In the picture above, the boxes are the memory areas. They are large
enough to hold a `Bounce` object, i.e. their size is `sizeof(Bounce)`.
Each one has a name. You have no control over where, within the memory,
those variables are allocated: it's the linker's call.

In contrast, when you declare an array, you get a _single variable_
which is mapped to a contiguous memory area large enough to hold the
whole array:

```c++
Bounce rmd[6] = { ... };
```

Gives:

```text
     ┌───────┬───────┬───────┬───────┬───────┬───────┐
rmd: |       |       |       |       |       |       |
     └───────┴───────┴───────┴───────┴───────┴───────┘
```

The individual cells do not have a name, and you instead use indices to
access them. For instance, `rmd[0]` references the first cell. Please,
note that in this example there is no variable named `rmd0`: if you try
to use that identifier the compiler will complain it is not defined.
Again, an array is not a “collection of variables”: it is a single
variable.

The array cells do behave in some sense much like individual variables
(they are called _lvalues_), as you can use `rmd[0]` in the same way you
would have used `rmd0` in the previous code. The point of using an array
is that the indices do not need to be literals: you can use a variable
instead (`rmd[i]`, where `i` is a variable), which comes handy when you
want to loop over all the cells.

> Edgar pointed out that I can write the variable `rmd3` by `int i = 3`
> and `rmd[i]`.

I hope it is now clear that this is not the case. There is no variable
named `rmd3` unless you create it explicitly. Declaring an array named
`rmd` _does not_ create such a variable.

> [Can I] "form" a variable by "characters"?

Your question is not very clear, but my guess is you are talking about
_computed variable names_. This is a programming technique where you
access a variable by computing its name at run time. For example, you
combine the strings "rmd" and "3" in order to build the name of the
variable "rmd3". Then you use this computed name to access the variable
that has this name.

Computed variable names are quite often supported by interpreted
languages. For example, in PHP this is called _variable variables_:

```php
$foobar = 42;           // the variable we want to access
$start = "foo";         // one piece of the name
$end = "bar";           // the other piece
$name = $start . $end;  // build the name from its pieces
print $name . "\n";     // prints the variable name: "foobar"
print $$name . "\n";    // prints the variable's value: "42"
```

Computed variable names are _not_ supported by C++, which is the
language you use to program an Arduino. And for a good reason: when the
compiler translates your program to machine code, the names of the
variables are lost, they do not make their way to the actual Arduino.
And this is a good thing, as you would not want those names to consume
memory on the microcontroller.

Note that the names are present in the .elf file, as they could be
useful for debugging. If you were programming for a PC, you program
could in principle look into the file and find those names. On Linux you
would do that with the [`dlopen()`][dlopen] and [`dlsym()`][dlsym]
functions, from the libdl library. The libdl technique is, however, very
far from the capabilities of your typical Arduino, orders of magnitude
more complex than a simple array, and perfectly useless for your use
case.

[dlopen]: https://man7.org/linux/man-pages/man3/dlopen.3.html
[dlsym]: https://man7.org/linux/man-pages/man3/dlsym.3.html


sender: user

message:
What is the best and most reliable way to detect if a book is pulled out of a book case?

I have a book case which I want to mount sensors to so that I can detect when certain books are pulled out, I don't need to know how much, all I need is a boolean trigger if the book has been pulled out 2+ cm or so (works with lower too). I would preferably also want to know when they have been replaced but that is just a bonus.

The goal of the project is to move a servo which may or may not open a secret door when 3 books are pulled out in a certain order.

The sensors need to be able to work continuously 24/7 for years.

Here is a masterfully drawn picture to explain it even better.

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

So far I have been thinking of mechanical switches, Ultrasonic Sensor (HC-SR04), or possibly some sort of infrared light and sensor that can detect a change in intensity (where a lower intensity is book being pulled out).

The mechanical switch I could easily do, but I would prefer something that is less obvious, and less "clicky" when it's triggered. I don't want to give away that there is something special with a book if someone picks it up on accident.

Any ideas on how it can be done?
Would love tips for specific components as I'm not native to the arduino world and have a hard time finding exactly what I'm looking for.

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

sender: assistant

body:
I assume all these solutions need to know exactly what book is where (positioned).

A solution could be a long LED strip (or other light) above the books, and at the bottom a strip of photo resistors (LDR), placed at every 2 cm. Place this photo resistors far enough backwards to cover the end of the shortest book (unless you do never change the order of the books you can place them exactly at the width of the book minus a cm or so).


body:
As Majenko stated in the comments, an easy and discrete way would be using IR proximity sensors behind each book. The IR light from them is invisible to the eye, they are easy to read with an Arduino and often the casing of the IR LED and IR sensor are black, so that you could easily hide them in a black backplate of your book case.

The IR sensor will output one pin state (HIGH or LOW depending on the sensor), when something (the book) is near it (on most sensor modules you can change to threshold to your liking), and the other, if nothing is near it (empty place in the book case)

Searching "ir proximity sensor" at amazon gives multiple good looking results for ready to use sensor boards.

---

Another - more hacky - way would be to build your own switches at the top of the book case. As a switch is nothing more than 2 electrical contacts with some mechanic suroundings, you could add a small piece of cardboard above each book, which falls down a bit, when the book is removed, but not enough, that it is easily spotted (a few millimeters should be enough). At the top of the case and on the cardboard piece you put some piece of tinfoil or aluminum tape. When the book is put in the box, the tinfoil pieces get pressed together by the book, thus make contact. Wire one piece to ground, the other to an Arduino pin.

I find the IR sensor solution better, but I wanted to include a solution, where you don't need to buy extra sensor modules.


body: Why not use RFID tags and sensor. You can do an inventory any time you want. The RFID tags are inexpensive and the sensor is not that much and available for the Arduino. Nothing shows if you put the tag in the spine of the book.


body: If you want the book and shelf to look normal, then use tiny magnets in the books and either reed switches or hall magnetic sensors embedded in the bookshelf. You can even discriminate two books by minding the magnet's polarity.


message:
Convert Hex to Decimal from signed 2's complement

I am reading data from a meter over dlms protocol and I am getting hex values from there. I want to convert that hex string to signed decimal value. For example - ff9d denotes a value of -99 [[reference]][1].

My hex to decimal code is:
```
unsigned int hexToDec(String hexString)
{
  unsigned int decValue = 0;
  int nextInt;

  for (int i = 0; i < hexString.length(); i++)
  {
    nextInt = int(hexString.charAt(i));
    if (nextInt >= 48 && nextInt <= 57) nextInt = map(nextInt, 48, 57, 0, 9);
    if (nextInt >= 65 && nextInt <= 70) nextInt = map(nextInt, 65, 70, 10, 15);
    if (nextInt >= 97 && nextInt <= 102) nextInt = map(nextInt, 97, 102, 10, 15);
    nextInt = constrain(nextInt, 0, 15);
    decValue = (decValue * 16) + nextInt;
  }
  return decValue;
}
```

Can anyone please help me how to do it in Arduino IDE?

  [1]: https://www.rapidtables.com/convert/number/hex-to-decimal.html

body:
> For example – ff9d denotes a value of -99

The function you wrote returns an _unsigned_ integer which, being
unsigned, cannot be negative. The simple fix is to declare it as

```c++
int hexToDec(String hexString)
```

That should be enough to get it working as expected. Note that the local
variable `decValue` still has to be unsigned, otherwise you would get a
signed overflow, which is _undefined behavoir_ (i.e. “forbidden”) in
C++. Returning an unsigned number from a function that is supposed to
return a signed number is perfectly fine: you get an implicit conversion
which is guaranteed to do the right thing.

Now, if I may provide some more feedback about this function:

* Use, if you can, plain C strings (`char *`) instead of `String`
  objects, as the latter are not very friendly to your Arduino's memory.
* Use fixed-length integers (`uint16_t` if your protocol dictates 16-bit
  integers) instead of the generic `int`, otherwise your code will fail
  if you move to a 32-bit platform, such as an ARM-powered Arduino.
* Use character literals (`'0'` instead of `48`) instead of hard-coding
  ASCII code points, as that makes the code more readable.
* Use a simple subtraction (`nextInt - '0'`) instead of the quite
  expensive `map()` function.

Here is my take at it. Note that it has a “classic C” accent you do not
need to replicate. You may prefer using indices to crawl the string.

```c++
int16_t hex2int(const char *hex)
{
    uint16_t value;  // unsigned to avoid signed overflow
    for (value = 0; *hex; hex++) {
        value <<= 4;
        if (*hex >= '0' && *hex <= '9')
            value |= *hex - '0';
        else if (*hex >= 'A' && *hex <= 'F')
            value |= *hex - 'A' + 10;
        else if (*hex >= 'a' && *hex <= 'f')
            value |= *hex - 'a' + 10;
        else
            break;  // stop at first non-hex digit
    }
    return value;
}
```

Example usage:

```c++
Serial.println(hex2int("ff9d"));  // prints "-99"
```

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

**Edit**: As revealed by the comments, the whole question is an [XY
problem][]. You are asking help about your misguided _solution_ rather
than your actual _problem_. The data you have is not hex: it's binary.
You have a 16-bit signed integer stored in a byte array, most
significant byte first. You figured out you can convert that to an
integer by converting it first to a string representation as
hexadecimal, then converting that representation back to a binary
number. Of course you can do that, but it's an overly complicated and
expensive way of doing something trivial.

The canonical way to recover an integer from a byte array is by
assembling the bytes together using bitwise logic and bit shifts. In
this case:

```cpp
int16_t reactive_power = (uint16_t) data[dataSize - 5] << 8
                       | data[dataSize - 4];
```

[XY problem]: http://xyproblem.info/


body:
Which mode of DLMS you are you using?

 > IEC 61107 or currently IEC 62056-21, was an international standard for a computer protocol to read utility meters. It is designed to operate over any media, including the Internet. A meter sends ASCII (in modes A..D) or HDLC (mode E) data to a nearby hand-held unit (HHU) using a serial port. [IEC 62056](https://en.wikipedia.org/wiki/IEC_62056)

In your question you mentioned:

 > hex string

which means a string of hex characters using ASCII (modes A to D).

However, in the comments you mentioned:

 > `void ReactivePower(unsigned char data[], int dataSize)`
 > `String reacP = String(data[dataSize - 5], HEX) + String(data[dataSize - 4], HEX);`

which means an array of bytes obtained from a stream of bytes using HDLC (mode E).

ASCII (Modes A to D)
====================

For ASCII (modes A to D), there is a simple transformation to get the digit value from the hex character.
```none
              ASCII
 Hex   --------------------                            Digit
 char  Decimal  Hexadecimal    Op1    Low nibble  Op2  Base 10
-----  -------  -----------  -------  ----------  ---  -------
 '0'      48        30        & 0x0F       0              0
 '1'      49        31        & 0x0F       1              1
 '2'      50        32        & 0x0F       2              2
 '3'      51        33        & 0x0F       3              3
 '4'      52        34        & 0x0F       4              4
 '5'      53        35        & 0x0F       5              5
 '6'      54        36        & 0x0F       6              6
 '7'      55        37        & 0x0F       7              7
 '8'      56        38        & 0x0F       8              8
 '9'      57        39        & 0x0F       9              9
 'A'      65        41        & 0x0F       1       +9    10
 'B'      66        42        & 0x0F       2       +9    11
 'C'      67        43        & 0x0F       3       +9    12
 'D'      68        44        & 0x0F       4       +9    13
 'E'      69        45        & 0x0F       5       +9    14
 'F'      70        46        & 0x0F       6       +9    15
 'a'      97        61        & 0x0F       1       +9    10
 'b'      98        62        & 0x0F       2       +9    11
 'c'      99        63        & 0x0F       3       +9    12
 'd'     100        64        & 0x0F       4       +9    13
 'e'     101        65        & 0x0F       5       +9    14
 'f'     102        66        & 0x0F       6       +9    15
```

 - For characters '0' to '9', simply `AND` with 0x0F.
 - For characters 'A' to 'F' and 'a' to 'f', `AND` with 0x0F and `add` 9.

```c++
char ch = '1';
byte b = 0;
if (ch >= '0' && ch <= '9')
{
  b = ch & 0x0F;
}
else if ((ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f'))
{
  b = (ch & 0x0F) + 9;
}
```
It's also important to know whether the transformation was successful, e.g. the first character could be bad (either a null terminator or non hex character), so this needs to be tested for during the transformation. Also, there are four nibbles in an `int16` so the transformation needs to quit when a maximum of four hex characters have been processed:
```c++
void setup()
{
  pinMode(13, OUTPUT);
  Serial.begin(115200);
}

void loop()
{
  char string[] = "A";
  //char string[] = "Waffle";
  //char string[] = "ff9d";
  int16_t the_int = 0;
  int count = AsciiToInt16(string, the_int);

  Serial.print(string);
  Serial.print(",  ");
  if (count)
  {
    Serial.print("Ok,  ");
    Serial.print(count);
    Serial.print(",  ");
    Serial.println(the_int);
  }
  else
  {
    Serial.println("Bad");
  }
}

int AsciiToInt16(const char* ch, int16_t& value)
{
  int count = 0;
  byte nibble = 0;

  // Stop after 4th nibble or null terminator.
  for(int i = 0; i < 4 && ch[i] != 0; i++)
  {
    if (AsciiToNibble(ch[i], nibble))
    {
      value <<= 4;
      value |= nibble;
      count++;
    }
    else
    {
      break;  // Stop after non hex digit.
    }
  }
  return count;
}

bool AsciiToNibble(const char ch, byte& b)
{
  if (ch >= '0' && ch <= '9')
  {
    b = ch & 0x0F;
    return true;
  }
  else if ((ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f'))
  {
    b = (ch & 0x0F) + 9;
    return true;
  }
  return false;
}
```
**Output**
```none
A,  Ok,  1,  10
Waffle,  Bad
ff9d,  Ok,  4,  -99
```

HDLC (Mode E)
=============

For HDLC (mode E), simply do:
```c++
void ReactivePower(byte data[], int dataSize)
{
  uint16_t reacP = (data[dataSize - 5] << 8) | data[dataSize - 4];
  Serial.println(dataSize);
  Serial.println(reacP);
}
. . .
  byte data[] = { 1, 3, 5, 2, 4, 8 };
  ReactivePower(data, sizeof(data));
```
**Output**
```none
6
773
```


message:
status whether the switch is connected to arduino or not?

I made a small circuit in which a push-button is connected to Arduino via a pulldown resistor. So, whenever it is pressed it connects to 5V otherwise pulled down to the ground. this is working fine but I wanted to know is there any way to detect whether the push-button is connected to the circuit or not? In case if push-button disconnects from the circuit, how to detect it?

body:
The simplest way, as @jsotola has said, is to put a resistor across the terminals of the SPST push-button and read the voltage using an ADC input of the MCU.

However, the resistor needs to be bonded to the push-button (or inside the push-button housing) to ensure that when, for example, a vandal rips the push-button out of your switchboard, the resistor is certain to go with it so that the MCU can tell the difference between HIGH, LOW, and MISSING as @EdgarBonet pointed out. You also need to consider the continuous current draw of the extra resistor for low power/battery devices. You could increase the resistor values, but that tends towards weak pullup/pulldown. If you increase the value of only the extra resistor, it shifts the output voltage closer to the rail voltage reducing the margin for error.

[![SPST Push-Button AWOL Detector][1]][1]

*Figure 1 – SPST Push-Button AWOL Detector.*

Perhaps a better, but more expensive way, is to use a SPDT push-button. This push-button requires no modification, but is more expensive than a SPDT push-button and requires an extra wire and resistor. This circuit draws less continuous current and has stronger pullup/pulldown.

[![SPDT Push-Button AWOL Detector][2]][2]

*Figure 2 – SPDT Push-Button AWOL Detector.*

  [1]: https://i.stack.imgur.com/oKiBm.png
  [2]: https://i.stack.imgur.com/ShY1y.png


message:
can i use bluetooth from a speaker as a bluetooth module?

**i have a Bluetooth speakers that i don't want,and i was wondering if i can use its Bluetooth as a Bluetooth module to use it with Arduino.
if so how what pins should i use. here is a pin diagram for the module.**

[![pin diagram of the bluetooth module][1]][1]

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

body:
Bluetooth actually uses many different protocols to support many different Bluetooth applications.  For 2 channel good fidelity music with high latency and a very low bandwidth return only suitable for short infrequent commands like PAUSE and PLAY, most use [A2DP or Advanced Audio Distribution Profile][1].

As most Arduino platforms use very low powered processors, good fidelity sound manipulation is not possible or is very difficult.  This only leaves the very low bandwidth return channel only suitable for short infrequent commands.  If you can imagine a use case for this channel it may be possible to use a low powered Arduino to send these PAUSE, PLAY, STOP type commands.

That said, you may want to buy a new well supported (in the Arduino community) Bluetooth module which uses the [HID (Human Interface Device) protocol][2] so you can build a keyboard for example or which uses the [SPP (Serial Port Profile) protocol][3] so you can build something that sends arbitrary data.

Added later...

I see in the diagram that there may be an "microphone in pin".  If true this hints that the module also supports the Bluetooth [HFP (Hands Free Profile) protocol][4].  This is a lower fidelity 2 directional low latency audio channel with a very low bandwidth return only suitable for short infrequent commands like ANSWER and HANGUP.  Instead of music this is used to make phone calls.  This might be of more interest to Arduino project builders as this might be made into an intercom.

  [1]: https://en.wikipedia.org/wiki/List_of_Bluetooth_profiles#Advanced_Audio_Distribution_Profile_(A2DP)
  [2]: https://en.wikipedia.org/wiki/List_of_Bluetooth_profiles#Human_Interface_Device_Profile_(HID)
  [3]: https://en.wikipedia.org/wiki/List_of_Bluetooth_profiles#Serial_Port_Profile_(SPP)
  [4]: https://en.wikipedia.org/wiki/List_of_Bluetooth_profiles#Hands-Free_Profile_(HFP)


message:
AccelStepper help - it just won't move!

I should begin by saying I am not a programmer, do not really know much about programming, and am programming an Arduino Uno for the first time. I am using a Nema 23 motor (23HS22-2804S) with a microstep driver (ST-M5045). Within the following code is the description of what I need the program to do:

```
#include <AccelStepper.h>

/* Using a stepper motor,
 rotate a vibrational model using gears interconnected by springs
 in such a way as to induce torsional vibration, which should be visible by comparing
 movement of juxtaposed rotating gears with markers painted on. */

AccelStepper stepper(AccelStepper::FULL4WIRE, 2, 6, 4, 8);

int Microstepping = 8; /* Microstepping factor, as set on the ST-M5045 control board.
                          Multiplies the number of steps per revolution on the stepper motor.
                          Reference controller manual for adjustments to this number. */
int Steps = 200; /* Number of steps on your stepper motor.*/
int SPS;
int Amp;
int Freq;
// int SC;
int n = 2;
int i;
int totalSteps = Microstepping * Steps;

/* It should be noted that the Microstepping and Steps factors are not necessary, and adjusting the microstepping factor
 *  on the fly will not break the code. However, be aware that changing the microstepping factor by more than one interval
 *  at a time can cause the motor to not keep up with the sudden changes, i.e. losing torque or vibrating/stuttering. */

void setup() {               // THIS RUNS ONCE //

  // read potentiometers; raw inputs from 0 to 1023 //
  SPS = analogRead(0)*0.733; // MAX RPM ~28, max speed ~750 steps per sec (speeds above 1000 steps per second are unreliable,
                             // according to AccelStepper documentation)//
  Amp = analogRead(1)/20;     // MAX AMP ~51//
  Freq = analogRead(2)/170;   // MAX FREQ ~6 Hz//

  stepper.setMaxSpeed(SPS);
  stepper.setAcceleration(SPS/1.5);

  int nextStop = totalSteps/Freq;

  stepper.moveTo(nextStop);
  stepper.run();
}

void loop() {
  int nextStop = totalSteps/Freq;

// reaches here, doesn't execute if loop.
   if(stepper.distanceToGo()== 0){
     SPS = analogRead(0)*0.733;
     Amp = analogRead(1)/20;
     Freq = analogRead(2)/170;
     i = SPS - Amp;
     if(i <=0)
       i = 1;
     stepper.setSpeed(i);
     stepper.moveTo(nextStop*n);
     stepper.run();
    }
    n++;
}
```

When I use Serial.println() to check where the program is working and where it isn't, I see that it completes the setup loop without ever moving, and in slightly different versions of the same code, it has entered the if() statement and executed it (also without moving.)

An earlier version of the program runs and executes all statements, but only moves a maximum of about 20 steps per second, without the fluctuations in speed I call for, and doesn't respond in real time to any input from the speed potentiometer that puts the speed above 20.

Ideally, the program would run the demo at full speed, and *freq* times per second, it would slow down just enough to be noticeable as a torsional vibration.

I have tried running the program with and without the run() lines, and I have tried using runToNewPosition(<position>) in attempts to get the program to stop and properly execute the movement.

I made the setup loop as close as possible to the setup loop in bounce.pde, the example program in the AccelStepper documentation which moves the stepper motor between two points repeatedly, accelerating and decelerating before changing directions. The reason I did this is because I know that the setup loop in bounce.pde *works*, and so I would feel more confident that my setup loop is not the root problem.

Any help you can offer me is appreciated! Thanks for your time.

body:
Please read the documentation for the AccelStepper library.

> Poll the motor and step it if a step is due, implementing
> accelerations and decelerations to achieve the target position. **You
> must call this as frequently as possible**, but at least once per
> minimum step time interval, preferably in your main loop. Note that
> each call to run() will make at most one step, and then only when a
> step is due, based on the current speed and the time since the last
> step.

[source](http://www.airspayce.com/mikem/arduino/AccelStepper/classAccelStepper.html#a608b2395b64ac15451d16d0371fe13ce)

You are only calling `run` once, after setting a new position.

Move `stepper.run();` out of the `if` statement, the the end of the `loop` function.

```
      ...
      stepper.moveTo(nextStop*n);
    }
    stepper.run();
    n++;
}
```


message:
How to connect 10 coin vibration motors to UNO?

I am new to arduino and anything related to electricals and electronics. I need info on how to connect 10 vibration motors to arduino uno without damaging the board. Do I need an external circuit to regulate and control power supply or can I directly plug in all 10 motors to the board directly?

body:
I would suggest a pair of ULN2003 chips.  These are 6 darlington transistors in a single chip.   Two chips will give you the ability to connect 12 motors.

Each one needs an IO pin to control it - if you want speed control then you will have to look into adding extra PWM channels. For just ON/OFF control any IO pin will do (even analog ones).

10 motors running at the same time will be up near the limit of the Arduino's 5V pin current supply, so you really should consider a separate external 5V power supply (maybe a USB phone charger) of 1A or more to power everything (connect the power supply to the motors and the 5V pin of the Arduino).


body:
The motor is not a constant output device, it still works by watts of power. The motor will only draw enough current to move its load at a given speed. Lets assum the impedance of the motor is a constant; If we change the voltage we change the wattage and hence the torque and probably speed. "The Arduino a power supply it is not!" On a good day it has a 200ma max capability. This is dependent on the power the regulator can dissipate, dictated by load and the voltage going into the Vin pin.

 If we look at the 66mA it draws times 10 motors that is 660 mA is way beyond the Arduino rating of 200ma. Total chip Vcc current (all output pins total and chip overhead): 10 output pin driving 10 motors @ 66 ma is way beyond max for whole chip.


message:
Can an Arduino access a network database?

This is a similar question to a previous question I have asked. Primarily I am looking to find out more about the capability of the Arduino.
Here is the scenario. There is a PC that is connected to a database via local network or internet. Is it possible that by plugging an Arduino in the usb port of this PC the Arduino could read from this database by means of an SQL query? Given that the Arduino would have the correct credentials. I am not asking if the Arduino could Hack into the database. I am asking if it is capable of accessing the database at all. Also this must be done without installing any special program on the PC. If that isn't possible, what type of program is needed? I am not necessarily looking for a tutorial, but if you could point me in the right direction that's be great.
Thank you.

body:
The M0 has a "native" USB interface. Because of that it can be programmed to appear as any kind of device you can image - as long as you can find (or write) the code to do that.

You *could* (though I have never tried and don't know what code is readily available for this) program the USB interface to be a USB Ethernet device. Your computer would then see it as a new Ethernet interface.

It would then be trivial to "share" your internet connection in Windows with that new Ethernet interface (nothing to install, but settings on the computer need changing), and your Arduino would then be on the network the same as your computer (just as if you'd given it a WiFi interface or something like that). Then it can connect to the database itself (or to a website that communicates with the database if that is simpler) and do whatever it needs to do.

Step one, of course, will be to find a library that will give you that USB Ethernet interface...

A much simpler option, if you're willing to change your M0 for something else, is to use a chip with a built in WiFi interface, such as the ESP32. There's no need for your computer at all then.


message:
How can i make my MLX90614ESF scan temperature after the MFRC522 scans the RFID tag?

//THIS IS THE RFID CODE

    #include <SPI.h>
    #include <MFRC522.h>

    #define RST_PIN         9           // Configurable, see typical pin layout above
    #define SS_PIN          10          // Configurable, see typical pin layout above

    MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

    //*****************************************************************************************//
    void setup() {
      Serial.begin(9600);                                           // Initialize serial communications with the PC
      SPI.begin();                                                  // Init SPI bus
      mfrc522.PCD_Init();                                              // Init MFRC522 card
        //shows in serial that it is ready to read
    }
    //*****************************************************************************************//
    void loop() {
      // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
      MFRC522::MIFARE_Key key;
      for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;
      //some variables we need
      byte block;
      byte len;
      MFRC522::StatusCode status;
      //-------------------------------------------

      // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
      if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
      }

      // Select one of the cards
      if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
      }

      byte buffer1[18];

      block = 4;
      len = 18;

      //------------------------------------------- GET FIRST NAME
      status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 4, &key, &(mfrc522.uid)); //line 834 of MFRC522.cpp file
      if (status != MFRC522::STATUS_OK) {
        return;
      }

      status = mfrc522.MIFARE_Read(block, buffer1, &len);
      if (status != MFRC522::STATUS_OK) {
        return;
      }

      //PRINT FIRST NAME
      for (uint8_t i = 0; i < 16; i++)
      {
        if (buffer1[i] != 32)
        {
          Serial.write(buffer1[i]);
        }
      }
      Serial.print(" ");

      //---------------------------------------- GET LAST NAME

      byte buffer2[18];
      block = 1;

      status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 1, &key, &(mfrc522.uid)); //line 834
      if (status != MFRC522::STATUS_OK) {
        return;
      }

      status = mfrc522.MIFARE_Read(block, buffer2, &len);
      if (status != MFRC522::STATUS_OK) {
        return;
      }

      //PRINT LAST NAME
      for (uint8_t i = 0; i < 16; i++) {
        Serial.write(buffer2[i] );
      }

      //----------------------------------------

      delay(1000); //change value if you want to read cards faster

      mfrc522.PICC_HaltA();
      mfrc522.PCD_StopCrypto1();
    }
    //*****************************************************************************************//

    // AND THIS IS THE MLX90614 CODE
    #include <Wire.h>
    #include <Adafruit_MLX90614.h>

    Adafruit_MLX90614 mlx = Adafruit_MLX90614();

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

      mlx.begin();
    }

    void loop() {

      Serial.print("*\Body Temperature = "); Serial.print(mlx.readObjectTempC()); Serial.println("*C");

      Serial.println();
      delay(500);
    }

body:
It appears that you have simply concatenated the code from the RFID tag Sketch and the code from Temperature Sketch together.  This will not work as both programs contain identically named functions. Specifically "setup()" and "loop()".  What you need to do is integrate the code for each "setup()" function into one "setup()" function.  Similarly, you need to do the same with the "loop()" functions.

Assuming you only want to scan the temperature after you have successfully recovered data from the RFID tag, place the Temperature Sketch loop code immediately before the delay in the RFID tag code.


message:
having problems with my arduino bluetooth car project(with L298n Motor Driver)

so the scenario is i am making a bluetooth controlled car(voice control)+obstacle avoidance function.I am using Arduino UNO with L298n motor driver and a HC-05 BT module in the sensors i am using the ultrasonic sensor and a IR sensor for the back and a servo motor is also used to rotate the ultrasonic sensor.so the problem is when i am sending command "turn left" the servo moves left and nothings happens and the other command i.e turn right,move backward,move forward are not working at all.

circuit diagram and code is given if i have done  something wrong with the code or else my motor driver or wiring is creating the issue

```lang-cpp

#include <NewPing.h>
#include<Servo.h>
#define TRIGGER_PIN A1
#define ECHO_PIN A0
#define MAX_DISTANCE 300
#define IR A2

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

Servo myservo;

String voice;

void setup() {
  Serial.begin(9600);
  myservo.attach(8);
  myservo.write(90);
  pinMode(IR, INPUT);
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode( 9, OUTPUT);

}

void loop() {
  int distance = sonar.ping_cm();

  if (Serial.available() > 0) {
    voice = "";
    delay(2);
    voice = Serial.readString();
    delay(2);
    Serial.println(voice);

    if (voice == "turn left") {
      left();
    } else if (voice == "left") {
      left();
    } else if (voice == "turn right") {

    } else if (voice == "right") {

    }

  }
  while (voice == "move forward") {
    forward();
  }
  while (voice == "move backward") {
    backward();
  }
}

void forward() {
  int distance = sonar.ping_cm();

  if (distance < 10) {
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite( 9, LOW);
    voice = "";
  } else {
    digitalWrite(12, HIGH);
    digitalWrite(10, HIGH);
  }
}
void backward() {
  int IR_Sensor = digitalRead(IR);
  if (IR_Sensor == 0) {
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite( 9, LOW);
    voice = "";
  } else {
    digitalWrite(11, HIGH);
    digitalWrite( 9, HIGH);
  }
}
void left() {
  myservo.write(180);
  delay(500);
  myservo.write(90);
  delay(500);
  int distance = sonar.ping_cm();

  if (distance < 10) {
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite( 9, LOW);
    voice = "";
  } else {
    digitalWrite(12, HIGH);
    delay(700);
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite( 9, LOW);

  }
}

void right() {
  myservo.write(0);
  delay(500);
  myservo.write(90);
  delay(500); {
    int distance = sonar.ping_cm();

    if (distance < 10) {
      digitalWrite(12, LOW);
      digitalWrite(11, LOW);
      digitalWrite(10, LOW);
      digitalWrite( 9, LOW);
      voice = "";
    } else {
      digitalWrite(10, HIGH);
    }
    delay(700);
    digitalWrite(12, LOW);
    digitalWrite(11, LOW);
    digitalWrite(10, LOW);
    digitalWrite( 9, LOW);
  }
}

void Stop() {
  digitalWrite(12, LOW);
  digitalWrite(11, LOW);
  digitalWrite(10, LOW);
  digitalWrite( 9, LOW);
}

```

body:
The code seems to have a few missing lines for logic. Here's a corrected version from my understanding.

    #include <NewPing.h>

    #include<Servo.h>

    #define TRIGGER_PIN A1
    #define ECHO_PIN A0
    #define MAX_DISTANCE 300
    #define IR A2

    NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

    Servo myservo;

    String voice;

    void setup() {
      Serial.begin(9600);
      myservo.attach(8);
      myservo.write(90);
      pinMode(IR, INPUT);
      pinMode(12, OUTPUT);
      pinMode(11, OUTPUT);
      pinMode(10, OUTPUT);
      pinMode(9, OUTPUT);

    }

    void loop() {
      int distance = sonar.ping_cm();

      if (Serial.available() > 0) {
        voice = "";
        delay(2);
        voice = Serial.readString();
        delay(2);
        Serial.println(voice);

        if (voice == "turn left") {
          left();
        } else if (voice == "left") {
          left();
        } else if (voice == "turn right") {
          right();
        } else if (voice == "right") {
          right();
        } else if(voice == "move forward"){
          forward();
        } else if(voice == "move backward"){
          backward();
        }

      }

    }

    void forward() {
      int distance = sonar.ping_cm();

      if (distance < 10) {
        digitalWrite(12, LOW);
        digitalWrite(11, LOW);
        digitalWrite(10, LOW);
        digitalWrite(9, LOW);
        voice = "";
      } else {
        digitalWrite(12, HIGH);
        digitalWrite(10, HIGH);
      }
    }
    void backward() {
      int IR_Sensor = digitalRead(IR);
      if (IR_Sensor == 0) {
        digitalWrite(12, LOW);
        digitalWrite(11, LOW);
        digitalWrite(10, LOW);
        digitalWrite(9, LOW);
        voice = "";
      } else {
        digitalWrite(11, HIGH);
        digitalWrite(9, HIGH);
      }
    }
    void left() {
      myservo.write(180);
      delay(500);
      myservo.write(90);
      delay(500);
      int distance = sonar.ping_cm();

      if (distance < 10) {
        digitalWrite(12, LOW);
        digitalWrite(11, LOW);
        digitalWrite(10, LOW);
        digitalWrite(9, LOW);
        voice = "";
      } else {
        digitalWrite(12, HIGH);
        delay(700);
        digitalWrite(12, LOW);
        digitalWrite(11, LOW);
        digitalWrite(10, LOW);
        digitalWrite(9, LOW);

      }
    }

    void right() {
      myservo.write(0);
      delay(500);
      myservo.write(90);
      delay(500); {
        int distance = sonar.ping_cm();

        if (distance < 10) {
          digitalWrite(12, LOW);
          digitalWrite(11, LOW);
          digitalWrite(10, LOW);
          digitalWrite(9, LOW);
          voice = "";
        } else {
          digitalWrite(10, HIGH);
        }
        delay(700);
        digitalWrite(12, LOW);
        digitalWrite(11, LOW);
        digitalWrite(10, LOW);
        digitalWrite(9, LOW);
      }
    }

    void Stop() {
      digitalWrite(12, LOW);
      digitalWrite(11, LOW);
      digitalWrite(10, LOW);
      digitalWrite(9, LOW);
    }


message:
L293D motor shield

I have the L293D motor shield on top of my Arduino UNO.

The L293D has a servo attached of 5 volt and a motor of 12 volt there is an external power supply.

If I remove the jumper of the board and power my motor with the 12 volt? Will my servo of 5 volt still have the 5 volt of the Arduino or is this connected to the external 12 volt?

body: No , your motor will actually get power from outside but the Servo Motor will be powered by arduino even if the jumper removed because the ln298 shield is mounted on the arduino.


message:
Arduino Pro Mini is burned by 12v. Can I save it?

I have this Arduino Pro Mini clone (ATmega328) 5v.

I gave it exactly 12 volts through the RAW power input, but it instantly got hot and started fuming. Fumes were coming out of the area close to the black S4 thingy.
I don't know why, because I thought it can accept up to 12v through that input.

Now when I give it 5v only the middle led is lighting up and it's not connecting to the USB-UART interface anymore.

Is there any chance to save it?

[![arduino pro mini][1]][1]

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

body:
Unfortunately, it sounds like it is dead.

I did this early on when I started with arduinos.
In my case I plugged in a "12v 1amp" wall adapter from a linksys router that I didn't check with a DMM to a uno-R3 barrel jack.

The adapter was putting out 22v @ god only knows how many amps. But it had the exact same symptoms I am sorry to say.

I wound up going with a cheap 5v/3.3v selectable breadboard power supply. You might want to look into those for future use, I got mine for less than $3 on eBay.

https://www.ebay.com/itm/1pcs-Breadboard-Power-Supply-Module-Shield-3-3V-5V-MB102-Solderless-Bread-Board/133519600754?hash=item1f16636c72:g:9NcAAOSwZzNfYHel


body: Wall adapters are not all the same. They can have AC and DC outputs. The DC outputs can be regulated or unregulated. Assuming 1 12V DC wall adapter unregulated you can get maybe 19Vdc from it depending on the design.Always check first, it is much more cost effective then going to the store to buy a new Arduino and what other devices.


body:
## 1. Your microcontroller is probably/maybe fine; your tiny little voltage regulator is dead; here's why:

Sergio, yes, you can probably/perhaps save it: your Arduino (the microcontroller--ie: processor at least) is likely just fine, assuming the linear regulator smoked and failed _open_, meaning it did NOT pass through the raw input voltage to your ATmega328 mcu. It's the linear voltage regulator that is fried! That's this circled component below:

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

So, desolder that part and throw it away and you can continue using the Arduino just fine. Just power it with a **regulated** 5V directly to VCC is all and you'll be fine. I've done exactly this on some parts I exploded or smoked the regulator on (see below), and they continued working just fine.

_IMPORTANT: if this is a safety-critical part, or a product, throw away the whole Arduino just in case._

### Details on the fixes:
1. Desolder the voltage regular (circled in the image above, and shown desoldered on my Pro Mini in the photo below) and throw the desoldered voltage regulator away.
1. Power the board now through Vcc with anything between 3.3V and 5V (recommended: a regulated 5V into Vcc, such as the 5V line coming straight out of your USB hub).
1. Reflash the bootloader with a USBasp programmer (shown in 2nd of the two photos below).
1. Upload a new blink sketch via the external USB serial UART to blink the built-in LED13. This works fine on my Pro Mini below shown with exploded and desoldered regulator:

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

    // the loop function runs over and over again forever
    void loop() {
      digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(500);                       // wait for a half-second
      digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
      delay(500);                       // wait for a half-second
    }
    ```
1. Unplug the USBasp programmer when done, and continue development with just the external serial UART plugged in.

Here's some photos of my Arduino Pro Mini with exploded voltage regulator that I desoldered. I found it today. The Arduino still works fine! I desoldered the regulator around the year 2014 or so, but just re-flashed the bootloader, uploaded the code, tested it, and took these photos today:

**Image 1:** Arduino Pro Mini used as a data-logging altimeter in \~2014; photo from today. The voltage regulator exploded (read below), so I desoldered it. Both the power LED (top center of board), and LED13 (bottom-left of board) are ON. _The power LED comes on automatically so long as you are powering the board through Vcc and GND from your USB port through your USB UART adapter, and the LED13 is blinking ON here due to the blink sketch above AND by powering the board with Vcc and GND from the USB serial UART to the Pro Mini. Note that the LED13 would NOT light up properly with just the USBasp plugged in, even when it was properly powered and programmed by the USBasp. I think it's because the USBasp was interfering with that pin. Plugging in the external serial UART to the Pro Mini's Vcc and GND fixed that, allowing LED13 to function properly as well while the Pro Mini ran the blink sketch above._

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

**Image 2:** External USB serial UART (in the USB hub top port), USBasp programmer wired to program the bootloader (in the USB hub under the USB UART), Pro Mini (bottom left) with power LED ON and LED13 (bottom-left of board) OFF.

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

----

On the surface, you didn't do anything wrong! You plugged 12V into the correct pin (`RAW`, which is the battery-in or voltage in line), and that is within the voltage limits of this part. BUT, what you neglected to consider is the _power dissipation capability_ of this footprint or size of a part. The power dissipation capability is soooo low that realistically, 12V is too much, and will destroy the part.

6 years ago or so I made a couple little data-logging altimeters with the Arduino Pro Mini, connected 12.6V (a fully-charged 3S LiPo battery) to the RAW pin, and 15 seconds later: pop! They **exploded**! Literally, that little voltage regulator _exploded_ into bits with 12.6V in. After that, I never put more than 8.4V in (a fully-charged 2S Lipo battery), and all was well. Since I was powering it from my main RC plane's 3S LiPo motor battery, this was accomplished by just tapping off of 2 of the 3 cells in the battery by plugging into the correct points on the battery's balance lead. So, I was able to use the same battery but just use 2 of its 3 cells instead of all 3 of them.

These regulators are just so tiny that they can't take much heat is all, and since they are _linear_ regulators, all excess voltage is burned off as heat. Here's a couple example power dissipation calculations to make the point:

Imagine you are drawing 100mA total (0.1A) from this regulator. With 12V plugged in, you have to burn off `12V - 5V = 7V` in that regulator chip.

    Power_dissipated = Current*Voltage = I*V = 0.1A * 7V = 700mW

700mW is HUGE! Pop! Explosion! Dead voltage regulator chip.

But, if you feed it just 8V this same chip would have to burn off only `8V - 5V = 3V` of excess voltage:

    Power_dissipated = Current*Voltage = I*V = 0.1A * 3V = 300mW

That's `300mW/700mW = 43%` as much power, or `57%` less power. These numbers are just for example purposes, but you get the point.

Solution? 1) switch to Arduino Nanos, and/or 2) use a much lower input voltage (ex: 8\~9V instead of 12V!). Nanos have MUCH bigger and beefier voltage regulators, and Nanos cost like $1 more when buying the Chinese clones.

## 2. How to calculate 1) how much power your regulator can dissipate without burning up, and 2) how much current you can therefore draw for different raw input voltages to the voltage regulator:

(Also: I wrote an article on my website covering more of these power, current, and voltage specs--see link [here][4] and at bottom.)

By the way, looking at the [Pro Mini schematic here][5], I see that the original board used a MIC5205 linear regulator. The Chinese clone you have certainly uses a different regulator, but let's look up the MIC5205 datasheet for benchmarking purposes. A [google search for "mic5205 datasheet"][6] leads me here: https://ww1.microchip.com/downloads/en/DeviceDoc/20005785A.pdf. The device is rated up to **150mA current** and **up to +16V input voltage**, but you _must_ consider power!

The equation for that is hidden on pg 5 here:

[![enter image description here][7]][7]

    Power_dissiplation_max =  P_D_max = (T_J_max – T_A)/theta_JA

    theta_JA = thermal resistance from Junction to Ambient = 220 degC/W

    T_A = ambient temperature = let's say, 40 deg C (104 deg F)

    T_J_max = max junction (internal chip) temperature = +125 degC

So, we crunch the numbers:

    P_D_max = (125C - 40C)/220 C/W = 85C / 220 C/W = 0.386W = 386mW max
    power.

Final result: this tiny, linear voltage regulator, assuming absolute max junction temperature of +125 C (257 F) [HOT HOT HOT!--not good] and ambient air temperature of 40C (104 F) can dissipate **386mW max power before you risk making it go "pop"!**

So, assuming you power it with 12V, how much current can you draw?

    Voltage drop across the regulator = V_D = Vin - Vout = 12V - 5V = 7V

    Power dissipation in the regulator = P_D = current * voltage drop = I*V_D

Solve for `I`:

    I = P_D/V_D = 0.386W/7V = 0.055A = 55mA current!

**With _12Vin_ and _5Vout_, any more than _55mA_ current draw goes "pop" or smokes the chip!**

With 8Vin, however, you could draw:

    V_D = 8V - 5V = 3V
    I = P_D/V_D = 0.386W/3V = 0.129A = 129mA current

**With _8Vin_ and _5Vout_, any more than _129mA_ current draw goes "pop" or smokes the chip!**

So, use a lower input voltage and you can draw much more current! How low can you go? Don't go lower than 5V + dropout voltage. The datasheet on p3 for this regulator shows a max dropout voltage of ~350mV, so stay > 5.35V input to get a regulated 5V output.

[![enter image description here][8]][8]

That's all for this MIC5205 chip, though. Note that other voltage regulators may have dropout voltages as high as 2\~3V, so you'd have to have an input voltage of at least 7V or so to ensure a regulated 5V output. I can't see the numbers well enough on your chip to google for its actual Chinese or whatever datasheet to do the calculations for your chip, but you can use my example calculations above to redo these calculations for any datasheet or part.

## Other reading:
1. [Google search for "sot 23-5 power dissipation"](https://www.google.com/search?q=sot+23-5+power+dissipation&oq=sot+23-5+power+dissipation&aqs=chrome..69i57.14810j0j7&client=ms-android-google&sourceid=chrome-mobile&ie=UTF-8#sbfbu=1&pi=sot 23-5 power dissipation)
    1. [Microchip Application Note AN792: A Method to Determine How Much Power a SOT23 Can
Dissipate in an Application](http://ww1.microchip.com/downloads/en/appnotes/00792a.pdf)
1. I also wrote an article on my personal website on 6 Jan. 2014 called ["Arduino Power, Current, and Voltage Limitations", here][4], for more info. on these limitations.

  [1]: https://i.stack.imgur.com/l2si2.jpg
  [2]: https://i.stack.imgur.com/fniQB.jpg
  [3]: https://i.stack.imgur.com/rA4UL.jpg
  [4]: https://www.electricrcaircraftguy.com/2014/02/arduino-power-current-and-voltage.html
  [5]: https://www.arduino.cc/en/uploads/Main/Arduino-Pro-Mini-schematic.pdf
  [6]: https://www.google.com/search?q=mic5205 datasheet&oq=mic5205 datasheet&aqs=chrome..69i57.4580j0j4&sourceid=chrome&ie=UTF-8
  [7]: https://i.stack.imgur.com/sXEa7.png
  [8]: https://i.stack.imgur.com/h0n1C.png


message:
Connect SDRAM to STM32

Well, first of all hello to everything and thanks for reading my question. I am designing a board with STM32F730R8T6 MCU, and I want to connect MT48LC16M16A2P-6A to it which is 4MB SDRAM chip. The connections are pretty basic from what I saw, the thing is, how can I access that memory from my MCU? I mean there is a library or something to use it? and, if someone can send me an example schematic, to connect the memory I would appreciate it. Greetings.

body:
As far as I know, you have to choose variant with FMC module (Flexible Memory Controller) with SDRAM support - that means you have to use 144pin version STM32F730**Z**8. The 100pin version does have FMC but doesn't support SDRAM.

After resolving this issue, it should be about configuring FMC module for using SDRAM (in STM32CubeMX for example) and the RAM will be available at some memory location according to the MCUs memory layout.


message:
Understanding NRF24L01 specifications

I was reading [this tutorial][1] about the NRF24L01 and came across a few terms which I did not clearly understand.

> It uses the 2.4 GHz band

1. Does this refer to the frequency of the EM waves that the device uses to communicate?

> If used in open space and with lower baud rate its range can reach up to 100 meters.

2. I know baud rate refers to how many "groups of bits" are transmitted per second. I don't quite understand why the range increases for a lower baud rate.

> The module can use 125 different channels which gives a possibility to have a network of 125 independently working modems in one place. Each channel can have up to 6 addresses, or each unit can communicate with up to 6 other units at the same time.

3. Here, does a channel mean a single frequency? How is the range of possible channels decided (why 125) and how is the smallest detectable resolution decided (smallest change in frequency which would cause a change in channel)? So does a single unit work on only one frequency or could the same unit communicate at different frequencies at the same time and so be a part of different networks simultaneously? In effect, I am not able to make sense of this paragraph!

  [1]: https://howtomechatronics.com/tutorials/arduino/arduino-wireless-communication-nrf24l01-tutorial/

body:
> > It uses the 2.4 GHz band
>
> Does this refer to the frequency of the EM waves that the device uses to communicate?

Yes. It generates (and receives) radio waves in the region of 2.5GHz.

>> If used in open space and with lower baud rate its range can reach up to 100 meters.
>
> I know baud rate refers to how many "groups of bits" are transmitted per second. I don't quite understand why the range increases for a lower baud rate.

Think of it like talking to someone. If you're stood right next to them you can speak nice and fast and they can understand you. Your speech comes across nice and clear.

However if you're the other side of a quarry you have to shout really loud, and if you talk too fast they can't understand you. You. Have. To. Shout. Slowly. so that they can understand you.

The environment makes a lot of difference to how your speech propagates. In large areas there's lots of echo and other things.  It's similar with RF communications. There's more noise and things that can interrupt communication. By having lower baud rates you're giving the receiver more time to understand what it's receiving and make sense of the data.

>> The module can use 125 different channels which gives a possibility to have a network of 125 independently working modems in one place. Each channel can have up to 6 addresses, or each unit can communicate with up to 6 other units at the same time.
>
> Here, does a channel mean a single frequency? How is the range of possible channels decided (why 125) and how is the smallest detectable resolution decided (smallest change in frequency which would cause a change in channel)? So does a single unit work on only one frequency or could the same unit communicate at different frequencies at the same time and so be a part of different networks simultaneously? In effect, I am not able to make sense of this paragraph!

There's a number of different factors at play here. First there is the "Bandwidth" of the channel. This is the maximum amount of data that can be squeezed into a particular carrier frequency with a particular amount of "space" around the signal. You can think of the channel width as the diameter of a pipe. The wider the pipe the more water can be pushed through the pipe per second.

You want to slice the RF allocation up into enough channels to give enough concurrent access to lots of devices, but at the same time you want to have enough bandwidth per channel that you can transfer reasonable amounts of data.

It's all a balancing act.

Nordic decided 125 channels was the optimal balance for their application.

One nRF24L01+ can work at one frequency at a time. That's not to say you can't instruct it to change frequencies at any time, but it can only be listening on the one frequency at once. Just like a normal FM radio - you can only listen to one radio station at a time.

But the nRF24L01+ protocol uses addresses within that one chosen channel, so lots of devices can all be on the same channel to talk together, and each is distinct by its address.

The protocol also includes the concept of "pipes" which are virtual wireless circuits between two physical devices. Once you have configured a pipe with an address any other device can communicate with that pipe. You can configure up to 6 pipes, so up to 6 devices can send to the same target at the same time and each devices data is kept separate and distinct from the others. It's kind of like having 6 serial ports all connected to different devices at once.


body:
 1. Yes. They call it a band, because the nRF24L01 can operate on frequencies from 2.400GHz to 2.525GHz

 2. It's like talking slower to someone. It makes it easier to distinguish the signal from the noise.

 3. Kind of. Every channel is 1Mhz apart from the next (`2.4Ghz + (125 * 1Mhz) = 2.525GHz` which is the range specified above). <strike>This difference is chosen more of less arbitrarily</strike>. The 125 channels is because it has to stay inside the ISM band 2.4-2.5Ghz. Note that the different channels can still interfere with each other, unless they are far enough apart from each other. Just like with WiFi where you had 11 channels, but were advised to only use channels 1, 6, or 11. The NFR can only run at one frequency/channel at a time. You can however change channels while it's running. But its better to have all running on the same channel and use the NRFs pipes to create separate "networks". Or even use the same pipe, but have the packet contain the info on what kind of data it contains.


message:
How to slowly change direction of the stepper motor with AccelStepper?

I know that direction can be changed with

    .setSpeed(speed);
    ... //check input
    .setSpeed(-speed);

I need to slowly decelerate and accelerate backwards, so I have to use

    .setAcceleration(200);
    ...
    .setMaxSpeed(speed);
    ... //check input
    .setMaxSpeed(-speed);

but documentation told that .setMaxSpeed argument Must be > 0.

So how to properly change direction with deceleration? Probably I have to use .moveTo with some very big values

body:
I have tested it on real motor, and it works as I want with function .moveTo . Speed slowly changed from +maxSpeed to -maxSpeed acording to Acceleration

    #define maxSpeed 1000
    #define Acceleration 500
    ............
    void setup(){
      stepper.setMaxSpeed(maxSpeed);
      stepper.setAcceleration(Acceleration);
    }
    void loop() {
     ............
     if(bDirection!=bDirection_last)
     {
      stepper.moveTo(bDirection?6000000:-6000000);
      ...........
     }
     stepper.run();
    }


message:
Why does the following code not cause the led's to flash but rather stay on continuously

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

    int timer = 1000;
    int thispin = 5;

    void setup() {
      for (int thispin = 5; thispin < 8; thispin++)
        pinMode(thispin, OUTPUT);
    }

    void loop() {
      for (int thispin = 5; thispin < 8; thispin++)
        digitalWrite(thispin, HIGH);

      delay(timer);
      digitalWrite(thispin, LOW);

      for (int thispin = 7; thispin = 5; thispin--)
        digitalWrite(thispin, HIGH);

      delay(timer);
      digitalWrite(thispin, LOW);
    }

I have the above code. I thought that how it was written would cause the led's to flash but they all stay on continuously. Could anybody help to explain what it is i have done wrong?
I am very new to this and I'm just fiddling basically trying to learn.
Thank you!

body:
Exchange the last lines:

    delay(timer);
    digitalWrite(thispin, LOW);

It is 2 seconds on and maybe a few hundred nanoseconds on.


body:
In the last for() loop, the limit expression, `thispin =5;` was probably meant to say `thispin <=5;`. As it is written, the expression is an assignment, not a test, and it will always be `true`, because 1) an assignment statement is also an expression having a value equal to the value assigned; and 2) the assigned value, '5', being non-zero, is equivalent to 'true'), so this loop will never end. thispin will get decremented forever and repeatedly set pin 5 to HIGH. It leaves the other pins alone, but they were already high, and the LEDs stay lit, which is what you observed.

(There are a couple of other errors, as noted earlier by previous responders, which will also prevent your code from operating as you expected.)


body:
From the given code it is not entirely clear what you are trying to achieve.
If I understood correctly, you want the pins to light up for one second and then go out. First from 5 to 7, and then from 7 to 5.
Try the given code.

    int timer = 1000;

    void setup()
    {
      for (int thispin = 5; thispin < 8; thispin++)
        pinMode(thispin, OUTPUT);
    }

    void loop()
    {
      for (int thispin = 5; thispin < 8; thispin++)
      {
        digitalWrite(thispin, HIGH);
        delay(timer);
        digitalWrite(thispin, LOW);
      }

      delay(timer);

      for (int thispin = 7; thispin >= 5; thispin--)
      {
        digitalWrite(thispin, HIGH);
        delay(timer);
        digitalWrite(thispin, LOW);
      }
    }

Also, using the same name for globals variable and  loop iterators is bad style.


body:
The objective of the code is not clear. It seems the idea is to repeatedly blink 3 LEDs, connected on pins 5,6 and 7. To do so, the code needs slight modification-

    int timer = 1000;
    int thispin = 5;

    void setup() {

      for (int thispin = 5; thispin < 8; thispin++)
        pinMode(thispin, OUTPUT);
    }

    void loop() {

      for (int thispin = 5; thispin < 8; thispin++)
        digitalWrite(thispin, HIGH);

        delay(timer);

      for (int thispin = 5; thispin < 8; thispin++)
        digitalWrite(thispin, LOW);

        delay(timer);

    }

Also, since you wanted to know why the LEDs stay ON continuously with your code-
This is because there is no delay statement after any of the digitalWrite-LOW statements. If there's no delay, the LEDs may turn off for a fraction of a millisecond, which won't be noticeable.


message:
Arduino Due SerialUSB Resetting

Having this basic example for using the `SerialUSB` function on the Arduino Due under Windows:

 // ARDUINO DUE BLINK LED
 void setup(){
   pinMode(13,OUTPUT);
   SerialUSB.begin(2000000);
   while(!SerialUSB){
  digitalWrite(13,HIGH);
  delay(100);
  digitalWrite(13,LOW);
  delay(100);
   }
 }

 void loop(){
   SerialUSB.println("Hello, World!");
   digitalWrite(13,HIGH);
   delay(100);
   digitalWrite(13,LOW);
   delay(900);
 }

I am having trouble understanding which shall be the operating sequence for this use. Normally I follow these steps:

 1. Open Arduino IDE, select Arduino Due (Programming Port) at COM 01, and connect it to PC USB,
 2. Compile and Upload the code,
 3. Open a Serial Monitor App, with COM 02, 2000000 bps or 9600 bps, 8b data, 1b stop, no parity, RTS|CTS flow control.

If I keep the Arduino connected to the Programming Port after trying the Native USB Port, I have to disconnect and connect everything to program it again (??), or disable it through the windows Device Manager.

Which is the proper sequence (and perhaps the code) for doing this the right way?.

body:
Assume the Arduino is already programmed and energized, i.e. from the Barrel 5V Power Source or from a USB Charger (as minimum) at Programming USB Port.

The following should be the proper steps:

 1. If not Programmed: Program the Arduino, either through the Programming USB Port, Native USB Port, etc.
 2. If Native USB Cable to PC is Plugged: Unplug Cable, or Reset Arduino,
 3. Plug Native USB Cable to PC,
 4. Check COM Number for the Native USB Port, i.e. COM01,
 5. If Serial Monitor Connected: Disconnect Serial Monitor,
 6. Connect through a Serial Monitor App, with COM01, any bps, 8b data, No parity, 1b stop, RTS|CTS flow control.

Done. The data flow should start immediately as soon as you Reset.

Check this for a [deeper][1] post with another example for debugging.

  [1]: https://arduino.stackexchange.com/questions/84635/dealing-with-usb-unplugging


message:
None of the pins work as inputs

I’m using an Arduino-uno

I'm trying to read an PWM signal being output by pin 6.
I'm attempting to read it with pin A0.

5 volts are being supplied from pin 6 to a 300 ohm resister in series with one led.
This circuit returns to the analog input pin A0.

It'll admit it's a strange set up and I was told to use a pass through filter to read the signal.

At this point I'm not concerned with whether the program reads the right values,
so despite the code involving the serial monitor I'm just trying to figure out why the led won't turn on anymore.

As I stated in the sketch, this exact set up was working fine yesterday. The led was on and (accurate or not) there were consistent values being printed to the serial monitor.

I'm trying to figure out now what changed after I unplugged it last to create a now open circuit.

***************

    ```

    void setup() {

      Serial.begin(9600);
      pinMode(6, OUTPUT);
      // I  also tried setting the A0 pin as an input even though I thought you didn't have to and it didn't change anything.

    }

    void loop() {

      analogWrite(6, 255); // This pin is working as an output, I tested it to ground and led lights.

      int value = analogRead(A0); // I realize inputs are typically used for things like potentiometers
                                  // But just as an example the LED should still turn on when connected here, correct?
                                  //And it did the first few times I did it... maybe that was the problem?

      Serial.println(value);  // This was  all working previously. It just randomly stopped.
                              // Now this just prints random numbers and the circuit remains incomplete.
                              // Even if the input pins are not supposed to be used with 5 volts, Why was it working before then...
                              // ALSO it does not matter which pins you use for what...
                              // No current is running through the digital inputs with digital output set to HIGH.
                              // And No current runs through the analogInput pins when analogWrite is set to 255.
                              // Once again, I apologize if my terminology is off.

    }
    ```

***************
This is what I did to trouble shoot:

With the same sketch running on the board...

I connected a jumper from pin A0 to ground and the serial monitor switched from a bunch of random values to a solid 0. So it recognizes input still... in a sense.

**Then** I modified the sketch...

   ```
void setup() {

  Serial.begin(9600);
  pinMode(6, OUTPUT);
  pinMode(8, INPUT);

}

void loop() {

// now I'm attempting to read a digital signal with the same circuit...
// Pin 6 is connected to a 300 ohm resistor in series with an led which returns to pin 8.

  digitalWrite(6, HIGH);

  int value = digitalRead(8);

  Serial.println(value);

}
   ```

This gave the same result. The led wont turn on anymore unless the circuit ends are connected from a voltage source to ground.

Previously, any pins configured as INPUT would not only read consistent values but also complete the circuit, turning the led on.

Now the pins only recognize zero volts and do not complete any circuits. You can't even use a simple potentiometer if you wanted.

Each pin that can be configured as an INPUT acts the same way.

The only thing I did between the times when it was working and wasn't was unplug and plug in the board...

body:
Sounds like there's a basic misunderstanding here.

Setting a pin as "output" mean it'll either supply +5V ("HIGH") or 0V ("LOW"). Both those states are considered "outputs", and the pin can source or sink current in those states. When driven "LOW", the circuit does "input" current to the chip, but that's not what "input" usually means.

"Input" means you can use the pin to read the voltage applied to the pin. When connected to a PWM source, this might manifest as the pin quickly switching between "1" / "HIGH" / "+5V" and "0" / "LOW" / "0V".
Normally, you would use the "input" mode to read things like switches, or potentiometers on the analog input pins.

Your desired use of "current input" pins will require you to configure the pin as "output", and then set it to "LOW", which will make it able to sink current.


body:
The LED would glow only when the pin is configured as an OUTPUT or it would be very dim in INPUT mode. This is because INPUT mode sets the pin to a high impedance state, suitable for reading voltages and not for driving circuits requiring current.

Setting a digital pin to INPUT mode, allows you to only read voltages as 0 or 1  which correspond to 0V and 5V respectively. For example, upload the code below to your Arduino and open the serial monitor. Now, by connecting Pin 11 to GND the serial monitor should display 0, and by connecting it to 5V, it should display 1. If this doesn't work something may be wrong with the Arduino.

    const int TESTPIN=11; //connect pin 11 to 5V and GND for testing

    void setup() {

      pinMode(TESTPIN, INPUT);
      Serial.begin(9600);
    }

    void loop() {
      Serial.println(digitalRead(TESTPIN));
      delay(500);
    }

However, I would recommend that you share your code and diagram before concluding a fault in the Arduino.


body:
In your second update you described the following circuit:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/o2WLQ.png)

<!-- End schematic -->

Then in code you are doing `digitalWrite(6, HIGH);`, which sets pin 6 to HIGH/1/true/5V. Pin 6 is configured as output, pin 8 as input. In this situation the LED will not light up. A pin, that is configured as input, will not draw or source current (except a very very small amount). The input pin behaves somewhat like a little capacitor to ground (so in principle nearly no current can flow). Thus no current is flowing through the circuit. No current also means, that the LED does not light up (it needs current for lighting up) and no voltage drop will happen on the circuit. The circuit will not be "completed", as you phrased it. Thus your input pin will also get HIGH/1/true/5V, which is what you then read on in the code.

When you instead change pin 8 to output (`pinMode(8, OUTPUT);`) and set it to LOW (`digitalWrite(8, LOW);`), the LED will light up, as now the voltage difference is the full 5V (from HIGH at pin 6 to LOW/ground at pin 8). If you now read the pin with `digitalRead(8)` you will just read, what you have written to it, meaning LOW/0/false/ground.

You might also have tried to use `digitalWrite()` with a pin, which is configured as `INPUT`. That does not really output anything. Instead it activates or deactivates the internal pullup resistor of the pin. As I remember, this pullup resistor is between 20 and 50 kΩ, so again you cannot get enough current to light an LED through that pin. The internal pullup resistor is then like an additional 20 to 50 kΩ resistor from the corresponding input pin to Vcc (5V in your case). If nothing else pulls on the pins value, the pullup resistor will pull the value of the input pin to HIGH/1/true/5V, so that you don't have a floating pin (see below for an explanation of that term).

---

**The next scenario: Using `analogRead()`**

Here you first tried to read an analog pin (A0), which was not connected to anything. That is called a **floating pin**. There is nothing, that gives this pin a definite value, thus it catches whatever electrical noise comes around, from the microcontroller, from other pins, from the circuit or from outside. A floating pin can change it's value rapidly and randomly, depending on the noise, which comes around. Thus you will get very different and varying values here.

Then you connected A0 to ground. That gives the pin a definite value (LOW/0/false/ground). Thus you now only read zero as value.

If you are doing the `analogRead()` with a circuit similar to the first case (with the LED between two pins) you will get a similar result as with `digitalRead()`. An analog input will also not source or draw any current (besides a very very small current). Thus you cannot "complete" a circuit to light an LED on the path.

---

> I'm trying to read an PWM signal being output by pin 6. I'm attempting to read it with pin A0.

A PWM signal is nothing else than changing rapidly between Vcc (5V in your case) and ground. The value, that you give the PWM signal via `analogWrite()`, defines the duty cycle of the signal, meaning the ratio between the HIGH and LOW portions in the signal. The function name `analogWrite()` is unfortunately very misleading, as you don't really output an analog voltage. Most Arduinos don't have the hardware to do that, so `analogWrite()` uses PWM to output a pseudo analog voltage. Devices like motors are not fast enough to react to the fast voltage change, so you can change the speed with PWM. LEDs are fast enough, but the human eye cannot see the individual on-off cycles, so you see the LED being dimmed with lower values.

But the `analogRead()` function (which uses the ADC hardware internally) is fast enough, thus you would only read a series of changes between 5V and ground, when reading a PWM signal. You could build a low pass filter, which will filter out the PWM frequency and give you a real analog voltage, which you can then read via `analogRead()`. Though keep in mind, that this makes it slower, so you cannot read fast changes with that. A low pass filter looks like this:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/RQRmM.png)

<!-- End schematic -->

The values come from the come from the comment of Edgar Bonet (thanks):

> The PWM frequencies of the Uno are 977 and 490 Hz, below the cut-off of the filter you drew. Per the ADC's specification, you can safely increase R1 up to 10 kΩ, which should put the cutoff low enough to attenuate the PWM frequencies by at least 30 dB.

Though you might also want to read up the formula for the cut-off frequency. You can google terms like "RC low pass filter".

If you don't want to use extra hardware, but still want to read the PWM signal, you need to read the pulse length. For this there are multiple ways, depending on the requirements. You can use `pulseIn()`, you can use interrupts and take timestamps, you can use the capture mode of a hardware Timer.

---

> As I stated in the sketch, this exact set up was working fine yesterday. The led was on and (accurate or not) there were consistent values being printed to the serial monitor.

Unfortunately this is not possible. The pins must behave like I described above. As electronics not break and then just magically unbreak, you must have done something different. An input pin (digital or analog) will not source or draw enough current to light an LED.

---

> Now the pins only recognize zero volts and do not complete any circuits. You can't even use a simple potentiometer if you wanted.

You may have damaged something, though I cannot really say, if that is really the case or if you are just doing something wrong there. A potentiometer has to be connected like the following: The outer pins to ground and 5V respectively, the middle pin directly to the analog input. Nothing else. You might check, if that is, what you did.

---

Besides all that, you didn't really state, what you are trying to achieve. As you already acknowledged in your question, the described circuit is not typical and a strange setup. To light an LED, you would just connect it to the output pin (via the resistor) and on the other side to ground.


message:
Multiple Push buttons to one input

So I am trying to use one input to control an LCD display. The goal being that once one of the buttons is pressed it delivers a message. I have watched quite a few [tutorials][1] and can get the program to work sometimes. Yet, it is still pretty buggy and I am wondering why that is. To get this make this project work somewhat used this code.

```java
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int buttonPin = A0;     //Button and LED pin numbers
    void setup()
{
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  //lcd.print("hello, world!");
  Serial.begin(9600);           //Serial monitor used to determine limit values

 }

void loop()
{
  int temp = analogRead(buttonPin);   //Read the analogue input
  Serial.println(temp);               //Display the read value in the Serial monitor
  if (temp = 340)                     //Lower limit for first button - if below this limit then no button is pushed and LEDs are turned off
  {
  lcd.print("No Button Pushed \n");
  }
  else if (temp = 867)                //First button limit - if below this limit but above previous limit then the first button is pressed
  {
 lcd.print("Button 1 Pushed");
  }
  else if (temp = 156 )                //Second button limit
  {
 lcd.print("Button 2 Pushed");
  }

  else                                //If none of the previous buttons are pressed, then the third button must be pressed
  {
  lcd.print("Button 3 Pushed");
  }
  delay(100);                         //Delay for stability
}
```

The output sometimes is correct other times it is off. I think it has something to do with the circuit. Yet, I am scratching my head to find out what.

[![Circuit][2]][2]

  [1]: https://www.the-diy-life.com/multiple-push-buttons-on-one-arduino-input/
  [2]: https://i.stack.imgur.com/0Hj2t.png

body:
You made a few mistakes with the three lines, first one being:

    if (temp = 340)

First, the single '=' is an assignment operator instead of a comparing operator.  You want to use '=='.

However, you need to check if it is within a range, so you need to use <= (to see if it is smaller or equal). Also you need to put them in the correct order, so you get something like:

    if (temp <= 156)
    {
       // Process value if temp is smaller or equal than 156
    }
    else if (temp <= 340)
    {
       // Process value if temp is smaller or equal than 340 (and higher than 156)
    }
    else if (temp <= 860)
    {
       // Process value if temp is smaller or equal than 860(and higher than 340)
    }
    else
    {
       // Process value if temp is higher than 860
    }


body:
Michel Keijzers pointed out the issues you have in your code. But then
there is also an issue with your circuit: if you press any of the push
buttons, the analog input pin gets connected to one of the nodes of the
resistor ladder, and you get a well defined voltage reading. Good.
However, if none of the buttons is pressed, the input is not connected
to anything: it is floating. In this case the reading you get is
unpredictable, as it depends on parasitic influences of stray
capacitances, environmental noise, etc. You should modify your circuit
to make sure that the input voltage is well defined even when no button
is pressed.

Then, regarding the program, I recommend you remove everything after
`Serial.println(temp);`. Just make it work like this, and take note of
the readings you get in each case. Make sure they are consistent. Once
you know the values you expect, you can decide on the threshold to
apply, which should be about halfway between the typical readings. E.g.
if the two lowest values you get are 0 and 240, you would set a
threshold at 120.


message:
Arduino Coding Issue

I'm running a water pump based on ultra sonic readings. Once the Ultra Sonic Sensor reads > 10 cm , I want the water pump to start until sensor reads < 5 cm. Would you please help me adjust the following code to meet my requirements.

    void loop(){
     digitalWrite(trigPin,LOW);
     delayMicroseconds(2);
     digitalWrite(trigPin,HIGH);
     delayMicroseconds(10);
     digitalWrite(trigPin,LOW);
     duration=pulseIn(echoPin,HIGH);
     distance=(duration*0.034/2);
     if(distance>5){
       digitalWrite(motor,HIGH);
       delay(30000);
       digitalWrite(motor,LOW);
     } else {
       digitalWrite(motor,LOW);
     }
    }

body:
So what you're asking is:

* If distance is greater than 10:
  * Turn on
* If distance is less than 5:
  * Turn off

That's not hard to code, since you already have an "if" there that compares the distance.

```
 if(distance>5){
   digitalWrite(motor,HIGH);
   delay(30000);
   digitalWrite(motor,LOW);
 } else {
   digitalWrite(motor,LOW);
 }
```

becomes:

```
if (distance > 10) {
    digitalWrite(motor, HIGH);
}

if (distance < 5) {
    digitalWrite(motor, LOW);
}
```

See how there's a direct 1:1 correlation between the English I wrote at the top and the code below it? That's often a good way to understand code: write it out in plain English step by step what you want and what decisions you need to make - then there's usually a simple conversion from English to code.

The hardest part of learning to program is understanding the logic. Do that in English first and the writing of the code itself becomes so much easier.


message:
ESP8266 with RTC DS1307 shield - WS2818B shield won't blink - I2C issue?

Dear Ladies and Gentlemen,

I'd like to let a LED blink base on the time of the day. So I took Wemos D1 mini and a [WS2818B shield][1] and a [RTC DS107 Shield][2] for the before mentioned ESP8266 model.

Based on my observation, I can let the LED blink on its own without starting the initialization of the RTC. As soon as I initialize the communication with the DS1307 shield, the LED shield won't translate any commands toward the desired behavior (e.g. the LED won't blink anymore).

What am I doing wrong?

I'm using the Ardunio IDE to program the D1 mini.

I stacked the shields and kept an eye on the pins to be sure I did wire everything the right way.

Libraries in use:
RTC: [https://github.com/Makuna/Rtc][3]
LED: [Adafruit NeoPixel][4]

Code:
```
// WIFI
#include <ESP8266WiFi.h>

// RTC
#include <RtcDateTime.h>
#include <RtcUtility.h>
#include <Wire.h> // must be included here so that Arduino library object file references work
#include <RtcDS1307.h>
RtcDS1307<TwoWire> Rtc(Wire);

// LED
#include <Adafruit_NeoPixel.h>
#define PIN        D2
#define NUMPIXELS 1
Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ400);

int DELAYVAL = 1000; // Time (in milliseconds) to pause between pixels

void setup() {

  Serial.begin(57600);
  Serial.println();
  Serial.flush();

  setupLed();

  setupWifiConnection();

  setupRtc();

}

void loop() {

  pixels.clear(); // Set all pixel colors to 'off'
  pixels.show();   // Send the updated pixel colors to the hardware.
  delay(DELAYVAL); // Pause before next pass through loop

  pixels.setPixelColor(0, pixels.Color(0, 150, 0));
  pixels.show();   // Send the updated pixel colors to the hardware.
  delay(DELAYVAL); // Pause before next pass

}

void setupRtc () {

  Rtc.Begin();

  RtcDateTime compiled = RtcDateTime(__DATE__, __TIME__);
  Serial.println();

  if (!Rtc.IsDateTimeValid())
  {
      if (Rtc.LastError() != 0)
      {
          // we have a communications error
          // see https://www.arduino.cc/en/Reference/WireEndTransmission for
          // what the number means
          Serial.print("RTC communications error = ");
          Serial.println(Rtc.LastError());
      }
      else
      {
          // Common Causes:
          //    1) first time you ran and the device wasn't running yet
          //    2) the battery on the device is low or even missing

          Serial.println("RTC lost confidence in the DateTime!");
          // following line sets the RTC to the date & time this sketch was compiled
          // it will also reset the valid flag internally unless the Rtc device is
          // having an issue

          Rtc.SetDateTime(compiled);
      }
  }

  if (!Rtc.GetIsRunning())
  {
      Serial.println("RTC was not actively running, starting now");
      Rtc.SetIsRunning(true);
  }

  RtcDateTime now = Rtc.GetDateTime();
  if (now < compiled)
  {
      Serial.println("RTC is older than compile time!  (Updating DateTime)");
      Rtc.SetDateTime(compiled);
  }
  else if (now > compiled)
  {
      Serial.println("RTC is newer than compile time. (this is expected)");
  }
  else if (now == compiled)
  {
      Serial.println("RTC is the same as compile time! (not expected but all is fine)");
  }

  // never assume the Rtc was last configured by you, so
  // just clear them to your needed state
  Rtc.SetSquareWavePin(DS1307SquareWaveOut_Low);
}

void setupLed () {

  pixels.begin();

  pixels.clear();
  pixels.show();
}

void setupWifiConnection () {

  WiFi.begin("some ap", "some password");

  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());
}

```

  [1]: https://www.berrybase.de/en/raspberry-pi-co/esp8266-esp32/ws2812b-rgb-led-shield-for-d1-mini?c=306
  [2]: https://www.berrybase.de/en/raspberry-pi-co/esp8266-esp32/ds1307-realtime-clock-shield-for-d1-mini?c=306
  [3]: https://github.com/Makuna/Rtc
  [4]: https://github.com/adafruit/Adafruit_NeoPixel

body:
According to your code, you’ve connected the Neopixel to D2. The RTC is an I2C device, so it’s also connected to D2. How is that supposed to work? The Neopixel isn’t an I2C device.

Move the Neopixel to a different pin that’s not used by anything else - so not D1. Try D3. Update your code to use D3. There may be other issues but at least you won’t be trying to use the same pin to talk to two very different devices.


message:
Beginners code, loop doesn't detect unplugged pin

I'm learning on an Arduno UNO board, and im trying to turn a LED on three times when I connect pin 10 to ground and then turn it off. Then when I unplug the pin number 10 it should NOT blink again... yet it does and I can't find the issue.

this is the entire code:

    bool ledBlinked = false;

    void setup() {
      // put your setup code here, to run once:
      pinMode(7, OUTPUT);
      pinMode(10, INPUT_PULLUP);
    }

    //Turns on and off a digital pin, a number of times, with a certain delay
    void blinkLed(int pin, int times, int del){
      // activates a pin a number of times
      for (int i=0; i<=times; i++){
        digitalWrite(pin, HIGH);
        delay(del);
        digitalWrite(pin, LOW);
        delay(del);
      }
    }

    //Checks if passed pin number is connected to ground
    bool pinIsGround(int pin){
      return (digitalRead(10) == LOW);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      if(pinIsGround(10) && !ledBlinked){ //if pin is connected to ground and the LED hasn't blinked
        blinkLed(7,3, 100); //blink pin 7, 3 times, with a delay of 100ms
        ledBlinked = true; //LED has blinked already
      }
      if (!pinIsGround(10) && ledBlinked){ //if pin is not connected to ground and the LED hasn blinked
        digitalWrite(7, LOW); //turn LED off (unnecesary?)
        ledBlinked = false; //LED hasn't blinked yet
      }

    }

body:
SInce I can coment I have to write this as answer.
there are two ways of understanding your question:

If you dont want it to ever blink again then simply remove
```ledBlinked = false;```

If you are trying to prevent the blinking until the button is depressed and pressed again then first think I see is the error in **blinkLed** function as

```for (int i=0; i<=times; i++)``` would run times+one time. because it runs first with value of ***i*** being 0
 (Eg times=4 would run for i equal 0,1,2,3,4 -> Five times )
 So correction to ```for (int i=0; i<times; i++)``` would run correct number of times (Eg times=4 would run for i equal 0,1,2,3 -> four times )

Although as you are not checking status during the running of blinkLed function for the status of the button, if you release it while blink is running the script would not notice unless its still unpressed when script gets back to Loop.

Although since hardware operation take more work then logical operation I would recommend **if...else** statement rather then multiple hardware operations. Although they make code simpler to read

```
if(digitalRead(10) == LOW){
         if(ledBlinked != true)...
   } else { ...}
```


message:
Arduino Vin pin does not work, but Arduino 5v pin power works

I have a very weird problem, at least it seems to me that way. I have connected L298N motor driver, Arduino and a hobby servo with a 6v power supply (tested with both 4xAA and 9v alkaline batteries). And wrote a simple program to rotate the servo every 10ms. There are no other motors connected as of yet.

 1. Power supply is connected to the L298N 12v and GND.
 2. Arduino is connected to the 5v and GND of L298N driver with the Vin and GND of Arduino respectively.
 3. Servo's power (red wire) is connected to L298N 5v, GND is connected to the L298N's GND, and, servo's control (orange wire) is connected to pin 9 of Arduino.

The problem is that the servo hardly moves when Arduino gets power supply gets from the Vin input. However, if I connect it to the 5v of the Arduino power it works as expected. But I was under the impression that 5v pin of Arduino was to for the output and not for the input power supply. Could you guys please tell me what am I doing wrong here?

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

  [1]: https://i.stack.imgur.com/8WM8d.jpg

body:
The Vin pin on the Arduino Uno board is connected to the **input** of the 5V onboard voltage regulator of the Arduino board.

This voltage regulator needs an input voltage that’s about 1.5V above its (regulated) 5V output that will feed the Arduino.

[Arduino - note the recommended values of the Input Voltage (7-12V)][1]

If you feed 5V into Vin, the voltage drop on the internal regulator will cause the Arduino board to be supplied with only about 3.5V, which is probably enough to make it function, but not enough to control the servos.

The solution, as you already found out, is to feed the 5V from the L298N board directly into the 5V pin of the Arduino. Please take care to measure the actual voltage from the L298N before you do this (it should be 5 Volts). Alternatively you could connect 12V to the Vin pin of the Arduino, but again, make sure you know what you’re doing.

  [1]: https://store.arduino.cc/arduino-uno-rev3


body:
You are using Arduino to drive one servo motor and that's simple with only using arduino board with this setting:

1. 5V supply pin
2. GND pin
3. any pwm pin

Now using the LM298N here isn't optimal. If you googled LM298N, you would get the main application of this driver which is to drive DC and stepper motors.

For driving multiple servo motors, you can use this module board to drive upto 16 servo motors.

[![PCA9685 16-Channel PWM Driver][1]][1]

Here is a link for it on Banggood.

[PCA9685 16-Channel 12-bit PWM Servo Motor Driver I2C][2]

  [1]: https://i.stack.imgur.com/Sl7JU.jpg
  [2]: https://www.banggood.com/PCA9685-16-Channel-12-bit-PWM-Servo-Motor-Driver-I2C-Module-p-1170343.html?gmcCountry=SA&currency=SAR&createTmp=1&utm_source=googleshopping&utm_medium=cpc_bgs&utm_content=frank&utm_campaign=frank-ssc-sa-en-all-0618feed&ad_id=443067658277&gclid=CjwKCAjwlID8BRAFEiwAnUoK1fNkJOGsM0RMeYpbO4V8bwwa1Xa2MqLl2A4M1SxMue8Dv5zB-M9P2hoCJIEQAvD_BwE&cur_warehouse=CN


message:
board stops working when writing serial

i just started using Arduino IDE for my XMC1100XMC2Go. Information about the microcontroller can be found here: https://github.com/Infineon/XMC-for-Arduino/wiki/XMC-2Go

I now started with my first codes and want to print things on the serial monitor with this code:

```
*/
/* For on board LEDs */
#include <LED.h>

/* Create an LED object */
LED Led;

//#define SERIAL_DEBUG 1

int p_LED = 5;
int p_Button = 4;
int i_stateButton = 0;

void setup()
{
  Led.Add(LED1);            // Configure the LEDs
  Led.Add(LED2);
  pinMode(p_LED, OUTPUT);
  pinMode(p_Button, INPUT);

  // Set default state of LEDs
  Led.On(LED2);
  Led.Off(LED1);

  digitalWrite(p_LED, LOW);
  Serial.print("Hello World!");

  Serial.begin(9600);
}

void loop()
{
  Serial.write("Hello World!");
  Serial.println(i_stateButton);
  delay(200);
  Led.Toggle (LED2);
  Led.Toggle(LED1);

  i_stateButton = digitalRead(p_Button);
  //digitalToggle(p_LED);
  digitalWrite(p_LED, i_stateButton);
}
```

I checked under tools that SerialOutput is set to PC (https://github.com/Infineon/XMC-for-Arduino/blob/master/variants/XMC1100/config/XMC1100_XMC2GO/pins_arduino.h#L54)

There are two Ports, COM1 and COM3. I can send new sketches to the microcontroller using COM3. I checked my Serial Monitor and it is set to COM3, too.

Baudrate is for both the same (code and monitor)

Now that i send the above sketch to the microcontroller it stops working. one LED is on and the other is off. But they do no longer change the state. Nothing appears on the monitor.
When i remove the both lines `Serial.write("Hello World!");  Serial.println(i_stateButton);` and send the sketch, the LEDs start flashing again.

I'm pretty sure it's a kind of configuration problem, but i cannot find out what it is. Does anyone have an idea?

body:
In the `setup()`, you have:

```c++
Serial.print("Hello World!");
Serial.begin(9600);
```

One should avoid printing to the serial port before enabling it with
`Serial.begin()`.