title: How can there be not enough current?

text:
# Question
Title: How can there be not enough current?
I am new to the Arduino world. I have a question regarding current that the Arduino outputs over its 5V port. Why is the current in the Arduino too weak for current hungry circuit when the only thing that changes in this equation `V=IR` is the current itself.

For instance, the voltage in an Arduino is restricted to 5 volts. Assuming that the resistance of the current stays the same, shouldn't the current also increase (following Ohm's law) over its 5V port? More specifically, I am talking about powering ESP8266 with an Arduino.

# Answer
> 4 votes
The problem is not that "there is not enough current", but that you can't dissipate enough power.

Let's assume you are powering the board from an external 12V supply. Now, the 5V are obtained from 12V with a resistive regulator: this means that the regulator (see this image if you are interested in knowing what component it is) simply behaves like a variable resistor, dissipating the power in excess. Now, let's assume you want to draw 4A from the 5V rail, since you want to turn on a lot of LEDs and other stuff. Since P=VI, the regulator (that very little component) has to dissipate (12V-5V)\*4A = almost 30W. This means that it becomes a little heater and.. Puff! it breaks.

Now, 4A is a really high current, but that regulator can withstand very little power dissipations. According to the datasheet, and estimating a 1cm x 2cm heatsing under it, we can estimate a 25 K/W thermal resistance, which means that each watt you dissipate raises the internal temperature by 25K (=25°C). You can't go beyond 150°C without damaging the component, which means that if your room is at 25°C you can dissipate AT MOST 5W. In practice, never go beyond 3W. Anyway even 5W mean that, at 12V, you can't get more than 5W/7V=0.7A.

By the way, the regulator is rated 0.8A, so you should never go beyond that value in any case.

Now, this was the external regulator. As for the usb, you can't get more than 500mA from that power supply. That's written in the specs. For this reason, a 500mA fuse is on that rail, so going beyond 500mA will blow that one, interrupting your power. Well, that's a self-healing fuse, so after some time (maybe hours?) it will operate again, but.. Don't try that.

In the end, the digital pin current. The atmega datasheet says that

1. The absolute maximum current per I/O Pin is 40.0mA
2. The absolute maximum current inside VCC and GND Pins is 200.0mA

This means that from each single pin you can get at most 40mA (but I suggest you never go beyond 20mA), and the sum of all the currents (and the internal peripherals) should never exceed 200mA. So if you need to power 2 leds, you can give each of them 20mA, if you need to power 15 of them you can't (you are limited to, let's say, 10mA). If you need more, use transistors to separate the current paths.

# Answer
> 1 votes
A very simple answer: The Arduino is limited to an absolute 40mA per pin, because within the controller chip (ATMega328 usually) the path the current follows is very small. More current can destroy the tiny transistors in the chip. Best case, you burn out that pin.

If you have a problem that requires more than 40mA (and really, as other posters point out, 20mA!) you should be using a transistor, mosfet or relay controlled by the Arduino, rather than directly power the end device.

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


# Question
Title: Issues on Arduino, LiPO battery and two mottors setup
My main objective with this project was to control these two DC motors with an Arduino Nano (it is not a UNO), powered by a 3-Cell 750mAh LiPO battery (both the motors as the Arduino itself). So, I came up with something like this (it is a simplified version):

If the load on the two mottors rise, could the Arduino be damaged by this current increase? Is the voltage too high for the Arduino handle? Is there any more issues that this setup can have?

When searching, I found that it would be wise to get a fuse between the power supply and the arduino (before reaching Vin). Is that necessary?

# Answer
> If the load on the two motors rise, could the Arduino be damaged by this current increase?

No, the motor current doesn't pass through the Arduino. It is completely separate.

> Is the voltage too high for the Arduino handle?

Borderline. The regulator (a lowly 7805) may well get very hot at that voltage (depending on the Arduino's current draw) and go into thermal shutdown.

> Is there any more issues that this setup can have?

Maybe add a small buck regulator to the 5V pin instead of using the on-board linear regulator. That will not overheat and will be far more efficient making your batteries last longer. Often marketed as "UBEC" (Universal Battery Elimination Circuit) and used throughout the model vehicle industry these are very easy to get hold of and are ideal for powering things like Arduinos from batteries like this.
> 0 votes

---
Tags: motor, battery, current
---


title: ESP8266 blue led stays stays on

text:
# Question
Title: ESP8266 blue led stays stays on
I have found a similar qustion to mine but there was no good response.

I've connected my ESP8266 to Arduino UNO.

Then I got some trouble with software serial communication with Arduino and decided to change baud-rate to 9600 (previously it was 115200).

I used AT+IPR=9600 command to change it.

After that blue led of esp stays on and not taking AT commands any more, but output some gibberish to serial monitor.

Note: I connected the esp8266 through a voltage regulator and a power source and both gave the same problem. My firmware is supposed to be updated so I don't think that it is the issue.

Could anyone please help me?

# Answer
Did you change the firmware? I think Baud rate can be changed only if you flash it with newer version of the firmware.
> 0 votes

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


# Question
Title: Getting the average of sound in last minute
I am reading sound input every 60 seconds and I would like to calculate the average of sound during that period using non-blocking code; what should I do to change the way that I calculate it in separated function as I need to do something else with other sensors.

```
int calculateSoundValue(){
    int average = analogRead(0);
    // loop to calculate the average simple formula sum div nbr of calculated times
    return average;
}

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

}
void loop() {
  // I donùt wanna calculate the average inside a loop but instead inside a function
  int value = calculateSoundValue();
  Serial.println(value);

  delay(600);
}

```

**UPDATE**

Is this what you mean ?

```
unsigned long previousMillis = 0;
const long interval = 6000;
int totalSamples = 0;
int count = 0

    int calculateSoundValue(){
        int sound = analogRead(0);
        totalSamples+= sound;
        count += 1;
        return totalSamples/count;
    }

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop() {

  unsigned long currentMillis = millis();
int totalSamples = 0;
int count = 0
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;

  }
      int value = calculateSoundValue();
      Serial.println(value);
}

```

# Answer
> 1 votes
You want to find the average of doing an `analogRead` over a minute, is that it?

How about this?

```
unsigned long total;
unsigned int count;

unsigned long whenStarted;

const unsigned long INTERVAL = 60000;  // one minute

void setup ()
{
  Serial.begin (115200);
  Serial.println (F("Starting ..."));
  whenStarted = millis ();
}  // end of setup

void loop ()
{
  // one more sample
  total += analogRead (0);
  count++;

  if (millis () - whenStarted >= INTERVAL) // is a minute up?
    {
    Serial.print (F("Average = "));
    Serial.println (total / count);
    total = 0;
    count = 0;
    whenStarted = millis ();
    }
}  // end of loop

```

# Answer
> 1 votes
I assume what you actually want is to measure sound intensity. This is significantly more involved than just averaging the samples you read. I have written a few weeks ago a program that does exactly that: it measures the sound intensity and sends those measurements through the serial port. It is a pretty short program (43 lines of code) you may be able to adapt to your needs, so I am now sharing it as a GitHub gist: sound-meter.ino.

In order for this not to be a link-only answer, I'll try to explain the program's inner working, and go through the theory of measuring sound intensity on an Arduino. But first let me put here a disclaimer: a “real” sound level meter should have a frequency response that complies with some standards, and it should be calibrated to absolute levels. This program only provides uncalibrated readings with whatever frequency response its analog hardware has.

## Signal conditioning

Four measuring sound on an Arduino, you obviously need a microphone, but you also need some kind of interface circuit between the microphone and the Arduino. The purpose of the interface is to “condition the signal”, i.e. to make sure the Arduino gets a voltage in the proper range for it's analog-to-digital converter (ADC). It's typically an op-amp based circuit that provides some amplification and also adds a DC bias to avoid clipping the negative side of each oscillation. Ideally, the DC bias should be around Vcc/2, i.e. 2.5 V on an Arduino Uno.

See this SparkFun microphone breakout for an example on how such a circuit may be built (click on “Schematic”).

## ADC sampling

Once you have a properly conditioned analog signal, you have to sample it fast enough to catch all its spectral content. The Nyquist–Shannon sampling theorem tells us the sampling rate should be at least twice the highest frequency in the signal. For audio signals, sampling rates of the order of 8 kS/s (kilosamples per second) are typical of low quality, telephone-like applications, whereas high quality audio would run at 44.1 to 48 kS/s.

The ADC of the Arduino Uno, in its default configuration, takes 104 µs to convert one sample. If you just call `analogRead()` in a tight loop, this gives a sampling rate of about 9.6 kS/s, which is fine for this kind of application, unless we have to measure noise above 4.8 kHz. The problem with this approach is that `analogRead()` is a *blocking* function. Calling it in a tight loop means the program will spend most of its time just waiting for the ADC. If you do anything else in the loop, not only will the sampling rate be lowered, it will also become unsteady, which is generally not desirable.

In order to avoid blocking the CPU, we have to forgo `analogRead()`, and instead get our hands dirty with low-level configuration of the ADC. The ADC of the Arduino Uno offers a so-called “free running mode”, which is well suited for this kind of application. In this mode, the ADC starts a new conversion as soon as the previous one is done, ensuring a very consistent sampling rate of 9.6 kS/s. It can also trigger an interrupt after each conversion, in order for the interrupt service routine to retrieve and process the sample. See the datasheet of the ATmega328P for details on configuring the ADC.

## Removal of the DC bias

Once we have the digitized samples, the first thing to do is to remove the DC bias that was added by the interface circuit. If the bias is stable and known (maybe determined by experiment), this only involves subtracting a constant. If it is not known, it can be estimated by running the samples through a digital low-pass filter with a cutoff frequency below the range of interest. Subtracting the output of a low-pass filter is essentially building a high-pass filter. As an alternative, a numerical derivative (difference between consecutive samples) can be used as a crude high-pass filter. This, however, will bias the sensitivity of the detection towards the high end of the spectrum. Depending on the noise you want to detect, and on the background noise, this could be acceptable for your application.

In the program I am sharing, I assume the DC bias is known: it's the `dc_offset` constant at the beginning of the program.

## Instantaneous intensity

With the DC bias removed, the signal we have is a digital image of the sound picked by the microphone. It could be tempting to just average it as is. This, however, would just give zero, as the positive fluctuations of the signal would cancel the negative ones.

The are several options to solve this problem. We could do a peak detection instead of an average, or we could take the absolute value before averaging. The most popular option is probably to compute the squares of the samples. Since the square of a real number is always positive, this avoids the averaging-out problem. But the square has also a deeper physical meaning: it is proportional to the sound intensity, i.e. the energy carried by the sound wave.

## Low-pass filter

The intensity computed above is a very fast varying quantity. If the signal is a simple tone of constant frequency and volume, the instantaneous intensity fluctuates between zero and some maximum at twice the tone frequency. In order to recover the “constant volume” property of the sound, we need to perform some sort of averaging or, in other words, we need a low-pass filter.

There are many ways to implement a digital low-pass filter. The most intuitive may be to group the samples into batches, and then compute the average of each batch. However, this is neither the best nor the most efficient to implement. When I need a quick and simple low pass filter, I generally use an exponential moving average. This is the discrete-time equivalent of an analog RC filter, and it can be implemented very efficiently by remembering the previous output and updating it as

```
output += input - output / N;

```

where, for efficiency reasons, N should be a power of two. The filter's time constant is N/fs, where fs is the sampling frequency. In the program I use N = 256, which makes the division virtually free. This gives a time constant of 26.6 ms. You can tune the time constant to your needs simply by changing N, but make sure it is still a power of two.

## Decimation

If you only want to trigger an event when the sound intensity exceeds a defined level, you may not need this. But if you have other processing to do with those measurements, it is probably not useful to process more than one intensity reading per time constant of the previous filter. That's why the program has a decimation step. This is simply the ISR periodically signaling the main program that an intensity reading is available. Notice that, since the sample count is an 8-bit variable, it automatically counts modulo 256. If you want to increase the decimation factor, you should make `sample_count` wider and mask out the bits you do not need.

# Answer
> 0 votes
The short answer is use millis() to keep track of time. You can also put all the time related stuff inside a class to have a nicely organized code. You can get more info about time management on the Arduino here. https://learn.adafruit.com/multi-tasking-the-arduino-part-1/ditch-the-delay

---
Tags: arduino-uno, c++, analogread, sound
---


# Question
Title: Compare the new sample in a high sampling rate datalogger
I am using sdFat library the analog bin logger example,

Github: SdFat/SdFat/examples/AnalogBinLogger/

The program is working fine and every thing but the thing is, this high speed datalogger uses interrupts and timers to make the ADC work at a pre-determined sampling frequency and it DOES NOT use the normal `analogRead ()`

What I want is, when the input of some analog pin is bellow a pre-determined value, I want to write HIGH or LOW to some digital pin, my question is, how can I compare the new sample in the analog bin logger example as I simply want to compare the new sample as in:

```
if ( analogRead() < 256 ) {// do something}

```

knowing that there is no analogRead() in the program because it uses timers and interrupts.

# Answer
> 2 votes
In the function

```
ISR(ADC_vect) {

```

the variable `d` contains the current sample:

```
  // Read ADC data.
#if RECORD_EIGHT_BITS
  uint8_t d = ADCH;
#else  // RECORD_EIGHT_BITS
  // This will access ADCL first.
  uint16_t d = ADC;
#endif  // RECORD_EIGHT_BITS

```

So you can just "do something" depending on what is in `d`. Of course, since this is a timer interrupt you have limited time to do anything, so you need to make sure that whatever you do is fast and efficient - so really you want to be using direct port access instead of digitalWrite().

---
Tags: arduino-mega, interrupt, sd-card, timers, datalogging
---


# Question
Title: How to get serial data in Arduino from a barcode scanner?
I want to interface my barcode scanner with an Arduino using RS232. I have connected 2 (RX), 3 (TX) and 5 (GND) of the RS232 with the corresponding pins of MAX232. I am taking TTL outputs on Arduino pins 6 and 7.

This is the code of the Arduino program:

```
#include <SoftwareSerial.h>

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

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

void loop() {
  // run over and over
  if (mySerial.available()) {
    byte x = mySerial.read();
    Serial.println(x);
  }
}

```

I am not getting any output on the serial monitor when I scan a product.

# Answer
> 7 votes
Assuming your Arduino has only one hardware serial connection (it's something like an Uno rather than a Mega) you're quite right in using software serial, the Arduino will already be using pins 2 and 3 to communicate via USB to the Serial monitor so you can't use them to communicate with the scanner.

However carefully look at your first line of code, you've asked software serial to use pins 6 & 7 yet hooked the barcode scanner to pins 2 & 3. Move those pins over to the one's you've specified.

Secondly in your setup function you've begun communication with hardware Serial but not software serial. You'll need to add something like mySerial.begin(XXX) where XXX is the baud rate for the scanner.

Finally you haven't told the Arduino what pinMode to use for 6 and 7. You'll want pinMode(6, INPUT) and pinMode(7, OUTPUT) in there too.

# Answer
> 0 votes
RS 232 works on different voltage levels than Arduino, I believe the values you are getting on the screen will have no meaning whatsoever, If the scanner output is TTL then yes it would work, but in my own experience that logic is inverted and you have to add a 1 to software serial:

SoftwareSerial mySerial(6, 7, 1); // RX, TX

The first step is checking what voltage level is given by your scanner output.

# Answer
> 0 votes
I tried this as well, for some reason it is NOT WORKING on pins 6 and 7, but it works perfectly using pins 10 and 11 instead. Of course, you still need to add the `mySerial.begin()`.

---
Tags: serial, rs232
---


# Question
Title: Graph plotting on Processing from Arduino sensor data
I am trying to plot a graph on processing but I'm having challenges going about it. The processing sketch below does work for plotting only one axis, and I'm trying to plot all three axis on the same sketch. Does anyone have an idea on how I could go about it. Below are the Arduino and Processing sketches.

**Arduino**

```
AcceleroMMA7361 ski;
int x;
int y;
int z;

void setup()
{
   Serial.begin(115200);
   ski.begin(13, 12,11,10, A0, A1, A2);
   ski.setARefVoltage(3.3);
   ski.setSensitivity(HIGH);
   ski.calibrate();
}

void loop()
{
    x = ski.getXRaw();
    y = ski.getYRaw();
    z = ski.getZRaw();
   //Serial.print("\nx: ");
     Serial.println(x);
   //Serial.print("\ty: ");
   //Serial.print(y);
   //Serial.print("\tz: ");
   //Serial.print(z);
   delay(10);                                     //(make it readable)
}//End of Arduino Sketch

```

**Processing**

```
import processing.serial.*;

Serial myPort;        // The serial port
int xPos = 1;         // horizontal position of the graph

float fValue;
boolean newVal = false;

void setup () {
   size(800, 630);
   println(Serial.list());
   myPort = new Serial(this, Serial.list()[0], 115200);
   myPort.bufferUntil('\n');
   background(2);
   stroke(127, 34, 255);
}

void draw () {
    if (newVal) {
       line(xPos, height, xPos, height - fValue);
       if (++xPos >= width) {
         xPos = 0;
         background(2);
       }
       newVal = false;
    }
}

void serialEvent (Serial myPort) {
   String inString = myPort.readStringUntil('\n');
   if (inString != null) {
       inString = trim(inString);
       fValue = float(inString);
       fValue = map(fValue, 0, 1023, 0, height);
       newVal = true;
     }
}

```

# Answer
I have edited your `serialEvent()` method a little bit, so it could handle the data from the Arduino, when split by a tab.

```
void serialEvent (Serial myPort) {
   String inString = myPort.readStringUntil('\n');

   if (inString != null) {
     values=split(inString,"\t");  //Splitting the output of the arduino into a String Array
     for(int i=0;i<values.length;i++){
       values[i]=trim(values[i]); //deleting the whitespaces as before
       float_values[i]=float(values[i]); //cast the string to a float as before
     }
       x = map(float_values[0], 0, 1023, 0, height); //map the value as before
       y = map(float_values[1], 0, 1023, 0, height);//map the value as before
       z = map(float_values[2], 0, 1023, 0, height);//map the value as before
       newVal = true;
     }
}

```

so your sending on the Arduino has to look like this:

```
void loop()
{
    x = ski.getXRaw();
    y = ski.getYRaw();
    z = ski.getZRaw();
    Serial.print("\n");
    Serial.print(x);
    Serial.print("\t");
    Serial.print(y);
    Serial.print("\t");
    Serial.print(z);
    delay(10);                                     //(make it readable)
}

```

You still have to make the drawing in the `draw()` method of processing, but I think that this is not the problem.

For the 3d draw you should have a look on the Processing reference or at this special topic, P3D by Daniel Shiffman.

I have not tested the code, but I think that it should work.

If you have questions, feel free to ask ;D
> 1 votes

---
Tags: serial, arduino-due, sketch, processing-lang
---


title: Uploading sketch to ESP8266

text:
# Question
Title: Uploading sketch to ESP8266
I'm managing to upload a sketch to the ESP8266 01. I have been researching on internet but I'm not able to get it.

I have installed the libraries for Arduino IDE and my circuit is the ESP powered by 9V converted to 3.3V using a LD 3.3 converter. I tested the voltages and works fine. Also the led in ESP is on (red). To connect to the computer I'm using a TTL USB cable without vcc connected only for tx and rx.

The commands for the ESP works fine (AT commands), but when I try to upload a sketch it shown the following error:

> espcomm\_open failed

I also have connected to GP0 (ESP) a button to ground. The circuit is:

9V battery --\> 3.3V converter --\> ESP---\> TTL

Anyone knows about that error and why could be? Because the AT commands works fine. Maybe I need to provide more information but not sure.

My goal is to do this tutorial: https://learn.adafruit.com/downloads/pdf/esp8266-temperature-slash-humidity-webserver.pdf

Another problem that I have following that tutorial is that in Arduino IDE, I cannot setup esptool as programmer, because isn't there. I loaded the same library for esp

# Answer
> 1 votes
Following on from user1637451 the following sequence has always worked for me:

1. Before download, pull both GPIO0 and RST to ground.
2. Release the pull down on RST, but keep GPIO0 low.
3. When the IDE has finished downloading, release GPIO0 from low.

I usually have pull-up resistors (10K) on both RST and GPIO0.

As to the IDE problem. I used the tutorial from Sparkfun entitled "ESP8266 Thing Hookup Guide" and then the section "Installing the ESP8266 Arduino Addon". Because I used a different ESP8266 board to them I set the IDE to use the "generic ESP8266 board". This worked for me.

---
Tags: usb, esp8266
---


# Question
Title: Why perform bitwise operations here? (SPI FRAM read method)
See: https://github.com/adafruit/Adafruit\_FRAM\_SPI/blob/master/Adafruit\_FRAM\_SPI.cpp The following method reads and converts the input to 8 bit. I have several questions concerning its function.

Using addr = 0xFFFF as an example, the method converts the variable to 0xFF. I understand that bits are removed from the end, but surely 65535 != 255. Perhaps relatively, to their max size, but how is this a useful conversion? I might be missing something about bitwise here..

```
uint8_t Adafruit_FRAM_SPI::read8 (uint16_t addr)
{
 digitalWrite(_cs, LOW);
 SPItransfer(OPCODE_READ); //read memory from fram array (2-byte)
 SPItransfer((uint8_t)(addr >> 8));
 SPItransfer((uint8_t)(addr & 0xFF));
 uint8_t x = SPItransfer(0);
 digitalWrite(_cs, HIGH);
 return x;
}

```

Correct me if I'm wrong, the casting is to keep sign extension from occurring.

The masking I understand in theory, but do not at all understand its application here.

Finally, it always returns the same value x = 0, why?

I also see there's a write method but no read method. Only read8. Reasoning?

# Answer
Let's assume `addr` is `0xbeef`. Then, if we break down each operation:

```
expression             │ value
───────────────────────┼───────
addr                   │ 0xbeef
addr >> 8              │ 0x00be
(uint8_t)(addr >> 8)   │   0xbe
addr & 0xFF            │ 0x00ef
(uint8_t)(addr & 0xFF) │   0xef

```

So this is essentially breaking down the address into two 8-bit chunks, and transmitting those chunks individually. It's done like this because SPI only transmits bytes.

> the casting is to keep sign extension from occurring.

Non, sign extension cannot occur, since `addr` is an unsigned number. The casting really serves no useful purpose, other than documenting the code. It would be done implicitly simply because `SPItransfer()` takes an `uint8_t` argument. The casting *could* be useful if `SPItransfer()` was overloaded with a 16-bit version.

> Finally, it always returns the same value x = 0, why?

No, it returns whatever the call to `SPItransfer(0);` returns, i.e. the data sent by the FRAM module.
> 2 votes

---
Tags: c++
---


# Question
Title: 3.95 MCU Friend Arduino TFT LCD flickering
I got the 3.95" LCD from aliexpress which uses IL9488. I used the MCUFRIEND\_kbv library. I am using an Arduino Mega as I need other GPIO to be used for other purposes. I can't use the Uno because of this limitation.

I have other modules like the DS3231, and ESP8266 connected to the Mega and this 3.95" LCD connected as well. ESP8266 is powered separately using a 12-5V converted supply. The Mega is powered using another source. The normal graphics test is working in the LCD. I am able to make it work with the Nano, Uno and Mega. Even for the Mega I am able to write customized messages.

What I intend to do is to update the time in the LCD which is received from the DS3231. It updates the LCD but I see a flickering issue here.

Every update (LCD display function is from the loop which sets the text when there is a second/time/hour difference in the time) seems like it draining more current as the one of the LED connected to Mega dims, the Rx/Tx LEDs also dim.

I am able to get the LCD refreshed but it shows a flickering. I powered the LCD 3.3V and 5V using another separate source but still the small flickering continues.

Moreover all these time I was connected to the Mega through the USB from the laptop. Once I unplug the USB, LCD starts and shows some update and again become white. This continues and an not able to see anything on LCD there after.

I am not sure why only when the Mega is connected to USB this LCD works and that too flickering but once the USB is removed the LCD is not working at all.

Can someone please do help me in this ?

# Answer
I think something is wrong with this LCD board. This is because in my case the display works sometimes perfectly with the ILI9481 driver but sometimes something hangs and the display starts to flicker. It looks like a chip charging problem. Anyway I solved the flickering problem by tuning the ILI9488 registers. Simply you have to change the `initlcd.h` for ILI9481 driver in UTFT library.

```
enter code here

case ILI9481:

LCD_Write_COM(0x11);
delay(70);

LCD_Write_COM(0x38);//Idle Mode OFF
LCD_Write_COM(0x13);//Normal mode

LCD_Write_COM(0x36); // Memory Access Control  crucial
LCD_Write_DATA(0x0A);

LCD_Write_COM(0x55);
LCD_Write_DATA(0x22);//High enhancment of CE ratio

LCD_Write_COM(0xB1);
LCD_Write_DATA(0x70);
LCD_Write_DATA(0x10);

LCD_Write_COM(0xB4);
LCD_Write_DATA(0x10);

LCD_Write_COM(0xB5);
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x12);

LCD_Write_COM(0xB6);        // Display Function Control
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x21);       // 0x42 = Rotate display 180 deg.
LCD_Write_DATA(0x3B);

LCD_Write_COM(0xC0);
LCD_Write_DATA(0x1F);//0X1F
LCD_Write_DATA(0x01);//0X10

LCD_Write_COM(0xC1);
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x10);

LCD_Write_COM(0xC2);
LCD_Write_DATA(0x00);//0X44 lower better
LCD_Write_COM(0xC4);
LCD_Write_DATA(0x00);//0X10

LCD_Write_COM(0xC5);
LCD_Write_DATA(0x00);//0X10
LCD_Write_DATA(0x80);//optimum
LCD_Write_DATA(0x80);//0X10

LCD_Write_COM(0x3A);//Interface Pixel Format
LCD_Write_DATA(0x55);

LCD_Write_COM(0x2A);//Column Address Set
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x01);
LCD_Write_DATA(0xDF);//320

LCD_Write_COM(0x2B);//Page Address Set
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x00);
LCD_Write_DATA(0x01);
LCD_Write_DATA(0x3F);//480

delay(60);

LCD_Write_COM(0x29);//Display ON
delay(30);

LCD_Write_COM(0x2C);//Memory Write
delay(30);
break;

```
> 1 votes

---
Tags: arduino-mega, lcd
---


title: Arduino and DC Motor control board

text:
# Question
Title: Arduino and DC Motor control board
I've this PWM Module - 6V-90V 15A Pulse Width PWM DC Motor Speed Controller Switch which I use to control a peristaltic pump (ordinary DC motor), now I want to replace the potentiometer with an Arduino in order to create a soft-start for the pump by pressing a button. The control is a 0-5V input from the potentiometer, and the description says "*you can external drive*" and "*It could use of PLC controls speed of motor*", unfortunately I cannot provide datasheets or schematics.

Is it possible? Or I need a digital pot?

How should I wire it? The 3 cables from the board to the pot are: **ground, 0-5V and 5V**

# Answer
> 1 votes
Or you may exchange the whole controller with a power mosfet module connected to your arduino. And use pwm directly from your arduino. http://store.arduino.cc/product/T010020

# Answer
> 0 votes
Functionally you can replace the potmeter with a digital potmeter.
If your arduino runs on 5 volt, you can simply connect the grounds and the wire connected to the middle of the pot to a pwm pin. If the pwm pin does not work smoothly use a RC filter. That is a resis tor and a capacitor. As explained here instructables
If your arduino runs on 3.3 you can still use the rc filter but you need to add a bridge.

---
Tags: arduino-uno, motor, pwm, potentiometer
---


# Question
Title: Instantiating bounce library inside a class
I am trying to get my head around how to instantiate objects from existing libaries inside a class object. Specifically I am trying to get the bounce2.h debouncer working.

At the moment my code compiles but i think the debounce function is not working as the button is filling my array with lots of random numbers (even from setup) whereas it works fine on a non-class based sketch, so I think that I am probably not instantiating the bounce object correctly. If anyone can help I would be very grateful!

My header:

```
#ifndef CandleRack_h
#define CandleRack_h

class CandleRack
{
  public:

    CandleRack(byte candleRackStatus);
    void begin();
    void pushButton();
    void selectRandomCandle();
    void turnOnCandle(byte candlePosition);
    void burnCandlesForMs();
    void fadeOutCandle(byte candlePosition);

  private:
    Bounce _debouncePushButton;
    byte _pushButtonPin;
    byte _candleRackStatus;
    byte _candlePosition;
    byte _candleStatus[];
    elapsedMillis _candleTimeElapsed;
    unsigned int _candleOnForMs;
};
#endif

```

My cpp

```
#include "Arduino.h"
#include <FastLED.h>
#include <elapsedMillis.h>
#include <Bounce2.h>
#include "CandleRack.h"

#define NUM_LEDS 50

CandleRack::CandleRack(byte candleRackStatus)
{
  _candleRackStatus = candleRackStatus;
}

void CandleRack::begin()
{
  randomSeed(analogRead(0));

  _debouncePushButton = Bounce();
  _pushButtonPin = 3;
  _candleOnForMs = 20000;
  pinMode(_pushButtonPin, INPUT_PULLUP);
  _debouncePushButton.attach(_pushButtonPin);
  _debouncePushButton.interval(10);

  for (byte b = 0; b < NUM_LEDS; b++)
  {
    _candleStatus[_candlePosition] = 0;
  }

  Serial.println("Candle Array: ");       // Debug ************************
  for (byte b = 0; b < NUM_LEDS; b++)     // Debug ************************
  {                                       // Debug ************************
    Serial.print(_candleStatus[b]);       // Debug ************************
    Serial.print(", ");                   // Debug ************************
  }                                       // Debug ************************
  Serial.println("");                     // Debug ************************
  Serial.println("Begin Complete");       // Debug ************************
}

void CandleRack::pushButton()
{
  // Look for a button push
  if (_debouncePushButton.update())
  {
    if (_debouncePushButton.fell())
    {
      selectRandomCandle();
    }
  }
}

void CandleRack::selectRandomCandle()
{
  byte randomCandlePosition;
  do
  {
    randomCandlePosition = random(0, NUM_LEDS);
  }
  while (_candleStatus[randomCandlePosition] != 0);

  turnOnCandle(randomCandlePosition);
}

void CandleRack::turnOnCandle(byte _candlePosition)
{
  // leds[_candlePosition] = CRGB::Red;
  _candleStatus[_candlePosition] = 1;

  Serial.println("Button Pushed: ");      // Debug ************************
  Serial.println(_candlePosition);        // Debug ************************
  Serial.println("Candle Array: ");       // Debug ************************
  for (byte b = 0; b < NUM_LEDS; b++)     // Debug ************************
  {                                       // Debug ************************
    Serial.print(_candleStatus[b]);       // Debug ************************
    Serial.print(", ");                   // Debug ************************
  }                                       // Debug ************************
  Serial.println("");                     // Debug ************************
}

void CandleRack::burnCandlesForMs()
{
  // See if it is time to turn the candle off
  for (byte b = 0; b < NUM_LEDS; b++)
  {
    if (_candleTimeElapsed > _candleOnForMs && _candleStatus[b] == 1)
    {
      CandleRack::fadeOutCandle(b);
      _candleTimeElapsed = 0;
    }
  }
}

void CandleRack::fadeOutCandle(byte _candlePosition)
{
  _candleStatus[_candlePosition] = 0;
}

```

My sketch:

```
#include "Arduino.h"
#include <FastLED.h>
#include <elapsedMillis.h>
#include <Bounce2.h>
#include "CandleRack.h"

CandleRack MyCandleRack(0);

void setup() {
  delay(3000); // sanity delay

  Serial.begin(9600);
  while (!Serial);

  Serial.println("Setup Starts");  // Debug ************************

  MyCandleRack.begin();

  Serial.println("Setup Complate");  // Debug ************************
}

void loop() {

  MyCandleRack.pushButton();
 // MyCandleRack.burnCandlesForMs();

  FastLED.show();
}

```

edit - added the code from the original debounce example for a single sketch

```
// Detect the falling edge

// Include the Bounce2 library found here :
// https://github.com/thomasfredericks/Bounce-Arduino-Wiring
#include <Bounce2.h>

#define BUTTON_PIN 2
#define LED_PIN 13

int ledState = LOW;

// Instantiate a Bounce object :
Bounce debouncer = Bounce();

void setup() {

  // Setup the button with an internal pull-up :
  pinMode(BUTTON_PIN,INPUT_PULLUP);

  // After setting up the button, setup the Bounce instance :
  debouncer.attach(BUTTON_PIN);
  debouncer.interval(500);

  // Setup the LED :
  pinMode(LED_PIN,OUTPUT);
  digitalWrite(LED_PIN,ledState);

}

void loop() {

  // Update the Bounce instance :
   debouncer.update();

   // Call code if Bounce fell (transition from HIGH to LOW) :
   if ( debouncer.fell() ) {

     // Toggle LED state :
     ledState = !ledState;
     digitalWrite(LED_PIN,ledState);

   }
}

```

# Answer
> 1 votes
Your main issue (the cause of your symptoms) is the fact that you have no size for your `_candleStatus` array. Without specifying a size you end up with no memory allocated to the array, and hence no valid content.

In your class definition the line:

```
byte _candleStatus[];

```

should be modified to:

```
byte _candleStatus[NUM_LEDS];

```

and `NUM_LEDS` should be defined in the header, not in the CPP file. (By specifying it in the header file, since the header file is included in the CPP file, the definition ends up in both files).

Aside from that this line doesn't do what you think it does:

```
_debouncePushButton = Bounce();

```

You are copying the content of an anonymous bounce object created just for the occasion into a pre-existing Bounce object. You don't want that line to exist since the Bounce object has already been instantiated by the construction of your `CandleRack` object.

However there is something you need to be aware of known as the *Static Initialization Order Fiasco* which can bite you on the rear end if you are not aware of it. This is basically when you use objects in other objects and those objects haven't yet been properly created since you cannot predict the order in which objects are initialized. This may or may not be an issue in your system - it all depends on how the other classes you use behave.

One way around the issue, if you find it does become a problem (or if you just want to avoid the problem altogether) is to use pointers and what is known as *Construct On First Use*. This is where you don't instantiate any objects in your constructor or the class definition - instead you just have pointers to them and use the `new` keyword to construct the object from within a member function (such as `begin()`).

For this you change your class definition object entries to be pointers, such as:

```
Bounce *_debouncePushButton = NULL;

```

*(Note that not all versions of the compiler will support that assignment in the class definition. It's a modern addition to C++ and depending on your version of the Arduino software may or may not work. If it doesn't you can move the assignment into the constructor by removing the `= NULL` from the definition and adding `_debouncePushButton = NULL;` into the constructor.)*

Then construct a new object in the `begin()` function (if it hasn't already been created):

```
if (_debouncePushButton == NULL) {
    _debouncePushButton = new Bounce();
}

```

Now you have to access the `_debouncePushButton` as a pointer to an object not an object, so change all your accesses to use the pointer dereference operator `->`:

```
_debouncePushButton->attach(_pushButtonPin);
... etc ...

```

In case the class should ever go *out of scope* or be used in a *dynamic* way you really should create a *destructor* to delete any objects that have been created:

```
CandleRack::~CandleRack() {
    if (_debouncePushButton != NULL) {
        delete _debouncePushButton;
    }
}

```

Note that you should only ever try and delete objects that have actually been created - hence the test to see if it's not null.

Excessive use of `new` and `delete` though is discouraged, so it is best to use objects in a static context if possible. Too much `new` and `delete` or `malloc` and `free` can cause *heap fragmentation* which can lead to you running out of memory and all the associated stability problems that come with it.

Of course, all this is optional and chances are it won't be needed if the other classes behave well.

---
Tags: library, class, debounce
---


# Question
Title: RFID detects the first card fine, but hangs on a second
I am writing a program that:

1. Reads string (one line) from com port
2. Waits for an RFID card to be present
3. Reads a block from the card

Here's the code (it uses this MFRC522 library, also the code is based on makecourse.com RFID tutorial):

```
#include <SPI.h> //include the SPI bus library
#include <MFRC522.h> //include the RFID reader library

#define SS_PIN 10  //slave select pin
#define RST_PIN 9  //reset pin
MFRC522 mfrc522(SS_PIN, RST_PIN);        // instatiate a MFRC522 reader object.
MFRC522::MIFARE_Key key; //create a MIFARE_Key struct named 'key', which will hold the card information

byte readbackblock[18]; //This array is used for reading out a block. The MIFARE_Read method requires a buffer that is at least 18 bytes to hold the 16 bytes of a block.

String inString = ""; // COM port incoming data buffer

void setup() {
  Serial.begin(9600);        // Initialize serial communications with the PC
  SPI.begin();               // Init SPI bus
  mfrc522.PCD_Init();        // Init MFRC522 card (in case you wonder what PCD means: proximity coupling device)
  Serial.println("Scan a MIFARE Classic card");

  // Prepare the security key for the read and write functions - all six key bytes are set to 0xFF at chip delivery from the factory.
  // Since the cards in the kit are new and the keys were never defined, they are 0xFF
  // if we had a card that was programmed by someone else, we would need to know the key to be able to access it. This key would then need to be stored in 'key' instead.

  for (byte i = 0; i < 6; i++) {
    key.keyByte[i] = 0xFF;//keyByte is defined in the "MIFARE_Key" 'struct' definition in the .h file of the library
  }

}

void loop() {
  while (Serial.available() > 0) {
    int inChar = Serial.read();

    if (inChar != '\n') {
      inString += (char)inChar;
    } else {
      // New line

      Serial.println("Start");
      while (!initcard()); // Detecting new card
      Serial.println("CardFound");
      readBlockToCom(2); // Reading a block
      Serial.println("Done");
      inString = "";
    }
  }
}

bool initcard()
{
  // Look for new cards (in case you wonder what PICC means: proximity integrated circuit card)
  if ( ! mfrc522.PICC_IsNewCardPresent()) {//if PICC_IsNewCardPresent returns 1, a new card has been found and we continue
    return false; //if it did not find a new card is returns a '0' and we return to the start of the loop
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {//if PICC_ReadCardSerial returns 1, the "uid" struct (see MFRC522.h lines 238-45)) contains the ID of the read card.
    return false; //if it returns a '0' something went wrong and we return to the start of the loop
  }
  return true;
}

void readBlockToCom(int number)
{
  readBlock(number, readbackblock);//read the block back
  Serial.print("read block: ");
  for (int j = 0 ; j < 16 ; j++) //print the block contents
  {
    Serial.write (readbackblock[j]);//Serial.write() transmits the ASCII numbers as human readable characters to serial monitor
  }
  Serial.println("");
}

int readBlock(int blockNumber, byte arrayAddress[])
{
  int largestModulo4Number=blockNumber/4*4;
  int trailerBlock=largestModulo4Number+3;//determine trailer block for the sector

  /*****************************************authentication of the desired block for access***********************************************************/
  byte status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &(mfrc522.uid));
  //byte PCD_Authenticate(byte command, byte blockAddr, MIFARE_Key *key, Uid *uid);
  //this method is used to authenticate a certain block for writing or reading
  //command: See enumerations above -> PICC_CMD_MF_AUTH_KEY_A   = 0x60 (=1100000),      // this command performs authentication with Key A
  //blockAddr is the number of the block from 0 to 15.
  //MIFARE_Key *key is a pointer to the MIFARE_Key struct defined above, this struct needs to be defined for each block. New cards have all A/B= FF FF FF FF FF FF
  //Uid *uid is a pointer to the UID struct that contains the user ID of the card.
  if (status != MFRC522::STATUS_OK) {
         Serial.print("PCD_Authenticate() failed (read): ");
         Serial.println(mfrc522.GetStatusCodeName(status));
         return 3;//return "3" as error message
  }
  //it appears the authentication needs to be made before every block read/write within a specific sector.
  //If a different sector is being authenticated access to the previous one is lost.

  /*****************************************reading a block***********************************************************/

  byte buffersize = 18;//we need to define a variable with the read buffer size, since the MIFARE_Read method below needs a pointer to the variable that contains the size...
  status = mfrc522.MIFARE_Read(blockNumber, arrayAddress, &buffersize);//&buffersize is a pointer to the buffersize variable; MIFARE_Read requires a pointer instead of just a number
  if (status != MFRC522::STATUS_OK) {
          Serial.print("MIFARE_read() failed: ");
          Serial.println(mfrc522.GetStatusCodeName(status));
          return 4;//return "4" as error message
  }
  Serial.println("block was read");
}

```

The problem I'm having is that

1. I send first line via com port
2. Apply a card to RFID-RC522
3. The program reads the block alright
4. But then I send the second line
5. Arduino hangs on card detect

Here's the output I receive:

```
Scan a MIFARE Classic card
Start
CardFound
block was read
read block: makecourse_____
Done
Start

```

I tried removing card and applying it again or applying a different card, but it still freezes on card detect, sometimes after some time it works, though.

# Answer
> 4 votes
You should try adding this, at the end of `readBlock()`:

```
// Halt PICC
mfrc522.PICC_HaltA();
// Stop encryption on PCD
mfrc522.PCD_StopCrypto1();

```

---
Tags: arduino-uno, rfid
---


title: Running Steppers with servo

text:
# Question
Title: Running Steppers with servo
I'm doing a project which is automatic box carrier. It will hold a box from a location and move it next to it. Kind of cnc work. Locations are fixed it just has to run the orders. I want to send an array of integers and manage them in the switch under main loop. for example

```
  orders[0]=2;
  orders[1]=2000;

  orders[2]=3;
  orders[3]=60;

  orders[4]=1;
  orders[5]=7000;

  orders[6]=2;
  orders[7]=2000;

  orders[8]=3;
  orders[9]=90;

  orders[10]=1;
  orders[11]=2000;

```

will be my orders array and here is the code i want to run. When I upload code to arduino steppers and servo doing fine until orders\[8\]. When came to that order; first servo goes to 30 degrees then goes to 0 and click sound starts. After that steppers are not doing remaining steps.

```
#include <Servo.h>
Servo myservo;

int distance=0;
int code =0;
int orders[10]={};
int thisStep=0;
int thisVal=1;
int pos = 0;
int currpos=90;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);

  pinMode(2,OUTPUT);
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  digitalWrite(2,LOW);
  digitalWrite(3,LOW);
  digitalWrite(4,LOW);
  digitalWrite(5,LOW);
  myservo.attach(9);

  orders[0]=2;
  orders[1]=7000;

  orders[2]=3;
  orders[3]=60;

  orders[4]=1;
  orders[5]=2000;

  orders[6]=2;
  orders[7]=2000;

  orders[8]=3;
  orders[9]=30;

  orders[10]=1;
  orders[11]=2000;

 /* orders[12]=2;
  orders[13]=5000;*/
}

void loop() {

  code = orders[thisStep];
  switch (code){
    case 1:

    go(orders[thisVal]);
    thisStep = thisStep + 2;
  thisVal = thisVal + 2;

    break;
    case 2:
     Serial.println(thisVal);
    goReverse(orders[thisVal]);
    thisStep = thisStep + 2;
    thisVal = thisVal + 2;

    break;

    case 3:
    goServo(orders[thisVal]);
    thisStep = thisStep + 2;
    thisVal = thisVal + 2;
    break;
  }

}
void go(int dist){
  digitalWrite(2,LOW);
  digitalWrite(4,LOW);
  do{
  digitalWrite(3,HIGH);
  digitalWrite(5,HIGH);
  delayMicroseconds(10);
  digitalWrite(3,LOW);
  digitalWrite(5,LOW);
  delayMicroseconds(10);
  distance = distance+1;
  Serial.println(distance);
  }while (dist>distance);
 distance=0;
 delay(500);
}
void goReverse(int dist){
  digitalWrite(2,HIGH);
  digitalWrite(4,HIGH);
  do{
  digitalWrite(3,HIGH);
  digitalWrite(5,HIGH);
  delayMicroseconds(300);
  digitalWrite(3,LOW);
  digitalWrite(5,LOW);
  delayMicroseconds(300);
  distance = distance+1;

  }while (dist>distance);
  distance=0;
  delay(500);
}

void goServo (int degree){
  myservo.attach(9);
  myservo.write(degree);

  delay(300);
   myservo.detach();
  /*if (currpos > degree)
  {
    for (pos = currpos; pos >= degree; pos -= 1) { // goes from 0 degrees to 180 degrees
      // in steps of 1 degree
       myservo.write(pos);              // tell servo to go to position in variable 'pos'
       delay(15);
       // waits 15ms for the servo to reach the position
      }
      delay(500);
  }
  else if (currpos < degree)
  {
    for (pos = currpos; pos <= degree; pos += 1) { // goes from 0 degrees to 180 degrees
      // in steps of 1 degree
       myservo.write(pos);              // tell servo to go to position in variable 'pos'
       delay(15);
       // waits 15ms for the servo to reach the position
      }

  }
  currpos=degree;

*/

}

```

Thanks.

# Answer
Your problem here is that you have an array of 10 bytes, which works fine, only that in your loop you don't stop or check that you are within that array.

If this is supposed to run forever, you could add a line like this at the end of your loop:

```
if (thisStep > sizeof(orders)-1) thisStep = 0;

```

(-1 because you have an array of 10, which are from 0-9, sizeof will return 10)

this will make it start from the beginning again.
> 1 votes

---
Tags: arduino-mega, arduino-ide, servo, stepper
---


title: Uploading code to Arduino wirelessly

text:
# Question
Title: Uploading code to Arduino wirelessly
I have been working on a project watch which would work best if it is entirely sealed (to waterproof it). The watch may need future updates, but I will be unable to send code to it using a usb connector or isp programmer without opening the case. What is the best way to connect my PC with this watch wirelessly?

I gather that the serial ports are usually used to send code via the usb, and that most Bluetooth modules use serial coms to communicate with the Arduino.

The Arduino that I am using is an Arduino Pro Mini clone.

Any help will be greatly appreciated.

# Answer
> 1 votes
You could use ESP8266 and ESP-LINK firmware to update the arduino firmware over the wire. Its also enables you to debug it wirelessly. What it does is provide a serial link but over wifi. Just like connecting it via cable.

---
Tags: bluetooth, arduino-pro-mini, wireless
---


# Question
Title: Power 4 leds with max7219 and LedControl.h
So this is my first arduino (or embedded for that matter) project. I am trying to power 4 leds with max7219. Max7219 seems easy to use, but for some reason after I upload the code, nothing happens. I've looked over my breadboard, and the connections seem right. My confusion arises from the fact that all the projects I have found on google use matrices for the leds. I am using 4 separate leds. Does this even matter?

Here is the code I use:

```
#include "LedControl.h"

LedControl ledControl = LedControl(12, 9, 10, 1);

void setup()
{
    //should be waking ledcontrol
    ledControl.shutdown(0, false);
    ledControl.setIntensity(0, 8);
}

void loop()
{
    ledControl.setLed(0, 0, 0, true);
}

```

# Answer
No it shouldn't matter that you are using separate LEDs, but you will have to connect them in a way that is acceptable to the 7219, they will have to share either a common anode or cathode (can't remember which of the top of my head).

I find its always best to check the basics (Based on personal experience)

* Have you got the LEDs the correct way around?
* Are you using the correct voltage for everything?
* Do the LEDs work when controlled directly by the Arduino, try "Blink"?
* Have you tried changing the intensity?
* Have you got the required resistors in?
* Try inverting the index of the LEDs, i.e. led(x=0,y=0) might be wired (x=7,y=7)?

You loop() is not pausing, so all it is going to be doing is calling that one statement repeatedly. Now that might not be a problem or the second call may be blocking the first from completing. So I suggest add a delay for a second or so and see if that changes anything. Also to prove you are running you Loop() code flash the LED on the board (pin13?).

Hope that helps.
> 1 votes

---
Tags: led, max7219
---


title: Using #define and multiple classes

text:
# Question
Title: Using #define and multiple classes
I am using the FastLED library in my program and the basic usage is that the following lines go at the top of the main sketch:

```
#include <FastLED.h>
#define NUM_LEDS 60
#define DATA_PIN 6

```

You can see the documentation at https://github.com/FastLED/FastLED/wiki/Basic-usage

However, I am using the FastLED library in several different objects in my program and I would like to be able to reference NUM\_LEDS in different header files for each object so that the number of LEDS can be controlled just by changing the value in the main sketch.

I am also intending that my own objects can be made into libraries for others to use, so they will then define the settings in their main sketch, that my libraries will then use.

# Answer
> 1 votes
As the OP suggested, I'm posting a summing up of the comments under his question since the answer was found.

In order to make a common define for those parameters in different source files, the easiest solution is to make a shared header. To do this, just create a new file called `FastLedInclude.h` and, inside of that, write

```
#include <FastLED.h>
#define NUM_LEDS 60
#define DATA_PIN 6

```

Then in every source file you will just have to `#include "FastLedInclude.h"` to be able to use that library.

The FastLED library also requires the programmer to create a struct. Now, placing the definition of the struct (i.e. `struct CRGB leds[NUM_LEDS];`) into the header file leads to compilation errors, since the compiler writes the code to allocate it once for every object file.

The correct way to share this among different object files is to declare it `extern` in the header, then define it just once in one of the cpp or ino files:

```
// into FastLedInclude.h
extern struct CRGB leds[];

// into any cpp or ino file (but just once)
struct CRGB leds[NUM_LEDS];

```

This can also be done in the main ino sketch file, but personally I prefer to define it into another one (it depends, however, on how you choose to divide the program).

If you want to create a library, some other problems arise. The easiest solution is to ask the user to manually modify the header file which will be in the library folder. This solution is a bit uncomfortable, but it is the safest one.

Another solution is to force the user to create a header file into the sketch folder. Then the library should know the sketch folder path to back-include it. But.. This is a very discouraged option, since it will require the library to know the sketch location, thus violating the consistency principle at the base of a library-based approach.

The third solution is to modify the approach, from a compile-time static definition to a dynamic one. In order to do this, instead of defining `NUM_LEDS` and `DATA_PIN` at compile time you save them as variables in the library class.

For instance, in your library class definition you have

```
class yourclass
{
    public:
        yourclass(uint8_t data_pin, uint8_t num_leds);
        ~yourclass();
    private:
        uint8_t _data_pin;
        uint8_t _num_leds;
        struct CRGB *leds = NULL;
};

```

And the implementation can be

```
yourclass::yourclass(uint8_t data_pin, uint8_t num_leds)
{
    _data_pin = data_pin;
    _num_leds = num_leds;

    // Dynamic allocation of the array
    leds = (struct CRGB *) malloc(num_leds * sizeof(struct CRGB));
}

yourclass::~yourclass()
{
    // you should free the leds array when done
    free(leds);
}

```

Then the user can write

```
yourclass *obj = new yourclass(6, 60);

// or, if he wants to define,
#define NUM_LEDS 60
#define DATA_PIN 6
...
yourclass *obj = new yourclass(DATA_PIN, NUM_LEDS);

```

or, in the case of a statically allocated object,

```
yourclass obj(6, 60);

// or, if he wants to define,
#define NUM_LEDS 60
#define DATA_PIN 6
...
yourclass obj(DATA_PIN, NUM_LEDS);

```

---
Tags: library, class, rgb-led
---


# Question
Title: What are ideal delay times between commands for RF24 lib
Am working on a WiFi based irrigation system that utilises the RF24 lib for comms. Have got prototype of remote sensor up and running which has a standby current of 0.036mA and transmits data every hour using around a peak of 12mA. While running the prototype I see various retry attempts which seem to vary with every transmission – despite the setup being under the same conditions all the time. I have coded a retry loop to limit this to 10 tries connecting to the master – don’t want the sensor to continuously be sending without getting a confirmation from the master

What I am trying to find is the ideal delay required between various RF24 commands to limit transmit times as much as possible to conserve power usage. Any ideas?? (code snippets attached)

```
   pinMode(mostureSensorVCC, OUTPUT);
   digitalWrite (mostureSensorVCC, HIGH); //VCC to sensor
   pinMode(mostureSensor1, INPUT);      //moisture sensor on
   delay(10);
   int sensorValue1 = analogRead(mostureSensor1); // read the input on analog pin
   Serial.print("Current Value Sensor 1 is : "); // debugging
   Serial.println(sensorValue1); // print out the value you read:
   msg[0] = sensorValue1;
    digitalWrite(mostureSensor1, LOW);
    digitalWrite(mostureSensorVCC, LOW);
      while (message != sensorValue1)
        {

          Serial.print("sensorValue in while loop is "); // debugging
          Serial.println(sensorValue1);                   // debugging
          Serial.print("Message One is ");                // debugging
          Serial.println(message);                        // debugging
          radio.powerUp();
          delay(70);

          radio.stopListening();
          delay(50);
          radio.write(msg, 2);
          delay(40);
          radio.startListening();
          delay(50);

         Serial.println(d);               // debugging

          if (radio.available())
            {
             Serial.println("Radio available");     // debugging
              radio.read(msg, sizeof(msg));
              message = msg[0];
              Serial.print("Check Message received from master ");// debugging
              Serial.println(message);

            }
            if(d>=10)
            {
              Serial.println("Unable to send to master");
              break;
            }
       d++;
  }

delay(1000);
radio.powerDown();
message = 0;
msg[0] = 0;

```

# Answer
> 1 votes
Remove all delays except the one after startListening.

You could replace it with a "wait for radio.available to be true OR 50ms to have passed" piece of code. There is no need to wait for 50ms if the message was already received after e.g. 10ms.

Even better would be to use the ACK-package feature of the NRF. With this feature the master already prepares a package for the slave. Then when the slave sends it's message (every hour), the prepared package is included in the ACK (acknowledgement) packet.

As to optimizing it even further. It would be better to optimize the sleep code, then the send code. The sleep part will still use more power in an hour than the sending code, even if it takes 10 second to do so.

As to the lost packages. Try using a different channel. You also might want to get an NRF module with an real antenna, and maybe even an amplifier, for the master.

PS You can remove the serial.print in the deployed version.

---
Tags: sensors, nrf24l01+
---


# Question
Title: Can I hook up two micros to one GPS module?
I've worked with a few different GPS modules. Most of them seem to just pump out data and not really interact with the micro controller.

I have a quadcopter (Cheerson CX 20 Big Sky) It has a gps break out board that looks similar to the one I've worked with before. Is it likely that I connect another micro controller to this board? I want to add a cellular module to my quad.

I know that the answer may be "it depends" but before I start testing and researching I just want to know if it's even likely to work.

If the gps is just barfing out coordinates and not interacting with the main board I think it could work. I could just tap in and "listen" -- is this even a possibility?

# Answer
You are quite wrong. The answer is not "it depends", but "yes".

You can have any number of devices listening to (receiving) the transmitted data. You can only have one device sending anything back to whatever it is that is broadcasting the data if you need to configure it in any way. That shouldn't be a problem of course if you have one main controller that does that configuration and everything else is just a passive listener. Just be sure that you don't connect the transmit pins of the passive listeners to anything (unless you want to use them for a completely unrelated purpose to transmit serial data to something else).

The only caveat is that each device you add as a listener will increase the load on the GPS's transmit pin and eventually the *slew rate* will become too slow and the signal will become distorted. If this ever becomes an issue reducing the baud rate can combat it to a certain extent. For serial though you would need quite a lot of devices for it to become an issue. Two devices certainly won't ever be an issue.
> 2 votes

---
Tags: gps
---


# Question
Title: error while loading libtinfo.so.5 - SOLVED
I just installed the 1.6.7 version and want to upload it a sketch to Arduino UNO hardware. I get error message:

> /home/pali/Irataim/TarBalls/Arduino/arduino-1.6.7/hardware/tools/avr/bin/avrdude: error while loading shared libraries: libtinfo.so.5: cannot open shared object file: No such file or directory

I'm on Gentoo linux operating system.

How can I solve this problem?

By following this link:

https://forums.gentoo.org/viewtopic-p-7815500.html?sid=f67283068e3655b2f9e259a2097efef6
I just add tinfo USE flag to ncurses package, re-emerged it and can run Arduino IDE that I emerged from Gentoo repository.

# Answer
> 2 votes
Install `libtinfo5`, the terminfo library.

If that doesn't help, you can try to debug the problem yourself. First, check which libtinfo avrdude is looking for:

```
ldd arduino-1.7.8-linux64/hardware/tools/avr/bin/avrdude_bin | grep libtinfo

```

On my Ubuntu, I get this:

```
libtinfo.so.5 => /lib/x86_64-linux-gnu/libtinfo.so.5 (0x00007fa74a888000)

```

Next, see where your libtinfo is installed:

```
find /lib /usr/lib -name 'libtinfo*'

```

On my system I get:

```
/lib/x86_64-linux-gnu/libtinfo.so.5
/lib/x86_64-linux-gnu/libtinfo.so.5.9

```

Do you have any discrepancy between the two?

# Answer
> 2 votes
You have to rebuild `sys-libs/ncurses` with `tinfo` USE flag turned on. (You can also make a symlink: `libtinfo.so -> libncurses.so`, but it's not elegant solution).

Firstly, check if you have a record for ncurses in any file in `/etc/portage/package.use`. If not, create a file `/etc/portage/package.use/ncurses` with such content:

```
sys-libs/ncurses tinfo

```

then, rebuild ncurses:

```
emerge -av sys-libs/ncurses

```

---
Tags: upload
---


# Question
Title: How do I correctly use enum within a class?
I am trying to set the status of an object from a private enum and I'm not sure how to get the private member to the public version in the constructor, and I'm pretty sure I should not be using `byte` in the constructor when it's an enum.

Also, I'm not sure if I should even have the values of the enum inside the header at all. Here is my code:

.h

```
class CandleRack
{
  public:

    CandleRack(byte candleRackStatus);
    ~CandleRack();
    void begin();
    void pushButton();
    void selectRandomCandle();
    void turnOnCandle(byte candlePosition);
    void burnCandlesForMs();
    void fadeOutCandle(byte candlePosition);

  private:
    Bounce *_debouncePushButton;
    byte _pushButtonPin;
    enum _candleRackStatus
    {
      inactive = 0,
      candlesOn = 1,
      rewardAnimation = 2,
      tweetArrived = 3,
      partyMode = 4,
    };
    byte _candlePosition;
    byte _candleStatus[NUM_LEDS];
    elapsedMillis _candleTimeElapsed[NUM_LEDS];
    unsigned int _candleOnForMs;
};

```

.cpp

```
CandleRack::CandleRack(byte candleRackStatus)
{
  _candleRackStatus = candleRackStatus;
  _debouncePushButton = NULL;
}

```

in the sketch

```
CandleRack MyCandleRack(0);

```

error:

```
error: expected unqualified-id before '=' token
_candleRackStatus = candleRackStatus;

```

Thanks!

# Answer
I see two separate issues here.

First of all your enum isn't available as a variable. By declaring it as a private type within your class the enum can't be used outside of that class.

This forces a user of that class to handle unintended calls like (attention, *bug*):

```
CandleRack(255);

```

which can make code harder to read (and debugging more difficult, since it wouldn't be detected by the compiler).

Second of all you try to directly assign a byte *value* to an enum *type*. This will be rejected by the compiler and/or cause runtime errors later (depending on compiler settings).

I recommend that you declare the enum type so that it is accessible directly via the header file:

.h

```
enum CandleRackStatus {
    inactive = 0,
    candlesOn = 1,
    rewardAnimation = 2,
    tweetArrived = 3,
    partyMode = 4,
};

class CandleRack
{
  public:

    CandleRack(CandleRackStatus candleRackStatus);
    ~CandleRack();
    void begin();
    void pushButton();
    void selectRandomCandle();
    void turnOnCandle(byte candlePosition);
    void burnCandlesForMs();
    void fadeOutCandle(byte candlePosition);

  private:
    Bounce *_debouncePushButton;
    CandleRackStatus _candleRackStatus;
    byte _pushButtonPin;
    byte _candlePosition;
    byte _candleStatus[NUM_LEDS];
    elapsedMillis _candleTimeElapsed[NUM_LEDS];
    unsigned int _candleOnForMs;
};

```

Now you can instantiate your class while using the correct enum type as the parameter.

.ino

```
CandleRack MyCandleRack(CandleRackStatus::inactive);

```

Within your implementation you can now directly store the constructor parameter in the private variable, the compiler will make sure it's always of the correct enum type:

.cpp

```
CandleRack::CandleRack(CandleRackStatus candleRackStatus) {
    _candleRackStatus = candleRackStatus;
    // rest of your initialisiation goes here
}

```

As an added bonus, there's the possibility to use a couple of C++ language features that will make your implementation easier:

.h

```
class
{
  public:
    CandleRack(CandleRackStatus candleRackStatus = CandleRackStatus::inactive);
    // [...]
}

```

.cpp

```
CandleRack::CandleRack(CandleRackStatus candleRackStatus) : _candleRackStatus(candleRackStatus) {
    // rest of your initializiation goes here
}

```
> 4 votes

# Answer
How about this refactoring?

```
class CandleRack
{
  public:
    enum status_t
    {
      inactive = 0,
      candlesOn = 1,
      rewardAnimation = 2,
      tweetArrived = 3,
      partyMode = 4,
    };
    CandleRack(status_t status = inactive);
    ~CandleRack();
    void begin();
    void pushButton();
    void selectRandomCandle();
    void turnOnCandle(byte candlePosition);
    void burnCandlesForMs();
    void fadeOutCandle(byte candlePosition);

  private:
    Bounce *_debouncePushButton;
    byte _pushButtonPin;
    status_t _candleRackStatus;
    byte _candlePosition;
    byte _candleStatus[NUM_LEDS];
    elapsedMillis _candleTimeElapsed[NUM_LEDS];
    unsigned int _candleOnForMs;
};

```

And in a sketch with either the default setting (inactive)

```
CandleRack MyCandleRack;

```

or explicit

```
CandleRack MyCandleRack(CandleRack::candlesOn);

```

Cheers!
> 0 votes

---
Tags: variables, class
---


# Question
Title: How to get a button state change within a for loop?
I have a `for` loop inside my `void loop()` that triggers a piezo.

What I want to happen is when I press a button, it breaks the loop of the piezo, but right now, it's as if it isn't detecting the button press inside my `for` loop.

Here's my code:

```
#include <Adafruit_NeoPixel.h>

#define PIN 6
#define TONE 8
const int buttonPin = 2;

long fadeTime = 5 * 1000L; // X minutes
int colorStops = 256;
int delaySpeed = fadeTime / colorStops;
int notes[] = {262,294,330,349};
int switchState = 0;         // variable for reading the pushbutton status

Adafruit_NeoPixel strip = Adafruit_NeoPixel(5, PIN, NEO_RGB);

void setup() {
  pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input

  strip.begin();
  strip.show();
}

void loop() {
  // read the state of the pushbutton value:
  switchState = digitalRead(buttonPin);

  // Fade in light
  for(int i = 1; i<colorStops; i++){
    for(int np = 0;np<strip.numPixels(); np++){
      strip.setPixelColor(np, strip.Color(i,i,0));
    }
    strip.show();
    delay(delaySpeed);
  }

  // Play tone after light fully bright
  for(int i = 1; i<100; i++){
    // Turn off tone on button press
    if (switchState == HIGH) {
      noTone(TONE);
      break;
    }
    tone(TONE, notes[random(0,3)]);
    delay(100);
  }
}

```

Does `switchState = digitalRead(buttonPin);` only get called at the start of the `void loop` and so it can't detect the button change until then? Something else?

Also, in case it's useful, here's my hardware set up...

# Answer
You aren't reading the state of the button within your loop.

You only read it the once at the top of your `loop()`:

```
void loop() {
  // read the state of the pushbutton value:
  switchState = digitalRead(buttonPin);

```

You need to replicate that every time you want a new reading from the button - so in your loop you need to add that `digitalRead` line:

```
// Play tone after light fully bright
for(int i = 1; i<100; i++){
  // Turn off tone on button press
  switchState = digitalRead(buttonPin);
  if (switchState == HIGH) {
    noTone(TONE);
    break;
  }
  tone(TONE, notes[random(0,3)]);
  delay(100);
}

```

Or you can do away with the variable altogether and just test the return value of the `digitalRead`:

```
// Play tone after light fully bright
for(int i = 1; i<100; i++){
  // Turn off tone on button press
  if (digitalRead(buttonPin) == HIGH) {
    noTone(TONE);
    break;
  }
  tone(TONE, notes[random(0,3)]);
  delay(100);
}

```
> 1 votes

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


# Question
Title: Failed to read DHT22 sensor using Intel Galileo Gen2 board
Why do I end up with the display

> Failed to read from DHT sensor!

in the serial monitor in most cases when I run the code given below? When I reduce the delay to 1000ms the reading shows 0.00 for both temperature and humidity which, as well, is pretty much false. Any help would be highly appreciated.

```
// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain

#include "DHT.h"

#define DHTPIN 2     // what pin we're connected to

// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// Initialize DHT sensor for normal 16mhz Arduino
DHT dht(DHTPIN, DHTTYPE);
// NOTE: For working with a faster chip, like an Arduino Due or Teensy, you
// might need to increase the threshold for cycle counts considered a 1 or 0.
// You can do this by passing a 3rd parameter for this threshold.  It's a bit
// of fiddling to find the right value, but in general the faster the CPU the
// higher the value.  The default for a 16mhz AVR is a value of 6.  For an
// Arduino Due that runs at 84mhz a value of 30 works.
// Example to initialize DHT sensor for Arduino Due:
//DHT dht(DHTPIN, DHTTYPE, 30);

void setup() {
  Serial.begin(9600);
  Serial.println("DHTxx test!");

  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements.
  delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  // Compute heat index
  // Must send in temp in Fahrenheit!
  float hi = dht.computeHeatIndex(f, h);

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hi);
  Serial.println(" *F");
}

```

# Answer
The article link by Nick is the same that I found, so it must be a well search problem.

What is described on the Intel forum is that the Galileo is not capable of direct communication with the sensor as it is a computer and not a microcontroller, so therefore lacks the ability for accurate timing required by the sensor and also the DHT\* is considered a peripheral and would thus require a way to interface with the "PC".

What is described in the post is to use two pins to create the proper digital signal for the DHT.

The circuit makes use of a diode to protect the output pin.

The OP on the forum describes the connections like this:

> Pin 2 of Galileo is connected to the data pin of the DHT11.
>
> Cathode of the diode is connected to pin 3 of the Galileo.
>
> Anode of the diode is connected to the DHT11 data pin.

The diode would be a standard diode, possibly a fast switching signal diode as the 1N4143. The resistor would be the standard pull up resistor of 10K Ohms.

Here is the OPs schematic:

<sub>(source: intel.com)</sub>

You will also need to make use of the code linked to by the OP in the linked post as it was modified to work with the workaround.
> 1 votes

---
Tags: sensors, arduino-galileo
---


title: Code problem w/ Uno+GPS+GPRS?

text:
# Question
Title: Code problem w/ Uno+GPS+GPRS?
I've got an Arduino Uno, SIM900 GPRS, and the Adafruit Breakout GPS.

Can this code be optimized?

```
 #include <SoftwareSerial.h>
 #include <TinyGPS++.h>
 #include <Ubidots_Arduino_GPRS.h>
 //Serial Relay - Arduino will patch a
 //serial link between the computer and the GPRS Shield
 //at 19200 bps 8-N-1
 //Computer is connected to Hardware UART
 //GPRS Shield is connected to the Software UART
 #define APN "myapn"
 #define USER ""  // If your apn doesnt have username just put ""
 #define PASS ""  // If your apn doesnt have password just put ""
 #define TOKEN "ubidotsToken"  // Replace it with your Ubidots token
 #define ID "Your_id_here" // Replace it with your Ubidots' variable ID
 // You can send 1 to 10 variable at the same time
 #define ID1 "idHere" // Replace it with your variable ID
 //#define ID2 "" // Replace it with your variable ID
 //#define ID3 "Your_id_here" // Replace it with your variable ID

 TinyGPSPlus gps; // The TinyGPS++ object for interfacing with the GPS
 //Declare indexes, and strings
 char latitude[12];
 char longitude[12];
 float value_1 = 1;
 char var[18] = "Lat: ";
 char var2[18] = "Long: ";
 Ubidots client(TOKEN);
 SoftwareSerial ss(2,3);
 void setup() {

 // the Serial port of Arduino baud rate.
   Serial.begin(9600);

   client.powerUpOrDown();
   client.setApn(APN,USER,PASS);
 //.endC is for _client.end() in Ubidots_GPRS.cpp
   client.endC();
   ss.begin(9600);
 }

 void loop() {

   //handling GPS data parsing
   while (ss.available() > 0) {
     gps.encode(ss.read());}
   //Once a valid location comes up it updates Lat/Long variables
    if (gps.location.isUpdated())
 {
     strcpy(var, "Lat: ");
     strcpy(var2,"Long: ");

     dtostrf(gps.location.lat(),10,6,latitude);
     strcat(var, latitude);

     dtostrf(gps.location.lng(),10,6,longitude);
     strcat(var2, longitude);
   //Added ss.flush();
     ss.flush();
     ss.end();
     Serial.flush()
   //Added client.beginC() for _client.begin(9600) is Ubidots_GPRS.cpp
     client.beginC();
     client.add(ID1, value_1, var, var2);
     client.sendAll();
     client.endC();
     ss.begin(9600);
   }
  Serial.println(var);
  Serial.println(var2);
 }

```

From this link, I moved the **println** from inside **.isUpdated()** to outside the if statement. I was able to get GPS data sent from the unit to my Ubidots account while driving around town. Afterwards I was able to input the data into Google Maps and the route produced was accurate. Do I need flush()?

# Answer
> 0 votes
It seems you're using the same hardware `Serial` port for both your PC and the GPS module. This will result in the GPS module receiving everything you send to the PC with `Serial.print()` and this may be the cause of your problem, as it could confuse the module and either make it send an endless stream of gibberish and/or making `isValid()` to always be false. You should instead create a `SoftwareSerial` instance attached to any 2 digital pins (maybe 2 and 3) like this:

```
SoftwareSerial ss(2, 3);

```

and in `setup()`:

```
ss.begin(9600);  // use your module baud rate

```

Then at the top of `loop()`, use this instead:

```
while (ss.available() > 0)
    gps.encode(ss.read());

```

Get rid of the recursive call of `loop()` within `loop()` since it will cause your stack to rapidly overflow.

If you want data to only be sent when the location values are *updated* based on recent received data (but not necessarily *changed*, since you may still be at the same location), you should use `if (gps.location.isUpdated())` instead.

Your call of `dtostrf()` is also wrong. The second argument should be the length of the string to be created (including decimal point) and the 3rd argument should be the number of digits after the decimal point. Something like this should be okay:

```
dtostrf(gps.location.lat(), 10, 6, latitude);

```

You can also put this at the end of `loop()` to check if data is actually being received from the module and processed by the library:

```
if (millis() > 5000 && gps.charsProcessed() < 10)
  Serial.println(F("WARNING: No GPS data.  Check wiring."));
  while (1){ // infinite loop
    if (ss.available())
      Serial.print(ss.read());
  }
}

```

This site may provide additional details.

---
Tags: gps, tinygps
---


# Question
Title: Stacking Arduino Shield (Motor Shield, LCD Keypad, LED Sensor)
I'm building a line follower with arduino, here some part that I'm going to use

I'm using LiPo Batteries 3 Cell 11.1v for power source.

I'm new in here so I didn't know how to stack that shield, if I recall I can stack up Arduino and the LCD Keypad, and Arduino and the Motor Shield, but didnt know how to stack those 2 together and adding another sensor like that line tracking sensor. May I know how to resolve that? thanks.

# Answer
> 3 votes
The Motor Shield 2A plugs in on top of the Arduino Uno, and the LCD Keypad plugs in on top of the motor shield. \[But see *Edit 1* below\]

There is better information about the 4 Channel Line Tracking Sensor at uctronics.com where you can see that its main board (with the LM339 chip) connects to the Arduino via six lines: Vcc, Gnd, Out1, Out2, Out3, Out4. That main sensor board does not mount on the stack, but instead can be located whereever is convenient and leaves its four comparator-level pots accessible for adjustment. Mount the four small boards for the tracking module as convenient and necessary for line following.

For connecting the six lines from the sensor main board to the Uno, you probably will need to solder two headers (rows of pins) to a board in the stack. Using right-angle headers (see below) will allow the pins to come out of the side of the stack without interfering with other layers of the stack. One of the headers should let you connect sensor Out1...Out4 digital outputs to four otherwise unused analog or digital pins, and the other header should let you connect Vcc and Gnd.

***Edit 1:*** In the LCD shield page, section 2 (Diagram) shows Vcc, Gnd, and D0-D3 available at the top right corner (the angled corner). Those six pins probably are a reasonable place to add a six-pin angled header for the sensor board.

Given that the LCD KeyPad Shield is a DFRobot.com model, the summary pinout at shieldlist.org shows that its use of D4,5,6,7 will conflict with use of those same lines by the DFRobot 2A Motor Shield. There are several ways to handle a conflict like this: **1,** use two Uno's, one per shield; **2,** make one shield or the other use different lines; **3,** share the lines.

**Method 2** could work as follows: Stack the LCD shield directly on the Uno (or any other compatible Arduino). Besides a header for the sensor board, add a header for a cable to the motor board, and drive the motor board's D4-7 inputs with some other lines from the Uno, eg A4-7. \[Alternately one could remove the D4-7 pins on the LCD shield and jumper from A4-7 to the D4-7 lines on the LCD shield. This would leave the boards in a single stack but would make some serious changes to the LCD board.\]

**Method 3** would work as follows: The LCD shield only pays attention to D4-7 (which from the DFRobot schematic drive DB4-DB7 on an LCD TC1602 chip) when the TC1602's E line is strobed. See pages 7 and 8 of Adafruit.com's copy of TC1602 specs, where timing diagrams show about half-microsecond times for writing to or reading from the TC1602.

You would need to run tests with your motors and see if they work ok in spite of the four inputs to the motor shield being random during the occasional half-microseconds that data is being written to the LCD. You might have to add more diodes or capacitors to suppress electrical noise due to rapid switching.

DFRobot's motor shield page has links to that board's schematic and to its L298 chip data sheet. Page 7 of the datasheet says

> An external bridge of diodes are required when inductive loads are driven and when the inputs of the IC are chopped; Shottky diodes would be preferred.

The motor shield schematic shows diodes; although not drawn using Schottky diode symbols they might be Schottky anyway (which would give better noise suppression, less heating, etc). The schematic also shows that JP1, a 16-pin dual row header, has jumpers that control ENA and ENB on the L298. In a "proper solution" for sharing D4-7 between the LCD and motor shields, you'd drive ENA and ENB low when using D4-7 for LCD i/o, which would allow the attached motors to briefly free run, as opposed to being suddenly commanded to stop or reverse.

# Answer
> 1 votes
The most elegant approach would probably be to use shields controlled by the I2C bus. I've found LCD+keypad and motor shield offered by Adafruit for example.

The I2C bus is shared by all slaves connected to it, and you should find microswitches on each shield to set its I2C address.

Regular shields should not interfere with I2C lines, so as last resort you can put one shield controlled "traditional way".

---
Tags: sensors, lcd, arduino-motor-shield
---


title: Do I need capacitors for these LEDs?

text:
# Question
Title: Do I need capacitors for these LEDs?
I have 5 of these NeoPixel LED's.

For these particular LED's, they recommend "use of a 0.1 μF capacitor between + and ground".

Here's what I've got:

The blue's are 100 μF and the little brown ones are...I have no idea. Both were just in this starter kit. Maybe 100 pF?

So, a few questions around this...

1. Are these actually necessary and why?
2. Is there any harm in using much higher capacitors than recommended?

# Answer
> 7 votes
The capacitors are called *decoupling capacitors* and are used to provide current at very short notice.

The LEDs, when not fully on or fully off, switch rapidly on and off. This switching needs current to be provided very rapidly at short notice, and batteries and power supplies aren't good at that - so you have the capacitors to act as a little reservoir of power that the LEDs can dip into.

The size of the capacitor (capacitance) can have an effect on how effective they are. Bigger capacitors respond slower than smaller ones, but store more energy. So you need the capacitor to be small enough for it to respond fast enough. But if you have it too small it won't store enough energy to give to the LEDs and they will be unable to do their job.

0.1µF (or 100nF), aka "104" capacitors are usually reckoned to be a good rule-of-thumb value to use since they are small enough to respond rapidly and yet large enough to store enough power for most small high speed fluctuations. The exact value though doesn't matter that much, however I would be wary about going below that, and going too high can be troublesome for other reasons as well as their slow response (google: "Inrush Current"). So you don't want to go too high. Around the 0.1µF to 1µF area is where you want to be, with maybe a 10µF for every group of 5 or so LEDs.

I would say 100µF is way too high to have on every LED, but maybe one of those on the breadboard where the power is fed in would be useful to provide a reservoir for larger low frequency demands from the rest of the board.

# Answer
> 1 votes
> Are these actually necessary and why?

The datasheet for the WS2812 says a "typical application circuit" should have them:

If the manufacturer recommends it, I would say it is necessary. I'm sure they would be happy to not have to recommend extra parts, but testing would have shown they are necessary. As Majenko replied, putting in 100 µF when you only need 0.1 µF seems way overkill (to say nothing of more expensive).

And don't forget the 150R resistors, eh?

---
Tags: arduino-uno
---


title: The importance of I/O pin DC current

text:
# Question
Title: The importance of I/O pin DC current
I am thinking about buying Arduino or Raspberry Pi. I generally know Arduino advantages (fast start-up, low consumption, ADC converters) and disadvantages (low memory, low connectivity, hard programming), but I simply cannot figure out maybe the most important issue: current output for controlling devices.

One of the common cited advantages of Arduino system compared to Raspberry Pi system is that power per I/O pin is much larger. Arduino Uno allegedly has up to 20 mA @ 5 V per pin and 50 mA @ 3.3 V per pin making quite substantial power of 0.15 W, compared to say typical 10 mA @ 5 V per pin for Raspberry Pi (although there is no official number available).

On the other hand

* this power is far too low to control any motors and you still have to provide shields,
* new version Arduino 101 reduced that current to 20 mA and even less for some other Arduino models.

So, what is really the importance (if any) of these higher currents for home projects, compared between different Arduinos themselves and compared to Raspberry Pi?

There is also a question of total current for all pins together, which is also limited, but it is soooooo difficult to get official limits (for both Arduino and Raspberry Pi).

Please give me some insight into this issue, so I can decide.

# Answer
The simple answer is: **It doesn't matter.**

Both Arduino and the Raspberry Pi, and every other common microcontroller board, are designed to control things, not provide power to things.

Digital IO pins aren't designed to drive heavy loads. Yes, some (like the Arduino) can provide slightly more current, but that is really unimportant for most projects.

Yes, some boards have more powerful power supply circuits on them so you can draw more current from their power supplies, but again that is largely irrelevant.

The one thing that you seem to be forgetting (or haven't realised) is that *the microcontroller board does not have to supply **all** the power.*

The Arduino, Pi, Teensy, chipKIT, whatever, is merely a controller. If your system needs more current it is up to you to provide that current. The Arduino etc merely controls the circuit or device that it is connected to.

It is very common to have multiple power supplies in a large project - each providing different voltages, or being used for different specific tasks within the project.

Just one thing you need to remember: **Connect the grounds.**
> 3 votes

# Answer
Bottom line is: the controllers are just not meant for supplying power.

They do have the ability to do so, within limits - fairly stringent limits for a controller chip itself, and *slightly* more generous limits for the on-board power supply. If you really need an all-in-one, you might consider making building your own controller board with a more capable on-board power supply and a number of transistor switches to provide power for the hungrier devices, that can be switched by the MCU chip.

Note that this will not improve the chip's ability to supply power - you can't, by any practical means - but the board can, through the switching transistors.

Figure out your project's power budget, or the budget you'd like to have for your future projects, and design an on-board power supply to exceed that by a healthy margin-of-safety. Likewise, for the individual switched circuits, in order to choose a sufficiently robust switching transistor.

If you prefer an off-the-shelf solution, one of the available motor-driver boards is probably a good choice but it will need to have an independent power supply if there isn't one on the driver board.
> 3 votes

# Answer
I bought a Pi a while back, and found it so tedious to use I put it in my parts drawer and haven't used it since. A Pi is like a small Unix PC - you have to install an operating system, boot it up (which takes time) and then install device drivers etc.

The Arduino (particularly the Uno) boots in under a second, and "just works". It is much easier to use for small to medium projects.

As for the current, as others have replied, you aren't supposed to be powering things, like motors, from the output pins. 20 mA is a nice amount of current to flash an LED, or send data to another device. The output pins are for **data** not for driving things like motors. If you need more than 20 mA you should be looking at driver circuits, like transistors or MOSFETs.

> ... hard programming ...

I wouldn't say that. You program in C++. What are you going to program the Pi in? There are many libraries for the Arduino to simplify programming, but you can get down to the "bare metal" quite simply.
> 3 votes

---
Tags: current
---


title: Flashing dotStar LED

text:
# Question
Title: Flashing dotStar LED
I have a DotStar LED strip that I want to make it blink (e.g., 1 second on, 5 second off in an endless loop).

I tried doing so via the script below but it does not work. Can someone please explain me how to do so?

Script:

```
#include <Adafruit_DotStar.h>
#include <SPI.h>

#define NUMPIXELS 10

#define DATAPIN    4
#define CLOCKPIN   5
Adafruit_DotStar strip = Adafruit_DotStar(NUMPIXELS, DATAPIN, CLOCKPIN, DOTSTAR_BRG);

void setup()
{
  strip.begin();
  strip.show();
}

void loop()
{
  strip.show();
  strip.setBrightness(155);
  for (int i=0; i <= 10; i=i+1) {
    strip.setPixelColor(i, 255, 255, 255);
  }
  delay(1000);

  strip.setBrightness(0);
  delay(5000);
}

```

# Answer
> 3 votes
The authors of the library are not fans of the `setBrightness()` method and advise handling it yourself.

The following code should do what you want.

```
#include <Adafruit_DotStar.h>
#include <SPI.h>

#define NUMPIXELS 60 // This should be the total number of LEDs in your strip

#define DATAPIN    4
#define CLOCKPIN   5
Adafruit_DotStar strip = Adafruit_DotStar(NUMPIXELS, DATAPIN, CLOCKPIN, DOTSTAR_BRG);

void setup()
{
  strip.begin();
  strip.show();
}

void loop()
{

  // loop through each pixel in the control array setting it to the colour mix you want.
  for (int i=0; i <= NUMPIXELS; i=i+1) {
    strip.setPixelColor(i, 25, 25, 25); // Even 25 on my strip gives reasonably bright flash
  }

  strip.show(); // Then push the control array to the strip
  delay(1000); // and leave it set for a while

// Then do it again for the 2nd brightness in your scheme

  // loop through each pixel in the control array setting it to off.
  for (int i=0; i <= NUMPIXELS; i=i+1) {
    strip.setPixelColor(i, 0, 0, 0);
  }

  strip.show(); // Then push the control array to the strip
  delay(1000); // and leave it set for a while

}

```

# Answer
> 2 votes
The basic idea of the program you're trying to write is:

```
loop() {
  strip.show(); // Turn LED strip on.
  delay(1000);  // One second, argument is milliseconds.
  strip.setBrightness(0); //Turn LED strip off.
  delay(5000);
  strip.setBrightness(155); //Turn LED strip on.
}

```

I haven't used the Adafruit DotStar library, so there may be details that I'm missing (like do you need to do a `strip.show()` after setting the brightness). But maybe this is enough to get you thinking about how to construct the program.

The real joy in hacking with something like this is the experimenting and the learning. Take the time to try to understand how you project works and to predict what will change as you modify the code and how you can tell if it is working the way you expect – that will get you a long way towards being a strong programmer.

When you're troubleshooting something new and/or unfamiliar, one thing that really helps is to break down the problem into simple steps. For example with this project a good first step would be to get the DotStart strip to turn on. Then see if you can get it to turn off. Build it up piece by piece.

---
Tags: led
---


# Question
Title: Does not name a type error when using makeTime
I am getting a "does not name a type" error when trying to use `makeTime()` from the Time.h library, code snippet as follows:

```
#include<Time.h>

tmElements_t tmet;
tmet.Year = 2013-1970;
tmet.Month = 8;
tmet.Day = 28;
tmet.Hour = 18;
tmet.Minute = 30;
tmet.Second = 0;

time_t dateMet = makeTime(tmet);

```

Alternatively I've also tried `time_t dateMet = maketime(&tmet);` with the same result. I am no expert so go easy on me but am I missing something small here?

Thanks

# Answer
You're trying to access the '*properties*' (i.e. the *members*) of the `tmet` variable in a scope where they aren't accessible (outside of a code block). In this global scope of the program the compiler expects a type name on the left side of a statement (i.e. a variable or type declaration), but `tmet`'s members like `tmet.Year` aren't types in and of themselves.

There are two solutions. You can move the access to the members of `tmet` into a code block like the `setup` function:

```
#include <Time.h>

tmElements_t tmet;
time_t dateMet;

void setup() {
  // put your setup code here, to run once:
    tmet.Year = 2013-1970;
    tmet.Month = 8;
    tmet.Day = 28;
    tmet.Hour = 18;
    tmet.Minute = 30;
    tmet.Second = 0;

    dateMet = makeTime(tmet);
}

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

}

```

Or you could declare and define `tmet` in one statement, which has a different syntax (since you have to provide the content of a `tmElements_t` in a single line:

```
#include <Time.h>

tmElements_t tmet2 = { 2013-1970, 8, 28, 18, 30, 0 };

time_t dateMet2 = makeTime(tmet2);

void setup() {
  // put your setup code here, to run once:
}

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

}

```

Both versions work right away from within the Arduino IDE (i.e. I tested them).
> 3 votes

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