title: Initializing variables of a function

text:
# Question
Title: Initializing variables of a function
By playing with some examples I found the following construct:

`void Show(int nav = 0) // -1 top, 1 bottom`

and I wondered what effect it has to initialize the handover parameters in the function declarations, I never noticed such an construct consciously.

So I made a small demo:

```
#include <M5Stack.h> //necessary for my board
  int a;
  int b;
  int c;

int addFunction(int x = 3, int y = 3){
  int result;
  result = x + y;
  return result;
}

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

  // testcase 1
  a = 1;
  b = 2;
  c = addFunction(a, b);
  Serial.println("testcase 1:");
  Serial.println((String)a + " + " + b + " = " + c);

   // testcase 2
  a = 1;
  b = 2;
  c = addFunction();
  Serial.println("testcase 2:");
  Serial.println((String)a + " + " + b + " = " + c);

   // testcase 3
  a = 1;
  b = 2;
  c = addFunction(a);
  Serial.println("testcase 3:");
  Serial.println((String)a + " + " + b + " = " + c);
}

void loop() {
}

```

The output was:

So I learnd:

* if you hand over parameters, the initialization is ignored, if you call the function without handing over paramters, the functions works with the init values.
* if you handover only one parameter it will be assigned to the first in the declaration.

**Question:**

Is there a syntax possible to only call the function with the second parameter, so that for the first paramter the intialized value of the declaration is used? Spoken for this example with a = 1, b = 2 you only handover b and the expected result would be 5.

# Answer
> 4 votes
This is (unfortunately) not an Arduino question. It is actually about the syntax of C++ which is a rather complex language.

The mechanism you have discovered is called **default arguments**. The function prototype or definition may contain the default values of the arguments. As this is a list the default values are restricted from right to left. It is not possible to use a default parameter for argument to the left of a given argument. The order is strictly right to left.

```
f(int x = 0, int y = 1, int z = 2)

f(1,2,3) binds x = 1, y = 2, z = 3
f(1,2) equals f(1,2,2) binds x = 1, y = 2, z = 2
f(1) equals f(1,1,2) binds x = 1, y = 1, z = 2
f() equals f(0,1,2) binds x = 0, y = 1, z = 2

```

There is a syntax for struct initialization (aka aggregate initialization) in C++ that allows naming of struct field values. This type of naming is not allowed for function calls.

Please read https://en.cppreference.com/w/cpp/language/default\_arguments, https://en.cppreference.com/w/cpp/language/aggregate\_initialization and https://en.cppreference.com/w/cpp/utility/functional/bind for more details. And a good C++ book.

There are languages that allow default arguments and named parameters e.g. C#, Python, Ruby and Smalltalk. Please see https://en.wikipedia.org/wiki/Named\_parameter.

Cheers!

(Update)

Below is a rewrite of @VE7JRO Add function class using cast operator to perform the evaluation:

```
class Add
{
public:
  Add(int x, int y) : m_x(x), m_y(y) {}
  operator int() { return m_x + m_y; }
  void x(int x) { m_x = x; }
  void y(int y) { m_y = y; }
  int print(Print& outp) {
    int res;
    res = outp.print(F("Add(x="));
    res += outp.print(m_x);
    res += outp.print(F(",y="));
    res += outp.print(m_y);
    res += outp.print(F(")"));
    return res;
  }
private:
  int m_x, m_y;
};

Add func(1,2);

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

  func.print(Serial);
  Serial.print(F("="));
  Serial.println(func);

  func.x(12);
  func.print(Serial);
  Serial.print(F("="));
  Serial.println(func);

  func.y(13);
  func.print(Serial);
  Serial.print(F("="));
  Serial.println(func);
}

void loop() {
}

```

# Answer
> 1 votes
If your function is inside a class, you can set either variable, both variables or use the defaults.

```
class Add{

    int a, b;

  public:

    Add(): a(1), b(2){}

    int AddTwoIntegers(){
      return a + b;
    }

    void SetInt1(int int1){
      a = int1;
    }

    void SetInt2(int int2){
      b = int2;
    }

};

Add Test1;

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

  Serial.print("Test default values = ");
  Serial.println(Test1.AddTwoIntegers());

  Test1.SetInt2(4);
  Serial.print("Set b = 4 then add to a = ");
  Serial.println(Test1.AddTwoIntegers());
}

void loop(){}

```

---
Tags: functions
---


# Question
Title: Can I use arduino's 3.3 V output directly to esp8266?
I just bought esp8266 and ftdi usb driver, I want to power the esp8266 with Arduino's 3.3 V output, is that possible?

I saw some tutorial on youtube in that they are suggesting us to use 3.3v regulator ic instead of directly power 3.3 V of Arduino or ftdi driver's 3.3 V output.

If I connect my ftdi or Arduino output directly into esp8266 is there a chance to damage the esp8266?

# Answer
> 9 votes
You should search for this data yourself, but since you are saying you are a newbie I'll tell you how to find this.

First of all you should search for a document called "datasheet". On a datasheet the producer writes all the relevant data about his product.

In your case, you should search for the electrical characteristics of the ESP8266. For instance here you have one of the datasheets. On page 13, there is the "Power consumption" chart, which says that the worst case has a typical current of 170mA. I suggest you to raise it a bit; let's say you need 250mA for the ESP.

Now, the arduino. You should search for the schematic of the board or read the part number of the 3.3V regulator. Since it's easier from the schematic and they released it on the web, you can see that the part number of the 3.3V regulator is LP2985. Searching for it on google will lead you to the texas instruments webpage, with the datasheet. Here you can see that the maximum output current is 150mA, so below the required current. Answer: you can't with arduino.

As for the FT232 cable, you should search for it because there are different models. Search on google and pick the first link pointing to the ftdi website.

As an example, the TTL-232RG has this datasheet. On page 9 they say that the TTL-232RG-VSW3V3-WE has an output current of 50mA, so you can't use it. The TTL-232RG-VREG3V3-WE, on the other side, has a maximum output current of 250mA, so you can use it.

If you have further questions, just ask here ;)

# Answer
> 1 votes
The specs for the Uno say that it does not provide as much current on the 3.3V line as the specs for the ESP8266 requires. You will need to provide another regulator that can supply enough current.

# Answer
> -1 votes
i know It's a delayed reply .but it might help some one else.The answer is yes. I powered up esp8266 with ardino 3.3V directly and it works fine for me.

---
Tags: arduino-uno, arduino-ide, wifi, esp8266, voltage-protection
---


title: Multiple definitions of "xxxx"

text:
# Question
Title: Multiple definitions of "xxxx"
I really need your help. I use VisualStudio and PlatformIo I still get this error:

> Linking .pioenvs\esp12e\firmware.elf .pioenvs\esp12e\src\main.cpp.o:(.data.DebugX+0x0): multiple definition of \`DebugX' .pioenvs\esp12e\src\customFunctions.cpp.o:(.data.DebugX+0x0): first defined here collect2.exe: error: ld returned 1 exit status \*** \[.pioenvs\esp12e\firmware.elf\] Error 1

I use header guards in my file, so I do not understand why is this part of code redeclared. I had to miss some elementary in cpp programming but I still can't get it to work.

Copy of my project: https://bitbucket.org/fires/programingtesting/src/master/ESP8266/cpp/RedefinedError/

main.cpp

```
    #include <Arduino.h>;
    #include "../include/defines.h"
    //#include "../include/customFunctions.h"
    // Time
    uint32_t mTimeToSec = 0;
    uint32_t mTimeSeconds = 0;
    void setup() {
    etc. etc. etc.

```

customFunction.h

```
    #pragma once
    #ifndef CUSTOMFUNCTIONS_H
    #define CUSTOMFUNCTIONS_H
    void connectWiFi();
    void initializeOTA();
    #endif

```

defines.h

```
    #pragma once
    #ifndef DEFINES_H
    #define DEFINES_H
    #include <jled.h>
    #define BowlingLed 5
    #define StatekLed 4
    int DebugX = 1;
    #endif

```

Thanks for the help, I read many articles and many issues but I still do not understand why DebugX is redefined if it is in header guard.

# Answer
> 4 votes
Included files are included before compilation, really replacing the #include with the content of the file.

If you write `int DebugX = 1;` you define a variable. And it is defined in every source file which includes it. Then the linker finds it in more then one unit and ends with "multiple definitions" error.

The variable must be defined only in one compilation unit (.c, .cpp). For example in your case customFunctions.cpp. To make it available in other source files put `extern int DebugX;` into the .h file.

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


title: Building an AtMega328p from Transistors

text:
# Question
Title: Building an AtMega328p from Transistors
I'm a little new to circuitry, and the Arduino in itself!

From what I know, I think that it might be possible to actually build one (the processor itself, of course) from transistors. This isn't a practical question, of course, but it would be an excellent learning opportunity.

Would it be actually possible to go through with such a project (Even without EEPROM)?

If so, how would it be completed?

Thank you!

# Answer
Yes, it is possible - after all, the Arduino is essentially just a bunch of incredibly tiny transistors. Early computers, before ICs were invented, were built from transistors. Before that it was valves. Before that it was relays. All just, at the end of the day, switches.

Would it be a practical project? Not really, although someone has done it (not for the AVR CPU, but the concept is the same): http://www.megaprocessor.com/

How would you start? Well, first off you'd create the basic building blocks of a CPU, which is logic gates. There are two basic ones that can be combined together to make any other gate: the NAND gate and the NOR gate. You'd pick one of those and put lots of them together to make the basic sections of the CPU. Then those blocks connect together to form the CPU. More logic gates go together to make the IO functionality, memory, interfaces, etc.

Basically:

* Transistors combine to make NAND gates (or NOR gates if you prefer that form)
* NAND (or NOR) gates combine to make complex gates.
* Complex gates combine to make logic functions
* Logic functions combine to make logic blocks (like the ALU)
* Logic blocks combine to make the CPU
> 5 votes

# Answer
I do not think you could build an ATmega328P out of discrete parts: you would need floating-gate transistors for implementing the flash, and these do not seem to be available as discretes.

If you forgo the flash (or replace it with RAM or ROM), then it should in principle be possible. This processor, however, is probably not a good choice for such a project. From the discussion linked to by Mikael Patel, it seems you would need something like 80 K transistors for the core alone, and much more if you include the RAM and the peripherals. It would be a daunting task to assemble all this by hand. For comparison, the Megaprocessor1 as about 42 K transistors total (core + RAM + LED drivers).

If you want to pursue such a project, I recommend you target a simpler CPU. The MOS 6502 may be a good choice. This CPU, which was very popular in the late 70s and early 80s, has “only” 3,510 transistors and is well documented. See for example the resources at visual6502.org. They have an amazing online transistor-level simulator built from the actual layout of the chip.

1Thanks Majenko for the link
> 3 votes

# Answer
The ATmega128 have 800000 transistors. (+-200000 transistors)
So If you want to take some transistors and breadboards and build an ATmega128p first count the money for transistors (if 1 transistor costs 0.01€ then 800000 x 0.01 = 8000€ and the breadboards is much more expensive than transistors!)
> 2 votes

# Answer
Try to build out the entire thing inside a simulator instead of buying 10s of thousands of transistors and several other components....less messy and gets the job done at almost no expense
> 2 votes

# Answer
Why not? Atmel did it. But if you mean by soldering up discretes...

In the mid 70s the Zilog Z80 had 8,500 transistors; a couple of years later, the Intel 8088 had 29000(source: Wikipedia). Neither of those had on-chip memory. The AtMega 328p has 2K of RAM and 1K of EEPROM on chip, so factor in for those and their drivers. At 20 MHz it will probably be fun 1) keeping signals where they belong; and 2) keeping the wire runs short enough and suitably arranged that capacitance doesn't slow and distort the signals to unusability.
> 1 votes

# Answer
While it is possible, you will have to spend a lot of money and a lot of time. I think about thousends of dollars and months of work. Even when accomplished you will have learned more about electronics than about the ATmega328P. In order to accomplish, you will also have to ask Atmel to hand you over the schematics to get the inner working right. I highly doubt they will aggree since it is not Open Hardware.

I highly discourage you to do that. Instead I suggest you start with an Arduino UNO and discover the capabilities and then go a step further and use a bare ATmege328P.
> 1 votes

# Answer
> Would it be actually possible to go through with such a project (Even without EEPROM)?

yes.

> If so, how would it be completed?

the easiest would be to find or write a soft-core for AVR on a fpga. Get the logic blocks for that softcore , and then implement those logic blocks with transistors.

Before you set out actually doing it, however, check if you have enough of space or bank account (for the electric bills).
> 1 votes

---
Tags: assembly
---


# Question
Title: Why is Arduino resetting while driving motors?
I am driving motors for my line-follower project . The circuit schematic is given below

The power source is a 11.1V 2200mAh 25C Lipo . Practically the cells give 11.5-12V. I used a switching buck regulator to step down the voltage. However , when i run my robot on track after few seconds,the arduino tends to reset and run again. This problem typically arises when i drive the motors at higher PWM(above 180 on analogWrite function). Since i use PID, limiting the PWM means i have to drive at lower speeds which i do not want.

I am providing links for the items i used for my circuit:

1. buck converter;
2. motor driver;
3. IR sensor module;
4. DC motors.

The sensor array draws 150mA at peak. Any suggestions as to where the problem might lie would be of great help. Thank you .

EDIT 1: Changed the input voltage Vin to 7.9V through the buck converter . The problem still persists .

# Answer
> 5 votes
The VIN pin goes to a 5V voltage regulator on the Arduino and needs at least about 7V minimum to work properly. If you want to supply 5V to an Arduino do it either on the 5V pin or via the USB connector. The VIN pin should receive 7V to 12V.

# Answer
> 2 votes
Resetting is due either to a software bug or voltage sag, and since it correlates with driving the motors harder, it's almost certainly the latter. You probably suspected as much since you mentioned the current draw of the sensor array. A quick experiment - disconnecting the sensors (and possibly a software patch to keep the robot running straight, without them) might help you discover the reason.

Each chip and each of its pin drivers has a current budget. It would be a good idea to look at the max current spec of the Atmega2560 and its pin drivers, and any other current specs mentioned in the datasheet, and make sure you're not trying to run it out of spec. The buck converter will have a limit, too, so make sure you're within its spec. If the output regulation of the buck converter is good enough, you can regulate it to 5v and bypass the Mega's on board regulator, for another saving.

# Answer
> 1 votes
One major drawback to working with motors is the large amounts of electrical noise they produce. This noise can interfere with your sensors and can even impair your microcontroller by causing voltage dips on your regulated power line. Large enough voltage dips can corrupt the data in microcontroller registers or cause the microcontroller to reset. You can avoid this problem by soldering capacitors along your motor terminals. Use 1µF ceramic capacitors for example

# Answer
> 1 votes
This is the common issue when trying to connect power and digital circuits together. Probably, when motor starts, there is a short-time voltage drop in **Vin** due to high motor start current. Consider to use Schottky diode and capacitor to protect digital power circuit from transitional currents.

# Answer
> 0 votes
You should either feed the 5.5v from the buck converter to the 5v pin of the arduino, or the 11.5v to the Vin. The arduino board contains its own 5v converter (and a 3.3v but that's not in question here). That takes the voltage of the Vin pin and converts it to 5v for the board to use. This regulated 5 v is available on the 5v pin for your sensors for example.

You can also power it directly on the 5v pin, but that requires regulated 5v. This is also how it is powered through USB which supplied regulated 5 v.

The 5.5 v from your buck should be fine for this, by you don't need it. Put the "raw" 11.5 to the Vin pin.

---
Tags: arduino-mega, power, motor, ir
---


# Question
Title: How to safely remove arduino nano from breadboard?
I did some prototyping with arduino nano in breadboard. And then after i done with the design, I was gonna implement it in a printed pcb so i need to remove the nano from breadboard. And this is when the disaster happened.

The board is kinda hard to pull by hand, so i use a long-thin screwdriver in the gutter to pull the nano up (just like i did many times to dip ICs with no problem). And successfully detached the nano from breadboard and also broke the tantalum under the nano in the process. So the question is:

1. How do you usually remove the nano board from breadboard safely? And
2. The tantalum i broke is 4.7uF smd. I can't find any 4.7uF tantalum in nearby shops, but i have electrolyte caps rated 4.7uF 16v. Can i use it for replacement?

# Answer
> 3 votes
> How do you usually remove the nano board from breadboard safely? And

If you can't remove it by hand (grip it lengthwise and ease up each end with your finger / thumb levering against the breadboard) then you need a lever. The best is a plastic spudger, such as this:

The plastic will flex rather than damage the Arduino. Using a screwdriver can, as you have noticed, damage the Arduino.

> The tantalum i broke is 4.7uF smd. I can't find any 4.7uF tantalum in nearby shops, but i have electrolyte caps rated 4.7uF 16v. Can i use it for replacement?

Sure. All that is, is a reservoir capacitor on the USB input. The value isn't super-critical, as long as the voltage is above 5V. It's not, strictly speaking, even needed. You can just remove it completely and clean up the pads to ensure there's no shorts. The board should still work fine.

# Answer
> 1 votes
I also had the same problem but what I had done was, I pressed the breadboard with my leg and used my all fingers to grip the nano and pulled it with my full force and then it is done. And no parts were damaged and id you lost any part you can search on https://octopart.com/ .

---
Tags: arduino-nano, breadboard, capacitors
---


title: Arduino delay inside of an Interrupt

text:
# Question
Title: Arduino delay inside of an Interrupt
Using the delay function inside of an ISR is frowned upon when programming in an Arduino. The general response to solve this desire is to design the program to delay in a more cleanly way outside of the interrupt.

My question is simply why. Why does putting a delay() inside of an ISR cause wonky behavior with the Arduino. Whats going on under the hood?

# Answer
> Why is putting a delay() inside of an ISR cause wonky behavior with the Arduino. Whats going on under the hood?

The first problem is that delay() is a busy loop monitoring millis(). The value that millis() returns will not change inside an ISR as interrupts are turned off inside an ISR; this is why ISRs must be as short and fast as possible, or they will interfere with other interupts

So if you call delay() within an ISR your poor AVR is now deadlocked! It is waiting for something to happen that can now never happen.

A second problem is that if your ISR takes too long, you can miss other interrupts; millis() and micros() can miss ticks and become inaccurate!
> 4 votes

# Answer
Because a delay inside an interrupt causes that interrupt and other (lower priority) interrupts not to execute anymore until the delay is over.

Assume in an ISR you handle the incoming bytes from a UART. If you add a delay in the ISR, and the buffer of the UART gets full, it will overflow and you miss bytes.
> 1 votes

# Answer
This is an addition to esoterik's answer.

Most of the times, that people try to use `delay()` inside an ISR it is a poor design choice to even use it in a general way, that will lead to the described problems (waiting forever or missing other interrupts). `delay()` is a simple function mainly for beginners with very simple programs. It is a simple starting point. Mostly the use of it in any program is not a good choice, since you are busy waiting without being able to do something else (like responding to user input). There are better ways, involving `millis()` itself, that keep your program extendable (so that, if you want to add a functionality, this will not be blocked by the first part of the code). And when your program reaches the complexity of using own ISRs, you should avoid `delay()`, unless you really know, what you are doing.

IMO at some (rather early) point, every Arduino programmer has to learn how to use `millis()` to do timed code execution. You can look at the `BlinkWithoutDelay` example, that comes with the Arduino IDE.
> 1 votes

---
Tags: isr
---


# Question
Title: Adafruit RGB LCD w/ Shield kit connection to arduino uno?
I have a adafruit rbg 16x2 lcd with shield kit and am trying to connect it to an arduino uno. The only thing is the assembly instructions have the lcd basically using every pin on the arduino, even tho it says its not for connections. Since we are using many of the pins already on the board, can I wire it to the board without soldering it to every pin, essentially only wiring to the few necessary pins?

Sorry, I am very new at this. Thank you for the help.

EDIT: Was essentially looking for the follwing diagram. Thanks to all!

# Answer
> 1 votes
The idea of shields is that they (in theory) can be stackable. (In practice they are usually not) This means that technically you can do this:

That's why by design every shield connects to every Arduino pin but uses only some of them. That way shield is mechanically well attached to the Arduino, and can pass "unused" pins to the shield above it.

Your shield is designed to be always "on top" so I think it only connects to some pins just for mechanical support. Technically the LDC screen needs only 6 pins and 1 pin per button.

EDIT: I read now that the shield you got uses only 2 pins and communicates using I2C bus (which is perfect) so I'm 100% sure that it's designed to be on top of the stack and work together with other shields and uses extra pins for mechanical support.

---
Tags: lcd, adafruit
---


# Question
Title: Powering an Arduino directly from a motor driver (DRV8825) or external power source?
Hello people from StackExchange,

I'm new to Arduino and driving stepper motors in general; please excuse me for my limited knowledge on the subject. I've been doing research for a few hours already, looking into powering stepper motors and the Arduino, though I've gotten conflicting information regarding my problem.

My problem, or well question if you will, is as follows: The circuit I need, simplified, contains an Arduino, a stepper motor driver (DRV8825), a NEMA17 5kg.cm stepper motor and a 12V battery pack (yet to be decided what kind of pack, though it will be 12V). Do I need another, lower voltage, battery pack?

After looking into how to power stepper motors using the Arduino online, I found several sites instructing me how to do so. All of the sites had the same circuit I would use, only the motor was different. Here is one of the circuits:

As you can see, it only has a single power supply (with capacitor to catch voltage peaks). I understand most of the circuit, though one question remains: why exactly is there only one power supply being shown here, is it because the Arduino can get its power from the driver? (You can see the pin descriptions in the second image below) Or do they simply not show the (5v) power supply for the Arduino?

The thing I want to know, is whether this circuit would function without an external power supply for the Arduino or not? And if not, would connecting the Arduino to the power supply via the VIN pin work? That would be nice, as it would offer a simple way of fixing the problem instead of getting a separate power source. Connecting the Arduino through USB wouldn't work for my project, as it can't have any wires coming from it. It needs to be completely mobile.

For comparison, here is a circuit that does show the Arduino with an external power source:

I'm a first years mechanical engineering student, hence my little knowledge on Arduino's and stepper motors.

Thanks in advance.

# Answer
> why exactly is there only one power supply being shown here, is it because the Arduino can get its power from the driver?

No. It is assumed that you will provide the power to the Arduino yourself - either through the USB connection to the computer, or through the barrel jack.

> The thing I want to know, is whether this circuit would function without an external power supply for the Arduino or not?

No. The Arduino requires power to be provided.

> And if not, would connecting the Arduino to the power supply via the VIN pin work?

Yes, but it's not ideal. At 12V the power wasted by the on-board linear voltage regulator will be proportionally high. As long as all that is being powered is the Arduino itself that shouldn't be too bad, but if you try to draw any significant current either out of the 5V pin or through multiple IO pins (for example to drive lots of LEDs) then it will overheat and potentially shut down.

A more ideal arrangement would be to connect a 5V switching regulator to the 12V battery and use that to power the Arduino either through the 5V pin or the USB connector. Personally, I use cheap UBEC modules from RC model suppliers. They are small, low-cost, and very easy to wire up.
> 1 votes

---
Tags: power, motor, stepper
---


# Question
Title: Replicate output of pwm pin on another output pin?
Ardiuno Mega 2560

I have a legacy PCB that connects PORTA, pins = {22, 23, 24, 25, 26, 27, 28, 29} to the PWM input of a set of actuators. The accompanying code made use of an interupt service routine to generate PWM signals. This in turn caused all sorts of other problems for the system.

So, I would like to leverage the Mega's internal counters & use the PWM available on pins = {2, 3, 4, 5, 6, 7, 8, 9} & use the `analogWrite()` function. At present there is nothing else connected to these pins but access is limited.

Before I go down the route of redesigning the PCB I was wondering if it was possible to replicate the outputs of pins {2, 3, 4, 5, 6, 7, 8, 9} to pins {22, 23, 24, 25, 26, 27, 28, 29}?

# Answer
> 1 votes
As Jot wrote, you cannot simply route a signal from pin to pin inside the chip/Arduino. So - unless you redesign the PCP, which would be the cleanest way, or use jumper wires, which is not so clean - you are down to using software PWM. There are also libraries for this, if you don't want to write this yourself, for example the SoftPWM library. These libraries have their own limits, especially in frequency. Be sure to check, if they fit your needs.

---
Tags: arduino-mega, pwm, analogwrite, digitalwrite
---


title: Getting weird characters from Arduino

text:
# Question
Title: Getting weird characters from Arduino
My arduino is connected to ultrasonic sensor and I am trying to read the value from it. When I tried running "tail -f \> /dev/ttyACM0" my arduino is sending some weird characters that I am not able to decode

# Answer
It would seem you failed to configure the port on the Linux side. By default, it is configured to who-knows-what baud rate, and to a “cooked” mode where the data is preprocessed by the kernel driver. You want instead to set it to the correct baud rate and to “raw” mode. The `stty` (meaning, “set terminal”) command does this:

```
stty -F /dev/ttyACM0 raw 9600

```

Replace 9600 with whatever baud rate your Arduino is using.

If you Arduino program attempts to read the serial port, it will see the echo of the characters it sends. In that case you probably want to disable this echo also:

```
stty -F /dev/ttyACM0 raw -echo 9600

```
> 3 votes

# Answer
Most likely this is incorrect baud rate. You can try with a program dedicated to serial ports, my personal choice is picocom but it can by minicom or any other:

```
$ picocom -b 9600 /dev/ttyACM0

```

The `-b` parameter is used for specifying the baud rate, depending on the sketch it can be something else than 9600, the most common ones are: 9600, 14400, 19200, 28800, 38400, 57600

Another solution is to configure the `/dev/ttyACM0` with correct baud rate using `stty`:

```
stty -F /dev/ttyACM0 9600 cs8 -cstopb -parenb

```

This will configure the serial port to 9600 bps, 8 bits, 1 stop bit, no parity, and allow the `tail` command to read it correctly, if the communication parameters match what the arduino is sending
> 0 votes

---
Tags: serial
---


# Question
Title: Can't upload to my Nano after updating to Arduino AVR Boards 1.6.21
I recently had the Arduino IDE notify me of available boards updates, so I updated. Since then when I try to upload to my Nanos it fails:

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

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

```

I installed Arduino IDE 1.0.6 and found that I can upload to all my Nanos with that IDE version.

How can I upload to my Nanos using Arduino AVR Boards 1.6.21?

# Answer
> 10 votes
Arduino recently changed the bootloader they ship on their official Nano boards. This required a change in the hardware definition for the Nano, which was the sole reason for the Arduino AVR Boards 1.6.21 release.

The new Nano hardware definition is not backwards compatible with Nanos that use the previous ATmegaBOOT bootloader. For this reason a new menu option was added: **Tools \> Processor \> ATmega328P (Old Bootloader)**. If you select that option the uploads to your Nanos will work again.

# Answer
> 0 votes
Check weather your arduino nano is Chinese having CH340G chip. If the chip is there then you have to install CH340G drivers in your computer..

# Answer
> 0 votes
I also had similar issues after upgrading my Ubuntu system.

Selecting 3.3V for the Mini board did the trick, For the Nano, the old loader worked.

---
Tags: arduino-uno
---


# Question
Title: Arduino Uno with 6x 5V solenoids + 9V battery - Not enough power?
I have 6 5V solenoids connected to an Arduino Uno, each of them with a TIP120 transistor, diode and resistor. Exactly like https://core-electronics.com.au/tutorials/solenoid-control-with-arduino.html but 6 times. I'm using a 9V battery connected to the DC input, as well as USB input to my PC.

Now the problem is that if I activate 5 or 6 solenoids at once, the Arduino seems to get interrupted / lose all power for a second (disconnect sound from the PC and no activity). I've tested them one by one and everything works, but I can activate at most 4 solenoids at once.

What am I missing? Do I need more power?

# Answer
> I'm using a 9V battery connected to the DC input

Well, there's your problem. Those 9V PP3 batteries are barely enough to power the Arduino by itself. Add anything like motors and solenoids and you're going to have problems. Big problems.

Ditch the PP3 battery. It's only suitable for very low current devices, like smoke alarms. For anything more you need at least multiple series AA batteries.

Also the solenoids must be powered direct from your power source (or through their own regulator if needed), since the Arduino's on-board regulator will go into thermal shutdown quite quickly with 9V in and a large current draw.
> 1 votes

# Answer
Another possibility is to use latching solenoids controlled by an H-bridge so that they only need power to turn on or turn off. However, I don't know if they are available for your application. When I looked into latching irrigation valves they were much more expensive than simple solenoid valves.
> 0 votes

# Answer
You're experiencing a lack of available current. When the solenoids are operating, the system is trying to draw more current than the battery can provide, so what happens instead is the voltage starts to drop. (I can't remember exactly why this happens right now). When this happens the arduinos power supply detects an under-voltage condition and shuts down, but as soon as it shuts down the current draw tanks and the voltage rises again causing the system to restart. Essentially, the answer to this is to provide your system with a larger current source and the problem should go away.
> 0 votes

---
Tags: power, battery, resistor, transistor
---


# Question
Title: Can the 'Adafruit Non-Latching Mini Relay FeatherWing' be used with an Arduino microcontroller such as an Arduino Mega 2560?
Can this relay found here:

https://www.adafruit.com/product/2895

Be used with an Arduino Mega? The description given seems to specify that you should hook it up to their dedicated 'Featherwing Board' but it's the only relay available on their site. Looking at the pins it has it seems it should hook up to an Arduino with no problems. Has anyone here had the chance to use this relay with an Arduino microcontroller? I asked them about this on their forum but I haven't received a reply yet.

PS: I want to use it to connect a 'Strobe Siren 12VDC' and the relay I was looking to get is out of stock at my local shop.

https://store.nerokas.co.ke/index.php?route=product/product&product\_id=1398 https://store.nerokas.co.ke/index.php?route=product/product&product\_id=1679

# Answer
> 2 votes
Yes.

There's not a lot more to be said really.

It's a relay, and they provide a MOSFET and associated circuitry to drive it cleanly.

Just connect power and ground to the Arduino, along with the "Signal" pin to the GPIO pin of your choice, and away you go.

Note that the relay is a 3.3V relay, so you must power it by the 3.3V pin, not the 5V pin.

# Answer
> 0 votes
That is a 3.3V device. you'll need to give it a separate 3.3V power input, and it needs much higher current at 3.3V than the Arduino can supply.

I don't know if you can feed it a 5V logic signal or not. (If it needs 3.3 V control signals as well, and it's current needs are modest you could step down the voltage from an Arduino 5V digital output to 3.3 with a simple voltage divider circuit.)

You'd be better off getting a 5V relay. If you do a Google search on "Arduino Relay" you'll find tons of them. You can get 1 relay, 2 relay, 4 relay, and more on a board. Many have optical isolation to make sure the relay coils don't add noise to the logic lines.

In general it's a good idea to use a separate power supply for the relay, or at least use a power supply with plenty of current to spare, and add filtering capacitors between the 5V rail and ground right next to both the relay and the Arduino. These capacitors serve to filter out variations in voltage as the relay coils are powered on and off.

(Even "digital" relays draw a large amount of current from their power source when they first turn on, and abruptly *stop* drawing current when they turn off, which introduces a lot of noise on the power line. "Naked" relays need "flyback diodes" to avoid reverse currents that will destroy transistors, but the "digital ready" relays I'm talking about have those built in.)

Here is one such relay I found from Googling "Arduino relay".

https://vetco.net/products/single-relay-module-for-arduino?gclid=EAIaIQobChMI8Ye70K-e4QIVBkSGCh2EBgEiEAQYAyABEgIxpvD\_BwE

---
Tags: adafruit, relay
---


# Question
Title: Determining state of charge using current sensor (ACS758) with arduino uno
I am working on a university project and I am struggling with estimating the state of charge of our batteries, by using coulomb counting.

Background: We are supposed to build a power supply for a mostly constant load of 100 W (can go up to 140 W) which will be placed outdoors for two years. The plan is to have a small wind turbine plus some solar PV connected to a large battery assembly. The system has to run close to 24/7 with limited downtime.

I have bought some ACS758 50A bidirectional current sensors as well as an Arduino UNO. I am extremely new to Arduino and I would really appreciate some help with the coding. The plan is to have the arduino do the sampling of current and integration, which is then translated to SOC as a percentage and sent to a Raspberry Pi which will send email alerts if the SOC is below a certain level.

I have been looking at sample code describing how to extract the raw data from the ACS sensor: https://www.dfrobot.com/wiki/index.php/50A\_Current\_Sensor(SKU:SEN0098) as well as sample code that performs integration (Integrating an analog signal using ARDUINO UNO SMD), which is what I would use for coulomb counting.

What I need is most likely a combination between the two, however I do not even know where to start from.

Thanks in advance!

# Answer
> 2 votes
Instead of using a separated component for each thing you can use a proper solution that is itself already a combination of both: the **DS2438's integrated current accumulator**. This link explain it pretty well, also here is a library to use it with arduino. They are pretty cheap (a few dollars) and will perform very well!

Although, in your place I would consider choosing a different approach. I don't know which kind of battery (Li-ion, LiPo, Lead-acid..) you are using, but in many cases if you monitor the battery voltage, you can have enough information about the battery state. I can't ask you in comment yet beause I'm new here and don't have enough reputation, but if you can describe better the kind of battery you are using and what you intend to monitor which your circuit, I can edit this post to offer you a better solution.

# Answer
> -1 votes
you should probably determine the soc using both current integration and open circuit voltage method.It is possible to cover the weakness of both techniques and provide an accurate monitoring technique.I can provide you the codes if you need,

```
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int mVperAmp = 100;const float chargingdfficiency= 0.7;
int RawValue= 0, ACSoffset = 2500;
double Voltage = 0, Amps = 0;
double g,q;
int m=0,c=0,d;
void resett(){
digitalWrite(8,LOW);
digitalWrite(7,LOW);}

void setup() {
pinMode(A0, INPUT);pinMode(A1, INPUT);
pinMode(7,OUTPUT);pinMode(8,OUTPUT);
pinMode(9,OUTPUT);
Serial.begin(9600);
delay(10);lcd.begin(20, 4); delay(10);}

void loop() {
resett();
double vini=analogRead(1);vini = vini*5/1023;
vini=5*vini;Serial.print(vini,3);vini=vini/6;
double soc=((666.6667)*vini)-1300;delay(10);
q=soc*.42;
if(soc<30){m=1;resett(); digitalWrite(7,HIGH);} //charging
if(soc>=100){m=0;resett();digitalWrite(8,HIGH); } // DISCHARGING
if(m==0){resett();digitalWrite(8,HIGH);}
delay(10);
while(1){
RawValue = analogRead(0);
Voltage = (RawValue / 1024.0) * 5000;
Amps = ((Voltage - ACSoffset) / mVperAmp);Amps=-Amps;
if((Amps<.098)&&(Amps>-.098)){Amps=0;}
if(Amps>9){
resett();
lcd.clear();
lcd.display();
lcd.setCursor(1,0);
lcd.print("Overload");digitalWrite(9,HIGH);
while(1);}
if(m==0){
if(Amps<=1.5){g=1.183;}
else if(Amps<=2){g=0.042*Amps+1.12;}
else if(Amps<=4){g=0.028*Amps+1.148;}
else if(Amps<=5){g=0.032*Amps+1.132;}
else if(Amps<=6){g=0.03*Amps+1.142;}
else if(Amps<=7){g=0.325*Amps-0.628;}
else if(Amps<=7.5){g=0.066*Amps+1.185;}
else if(Amps<=8){g=0.028*Amps+1.47;}
else if(Amps<=10){g=1.694;}
soc=(q-Amps*g*0.0002778)*2.38095; q=soc*.42;
if(soc<5){m=1;resett();digitalWrite(7,HIGH);} }
if(m==1){
soc=(q-Amps*chargingdfficiency*0.0002778)*2.38095;
q=soc*.42;
if(soc>=100){m=0;resett();digitalWrite(8,HIGH);}}
lcd.clear();
lcd.display();
lcd.setCursor(1,0);
lcd.print("Soc = ");
lcd.setCursor(13,0);
lcd.print(soc,1);
lcd.setCursor(19,0);
lcd.print("%");
lcd.setCursor(1,1);
lcd.print("Amps= ");
lcd.setCursor(13,1);
lcd.print(Amps,1);
if(m==1){lcd.setCursor(1,2);lcd.print("Charging");}
else{lcd.setCursor(1,2);lcd.print("Discharge");}
lcd.setCursor(1,3);lcd.print("Normal");
Serial.println((vini),3);
Serial.print("Amps = ");
Serial.println(Amps,9);
Serial.print(" Soc = ");
Serial.println(soc,9);

for(d=0;((Amps==0)&&(d<=1200));d++){RawValue = analogRead(0);
Voltage = (RawValue / 1024.0) * 5000;
Amps = ((Voltage - ACSoffset) / mVperAmp);Amps=-Amps;
if(d==1200){vini=analogRead(1);vini = vini*25/(6*1023);
soc=((666.6667)*vini)-1300;d=0;}}

delay(1000);
}
}

```

---
Tags: arduino-uno, programming, sensors, battery
---


# Question
Title: Control 2 ESC with a potentiometer with arduino
I have 2 ESC (electronic speed controller) which control these brushless motors: Hobbyking Donkey ST3511 Brushless Motor

I would like to make them work with a poentiometer, under arduino.

I have a program but it only works with one engine. Here is the program :

```
#include <Servo.h>//Using servo library to control ESC

Servo esc;
Servo esc2;
//Creating a servo class with name as esc

void setup()

{

esc.attach(9); //Specify the esc signal pin,Here as D8

esc.writeMicroseconds(1000); //initialize the signal to 1000

Serial.begin(9600);

esc2.attach(9); //Specify the esc signal pin,Here as D8

esc2.writeMicroseconds(1000); //initialize the signal to 1000

Serial.begin(9600);

}

void loop()

{

int val; //Creating a variable val

val= analogRead(A0); //Read input from analog pin a0 and store in val

val= map(val, 0, 1023,1000,2000); //mapping val to minimum and maximum(Change if needed)

esc.writeMicroseconds(val); //using val as the signal to esc
esc2.writeMicroseconds(val);
}

```

I did not find help on the internet, thank you in advance.

# Answer
If you want one potentiometer to handle BOTH ESCs' speed, you could use this code:

```
//Using servo library to control ESC
#include <Servo.h>

//Starting the servos
Servo esc1;
Servo esc2;

void setup() {
    esc1.attach(9); // Use a PWM pin to the Servo, in this case 9
    esc1.writeMicroseconds(1000); //initialize the signal to 1000
    esc2.attach(10); // Pick another PWM to the other, in this case 10
    esc2.writeMicroseconds(1000); //initialize the signal to 1000

    Serial.begin(9600);
}

void loop() {
    int val; //Creating a variable val
    val= analogRead(A0); //Read input from analog pin a0 and store in val
    val= map(val, 0, 1023,1000,2000); //mapping val to minimum and maximum(analogRead's goes from 0-1023 and analogWrite's goes from 0-255, check your servo's specs)
    esc1.writeMicroseconds(val); // write to the first ESC
    esc2.writeMicroseconds(val); // write to the second ESC
    delay(100); // We usually set a small delay to avoid excessive readings or over-heating, but thats optional...
}

```

If you need to use two potentiometers, one for each ESC, then you would have to start another variable to read the 2nd pot value and use it to write on the 2nd ESC, simple as that! :)
> 1 votes

---
Tags: arduino-uno, electronics, potentiometer
---


title: Is Ticker.h really safe to use?

text:
# Question
Title: Is Ticker.h really safe to use?
I have this code

```
#include <Ticker.h>  //Ticker Library
Ticker blinker;
/* ... */

//blinker.attach(1, []() { digitalWrite(LED,!digitalRead(LED)); }
while(!client.connect(laptop,port)) {
   Serial.println("Connecting...");
   delay(1000);
}

```

Which works fine, tries connecting, then eventually connects.

If I uncomment the line attaching to this 'blinker' Ticker, then I get a crash right after the first 'Connecting...' print. When I look at the stack trace, it mentions that the crash happens during the delay(1000) in my while loop (which is presumably the moment when the program yields and the blinker can do some work)

Is there anything I can do to make this timer work better?

# Answer
> 4 votes
**Update**: the original question mentioned timers, so this answer is for a hardware timer interrupt handler. It doesn't apply to `Ticker`, which is what the question is now about.

The callback that you attach to `blinker` will be called as an interrupt handler, so it's important to make sure it's already loaded into executable instruction memory (iRAM) on the ESP8266. When you pass anonymous function inline to `blinker.attach()` it won't tagged to be stored in iRAM.

Try this instead:

```
void ICACHE_RAM_ATTR blinker_handler(){
    digitalWrite(LED,!(digitalRead(LED)));  //Toggle LED Pin
}

...

blinker.attach(1, blinker_handler);

```

`ICACHE_RAM_ATTR` tells the system to keep the code in the instruction RAM. There's not a lot of iRAM (32Kbytes) so you don't want to do this too often, but it's important for interrupt handlers (another reason to keep them short and sweet).

---
Tags: esp8266
---


# Question
Title: Powering Uno with 9v battery makes it "freak out"
I encountered an odd problem with my Uno, it works completely fine through USB on the PC or when powered by a power bank, but as soon as I connect it on a 9v battery it just freaks out. I have a relay connected to it that is connected to a switch, works fine, but on the battery it keeps turning on and off super fast, like so fast that the relay doesn't even show it's doing it, I noticed because of the noise it makes. I even tried to slow it down with a delay but nothing changed.

Anyone have any idea why the battery would make this happen?

# Answer
Not enough current available from the battery, relays take quite a lot. As soon as the relay tries to switch the voltage drops and the Uno resets due to brownout (low voltage)
> 4 votes

# Answer
It's actually not just the relay that takes up a lot of current. The 9V-port on your arduino uno is actually not meant for a 9V block, because the arduino uno needs a higher current than your 9V block can deliver. You can put 6 1.5V battery cells (AA batteries) in series, they will deliver the current you'll need.
> 1 votes

---
Tags: arduino-uno, battery
---


# Question
Title: Parsing array of an object in a library constructor
I am trying to develop an Arduino library that consists out of two classes. I want 'WayPointStack' to store an array of 'WPCommand', but I can't get it to work.

WayPointStack.h

```
#ifndef WayPointStack_h
#define WayPointStack_h

#include "Arduino.h"
#include "WPCommand.h"

class WayPointStack
{
  public:
    WayPointStack();
    WayPointStack(WPCommand* wp);
    WPCommand GetNextWP();
    WPCommand GetWP(int i);
    void AddWP(int target, int time);
    int SetWPPointer(int i);
    int GetLength();
  private:
    WPCommand* _wp;
    int pointer;
    int length;
};
#endif

```

WPCommand.h

```
#ifndef WPCommand_h
#define WPCommand_h

#include "Arduino.h"

class WPCommand
{
  public:
    WPCommand(int target, int time );
    WPCommand();
    int GetTarget();
    int GetTime();
    int LEFT;
    int RIGHT;
    int FORWARD;
    int BACKWARD;
    int STOP;
    int END;
  private:
    int _target;
    int _time;
};

#endif

```

Parts of WaypointStack.cpp

```
#include "Arduino.h"
#include "WayPointStack.h"
#include "WPCommand.h"

#define arrSize 100

WayPointStack::WayPointStack()
{
  _wp = new WPCommand[arrSize]; // should be enough, heap blabla
  length = 0;
  pointer = 0;
}

WayPointStack::WayPointStack(WPCommand[] wp)
{
    _wp = new WPCommand[arrSize]; // should be enough, heap blabla
    for (int i = 0; i < sizeof(wp), i++){
        _wp[i] = wp[i];
    }
    length = sizeof(wp);
    pointer = 0;
}

```

I'm pretty sure I'm doing something wrong with the pointers, but I don't know how to fix it. The first two errors are

```
WayPointStack.cpp:24:42: error: expected ',' or '...' before 'wp'
WayPointStack::WayPointStack(WPCommand[] wp)

```

and

```
WayPointStack.cpp:27:29: error: 'wp' was not declared in this scope
for (int i = 0; i < sizeof(wp), i++){

```

I obviously have to use a pointer. This is all I know, so far. Has someone an idea?

# Answer
> 1 votes
This is a C++, not Arduino question and should be asked on Stack Overflow.

In C/C++ the \[\] must be on variable name, not on type. `WPCommand wp[]` (it is the same as `WPCommand* wp`).

`sizeof` return size in bytes, not element count. send `length` as parameter

Dynamic memory allocation in MCU is not a good thing. You can have in `WayPointStack`

```
WPCommand _wp[arrSize]

```

---
Tags: arduino-uno, c++, library, array, pointer
---


title: PID control for Motor Speed control

text:
# Question
Title: PID control for Motor Speed control
I was trying to apply PI controller to a motor using Arduino. I have somewhat achieved the task but the problem is that it oscillates too much. Also i couldn't figure out what to do when pwm signal are calculated as negative

```
  int counter = 0;
  double end_time=0;
  double ini_time=0;
  double rpm=0;
  double my_time=0;
  double temp = 0;
  int pid_speed=0;
  float kp=2.25;
  float ki=.01;
  float kd=0.005;
  int prev_error=0;
  double pwm_sig=0;
  int integrator  = 0;
  int motor_sig_pin= 5;
  int error=0;
  int absolute = 0;
  float desired_rpm=1000; //my desired RPM value
  double zero_time=0;
  double i_time=0;
  double f_time=0;
  int rpm_tacho=0;
  int previous_error=0;
  int derivative=0;

  void setup() {
    pinMode(2,INPUT);
    digitalWrite(2,HIGH);
    pinMode(motor_sig_pin,OUTPUT);
    pinMode(9,OUTPUT);
    pinMode(10,OUTPUT);
    digitalWrite(9,HIGH);
    digitalWrite(10,LOW );
    attachInterrupt (0,Count,RISING);
    ini_time = micros();
    i_time=micros();
    Serial.begin(115200);
  }

   void Count(){ //calculating time for one round using encoder

      counter++;
      if (counter>=100){
        end_time=micros()-ini_time;

        ini_time=micros();
        counter=0;
      }
   }
  void loop() {
      rpm = ((1000000*60)/(end_time));
      rpm = abs(rpm);
      rpm_tacho = ((1000000*60)/(zero_time));
      if (rpm <10 || rpm>5000){
        rpm=0;
      }
      error=desired_rpm-rpm;

      integrator += error;
      pid_speed = kp*error; + ki*integrator;

      pid_speed=(int)pid_speed;

      Serial.print(pid_speed);
      Serial.print("       ");

      if (pid_speed> 0){
        if (pid_speed>255)
          analogWrite(motor_sig_pin,255);
        else
          analogWrite(motor_sig_pin,pid_speed);
      }
      if(pid_speed<0){
        if(pid_speed<-255)
        {
            analogWrite(motor_sig_pin,0);
        }
        else
       {
          pid_speed=abs(pid_speed);
          analogWrite(motor_sig_pin,255-pid_speed);
       }
      }
      Serial.print ("      ");
      Serial.println(rpm);
  }

```

# Answer
> 1 votes
Instead of thinking of the PID output as pid\_speed, think of it as motor\_power, and what the PI controller is doing is translating errors in rpm into a motor power setting.

You are probably getting oscillation because of integral windup. If your loop is fast relative to your system, each loop worth of error adds to integrator quickly/quicker than the system can adjust. For example, if a loop takes 1ms, an error of 100rpm could overflow the "int integrator" past 32768 in only 0.327 seconds, and past the threshold where the integrator could peg the output 25500 (=255/Ki) in only 0.255sec If the integrator is faster than the system, it can easily cause overshoot. You might consider slowing the loop down to 10ms, 100ms or 1000s to match the physical process and make the kI term be a sane conversion of the integrator's rpmError*seconds/100, rpmError*seconds/10, or rpmError\*seconds into output power.

To handle the numerics and constraints better, like overflowing integrators and negative output values, it would probably be best to use the Arduino PID library from http://playground.arduino.cc/Code/PIDLibrary as in Edgar Bonet's comment.

# Answer
> 0 votes
I do not know if this question still exists or you managed to solve it. Regardless, I was (still am) working on a self balancing robot where I also faced such an issue and I came to this forum. The way I tackled it was to set PID outputs (assuming you are using Arduino 's PID library) 0 - 255 instead of -255 to 255. Now for my project I needed to change direction of the motor depending upon the inclination angle of the robot. So, each time I need to change the motor rotation direction, I do the following

* I first reset the Iterm (or make it zero).
* Change the direction of rotation.
* Begin PID computation again.

Earlier I was also trying to achieve this by -255 to 255, but it was very jerky and I was not sure if that was the correct way to do it. With my current approach, I have managed to solve my problem.

---
Tags: arduino-uno, pwm, pid
---


# Question
Title: Arduino nano power 5V or 12V and LED strip 2812B 5V
I would like to know a little more about Arduino inputs and outputs.

I'm doing a small project which is composed of 1 LED strip with 40 LED's.

Can't find any definitely information about Arduino + LED strip.

At the moment all of this doesn't work correctly and I guess the reason is bad power connection .

The main power is from USB. So all of this in a car. I have ~12v (+2 or -2 Volts ) and then Voltage regulator to 5V with USB output and then cable connecting 5V through USB Arduino . Then I took wires from VIN ( pin number 30 ) to LED strip +5V ( which is basically main fuse on the strip ) and then GND to ground of led strip and of course DIN to DIN like it should be.

Conclusion is - the led strip won't work normally and colors are not proper .

How should I do connect ?

If I will take off the voltage regulator then main fuse from the car ~12V connect to the VIN (it will be a main arduino power) . GND - GND pin obviously. - and then again from same point ~12V of car will connect to voltage regulator 12V to 5V and that 5V must be with LED strip FUSE +5V ?

Is it will be correct way ? And one more question, shall I put between "*main fuse from the car ~12V connect to the VIN (it will be a main arduino power)*" - Voltage regulator 12V to 5V ? is it necessary ?

Thanks for you answers guys, hope you will help me with this.

I'm going to read same questions and answer with this any way. Will wait your answers too :)

# Answer
> The main power is from USB. So all of this in a car. I have ~12v (+2 or -2 Volts ) and then Voltage regulator to 5V with USB output and then cable connecting 5V through USB Arduino .

Good. That is the best way of powering an Arduino in a car. Use a phone charger is best.

> Then I took wires from VIN ( pin number 30 ) to LED strip +5V

There's no such thing as a "pin number 30" on an Arduino Uno. However, powering *anything* from VIN when you are supplying power into the Arduino through USB is *very* bad.

Basically, the current has to flow *backwards* through the onboard regulator to get to the VIN pin - and the regulator *really* doesn't like that.

Instead, you should be connecting your LED strip to the 5V pin of the Arduino so it is connected direct to the 5V USB power.

Note, however, that the USB power has a limit of 500mA. This is not a limit of the supply - it is a limit imposed by a 500mA PTC fuse on the Arduino that will shut off the current if more than 500mA is drawn. It would be far better if you could cut the USB cable and take the 5V and GND wires and directly connect them to both the Arduino's 5V and GND pins, and the LED strip's 5V and GND connections. That will then mean that the LEDs are taking their power directly from the power supply, not from the Arduino.
> 2 votes

# Answer
40 LEDs can draw up to 60mA x 40 = 2.4A (2400mA). Make sure you have a large enough current source if you are planning on using full white on all LEDs.

Arduino regulators are not selected to support 2.4A. 600-700 mA tops, and then only if the voltage to the barrel jack is 7.5V max. With 12V, much less current is supported as the regulator gets hot dissipating (12V - 5V) x current draw as excess heat.

And 500mA for USB as noted due to PTC fuse.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Im trying to get a 3 button password sequence working
I'm trying get a password system working that when you click 3 buttons in a certain order (1, 2, 3, 3, 1) then an LED will light up. But as I'm going to implement this into a larger code I can't just have the void loop() going forever to wait for it.

I think my issue is in the while loops and making it wait for one of the buttons to be pressed but I don't know how to get it to work.

thanks

```
#define greenLED A0
#define redLED A1

int button1 = 5;
int button2 = 4;
int button3 = 3;

void setup() {
  // put your setup code here, to run once:
  pinMode(A0, OUTPUT);
  pinMode(A1, OUTPUT);
  pinMode(button1, INPUT_PULLUP);
  pinMode(button2, INPUT_PULLUP);
  pinMode(button3, INPUT_PULLUP);
}

void loop() {
  // put your main code here, to run repeatedly:
  int total = 0;
  while(digitalRead(button1) == LOW && digitalRead(button2) == LOW && digitalRead(button3) == LOW){
    while(digitalRead(button1) == LOW && digitalRead(button2) == LOW && digitalRead(button3) == LOW){
      while(digitalRead(button1) == LOW && digitalRead(button2) == LOW && digitalRead(button3) == LOW){
        while(digitalRead(button1) == LOW && digitalRead(button2) == LOW && digitalRead(button3) == LOW){
          while(digitalRead(button1) == LOW && digitalRead(button2) == LOW && digitalRead(button3) == LOW){
            if(digitalRead(button1) == HIGH){
              total = total + 1;
            }
          }
          if(digitalRead(button2)==HIGH){
            total = total+1;
          }
        }
        if(digitalRead(button3)==HIGH){
          total = total + 1;
        }
      }
      if(digitalRead(button3)==HIGH){
        total = total+1;
      }
    }
    if(digitalRead(button1) == HIGH){
      total = total+1;
    }
  }
  if(total == 5){
    digitalWrite(A0, HIGH);
    delay(2000);
    digitalWrite(A0, LOW);
  }else{
    digitalWrite(A1, HIGH);
    delay(2000);
    digitalWrite(A1, LOW);
  }
}

```

# Answer
> 2 votes
Without programming everything out, use something like this:

* Initialization:

+ Create a (global) variable of string ("12331") which is the code
    + Create a (global) variable of int that shows the number of correct numbers so far (initially 0)
* In the while loop:

+ Check which button is pressed
    + If it is the correct button
    + increase the int variable
    + If that variable is 5 (meaning all numbers ok), light up the LED
    + Delay
    + Make the variable 0 again
    + Clear the LED
    + If the wrong button is pressed
    + If it is equal to the first value ('1')
        - Set the variable to 1 (since the wrong number is the first correct number)
    + Else
        - Set the variable to 0

# Answer
> 0 votes
For something like this, a state machine would probably be useful. Since this is software, we can skip the register assignment and use a state table directly.

```
The table would look as follows:
1. If button 1 is pressed, 2. Else 1.
2. If button 2 is pressed, 3. Else 1.
3. If button 3 is pressed, 4. Else 1.
4. Run task, go to 1.

```

The code would require you to add an integer or byte outside `setup` or `loop`. This would then contain the state number.

Inside `loop`, you can add the if statements for reading the button pins.

If one of the buttons is pressed (the if-statement fires), you can compare the state with the condition listed above. If the state and the correct condition match, set the state to the new state.

Otherwise, reset it to the initial state (0 is default if you do not explicitly change it when programming, and most things are 0-indexed. You can also use 1, but you have to remember to initialize it to 1 when declaring the state variable. i.e. `byte state=1;`)

The below sample code presumes that the buttons are connected between GND and the GPIO input pin on the Arduino. Since it's using the internal pullup resistors, no external ones are needed. The one minor issue is that it inverts the state of the buttons -- 0==pressed, 1==released (not pressed).

```
byte state = 0;
bool pressed=false;//used to prevent repeats

void setup(){
  pinMode(pin1,INPUT_PULLUP);
  //Repeat for other pins. Replace pin# with the number.
}

void loop(){
  if (digitalRead(pin1)==0 && !pressed){
    pressed=true;
    if (state==0){
      state=1; //go to next state.
    }
    else{
      state=0; //reset state. Needed even here since the button might be
               //pressed later at the wrong time. Add 'else if (state==#)'
               //sections if the button needs to be reused again in later states.
   }
   if (digitalRead(pin1) && pressed){
     pressed=false;
   }
   //Add more if statements here, following the pattern, for any more buttons you need.
}

```

Further improvements may involve getting independent press-detection variables (one for each button), but being only able to register one button press at a time is probably a good thing, actually.

# Answer
> 0 votes
You can split this into two different problems, and I suggest you track them one at a time.

The first problem is to detect the button presses. This is not as trivial as it sounds. For once, `digitalRead()` tells you whether the button is pressed, but that's not quite what you want. You want to detect the discrete press “events”. In other words, you have to remember the previous state of the button, and record a press event only when the state *changes* from `HIGH` to `LOW`. This is called “edge detection”. When doing this on mechanical buttons, you *absolutely must* do some kind of debouncing.

I will not elaborate on this topic, as there are a few Arduino libraries available for debouncing buttons that also do edge detection. Once you have sorted this out, each of your buttons will have a `.fell()` method that tells you whether that button has just been pressed. Then, inside `loop()`, you can do something like

```
char key = 0;  // key pressed by the user, 0 = none
if (button1.fell()) key = '1';
else if (button2.fell()) key = '2';
else if (button3.fell()) key = '3';
if (key) {  // some key has been pressed
    // process key...
}

```

The “process key...” part should initially be a simple `Serial.write(c);`. This way you can use the serial monitor to check that this part of the program is working properly. Only when this is the case you can move to the second part.

The second problem is to process the key presses in order to detect whether the correct code has been entered. There are various possible approaches. One of them is to store in an array the 5 last keys entered by the user, and compare that array with the correct code to know whether the entry was correct. This is not very elegant, as it will require storing more information than necessary, and shifting the array each time a new key is typed.

A more elegant solution is given by Michel Keijzers. Let me paraphrase it in C++. Inside `loop()`:

```
if (key) {  // some key has been pressed
    if (check_code(key)) {  // correct code typed
        digitalWrite(LED, HIGH);
        delay(1000);
        digitalWrite(LED, LOW);
    }
}

```

where the logic for checking the correctness of the typed code is:

```
bool check_code(char key)
{
    const char code[] = "12331";
    const uint8_t length = sizeof code - 1;
    static uint8_t i = 0;  // number of correct characters so far

    if (key == code[i]) {  // correct key
        ++i;               // one more correct character
        if (i == length) {
            i = 0;         // reset
            return true;   // report entry is correct
        }
    } else {               // wrong key
        if (key == '1')
            i = 1;
        else
            i = 0;
    }
    return false;
}

```

Note that the part that handles a wrong key press is specific to that particular code. If you want the program to be generic, so that you can change the secret code just by changing the string `code`, it can get more complicated. For example, if the correct code is “12313” and the user has so far typed “1231”, he has so far 4 correct keys. Then,

* if he types 1, he now has 1 correct key press
* if he types 2, he has 2 correct keys (namely “12”)
* if he types 3, he completed the code.

Handling this generically requires walking back the code string and searching for the longest possible match. Here is my take at it: replace the `else` part in the function above with:

```
// ...
} else {               // wrong key
    for (int j = i-1; j >= 0; j--) {
        if (key == code[j]) {
            int k;
            for (k = 0; k < j; k++) {
                if (code[k] != code[i-j+k])
                    break;
            }
            if (k == j) {  // found a partial match
                i = j + 1;
                return false;
            }
        }
    }
    i = 0;  // no partial match
}
// ...

```

Here `j` is the position, within the code string, where the key typed by the user may match.

# Answer
> 0 votes
As Edgar Bonet mentions in his answer, button debouncing is a critical component, and there are libraries available to simplify this part of the requirement. I used the Bounce2 library with three N.O. push button switches. The following sketch works, but it still needs one or two improvements.

One issue occurs if the user enters 4 button presses, then leaves and comes back in 1 hour. All they have to do press the last correct button in the sequence, then they are authenticated. This could easily be fixed by introducing a `millis()` based timer that starts on the first button press, and stops after 5 seconds, for example. This timer would reset the `counter` variable and the `buttonsPressed[]` byte array.

Perhaps a "enter" code button and/or a "cancel" button would be useful.

```
#include <Bounce2.h>

const byte sequenceLength = 5;
byte sequence[sequenceLength] = {1, 2, 3, 3, 1};

byte buttonsPressed[sequenceLength];
byte counter = 0;
const byte ledPinCodeAccepted = 2;
const byte ledPinCodeDenied = 3;
const byte button1Pin = 10;
const byte button2Pin = 11;
const byte button3Pin = 12;
const unsigned long debouncerInterval = 50;

Bounce button1 = Bounce();
Bounce button2 = Bounce();
Bounce button3 = Bounce();

void setup(){
  pinMode(ledPinCodeAccepted, OUTPUT);
  pinMode(ledPinCodeDenied, OUTPUT);
  button1.attach(button1Pin, INPUT_PULLUP);
  button1.interval(debouncerInterval);
  button2.attach(button2Pin, INPUT_PULLUP);
  button2.interval(debouncerInterval);
  button3.attach(button3Pin, INPUT_PULLUP);
  button3.interval(debouncerInterval);
}

void loop(){

  if(button1.update()){
    if(button1.read() == 0){
      buttonsPressed[counter] = 1;
      counter++;
    }
  }

  if(button2.update()){
    if(button2.read() == 0){
      buttonsPressed[counter] = 2;
      counter++;
    }
  }

  if(button3.update()){
    if(button3.read() == 0){
      buttonsPressed[counter] = 3;
      counter++;
    }
  }

  if(counter == sequenceLength){
    counter = 0;
    digitalWrite(ledPinCodeAccepted, LOW);
    digitalWrite(ledPinCodeDenied, LOW);
    for(byte i = 0; i < sequenceLength; i++){
      if(sequence[i] == buttonsPressed[i]){counter++;}
      else{break;}
    }
    if(counter == sequenceLength){
      digitalWrite(ledPinCodeAccepted, HIGH);
    }
    else{
      digitalWrite(ledPinCodeDenied, HIGH);
    }
    counter = 0;
  }
}

```

---
Tags: arduino-uno
---


# Question
Title: 1st LED turn ON when 1st button is pressed and other LEDs remaining OFF
I have 2 LEDs and 2 buttons. What I want to code is when first button pressed the 1st LED turn on (stay on for 5 seconds) and 2nd LED remain off, and same if 2nd button pressed the 2nd LED turn on and 1st LED remain off. I want the processing reset after 5 seconds. Here is my work, what it does now is 1st LED turn on when I press 1st button, but the 2nd button and 2nd LED still can press and light up right after. I want the 2nd button deactivate when 1st button pressed for 5 seconds. Please give me basic program because I am new to this.

```
int pinButton_1 = 8; //the pin where we connect the button
int pinButton_2 = 9;
int LED_1 = 1; //the pin we connect the LED
int LED_2 = 2;
void setup() {
  pinMode(pinButton_1, INPUT); //set the button pin as INPUT
  pinMode(pinButton_2, INPUT);
  pinMode(LED_1, OUTPUT); //set the LED pin as OUTPUT
  pinMode(LED_2, OUTPUT);
}

void loop() {
  int stateButton_1 = digitalRead(pinButton_1); //read the state of the button
  int stateButton_2 = digitalRead(pinButton_2); //read the state of the button
  if(stateButton_1 == 1) { //if is pressed
     digitalWrite(LED_1, HIGH); //LED_1 on
     digitalWrite(LED_2, LOW); //LED_2 off
     delay(50);
  }
     if (stateButton_2 == 1) {
      digitalWrite(LED_1, LOW);
      digitalWrite(LED_2, HIGH);
      delay(50);
     }
  }

```

# Answer
First of all you have not implemented a stay on time of 5seconds `delay(5000);` but only 50ms `delay(50);`.

Second, you are not really switching of your LED's if no further button is pressed.

Change your `loop()` to the following, I guess this will help you to start your next steps into getting familiar with your code:

```
    void loop() {
      int stateButton_1 = digitalRead(pinButton_1); //read the state of the Button_1
      if(stateButton_1 == 1) {      //if Button_1 is pressed
         digitalWrite(LED_1, HIGH); //LED_1 on
         digitalWrite(LED_2, LOW);  //LED_2 off
         delay(5000);
      }
      digitalWrite(LED_1, LOW); //Switch off LED_1

      int stateButton_2 = digitalRead(pinButton_2); //read the state of the button 2
      if (stateButton_2 == 1) {
         digitalWrite(LED_1, LOW);
         digitalWrite(LED_2, HIGH);
         delay(5000);
      }
      digitalWrite(LED_2, LOW); //Switch off LED_2
    }

```

**Hint:** Using `delay()` is often not a good construct, better to do it with `millis()`, but this means some more changes. For the start in your case `delay()` will do, but check out what here in different Questions/answers is already written about `delay()` vs. `millis()`
> 1 votes

---
Tags: led, button
---


# Question
Title: Trying to measure change in light levels over time
I have two LDR's attached to my Arduino Uno and an RGB LED as an output component. The two LDR's are at different offboard heights in order to see the change in light between them. I want to code on Arduino so that if the difference in light between the two LDR's does not change by a large amount over a 1 hour period (i.e stays similar), it will make the RGB LED flash. I know that I have to use an if and else statement to do this, but does anyone know how I can code it so that I can achieve the above statement?

Thanks

# Answer
> 2 votes
Break this into pieces. Solve the pieces one at a time.

Write code that reads the 2 photocells and calculates the difference between them. Log that difference to the console.

Then add a global variable to remember the old difference, and a max difference. Each time you take a new set of readings and calculate the difference, compare it to the old difference. If the new difference is greater than the old difference, update the max difference. Then update the "old difference" with the new reading.

Figure out how to use millis() to record a starting time, and monitor the reading difference until an hour has passed. If the reading difference is below your "large amount" threshold, start the light blinking.

Then you need to decide what to do about times greater than an hour. Do you track the max difference over the most recent 60 minutes and flash the light if it is below your threshold? Maybe save a difference reading every 5 minutes into a ring buffer with 12 entries (an hour's worth of entries) and keep checking the ring buffer for a difference value greater than your threshold? (You should be able to Google search "C ring buffer" for sample ring buffer code. It's actually quite simple to implement.

You might also want to calculate a moving average difference reading, and compare each reading to that. I recommend using an Exponential Moving Average (EMA).

I have code in my project that uses EMA to calculate a single brightness value rather than a difference, but the idea is the same. Here is an excerpt from my code:

Define a global:

```
float   photocellAverage =      0;

#define sampleCountToAverage 100  //The larger the number of samples, the more slowly the average will change with each new reading.

```

Then

```
int photocellValue = analogRead(photocellPin);
photocellAverage -= photocellAverage / sampleCountToAverage;
photocellAverage += float(photocellValue)/sampleCountToAverage;

```

For you, you'd be calculating a difference reading and an EMA of that difference reading:

```
float   photocellDifferenceAverage =      0;

int photocell1Value = analogRead(photocell1Pin);
int photocell2Value = analogRead(photocell2Pin);
int photocellDifference = photocell1Value - photocell2Value;
photocellDifferenceAverage -= photocellDifferenceAverage / sampleCountToAverage;
photocellDifferenceAverage += float(photocellDifference)/sampleCountToAverage;

```

---
Tags: arduino-uno, rgb-led
---


# Question
Title: switching two relays without delay using millis
I have an Arduino-uno and two relays. Each relay has two switch on for two seconds at regular intervals. total loop time relay 1 and relay2 is 1800 seconds. relay 1 - 2 on,360 off,2 on,600 off,2 on,430 off,2on,402 off. relay 2 - 12 off, 2 on, 358 off, 2 on, 606 off, 2 on, 478 off, 2 on, 338 off. Can somebody help me on a code for this please.

# Answer
> 2 votes
this is a typical application for Blink Without Delay

# Answer
> -1 votes
```
// Turn leds on and off at certain times.
//
// When the digital output pin is HIGH, then the relay is off.
// When the digital output pin is LOW, then the relay is on.

enum actionEnum {
  RELAY1_ON,
  RELAY1_OFF,
  RELAY2_ON,
  RELAY2_OFF,
};

struct tableStruct {
  unsigned int time;
  actionEnum action;
} const table[] = {
  { 0, RELAY1_ON},
  { 2, RELAY1_OFF},
  { 2 + 360, RELAY1_ON},
  { 2 + 360 + 2, RELAY1_OFF},
  { 2 + 360 + 2 + 600, RELAY1_ON},
  { 2 + 360 + 2 + 600 + 2, RELAY1_OFF},
  { 2 + 360 + 2 + 600 + 2 + 430, RELAY1_ON},
  { 2 + 360 + 2 + 600 + 2 + 430 + 2, RELAY1_OFF},
  // remaining 402 for a total of 1800
  { 0, RELAY2_OFF},         // not needed, it is already off
  { 12, RELAY2_ON},
  { 12 + 2, RELAY2_OFF},
  { 12 + 2 + 358, RELAY2_ON},
  { 12 + 2 + 358 + 2, RELAY2_OFF},
  { 12 + 2 + 358 + 2 + 606, RELAY2_ON},
  { 12 + 2 + 358 + 2 + 606 + 2, RELAY2_OFF},
  { 12 + 2 + 358 + 2 + 606 + 2 + 478, RELAY2_ON},
  { 12 + 2 + 358 + 2 + 606 + 2 + 478 + 2, RELAY2_OFF},
  // remaining 338  for a total of 1800
};

const unsigned int totalTime = 1800;  // total amount of seconds for sequence
unsigned int seconds;

unsigned long previousMillis;
const unsigned long interval = 1000;  // 1000 ms is one second

const int relay1Pin = 2;
const int relay2Pin = 3;

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

  // The relay is off when the pin is high.
  // Turn output high before setting the pinMode.
  // Then the output changes from a floating pin to high,
  // and the relais will not be activated.
  digitalWrite(relay1Pin, HIGH);
  pinMode(relay1Pin, OUTPUT);
  digitalWrite(relay2Pin, HIGH);
  pinMode(relay2Pin, OUTPUT);
}

void loop() {
  // A one-second timer with millis
  if (millis() - previousMillis >= interval) {
    previousMillis += interval;

    // Scan table
    for (int i = 0; i < int(sizeof(table) / sizeof(tableStruct)); i++) {
      if (table[i].time == seconds) {
        switch (table[i].action) {
          case RELAY1_ON:
            Serial.println("Relay 1 on");
            digitalWrite(relay1Pin, LOW);  // low = relay on
            break;
          case RELAY1_OFF:
            Serial.println("Relay 1 off");
            digitalWrite(relay1Pin, HIGH);  // high = relay off
            break;
          case RELAY2_ON:
            Serial.println("Relay 2 on");
            digitalWrite(relay2Pin, LOW);   // low = relay on
            break;
          case RELAY2_OFF:
            Serial.println("Relay 2 off");
            digitalWrite(relay2Pin, HIGH);  // high = relay off
            break;
          default:
            Serial.println("Error, a bug in the sketch");
            break;
        }
      }
    }

    seconds++;
    if (seconds >= totalTime) {
      seconds = 0;
    }
  }
}

```

---
Tags: arduino-uno
---


# Question
Title: How can I connect an Arduino / ESP8266 to an Azure MySQL database?
I am currently trying to connect an ESP8266 to my Azure MySQL database via WiFi, but have not yet been successful.

I have tried a bunch of guides, but no luck and I'm running out of ideas. I have made a connection to an IoT Hub in Azure but could not forward the messages to the MySQL database in the cloud. I managed to get it stored in a blob datatype but had so many issues with it that I kinda scratched that idea.

Last thing I tried was trying to implement the example from https://github.com/ChuckBell/MySQL\_Connector\_Arduino more specifically the 'connect\_wifi' example. I was unable to find the ip of my azure server so i tried using some of the code from the 'connect\_by\_hostname' but no luck there.

I'm new to Arduino and cloud in general so any help is appreciated.

# Answer
Not sure how you would directly connect with an C++ embedded file. One way you could achieve this is by creating a computer application and connect to the machine via Bluetooth.

```
{Arduino}
* Intake information
* Process into commands
* Push through software serial ----(Blue Tooth-----> { PC or MAC}
                                                    *Create C# or Swift App
                                                    *Intake information via COM-PORT
                                                    *Prepare SQL command with serial data
                                                    *Push to database server

```

This may of not of been the method you were looking for, but it's a way I found around the issue when working with Azure Databases and Arduino Micro-Controllers. An alternative is going to Raspberry Pi which has a little more resources to deal with server functions.

Hope this helps.
> 1 votes

---
Tags: esp8266, wifi
---


# Question
Title: Is it possible to send data from device (e.g. MPU6050) to Arduino through cut/hacked USB cable?
So I understand the USB cable consists of VCC, GND and Data+, Data-.

Is it possible to connect an MPU-6050 gyro to these 4 pins, especially data+/-, and still receive them normally through the SCL/SDA pins on the Arduino?

The goal is to make an input piece modular by having an USB out at it while having an USB in at the Arduino.

Here is a basic visualization:

# Answer
Execellent non-Arduino question about I2C cable so the answer is also non-Arduino. I recommend the following Hackaday blog. https://hackaday.com/2017/02/08/taking-the-leap-off-board-an-introduction-to-i2c-over-long-wires/. You can find a more theoretical model in https://www.analog.com/media/en/technical-documentation/technical-articles/I2C-Cabling.pdf

Basically yes you can use cables. Different cables have different level of capacitance per meter. This will reduce the maximum frequency and may also require adjustment of the pull-up resistors.

Cheers!

BW: "nihil novi sub sole": This question has been asked before, https://forum.arduino.cc/index.php?topic=143337.0
> 1 votes

---
Tags: arduino-uno, usb, mpu6050
---


# Question
Title: VNH2SP30 Motor Driver not working in reverse
I bought 2 new VNH2SP30 Motor Drivers because i thought the first one was broken but they are both giving me the same issue, they run in forward direction but not reverse...

When the motor is unplugged the forward led is bright green, when the code executes the reverse direction, the reverse led is lit very dimly and multi meter measures no voltage.

I have tried:

* changing power source and voltage
* using different cables and pins
* using different motors
* using different code
* using different VNH2SP30 Motor Driver
* using different arduino

here is the code:

```
  #define INA 5 // outputs arduino
 #define INB 7
 #define EN 8
 #define PWM 11

 int motorSpeed = 255 ;  // motor speed

 void setup ( ) {
  pinMode ( INA , OUTPUT ) ;
  pinMode ( INB , OUTPUT ) ;
  pinMode ( EN , OUTPUT ) ;

  digitalWrite ( EN , HIGH ) ;
 }

 void loop ( )
 {
  digitalWrite ( INA , LOW ) ;  // turn the motor in one direction
  digitalWrite ( INB , HIGH ) ;
  analogWrite ( PWM , motorSpeed ) ;
  delay ( 1000 ) ;

  digitalWrite ( INA , HIGH ) ;  // turn the engine in the opposite direction
  digitalWrite ( INB , LOW ) ;
  analogWrite ( PWM , motorSpeed ) ;
  delay ( 1000 ) ;

  digitalWrite ( EN , LOW ) ;  // turn off
  delay ( 1000 ) ;
  digitalWrite ( EN , HIGH ) ;

 }

```

Heres the wire diagram but my outputs are just on different pins.

# Answer
There appears to be quite a few faulty drivers such as this one currently on Aliexpress. Of the 4 I have bought, only one works - the other three function exactly as you described. Same program, same motor, same control wiring as the one which works. I can only suggest try to buy from a different seller on ebay or ali; or of course pay top dollar for a chip from a reputable source.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Reading Digital Pins and Outputing on entire Ports
I'm very new to coding so please don't grill me.

I'm working on a scientific project where I am using a NI-DAQ to digitally trigger mosfets to trigger 300us - 3ms pulses on two high powered LED arrays. My intention is to use the Arduino UNO to basically relay one digital output into many. It remains important to use the NI-DAQ as the pulses are dependent on video cues and other outputs, otherwise the pulses would be purely produced by the Arduino.

I have decided to the port Port reg output to accomplish this as it would appear to have the greatest temporal precision but I’m having a very difficult time getting a single pin to trigger a port. I would greatly appreciate some help.

My code currently looks as such:

```
int inpin = 2; //input specified as pin 2
int x = 0; // variable to store the read value

void setup() {
pinMode(inpin, INPUT); //sets digital pin 13 as input
DDRD=B11111111; //pin 8-13 is in output mode
DDRC=B11111111; //pin A0-5 designated output
}

void loop() {
x = digitalRead(inpin); //read the input pin
if (inpin = HIGH) PORTB=B11111111; // if digital input is high, all Bport high
if (inpin = HIGH) PORTC=B11111111; // if digital input is high, all Cport is high
if (inpin != HIGH) PORTB=B00000000; // if digital input is low, all Bport is low
if (inpin != HIGH) PORTC=B00000000; // if digital input is low, all Cport is low

}

```

At the moment it seems the board it reading the input but is not relaying the outputs correctly with the PORTB continuously off and PORTC continuously on. Any help would be great!

# Answer
You have some coding errors. You likely meant to write something like:

```
void loop() {
  x = digitalRead(inpin); //read the input pin
  if (x == HIGH) PORTB=B11111111; // if digital input is high, all Bport high
  if (x == HIGH) PORTC=B11111111; // if digital input is high, all Cport is high
  if (x != HIGH) PORTB=B00000000; // if digital input is low, all Bport is low
  if (x != HIGH) PORTC=B00000000; // if digital input is low, all Cport is low
}

```

Which could be simplified to:

```
void loop() {
if (digitalRead(inpin) == HIGH)
{
  PORTB=B11111111; // if digital input is high, all Bport high
  PORTC=B11111111; // if digital input is high, all Cport is high
}
else
{
  PORTB=B00000000; // if digital input is low, all Bport is low
  PORTC=B00000000; // if digital input is low, all Cport is low
}
}

```
> 2 votes

# Answer
If you are doing this sort of low-level port manipulation, I suggest you ditch the Arduino core and go the avr-libc way:

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

int main(void)
{
    DDRB = 0xff;  // all port B as output
    DDRC = 0xff;  // all port C as output
    DDRD = 0;     // all port D as input
    for (;;) {
        if (bit_is_set(PIND, PD2)) {  // if PD2 reads HIGH
            PORTB = 0xff;  // all port B goes HIGH
            PORTC = 0xff;  // same for port C
        } else {
            PORTB = 0;     // all port B gos LOW
            PORTC = 0;     // same for port C
        }
    }
}

```

This compiles to very efficient code that takes at most 7 CPU cycles per loop iteration. In contrast, a call to `digitalRead()` can take hundreds of cycles, greatly increasing the program latency.

Obviously a buffer would still be way better in terms of latency, as pointed out by ratchet freak in a comment.
> 0 votes

---
Tags: led, array
---


# Question
Title: Varible Ramp up speed for motors controlled by joytstick
I trying to create a piece of code which will ramp up the motors speed to a changing value controlled by a joystick. For example joystick requests 120 speed to motors so instead of going 0 to 120 it goes 0, 10, 20 …. 120. But the maximum value will constantly change between 0-130 so it needs to ramp up each time. This is a snippet of my code to run the motors in the forwards direction.

```
{
  motorControl = analogRead(joystick);
  motorControl = motorControl / 4;
  if(motorControl > 129)

{

    digitalWrite(pwm2, 0);
    digitalWrite(pwm3, 0);
    speedI = (motorControl - 130);
    speedFadeI =
    Serial.println(speedFadeI-130);
    analogWrite(pwm1, (speedFadeI - 130));
    analogWrite(pwm4, (speedFadeI - 130));

```

thank you for anyone who has a idea

# Answer
I assume from the `0, 10, 20 …. 120` series, that you want to have a linear ramp to the desired speed. This can be done really easily, if your requirements are not to high.

First we define the interval, in which we want to update the speed, and a constant acceleration, that you can choose. The current speed will be saved in a global variable.

```
#define INTERVAL        100
#define ACCELERATION    51
int current_speed = 0;

```

I chose an interval of 100ms and the acceleration value, so that it will ramp from 0 to 255 (full speed) in 5s (which results in 51 PWM values per second). Now, in the `void loop()` function, we use an if-statement with the `millis()` function to trigger an speed update at the regular interval. For this to work, we need a (here global) variable, that holds a timestamp. (If you don't know this technique, you can see it in the `BlinkWithoutDelay` example, that comes with the Arduino IDE, and there are many tutorials about this on the web)

Inside the if-statement, we write a second if-statement. It checks, if the current speed is above or below the set point, that comes from the joystick. If it's above, we will substract one speed step (calculated by acceration and interval and divided by 1000, because we used milliseconds and not seconds for the interval), if it's below we will add one speed step.

```
unsigned long timestamp = 0;

void loop(){
    int setpoint = analogRead(joystick)/4;
    if(millis() - timestamp > INTERVAL){
        if(current_speed > setpoint){
            current_speed -= ACCELERATION*INTERVAL/1000;
        } else {
            current_speed += ACCELERATION*INTERVAL/1000;
        }
        if(current_speed > 255) current_speed = 255;
        else if(current_speed < 0) current_speed = 0;
        analogWrite(pwm1, current_speed);
        timestamp += INTERVAL;
    }

```

I also added if-statements to cap the current speed between 0 and 255. Otherwise the value would overflow, when written to the corresponding 8-bit timer register by the `analogWrite()` function.

Of course, this method also has drawbacks. You will have to find a good value combination of `ACCELERATION` and `INTERVAL`, because when the current speed reaches the setpoint, it will oscillate around this value. The best way is to set the `ACCELERATION`, that you need, and choose a good interval based on that.

There are other ways to program this, but I like this way for being really simple.
> 0 votes

---
Tags: arduino-mega, motor, joystick
---


# Question
Title: Serial.parseInt() takes longer time than desired
**My whole code for master. Please head to void read() where I've used parseInt()**

```
#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>

RF24 radio(7, 8); //Set up nRF24L01 on CE pin and CSN pin respectively

const uint64_t pipe = 0x0ABCDEF; //Address for communication between master and slave
uint16_t data[7];
const uint16_t buffer_size = sizeof(data); //Size of the payload for the RF
int i, flag;
int tx_counter = 0;

void read();
void setup() {

  Serial.begin(115200);

  radio.begin();
  radio.setChannel(2);
  radio.setDataRate(RF24_1MBPS);
  radio.setPALevel(RF24_PA_MIN);
  //radio.powerUp();
  radio.openWritingPipe(pipe);
  //radio.setPayloadSize(7);
  radio.stopListening();

  //Default values range from 100 to 700
  for (i = 0; i < 7; i++) {
    data[i] = 100 + (100 * i);
  }
  flag = 0;
  Serial.println("Enter 7 values");
}

void loop() {

  read();

  if (flag) {
    bool tx_ok = radio.write(data, buffer_size);
    tx_counter++;
    Serial.print("Transmission count:\t");
    Serial.println(tx_counter);
    print();
    if (tx_ok) {
      Serial.println("Transmitted Successfully");
      Serial.println("\nEnter Next set of 7 numbers");
    }
    else Serial.println("Transmission failed");

  }
}

void print() {
  for (i = 0; i < 7; i++) {
    Serial.println(data[i]);
  }
  flag = 0;
}

void read() {
  while (Serial.available()) {
    for (i = 0; i < 7; i++) {
      data[i] = Serial.parseInt();
    }
    flag = 1;
  }
}

```

My problem is that Serial.parseInt() takes some time. The code prints out the values to the serial monitor after sometime. I have timed it and it appears to be around 7 seconds. The arduino page on the function says default timeout is 1 sec. So I think 7 elements in the array takes 1 sec each. If I use `Serial.setTimeout(2000)`, the same thing takes 14 seconds.

This has got to have a simpler way. I want it to behave like when we use `Serial.read`. Please help me on this.

# Answer
> 0 votes
this is what you want:

```
void read() {
  for (i = 0; i < 7; i++) {
    while (!Serial.available()); // wait forever for some input
    data[i] = Serial.parseInt();
  }
  flag = 1;
}

```

---
Tags: arduino-uno, serial, communication, nrf24l01+
---


# Question
Title: Serial communication stops when powered with batteries?
Circuit explanation-

1. Arduino Uno connected to multiple sensors and to 16 x 2 LCD.
2. Uno's TX pin to ESP-01 RX pin.
3. Uno has been programmed to read values from sensors and display them on LCD along with printing them on Serial Monitor.
4. ESP-01 has been programmed to receive values from Serial Monitor and transmit it to ADAFRUIT MQTT server.

Problem - However when i am using USB to power the Uno it is successfully displaying data on LCD as well as to Serial Monitor and values are succesfully being send on the MQTT server after being read from Uno's serial. **But when Uno is battery powered, serial communication stops.**

I have tried adding 2 decoupling capacitors of 100uF to 12V battery supply. Battery are rechargeable cells.

What could be the issue?

# Answer
> 1 votes
I will put the solution from the comments into an answer.

All devices, that should interact through electrical wires with each other, must have a common ground. Ground is the point, from which the voltage is measured, and the devices need a reference, that is not only valid for themselves, but also valid for the communication partner.

You can think of the following analogy: Image that you and a friend have each one ball, that you are throwing into the sky (a positive height/voltage) and catching it again (zero height/voltage --\> ground). While you stand on the parking lot, your friend is standing on a high building. As long as you both only play this with yourself, it is easy for you to throw and catch the ball, because you can easily measure the height of the ball and it will always behave the same. But know imagine, that you want to play together. The height/voltage, that your ball reaches is still positive for you. But from the perspective of your friend it will look, like a large negative height/voltage. How should your friend interpet that and how should he now play with you?

---

In some electrical circumstances you don't want to connect the grounds of two devices together (maybe because of noise on the ground line). Then you have to achieve galvanic isolation, so no electrical connection between those two. An optocoupler is a device, that can achieve this. Basically it's just an LED and a phototransistor in one casing. From one device you power the LED. Due to the LEDs light, the phototransistor (which is connected to the other device) will become conductive. In combination with a pullup/pulldown resistor on the phototransistor you can have communication without common grounds.

---
Tags: arduino-uno, serial, esp8266, battery, capacitors
---