# Question
Title: Passing a time_t array as a function parameter
I'm trying to log reconnections and disconnections of a network. For that I've created 2 `time_t` arrays to store such occurances:

```
const int logSize = 10;
time_t conLog[logSize];
time_t disconLog[logSize];

```

Now, down the road, I have some manipulation and time calculation to do, and for that I wish to pass those log as a variable.

For example - zeroing its values:

```
void initLog(time_t log[], time_t init_val = 0)
{
        int sizeLog = sizeof(log) / sizeof(log[0]);
        Serial.print("size: ");
        Serial.println(sizeLog);
        for (int i = 0; i < sizeLog; i++)
        {
                log[i] = init_val;
        }
}

```

in order using it in a simple way : `initLog(conLog);` But unfortunately this is wrong.

I've tried to replace `time_t log[]` with `time_t &log` \- but still no luck.

What do I do wrong ?

# Answer
When you pass an array to a function it "collapses" the array into just a pointer. All the receiving function knows is the type of the contents of the array (`time_t`) and where it starts in memory - it knows nothing about the size of the array.

The `sizeof()` call just gives you the size of that pointer, not the size of the memory it points to.

`sizeof()` is not actually a function, it's a compile-time construct. It can't know anything about runtime values, only what is there at compile time.

Instead you must pass the length of the array with the array as a separate parameter, which can only be calculated in the same scope as where the array is defined, and then only by using the original name of the array. It is typical to create a macro to do this for you at the time you make the array:

```
time_t conLog[logSize];
#define CONLOG_SIZE (sizeof(conLog) / sizeof(conLog[0]))

```

Then pass that to your function:

```
initLog(conLog, CONLOG_SIZE);

```

Alternatively, since you already have the size in a constant in this case, you could just use that:

```
initLog(conLog, logSize);

```
> 2 votes

---
Tags: array, functions
---


# Question
Title: Why should a pin be set as an input if it can read input when set as output?
I recently created a circuit to read the value from two sets of buttons using only two analog pins. It involves setting one pin `HIGH` and reading the input on the other pin and then swapping. With both pins set to `OUTPUT` I can still read in values with `analogRead()` without having to keep switching pin modes.

My question is why is that the case? What is the point of setting a pin to `INPUT` if `OUTPUT` can still read in values? Are there any disadvantages of doing so?

# Answer
The reason for this is because `analogRead()` has absolutely nothing to do with what mode the pin is in. That mode only has any meaning in the scope of *digital* operations - i.e., when using `digitalRead()` and `digitalWrite()`. When using `analogRead()` the Arduino code switches the pin into analog mode first and then reads from it.
> 1 votes

# Answer
> My question is why is that the case? What is the point of setting a pin to INPUT if OUTPUT can still read in values? Are there any disadvantages of doing so?

If you do a `digitalRead` you can read the current latched state of an **output** pin (it doesn't change it to input). In other words, you read what was last written to it.

If you do a `digitalWrite` of HIGH to an **input** pin it sets the internal pull-up. If you write LOW it disables the internal pull-up. If it switched it to output for you, you wouldn't be able to enable or disable the pull-up. (Note: this applies to older versions of the IDE, newer ones have a pinMode setting of INPUT\_PULLUP).

> What is the point of setting a pin to INPUT if OUTPUT can still read in values?

That certainly won't work with `digitalRead` because you are writing a value to the pin in OUTPUT mode, so you will merely read back what you are writing. In other words, you have activated the driver transistors, which will override whatever value you are trying to read.
> 1 votes

# Answer
Because I/O pins can be used for either digital input or digital output and can be switched to perform in a given direction. Some of the pins also have an analog capability, either A-to-D conversion (input) or PWM (kind of a psuedo-analog output) but only in one direction permanently assigned by the hardware and therefore not switchable from one to the other.
> 0 votes

# Answer
It is good practice to define them, especially if you program something other then an arduino. For example a port pin on the PCF8574 (Peripheral device) is written as a 1 so you can read it, it has a small internal pull up. If you pull it low in this condition you will read a zero. If you write a zero you will always read a zero. Driving it to a 1 when set to zero can destroy the part. This configuration is also used on microcontrollers. There are hundreds of different port configurations and programming options, it is best to read the data and understand it first otherwise you may be purchasing another.
> 0 votes

---
Tags: pins, input
---


# Question
Title: If I use a biasing circuit for a signal going into an analog input pin, will it affect the ADC operation?
If I have a single 100Hz AC signal biased by two 1 M-ohm resistors (as per schematic below), and then output to an Arduino UNO analog input pin, with the UNO sampling at around 1 kHz using delays, would there be any issues with the ADC result?

(*Source of schematic: http://tinyurl.com/ycprqsdx*)

From the Atmega328P's spec sheet (the UNO's microprocessor) it recommends an output impedance of 10 k-ohms or less, as shown below. If I used the pair of 1 M-ohm resistors as a biasing circuit and then deliberately slow down the sampling with delays (i.e.: in loop, do analogRead, then delay, then do analogRead, etc.), would it still be okay?

# Answer
It will give bad results. You're not slowing down the sampling, you're taking samples at a longer interval - a very different thing.

The Arduino uses a *Successive Approximation* ADC. That uses a clock to control the output of a DAC and compare that voltage with the incoming voltage stored in the S&H capacitor.

In order for the S&H capacitor to get charged to the correct level it has to be connected to the GPIO pin long enough. Since there is only one ADC and 6 analog input pins, it goes through a MUX first.

The delay that needs increasing is the delay between the pin being connected to the capacitor and the capacitor being connected to the ADC. This is called the *acquisition time*.

The `analogRead()` function does these basic operations in sequence:

1. Connect the SHC to the GPIO pin through the mux.
2. Wait
3. Disconnect the SHC from the GPIO and connect it to the ADC
4. Clock each bit from the comparator to the result registers.

Putting a delay between each analogRead would just delay the connecting of the SHC to the GPIO pin, not increase the time it's connected to the GPIO pin.

You would have to manipulate the ADC registers to do your own sample timing. Or, just reduce your output impedance.
> 0 votes

# Answer
Adding capacitance to the input will help compensate for the high impedance but it also forms a low pass filter. For a 16 MHz Arduino the ADC clock is set to 16 MHz/128 = 125 KHz. Each conversion in AVR takes 13 ADC clocks so 125 KHz /13 = 9615 Hz. That is the maximum possible sampling rate, but the actual sampling rate in your application depends on the interval between successive conversions calls.
> 0 votes

---
Tags: arduino-uno, analogread, adc, input, analog-sampling
---


# Question
Title: Does lowering arduino analog reference increase precision in measuring low voltage?
The definition for Analog Reference is as follows: The reference voltage used for analog input (i.e. the value used as the top of the input range).

By default you have analog reference of 5V. So the precision of analogRead is 5 / 1023 = 0.0048875.

Now what happens if I lower the analog reference to let's say 1V. Does that mean that the precision now is 1 / 1023 (and the arduino can't measure voltages higher than 1V) or it is the same precision as before with the only difference being the fact that the arduino can't measure voltages higher than 1V anymore?

# Answer
> 2 votes
The former, i.e precision would now be 1/1023 but the accuracy of the AD converter is 4 / 1024 or 1 part in 256 i.e. 0.25%.

Also be aware that the internal reference voltages themselves are not very accurate :

DEFAULT: depends on your computer power supply USB2 Vbus = 4.4V - 5.25V, Vint 1 = 1.1V actually 1.0 -- 1.2V, Vint 2 = 2.56V actually 2.4 -- 2.8V

# Answer
> 0 votes
The A/D simply gives a binary value between 0 and 1023. That value is evenly divided between reference and ground. Since it is a successive approximation register that starts counting at zero and counts up in consistent steps until the reference voltage is reached, that count is saved and presented as the reading. If your input voltage is in that range you will get a reading on the number of steps from zero where it matched (0 to 1023). If measuring higher voltages you simply use a resistor divider and multiply the reading by that ration.

---
Tags: arduino-uno, analogread
---


title: Analog Reference and Power Voltage

text:
# Question
Title: Analog Reference and Power Voltage
On the Arduino website it states that the analog pins read voltages from 0 to 5 volts (default) and return a value from 0 to 1023. One can also set the range with analogReference(). However, this is probably assuming the Arduino is running at 5 volts. If one powers the board with, say 4 volts, will the analog reference still be 5 volts default, or changed to the input voltage of 4 volts?

# Answer
> 4 votes
Your suspicions are correct. Calling `analogReference()` with a value of `DEFAULT` sets the ADC reference to the voltage at AVCC which at least on the Uno R3 is tied directly to VCC and hence has the same voltage as whatever you're supplying there.

# Answer
> 0 votes
There is code published that shows how to read the internal voltage, I use that to correct my A/D readings. It is not perfect but close. You can of course select a lower reference voltage by changing the appropriate registers and use a different reference. This is much safer then supplying an external reference.

---
Tags: analogread
---


# Question
Title: Do I need to worry about voltage, coming from ground, and effecting an analog input?
I am building a project that includes an analog Input and several digital Inputs and Outputs. All of them connect to ground in some way. Do I need to worry about voltage, coming from the digital outputs, going to ground, and effecting readings on the analog input? If so, how do I deal with this?

# Answer
The arduino has build in pull up resistors, it is not a residue voltage coming from ground more than a "not 100% 0 volt" resistor.

Even though there is built in pull-up resistors one can add additional resistance to the arduino to make sure it will not show a false positive.

From what i have learned, you cannot experience voltage comming from ground (if everything is properly wired), if you want to make sure. Place a diod in the direction of the power flow, to prevent this.
> 1 votes

# Answer
In this case I do not believe ground bounce will be a problem. I normally only encounter it on high speed PCB designs. You will get noise from the power supply(s). Any impedance induced between the ground of analog input (circuit board ground) and the sensor will give you problems. Be sure all grounds are low impedance in nature. Since you are designing the project consider and I assume a PCB, filtering the Aref pin supply with a small cap and a 100 ohm resistor. A low pass filter on all inputs will help, a small cap from the input pin to ground and feed it via a resistor. Good capacitors are very important.
> 0 votes

---
Tags: analogread
---


# Question
Title: ESP32: How to run two independent PID controllers, one per core?
I want to control 2 independent processes with 2 PID controllers. Is it possible to run each controller on a separate core? I'm using this PID library. According to its documentation, the `PID::Compute()` function should be called once every `loop()`. How can this be achieved when using RTOS tasks (for multi core execution)?

# Answer
Sure. The existing Arduino setup and loop are just executed in their own task:

```
void loopTask(void *pvParameters)
{
    setup();
    for(;;) {
        if(loopTaskWDTEnabled){
            esp_task_wdt_reset();
        }
        loop();
    }
}

extern "C" void app_main()
{
    loopTaskWDTEnabled = false;
    initArduino();
    xTaskCreateUniversal(loopTask, "loopTask", 8192, NULL, 1, &loopTaskHandle, CONFIG_ARDUINO_RUNNING_CORE);
}

```

So there's no reason not to replicate that to give yourself an entire new setup and loop, or just a single function that does it all if you prefer.

```
TaskHandle_t secondPidTaskHandle;

void secondPidLoop() {
    // setup code here
    for (;;) {
        // PID loop code here
    }
}

void setup() {
    xTaskCreateUniversal(secondPidLoop, "secondPidLoop", 8192, NULL, 1, &secondPidTaskHandle, 0);
}

void loop() {
    // First PID code
}

```

The last parameter to `xTaskCreateUniversal()` is the core to execute on. The default setup/loop runs on core 1:

```
#define CONFIG_ARDUINO_RUNNING_CORE 1

```

So just use `0` and it'll run it on core 0.
> 0 votes

# Answer
esp32\_technical\_reference\_manual\_en.pdf

Page 620

As mentioned before, only an elevated process with PID of 0/1 can initiate a process switch. The new process may have any PID from 0 ~ 7 after the process switch. The key for successful proactive process switching is that Espressif Systems 620 Submit Documentation Feedback ESP32 Technical Reference Manual V4.3 29. PID Controller when the last command of the current process switches to the first command of the new process, PID should switch from 0/1 to that of the new process. The software procedure for proactive process switching is as follows:

1. Mask all the interrupts except NMI by using software.
2. Set register PIDCTRL\_NMI\_MASK\_ENABLE\_REG to 1 to generate a CPU NMI Interrupt Mask signal.
3. Configure registers PIDCTRL\_PID\_DELAY\_REG and PIDCTRL\_NMI\_DELAY\_REG.
4. Configure register PIDCTRL\_PID\_NEW\_REG.
5. Configure register PIDCTRL\_LEVEL\_REG and PIDCTRL\_FROM\_n\_REG.
6. Set register PIDCTRL\_PID\_CONFIRM\_REG and register PIDCTRL\_NMI\_MASK\_DISABLE\_REG to 1.
7. Revoke the masking of all interrupts but NMI.
8. Switch to the new process and fetch instruction. Though we can deal with interrupt nesting, an elevated process should not be interrupted during the process switching, and therefore the interrupts have been masked in step 1 and step 2. In step 3, the configured values of registers PIDCTRL\_PID\_DELAY\_REG and PIDCTRL\_NMI\_DELAY\_REG will affect step 6. In step 4, the configured value of register PIDCTRL\_PID\_NEW\_REG will be the new PID after step 6. If the system is currently in a nested interrupt and needs to revert to the previous interrupt, register PIDCTRL\_LEVEL\_REG must be restored based on the information recorded in register PIDCTRL\_FROM\_n\_REG in step 5. In step 6, after the values of register PIDCTRL\_PID\_CONFIRM\_REG and register PIDCTRL\_NMI\_MASK\_DISABLE\_REG are set to 1, PID Controller will not immediately switch PID to the value of register PIDCTRL\_PID\_NEW\_REG, nor disable CPU NMI Interrupt Mask signal at once. Instead, PID Controller performs each task after a different number of clock cycles. The numbers of clock cycles are the values specified in register PIDCTRL\_PID\_DELAY\_REG and PIDCTRL\_NMI\_DELAY\_REG respectively. In step 7, other tasks can be implemented as well. To do this, the cost of those tasks should be included when configuring registers PIDCTRL\_PID\_DELAY\_REG and PIDCTRL\_NMI\_DELAY\_REG in step 3. Espressif Systems 621 Submit Documentation
> 1 votes

---
Tags: esp32, pid, threads
---


# Question
Title: Nodemcu is connected to 5v relay with logic converter but still not working
I am using a bi-directional 3.3-5V logic converter to control 5V relay with 3.3V D5 pin of nodemcu. link of logic converter is here

However, I expected to control the relay but it didn't work. I don't think there is a problem with electrical connection or code since that is simple.

3.3V sides of nodemcu is connected to LV and 5V side of Relay is connected to HV.

Code:-

```
void setup() {
  // put your setup code here, to run once:
pinMode(D5, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
digitalWrite(D5, HIGH);
delay(2000);
digitalWrite(D5, LOW);
delay(2000);
}

```

My Observations:- 1) When relay is removed, multimeter shows 3.3V at the LV & HV side. (so logic converter is not working i guess) 2) When relay is connected, multimeter shows 2.5V on both sides.

Everything is powered from nodemcu pins. Does it means that i have to supply extenal power or something wrong with logic converter?\[!\[enter image description here\]\[2\]\]\[2\]

What do you guys think?

PS - I soldered the pins another way around on logic converter. Does it change anything?

circuit image, nodemcu is powered by the laptop USB

# Answer
> 2 votes
You must supply a steady, regulated voltage to both 3.3v and 5v pins at all time (see Voltage Inputs on https://learn.sparkfun.com/tutorials/bi-directional-logic-level-converter-hookup-guide/all).

Logic level controller does NOT convert 3.3v to 5v for powering the relay, it just let you turn 3.3v signal to 5v so a relay can get activated. Relay's positive pin still needs to be supplied with a 5v from a PSU or other sources.

# Answer
> 1 votes
To make that work you'd need to connect the HV connection to the Vin of the NodeMCU (as well as to the relay board) which should be the 5 V coming form the USB port. You'd also need to connect the GND on the HV side to the GND of the NodeMCU.

# Answer
> 0 votes
The converter and/or the nodemcu can't provide enough current to drive the relay. So you should get a 5V psu. For further details we need more information about the parts you use.

---
Tags: nodemcu, electronics, electricity
---


title: BJT - BC547 not working with LED strip

text:
# Question
Title: BJT - BC547 not working with LED strip
I'm connecting an LED strip that takes 12V input to an `Arduino Uno R3`'s `5V` VCC using a `B547` transistor.
Here's my circuit:

```
Base -> 1K ohm resistor -> DO13
Collector -> -ve of LED strip
Emitter -> GND
VCC 5V -> +ve of LED strip

```

Nothing happens when I try to turn on the LED strip. However if I remove the 1K resistor and turn on the LED, Arduino's built in LED gets dimmer but the LED strip does not turn on.
What am I doing wrong?
TIA!

# Answer
> 2 votes
Ok. First off, if you have a 12V LED strip then you have to power it from 12V. Powering the Arduino from 12V and then powering the LED strip from the 5V pin of the Arduino is *not* powering the LED strip from 12V, it's powering the Arduino from 12V and the LED strip from 5V.

The LED strip's anode (+) must be connected to the + of the 12V supply or, if it's only a very short LED strip then you can use VIN on the Arduino.

LED strips typically have a number of LEDs (eg 3) in series with a resistor to make one "segment", and many "segments" in parallel. This gives a total forward voltage of typically 9V or more - so you must provide *at least* that to get the LEDs to light.

Secondly the BC547 is not a good transistor to use for switching an LED strip. It has a maximum continuous collector current of 100mA. That means that you can only have a maximum of 100mA going through your LED strip before the transistor blows.

For reference, 100mA is the equivalent of 5 "normal" (5mm, of the kind you'd use in a breadboard) LEDs at full current and brightness. A typical LED strip (depending on length) can use many hundreds or thousands of mA.

Really you should be using an N-channel MOSFET that is rated for *at least* as much current as your LED strip requires to run. For safety, and to reduce heat dissipation, you ideally want it to be many times more powerful than the LED strip needs.

A common choice is the IRF530, which is rated at 10A with a switching voltage (the "threshold" voltage) that is low enough for a 5V Arduino to control (there are more suitable ones, but these seem to be the "go-to" component for many Arduino users - they're adequate for most uses).

simulate this circuit – Schematic created using CircuitLab

---
Tags: led, voltage, transistor
---


# Question
Title: I am getting an error while trying to set up the U8g2 library
I am just trying to set up the U8g2 library to use an OLED. I read through the documentation and tried copying and pasting the code block example for the constructor, but switched out their information for my OLED's information. After trying to verify, the IDE returned this error: exit status 1 expected ')' before ',' token

<pre><code>#include <SPI.h>
#include <U8g2lib.h>

//Constructor
U8G2_SSD1306_128X64_NONAME_1_SW_I2C(U8G2_R0,A5,A4);```

I saw a similar post about this problem from four years ago, but the only suggestion on there was to capitalize the "A" in the analog pins. I tried this and nothing changed. Any help would be much appreciated!
</code></pre>

# Answer
> 1 votes
I figured out what I was doing wrong. I was copying the name from the Constructor Reference and immediately inputting the arguments in parentheses. I needed to put u8g2 after the constructor name and then put the arguments. Thanks!

The corrected code is as follows:

```
#include <Arduino.h>
#include <SPI.h>
#include <U8g2lib.h>

//Constructor
U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0,A5,A4);

```

---
Tags: compilation-errors, oled, u8glib, ssd1306
---


title: 8266 analogRead(A0) always 1024

text:
# Question
Title: 8266 analogRead(A0) always 1024
dear member. I have 4 ESP-12 averything OK but one chip behave weird. always return 1024 on analogRead(A0); once use ADC\_MODE(ADC\_VCC) and reflash using ADC\_MODE(ADC\_TOUT); and never back to normal, is my Chip Error..?

FM 4MB

ArduinoIDE 1.8.13

BR 115200

PS 80MHz

```
int iVal = 0;
void setup() {
  Serial.begin(115200);
  delay(999);
  pinMode(A0,INPUT) ;
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  iVal=analogRead(A0);
  Serial.println(iVal);

  if (iVal > 900) digitalWrite(LED_BUILTIN,HIGH);
  else   digitalWrite(LED_BUILTIN,LOW);
  delay(720);
}

```

# Answer
> 1 votes
First be sure your voltage on the analog input is less then 1V and greater then zero, that is the range for the input. If nothing connected no guarantee what you will get. Just guessing, no circuit or definition.

---
Tags: esp8266, adc
---


# Question
Title: How to turn the digital pin to analog pin?
I am using a 10 IR sensor array and they use analog pins. I am using a motor shield for the Uno. So I cannot use the Mega. I have only five analog pins I need 8. How can I do it?

# Answer
You can use an external A/D converter, there are a lot of varieties in a lot of price ranges for the Arduino. Check your favorite online source. That will require two of your existing analog pins for the I2C interface but you will gain back many more depending on your choice. If you choose to use SPI that will take 4 pins.
> 1 votes

---
Tags: arduino-uno, digital-analog-conversion
---


# Question
Title: how to ignore a sensor being tripped the first time and start recording millis on the 2nd time it is tripped
I am building a timing system that has a start, split and finish beams with this I am using a start gate that will drop when the race starts. when it drops it will trip the 1st sensor starting to count the millis which I am using to calculate the time. I am using IR sensors to that give me the 3 times based on the millis and then I do a calculation in excel that will give me the split and finish time.

Where I am running into issues is that after the person goes through the 3 timer sensors I have to close the start gate which trips the first sensor which messes up my times for the next person.

So I need to adjust my sketch so it takes this into consideration when it starts counting the millis. Basically I am thinking it needs a line of code to have the 1st sensor == LOW once and do nothing and then on the 2nd time that same sensor is == LOW it records the millis from that point.

Below is the sketch I am working on.

```
//timer
unsigned long start, reaction, push, elapsed;

void setup()
{
  Serial.begin(115200);
  pinMode(2, INPUT); // start switch
  pinMode(3, INPUT); // split sensor
  pinMode(4, INPUT); // finish sensor
}

void loop(){

if (digitalRead(2) == LOW)
  {

    start = millis();

  }

  if (digitalRead(3) == HIGH)
  {

    reaction = millis();
 //   delay(200); // for debounce

  }

     if (digitalRead(4)==HIGH)
      {

       push=millis();
       delay(500); // for debounce

    Serial.print(start);
    Serial.print(",");
    Serial.print(reaction);
    Serial.print(",");
    Serial.print(push);
    Serial.println();

  }

}

```

# Answer
> 1 votes
The start time will default to zero, so you could change it to:

```
if (digitalRead(2) == LOW && start == 0)
  {

    start = millis();

  }

```

---
Tags: arduino-uno, sensors, millis
---


title: Make the Arduino read data from the PC

text:
# Question
Title: Make the Arduino read data from the PC
I will be brief. There is as windows PC running a program. This program has live updating data on it. Without modifying the PC or adding any programs to the PC, is it possible to program an Arduino to read specific data from this program. In other words the Arduino would be connected to the PC via a USB port and it would need to actively read specific data from this program without having to modify the PC in any way, software or otherwise. I do have access to the PC and can learn almost anything I need to about the program during the development of this system, however in practice, I need the Arduino to simply be plugged into this PC and begin reading its data. Is this possible? I am not asking for a tutorial however if you could point me in the right direction that would be great. Thanks

# Answer
> 1 votes
As the comments already stated: No, not possible. For multiple reasons:

* USB is a master/slave protocol. The slave (here the Arduino) cannot do anything without the master. It can just expose it's data endpoints and hold data ready to read at these endpoints for the master or wait for data from the master on these endpoints. When the application on the PC is not programmed to speak over USB, you cannot get the data over USB.
* Even directly on the PC you cannot simply extract data from a different program. That would be a very huge security risk. Even more, when just initiated via an USB device. There are USB devices, which use certain behaviors of some OS's (like auto execution of specific types) to install a virus on the PC. But even then you cannot "just read" the data. It would be way more elaborate and not possible with a simple Arduino, thus off topic here. (And you might frown upon hacking your own PC this way)

From our point of view (means leaving the hacking off limits), I would aggree with Majenko in the comments. Using the visual output is the most viable and easy solution, though your results might vary.

For that you would need a camera pointing at the screen (check if you get a good image. It might be distorted due to slow refreshing...) and use a Raspberry Pi or similar to connect it. On the Pi you can then take pictures of the screen and use an OCR tool, which will read the text from the image. Then you need to extract and structure the relevant information. (Maybe it will be easier to create subimages in your program and let the OCR tool run over these to distiguish between the different data parts). Results will hardly depend on the quality of the image. If you can live with an additional program running the PC, you could instead make the images of the screen as screenshots, which will be way better quality. Though at that point you can also put the rest of the logic on the PC and just remove the Pi.

This way will still be hard to do for a beginner, but possible.

---
Tags: serial
---


# Question
Title: Why do we declare constant lat and lon value
static const double LONDON\_LAT = 51.508131, LONDON\_LON = -0.128002;

What does this mean?

https://github.com/mikalhart/TinyGPSPlus/blob/master/examples/FullExample/FullExample.ino

The above link contains the full example program of that line.

This line is from tinygps++ library for extracting the coordinates and displaying in a table format. I'm using arduino uno, GSM module and GPS module to extract the coordinates and transmit it as message. Can anyone explain what dies this constant value mean and why do we use this?

# Answer
Static variables are allocated storage only once in a program lifetime The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it and you can't change const variable's value and i guess you know double is a data type that can save floating point numbers that line declare two variables with names `LONDON_LAT` and `LONDON_LON` and both of them are in one line and because london's latitiude and longtitude doesn't change the `const` keyword is used

also i guess because those variables are constants you can use `#define` visit https://www.arduino.cc/reference/en/language/structure/further-syntax/define/
> 2 votes

# Answer
It's a good idea to declare variables the strictest possible way. So if you don't intend to change the value of LONDON\_LAT at runtime, declare it as **const**.

This allows the compiler to alert you if your code tries to modify it, and it often allows the compiler to optimize the code.
> 0 votes

---
Tags: arduino-uno, tinygps
---


title: Wave file will not play with Teensy 3.5

text:
# Question
Title: Wave file will not play with Teensy 3.5
I am attempting to play a wav file from an SD card using a Teensy 3.5. I am using this buzzer and I have the following code currently:

```
#include <Audio.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <SerialFlash.h>

// GUItool: begin automatically generated code
AudioPlaySdWav           playSdWav1;     //xy=557,157
AudioOutputPWM           pwm1;           //xy=889,184
AudioConnection          patchCord1(playSdWav1, 0, pwm1, 0);
AudioConnection          patchCord2(playSdWav1, 1, pwm1, 0);
// GUItool: end automatically generated code

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

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("Play");
  playSdWav1.play("sound.wav");
  delay(100);
  while (playSdWav1.isPlaying()) {
    delay (100);
  }
}

```

I don't know which pin is supposed to be outputting the PWM signal. I tried searching "patchCord1" to see what the parameters for it are, but was unsuccessful. The code was generated by The Audio System Design Tool.

As for the hardware configuration, I am attempting to wire the `I/O` pin to various PWM pins (to check for output) with no success. I have `GND` to Analog Ground and `VCC` to 3.3V (250 mA max). This is according to this diagram.

Which PIN is the Teensy supposed to output the pulses to?

Edit:

I can get the buzzer to work by using manual PWM (analogWrite), so I know that it functions.

# Answer
> 1 votes
The documentation implies you have to combine pins 3 and 4.

Here is a circuit diagram:

https://www.pjrc.com/teensy/gui/img/pwmdualcircuit.jpg

Source:

https://www.pjrc.com/teensy/gui/?info=AudioOutputPWM

---
Tags: sd-card, audio, teensy
---


title: Output voltage range between 0-5v

text:
# Question
Title: Output voltage range between 0-5v
I am using arduino Uno/Mega.

I am trying to output a range of 0-5v volts using PWM.

Is it possible to do it?

It’s would be nice to see some code or instructions, as far I have seen, they used external Module to get that voltage range, maybe I am wrong or I didn’t understand them well.

Thanks!

# Answer
Short answer: No.

Arduino Unos and Megas have PWM (Pulse Width Modulation) output, which rapidly turn the output on and off with a varying "duty cycle" (The ratio of on time to off time.) That is not the same thing as an analog output voltage.

If you have a constant load you can build a low pass filter that will smooth the output to a slightly dirty DC output based on the PWM output.

You're better off using an external DAC (Digital to Analog Converter.) You send that a digital value and it converts it to a clean, filtered analog output. Most modern DACs are fast enough to output complex waveforms like music.

## Edit:

The Arduino zero apparently has a built-in DAC with up to 10-bit resolution. you could use that to output a low current DC voltage. However the zero is a 3.3V device.
> 5 votes

# Answer
The Arduino is a digital device; each output pin is either HIGH (+5v) or LOW (0v = GND), not in between.

For certain types of devices (motors, LEDs) there is a technique you mentioned called PWM, pulse width modulation, which turns the output on and off rapidly. It's still just a square wave alternating between 0 and 5v but it's doing it really fast. So for an LED for example, your eye will make you think it's at half-brightness even though it is flashing on and off very quickly.

To do this you need to use a pin that has "analog" ability and use the "analogWrite" command.
> 1 votes

---
Tags: arduino-uno, pwm, voltage-level
---


# Question
Title: Noise in Analog Read Serial from an instrumentation amplifier(ina122p)
I am trying to read the values from a simple EMG circuit (with an INA122P) using the analogRead() and plotting in the plotter using an Arduino nano v3. I am powering the ina1222p from the 5v pin of the Arduino. But no matter what I do, the signal comes out very noisy most of the time(i can rarely make out the EMG). The bandpass filter is also not really helping. I am using regular solid core wire and alligator clips to connect to the electrodes.

Can someone please tell me what I am doing wrong? or tell me how to make a simple EMG circuit that uses the Arduino's analogRead().

I am also getting ac sine waves when my laptop is plugged to power, so I tried removing the power. The distinguishable sine wave wasn't really showing up, but it was still just as noisy...

**I am a beginner to both Arduinos and designing Analog circuits.**

I found this design from here: https://greenhecktech.wordpress.com/2016/09/19/improving-the-emg-amplifier/

# Answer
> 1 votes
"noisy most of the time" - good news: if it's not all the time, that's a sign it can be fixed.

"bandpass filter is also not really helping" - *INA122P circuit likely has something wrong. check any resistors involved.* Edit: if this was about U2.2, see below as that doesn't look like a band pass...

"regular solid core wire and alligator clips to connect to the electrodes" - basically 0 shielding with mini-rabbit ears at each end and a big loop area between the wires. Eventually you will want something better than gator clips. My main recommendation is that as far as wire goes, if you *form twisted pairs* they tend to be pretty darn good at rejecting noise at least for that part of the wire. You will want to twist a signal along with its reference (such as a +V and a ground).

Some explanation of the circuit:

U2.1 is creating a 2.5V source that it uses as the reference 'ground' for U1. Reason for this is to treat 0 as "-2.5" and 5 as "2.5" as op amp math is generally done on a +V, -V basis. (Personally, I prefer to use voltage regulators to make power buses instead of this. As a result, I give a stink eye to circuits that use the op amp method and claim something about reducing part count.)

U2.2 is a capacitor shy of an active band pass. It's a high pass filter that is helping preserve and even promote some of the high frequency noise you are picking up. So yes, you may wish to modify or even ditch it until you have high frequency noise under control.

If possible, you may also wish to look into operating at a higher voltage. This can help improve your signal to noise ratio. If your signal is essentially +/-2.5V, 250mV of noise would be 10:1, but if you can run at +/-5 V, that same 250mV noise contribution gets dwarfed 20:1.

---
Tags: sensors, analogread, analog-sampling, op-amp, analog
---


title: Saving a value with a click

text:
# Question
Title: Saving a value with a click
I have a rotary encoder and 2 buttons to a. Store the encoder value b. Reset the encoder value to 0. The reset buttons work fine the issue is with the set/store button. Where the value changes without pressing the button as well. Any help is appreciated.

```
int encoderPin1 = 2;
int encoderPin2 = 3;

volatile int lastEncoded = 0;
volatile double encoderValue = 0;
long lastencoderValue = 0;

int lastMSB = 0;
int lastLSB = 0;

// buttons
int resetPin = 43;
int settPin = 22;
int val = 0;
int val2 = 0;

//reset-set
double setValue = 0.0;
double resetValue = 0.0;

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

  pinMode(encoderPin1, INPUT);
  pinMode(encoderPin2, INPUT);

  digitalWrite(encoderPin1, HIGH);
  digitalWrite(encoderPin2, HIGH);

  attachInterrupt(0, updateEncoder, CHANGE);
  attachInterrupt(1, updateEncoder, CHANGE);

  //buttons
  pinMode(resetPin, INPUT);
  pinMode(settPin, INPUT);

  pinMode(LED_BUILTIN, OUTPUT);

}
void loop(){
  //Serial.println(encoderValue); //print
  delay(1000);

  //
val = digitalRead(settPin);
if (val == HIGH){
  set();
  digitalWrite(LED_BUILTIN, HIGH);
}

/*val2 = digitalRead(resetPin);
if (val2 == HIGH){
  //reset
  encoderValue = resetValue;
  Serial.println(encoderValue);
  Serial.print("reset");
  delay(100);
}*/

}

void set(){
  //set the value
  setValue = encoderValue;
  Serial.println(setValue);
  Serial.print("setValue");
  delay(100);
}

 void updateEncoder(){
  int MSB = digitalRead(encoderPin1);
  int LSB = digitalRead(encoderPin2);

  int encoded = (MSB << 1) |LSB;
  int sum = (lastEncoded << 2) | encoded;

  if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) encoderValue ++;
  if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) encoderValue --;

  lastEncoded = encoded;
  }

```

# Answer
thank you for your suggestion. The issue isn't with the code but was with the button. I changed the button and it worked fine. Thanks for the help!
> 1 votes

---
Tags: arduino-mega, button, rotary-encoder
---


title: ATTINY85 and POT

text:
# Question
Title: ATTINY85 and POT
I need to read a potentiometer value from an ATTINY85. I have big fat 10K POT but for this use case I need it to be very small so I used a salvaged 2.4K one, the kind that is soldered directly onto a PCB.

I am using tinkercad to prototype my project and I am facing a very weird problem. Everytime I read from the POT Pin, I get the value of 512 (using the debugger)

Here is a screenshot of my prototype:

The goal is to power the circuit and the lamp (does not matter what is there, consider it just a load) with a 9V battery, use a 5V regulator to power the ATTINY85 and use an NPN transistor to turn the lamp/load on or off.

For information, the whole regulator and transistor setup is tested and works like a charm.

Here is the code I wrote for the this case:

```
void setup()
{
  pinMode(PB0, INPUT);
}

int potValue = 0;

void loop()
{
  potValue = analogRead(PB0);
  delay(100);
}

```

Not real fancy right? Now no matter what use for the POT, and I tried 2.4K, 10K and up to 100K, the value read by the ATTINY is always 512.

Do you see something wrong in this setup? Could it be a bug in tinkercad? (I'd be surprised though)

I could try and share this circuit within tinkercad if someone would be willing to have a look...

EDIT: I just tried with PB2 as suggested but not the value is always 58:

# Answer
> 3 votes
Port PB0 is not an ADC (analog input) pin on the ATTiny85.

Available pins of the ATTiny85 (from the Atmel ATtiny 25, 45, 85 datasheet):

Choose PB2, PB3, PB4 or PB5 if you need an analog input.

Additional information: When built in TinkerCAD, using PB2 as an analog input does not seem to work correctly and produces a fixed value. Using PB3 did work correctly however. This might be a bug in TinkerCAD.

---
Tags: potentiometer, attiny85
---


title: ESP32 softAP SSID not const

text:
# Question
Title: ESP32 softAP SSID not const
I would like to be able to set the wifi SSID in the setup(), so I can customize it based on the MAC address or something similar. (avoiding to ESP's with the same code having the same SSID). However since it requires a const it does not seem to be possible, or am I missing something?

I'm using platformIO if that matters...

# Answer
A `const` parameter to a function doesn't define what can be passed. It is, instead, a "promise" by the function that it will not modify the data you pass it.

In C when you pass a "string" (which is actually an array of characters) to a function you don't actually pass the string (as in the content). You really just pass a pointer to the location in memory where the string is stored.

It is perfectly possible for a function to then make modifications to that passed "string", which will be modifying the original data in memory. That is not really desirable in many situations.

So by flagging the parameter as `const` you tell the compiler "From this moment onwards the data pointed to by this variable must not be changed". All attempts to write to the memory using that variable will be blocked by the compiler.

There's no actual difference between, say, a `char *` and a `const char *` other than how the compiler treats attempts to write to them.

When you pass a `char *` to a function that is expecting a `const char *` the pointer is "upgraded" to a constant so that no attempts to change the data will be allowed.

The converse is not allowed though - you can't (or shouldn't) try and convert a `const char *` to a `char *` as on some systems ("Princeton" architecture systems with a single monolithic memory address space) the pointer could be pointing to data stored in flash, and an attempt to write to that will obviously fail.

The function you are calling to set the SSID is merely promising that it won't attempt to change the data you pass it. It doesn't matter if it's a constant or not - both will be treated as a constant and not be changed.
> 1 votes

# Answer
The library WifiManager might work for you, it’s got a captive portal to configure your wifi connection on the fly. It’s got quite some configuration options to shape it to your will if I am not mistaken, I hope it serves you well.
> 0 votes

---
Tags: wifi, esp32, espressif, esp, softap
---


# Question
Title: Why should I connect the l289n motor driver wires to specific arduino pins only?
So, I am new with arduino and am to build a robot using motors, for that I have bought l298n H bridge motor driver. I have watched various site and videos ,to make sure not to make a mistake but, in every video and sites

I have found their connecting the motor direction controller to

IN1 -\> Arduino Pin 8 (digital) and IN2 -\> Arduino Pin 7 (digital)

Till then it was fine ... Now the fishy thing for me is

IN3 -\> Arduino Pin 5 (PWM) and IN4 -\> Arduino Pin 4 (Digital)

Why connect to a Digital and a PWM?

For E1 and E2 I am sure that the wires should be connected to the PWM (~) pins for arduino, to control speed of the motor..

But, Should not I be able to connect IN3 and IN4 both to rest of the digital pins 12, 13 or 2,4 Just Like IN1 and IN2 is connected to 7 and 8.

But the IN3 and IN4 is connected to a PWM and a Digital pin.

Conclusion,

So can I use all the unused non PWM digital pins to connect the motor direction control?

Thanks for your precious time..!

# Answer
> 2 votes
Pwm is just a digital out with extra fancy on off controls. You can use any digital out if you do not need those extra features.

To just signal a single H bridge (1 motor of your l289n) for forward, reverse, stop, one only needs two digital outs.

I recommend you get the hang of your h bridge first - signaling it on a bread board with vcc (usually 5v but can be 3.3) and ground rather than the arduino. Then once you understand the motor directions that result from your wiring, write the code accordingly. This tends to result in:

1. fewer fried arduinos
2. code with functions and signals named after their intent (rather than having to mix forward and reverse)

---
Tags: arduino-uno
---


# Question
Title: Ooops, no LSM303 detected ... Check your wiring!
**History**

I have an Adafruit 10DOF IMU Breakout which has been working on my `Mega` for some time. This morning my `program` did not run so I starting *troubleshooting*.

**Scenario**

I eventually plugged the IMU breakout into my `Uno` with the \*out-of-the-box accelerometer reader program from Adafruit. That's when I started seeing

`Ooops, no LSM303 detected ... Check your wiring!`

And upon close inspection have verified all wires are in the correct spot.

---

# Question

How do I troubleshoot this further? Also, I'm starting to think that my IMU may be fried. How can I test this?

---

*** AHRS out-of-the-box Program from Adafruit:**

```
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_LSM303_U.h>
#include <Adafruit_BMP085_U.h>
#include <Adafruit_L3GD20_U.h>
#include <Adafruit_10DOF.h>

/* Assign a unique ID to the sensors */
Adafruit_10DOF                dof   = Adafruit_10DOF();
Adafruit_LSM303_Accel_Unified accel = Adafruit_LSM303_Accel_Unified(30301);
Adafruit_LSM303_Mag_Unified   mag   = Adafruit_LSM303_Mag_Unified(30302);
Adafruit_BMP085_Unified       bmp   = Adafruit_BMP085_Unified(18001);

/* Update this with the correct SLP for accurate altitude measurements */
float seaLevelPressure = SENSORS_PRESSURE_SEALEVELHPA;

/**************************************************************************/
/*!
    @brief  Initialises all the sensors used by this example
*/
/**************************************************************************/
void initSensors()
{
  if(!accel.begin())
  {
    /* There was a problem detecting the LSM303 ... check your connections */
    Serial.println(F("Ooops, no LSM303 detected ... Check your wiring!"));
    while(1);
  }
  if(!mag.begin())
  {
    /* There was a problem detecting the LSM303 ... check your connections */
    Serial.println("Ooops, no LSM303 detected ... Check your wiring!");
    while(1);
  }
  if(!bmp.begin())
  {
    /* There was a problem detecting the BMP180 ... check your connections */
    Serial.println("Ooops, no BMP180 detected ... Check your wiring!");
    while(1);
  }
}

/**************************************************************************/
/*!

*/
/**************************************************************************/
void setup(void)
{
  Serial.begin(115200);
  Serial.println(F("Adafruit 10 DOF Pitch/Roll/Heading Example")); Serial.println("");

  /* Initialise the sensors */
  initSensors();
}

/**************************************************************************/
/*!
    @brief  Constantly check the roll/pitch/heading/altitude/temperature
*/
/**************************************************************************/
void loop(void)
{
  sensors_event_t accel_event;
  sensors_event_t mag_event;
  sensors_event_t bmp_event;
  sensors_vec_t   orientation;

  /* Read the accelerometer and magnetometer */
  accel.getEvent(&accel_event);
  mag.getEvent(&mag_event);

  /* Use the new fusionGetOrientation function to merge accel/mag data */
  if (dof.fusionGetOrientation(&accel_event, &mag_event, &orientation))
  {
    /* 'orientation' should have valid .roll and .pitch fields */
    Serial.print(F("Orientation: "));
    Serial.print(orientation.roll);
    Serial.print(F(" "));
    Serial.print(orientation.pitch);
    Serial.print(F(" "));
    Serial.print(orientation.heading);
    Serial.println(F(""));
  }

  /* Previous code removed handling accel and mag data separately */
  //  /* Calculate pitch and roll from the raw accelerometer data */
  //  Serial.print(F("Orientation: "));
  //  accel.getEvent(&accel_event);
  //  if (dof.accelGetOrientation(&accel_event, &orientation))
  //  {
  //    /* 'orientation' should have valid .roll and .pitch fields */
  //    Serial.print(orientation.roll);
  //    Serial.print(F(" "));
  //    Serial.print(orientation.pitch);
  //    Serial.print(F(" "));
  //  }
  //
  //  /* Calculate the heading using the magnetometer */
  //  mag.getEvent(&mag_event);
  //  if (dof.magGetOrientation(SENSOR_AXIS_Z, &mag_event, &orientation))
  //  {
  //    /* 'orientation' should have valid .heading data now */
  //    Serial.print(orientation.heading);
  //  }
  //  Serial.println(F(""));

  /* Calculate the altitude using the barometric pressure sensor */
  bmp.getEvent(&bmp_event);
  if (bmp_event.pressure)
  {
    /* Get ambient temperature in C */
    float temperature;
    bmp.getTemperature(&temperature);
    /* Convert atmospheric pressure, SLP and temp to altitude */
    Serial.print(F("Alt: "));
    Serial.print(bmp.pressureToAltitude(seaLevelPressure,
                                        bmp_event.pressure,
                                        temperature));
    Serial.println(F(""));
    /* Display the temperature */
    Serial.print(F("Temp: "));
    Serial.print(temperature);
    Serial.println(F(""));
  }

  delay(100);
}

```

-- EDIT --

I'm pretty sure the board is dead. The program stops at `accel.begin()`, `mag.begin()`, or `bmp.begin()`; I've tried each individually.

# Answer
> 1 votes
Check each of your conditional statement at

```
if(!accel.begin())
  {
    /* There was a problem detecting the LSM303 ... check your connections */
    Serial.println(F("Ooops, no LSM303 detected ... Check your wiring!"));
    while(1);
  }
  if(!mag.begin())
  {
    /* There was a problem detecting the LSM303 ... check your connections */
    Serial.println("Ooops, no LSM303 detected ... Check your wiring!");
    while(1);
  }
  if(!bmp.begin())
  {
    /* There was a problem detecting the BMP180 ... check your connections */
    Serial.println("Ooops, no BMP180 detected ... Check your wiring!");
    while(1);
  }

```

by commenting the others.

# Answer
> 1 votes
I had a similar issue. Turns out it was faulty wiring, probably due to a cheap breadboard (as a noob you would expect perfect connectivity from something like a breadboard! Turns out: not at all!)

Here's how I went about debugging it, using an i2c scanner to debug connectivity (find library + example here).

1. remove the `while(1)` loops that halt your program, so the program doesn't 'stop' on error
2. Use an 'error variable' e.g. `fail`. Initialize e.g. as `fail=0` at start of script so it's global. Add `fail=1` for every *oops case* in `initSensors()`
3. in `loop()`, check if `fail==0`, if yes, continue with outputting the 10DOF sensor values, if there is an error (`fail==1`) call `initSensors()` and the `i2cscanner()` so you get a debugging view of your connectivity. This would look like below, and will keep calling the debug function until you connected it properly.

Hope this was useful or at least interesting to you, good luck.

Screenshot of i2c scanner:

# Answer
> 0 votes
I this one of many Arduino invented terminology ? Normally function returns ZERO on success and -1 or positive number identifying the error.

```
if(!accel.begin())

```

{ /\* There was a problem detecting the LSM303 ... check your connections \*/ Serial.println(F("Ooops, no LSM303 detected ... Check your wiring!")); while(1); }

---
Tags: adafruit, accelerometer
---


# Question
Title: analogWrite never outputs a non-zero voltage
With a very simple connection of an LED (which can withstand 5V) to ground and to a pin on my Galileo gen2, I can never output a non-zero voltage from the pin via `analogWrite`, regardless of whether the pin is digital or analog (although PWM digital works)

The LED is in the correct bias and I'm calling `pinMode(pin, OUTPUT)` before attempting to call `analogWrite(pin, 255)` (or any 2nd parameter in-between), even though it's not even necessary.
The LED glows if I call `digitalWrite(pin, HIGH)` on both analog and digital pins, but does not glow at all for `analogWrite(pin, 255)` with the same configuration and pins, nor does it for any 2nd param in \[0, 255\]. This holds for whether the call is attempted in `loop()` or `setup()`.

The only possible way I can get the LED to receive any power from `analogWrite` is through a digital PWM pin, but I know the other digital pins can still produce square-waves with timers and the analog pins should certainly be able to use PWM.

(So far, I've been to scared of short-circuits to connect the analogWrite output straight into an analog input to read the voltage)

Is there something I don't understand about the underlying board, or am I experiencing some strange malfunction?

Thanks,
Tyson

# Answer
On most boards, the standard implementation of Arduino's `analogWrite()` will only ever produce PWM, and only on a specific set of (digital) pins. These are usually pins 3, 5, 6, 9, 10, and 11, although it's slightly different on some boards.

The only official board which has 'true' analog output is the Due (pins DAC0 and DAC1).

If you want any other behaviour (such as outputting PWM on non-standard pins), you'll either need to modify the Arduino implementation, or directly manipulate the microcontroller's special registers. Note though that modifying the chip's configuration could cause other standard Arduino functions not to work as expected.
> 1 votes

# Answer
I don't believe Galileo has a D/A converter, which is what it sounds like you're expecting. In the Arduino 'eco-system', analogWrite() sets a PWM duty cycle - that's kinda-sorta somewhat like an analog output, but not really. You could add external circuitry to low-pass filter the PWM and produce some sort of proportional DC but it might be a good trick get it clean enough for whatever you plan to put downstream.
> 0 votes

# Answer
I am not sure where you are getting your LEDs but the ones I purchase do not survive 5 volts. You need to put a resistor in series with then, something in the 220 to 510 ohm range. When you get some resistors test your LEDs you may have damaged them as well. A good indication of this if there color if obviously off and or dim. If the timers are set up correctly the digitalwrite will set the PWM value, somewhere from 8 to 16 bits depending on the Arduino and timer used. This PWM output will appear to control the brightness of the LED. It does this by simply turning it on and off at a speed the eyes cannot follow. the longer it is on the brighter it is. Hopefully this will help you get your arms around the circuit.
> 0 votes

---
Tags: led, pwm, analogwrite
---


# Question
Title: Direct 5V current based on analog signal
I would like to manage many LEDs from my Arduino - 12 or so - but I do not have the available digital pins to do this. Only one LED needs to be on at one time. Instead, I was hoping to control these with an analog pin. I was wondering if there is some sort of switch out there which can take an analog signal and, based on the value, direct a 5V current to a certain LED.

I realize that I could use a second Arduino for this, but I am trying to avoid that.

Thanks in advance for any help!

# Answer
> 1 votes
You can accomplish this digitally with a device called a *decoder*. For example, the 74154 takes 4 inputs and maps those to one of 16 outputs (depending on the binary coding of the inputs). From the data sheet:

> The 74HC154; 74HCT154 decoders accept four active HIGH binary address inputs and provide 16 mutually-exclusive active LOW outputs.

# Answer
> 3 votes
If you have 4 pins available, you could use charlieplexing to selectively light up 12 led.

Alternatively you could use some IC. You could use the one Greg suggested.

Or you could use a shift-register. This requires only 2 or 3 pins, an will enable you to light up any one or more leds at the same time. Most have 8 outputs, but you can connect one to the other (daisychain), so with 2 shift-registers you can individually turn on/off 16 leds. You can easily control these using arduino's `shiftOut` command.

You could also use a port-expander using I2C to talk to it. More complicated, and a bit more expansive. But also more powerful. It will require only 2 pins (A4, and A5).

# Answer
> 0 votes
You can use some of the analog pins to clock a shift register by defining them as a digital output. Also two of the analog pins are also defined as I2C depending on your code. You could use 2 PCF8574s or an PCF8575 expansion board and control it that way. They can be used as inputs and outputs any order you want. There are a lot of other chips you can use to do this. The reason I am suggesting this approach is later you will probably want to expand into other peripherals such as LCDs etc.

---
Tags: analogwrite
---


title: Making AC current with pin 11

text:
# Question
Title: Making AC current with pin 11
I'm trying to make AC current (50Hz) with an Arduino Uno. It seems to be not working (or wrong code).

```
int up;
int down;
int out = 11;
void setup() {
  pinMode(out, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  for (up = 0; up <= 255; up++) {
    analogWrite(out, up);
    delay(1);
  }
  for (down = 255; down >= 0; down--) {
    analogWrite(out, down);
    delay(1);
  }
}

```

**Update:**

1. Now the code above is giving output voltage of 0-5V (getting increased from 0 to 5 and then decreased) not giving a negative cycle (-5V).
2. After setting the minimum delay of 1, the output wave is still half wave rectifier with frequency 2Hz.
3. Without delay LED is blinking so fast I don't know what's its frequency.

How do I make make 50Hz AC current a with negative cycle?

# Answer
> 2 votes
I ran your sketch and this is the output signal:

`analogWrite` produce a square wave.

As Majenko said, you have to add a low pass filter to get that sine wave.

# Answer
> 0 votes
If you are not critical on the waveform you can use a transformer where the secondary has a center tap. The primary should have one as well. Tie the input center tap to +12 or whatever is available but DO NOT use the arduino 5 volt pin. Then using two avalanche protected N channel MOSFETs you them to drive the remaining two input leads. The output will be a pseudo sine wave, far from perfect but it will have the negative excursion you want.This type of circuirity can be found in Switch Mode Power Supplies (SMPS). Note the transformer winding ratio will determine your output voltage. You will need a little dead time between turning one MOSFET off and the Other on. A single mosfet would work but there would only be two connections to the transformer primary not 3 and the wave form will be a lousy.

---
Tags: arduino-uno, analogwrite
---


# Question
Title: How to count positive electrical pulses?
I have a device that has one blinking LED.

I want to count the number of blinks. I planned to do it using Arduino. I will connect two terminals of LED input to Arduino digital input pins, and I will count the number of positive voltage pulses

I just want to know if it is possible? and if yes then can you please hint the code for the same?

# Answer
> 1 votes
You should not count the number of pulses, but the number of transition from 0 to VCC volts or VCC to 0 volts (called rising resp. falling edge).

If you don't want to solder, you can also use a light dependent resistor (LDR) very close by the LED to measure the difference in brightness. See also chrisl's remark below.

The counting you can do manually (in a loop, check as often as possible or needed), or by setting up a timer to check for either rising or falling edges.

I will give the pseudo code so you can figure out the actual code:

```
bool _ldrPin;
unsigned long int _counter;

setup()
{
   // Set Serial
   Serial.begin(9600);

   // Set LDR
   setAnalogPin(X, INPUT);
   _ldrPin = readAnalog(X);
}

loop()
{
    if (!_ldrPin && readAnalog(X) == HIGH)
    {
        // Rising edge, increase counter
        _counter++;
        Serial.Write(_counter);
        _ldrPin = true;
    }
    else if (ldrPin && readAnalog(X) == LOW)
    {
       // Falling edge, reset status
        _ldrPin = false;
    }
}

```

# Answer
> 1 votes
# Detecting the LED Pulses

You want to detect each LED pulse. For this you will need **edge detection code**. There is an Arduino example built into the IDE and information describing the function here: https://www.arduino.cc/en/Tutorial/BuiltInExamples/StateChangeDetection

To add to the Arduino explanation, you can either detect the rising edge (ie. the transition from a LOW to a HIGH) or the falling edge (ie. the transition from a HIGH to a LOW). I personally prefer the following code to detect a rising edge. In simple terms the code can be translated to this:

```
if ( (lastLedState == LOW) && (ledState == HIGH) )

```

where `ledState` would be assigned by a `digitalRead` and `lastLedState` would record the value of `ledState` at the end of the loop function (ie. just before it reads in the led states again).

# Full Code

Now if we optimise the above statement and put it into context:

```
unsigned long int pulseCounter = 0;
const int LedInput = 3;    // Digital input 3
bool ledState = 0;
bool lastLedState = 0;

void setup() {

}

void loop() {
    ledState = digitalRead(LedInput);

    // If the LED turns ON
    if (ledState && !lastLedState)
    {
        // Increment your counter
        pulseCount++;
    }

    // Update LED flag
    lastLedState = ledState;
}

```

---
Tags: led, digital
---


title: Simple ModBus Master function 15

text:
# Question
Title: Simple ModBus Master function 15
I have a simple setup with arduino Nano as slave and a arduino Mega as master Can anyone explain how the function 15 FORCE\_MULTIPLE\_COILS Works

i have been running some test on this and cant figure out how to use the local\_start\_address

is this the data to read from or is it a pointer to another File

modbus\_construct(&packets\[PACKET1\], 1, 15, 1, 8, 1021);

dec 8 = (no\_of\_registers = packet-\>data) // number of coils

so frame 6 = 1 (frame\[6\] = no\_of\_bytes;) // number of bytes more

dec 1021 = (packet-\>local\_start\_address) the dec 1021 and 65565 seams to work ???? but makes no sense to me in binary format ?

Here is
part of CPP file:

```
enter code here

unsigned char construct_F15()
{
   // function 15 coil information is packed LSB first until the first 16 bits are completed
  // It is received the same way..
  unsigned char no_of_registers = packet->data / 16;
  unsigned char no_of_bytes = no_of_registers * 2;

  // if the number of points dont fit in even 2byte amounts (one register) then use another register and pad
  if (packet->data % 16 > 0)
  {
    no_of_registers++;
    no_of_bytes++;
  }

  frame[6] = no_of_bytes;
  unsigned char bytes_processed = 0;
  unsigned char index = 7; // user data starts at index 7
   unsigned int temp;

  for (unsigned char i = 0; i < no_of_registers; i++)
  {
    temp = register_array[packet->local_start_address + i]; // get the data

frame[index] = temp & 0xFF;

    bytes_processed++;

    if (bytes_processed < no_of_bytes)
    {
      frame[index + 1] = temp >> 8;
      bytes_processed++;
      index += 2;
    }
  }
   unsigned char frameSize = (9 + no_of_bytes); // first 7 bytes of the array + 2 bytes CRC + noOfBytes
   return frameSize;
}

```

# Answer
> 1 votes
i found it

it is the

temp = register\_array\[packet-\>local\_start\_address + i\]; // get the data in the ccp file

register\_array\[packet-\>local\_start\_address + i\]

its pointing to the wrong location... register\_array??

supersized no one has noticed this as long as the simple modbus master for adruino has been used ?

or i have a bad CPP file ?

i have temp corrected this by replacing with

```
unsigned char construct_F15()
{
    // function 15 coil information is packed LSB first until the first 8 bits are completed
    unsigned char frameSize = 10;
    unsigned char temp;
    frame[6] = 1;
    frame[7] = packet->local_start_address ^ 0XFFFF;
    return frameSize;
}

```

works (0 = off / 255 = on)

modbus\_construct(&packets\[PACKET1\], 1, 15, 1, 8, 0); // 1 thru 8 = off

modbus\_construct(&packets\[PACKET2\], 1, 15, 1, 8, 255); // 1 thru 8 = on

---
Tags: communication, software, modbus
---


# Question
Title: send configuration commands with arduino
I am using ublox zed F9P multi GNSS module. I have to program it for its configuration messages. Like I have to run a specific configuration of my receiver with the help of Arduino. I know arduino parse the GNSS sentences but can anyone tell me how to write code for ublox configuration commands such that that command can change setting of the receiver upon burning it in Arduino. Also, that code should retain in the receiver even if arduino is disconnected (closing arduino IDE console). Please help

# Answer
> 0 votes
Here you find a **standard** library from arduino.

https://www.arduino.cc/reference/en/libraries/sparkfun-ublox-arduino-library/

You can find the documentation here:

https://github.com/sparkfun/SparkFun\_Ublox\_Arduino\_Library

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


# Question
Title: Can I use arduino pro micro rx tx as digital pins
I'm using arduino pro micro Atmega32u4 5v 16Mhz

I want to use it to make a HID Keyboard and Mouse but I ran out of pins so I was wondering if I can use the RX and TX pins as digital input pins. Will it work? Will it affect the communication of the arduino to the computer?

# Answer
> 1 votes
Using TX and RX on a 32U4 does not affect PC communication. It uses a competent different communication channel.

You can use those pins for digital operation with no problems, you just won't be able to use `Serial1` for communication with serial peripherals.

# Answer
> 1 votes
Welcome to ASE.

1. Communication between the PC and the Arduino Pro Micro happens through the USB, unlike the Arduino Uno and Mega, which use the RX and TX lines.
2. In your case, the USB pins of the Micro are used to communicate with the PC. Hence, the RX and TX pins are available for digital input and output operations.

---
Tags: arduino-pro-mini, keyboard, atmega32u4
---


# Question
Title: Can Arduino UNO permanently store a code?
I'm really new to Arduino and wanted to know if I can make Arduino a permanent controller? and could you help me with a cheaper alternative? I also wanted to know about "fuse", i read it somewhere that i can protect the code from someone else who wishes to use, using a FUSE.

Thanks a lot for helping me out:)

# Answer
> idk if the arduino stores the code for ever

The code is saved in the flash memory, which is non-volatile. It does not lose its content during power cycles. Also, when looking at the time dimension, it holds the code over a very long time, though not for ever. The datasheet of the Atmega328p (the microcontroller in the Arduino Uno or Nano) states:

> Reliability Qualification results show that the projected data retention failure rate is much less than 1 PPM over 20 years at 85°C or 100 years at 25°C.

So over 20 years at a temperature of 85°C you can get 0.0001% of data loss in the flash memory. At normal room temperature you can get that loss in 100 years. So significantly longer than the lifetime of most electronic products.

> I also wanted to know about "fuse", i read it somewhere that i can protect the code from someone else who wishes to use, using a FUSE.

There are different ways and levels of protection. Though that is a more advanced topic, that you should tackle, when your product is finished otherwise. There are multiple resources on the web about this. The first place to look is always the datasheet of the used microcontroller. First part might be to not use the standard Arduino bootloader, but your own. And then you can set 2 fuses for getting different levels of protection (write protection, read protection), that will lock out 99% of the people. This question on Electrical SE might also be interresting for you. You can find many resources on the web by searching for something like "Arduino code protection" or "AVR code protection" (if you are using an AVR based microcontroller like with the Arduino Uno/Nano/Mega)

---

Apart from that I also would open the question to you, if your code is really that new and ingenious, that you need to protect it from being read that way? It might totally be, that this is the case for you. But from my perspective the probability is very low. I cannot say of my own codes, that they are worth the hassle of protection. And it also depends on what you really want to prevent that way.

For context: When you program the Arduino (or any microcontroller) with your C/C++ program, the text of the program is not saved on the Arduino. Instead the code is first converted to Assembler code and then compiled into binary machine code. On that level all the nice concepts of the higher level languages are not present, so they are done by multiple lower level functions (for example loops are jumps with conditions). An attacker might read the machine code back from the microcontroller. The biggest threat here is, that he would just copy it to a new microcontroller.

If he wants to get "code" from it, he would invoke a disassembler, which converts the machine code back to the assembler language. But at this point all symbols (names of variables, functions, ...) are lost, because they are not saved in the original machine code from the start. Reading and understanding such a code is very difficult, especially, if your code is rather big and complex. Most times it would be easier for an attacker to just reverse engineer your code based on the behavior of the original microcontroller.

So in the end, you cannot really prevent people from building counterfeit products. That's what a patent is for.

This does not mean, that you should not use the code protection. Just do a realistic security assessment and then decide, if it is worth the hassle.
> 3 votes

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


title: working with ultrasonic sensors

text:
# Question
Title: working with ultrasonic sensors
I have a little problem dealing with ultrasonic sensor I want a simple thing , when the sensor read High pulse then after it low pulse , turns on the led so I try to make it with a 5cm distance and a flag , but it's dose not work help me please!

```
    #define echoPin 5
    #define trigPin 7
    int GREEN = 2;
    int YELLOW = 3;
    int RED = 4;
    int pos = 0;
    int flag = 0 ;
    long duration;
    int distance;
    void setup() {

  // put your setup code here, to run once:
    pinMode(GREEN, OUTPUT);
    pinMode(YELLOW, OUTPUT);
    pinMode(RED, OUTPUT);
    pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
    pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
     }

    void loop() {

    ultra();

    if ( distance <= 5 && flag == 0)
    {//H
      flag = 1 ;}
    } //high pulse (When the distance <=5)

    if ( distance >5 && flag == 1)
    {//L
      red_light(); }

    }//the led should turned on when low pulse appears (When the distance >5)

    void red_light()
    { digitalWrite(GREEN, LOW);
    digitalWrite(YELLOW, LOW);
    digitalWrite(RED, HIGH); }

    void ultra()
    { digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = duration*0.034/2; }

//this is my code

```

# Answer
> what actually happens with this code is when I put something near the sensor \<= 5 , the led is on without i removed the thing , but I want the led on when I put then remove the thing

Here is my theory on what happens here. You can confirm it by using one of the solutions, that I will explain below.

Currently your code is measuring the distance as fast as it can. The measurement is what takes the longest time in one iteration of the `loop()` function. Thus you get many many measurements per second. But such distance measurements are always noisy, meaning that the values change randomly in a specific range. When you put the object in front of the sensor, you expect the values to just go down, but actually they are sometimes rising again for 1 or 2 values because of the noise. So the measured values might look something like this (only imagined for making the point; not real values):

```
5.4 --> 5.2 --> 4.99 --> 5.001 --> 4.89 --> 4.90 --> 4.5

```

Overall the values go down, but you are comparing always the current value with the fixed threshold of 5cm. When the noise just raises the value again, while you pass 5cm, you will get a false "put and removed again" outcome. At the probability of the noise doing that is really high, since you measure that often and ultrasonic sensors are not accurate down to millimeters. You could even have the distance pass 5cm multiple times due to the noise.

There are some possibilities to reduce noise or to handle it.

* **Hysteresis:** The first, that I would implement here is hysteresis. That means, that you set the "put" distance different than the "remove" distance. For example you could use 5cm as the distance to register, that the object is put in front of the sensor, but then you wait for the distance to go above 7cm to actually treat the object as "removed". You need to choose the difference between the distances larger than the noise (you can find that out via experimenting). This principle is also used directly with noisy digital signals on the Arduinos input pins. An Arduino Uno will treat voltages above about 2.6V as digital 1 (HIGH signal), and a value below 2.1V as digital 0 (LOW signal) (taken from the datasheet of the Atmega328P, which is the microcontroller on an Arduino Uno, while assuming the controller running on 5V like in an Arduino Uno). In electrical terms this is called a Schmitt-Trigger.

For implementing this, you can just change the threshold values in your if statements.
* You can reduce the noise by always measuring multiple times in a row and then calculating the mean value from it. Since a part of the noise is random, you can smoothe out this part a bit through taking the mean. That also reduces your time resolution, but in such a simple use case that mostly doesn't matter that much.
* If the reaction time doesn't matter that much, you could reduce the frequency of measurements, so that subsequent distance measurements are already to far away from each other for the noise to create false triggers. This is worse than the other solutions, since it also depends on how fast you put the object in front of the sensor, but it is really easy to implement (just a simple `delay()` call, or better using `millis()` like in the `BlinkWithoutDelay` example for non-blocking code)

I would first implement the hysteresis. Then, if the difference in distances, that you need for it to work good, is too big for you, you can take the mean of multiple value to reduce the noise.

---

And just for protocol, as it already was said in the comments: Your first if statement has an extra closing bracket `}` which should not be there.
> 1 votes

---
Tags: arduino-uno, arduino-mega, ultrasonics
---


# Question
Title: iterate through 8 thermocouple sensors (MAX31856)
I have 8xMAX31856 and I am trying to use the Adafruit library. Instead of writing all 8 thermocouple channels each time in code (and wasting memory), I want to store the objects in an array and loop through them periodically.

Here is my code:

```
Adafruit_MAX31856 TCouple1 = Adafruit_MAX31856(2,11,12,13);
Adafruit_MAX31856 TCouple2 = Adafruit_MAX31856(3,11,12,13);
Adafruit_MAX31856 TCouple3 = Adafruit_MAX31856(4,11,12,13);
Adafruit_MAX31856 TCouple4 = Adafruit_MAX31856(5,11,12,13);
Adafruit_MAX31856 TCouple5 = Adafruit_MAX31856(6,11,12,13);
Adafruit_MAX31856 TCouple6 = Adafruit_MAX31856(7,11,12,13);
Adafruit_MAX31856 TCouple7 = Adafruit_MAX31856(8,11,12,13);
Adafruit_MAX31856 TCouple8 = Adafruit_MAX31856(9,11,12,13);

char* thermocouples[] = {TCouple1, TCouple2, TCouple3, TCouple4, TCouple5, TCouple6, TCouple7, TCouple8};

```

however, I am met with this error on compile:

```
cannot convert 'Adafruit_MAX31856' to 'char*' in initialization

```

Why can I not store these variables in an array and call on them later? Is there another way to do this? They work on SPI logic...

# Answer
You CAN store them in an array, but NOT in an array of pointers to characters. That is just the wrong type. Try

```
Adafruit_MAX31856 thermocouples[] = {TCouple1, ...}

```

or even ditch the first declarations and use

```
Adafruit_MAX31856 thermocouples[] = {
    Adafruit_MAX31856(2,11,12,13),
    Adafruit_MAX31856(3,11,12,13),
    Adafruit_MAX31856(4,11,12,13),
    ...
};

```

I don't have that library installed, but I tried compiling this pattern with the `Bounce2` library and it works. That looks like this:

```
Bounce buttons[] = {
    Bounce(),
    Bounce(),
    Bounce()
};

```
> 1 votes

---
Tags: adafruit, array
---


title: Object composition (class uses class)

text:
# Question
Title: Object composition (class uses class)
I would like to write a class which utilises another class and it´s member functions. I found out that this is object composition and read some examples of how to do it but it ither doesn´t work for me or I just don´t understand it completely. Here are parts of my code.

```
#include <SPFD5408_Adafruit_GFX.h>    // Core graphics library
#include <SPFD5408_Adafruit_TFTLCD.h> // Hardware-specific library
#include <SPFD5408_TouchScreen.h>     // Touch library
#include <TriangleButton.h>        // TriangleButton library

```

I want to use an Adafruit\_TFTLCD object and its member functions inside my own class TriangleButton. The object tft is initialised before setup.

```
Adafruit_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET); //Class is part of SPFD5408_Adafruit_TFTLCD.h

```

I built the TriangleButton.h similar to this thread (Use object of other class within class) and used a reference to the tft object.

```
/*
  TriangleButton.h - Library for for constructing and reading triangle Buttons.
*/
#ifndef TriangleButton_h
#define TriangleButton_h

#include "Arduino.h"
#include <SPFD5408_Adafruit_TFTLCD.h>

class TriangleButton
{
  public:

    TriangleButton(Adafruit_TFTLCD &tft, int16_t coordX, int16_t coordY, int16_t orientation, uint16_t size, uint16_t color) : _tft(tft){}
    boolean IsTriggered();
    void dash();
  private:

    Adafruit_TFTLCD &_tft;
    int16_t _coordX;
    int16_t _coordY;
    int16_t _orientation;
    int16_t _size;
    int16_t _color;
    int16_t _ru;
    int16_t _hc;
};

#endif

```

In the ccp. i put a coresponding constructor.

```
TriangleButton::TriangleButton(Adafruit_TFTLCD &tft, int16_t coordX, int16_t coordY, int16_t orientation, uint16_t size, uint16_t color)
:
_tft(tft)

```

Now i get the following error message:

C:\Users\Erik\Documents\Arduino\libraries\AquariumController\_Library\TriangleButton.cpp:19:1: error: redefinition of 'TriangleButton::TriangleButton(Adafruit\_TFTLCD&, int16\_t, int16\_t, int16\_t, uint16\_t, uint16\_t)' TriangleButton::TriangleButton(Adafruit\_TFTLCD &tft, int16\_t coordX, int16\_t coordY, int16\_t orientation, uint16\_t size, uint16\_t color) ^~~~~~~~~~~~~~ In file included from C:\Users\Erik\Documents\Arduino\libraries\AquariumController\_Library\TriangleButton.cpp:7:0: C:\Users\Erik\Documents\Arduino\libraries\AquariumController\_Library\TriangleButton.h:14:5: note: 'TriangleButton::TriangleButton(Adafruit\_TFTLCD&, int16\_t, int16\_t, int16\_t, uint16\_t, uint16\_t)' previously defined here TriangleButton(Adafruit\_TFTLCD &tft, int16\_t coordX, int16\_t coordY, int16\_t orientation, uint16\_t size, uint16\_t color) : \_tft(tft){} ^~~~~~~~~~~~~~ exit status 1

I don\`t understand why ther is a redefinition. Can somebody explain it to me?

# Answer
> 0 votes
> error: class 'TriangleButton' does not have any field named '\_tft'

This should be self-explanatory. When you write in the constructor

> ```
> _tft(tft)
>
> ```

It means “initialize the property `_tft` of this object with the parameter `tft`.

It is not very clear what you mean by “object composition”. In the usual sense, it means that object A either *is* or *has* an object B. In your case, it seems like you want your `TriangleButton` to hold a *reference* to an `Adafruit_TFTLCD`. This is not really composition, as your class neither *is* nor *has* an LCD.

As an immediate solution, just add an appropriate data member to the class:

```
Adafruit_TFTLCD &_ftf;

```

Assuming that holding a reference to the LCD is really what you want for your class, this should be enough to solve your issue.

---

**Edit**: To answer the edited question.

“Redefinition” means you are defining again something that has already been defined before. In this case, the constructor is defined inline in the header file:

```
TriangleButton(Adafruit_TFTLCD &tft,
        int16_t coordX, int16_t coordY,
        int16_t orientation, uint16_t size, uint16_t color)
    : _tft(tft){}

```

(yes, that's a complete definition with an empty body).

And then you try to define it again in the cpp file. This is an error, every method should be defined only once. At your choosing, it can be either inline in the header or in the .cpp, but not both.

---
Tags: class, tft, object-oriented
---


title: Monitor two baud rates

text:
# Question
Title: Monitor two baud rates
I am using different codes which set different values of baud rate through the `Serial.begin()` function.

I have an Uno using `Serial.begin(9600)` connected to an ESP8266 ESP-01 module

```
SoftwareSerial WiFiBoard(2, 3);
WiFiBoard.begin(115200)

```

Both of them are printing and reading from Serial, but when I use Arduino IDE Serial Monitor, I'm only able to display the content of the `9600`... Am I missing a setting somewhere?

Also, when I configure both of them to use the baud rate `9600`, I still only see the Uno information

# Answer
Your computer can not see what is going over the WiFiBoard serial connection because that connection has nothing at all to do with the connection to your computer.

If you want your computer to see what is being received on that port you must read the data from that port then send it to your computer.

It doesn't (much) matter about the difference in baud rates (only that if one sends too much data too fast for the other to forward it you will lose some data).

It's common to use something like:

```
while (WiFiBoard.available()) {
    Serial.write(WiFiBoard.read());
}

```

That will forward anything received from the WiFi board over the serial port to the computer.
> 2 votes

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


title: How to combine two codes in arduino?

text:
# Question
Title: How to combine two codes in arduino?
bine

```
#include <LiquidCrystal.h>
LiquidCrystal lcd(12,11,5,4,3,2);

#define sensor A0
#define led 13
#define ledd 8  // d out from mq3
#define buz 9
#define motor 10
void setup()
{
  Serial.begin(9600);
  lcd.begin(16,2);
  lcd.print("ALCOHOL MONITORING");
  lcd.setCursor(0,1);
  lcd.print(" VEHICLE SYSTEM ");
  delay(2000);
  pinMode(sensor, INPUT);
  pinMode(buz, OUTPUT);
  pinMode(led, OUTPUT);
  pinMode(ledd, OUTPUT);
  pinMode(motor, OUTPUT);
  lcd.clear();
}

void loop()
{
  float adcValue=0;
  for(int i=0;i<10;i++)
  {
    float actualanalogReading =  analogRead(sensor);
    adcValue = adcValue + actualanalogReading;
    Serial.println("In loop counter >"); // logging
    Serial.print(i);
    Serial.print(" input reading : ");
    Serial.print(actualanalogReading);
    Serial.print(" cumulative input reading : ");
    Serial.print(adcValue);

    delay(10);
  }
    float v= (adcValue/10) * (3.0/1024.0);
    float mgL= 0.67 * v;
    Serial.println("");
    Serial.print("Post calculation v value >" );
    Serial.print(v);
    Serial.print(" mg/L > ");
    Serial.print(mgL);
    Serial.println("");
    Serial.print("BAC:");
    Serial.print(mgL);
    Serial.print(" mg/L");
    lcd.setCursor(0,0);
    lcd.print("BAC: ");
    lcd.print(mgL,4);
    lcd.print(" mg/L        ");
    lcd.setCursor(0,1);
    if(mgL > 0.8)
    {
      lcd.print("Drunk ENGINE OFF ");
      Serial.println("Drunk ENGINE OFF ");
      digitalWrite(buz, HIGH);
      digitalWrite(led, HIGH);
      digitalWrite(ledd, LOW);
      digitalWrite(motor, LOW);
    }
    else
    {
      lcd.print("Normal ENGINE ON ");
      Serial.println(" Normal ENGINE ON ");
      digitalWrite(buz, LOW);
      digitalWrite(led, LOW);
      digitalWrite(ledd, HIGH);
      digitalWrite(motor, HIGH);
    }

    delay(100);

}

```

top code^^^ combines with this\>\>

```
const int LED = A5;
const int DO = 6;
void setup() {
 Serial.begin(9600);
 pinMode(LED, OUTPUT);
 pinMode(DO, INPUT);
}
void loop() {
 int alarm = 0;
 float sensor_volt;
 float RS_gas;
 float ratio;
//-Replace the name "R0" with the value of R0 in the demo of First Test -/
 float R0 = 0.10;
 int sensorValue = analogRead(A1);
 sensor_volt = ((float)sensorValue / 1024) * 5.0;
RS_gas = (5.0 - sensor_volt) / sensor_volt; // Depend on RL on yor module
 ratio = RS_gas / R0; // ratio = RS/R0
//------------------------------------------------------------/
 Serial.print("sensor_volt = ");
 Serial.println(sensor_volt);
 Serial.print("RS_ratio = ");
 Serial.println(RS_gas);
 Serial.print("Rs/R0 = ");
 Serial.println(ratio);
 Serial.print("\n\n");
 alarm = digitalRead(DO);
 if (alarm == 1) digitalWrite(LED, LOW);
 else if (alarm == 0) digitalWrite(LED, HIGH);
 delay(1000);
}

```

# Answer
While I'd like to direct you to ways to set up a nice tasking system with a frame counter, your system is likely simple enough that it is unnecessary. You can likely just replace the delay(1000); of the second program with approximately 5 calls of the first program's loop. May you instead learn something when cleaning up the following (which is literally a copy paste with minimal changes).

```

#include <LiquidCrystal.h>
LiquidCrystal lcd(12,11,5,4,3,2);

#define sensor A0
#define led 13
#define ledd 8  // d out from mq3
#define buz 9
#define motor 10
void setup1()
{
  Serial.begin(9600);
  lcd.begin(16,2);
  lcd.print("ALCOHOL MONITORING");
  lcd.setCursor(0,1);
  lcd.print(" VEHICLE SYSTEM ");
  delay(2000);
  pinMode(sensor, INPUT);
  pinMode(buz, OUTPUT);
  pinMode(led, OUTPUT);
  pinMode(ledd, OUTPUT);
  pinMode(motor, OUTPUT);
  lcd.clear();
}

void loop1()
{
  float adcValue=0;
  for(int i=0;i<10;i++)
  {
    float actualanalogReading =  analogRead(sensor);
    adcValue = adcValue + actualanalogReading;
    Serial.println("In loop counter >"); // logging
    Serial.print(i);
    Serial.print(" input reading : ");
    Serial.print(actualanalogReading);
    Serial.print(" cumulative input reading : ");
    Serial.print(adcValue);

    delay(10);
  }
    float v= (adcValue/10) * (3.0/1024.0);
    float mgL= 0.67 * v;
    Serial.println("");
    Serial.print("Post calculation v value >" );
    Serial.print(v);
    Serial.print(" mg/L > ");
    Serial.print(mgL);
    Serial.println("");
    Serial.print("BAC:");
    Serial.print(mgL);
    Serial.print(" mg/L");
    lcd.setCursor(0,0);
    lcd.print("BAC: ");
    lcd.print(mgL,4);
    lcd.print(" mg/L        ");
    lcd.setCursor(0,1);
    if(mgL > 0.8)
    {
      lcd.print("Drunk ENGINE OFF ");
      Serial.println("Drunk ENGINE OFF ");
      digitalWrite(buz, HIGH);
      digitalWrite(led, HIGH);
      digitalWrite(ledd, LOW);
      digitalWrite(motor, LOW);
    }
    else
    {
      lcd.print("Normal ENGINE ON ");
      Serial.println(" Normal ENGINE ON ");
      digitalWrite(buz, LOW);
      digitalWrite(led, LOW);
      digitalWrite(ledd, HIGH);
      digitalWrite(motor, HIGH);
    }

    delay(100);

}

const int LED = A5;
const int DO = 6;
void setup() {
 setup1(); //Serial.begin(9600);
 pinMode(LED, OUTPUT);
 pinMode(DO, INPUT);
}
void loop() {
 int alarm = 0;
 float sensor_volt;
 float RS_gas;
 float ratio;
//-Replace the name "R0" with the value of R0 in the demo of First Test -/
 float R0 = 0.10;
 int sensorValue = analogRead(A1);
 sensor_volt = ((float)sensorValue / 1024) * 5.0;
RS_gas = (5.0 - sensor_volt) / sensor_volt; // Depend on RL on yor module
 ratio = RS_gas / R0; // ratio = RS/R0
//------------------------------------------------------------/
 Serial.print("sensor_volt = ");
 Serial.println(sensor_volt);
 Serial.print("RS_ratio = ");
 Serial.println(RS_gas);
 Serial.print("Rs/R0 = ");
 Serial.println(ratio);
 Serial.print("\n\n");
 alarm = digitalRead(DO);
 if (alarm == 1) digitalWrite(LED, LOW);
 else if (alarm == 0) digitalWrite(LED, HIGH);

 for(int dd = 0; dd < 5; dd++) loop1();
}

```
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: AT firmware upgrade in ESP-01 using Arduino UNO R3
I need to upgrade the AT firmware in ESP-01 by using Arduino UNO R3 serial interface. Do I need to remove the Microcontroller Chip from the DIP socket before burning firmware? Does it going to affect Arduino Bootloader?

# Answer
> 1 votes
> Do I need to remove the Microcontroller Chip from the DIP socket before burning firmware?

No, just connect RESET to GND to stop the MCU from running.

> Does it going to affect Arduino Bootloader?

No.

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


# Question
Title: How do I use lambda functions in Arduino?
I want to pass a lambda function as an argument to a method. Example:

```
T reduce(const T initial, const std::function<T(T, T)> acc) {
    T value = initial;
    for (size_t i = 0; i < S; ++i) {
        value = acc(value, this->values[i]);
    }

    return value;
}

...

int sum = this->reduce(42, [](int acc, int value) { return acc + value; });

```

If I try to compile this code for Arduino, I get an obvious error:

> error: 'function' in namespace 'std' does not name a template type

How can I use a lambda function in Arduino?

# Answer
> 1 votes
`std::function` is ~~not supported by the Arduino environment~~. (**Edit**: as mentioned by KIIV in a comment, it's supported on ARM targets, but not on AVR.) You can, however, pass a non-capturing lambda to a function that expects a plain function pointer. For example, given

```
T reduce(const T initial, T (*acc)(T, T)) {
    T value = initial;
    for (size_t i = 0; i < S; ++i) {
        value = acc(value, this->values[i]);
    }
    return value;
}

```

You can call it as

```
int sum = test.reduce(42, [](int acc, int value){ return acc + value; });

```

If you want your lambda to capture something, it would seem you are out of luck...

---
Tags: c++, stl, lambda
---


# Question
Title: Wrong data receiving in my Arduino by bluetooth
I have programmed a client-server between an Arduino and my mobile app in Android. I´m using a buetooth HC-06. For the moment is a very basic code just to turn ON/OFF a led, regulate its voltage, and receive the charge of the battery.

This is my Arduino code for receiving the message:

```
#include <SoftwareSerial.h>
#include <TimerOne.h>
SoftwareSerial hc06(2,3);

char command;
String string;
boolean ledon = false;
const byte MAX_STRING_LEN = 40;
const int  BLINK_INTERVAL = 1000;

char inputString[MAX_STRING_LEN];  // a string to hold incoming data

int BatteryPin = A0;    // select the input pin for the potentiometer
int sensorValue = 0;  // variable to store the value coming from the sensor
float BatteryCar = 0;
int PercentageBatt = 0;
int intensidad = 0;
byte strLen   = 0;                 // current length of rec'd string

#define led 11
void setup()
{
  Serial.begin(9600);
  hc06.begin(9600);
  pinMode(led, OUTPUT);
  Timer1.initialize(10000); // set a timer of length 10000 microseconds (or 0.01 sec - or 1Hz => the led will blink 5 times, 5 cycles of on-and-off, per second)
  Timer1.attachInterrupt( SendVoltage );
}
void loop()
{

  sensorValue = analogRead(BatteryPin);
  BatteryCar = sensorValue * (5.0 / 1023.0);
  if (hc06.available() == 0)
  {
    analogWrite(led, 0);
    delay (10);
  }
  while(hc06.available() > 0)
  {
    command = ((byte)hc06.read());
    if((command == '\n') || (command == '\r'))
    {
      command =='\0';
      break;
    }
    else if (command == 'O')
      analogWrite(led, 255);
    else
      analogWrite(led, 0);
    delay(10);
    Serial.println(command);
  }
}

void SendVoltage ()
{

  PercentageBatt = (BatteryCar * 100)/4;
  hc06.println(PercentageBatt);
}

```

This is the data that I´m receiving:

It supposed that i should only receive "O" or "F". Any suggestion??

thanks in advanced,

# Answer
> 1 votes
Well, after a lot of research, it seems that my main problem was that I´m receiving and sending information at the same time. And with the library Softwareserial, only 1 can be active at the same time. I found two solutions, but to be honest I'm not complete satisfy with neither of them. However, for my application will work.

The first solution: Is to used the HardwareSerial (pin 0,1) itself, instead of using the pin 2 and 3. When I used those, it didn't have any problem. Although I decided no to used because it help me debugging my code.

The second solution: Is to decrease the frecuency of what I´m sending. For me its ok I send the data every second. So my code would be like this:

```
#include <SoftwareSerial.h>
#include <TimerOne.h>
SoftwareSerial hc06(2,3);

char command;
String string;
boolean ledon = false;
const byte MAX_STRING_LEN = 40;
const int  BLINK_INTERVAL = 1000;

char inputString[MAX_STRING_LEN];  // a string to hold incoming data

int BatteryPin = A0;    // select the input pin for the potentiometer
int sensorValue = 0;  // variable to store the value coming from the sensor
float BatteryCar = 0;
int PercentageBatt = 0;
int intensidad = 0;
byte strLen   = 0;                 // current length of rec'd string

#define led 11
void setup()
{
  Serial.begin(9600);
  hc06.begin(9600);
  pinMode(led, OUTPUT);
  Timer1.initialize(1000000);
  Timer1.attachInterrupt( SendVoltage );
}
void loop()
{

  sensorValue = analogRead(BatteryPin);
  BatteryCar = sensorValue * (5.0 / 1023.0);
  if (hc06.available() == 0)
  {
    analogWrite(led, 0);
    delay (10);
  }
  while(hc06.available() > 0)
  {
    command = ((byte)hc06.read());
    if((command == '\n') || (command == '\r'))
    {
      command =='\0';
      break;
    }
    else if (command == 'O')
      analogWrite(led, 255);
    else
      analogWrite(led, 0);
    delay(10);
    Serial.println(command);
  }
}

void SendVoltage ()
{

  PercentageBatt = (BatteryCar * 100)/4;
  hc06.println(PercentageBatt);
}

```

I have read about this library (AltSoftSerial), but I couldn't get it work. I have usde the pin 8 and 9, but nothing.

---
Tags: arduino-uno, bluetooth, android, hc-06
---


# Question
Title: How to upload a sketch to an atmega328 via FTDI FT232RL UART and Arduino IDE?
I have a sparkfun AVR Pocket Programmer and have burned the bootloader and uploaded programs using "upload using programmer" via USBtinyISP. It works fantastic.

I have a sparkfun FTDI Basic (as well as another FTDI breakout) that can send and receive bytes via the Arduino IDE serial monitor.

However, I cannot upload a new sketch or modified sketch to the atmega328 via FTDI. The IDE just hangs at the upload till timeout. Here is the list of some of my troubleshooting attempts:

1. I have tried uploading a plain bootloader, as well as a running program via the ISP programmer before attempting the FTDI.
2. I have tried direct connecting the FTDI DTR/RTS reset to the Atmega328 pin1.
3. I have also tried connecting the FTDI DTR/RTS reset to a one side of a 0.1uF cap, and the other side of the cap to the Atmega328 pin1. I assume the cap is to send just a reset pulse instead of a reset constant.
4. I have tried a different brand of FTDI FT232RL chip. No difference.
5. I have tried adding 1k resistors on the Tx and Rx lines. No difference.

Being able to program over serial is really the secret sauce that makes Arduino so much easier for beginners than a stock AVR chip. However, I have not been able to locate any detailed information on how this Arduino programming via serial really works. Also, I am not sure how the reset pin works in relation to this process. I remember something that on old Arduino boards you had to press or hold the reset when uploading, but have not be able to find any of this information either as it has been buried by time.

This Building an Arduino on a Breadboard Article and photo from that article below is a good outline of the setup I have right now. But in this configuration it seems that a sketch can not be uploaded. What do I need to add breadboard circuit in order to upload a sketch via serial? Or what procedure do I need to do with the reset button when uploading?

Thanks!

Atmega328 Spec Sheet PDF

# Answer
> 1 votes
Answering my own question; I just got lost in the troubleshooting.

Though I tested it both ways, I evidently overlapped issues, masking the core problem. Upload using programmer works great for transferring your sketch but it does **NOT** allow sketches to be uploaded via serial later. (Not sure if there is an inherent or logical reason for this, but this is what I have found by experimentation).

And like hcheung mentioned in the comments, a capacitor on the FTDI reset line is required. Connecting it directly will NOT work. I used a 0.1uF and it worked well. I have attached a couple different photos of my setup for someone following this path in the future. Note that the LED I am using has an internal resistor; a normal LED will need an 1k series resistor. Also, leaving the ISP programmer attached while uploading a sketch over serial did not seem to cause any issues.

---
Tags: arduino-ide, atmega328, uart, ftdi
---