title: Where is my BUG?

text:
# Question
Title: Where is my BUG?
Thank you everyone for help on my last post, i managed to make it work. I still keep trying to craft my skill with the arduino. This time I need to make a coffee hot plate simulation. When the sensor is not up to temp an LED will blink, once the sensor gets up to temp the LED will blink but turn off (go to low) after five seconds. This is the code i am working on. The sensor is at temp and the LED is still blinking instead of turning off. When its low it blinks as should. I think the bug is in the millis() portion of code. Any ideas would be greatly appreciated. I also ran the println screen, and the temp is consistantly around 210-220.

```
const int led         =  11;       // hot plate led on pin 11
const int sensor      =   9;       // temp sensor on pin 9
const int LOWER_BOUND = 174;       // lower temp
const int UPPER_BOUND = 220;       // upper temp

int val = 0;                       // analog reading

unsigned const long period = 5000; // time it takes to turn led off at temp

unsigned long startMillis;
unsigned long currentMillis;

void setup() {
    Serial.begin(9600);
    pinMode(led, OUTPUT);
    pinMode(sensor, INPUT);
    startMillis = millis();
}

void loop() {

    val = analogRead(sensor);      // temp recorder
    Serial.println(val);
    currentMillis = millis();

    if (val == UPPER_BOUND){
        digitalWrite(led, HIGH);
    }

    else if (val == UPPER_BOUND && currentMillis - startMillis == period) {
        digitalWrite(led, LOW);
    }

    else (val <= LOWER_BOUND); {
        digitalWrite(led, LOW);
        delay(200);
        digitalWrite(led, HIGH);
        delay(200);
    }
}

```

# Answer
First, let me point out a few technical issues with your program:

1. `const int sensor = 9;` is wrong. On an Uno, you can only use `analogRead()` on the pins labeled `A0` through `A5`.
2. `if (val == UPPER_BOUND)`. Never test an analog reading for exact equality. The reading is noisy, and you shouldn't expect continuity. It can very well jump from `UPPER_BOUND-1` on one reading to `UPPER_BOUND+1` on the next one. Instead, test for `val >= UPPER_BOUND`.
3. `currentMillis - startMillis == period`. Again, you should not test for exact equality. This time it's for a more subtle reason that has to do with the implementation of `millis()`: some values (roughly one every 42) are skipped over. Here again, test for `>= period`.

There is also the issue, already pointed out by PhoenixRevealed, of your code defining two thresholds, while your prose only mentions one. This may well be just you being sloppy and not describing your requirements precisely enough.

Next, and since you are interested in perfecting your learning process, let me advise you on two techniques that are worth learning, because they are extremely useful for mostly any Arduino project more complex than just blinking an LED:

1. **Avoid using `delay()`**. While the Arduino is busy delaying, it can do nothing else. For instance, it cannot monitor the temperature changes on the hot plate. In this particular case, it may well be the case that you don't care, because the hot plate is so slow that you can afford to be 400 ms late. But if you get into the habit of relying on `delay()`, it will bite you sooner or later. So the sooner you learn to blink an LED without using `delay()`, the better.
2. Learn to program a **finite state machine**. This is a programming concept that is very well suited for describing reactive systems, i.e. systems that have to react to external “events”. It is a very useful concept for writing most programs that are meant to control hardware. There are quite a few tutorials out there. I would recommend The Finite State Machine, by Majenko.

Here is my interpretation of your requirements in terms of a finite state machine: your Arduino can be in any of 3 states: `COLD` (initial state, the plate has not reached the required temperature), `WAITING` (the plate reached the temperature and we are delaying five seconds), `DONE` (the five seconds have elapsed). The rules for changing states are:

* `COLD``WAITING`: when in the `COLD` state, if the temperature reaches a specified threshold, go to the `WAITING` state.
* `WAITING``DONE`: when in the `WAITING` state, once five seconds have elapsed since we entered the state, go to the `DONE` state.
* When we are in the `DONE` state... nothing more ever happens.

Here is the corresponding state diagram:

Notice that once we reach the `DONE` state, the system gets stuck. This situation can only be recovered from by rebooting the Arduino. You may want to revise your specification in order accommodate a `DONE``COLD` transition in some way. But from your specification *as written in your question*, I assume you are fine with the system getting stuck.

I tried to implement this state diagram in code, using the traditional `switch`/`case` construct. But then I got lazy and noticed that calling `exit()` is the easiest way of implementing the `DONE` state, as this function is precisely designed to get the program stuck in a do-nothing state. Then, since there are only two states left to care about, a boolean can be used as a state variable. In the end, the code I propose may not look like a finite state machine. However, it is important to notice that, event if such case, the finite state machine is a very useful concept for *thinking* about your program and writing down its requirements.

```
// Pinout
const uint8_t LED = 11;
const uint8_t SENSOR = A0;

// Threshold temperature reading.
const int THRESHOLD_TEMP_READING = 220;

// Timing.
const uint32_t LED_TOGGLE_PERIOD = 200;
const uint32_t WAIT_TIME = 5000;

bool is_hot = false;
uint32_t last_led_toggle;
uint32_t wait_started;

void setup()
{
    pinMode(LED, OUTPUT);
    pinMode(SENSOR, INPUT);
}

void loop()
{
    // Read the time once per loop.
    uint32_t now = millis();

    // Toggle the LED state.
    if (now - last_led_toggle >= LED_TOGGLE_PERIOD) {
        digitalWrite(LED, !digitalRead(LED));
        last_led_toggle = now;
    }

    if (is_hot) {
        // If the plate is hot, keep blinking during WAIT_TIME.
        if (millis() - wait_started >= WAIT_TIME) {
            digitalWrite(LED, LOW);  // turn off the LED
            exit(0);                  // stop everything
        }
    } else {
        // If the plate is cold, take note when it gets hot.
        if (analogRead(SENSOR) >= THRESHOLD_TEMP_READING) {
            is_hot = true;
            wait_started = now;
        }
    }
}

```
> 1 votes

# Answer
I see a couple of issues with your code. The biggest problem is that you capture startMillis in setup() and then compare it with currentMillis in your loop. If it takes more than five seconds for the pot to get hot enough you will never match (currentMillis - startMillis) == period because (currentMillis - startMillis) will already be \> period before you start testing it. Changing "== period" to "\>= period" will fix this, but it still won't behave the way you want since you should be setting startMillis when the pot first reached the target temp, not at program startup.

Also, your code does nothing when the temp is between LOWER\_BOUND and UPPER\_BOUND, which I suspect is not what you want. You don't specify whether "up to temp" means at or above LOWER\_BOUND or at or above UPPER\_BOUND. I'm going to assume that you want the LED to flash when the temp is below LOWER\_BOUND, go solid on while the temp is between LOWER\_BOUND and UPPER\_BOUND, and then turn completely off five seconds after the pot reaches UPPER\_BOUND.

Personally I would rewrite it like this, both for functionality and readbility...

```
int val = 0;                       // analog reading

unsigned const long period = 5000; // time it takes to turn led off at temp

// ---We don't need this till later, zero it so the loop knows not to use it till then
unsigned long startMillis = 0;

void setup() {

    Serial.begin(9600);
    pinMode(led, OUTPUT);
    pinMode(sensor, INPUT);

}

void loop() {

    val = analogRead(sensor);      // temp recorder
    Serial.println(val);

    if ( val <= LOWER_BOUND ) {

        // ---Coffee temp is low, flash the LED
        digitalWrite(led, LOW);
        delay(200);
        digitalWrite(led, HIGH);
        delay(200);

    } else if ( val < UPPER_BOUND ) {

        // ---Coffee temp is medium, turn the LED solid on (assumes switched cathode)
        digitalWrite(led, LOW);

    } else {

        // ---Coffee is hot!
        if ( !startMillis ) {

            // ---Coffee just reached UPPER_BOUND... start timing (LED is already on)
            startMillis = millis();

        } else {

            // ---Has the period timed out yet?
            if ( ( millis() - startMillis ) >= period ) {

                  // ---More than 5 seconds has passed, make sure LED is off
                  digitalWrite(led, HIGH);

            }
        }
    }
}

```

A couple of points about this implementation...

1. I have not tested this code on a physical Arduino.
2. Notice that we don't care to start storing or watching millis() until the pot first reaches UPPER\_BOUND. Until then all the program cares about is the temp of the coffee.
3. Like your original code, this implementation doesn't consider the wraparound of millis() every 50 days or so. It's unlikely a coffee pot will take over 50 days to reach the target temperature, so I wouldn't worry about it, but you should consider this situation when coding long-running applications (I refuse to call them "sketches").
4. I based this on your original code, so like yours, once the temp reaches at least LOWER\_BOUND it continuously writes to the LED pin every pass through the loop, even though it likely hasn't changed since the last iteration. If I was doing this for real I would restructure it so it only writes to the pin when the state of the LED actually changes. This is only an efficiency issue though... writing the same value to a pin repeatedly will work fine, it just isn't very elegant.
5. If the coffee starts to cool down after reaching UPPER\_BOUND then behaviour is undefined. I suspect that it would work normally when the coffee temp is low or medium, but if the coffee reached the UPPER\_BOUND the second or more times I believe the LED would turn off immediately rather than after 5 seconds. It wouldn't be difficult to enhance the code to behave correctly no matter how many times the pot temp cycles up and down, but this solution was to the problem as you described it, which was a coffee pot warming up just once from cold to a target temperature.
> 0 votes

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


title: MCP2515 CAN bus with Arduino

text:
# Question
Title: MCP2515 CAN bus with Arduino
I'm using MCP2515 CAN controller and TJA1050 transceiver. I want to send some square waves to TJA1050 with digital write and delay instruction of Arduino. How can I do that? I also read the MCP2515's datasheet. It has 5 GPIOs. Can I use these pins to send square waves to the transceiver? Here is the library I used:https://github.com/Seeed-Studio/CAN\_BUS\_Shield The examples of this library contains a sample code as gpioread and gpiowrite but when I compile them I got error: exit status 1 'class MCP\_CAN' has no member named 'pinMode'

Thanks in advance.

# Answer
> 0 votes
This is not really a general Arduino question but...

The compiler is telling you that the member function 'pinMode' is not available. A closer look at the commit history for the library reveals that they have recently rolled back to a "working version". There is a commit with the member functions 'pinMode', 'digitalRead' and 'digitalWrite' included.

Please see: https://github.com/Seeed-Studio/CAN\_BUS\_Shield/commit/15c6bfb80a50c924a9c708117a66a66b54af5370

---
Tags: arduino-uno, pins, can-bus
---


title: Can't upload the program to Arduino Uno

text:
# Question
Title: Can't upload the program to Arduino Uno
My Arduino Uno R3 is not detected by any laptop (I tried 3 laptops). Under devices there is no Arduino port or other devices option. It does not make sound on inserting USB cable. On plugging the USB LED 13 doesn't blink. I is just continuously on. Reset also didn't blink LED 13. Even on external power also it's not resetting.

I checked the USB cable but it's working for my friend's Arduino in my laptop too.

5V Pin giving voltage around 4.96 v, and 3.3 also giving voltage around 3.27 v.

Now I don't have access to any other Arduino for testing. Is there any way to figure out whether the ATmega chip is fried or whether it's a bootloader problem? And how to fix them? Thanks in advance.

# Answer
> 2 votes
While installing the Arduino software,
there are several **window pop ups** which occur to **install the drivers** needed for the operating system to communicate with the device.
Click **install** to all of them.

# Answer
> 1 votes
If you have access to a linux computer, what does `lsusb` say when it is plugged in over USB? Compare that output to lsusb with no Arduino plugged in. If you don't, does the arduino show up as a device to your OS at all?

You could also use your friend's arduino to reflash your bootloader. If that still doesn't work, or if your arduino doesn't show up as a device, you can try reflashing the atmega16u4 ( the USB \<-\> serial chip ). It is the chip responsible for telling the computer that it is an arduino serial port, so if things are still getting power, but not showing up, I would check that chip.

If it is neither of those things, there may be something wrong with one of the passive USB components, maybe one of the varistors died and is now shorted to ground, for instance. I could give more help if you share the schematic for your specific board.. is it an official Arduino, or a clone?

# Answer
> 0 votes
> Can't upload the program to Arduino Uno

if your trouble is limited to just "the program", then the issues must be specific to that program.

if you cannot upload "any program", then the issues must be hardware or host related.

# Answer
> 0 votes
It is probably not a problem with the Atmega328p chip or its bootloader; the Uno has a separate processor to handle USB - an Atmega 32U4, which is the flat, surface-mount chip right behind the USB connector on the board. If that or its firmware is damaged, your PC won't recognize the device when you plug it in. If that chip is up and running, your PC will see it.

---
Tags: arduino-uno
---


title: Timer with ajustable time delay

text:
# Question
Title: Timer with ajustable time delay
I have a led strip, and each led should be turned on sequentially, such as this one: \[http://1.bp.blogspot.com/-CTT6yvYtdos/VihhhBItwjI/AAAAAAAAAvM/q1jbUylMMdM/s400/ezgif.com-video-to-gif.gif\]\[1\] The time delay between 2 consecutive leds is ts, and that time should be adjusted externally through a pushbutton switch. Each time the button is pressed, the time period shoud increment in a fixed amount. I've already used the timerOne library, but it just works with a fixed time delay ts. How can I solve this issue with VARIABLE time delay? I prefer to use interruptions rather than polling, since this system will be more complex (other buttons and variables will be involved). Thanks! Fernando

# Answer
> 1 votes
https://github.com/PaulStoffregen/TimerOne/blob/master/TimerOne.h#L55

Defines the function in TimerOne called `SetPeriod()`. That will change the period.

# Answer
> 0 votes
I've found the solution, through the function

```
attachInterrupt(function,period);

```

inside

```
loop()

```

In other words, I wrote

```
loop(){
Timer1.attachInterrupt(function,period);
// rest of the code
}

```

where "period" changes inside the ISR called when the external button is pressed. Thanks a lot @jose can u c!!

---
Tags: arduino-uno, interrupt, timers
---


title: Neopixle animation help

text:
# Question
Title: Neopixle animation help
Ok I'm stupid when it comes to coding. I have a simple project that I need some help with. Is it possible to make neopixle change what animation runs via multiple switches. Example they stay off till switch is flipped then if a different switch is flipped they run a different animation and vice versa.

# Answer
Yes absolutely it is possible. As a beginner, I suggest something like this:

simulate this circuit – Schematic created using CircuitLab

In your `setup` you will need to declare D4 - D7 as inputs. I have used D4 - D7 but you can choose whatever pins are available.

Then in the `loop` part of the code you want to look for the rising edge on the input (ie when the switch is pressed). Switch debounce is less important for this application as it is not a counter but rather a mode change.

I have written a good answer for detecting a button press here.

Nick Gammon has an excellent switch tutorial gammon.com.au/switches that covers all kinds of conceivable situations (high or low, GND or +5V, internal pull-up or pull-down, capacitor debounce or software debounce, etc.)

I would imagine the code would look something like this:

```
if( digitalRead(SW1) == HIGH )
    mode = 1;

if( digitalRead(SW2) == HIGH )
    mode = 2;

if( digitalRead(SW3) == HIGH )
    mode = 3;

if( digitalRead(SW4) == HIGH )
    mode = 4;

```

You could then use a switch-case statement to run the various NeoPixel patterns.

For more programming reference see: https://www.arduino.cc/reference/en/
> 0 votes

---
Tags: programming
---


title: Code for a rolling average

text:
# Question
Title: Code for a rolling average
Below is some code I wrote to find the rolling average of a temp sensor hooked up to an arduino and display it to an lcd display. My issue is that for the first minute it is running, the average is not correct. It starts at 0 and then progresses up to where it should be (~85F) in increments of approximately 3. After the first minute it is fine and works as it should.

What I want the code to do is to simply take the average of the sum of the values that have been recorded in the first minute.

My knowledge of C is fairly limited(I only had a semester long class on it) so that is why it is simple. I am a mechanical engineering student and this code is for project at my internship.

```
#include <Adafruit_MLX90614.h>
Adafruit_MLX90614 tempSensor;

#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

Adafruit_MLX90614 mlx = Adafruit_MLX90614();

double array[30];
double rollingaverage=0;
int i=0, j=0;
double sum=0;
double newreading;
void setup() {

  Serial.begin(9600);
  lcd.begin(20,4);
  mlx.begin();
  Wire.begin();

}

void loop() {
  if(j=0){
      newreading = mlx.readObjectTempF();
      array[i] = newreading;
      sum += array[i];
      if(i>0){
          rollingaverage = sum/(i+1);
      }
      j=1;
  }
  else{
      newreading = mlx.readObjectTempF();
      array[i] = newreading;
      if(i < 29){ //wraps i back around to 0 if it is at 29 to subtract the oldest value
          sum = sum + array[i] - array[i+1];
          rollingaverage = sum/30;
      }
      else{
          sum = sum + array[i] - array[0];
          rollingaverage = sum/30;
          i=0; //reset index to 0
      }
  }
  i++;

  lcd.clear();
  lcd.print("Belt: "); lcd.print(rollingaverage);
  lcd.setCursor(1,2);
  lcd.print("Air: "); lcd.print(mlx.readAmbientTempF());

delay(2000);
}

```

Its not a huge deal because it works fine after the first minute, it is just annoying that I can't figure out why it doesn't work as intended in the first minute. Thanks

# Answer
Your problem stems from you starting out with 30 values of 0 which you include in your average. You have to take that into account and ignore those values, dividing your total by only the number of actual values you have.

I have a library that does it all for you that would make things easier for you:
> 2 votes

# Answer
One way is to initialize the whole buffer to the first value. Your average won't be "true" in some sense, until the whole buffer has been replaced with read data, but as long as that first value isn't too different from the true temperature, your average during that period will be more sensible. I.e., it won't have to ramp up from zero.

Another way is to use an Exponential Average instead of the Rolling- or Boxcar-Average. The Exponential Average doesn't depend on storing old samples and can adjust well - i.e. within a few samples, depending on 'X' (see below) - to a sudden change (which temperatures don't normally do, anyway).

It calculates a new average by summing X percent of the current average + (100-X) percent of the next sample - you choose the value of 'X' that works best in your own application. I have good results averaging temperatures, even from analog sensors, using X=75. For fixed-point numbers such as the 4 binary places returned by the Max DS18b20 sensors, would be

```
// (3 * avg + 1 * sample) / 4
avg = (((avg<<2) - avg + sample) + 2) >> 2;

```

For floating point numbers, it would just be:

```
avg = (3. * avg + sample)/4.;

```

Update:

> Initialization is as much an issue with an exponential average as it is with a boxcar average.

Yes, it is. I initialize my exponential averagers with the first sample and usually get along pretty well. It might not work so well if the averager was too heavily damped.

> ... a boxcar of width 30 ...

An exponential average, by its nature, can give recent samples more weight than older ones so giving so little weight as you suggest to the next sample will make it quite heavy-handed! X=75% has worked quite well *for me* to reduce noise without heavy-handed damping. What works well for one system may not work for another, but by running a saved sample-set through a few trials on your desktop will quickly get you to a reasonable X.

We don't know how that width (30) was arrived at; perhaps it is necessary? But averaging, by its nature, being both low-pass (usually desired) and delaying (generally not desired), spreads sudden features like spikes while it limits their amplitude. I've sometimes use a spike suppressor ahead of a lighter averaging filter, where the alternative average-only would have required enough averaging to damp significant signal features too heavily.
> 1 votes

# Answer
The other answers address the problem with your code, however a better solution is to use a different algorithm.

I would use exponential smoothing (which is simpler to code, requires less data and produces a similar result). This is the technique I used to use when responsible for producing statistical performance reports. If readings are plotted this results in a smoother graph, which shows trends and discounts noise.

Briefly take the current sample, multiply by a discounting factor and add the a proportion of the current value.

> s = x * α + (1-α) * s

To produce results from the start initialise the sample to the first reading then calculate.

See https://en.wikipedia.org/wiki/Exponential\_smoothing

I would probably start with a smoothing factor of 0.3 - choose a smaller value to give more weight to past values.
> 0 votes

---
Tags: c
---


# Question
Title: Powering Arduino Uno, CAN Crocodile and NeoPixels from Car
I have purchased a cigarette adapter that gives me 2 USB ports, however this gives me 5v and up to 2.4A.

Thats ok for powering the Arduino Uno, I need 12/24v to power the CAN crocodile.

I also want to drive quite a lot of NeoPixels.

How can I do this?

# Answer
A reasonable estimate for current consumption of 5V NeoPixels is 60mA per pixel. For 186 pixels, that means about 11.16A at 5V; well over the 2.4A of the adapter being used for your other components.

There exist modules called "DC-to-DC Buck Converters", which can step down the 12-14V of your automobile to pretty much any voltage under the input voltage. To be safe, look for a buck converter of at least a 75W rating, and which meets your criteria for input and output range (minimum of 12V input, could be rated higher; output range inclusive of 5V.)

Be sure that the Ground connections for the NeoPixel power supply and the other supply are shared/connected, but don't share the +5V line between supplies.
> 3 votes

---
Tags: arduino-uno, neopixel, can-bus
---


# Question
Title: Using AysncUDPMessage for ESP32 to send string data
I am in search for some examples as to how can one use the `AsyncUDPMessage` in an Application for sending out UDP packets to a host with specific IP address and Port number from an **ESP-WROOM-32** (Olimex ESP32-PoE) module?

The Class for AsyncUDPMessage in arduino-esp32 library inherits from `Print`.

I want to send sensor measurements to InfluxDB in the Line Protocol (InfluxDB specific).

### Example

```
 imu,location=front,nodeid=node1 status=0.00,liac_x=-1.18,liac_y=0.02,liac_z=9.63,eul_x=0.00,eul_y=-6.81,eul_z=0.25 1538507409930

```

The above mentioned example is stored in the form of a `String` and the methods to send information via UDP viz. `send()` `sendTo()` all mention usage of `AsyncUDPMessage` as the first parameter.

### goal

Send the above measurement to the particular Device's IP and port

```
udp.sendTo(Message, IPAddress(192,168,3,11), 8089);

```

I am currently using `broadcastTo(const char * data, port)` menthod to send information the InfluxDB instance.

### Code

```
void loop(void) {

  DateTime now_time = rtc.now();

 // create a measurement
  influxMeasurement row("imu");
  row.addTag("location", "front");
  row.addTag("nodeid", "node1");

// get information from BNO055
  imu::Vector<3> li_ac = bno.getVector(Adafruit_BNO055::VECTOR_ACCELEROMETER);
  imu::Vector<3> euler = bno.getVector(Adafruit_BNO055::VECTOR_EULER);
//  Serial.print(li_ac.x());
//  Serial.print(li_ac.y());
  row.addField("status", 0);
  row.addField("liac_x", li_ac.x());
  row.addField("liac_y", li_ac.y());
  row.addField("liac_z", li_ac.z());
  row.addField("eul_x", euler.x());
  row.addField("eul_y", euler.y());
  row.addField("eul_z", euler.z());

  // add timestamp
  row.addTimeStamp_ms(String(now_time.unixtime()) + String(millis()%1000));

  // print the Line Protocol output
  Serial.println(row.postString());

  // UDP Sending
  char buf[2048]; // make buffer for `broadcastTo()`
  row.postString().toCharArray(buf, sizeof(buf)); // string to char array
  // Serial.println(buf);
  udp.broadcastTo(buf ,8089);

  delay(100);
}

```

### method

I create a Line protocol `String`, make a buffer, convert the string to `char []` and send it out.

### Question

1. how do I use `AsyncUDPMessage` so I can pass the string to it directly?
2. I am not sure but will `char buf[2048]` within a `loop` is a good idea as every time a buffer allocation might make the ESP32 run out of memory? And if `AsyncUDPMessage` can avoid this concern?

# Answer
> 1 votes
Use `udp.print(row.postString().c_str())`

AsyncUDPMessage in AsyncUDP library is only a buffer. It is used only in AsyncUDP send function:

```
size_t AsyncUDPPacket::send(AsyncUDPMessage &message)
{
    return write(message.data(), message.length());
}

```

---
Tags: ethernet, networking, esp32
---


# Question
Title: Interfacing 4 ESCs and an Arduino with a single LiPo battery
I have 4 BLDC motors, and 4 ESCs, one for each motor. But I have one LiPo battery from which I want to power one Arduino Mega and all the 4 ESCs. Can I remove the connectors from the ESCs and put them on a breadboard in a single column/row so that they are connected together, and then connect the + and - of the battery (after removing its connector as well) to the respective breadboard column/row, so that they are essentially connected together to power all the ESCs? Also, I would want to use a jumper from the Arduino Vin and GND pins to the same column/row on the breadboard. Will this method of powering all the 4 ESCs and the Arduino from a single LiPo work?

# Answer
> 1 votes
Powering all the ESCs from a single LIPO is not an issue.

Using a breadboard to distribute this power is highly unlikely to work, breadboard connectors are usually only good to a few hundred mA, 1A is you want to push your luck. Most ESCs and BLDC motors are in the 5A to 50A range (each, your power bus has to handle 4 times this current).

Also, ESCs tend to inject a lot of noise into the power bus. If you connect the arduino to the ESC power bus, you will likely get random resets and really poor noise performance on the ADCs. Keep in mind that some ESCs actively brake the motors using regenerative braking, which puts the kinetic energy of the motor back into the power bus. This can increase the voltage on the power bus to more than the nominal battery voltage and can have large voltage spikes on it causing a failure on the Arduino.

If you are prototyping, use a separate power supply/battery for the arduino and connect all the grounds together instead of using a single supply. If you are building a rover/uav/whatever and don't want a second battery, use a high quality BEC (or the BEC output from a high quality ESC) and remember that the 5V output on a BEC/ESC can be significantly higher than 5V in reality).

ESC = Electronic Speed Controlled BEC = Battery eliminator circuit (I think, basically a 5V-ish regulator) BLDC = Brushless DC motor (three phase in this case)

---
Tags: arduino-mega, power, lipo
---


# Question
Title: Unexpected result with the GSM module A6
I have a **GSM A6** module, like this one.

I'm going to use an **Arduino Nano** as a *bridge* to communicate with it, I have an external power source (since I read that this module can consume up to 2A at its maximum consumption) (this power supply shares the GND with the module and the Arduino) and I upload the following code in the **Nano**:

```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11);

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and A6
  mySerial.begin(115200);

  Serial.println("Initializing...");
  delay(1000);

}

void loop()
{
  updateSerial();
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

```

I set the **baud rate** at **115200** of my SoftwareSerial port (connected to 10 and 11 pins on the ArduinoNano) because (even if the module says that it has auto-detect speed hability) doesn't work if I set the speed at **9600** (or **any other**), and I modified the SoftwareSerial library for expand the buffer from *64k* to *512k* (trying to solve this problem) following this page instructions (also: NICE WORK in this page!!!).

And it works ... it works relatively well, I mean: The **AT** commands to test (according to the datasheet itself) are **AT** and **ATI** (in one I recieve "*AT /r OK*" and the last one give some usefull information like the OS and other things), and they work, only they do not show me the same answer always, I leave screenshots:

As you can see, the answers are not always **exact**, there is some garbage characters, and I **need** them to be **exact**, because my idea is to create a kind of alarm, in which the Arduino (One, Nano or Mega) sends and receives AT commands. I worked with the SIM900 module before and always received the same answer when I sent an AT command.

So... any help?!

# Answer
Apparently the SoftwareSerial library have some limitations, so I change the baudrate communication in the moduel ussing this sentence:

> AT+IPR=9600

And change the code that I upload to the Nano, changing the baudrate speed in the declaration, from:

```
mySerial.begin(115200);

```

to

```
mySerial.begin(9600);

```

And now all is well :D
> 1 votes

---
Tags: gsm, softwareserial
---


# Question
Title: How do I run a bipolar motor with an arduino uno?
At the risk of looking like a complete idiot on the internet, I'll preface with this; I'm incredibly new to this. I'm new even to coding, and not sure what questions I should be asking.

I'm trying to run a bipolar motor with an Arduino Uno. I'm fairly sure it should be as simple as set a pin to high, plug the motor into that pin and a ground and it should run. I did this a week ago, and it worked then.

Now I'm trying to essentially run a modified version of blink with this motor running instead of the LED. Running the code with pin 13 as my positive does still flash the LED. If I set my pin to high with the motor, the motor no longer runs. However, It does run when plugged into the 5V and ground. The motor also runs straight off of the two poles of a 9V battery.

I'm unsure what I'm doing wrong. Do I need to step up the voltage of my pins somehow?

Thanks in advance. -Alec Rosso

Edit 1:Here's the code:

```
int motorPin1 = 13;
int interval= 5000;

void setup() {
pinMode(motorPin1, OUTPUT);
digitalWrite(motorPin1, HIGH);
}

void loop() {
digitalWrite(motorPin1, HIGH);
delay(interval);
digitalWrite(motorPin1, LOW);
delay(interval);
}

```

As far as voltage or current specifications, it says DC 12V.

Edit 2: it is not a stepper motor. The serial number is TS-32GZ370-950. It's apparently a "DC geared motor."

Final Edit: I've got it working using an L298. I used a 9-volt battery in addition to my arduino's 5 volts, and everything works like a dream. Thank you for your help.

# Answer
Just for your knowledge and future reference - Arduino digital pins can deliver maximum of 40mA each. If you power Arduino by USB, Arduino UNO can draw maximum of 1A, and Nano maximum of 500mA. That is, the 5V pin can deliver that current, not a digital pin. Therefore pin 13(digital pin) can deliver 40mA at 5V, which is 200mW power.

Now, looking at your motor, TS-32GZ370-950,from datasheet at maximum efficiency the current needed is 140mA. Stall current is 480mA, therefore you should be able to deliver close to 480mA @ 12V for the motor to work under all possible loads. Now, that is 5.6W or so. Your 5V pin making the motor work simply meant that the load is low to medium. But you are unable to use the motor's full potential anyway.

Your driver choice is ok, because L298 can deliver up to 2 A, which is fine. The 9V battery(Alkaline I suppose?) will work, but the lifespan will be very very short. You can look at discharge graphs here : https://www.powerstream.com/9V-Alkaline-tests.htm

It will last about 1 hour at moderate load. Consider using other types of batteries. Your motor accepts voltage up until 24V, so feel free to experiment.

Best of luck!
> 1 votes

# Answer
"At the risk of looking like a complete idiot on the internet,"

Without getting personal - you cannot put 10 pounds of potatoes in 5 pounds bag.

AKA you cannot run 12V device with (5V output) Arduino BECAUSE 12V device / motor requires far more current than Arduino can safely provide.

That is the short version - you probably moved the motor at very slow speed and lucked out before you let the smoke out from the Arduino chip.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: limit length of the generated timestamp from ESP32 with DS3231 to 13
I am using **ESP-WROOM-32** (Olimex ESP32-PoE) with **DS3231**. I have used the a patch from PR on RTClib to avoid the rollover from the DS3231.

Since the DS3231 RTC provides Unix Epoch Timestamps which have a precision of only seconds, I wish to concatenate the `millis()` to the above mentioned timestamps to provide millisecond precision.

This is critical since I want to store information to InfluxDB from the nodes with ms precision. **For that the timestamps should always be 13 digits**.

## code

```
#include <RTClib.h>
#include <Wire.h>

// PoE setting for Olimex PoE board

#define ETH_CLK_MODE ETH_CLOCK_GPIO17_OUT
#define ETH_PHY_POWER 12

// Pins for I2C on Olimex PoE board
#define I2C_SDA 13
#define I2C_SCL 16

RTC_DS3231 rtc;
RTC_Millis software_time;

void setup() {
  // put your setup code here, to run once:
  Wire.begin(I2C_SDA, I2C_SCL, 400000);
  Serial.begin(9600);
  if (!rtc.begin()) {
    Serial.println("No RTC Detected");
  }
  // adjust RTC Time
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  // adjust software timer
  software_time.adjust(rtc.now());

}

void loop() {
  // put your main code here, to run repeatedly:
  DateTime rtc_now_time = rtc.now();
  DateTime software_now_time = software_time.now();
  Serial.println();
  Serial.print("RTC now: "); Serial.print(rtc_now_time.unixtime());
  Serial.println();
  Serial.print("millis: "); Serial.print(millis());
  delay(100);

}

```

## Output

```
RTC now: 1538502183
millis: 28
RTC now: 1538502183
millis: 128
RTC now: 1538502183
millis: 228
RTC now: 1538502183
millis: 328
RTC now: 1538502183
millis: 428
RTC now: 1538502183
millis: 528
RTC now: 1538502183
millis: 628
RTC now: 1538502183
millis: 728
RTC now: 1538502183
millis: 828
RTC now: 1538502183
millis: 928
RTC now: 1538502184
millis: 1028

```

I will store the timestamps in `String` so I was thinking of concatenating the `.unixtime()` with `millis()`. However since I want all my timestamps to be of fixed lenght (13) with the increasing `millis` value seems to be difficult because as soon as the number goes more that `999` the a digit increases making the string length 14.

**Side Effect**

if the timestamps for ms do not match length of 13, InfluxDB rejects the data passed through

**Epoch Time**

the output provided above is of 10 digits which is the epoch time since 1970. The precision of the timestamps above is of seconds. If one wants to add milliseconds to it one needs to add 3 more digits behind it. If precision needs to be `microseconds` it should have 6 digits and so on.. One can check the timestamps above on \[https://epochconverter.com\]

Any suggestions on overcoming this issue ?

# Answer
For getting millisecond resolution out of an RTC, I think the only viable solution is to sync with the 1 Hz square wave output, as suggested by Jot in a comment. Note that, since you are only counting seconds and milliseconds, you probably don't care about hours, minutes, days, months, etc. So you won't use the RTC for timekeeping: only for providing the 1 Hz reference signal and, maybe, an initial timestamp at program startup.

Connect the SQW pin of the DS3231 to an interrupt-capable input of your MCU. Add the following to your `setup()`:

```
pinMode(SQW_PIN, INPUT_PULLUP);
rtc.writeSqwPinMode(DS3231_SquareWave1Hz);
attachInterrupt(digitalPinToInterrupt(SQW_PIN), tick, FALLING);

```

Use the interrupt routine to both keep track of the total second count (seconds elapsed since the Unix epoch) and record the `micros()` value of the last tick:

```
volatile uint32_t seconds_since_epoch;
volatile uint32_t micros_on_tick;

void tick() {
    seconds_since_epoch++;
    micros_on_tick = micros();
}

```

Now you can combine these two values to get a millisecond-resolved timestamp as follows:

```
uint64_t millis_since_epoch() {
    noInterrupts();
    uint32_t seconds = seconds_since_epoch;
    uint32_t microseconds = micros_on_tick;
    interrupts();
    uint32_t extra_micros = micros() - microseconds;
    uint16_t extra_millis = extra_micros / 1000;
    if (extra_millis > 999)
        extra_millis = 999;
    return (uint64_t) seconds * 1000 + extra_millis;
}

```

The value returned from this function is the 13-digit number you want, provided `seconds_since_epoch` has been sensibly initialized.
> 1 votes

# Answer
the goal is to generate unique and ordered millis part of timestamps in one epoch second.

```
unsigned long thisNowMillis;
uint32_t thisNow;

```

-

```
 uint32_t now = rtc_now_time.unixtime();
 if (now != thisNow) {
   thisNow = now;
   thisNowMillis = millis();
 }
 Serial.print("millis: "); Serial.print(millis() - thisNowMillis);

```

not tested and it will not work for counting intervals between timestamps.
> 0 votes

---
Tags: rtc, esp32
---


title: Arduino Hello World in Serial monitor

text:
# Question
Title: Arduino Hello World in Serial monitor
Hi we were asked to program something which when i enter something in the serial monitor it prints Hello world but the catch is it only prints hello world under the conditions that your input in the serial monitor is a 3 bit input and after that i need to have a code which then stops it from printing over and over again. my only problem is that i don't really know how to count the number of bits of an input and also to stop it from printing continuously.

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

}

void loop() {
  String readSerial;
    String input;
    while(Serial.available() > 0){// put your main code here, to run repeatedly:
    delay(2);
  input.concat(String((char)Serial.read()));
  return input;
  }
  Serial.println("HELLO WORLD");
}

```

# Answer
> 3 votes
Judging from the comments, you lag some basic knowledge. To really learn, what you are supposed to learn in this assignment, you should review your learning material or C/C++ and Arduino Tutorials on the web. Here I will only give you some hints with reasoning, that may help you in solving the assignments task. (Unfortunately it is not really clear, what exactly the task is here)

* The `Serial` interface of the Arduino (an UART interface) sends the data in bytes, one at a time and one after another (hence the name `serial`). 1 byte is a series of 8 bits, each of them with a value of 1 or 0. Together the 8 bits form a value, that can also be expressed as a decimal value from 0 to 255. For example `01001011` is the binary equivalent of the decimal number 75. (For further explanations google the binary number system) The byte data can also be expressed as characters, as they are defined in the ASCII standard. Every binary value refers to a specific character. This is what happens in the serial monitor of the Arduino IDE. (For more explanations google ASCII)
* Since the data is send serially, there may appear some delays in the transmission, which are unnoticeable by humans, but the Arduino is fast enough, so that the `Serial.available()` command may return 0, because at that moment a little delay in the transmission occurred. Hence it is important to catch the whole message, before trying to work with it. You can do this by either counting bytes (waiting until at least 3 bytes are available in the buffer) or by marking the end of the message with a special character (for example the newline character '\n'). There are a lot of tutorials on the web how to do both. You can start with Majenko's blog.
* You can get the number of bytes, that were received, with the return value of `Serial.available()`. It will return 3, when there are 3 ready to be read bytes in the buffer.
* If you define a variable inside the `void loop()`, it will be thrown away when the function ends and redefined, when the function starts again (In the Arduino world the `void loop()` function is called again and again forever). You will loose all content, that was written to this variable. If you want to persist data over the executions of the `void loop()` function, you can define the variable outside of any function at the top of your program. This variable is then global and will be defined only once at the start of the program and hold for the whole lifetime of the program.
* As wrote in the comment you should not return a value from a `void` function, since `void` mostly means, that there is no return value. And returning from the `void loop()` function will only restart this function (since we are in the Arduino world).
* You can ditch the `delay(2)`. There is no need for it. And if it only works with the delay, then something else is not correct and you are just working with the symptoms instead with the real issue.

Also you should not try to build everything on your own and reinvent the wheel. Instead try to look at the examples, that come with the Arduino IDE. For example the `SerialEvent` example, which shows how to receive a serial message (which is ended by a newline character '\n'). Also have a look at the other related examples. If you understand, how they work, you will be able to do the assignment without any problem.

# Answer
> 1 votes
Assuming that the sketch should print "Hello World" when the input character has 3 bits high. Here are a few different variants of counting the number of bits set in a byte.

```
int bits1(int c) {
  int res = 0;
  for (int i = 0; i < 8; i++) {
    if ((1 << i) & c) res = res + 1;
  }
  return (res);
}

int bits2(int c) {
  int m = 0x80;
  int res = 0;
  do {
    if (m & c) res++;
  } while (m >>= 1);
  return (res);
}

int bits3(int c) {
  int m = 0x80;
  int res = 0;
  do {
    res += (m & c) != 0;
  } while (m >>= 1);
  return (res);
}

#define bits4(c) __builtin_popcount(c)

#define bits bits4

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

void loop() {
  if (Serial.available() > 0) {
    int c = Serial.read();
    if (bits(c) == 3) {
      Serial.print((char) c);
      Serial.print(':');
      Serial.print(c, BIN);
      Serial.println(": Hello World");
    }
  }
}

```

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


# Question
Title: HTTP POST/ METHOD to Emoncms doesn't work
So Ive setup the emoncms on my server and posted the example power1:100…power3:300 JSON POST and it logged in my INPUTS. Now Im trying to send data from my arduino and it seems to post fine, but when I go to the INPUTS its not there for some reason.

Here is my code. Im just posting a temperature value to a new node:

```
#include "SoftwareSerial.h"
//For DHT22 Grove Pro
#include "DHT.h"
#define DHTPIN A1     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE);

String ssid ="myssid";
String password="mypassword";
String server = "www.santiapps.com"; // www.example.com
String uri = "/emoncms/input/post.json";// our example is /esppost.php
#define EMON_APIKEY F("myapikey")

byte dat [5];
String temp ,hum;
String data;
char dataString[200];

SoftwareSerial esp(6, 7);// RX, TX

void setup() {
  esp.begin(9600);
  Serial.begin(9600);
  Serial.println("setup");
  reset();
  connectWifi();
}

void reset() {
  Serial.println("reset");
  esp.println("AT+RST");
  delay(1000);
  if(esp.find("OK") ) Serial.println("Module Reset");
}

void connectWifi() {
  Serial.println("connect to wifi");
  String cmd = "AT+CWJAP=\"" +ssid+"\",\"" + password + "\"";
  esp.println(cmd);
  delay(400);
  while (esp.available()){
     String inData = esp.readStringUntil('\n');
     Serial.println("Got reponse from ESP8266: " + inData);
  }

  if(esp.find("OK")) {
    Serial.println("Connected!");
  } else {
    connectWifi();
    Serial.println("Cannot connect to wifi"); }
}

void start_test () {
  //For DHT22 Grove Pro
  static char outstr1[15];
  static char outstr2[15];
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  dtostrf(t, 8, 2, dataString);
  Serial.println(dataString);
}
void loop(){
  Serial.println("loop");
  start_test();
  httppost();
  delay(100000);
}

void httppost () {
  esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");//start a TCP connection.
  if( esp.find("OK")) {
    Serial.println("TCP connection ready");
  }
  delay(1000);
  String postRequest="POST " + uri + " HTTP/1.0\r\n"+"Host: " + server + "\r\n" + "Accept: *" + "/" + "*\r\n"+"Content-Length: " + strlen(dataString) + "\r\n" + "Content-Type: application/x-www-form-urlencoded\r\n"+"\r\n" + "&node=fortnite&data={a:" + dataString + "}" + "&apikey=" + EMON_APIKEY;
  Serial.println(postRequest);
  String sendCmd = "AT+CIPSEND=";//determine the number of caracters to be sent.
  esp.print(sendCmd);
  esp.println(postRequest.length());
  delay(500);
  if(esp.find(">")) {
    Serial.println("Sending..");
    esp.print(postRequest);
    if(esp.find("SEND OK")) {
      Serial.println("Packet sent");
      while (esp.available()) {
        String tmpResp = esp.readString();
        Serial.println(tmpResp);
      }
      // close the connection
      esp.println("AT+CIPCLOSE");
    }
  }
}

```

Here is my Serial Monitor:

```
setup
reset
connect to wifi
Got reponse from ESP8266: AT+CWsetup
reset
Module Reset
connect to wifi
Got reponse from ESP8266:
Got reponse from ESP8266: CLOSED
Got reponse from ESP8266: WIFI DISCONNECT
Got reponse from ESP8266: `BԄQR���ȤRN�ɤRN�H��OAT+CWJAP="tha
connect to wifi
Got reponse from ESP8266: %J:E
Got reponse from ESP8266: HըRP=“myssid”,“mypassword”
Got reponse from ESP8266: busy p…
connect to wifi
Got reponse from ESP8266: AT+CWJAP=“myssid”,“mypassword”
Got reponse from ESP8266: busy p…
Got reponse from ESP8266:
Got reponse from ESP8266: O
connect to wifi
Got reponse from ESP8266: AT+CWJAP=“myssid”,“mypassword”
Got reponse from ESP8266: WIFI DISCONNEC
Connected!
Cannot connect to wifi
Cannot connect to wifi
Cannot connect to wifi
loop
31.00
TCP connection ready
POST /emoncms/input/post.json HTTP/1.0
Host: www.myserver.com
Accept: /
Content-Length: 8
Content-Type: application/x-www-form-urlencoded
    &node=fortnite&data={a:   31.00}&apikey=mykey
    Sending..
    Packet sent

    +IPD,422:HTTP/1.1 200 OK
    Server: nginx
    Date: Tue, 02 Oct 2018 21:38:18 GMT
    Content-Type: application/json
    Connection: close
    X-Powered-By: PHP/5.4.16
    Expires: Thu, 19 Nov 1981 08:52:00 GMT
    Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
    Pragm

```

Here is a snapshot of the posted data when I used this URL directly in my browser:  http://santiapps.com/emoncms/input/post?node=emontx&fulljson={"power1":100,"power2":200,"power3":300}&apikey=mykey

￼=========

# Based on jose's suggestion:

I changed this code to:

```
void httppost () {
  esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");//start a TCP connection.
  if( esp.find("OK")) {
    Serial.println("TCP connection ready");
  }

//  //CODE USED TO BUILD COMPLETE STRING
  String apiKeyString="apikey=";
  apiKeyString.concat(EMON_APIKEY); //JOIN PARAMETER LITERAL STRING => String Object
  //Serial.println(apiKeyString); //THIS IS NOW A STRING OBJECT
  String nodeData="&node=fortnite&data={\"a\":";
  String combinado=apiKeyString+nodeData; //COMBINE BOTH PREVIOUS STRING OBJECTS
  String finalData=combinado + dataString + "}"; //COMBINE STRING OBJECT WITH CHAR[]
  Serial.println("finalData");
  Serial.println(finalData);
  //unsigned int tamano = strlen(dataString);
//  char postThis[100] = finalData;
//  //ADDING THIS TO POSTREQUEST +finalData; && changing length for strlen(finalData)

  delay(1000);
  String postRequest="POST " + uri + " HTTP/1.1\r\n"+"Host: " + server + "\r\n" + "Accept: *" + "/" + "*\r\n"+"Content-Length: " + finalData.length() + "\r\n" + "Content-Type: application/x-www-form-urlencoded\r\n"+"\r\n" + finalData;
  Serial.println("postRequest");
  Serial.println(postRequest);
  String sendCmd = "AT+CIPSEND=";//determine the number of caracters to be sent.

```

but now I dont even get the HTTP200OK response. The result is:

```
loop
31.30
finalData
apikey=myKey&node=fortnite&data={"a":31.30}
postRequest

```

# Answer
> 2 votes
Your Serial monitor output shows the content of the POST as:

`&node=fortnite&data={a: 31.00}&apikey=mykey`

I can't tell if the `&` are actually in your serial monitor, or if your copy/paste did some kind of HTML format attempt, but `&` is wrong and should be `&`

Your JSON data is not proper JSON

`{a: 31.00}`

should be

`{"a": 31.00}`

---

Strangely, your serial monitor output also writes `Host: www.myserver.com`, which doesn't match your code, where `server` was assigned `www.santiapps.com`, so that makes it difficult to trust that the serial output you show actually came from the code.

---
Tags: esp8266, arduino-nano
---


# Question
Title: backup battery for FeatherWing DS3231, RTC
I am working with slightly modified example code for the Adafruit FeatherWing DS3231 RTC (real time clock) board. The DS3231 chip itself is from Maxim. Since the cell is described as a "backup battery" a literal interpretation suggests that you don't need the backup battery in order to operate the board if the board itself is powered and you don't mind that the device cannot remember the time when board power is lost. I might be taking the term "backup battery" too literally since it doesn't seem to work.

The Adafruit (Arduino) code:

```
> #include <Wire.h>
> #include "RTClib.h"
> RTC_DS3231 rtc;
> void loop()
>{
>     rtc.adjust(DateTime(2018, 1, 1, 0, 0, 0));
>     DateTime now = rtc.now();
>     Serial.print(now.year());
>     Serial.print(" ");
>     Serial.print(now.month());
>     Serial.print(" ");
>     Serial.print(now.day());
>}

```

The output is:

```
2165 165 165

```

The Maxim datasheet says this about the VBAT line which is the line between the DS3231 chip and the missing backup battery:

> Backup Power-Supply Input. When using the device with the VBAT input as the primary power source, this pin should be decoupled using a 0.1μF to 1.0μF low-leakage capacitor. When using the device with the VBAT input as the backup power source, the capacitor is not required. If VBAT is not used, connect to ground.

So I connected it to ground and it makes no difference. I can't buy a battery until tomorrow morning. Can somebody please confirm that the backup battery is actually essential. **EDIT**: I installed a battery and it makes no difference.

Aside: A good reason for not having a backup battery if possible is to have fewer user serviceable parts.

# Answer
The problem was a bad connection for one of the serial lines.

I found the solution at this link.

The battery is not necessary to make this work.
> 1 votes

# Answer
Your code does not include the line(s) necessary to initialise the rtc.

in setup, you need something like

```
rtc.begin()

```

If you've followed the instructions from the Adafruit website for installing the RTC library:

* Start Arduino IDE
* File-\>Examples-\>RTClib-\>ds3231

This will open the RTC usage example.

Else, go to the example on the Adafruit Github page

look to the setup() code and see how they initialise the device
> 0 votes

# Answer
Assuming your code is in Arduino IDE "loop". Assuming

> rtc.adjust(DateTime(2018, 1, 1, 0, 0, 0)); initializes the rtc.

Your code should be continually printing the rtc.adjust value.

Hence move the rtc.djust out of the "loop" and provide some kind of delay , say 1 second, to print rtc every second. Then we can take a look why your are getting wrong data.
> 0 votes

---
Tags: adafruit, battery, rtc
---


title: PWM of a frequency signal?

text:
# Question
Title: PWM of a frequency signal?
Working on my first real sketch, so will try to keep this short. Feel free to ask more info if needed.

To power a flyback transformer I need to apply PWM -to- a PWM signal. The easiest way to describe this is that while a standard PWM signal is 'on' for some set time, then 'off' for the remainder of the period, I need to send a signal where the 'on' is actually a 14kHz square wave of 50% duty...then pulse this signal ~1 to 100% duty at ~500Hz.

No problem with the 14kHz PWM - I found the PWM.h library and set that up.

But what is the best way to chop that up with a second PWM at, say 500Hz?

With some amount of kludge, can I 'bit bang' it with DO - WHILE? Will WHILE read a variable outside the loop? Are there easier ways?

```
i=1;
do {                                //Pulse microsecond 'frames' of high freq signal?
                                    //ie 14kHz carrier PWM'd at 500Hz = 2000 microseconds per 'frame' cycle
                                    //at 50% duty would be 1000 micros high and 1000 micros low

    pwmWrite( outpin, 128 );        //Turn on 14kHz carrier at 50% duty
    delayMicroseconds(1000);        //Delay to generate the 'HIGH' portion of the frame
    pwmWrite( outpin, 0 );          //Turn 14kHz carrier off
    delayMicroseconds(1000);        //Delay to generate the 'LOW' portion of the frame
   } while (i == 1);                //...and keep doing loop while the state is '1' or 'ON'

delay(1000);                        //?Will this allow the above loop  to repeat while waiting here for 1 second?
i=0;                                //i != 1, so break out of the while loop above?
                                    //then continue doing other stuff below...

```

Any help greatly appreciated.

# Answer
On an Arduino Mega (or an Uno with the ATmega328P replaced with an ATmega328PB, but then you'd have to adapt the code slightly), this can be done via the output compare modulator:

```
void setup() {
  // CTC, OC0A toggle on compare match, prescale 1/8
  TCCR0A = _BV(COM0A0)|_BV(WGM01);
  TCCR0B = _BV(CS01);

  // toggle every 35.5 μs at 16 MHz and 1/8 prescale
  OCR0A = 70;

  // phase and frequency correct PWM, TOP is OCR1A, OC1C clear going up and set going down, no prescale
  TCCR1A = _BV(COM1C1)|_BV(WGM10);
  TCCR1B = _BV(WGM13)|_BV(CS10);

  // period of 2 ms at 16 MHz and no prescale
  OCR1A = 16000;

  // on-time of 1 ms at 16 MHz and no prescale
  OCR1C = 8000;

  // no interrupts from the timers
  TIMSK0 = 0;
  TIMSK1 = 0;

  // only output a 1 when both timers are outputting a 1
  PORTB &= ~_BV(PORTB7);

  // halt the timers and reset the prescaler
  GTCCR |= _BV(TSM);
  GTCCR |= _BV(PSRSYNC);

  // reset both timers
  TCNT0 = 0;
  TCNT1 = 0;

  // enable output
  DDRB |= _BV(DDB7);

  // let the timers run
  GTCCR &= ~_BV(TSM);
}

void loop() {
  // Just adjust the frequencies and duty cycle as required here.
  // Everything is handled by the hardware and takes effect immediately upon writing to the register.
  // OCR1A: the desired period of the slower signal, in 8ths of microseconds. Can be up to 65535.
  // OCR1C: the desired on-time of the slower signal, in 8ths of microseconds. Can be up to 65535.
  // OCR0A: 1 less than the desired period of the faster signal, in microseconds. Can be up to 255.
  // The on-time of the faster signal is always half of the period.
  // If necessary, you can trade precision for more range for any of the above values by adjusting the prescaler.
}

```

With that sketch, pin 13 on the Mega will have the desired waveform. There's two big advantages to this method. First, it doesn't require any CPU resources at all (no loops or interrupts) once it's set up, so you can dedicate all of `loop` to reading the potentiometer and adjusting the duty cycle without worrying about glitches in the output. Second, being entirely hardware controlled means its output will be accurate and perfectly consistent (the 500 Hz component is perfect, and the 14 kHz component is approximately 14085 Hz). The one disadvantage, though, is that `millis` and everything else in the Arduino library that uses timers internally won't work quite right, since we're using the same hardware timers that they depend on.
> 4 votes

# Answer
Your 14kHz carrier can be generated by the `tone()` function that is part of the Arduino core. You can then use the TimerOne library to toggle the tone on and off.

Here is an untested sample sketch demonstrating the usage:

```
#include <TimerOne.h>

const uint8_t outpin=4;

void setup() {
  // put your setup code here, to run once:
  pinMode(outpin, OUTPUT);
  Timer1.initialize(1000);  // 1000 microseconds per half-cycle
  Timer1.attachInterrupt(toggleCarrier);
}

void loop() {
  // put your main code here, to run repeatedly:

}

void toggleCarrier() {
  static uint8_t isPlaying;
  if (isPlaying) {
    noTone(outpin);
    isPlaying=0;
  } else {
    tone(outpin, 14000);
    isPlaying=1;
  }
}

```
> 3 votes

---
Tags: pwm
---


# Question
Title: How do you use the plastic cover/case that came with Arduino?
They have holes for screw on, on top of the holes on the Arduino itself. Where can I find parts that are compatible with this case/cover? What was the intended use of this case/cover? Thanks.

# Answer
The cover was developed for Arduinos with on-board Ethernet with POE and similar cover has the Ethernet shield with POE. POE - power over Ethernet is 48 V, so it is better to not to touch a soldering point with this voltage.

The arduino.org boards were sold with this cover. Some of them had on-board esp8266 and soldering points leading to esp8266 sensitive pins. Again, better not to touch.

I used the cover to attach the Arduino to a DIN rail over a DIN rail clip.
> 1 votes

---
Tags: arduino-uno, shields, hardware
---


# Question
Title: Serial communication between an Uno and an Esplora by connecting their usb ports together
I’m trying to send a character message from an arduino uno to an esplora by connecting their usb ports together. The esplora has a micro usb port, while the uno uses a usb B port. To hooked them up, I connected a micro usb to usb A cable to a usb A to usb B cable using a female to female usb A connector. I even hooked up the uno and esplora grounds together. But the two boards just don’t seem to communicate. Ordinarily when hooking up the esplora to my computer, the tx light flashes whenever sending the message and the message appears as expected on the serial monitor. I’ve also tested sending character messages from the computer to the uno and they seem to be read as expected. But when connecting the esplora to the uno without going through the computer, those tx lights on the esplora do not seem light up at all and the uno rx lights don’t flash either.

Any idea what could be the issue here?

# Answer
> 1 votes
It will not work. USB communication is master/slave. There must be a 'host' and a 'device'. Uno and Esplora are two 'devices'.

Connect the boards over TTL Serial. Wire Rx and TX pins together, TX to RX and RX to TX. And ground of course.

`Serial` on Esplora is the USB interface. In 'core' I see the Esplora has a second serial interface called `Serial1`. According to schematics, the RX and TX pin of `Serial1` on Esplora are on LCD header as DC\_LCD (RX) and RESET\_LCD (TX). Use this `Serial1` to communicate with Uno.

On Uno side you should disconnect the Uno from computer to not disturb the Serial interface with USB connection. Or use SoftwareSerial to communicate with Esplora and have debug prints to Serial Monitor.

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


title: MKR Fox 1200 doesn't wake up from sleep

text:
# Question
Title: MKR Fox 1200 doesn't wake up from sleep
I have a Sigfox Arduino meassuring some sensors, sending it to the cloud and then falling asleep.

```
void setup()
{
Serial.begin(9600);
  while (!Serial) {};
  if (!SigFox.begin()) {
    Serial.println("Shield error or not present!");
    return;
  }
  SigFox.debug();
  delay(100);
  SigFox.end();
}

void loop()
{
SigFox.begin();
  delay(100);
  SigFox.status();
  delay(1);
  SigFox.beginPacket();
  SigFox.print("123456789012");
  int ret = SigFox.endPacket(true);

  if (ret > 0) {
    Serial.println("No transmission");
  } else {
    Serial.println("Transmission ok");
  }
  Serial.println();
  SigFox.end();
LowPower.sleep(20000);
}

```

The Issue I have is that the sending to the backend doesn't work when leaving the sigfox.debug() away and that it doesn't wake up from the sleep. It stays in sleep forever.

# Answer
Looks like same problem as described in https://forum.arduino.cc/index.php?topic=483636.0 Solution described in that thread: Add

```
LowPower.attachInterruptWakeup(RTC_ALARM_WAKEUP, alarmEvent0, CHANGE);

```

to setup() and create a dummy function

```
void alarmEvent0() {
}

```
> 1 votes

---
Tags: sleep
---


title: Dimming multiple leds with pot meter

text:
# Question
Title: Dimming multiple leds with pot meter
I'm working on a small project. I have 13 leds which need to be controlled individually (turn on or turn off); Since I don't have 13 pwm pins I used a potentiometer to change the brightness.

This works fine for as long as all of the leds stay in the state they are. But once one led turns on or off it affects the brightness of all other leds.

In the picture below you can see how I did connect them. I have the analog pins A0, A1, A2 and A3 occupied by some buttons.

Does anyone know how I can dim the leds in a way where the leds themselves don't affect the brightness?

(note: I am a programmer and not so much of an electrical engineer. Code-related answers are (usually) easy for me to understand. ones about the hardware are not.);

# Answer
> -1 votes
Read the pot with analogRead(). Do not connect it to the LEDs at all, just 5v, Gnd and wiper to A5 (any of the analog input pins). LEDs just go from resistor on one leg to Gnd on the other (or 5V, depends on whether anode or cathode is connected to the resistor).

Then use software PWM to control the LEDs.

For example:

```
byte potPin = A5;
int potValue;
byte ledPin[] = {2,3,4,5,6,7,8,9,10,11,12,13,14};
byte x;

void setup(){
  for (x=0; x<13; x=x+1){
  pinMode (ledPin[x], OUTPUT);
  }
}
void loop(){
potvalue = analogRead (potPin); // 0 to 1023 value
for (x = 0; x<13; x=x+1){
  digitalWrite (ledPin[x], HIGH);
  delayMicroseconds(potValue);
  // 0 = max brightness, 1023 (1.023mS) will be dimmest
  // manipulate potValue if 1023 is not dim enough - double it, triple it, etc.
  digitalWrite (ledPin[x], LOW);
  delayMicroseconds(potValue);
  }
 }

```

From here, you can play with other setups for controlling the brightness.

---
Tags: led, potentiometer
---


# Question
Title: How to connect 2 Arduino Unos when one has a TFT LCD display attached to it?
I have to make a school project involving an Arduino Uno with a 2.8" TFT LCD touch screen display. in my project, i have to connect it such that the display is linked to a LED push button that receive inputs and react accordingly, as well as a speaker. However, my TFT LCD display fits perfectly into my Arduino Uno meaning i have no more input slots to connect to my push buttons nor my speaker. initially i found a different TFT display that came with an Arduino Shield that made life simplier however those products were not being shipped to my country:(

i am unable to use an Arduino Mega either since the SD socker in my TFT LCD display does not support the Arduino Mega. i understand in order to have my tft lcd display and my LED buttons and speaker to work i can have 2 Arduino Unos and have them work in Master-Slave however i would still need to have a common ground for both arduinos first and connect them which i am unable to do so since there's simply no way i can fit a jumper cable in there once i place my tft lcd display on the arduino uno. Please help guys:(

# Answer
> 0 votes
You can put a screw shield between the TFT shield and the Arduino to make access to the unused pins easier. You can see an example of a board I offer at www.crossroadsfencing.com/BobuinoRev17/ We have been able to ship to any country to date.

---
Tags: arduino-uno, lcd, tft
---


# Question
Title: How to flash an ATMEGA2560 using a WIZnet 5500?
I am wondering if anyone has ever flashed a ATMEGA2560 utilizing a WIZnet 5500? I have looked at this bootloader package but it only supports the 5100. I may have to do it myself but am a little worried as there doesn't seem to be any support/documentation online and I am not the best programmer. Any help would be greatly appreciated.

# Answer
> 2 votes
The latest Ariadne bootloader from 'codebender' is in his 'personal' GitHub repository. It has W5500 support. Per created his fork with better documentation and a hardware package earlier. The loathingKernel's repo still lacks good documentation.

I installed Per's Ariadne package over Board Manager and then I replaced the files in Per's package with files from loathingKernel's repo. The I flashed the bootloader to Mega without problems and the Ariadne bootloader worked for me over W5500.

I configured the upload from IDE too.

---
Tags: ethernet
---


# Question
Title: Why can I wake Arduino only once with this code?
This is my enhanced code for a daylight alarm on Arduino UNO with an added MP3-Player. The device is supposed to sleep all the time except when I hit the play button (then it is supposed to play music) or when the RTC wakes it up, both via interrupt. When the RTC wakes it up it will start its actual daylight alarm routine.

I just implemented the sleep/power-down code and got it working so that I could wake it up and put it to sleep with pins 9 (sleep) and 2 (wake up via interrupt). There was a problem though and I had to change the code.

Apparently while trying to fix it I broke something. The current behiour upon startup is: 1. Go to sleep (correct) 2. When I bridge pin 2 and ground, it wakes up. (correct) 3. When I then bridge pin 9 and ground it goes to sleep. (correct). 4. When I bridge pin 2 and ground again it does not wake up again.

I have changed the code so that in addition to playing music the builtin LED will light up.

```
#include <avr/sleep.h>
/************ init mp3-player ***************/
#include <SoftwareSerial.h>

#define ARDUINO_RX 4  //should connect to TX of the Serial MP3 Player module
#define ARDUINO_TX 5  //connect to RX of the module

SoftwareSerial mp3(ARDUINO_RX, ARDUINO_TX);
static int8_t Send_buf[8] = {0}; // Buffer for Send commands.  // BETTER LOCALLY
String sbyte2hex(uint8_t b);

#define CMD_SLEEP_MODE    0X0A
#define CMD_WAKE_UP       0X0B
#define CMD_SEL_DEV       0X09
#define CMD_PLAY          0X0D
#define CMD_STOP_PLAY     0X16  // Stop playing continuously.
#define CMD_FOLDER_CYCLE  0X17
#define CMD_SET_DAC       0X1A
#define DAC_ON            0X00
#define DAC_OFF           0X01
#define DEV_TF            0X02

/**************** init the real time clock ***************/
#include <Rtc_Pcf8563.h>
Rtc_Pcf8563 rtc;

/**************** setup pins & buttons ***************/
const byte led = 11; // Pin LED is connected to
const byte sixAmPin = 6; // Pin for set-alarm-to-6am-button
const byte sevenAmPin = 7; // Pin for set-alarm-to-7am-button
const byte eightAmPin = 8; // Pin for set-alarm-to-8am-button
const byte stopPin = 9; // Pin for stop button
const byte timeResetPin = 10; // Pin for reset-clock-to-9am-button (useful e.g. after battery failure)
const byte playPin = 2; // Pin for play-music-button (and interrupt!)
const byte rtcIntPin = 3; // Pin for RTC interrupt

byte sixAmButton = 1; // State of 6am-set-button
byte sevenAmButton = 1; // State of 7am-set-button
byte eightAmButton = 1; // State of 8am-set-button
byte stopButton = 1; // State of stopButton
byte timeResetButton = 1; // State of time-set-button
byte playButton = 1; // State of play-music-button

byte brightness = 0; // LED brightness
bool wakeupMode = false;
unsigned long prevStepTime = millis();
unsigned long time;

/*************** Changeable variables here **************/
byte setHour = 6;
byte setMin = 30;
byte fadeDuration = 30; // Duration of fade in minutes (default: 30)
byte afterBurn = 30; // Keep light on after alarm for this many minutes (default: 30)
/********************************************************/

unsigned long keepLight = afterBurn * 60000UL; // Calculate time to keep LED on after fade (in ms)
int fadeStepLength = fadeDuration * 60000 / 255; // Calculate step duration for increasing LED brightness (in ms) (default: fadeDuration * 60000 / 255)

void setup() {
  /*DEBUG*/
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);
  /*DEBUG END*/

  // Serial.begin(9600); //uncomment after testing
  mp3.begin(9600);
  delay(500);

  sendCommand(CMD_SEL_DEV, 0, DEV_TF);
  delay(500);

  // declare LED pin to be an output:
  pinMode(led, OUTPUT);

  // declare button pins as inputs:
  pinMode(stopPin, INPUT_PULLUP);
  pinMode(sixAmPin, INPUT_PULLUP);
  pinMode(sevenAmPin, INPUT_PULLUP);
  pinMode(eightAmPin, INPUT_PULLUP);
  pinMode(timeResetPin, INPUT_PULLUP);
  pinMode(playPin, INPUT_PULLUP);
  pinMode(rtcIntPin, INPUT_PULLUP);

  attachInterrupt(digitalPinToInterrupt(playPin), wakeUpPlay, FALLING);
  attachInterrupt(digitalPinToInterrupt(rtcIntPin), wakeAlarm, FALLING);
}

void loop() {
  goToSleep();
}

void wakeup() {
  // If wake-up-mode is true and brightness < 255, add +1 to brightness every 7 seconds (256 steps)
  wakeupMode = true;
  while (wakeupMode == true) {
    //update clock
    time = millis();

    // If current time is wakeup-time, increase LED brightness slowly over the course of 30 minutes
    if (brightness < 255 ) {
      // Delay brightening in steps. Do only if interval has passed.
      if (time > prevStepTime + fadeStepLength) {
        brightness ++;
        prevStepTime = millis(); // Resets counter to restart interval
      }
     }
    // Turn off light and exit wakupMode x minutes after max brightness
    else if (brightness == 255 && time > prevStepTime + keepLight) {
      brightness = 0;
      wakeupMode = false; // Exit wakeupMode loop
    }
    readButtons(); // Check for button input
    analogWrite(led, brightness); // Set LED brightness accordingly
  }
  goToSleep;
}

void readButtons() {
  // Always run this:
  // Check if alarm gets set for 6, 7 or 8am
  sixAmButton = digitalRead(sixAmPin);
  if (sixAmButton == LOW) {
    rtc.setAlarm(5, 30, 99, 99);
  }
  sevenAmButton = digitalRead(sevenAmPin);
  if (sevenAmButton == LOW) {
    rtc.setAlarm(6, 30, 99, 99);
  }
  eightAmButton = digitalRead(eightAmPin);
  if (eightAmButton == LOW) {
    rtc.setAlarm(7, 30, 99, 99);
  }

  // If stopButton is pressed: stop playing music, turn off LED, sleep mp3-player, sleep arduino
  stopButton = digitalRead(stopPin);
  if (stopButton == LOW) {
    wakeupMode = false;
    brightness = 0; // uncomment after testing
    analogWrite(led, brightness); // Set LED brightness accordingly
    sendCommand(CMD_STOP_PLAY);
    sendCommand(CMD_SLEEP_MODE);
    delay(200);
    goToSleep();
  }

  // If timeResetButton is pressed, reset RTC to 9am
  if (timeResetButton == LOW) {
    rtc.setTime(9, 0, 0);
  }

  // If Play music button is pressed, start playing music
  playButton = digitalRead(playPin);
  if (playButton == LOW) {
    playMusic();
    }
}

void playMusic(){
  digitalWrite(LED_BUILTIN, HIGH);
  sendCommand(CMD_WAKE_UP);
  delay(200);
  sendCommand(CMD_FOLDER_CYCLE, 1, 0);
  while (1){
    readButtons();
  }
}

void wakeUpPlay(){
  sleep_disable();
  detachInterrupt(digitalPinToInterrupt(playPin));
  detachInterrupt(digitalPinToInterrupt(rtcIntPin));
  playMusic();
}

void wakeAlarm(){
  sleep_disable();
  detachInterrupt(digitalPinToInterrupt(playPin));
  detachInterrupt(digitalPinToInterrupt(rtcIntPin));
  wakeup();
}

void goToSleep() {
  sleep_enable();
  attachInterrupt(digitalPinToInterrupt(playPin), wakeUpPlay, FALLING);
  attachInterrupt(digitalPinToInterrupt(rtcIntPin), wakeAlarm, FALLING);
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  digitalWrite(LED_BUILTIN, LOW);
  delay(500);
  sleep_cpu();
}

/**************************/
/** Stuff for MP3 player **/
/**************************/

/********************************************************************************/
/*Function: Send command to the MP3                                             */
/*Parameter: byte command                                                       */
/*Parameter: byte dat1 parameter for the command                                */
/*Parameter: byte dat2 parameter for the command                                */

void sendCommand(byte command){
  sendCommand(command, 0, 0);
}

void sendCommand(byte command, byte dat1, byte dat2){
  delay(20);
  Send_buf[0] = 0x7E;    //
  Send_buf[1] = 0xFF;    //
  Send_buf[2] = 0x06;    // Len
  Send_buf[3] = command; //
  Send_buf[4] = 0x01;    // 0x00 NO, 0x01 feedback
  Send_buf[5] = dat1;    // datah
  Send_buf[6] = dat2;    // datal
  Send_buf[7] = 0xEF;    //
  Serial.print("Sending: ");
  for (uint8_t i = 0; i < 8; i++)
  {
    mp3.write(Send_buf[i]) ;
    Serial.print(sbyte2hex(Send_buf[i]));
  }
  Serial.println();
}

/********************************************************************************/
/*Function: sbyte2hex. Returns a byte data in HEX format.                       */
/*Parameter:- uint8_t b. Byte to convert to HEX.                                */
/*Return: String                                                                */

String sbyte2hex(uint8_t b)
{
  String shex;

  shex = "0X";

  if (b < 16) shex += "0";
  shex += String(b, HEX);
  shex += " ";
  return shex;
}

/********************************************************************************/
/*Function: shex2int. Returns a int from an HEX string.                         */
/*Parameter: s. char *s to convert to HEX.                                      */
/*Parameter: n. char *s' length.                                                */
/*Return: int                                                                   */

int shex2int(char *s, int n){
  int r = 0;
  for (int i=0; i<n; i++){
     if(s[i]>='0' && s[i]<='9'){
      r *= 16;
      r +=s[i]-'0';
     }else if(s[i]>='A' && s[i]<='F'){
      r *= 16;
      r += (s[i] - 'A') + 10;
     }
  }
  return r;
}

```

I can only imagine that the problem lies in the way I send Arduino to sleep when playing music (i.e. the way I call goToSleep(); from the wakeUpPlay()-class). Waking up from sleep does work when sleep was induced from the main loop (apparently). Do you have any idea what is wrong? (I thought about reducing my code to the bare minimum so it is less confusing for you - but then I'd probably change too much to find the bug).

# Answer
> 3 votes
All your music playing code is inside a interrupt. While an interrupt is running all other interrupts are disabled. It's advised to keeps interrupt routines as short as possible.

You could have the interrupt routine set a boolean variable. Then in the `loop` function read that variable and call the play-music function.

```
volatile boolean startPlayback = false;

...

void wakeUpPlay(){
  startPlayback = true;
  sleep_disable();
  detachInterrupt(digitalPinToInterrupt(playPin));
  detachInterrupt(digitalPinToInterrupt(rtcIntPin));
}

...

void loop() {
  goToSleep();
  if( startPlayback )
  {
    startPlayback = false;
    playMusic();
  }
}

```

Do something similar with wakeAlarm.

---
Tags: interrupt, sleep
---


title: How to speed up Due ADC

text:
# Question
Title: How to speed up Due ADC
I'm doing a project where in I'm using Arduino Due to measure the time difference of arrival of signals to four piezoelectric sensors. The piezo sensors where glued on a board and we want to localize the source of taps on the boards based from the TDOA of the vibration to the piezos.

Originally, we are using interrupts to raise flags once we have detected the signals (basically, we've set a threshold on the piezo voltage to say that we've 'detected' a signal) but that seems susceptible to noises especially when the environment has loud noises (music, voices on microphones, etc.).

So what we think as a solution is to perform signal processing. However, to do this, we need to measure the voltage of the incoming signal using the ADC.

So far, my target is to make the performance of this approach comparable to that of the one where we are using interrupts. As of now, the new approach is super sensitive to the difference on the taps giving it a high POE.

As I understand it, the main difference between the two approach is that the interrupt approach has a microsecond difference between counts making the difference of the taps to about 10 to 30 microsecond. However, the Analog approach has a 20 microsecond difference between each sample for each channel, making the count difference 20 second also. Even a count difference would make it 20 us.

Is there anyway to make this time faster? I know the ADC needs time to convert and push the data to the appropriate registers but I'm just trying to find ways to make this faster. I've read on the datasheet of the Due MCU that it has 14 ADC channels plus a temp sensor at the 15th. Maybe a way of doing this could be to reduce the number of channels? I don't know how.

Are there any way to make the ADC conversion of the Arduino Due faster?

# Answer
Yes, there is a possibility to configure `ADC` to run faster, as it can handle `1Msps`. For four `ADC` channels it means `250ksps` each (with `1us` time difference between samples). It's not possible with Arduino wrappers as they are way too slow and also waits for conversion end. You have to configure it directly in MCUs registers, so start with `SAM3X8` datasheet.

In short: free running mode, sequenced readings like: `0 1 2 3`, with interrupt on 4th sample, interrupt handler and some processing.
> 2 votes

# Answer
> difference between each sample for each channel,

That's way too slow for any mcu made since the 1980s.

Look into the datasheet and compare it via your code to see where you can pick up the speed. Typically there is a clock prescaler for the adc that you can change.

In general, the fastest would be continuous adc into dma. If you need to add multiple channels turn on scanning.
> 0 votes

# Answer
//Configure ADC PMC-\>PMC\_WPMR &= ~(PMC\_WPMR\_WPEN); //Disable the Write Protect Mode PMC-\>PMC\_PCER1 |= PMC\_PCER1\_PID37; //Enable ADC Peripheral Clock

PIOA-\>PIO\_PDR |= PIO\_PDR\_P16; //Disable PIO Controller

ADC-\>ADC\_WPMR &= ~(ADC\_WPMR\_WPEN); //Disable the Write Protect Mode ADC-\>ADC\_CHER |= ADC\_CHER\_CH7; //Enable A0 pin ADC-\>ADC\_MR = 0; //ADC-\>ADC\_MR = ADC\_MR\_PRESCAL(2); //ADC Clock set to 16MHz ADC-\>ADC\_MR = ADC\_MR\_PRESCAL(4); //ADC Clock set to 8MHz ADC-\>ADC\_MR |= ADC\_MR\_TRACKTIM(3); ADC-\>ADC\_MR |= ADC\_MR\_STARTUP\_SUT8; ADC-\>ADC\_EMR = 0;

//read ADC output ADC-\>ADC\_CR |= ADC\_CR\_START; //Software Trigger uint32\_t adc\_read = ADC-\>ADC\_CDR\[7\];

you can change the parameters of prescaler to get the required speed
> 0 votes

# Answer
You can set the ADC in freerun mode to get results as fast as they can be read.

Use adc\_configure\_trigger for this.

```
adc_configure_trigger(ADC, ADC_TRIG_SW, ADC_MR_FREERUN_ON);

```

To enable freerun on the ADC or to configure as needed. No need anymore to set registers.

There was a bug with this function before if called more than once, but it is now fixed. https://github.com/arduino/Arduino/issues/1819
> 0 votes

---
Tags: arduino-due, adc
---


# Question
Title: Two floating point values do not get added and printed on ESP-WROOM-32
I have a Olimex ESP32-PoE board which has a **ESP-WROOM-32**.

I just found out a strange behaviour for printing floating point numbers on the board.

### Sketch

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

void loop() {
  // put your main code here, to run repeatedly:
  float a=34567891.234;
  float b=2.3456;
  a++;
  Serial.print(a+b, 4);
  Serial.println("");
  delay(1000);
}

```

the sketch is extremely simple where I want to add two floating point numbers, one a big and another small to print their addition result upto 4 places.

### Output

on the serial console in the Arduino IDE

```
34567896.0000
34567896.0000
34567896.0000
34567896.0000
34567896.0000
34567896.0000
34567896.0000
34567896.0000
34567896.0000
34567896.0000
34567896.0000
34567896.0000
34567896.0000

```

Everytime I increment the `float a` using `a++` i expect it to increment by one and print the result but the output above is completely off.

### Without Increment

```
void loop() {
  // put your main code here, to run repeatedly:
  float a=34567891.234;
  float b=2.3456;
  Serial.print(a+b, 4);
  Serial.println("");
  delay(1000);

}

```

### output

```
34567896.0000
34567896.0000
34567896.0000

```

Same output.

Is this Board specific or is the `Serial.print` not supporting float?

# Answer
As already stated in comments and Dave X's answer, floats have a limited resolution. That resolution is given by the constant `FLT_EPSILON`, which is the difference between 1 and the smallest float larger than 1. On any system conformant to IEEE 754, `FLT_EPSILON` is 2−23, or about 1.19e-7. The implication is that, within the interval \[1, 2\], the real numbers that can be exactly represented by floats are the multiples of `FLT_EPSILON`. The resolution, however, degrades as you consider larger numbers. Within the interval \[2, 4\] it is twice as coarse. Within \[4, 8\], it's four times as coarse and so on:

```
interval     resolution
------------------------------------------
1    – 2     2^-23 ≈ 1.19e-7 (FLT_EPSILON)
2    – 4     2^-22
...
2^23 – 2^24  1
2^24 – 2^25  2
2^25 – 2^26  4
...

```

Your number `a` is just slightly larger than 225. Within this range, the numerical resolution (aka “ulp”: unit in the last place) is 4 (last line in the table above). Thus floats in this range can only represent exact multiples of 4. When you write

```
double a=34567891.234;

```

the compiler replaces this by the closest float, which happens to be 34567892. Same thing for b, but in this case the rounding error is tiny and inconsequential (about -1.1e-7). When you write

```
a++;

```

you are replacing `a` with the float that is closest to `a+1`, which happens to be `a` itself. So the instruction has no effect. When yo do

```
Serial.print(a+b, 4);

```

you are computing the float closest to 34567892+2.3456, which is 34567896.

A `double` instead has a resolution `DBL_EPSILON` which is 2−52, or about 2.22e-16. This gives you some precision margin, but be aware that AVR-based Arduinos do not really support doubles and treat the `double` keyword as a synonym for `float`. This may only be an issue if you ever have to move your code to a more traditional Arduino.
> 2 votes

# Answer
Try doubles instead of floats.

Your initial value, 34567891.234 needs 35 bits of precision to keep track of the decimals, but floats only have 24 bits pf precision. So to have enough precision to keep track of the difference between `34567891.234` and `34567891.234+1`, you need higher precision storage.

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

void loop() {
  // put your main code here, to run repeatedly:
  double a=34567891.234;
  double b=2.3456;
  a++;
  Serial.print(a+b, 4);
  Serial.println("");
  delay(1000);
}

```
> 3 votes

---
Tags: serial, esp32, float
---


# Question
Title: How do I get the request params from a ESPAsyncWebServer?
I currently have the following code

```
server.on("/on", HTTP_POST, [](AsyncWebServerRequest *request) {
    Serial.println("ON hit.");
    String message;
    Serial.println(request->url());
    if (request->hasParam("device"))
    {
        message = request->getParam("device")->value();
    }
    else
    {
        message = " not specified";
    }
    request->send(200, "text/plain", "On, GET: " + message);
    Serial.print("Device ");
    Serial.println(message);
....

```

When sending in a request I get the out put, "Device not specified".

I take a look at the request-params() which gives me back a count of params that are in there and it's returning 1. I write this out:

```
server.on("/off", HTTP_POST, [](AsyncWebServerRequest *request) {
    Serial.println("OFF hit.");
    String message;
    int params = request->params();
    Serial.printf("%d params sent in\n", params);
    for (int i = 0; i < params; i++)
    {
        AsyncWebParameter *p = request->getParam(i);
        if (p->isFile())
        {
            Serial.printf("_FILE[%s]: %s, size: %u", p->name().c_str(), p->value().c_str(), p->size());
        }
        else if (p->isPost())
        {
            Serial.printf("_POST[%s]: %s", p->name().c_str(), p->value().c_str());
        }
        else
        {
            Serial.printf("_GET[%s]: %s", p->name().c_str(), p->value().c_str());
        }
    }
    if (request->hasParam("device"))
    {
        message = request->getParam("device")->value();
    }
    else
    {
        message = "not specified";
    }
    request->send(200, "text/plain", "Off, GET: " + message);
    Serial.print("Device ");
    Serial.println(message);

```

and get the output now of

```
1 params sent in
_POST[device]: puddle
Device not specified

```

If I try to do something like request-\>getParam(0)-\>value().c\_str() I get a stack dump of a bunch of hex values that I have no idea what it means: but it looks like a big fat error.

# Answer
> 3 votes
For POST request the `hasParam` needs to know if you want to test the url parameters or `x-www-form-urlencoded` parameters in body of the POST request. The second parameter of the `hasParam` is `boolean post` and it has default value `false`. Use `hasParam("device", true)`.

---
Tags: esp8266, web-server
---


# Question
Title: Why does my Esplora only send serial data when the serial monitor is on?
I've noticed that when I'm sending serial data to my computer's serial monitor, the tx light only lights up when the serial monitor is open. When I close the monitor, it seems to stop sending data. Is this a normal thing?

The reason I ask is because I'm really trying to send data from my esplora to an uno, and I notice that despite (1) having the grounds of both arduinos connected and (2) connecting the esplora's tx pin (reset\_lcd) to the uno's rx pin (pin 0) and the esplora's rx pin (dc\_lcd) to the uno's tx pin (pin 1), the tx light on the esplora and the rx pin on the uno don't light up at all.

What could be the problem?

# Answer
> 2 votes
Esplora is based on a MCU with native USB. The native USB reports connected only when it really connects. You have in setup() a while loop until the USB Serial is valid. The skech waits there for connection. Comment out the while (Serial) loop.

The TX and RX LEDs of Esplora are connected to the native USB port Serial interface. They will not light for the Serial1 interface.

You should disconnect the Uno from computer to not disturb the Serial interface with USB connection. Or use SoftwareSerial to communicate with Esplora and have debug prints to Serial Monitor.

---
Tags: serial, arduino-esplora
---


# Question
Title: Multiplication, division. What is wrong?
```
const unsigned long C1 = 30 * 1000;
const unsigned long C2 = (300 * 1000)/C1; // must be = 10

void setup() {
  Serial.begin(57600);
  Serial.println("\n-------");
  Serial.print("C1 = "); Serial.println(C1);
  Serial.print("C2 = "); Serial.println(C2);

  unsigned long V1 = (300 * 1000)/C1;   // must be = 10
  Serial.print("V1 = "); Serial.println(V1);

  long V2 = (300 * 1000)/30000; // must be = 10
  Serial.print("V2 = "); Serial.println(V2);

  int V3 = (300 * 1000)/30000; // must be = 10
  Serial.print("V3 = "); Serial.println(V3);
}

void loop() {
}

```

Arduino UNO printed in monitor console:

```
C1 = 30000   (ok)
C2 = 143164  (must be = 10)
V1 = 143164  (must be = 10)
V2 = 0       (must be = 10)
V3 = 0       (must be = 10)

```

What is wrong?

# Answer
```
300

```

and

```
1000

```

are integers.

What

```
long V2 = (300 * 1000)/30000;

```

really does is take the *integers* 300 and 1000 multiply them. This calculation overflows, and equals -27680. Dividing that by 30000 yields 0. What you added in your comment isn't a hack, it's the proper solution. By including the suffix L or UL you tell the compiler that you want longs, not ints.
> 5 votes

# Answer
> What is wrong?

You are assuming that the expression is long int but it is actually int. The literals are int. You need to convince the compiler that the expression is actually long int. That can be done by cast:

```
((long) 30000)

```

or literal long integer syntax:

```
30000L

```

The AVR GCC compiler uses int defined as 16-bit. Expression and literals are implict 16-bit.

More on the representation of C/C++ data types, expressions, and calling conventions can be found here.

Cheers!
> 2 votes

# Answer
A good practice with literal numbers which you want to divide and multiply is to always define them as `double`, and convert them to integer when they are used. This is often the case with frequency/period constants. This prevents most catastrophic overflow / rounding errors that integer math would have, while allowing you to use consistent units in your definitions.

```
 #define F_CPU 16000000.0   // in Hz
 #define F_TICK (1.0/F_CPU) // in seconds
 #define DELAY 0.001        // in seconds
 #define COUNT ((uint16)(DELAY/F_TICK))
 Serial.println(COUNT);

```

Of course, you can calculate the number of CPU ticks per millisecond using fixed-point math, for example by defining the frequency in MHz and the tick time in nanoseconds, but you'll have to scratch your head every time you need to convert a period to a frequency and vice versa, and you'll have to change units the moment your frequency will not be a multiple of MHz.
> 1 votes

---
Tags: programming, data-type
---


# Question
Title: I do not know what the board is. Can someone please help
It says that it is a pro micro, but I have searched the arduino website and i cannot find something that looks like this or is called this.

# Answer
> 0 votes
An Arduino compatible board don't have to look like one in Arduino web site. There are many clones and custom boards are available. Since it says pro micro, choose `Pro micro` from bard option and try uploading some code.

---
Tags: arduino-pro-micro
---


# Question
Title: Multiple RGB led strips with Uno - options?
I know there's quite a few threads with similar answers already, but I hope you won't mind me asking anyways. One thread has what looks like a good solution but it's old and thought it may be better to ask fresh.

I have ten 12v rgb strips with 4 wires each, a 12v power supply and 30 mosfets. I want to control them individually with an Uno.

I'd like to make a wave effect where the strips increase and decrease in brightness at separate times. It's fine if they are all the same color during a wave. Then a wave of a different color.

(1) I'm thinking of trying the approach in this thread where AMADANON suggests using 3 pins for the color and then each strip gets its own common pin, 13 pins in my case. If I go this route, will I be able to set a color for all strips and a brightness for individual strips? This would let me make the wave effect I'd like.

(2) Alternately I'm thinking of upgrading to a Mega with 54 pins. I assume I could then control each strip individually using 3x10 = 30 pins?

(3) I've read lots of advice on chips to control the strips, but I'm a newbie and would like to keep it as simple as possible (plus delivery to my country takes 3 weeks or more, and I'd like to get started now)

Thanks for any advice!

**EDIT:** (I replied to answers in comments, and I now see I should just instead edit this question. Thanks for your patience with a newbie!)

The mosfets are N-Channel MOSFET 60V 30A.

The led strips are rgb non-addressable with 4 wires, wired on both ends so they can be easily daisy-chained. But in my project the strips are snaking around some tracks and connected them in serial poses a problem. I'd prefer to wire each from only one end.

I think I'll try Gerben's and Andrew's advice about a chip and check out PCA9685 chip module as per Andrew's suggestion. Sounds inexpensive!

chrisl's suggestion for using WS2811 chips sounds easy too and maybe less wiring. In the same vein was an idea from this thread from gre\_gor:

Setting 10 RGB Strips Independently from Single Arduino

... which talks about chainable STM32 rgb chips, only about 2 bucks on ebay, no mosfets, and pretty efficient.

Thanks for all the advice guys! I'm finishing the box and strips placement now and waiting for my Arduino to arrive which should be any day. This is my first venture into this domain (though I've done plenty of coding and have some experience with electronics).

# Answer
I know what you mean - LED strips with all the same colour at the same time. I've used these and I assume you can wire up the MOSFETs ok. If you don't need individually-addressable LEDs they can still produce some effects.

To control 30 PWM lines, at first I thought using the Mega would solve it, but as someone else reminded us, only 15 are full (hardware) PWM and some would have to be software PWM. This may be good enough, I don't know. More expensively, you could use two MEGAs with one acting as a slave to get 30 full PWM pins.

Another idea would be to use a PCA9685 chip module. I got a couple of these on ebay some while ago (dirt cheap, under £2/$2 ) and each board provides 16 PWM outputs, all controlled from I2C input. They aren't hard to use and have library code for Arduino. Two of these and an UNO would do it or one and a MEGA.
> 2 votes

# Answer
It sounds to me that you have this kind of tape leds.

If I'm right then your led strip has 4 pins:

1- Blue

2- Green

3- Red

4- GND

With this you can create up to (2^8)*(2^8)*(2^8) = 16,777,216 colors (using PWM or any other dimming technique with the Arduino), **BUT ALWAYS** having the same color in all the led strip. So, *at least as far as I know*, you can not do the effects you want with that strip.

What do you need? You need a "smart" tape, one like this

As you will see in the name says **addressable**, this means that, for example, you can put the green color on led No1 and the red color on led No2 and so on, and you can move those LEDs making very interesting and cute effects!

Hope you can find this fast explanation helpfull.
> 1 votes

# Answer
> I have ten 12v rgb strips with 4 wires each, a 12v power supply and 30 mosfets. I want to control them individually with an Uno.

These sound like non-smart LED strips, where you supply 12V on one pin and then there is a control line for each color. Three resistors for each 3 LEDs, with the groups of 3 wired in parallel on the strip. In which case, 3 MOSFETs per strip to sink current to Gnd sounds good, and you can likely one MOSFET control the same color on multiple strips. Thus you can use the 18 IO of an UNO, leaving D0/D1 free for serial comms with your PC.

Uno has 6 hardware PWM pins for 256 levels of brightness via analogWrite(), and you can create software PWM for the other pins as well.

Which MOSFET do you have?
> 0 votes

# Answer
As stated before by other users, there are multiple ways to go, but you will have to make compromises.

* When using an Arduino Mega, you will have to bitbang the PWM signal (directly or by using some timer interrupts), because only 15 of it's pins can be used as native PWM pins.
* In my opinion it would be the cleanest solution, to use a single driver chip for each LED strip. You can use the WS2811 chip, which is used in most LED strips with individually addressable LEDs. It outputs 3 PWM signals (for red, green and blue) and gets controlled by shifting bits through it's input. Also these chips can be daisy-chained; meaning, that only the first is hooked up to the Arduino and all other chips will be chained together (serial output to serial input). In this solution each chip would controll one of the ten LED stripes (note, that you still have to use a capable MOSFET between WS2811 and strip, since the chip cannot provide enough power for a whole strip), and they would be chained together, effectively only using 1 pin on the Arduino. You can then use librarys like the `Adafruit_Neopixel` to control the strips. Each of your strips then corresponds to 1 LED in the library. You can buy the WS2811 chips at various sources. When googling I found them for 5$ at Adafruit, but you may find them somewhere else for less (This was simply the first shop, where I found them. Didn't searched long). The datasheet (for example here) contains example applications, which show, how the chips have to be connected. For this solution, you would have to replace the depicted LEDs with MOSFETs, that drive the strips PWM lines.
> 0 votes

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