title: How Arduino IDE works?

text:
# Question
Title: How Arduino IDE works?
You know , a simple arduino sketch has no main function , no include preprocess cmds,so I just want to know how arduino IDE convert a sketch to normal C/C++ source code,and what is the source code looks like.

If possible,I also want to use cmd like *g++ -E* to see the .i file genetated after preprocess.How to do it?

ps: my English is poor.

# Answer
You can turn on verbose compiling.
This will show all the compiler commands used by Arduino IDE.

The ino file is converted to a .cpp file (which you can see in the verbose output). Basically the conversion is as follows:

1. merge all .ino files into one big .ino file with the \[project\].ino file first
2. Add arduino.h
3. Add all function declarations of methods defined in the .ino files
4. Save as .cpp file

As to the lack of main method. The core contains a main.cpp file which defines main in avr world this looks like

```
int main(void)
{
    init();

    initVariant();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

```
> 6 votes

# Answer
I'm not entirely sure what the `arduino-builder` does, but it should be similar to the traditional method.

Given the "bare minimum" sketch of:

```
void setup() {
}

void loop() {
}

```

First the IDE combines all `.ino` and `.pde` files together into one large one. I believe the order of concatenation is:

1. Start with the "main" INO file (the one named the same as the folder it's in).
2. Append to that each other `.ino` or `.pde` file in alphabetical order.

Then the IDE will add the required `#include <Arduino.h>` and function prototypes for any functions found - so it would end up as:

```
#include <Arduino.h>

void setup();
void loop();

void setup() {
}

void loop() {
}

```

Finally it runs normal `gcc` and `g++` commands on the generated file(s). You can find the generated file(s) in the *build* folder. Where that is depends on the operating system you are using. Turn on *verbose compilation* in the preferences and you can see the `gcc` and `g++` commands that are being executed, and as well the paths for the files involved, which lets you then see where the preprocessed files are stored.

Another important step the IDE performs, which doesn't modify the files themselves, is to look for any `#include` entries that match libraries and add `-I <path>` to the compilation commands for those libraries. It also then finds any source files associated with those libraries and compiles them. It also compiles all the *core* source files, which is where the `main()` functions is (see @jantje's answer for details on how the `main()` function is formed).

Once the IDE has finished with its parsing and processing it's all standard `gcc` and `g++`.
> 5 votes

---
Tags: arduino-uno, arduino-mega, arduino-ide
---


title: Use registers as parameter?

text:
# Question
Title: Use registers as parameter?
I'm writing a helper class to manage timers, and I'm writing a lot of code like

```
if (timer == 1)
        ICR1 = icr;
    else if (timer == 3)
        ICR3 = icr;
    else if (timer == 4)
        ICR4 = icr;
    else if (timer == 5)
        ICR5 = icr;

```

Is there a better way to store these registers? e.g. an array

```
timers {
{ ICR1, TCCR1A, OCR1A, OCR1B },
{ ICR2, TCCR2A, OCR2A, OCR2B }

```

etc.

to be accessed like

```
timers[1][0]

```

for ICR1.

And ultimately, how would I assign a value? e.g.

```
*timers[1][0] = 100;

```

**UPDATE:**

I solved the problem with

```
volatile uint16_t* ICRs[5];
ICRs[1] = &ICR1;
ICRs[3] = &ICR3;
ICRs[4] = &ICR4;
ICRs[5] = &ICR5;

*ICRs[1] = x;

```

# Answer
> 1 votes
registers are nothing but pointers to memory addresses. so the best way to "parameterize" them is to do so via pointers.

*assuming* that ICRi is of 8-bit types - they are NOT to be sure:

```
uint8_t *ICRs[4];  //isr pointers

//initialize the icrs
ICRs[0]=(uint8_t *)&ICR0;
ICRs[1]=(uint8_t *)&ICR1;
...

*ICRs[i]=icr; //assign value to ICRi

```

*note:* that piece of code isn't operable in reality. The way to go is to use a pointer to void. But I'm sure you can figure that out.

# Answer
> 2 votes
i would suggest creating macro definitions for the timers you want

Something along the lines of:

```
#define OCR_BY_INDEX(i) OCR##i
//...other code...
OCR_BY_INDEX(1) = value;

```

and then have the indices in an array

# Answer
> 1 votes
You can better use a switch statement:

```
switch (timer)
{
case 1:
    ICR1 = icr;
    break;

case 3:
    ICR3 = icr;
    break;

case 4:
    ICR4 = icr;
    break;

case 5:
    ICR5 = icr;
    break;

default:
    // Handle other cases
    break;
}

```

About the variables:

You can make a 2 dimensional array:

```
typedef enum
{
   TYPE_ICR,   // Value 0
   TYPE_TCCRA, // Value 1
   TYPE_OCRA,  // Value 2
   TYPE_OCRB,  // Value 3
   TYPE_LAST,  // Value 4
} EType;

EType timers[TYPE_LAST][2];

```

You can access it by

```
timers[(int) TYPE_OCRB][0] = 3;
timers[(int) TYPE_OCRA][1] = 0;

```

Maybe the (int) cast is not needed.

You also can just iterate over the type:

```
for (int type = 0; type < (int) TYPE_LAST; type++)
{
    timers[type][0] = -1;
    timers[type][1] = -1;
}

```

Note 1: if a cast is needed probably static\_cast(...) is better to use. Note 2: I haven't tested the code above

---
Tags: timers
---


# Question
Title: Arduino nano select port option is blurred | Driver issue
I have just bought arduino nano board. when i connect the board via usb, system detects the new device but i am not able to select port in arduino ide for writing any code on board. I checked my device manager it says

> The drivers for this device are not installed. (Code 28)
>
> There are no compatible drivers for this device.

I have also updated my board and library list in arduino ide.

please help me out?

# Answer
> 2 votes
on my nano board CH340G USB\<--\>uart chip was present, so i installed driver for that chip and everything works fine now. :P

link for the driver (windows 8,10): http://www.arduined.eu/ch340-windows-8-driver-download/

---
Tags: arduino-nano
---


# Question
Title: How to generate two pulses one with 60 and other 66 duty cycle at same instant in 2 pins?
I have to drive two switches one at a duty cycle of 60% and the other at a duty cycle of 66% simultaneously at 50khz frequency. I am using an Arduino Uno ATmega 328.

# Answer
I proposed a few approaches in generating 100kha pwm pulse trains here in response to someone's ask a couple of days ago. The identical code would work for your purpose as well.

It should come up quickly if you do a scan of topics here.

edit: to make it a little bit easier, here is the code I used to generate 50Khz pulse train with 60% and 66% duty cycles.

```
void setup() {
  // put your setup code here, to run once:
  //pinMode(led1, OUTPUT);                      //led1 as output
  //pinMode(led2, OUTPUT);                      //led2 as output
  pwm1topr(F_CPU / F_PWM);                      //set tmr1/pwm frequency to F_PWM
  analogWrite(led1, F_CPU / F_PWM * 60 / 100);  //led1 @ 60% duty cycle
  analogWrite(led2, F_CPU / F_PWM * 66 / 100);  //led2 @ 66% duty cycle
}

void loop() {
  // put your main code here, to run repeatedly:
    //digitalWrite(led, HIGH);  // turn the LED on (HIGH is the voltage level)
    //delay(100);               // wait for a second
    //digitalWrite(led, LOW);   // turn the LED off by making the voltage LOW
    //delay(100);               // wait for a second
}

```

and a quick sim confirms its functionality.

enjoy.
> 0 votes

---
Tags: pwm, atmega328
---


title: Help using thermistor with esp8266

text:
# Question
Title: Help using thermistor with esp8266
So I am trying to use this thermistor to measure temperature and with this code below it always puts the same value (2147483647). I used this tutorial to do the wiring and coding. I don't think the wiring is the problem but think the problem is somewhere in my code or perhaps I am using a wrong type of thermistor? Am I missing something? Any help is greatly appreciated.

I am only using a 1k resistor in series with the thermistor but don't think that would be a problem, right?

Edit: I should have mentioned I'm using the adafruit huzzah esp8266 so there are a few pins.

```
#include <DHT.h>
#include <ESP8266WiFi.h>
#include <Phant.h>
#include <ESP.h>

#define DHTPIN 2
#define DHTTYPE DHT22
#define THERMISTORPIN 4

DHT dht(DHTPIN, DHTTYPE);

const char* ssid = "xxxx";
const char* password = "yyyyyy";
const char* host = "data.sparkfun.com";
const String publickey = "uuuuuu";
const String privatekey = "ttttttt";
const byte NUM_FIELDS = 5;
const String fieldNames[NUM_FIELDS] = {"ghumidity", "gtemp", "light", "otemp", "wtemp"};
String fieldData[NUM_FIELDS];

//thermistor variables
const int thermresistor = 987; //value of resistor in series with thermistor
int thermtemp = 0;
uint8_t i;
uint8_t numsamples = 5;
uint8_t To = 25;
const int B = 3950;

void setup(){
    Serial.begin(115200);
    delay(10);
    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
  delay(500);
}

    fieldData[0] = 1; //humidity
    fieldData[1] = 2; //garden temp
    fieldData[2] = 3; //light
    fieldData[3] = 4; //outside temp
    fieldData[4] = 8; //water temp

//turnpumpon();
posttophant();
//turnpumpoff();
ESP.deepSleep(1200000000, WAKE_RF_DEFAULT);

}

void posttophant()
{
    fieldData[0] = dht.readHumidity();
    fieldData[1] = dht.readTemperature(true);

    //read outside temp (otemp) data and convert to a temp
    for (i=0; i<numsamples; i++){
      thermtemp = analogRead(THERMISTORPIN);
      thermtemp += thermtemp;
      delay(10);
    }

    //take the sum of all the readings and divide by # of samples to get avg.
    thermtemp = thermtemp / numsamples;

    #voltage divider equation
    thermtemp = thermresistor / (1023 / thermtemp - 1);

    //Steinhart eqn.
    thermtemp = 1 / (log(thermtemp / thermresistor) / B + (1 / (To + 273))) - 273;
    fieldData[3] = String(thermtemp);

    WiFiClient client;

    const int httpPort = 80;
if (!client.connect (host, httpPort)){
  return;
}

    client.print("POST /input/");
    client.print(publickey);
    client.print("?private_key=");
    client.print(privatekey);
    for (int i=0; i<NUM_FIELDS; i++)
    {
      client.print("&");
      client.print(fieldNames[i]);
      client.print("=");
      client.print(fieldData[i]);
    }
    client.println(" HTTP/1.1");
    client.print("Host: ");
    client.println(host);
    client.println("Connection: close");
    client.println();
}

```

# Answer
> 3 votes
**Considerations about the ESP8266 analog pin**

The ESP8266 has only one pin that allows analog read. This pin is call A0 on the NodeMCU module or A on the ESP8266 Huzzah (some other ESP module don't expose that pad - for example ESP8266-01) or might label it differently - check the documentation of your ESP module. Following your edit: make sure that you connect your thermistor to the A pin of the Huzzah ESP8266 module.

You should keep in mind that this analog pin is a 10bit ADC with in principle limited input voltage range.

To read an external voltage applied to the ADC pin, use `analogRead(A0)`. Unless you are using a board specially design to increase its range, the input voltage range is 0 — 1.0V. As @dandavis pointed out some boards (Node MCU e.g.) include a voltage divider on board to give you a full 0 - 3.3V input range.

**Thermistor equations**

The datasheet of your thermistor states that the TCR coefficient is 3000ppm/%C and has a 10K value \[note that the manufacturer doesn't provide you with the temperature at which R = 10K\]. The equation of the resistance variation ∆R with temperature variation ∆T is given by:

`∆R = ∆T*10k*3000ppm = 30*∆T`

So if T\_0 is the temperature where R = 10k, the equation of the resistance value is given by:

`R = 10k + (T-T_0)*30`

I am assuming that you are using the 3.3V supply of your ESP and creating a voltage divider using the 1K resistor and the thermistor. There are two ways to do this divider:

*1. Voltage divider option 1*

simulate this circuit – Schematic created using CircuitLab

\[Note that the thermistor needs to be connected to the A pin of your ESP8266.\]

*2. Voltage divider option 2*

simulate this circuit

**Equation of voltage at node A**

For both case here is the voltage V\_A seen at node A:

*1. Voltage divider option 1*

`V_A = R_series *3.3 / (R_th + R_series)`

*2. Voltage divider option 2*

`V_A = R_th *3.3 / (R_th + R_series)`

**Analysis of the variations of V\_A with temperature**

Lets look at the difference between the 2 formulas above:

*1. Voltage divider option 1*

The numerator is a constant with temperature while the denominator changes with T. You will get a strong variation.

*2. Voltage divider option 2*

Both the numerator and denominator increase with temperature. You won't get a lot of variation on V\_A with temperature. *You should avoid this configuration.*

**Analysis of the maximum allowed value of R\_series**

The important consideration is that for your ESP module V\_A cannot be higher than 1V.

*1. Voltage divider option 1*

Increasing R\_series will increase V\_A so we compute a **maximum** value: `1V = 3.3V*R_series_max/(R_series_max+10K)`

That gives you: `R_series_max = 4300Ohms`

*2. Voltage divider option 2*

Increasing R\_series will decrease V\_A so we compute a **minimum** value: `1V = 3.3V*10k/(R_series_min+10K)`

That gives you: `R_series_min = 23kOhms`

This is the reason why it was suggested to you using a 30k resistor in that case.

**Considerations about temperature measurement precision**

The voltage variation `∆V` on the node `A` of the ESP between temperature T1 and T2 can be computed as follow: `∆V = 3.3 *1K/(1k + 10k + 30*T1) - 3.3 *1K/(1k +10k+ 30*T2)`

If we assume that the thermistor is 10K for ambient temperatures the baseline voltage measured on the `A` pin is: `3.3V*1K/11k = 0.3V`

For a 0 to 1V 10bit DAC of the ESP8266 that is around: 2^10\*0.3 = 307

A change of 10C would lead to a variation of voltage of: `∆V = 0.3 - 3.3 *1K/(11k + 300) = 8mV ~8ADC code`

The equation of ∆T vs ∆V is not linear but for small variation of temperature with your current setup you get ~1ADC code per degree.

Depending of your application this might not be enough for you. As suggested in several comment you could:

* Add more thermistors in parallel
* Increase the 1K series resistor (but not too much or you will saturate the ADC).
* Change the architecture of the measuring circuit (RC oscillator using the thermistor and interrupt counter in the ESP, 555 timer circuit loaded with the thermistor and interrupt counter, ...)
* Or since you want to do humidity and temperature measurement why don't you get the BME280 module. It can be read over I2C and libraries are readily available to read it with the ESP8266.

# Answer
> 1 votes
Re “the problem is somewhere in my code”, lots of places in the code have problems.

• The following loop does not add up readings; it takes a bunch of readings and throws them away, then doubles the last one. For example, if the five readings in a row are 300, 400, 500, 600, and 100, `thermtemp` is 200 after the loop. To see this, try it out – mentally simulate what the code does, writing down the value of `thermtemp` after each step.

```
for (i=0; i<numsamples; i++) {
   thermtemp = analogRead(THERMISTORPIN);
   thermtemp += thermtemp;
   delay(10);
}

```

• Your “voltage divider equation” (below) has a form like that shown in the Adafruit tutorial, but because *your* `thermtemp` is declared as an `int` (vs Adafruit's `float`), integer division with truncation will be used, producing inaccuracy.

```
thermtemp = thermresistor / (1023 / thermtemp - 1);

```

• Your Steinhart-Hart equation is miscoded. At that step, the fixed resistor's value, `thermresistor`, is no longer relevant. The relevant value is the ADC reading as converted to thermistor resistance.

• In your Steinhart-Hart misimplementation, `log(thermtemp / thermresistor)` takes log of zero because in integer arithmetic, `thermtemp / thermresistor` is zero.

• The expression `1 / (To + 273)` is zero in integer arithmetic.

# Answer
> 1 votes
There are a few possible issues you're having:

First off, from what I understand, the ESP8266 ADC only reads up to 1V. If wired per the Arduino example you cited, and using 1K, you'll have VCC-\>1K-\>THERMISTOR-\>GND. At room temp the thermistor is 10K, so the voltage at the ADC will be 3.3\*(10K/(1K+10K)), so pretty close to 3.3V. I don't know the behavior of the ADC when overrange, but I'd assume you'd just get 0xFFFF. You'll probably want \>30K in series with the thermistor to get it into a usable range.

I also see a subtle error(I think) in your code:

```
//read outside temp (otemp) data and convert to a temp
for (i=0; i<numsamples; i++){
  thermtemp = analogRead(THERMISTORPIN);
  thermtemp += thermtemp;
  delay(10);
}

```

Should be:

```
//read outside temp (otemp) data and convert to a temp
thermtemp = 0
for (i=0; i<numsamples; i++){
  thermtemp += analogRead(THERMISTORPIN);
  delay(10);
}

```

Otherwise thermtemp is just the last reading added to itself.

Lastly, I would probably make the part of the code that posts the result to a function and call it throughout your calculations of the temp, to see if anything weird happening.

Hope this helps.

---
Tags: arduino-ide, esp8266, temperature-sensor
---


# Question
Title: Directly read analog voltage using PWM duty cycle timer registers
I'm outputting an analog voltage by setting an 8-bit duty cycle using `analogWrite`. Once set, I'd like a way to read back this duty cycle. I've managed to read the duty cycle back from the `OCR4D` register, which matches the value set, e.g.:

```
pinMode(6, OUTPUT);
analogWrite(6, 123);
Serial.print(OCR4D);   // 123

```

However, when setting the duty cycle to `0` or `255`, `OCR4D` is not actually set at all; instead `analogWrite` calls `digitalWrite` behind the scenes and the pin is digitally set to `LOW` or `HIGH`. This is seen in the source for `analogWrite`:

```
if (val == 0)
{
    digitalWrite(pin, LOW);
}
else if (val == 255)
{
    digitalWrite(pin, HIGH);
}
else
{
// set PWM duty cycle as normal...

```

The problem with this is that `OCR4D` is simply left at its previous value, so it's not always possible to tell the actual output by reading `OCR4D` alone. In other words there is no way to tell the difference between: \- PWM is active and `OCR4D` reflects the duty cycle \- PWM is disabled and `OCR4D` reflects a previous duty cycle (which is not useful)

Which register(s) can I read to crosscheck the PWM is active?

I'm also aware of the `pulseIn` function, but would rather read the PWM register directly.

# Answer
In the end I managed to do this by reading the timer/counter control register relevant to pin 6:

```
// read the voltage on an analog output pin
int analogReadOutput(int pin) {
    switch(digitalPinToTimer(pin)) {
        case TIMER4D:
            if (TCCR4C & (1 << COM4D1)) {   // PWM active
                return OCR4D;
            } else {                        // PWM not active
                return 255 * digitalRead(pin);
            }
        case TIMER4A:
            if (TCCR4A & (1 << COM4A1)) {   // PWM active
                return OCR4A;
            } else {                        // PWM not active
                return 255 * digitalRead(pin);
            }
        default:
            return -1;
    }
}

```

Note that this assumes two things that possibly aren't always true (outside of my simple program):

* `COM4D1` bit is a reliable way of telling if PWM is enabled,
* duty cycle value is 8 bit with a max of 255.
> 1 votes

---
Tags: pwm, arduino-leonardo, analogwrite
---


# Question
Title: How to display extended ASCII characters, e.g., the standard degree symbol, DEC 167, on the Serial Monitor [not LCD]?
I spent an afternoon researching this, and read a lot of material, but with no successful results. \[I really thought this would be a trivial task.\]

Is this problem Windows, or WIN10, specific, as the extended characters all seem non-displayable? Regardless, is there a solution?

# Answer
> 3 votes
The Arduino serial monitor uses UTF-8, per the discussion at http://forum.arduino.cc/index.php?topic=172814.0 --

For the U+00B0 degree symbol, you'd send the bytes UTF8 `0xC2 0xB0` like this:

```
Serial.print("°");

```

---
Tags: arduino-ide
---


# Question
Title: Programming Micro controllers using Arduino ISP
Can I burn my Arduino Code into this:

http://www.microchip.com/wwwproducts/en/ATSAM3A4C

or something similar by just using just the Arduino ISP?

# Answer
> 1 votes
Page does nog exist (404).

Also, to run actual Arduino code on it, you'll most likely have to port the Arduino library, if this hasn't been done before.

You may opt for something as easy as a teensy 3.2, they probably meet your requirements and work well in combination with Arduino. Or fetch one of the newer Arduino models that have comparable microcontrollers

If you still want an M3 (without development board?) you'll be entering a somewhat advanced usecase, in which you probably don't even want to rely on or use Arduino. There are far better IDE's.

# Answer
> 0 votes
I don't know about that chip I think this one also can be done as some of the other chips can be programmed using the Arduino ISP I think it can be even done for this one. This one uses an AVR ISP Programmer while we are using the Arduino one but as they have similar working It is maybe possible. For example this one

---
Tags: programming, arduino-ide, atmel
---


title: Sketch Memory and EEPROM

text:
# Question
Title: Sketch Memory and EEPROM
Since I'm running out of sketch memory, I've decided to use the 512 bytes of EEPROM memory by using `EEPROM.put(addr,variable)`. But every time I use this my sketch memory use in gradually increasing. What am I missing in writing data to EEPROM? Why is the sketch memory use increasing? I'm using Arduino Pro Mini.

# Answer
> What am i Missing in writing data to EEPROM ? Why is the Sketch memory getting increased ?

Reading and writing to EEPROM will increase program memory size. They are function calls. One way to reduce code is to read/write blocks instead of single bytes. Post some code and we can help you rewrite to something smaller. There are plenty of tricks.
> 3 votes

---
Tags: eeprom
---


# Question
Title: Arduino board is turning off when I connect to +5V
I am trying to set up an LCD screen without using a resistor or a potentiometer for an Arduino project. This is the LCD I am using: Basic 20x4 Character LCD.

But when I connect to +5V on the Arduino board, my Arduino board turns off. This is how I have the LCD connected to the Arduino on a breadboard.

Connections:

LCD RS pin to digital pin 12

LCD Enable pin to digital pin 11

Data:

• LCD D4 pin to digital pin 5

• LCD D5 pin to digital pin 4

• LCD D6 pin to digital pin 3

• LCD D7 pin to digital pin 2

LCD R/W pin to ground

LCD VSS pin to ground

LCD Cathode pin to ground

LCD Anode pin to digital pin 9

LCD VCC pin to 5V

Code:

```
// include the library code:
include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  analogWrite(6,20);
  // set up the LCD's number of columns and rows:
  lcd.begin(20, 4);
  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop() {
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis() / 1000);
}

```

# Answer
Try out this connection. It will helpful.
> 4 votes

# Answer
Looking at your picture, it seems that you're powering everything through a USB cable. USB 1.x and 2.0 can supply up to to 500 mA **AFTER** the port is enumerated, otherwise the current is limited to 100 mA.

A quick current consumption budget:

* LED backlight of your LCD module: typ **240 mA**
* Arduino Mega2560: min **70 mA**
* MIDI shield: some **15-35 mA**

That's just 325-350 mA to begin with, and probably higher than that. It's still safely within the 500 mA limit, but as I said some computers will provide 500 mA only after successful enumeration of the device connected to the USB port.

My recommendation for you would be to power your Arduino + MIDI shield + LCD through a wall adapter \> 7V. If it works, then the problem is your USB port being unable to supply the required current right from the start.
> 0 votes

---
Tags: arduino-mega, power, lcd, wires
---


# Question
Title: Fastest way to send serial commands and do something
I am trying to send a lot of serial commands really fast. I basically need to change color of my LED strip many times per second (10 times per second should really be enough). If I do this over WiFi, it will eventually clutter up and make the ESP8266 unresponsive. I need to send the colors as hex, then convert them into usable values (HEX to RGB). Something tells me that's going to cost a lot of resources and the MCU is therefore spending a lot of time just converting the colors into RGB values. Here's a pseudo code example of what I am trying to achieve:

```
void loop() {
    if(Serial.available()) {
        if(Serial.read().first(8) == "0xABCDEF") {
            //0xABCDEF is basically my indicator saying "this is for individual LEDs"
            //Serial.read() can now be something like 0xABCDEF FF0000 00FF00 0000FF FFFFFF 000000
            char* colors[] = Serial.read().split(" ");
            colorLED(colors);

        }
    }
}

void colorLED(colors) {
    for(i = 1; i < colors.length; i++) {
        strip.SetPixelColor(i, color[i]);
    }
}

```

I hope this example makes sense. I can send a serial command like `0xABCDEF FF0000 00FF00 0000FF FFFFFF 000000`. 5 colors in HEX.

My real question is: How do I take a lot of inputs like above (or another way) and turn them into strings, so I can convert them to RGB? Is there a better way to send commands (like pure RGB values? but remember I need to send many)?. Here is how I convert my colors into RGB:

```
//hexColor can be "FF0000"
int number = (int)strtol(&hexColor[0], NULL, 16);

int r = number >> 16;
int g = number >> 8 & 0xFF;
int b = number & 0xFF;

```

# Answer
> 2 votes
Simple answer: don't.

Don't even consider strings in any form. Instead you want a state machine.

In pseudocode:

1. Start with an invalid count number (-1)
2. Read a character.
3. If that character is `x` then set your counter to 0.
4. Otherwise, if counter is 0 or more, convert the character to a number and place it into the right byte depending on the value of your counter
5. Increment counter
6. If counter is 6 then set your LED colours and set the counter to "invalid".
7. Return to start.

Or, in untested C:

```
static int8_t counter = -1;
static uint8_t r = 0;
static uint8_t g = 0;
static uint8_t b = 0;

if (Serial.available()) {
    char c = Serial.read();
    if (c == 'x') {
        counter = 0;
    } else {
        if (c > 0x39) c -= 7;
        uint8_t v = c & 0x0f;
        switch (counter) {
            case 0: r = v << 4; break;
            case 1: r |= v;
            case 2: g = v << 4; break;
            case 3: g |= v;
            case 4: b = v << 4; break;
            case 5: b |= v;
        }
        counter++;
        if (counter == 6) {
            counter = -1;
            analogWrite(3, r);
            analogWrite(5, g);
            analogWrite(6, b);
        }
    }
}

```

The "clever" bit that may confuse you is:

```
if (c > 0x39) c -= 7;
uint8_t v = c & 0x0f;

```

That is, if the character is greater than a "9" (character 0x39) then it *should* be a-f. Subtracting 7 from it converts ASCII HEX from `0123456789ABCDEF` to `0123456789:;<=>?`. If you then mask it with 0x0F you end up with a number between 0 and 15, or 0-F in hex.

The rest just takes each nibble and places it into the right half of the right colour variable.

# Answer
> 0 votes
Since Majenko is convinced that using binary is far too complicated here's how to do it in binary sending 32 bits per color.
The start of strip marker is any 4 non-zero bytes in a row e.g 0x01010101
Each LED is then sent as four binary bytes: 0x00, 0xRR, 0xGG, 0xBB

In the unlikely event that a byte is lost in transmission then it will re-sync at the start of the next update, depending upon the pattern there is a fair chance that lost data will be noticed and the incorrect colors not get displayed on the strip.

```
loop() {
  static color_t color;
  static int8_t counter = -1;
  static int ledIndex = 0;
  static bool aligned= false;

  if (Serial.available()) {
    if (aligned) {
    switch (counter) {
      case 0: color.r=Serial.read(); break;
      case 1: color.g=Serial.read(); break;
      case 2: color.b=Serial.read();
              strip.SetPixelColor(ledIndex, color);
              ledIndex++;
              break;
      case 3: // first byte of next data, should always be 0
              // only not 0 if we've lost a byte or want to restart the strip
              if (Serial.read() != 0) {
                aligned=false;
                counter = 0;
              } else
                counter = -1;
              break;
      default: break;
    }
    counter++;
  } else { // not aligned
    ledIndex = 0;
    if (Serial.read() != 0) // count non-zeros
      counter++;
    else {
      if (counter >= 4)     // had a start marker, next byte is r
        aligned = true;
      counter = 0;
    }
  }
}

```

Is it worth doing it in binary? It gives a 50% decrease in RS232 data which if serial data rate is an issue will be a big help. It also gives a decrease in required calculations, if you look at the code there are virtually no mathematical operations beyond increasing counters.
Personally I prefer this method because it just seems more efficient and cleaner to transfer numbers as numbers rather than converting them to text and back but ultimately if you don't need every last bit of performance then it comes down to what you feel most comfortable with.

---
Tags: serial, esp8266
---


# Question
Title: How to send data in response to HTTP get request from ESP8266?
I'm trying to control some RGB LEDs with ESP8266. I have built an HTML page to set the color and send the RGB color code to the ESP using HTTP get request. Everything works as expected. I just want to send an HTTP get request to the ESP and ask what the current color is. But after a couple of hours of searching and trying I don't know how to send data in response to get request, I just can send HTTP ok code. I'm using jquery to send get command as below

```
$.get("http://192.168.4.1/rgb(120,50,60)", function(data,status){
    //I don't know how to send data fram ESP get it here.
});

```

this is the corresponding ESP response code written in Arduini IDE

```
WiFiClient client = server.available();
   if (client) {
  String req = client.readStringUntil('\r');
  client.print("HTTP/1.1 200 OK\r\n");
  client.print("Access-Control-Allow-Origin: *");
.
.
.

```

This is the HTTP header, How do I send some data(text)?

# Answer
> 1 votes
@Gerben answered my question in a comment all credit goes to him. I retype it here maybe it helps someone in the future.

I had to send two new line after setting up the header

```
//header
client.print("\r\n\r\n");
clinet.print("Hello, I'm comming from ESP!!");

```

And in jQuery I get it like this:

```
$.get("http://192.168.4.1/rgb(120,50,60)", function(data,status){
    var receivedData=data;  //=Hello, I'm comming from ESP!!
});

```

It is simple but it may help some newbie like me.

---
Tags: esp8266, http
---


# Question
Title: Using N mosfet to switch ESC to BLDC phases
I have an ESC that powers 36v 3 phase BLDC motor. The ESC has limited functionality and can power motor only in one direction. If I switch manually two of the ESC to Motor phase connections, than the motor direction will change. Now, I want to do the same i.e. switching phase to phase connections with 4 power mosfets.

As in scheme, the blue ESC phase will be connected to Mosfet source and the drain will be connected to Motors yellow phase. The next mosfet will connect to ESC yellow at source and motor blue at drain. Two other mosfets will connect blue to blue and yellow to yellow.

I won't do the switching while motor is on so I assume it should be safe.

How can I connect MOSFET's gate to Arduino ? I need no pwm just ON/OFF.

# Answer
> 0 votes
This is covered fairly well in an EDN.com “MOSFET pair makes simple SPDT switch” article. You would use two of the SPDT circuits to make a DPDT. Attach switch commons to yellow and blue, and attach the “switch points” of one circuit to motor yellow and blue, and those of the other vice versa. Attach both control pins to one Arduino IO pin. The picture below comes from the referenced article, which shows the circuit in use for a primary-power vs secondary-power application. See the article for details.

---
Tags: motor, mosfet
---


# Question
Title: How to find if AC Appliance is on or off using ACS712 current Sensor
I am trying to get the status of appliance using current sensor. My Circuit looks like below image. I don't want to measure current. I just want to know whether appliance is on or off.

I am getting following readings when power turned on and off, I don't see any difference, I am not able to figure out whether the bulb is on or off.

Please help me to know the status of appliance/bulb.

PS. Please find my code below:

```
/*
Measuring AC Current Using ACS712
www.circuits4you.com
*/
const int sensorIn = A0;
int mVperAmp = 185; // Use 100 for 20A Module and 66 for 30A Module

double Voltage = 0;
double VRMS = 0;
double AmpsRMS = 0;

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

void loop(){

 Voltage = getVPP();
 VRMS = (Voltage/2.0) *0.707;  //root 2 is 0.707
 AmpsRMS = (VRMS * 1000)/mVperAmp;
 Serial.print(AmpsRMS);
 Serial.println(" Amps RMS");
}

float getVPP()
{
  float result;
  int readValue;             // value read from the sensor
  int maxValue = 0;          // store max value here
  int minValue = 1024;       // store min value here

   uint32_t start_time = millis();
   while((millis()-start_time) < 1000)  // sample for 1 Sec
   {
       readValue = analogRead(sensorIn);
       // see if you have a new maxValue
       if (readValue > maxValue)
       {
            /*record the maximum sensor value*/
           maxValue = readValue;
       }
       if (readValue < minValue)
       {
           /*record the minimum sensor value*/
           minValue = readValue;
       }
   }

   // Subtract min from max
   result = ((maxValue - minValue) * 5.0)/1024.0;

   return result;
 }

```

# Answer
The code looks like it would produce rather larger values than you are seeing, if it gets correct inputs from the sensor. For that reason, you probably should carefully check your wiring. Also, with a DVM, measure the sensor output voltage with the light on and with it off, to verify sensor operation. If you measure ok sensor voltages but don't get good readings, your analog input pin may have a problem; you could try other analog input pins.

Note, when debugging an issue like this, it does not make sense to run a few numbers through five levels of processing before printing anything out. You should at least add serial prints in `getVPP()`, and just before returning the result, print out `result`, `maxValue`, and `minValue`.

Note, fix the erroneous comment “//root 2 is 0.707”; the square root of 2 is about 1.414213562, while 1/√2 = (√2)/2 is about 0.707106781.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: How to change baudrate of ESP8266 (12e) permanently?
## IMPORTANT: DO NOT USE `AT+IPR=9600`! (see update)

I have an ESP8266 12E module that communicates at 115,200 bauds. Since I use it with an Arduino Nano with SoftwareSerial things get messy. So I found that I should reduce the baud rate of the ESP module.

I found this link on how to do it.

**I am wondering**

* Is this a permanent change or do you need to do this every time after the module is powered?
* Can I achieve the same by sending the command from the Arduino over SoftSerial? Well, I guess not since I tried and I always get an error on `AT+CIOBAUD=9600` or `AT+IPR=9600`.
* I read somewhere that in newer firmware versions of the ESP8266, the baud rate defaults to 9,600. Can anyone confirm this and if so, is it better to flash this newer firmware?

The module's vendor:

```
Ai-Thinker Technology Co.,Ltd.

```

I think the current version of the firmware is 0.3.0. If I send `AT+GMR` I get:

```
sending AT+GMR

response: ?AT¥TJÕ¨H(Q�²•ÉÍ¥½¹é‚r¢‚r‚r‚BÕ��Â’‚ŠªŠ¢Ò¢ªÒªÂJm
 SDK versioo:0.3.0
 Ai�½½
 ‚Šj

```

Again some garbage because of the baud rate which is too high.

Other info on the module:

```
sending AT+RST
response: ?AT+RST
OK
WRT
"%M
<99CT
 ets Jan  8 2013,rst catse:2, boot lode:(3,7)
load 0x40100000ntail 4
chksum 0x89
ld tail 4
chm3 tail 8 r 0 aM
 ón't use rtc mem dat`
sl��oÌÿ
Ai-Thinker Technology Co.,Ltd.

```

**UPDATE**

(\*) I used an FTDI232 module to send `AT+IPR=9600` to my ESP8266-12E module **and I bricked it**!

**DO NOT USE `AT+IPR=9600` ON AN ESP8266(-12E).**

I did not manage to recover it so far! I tried re-flashing it but I get Invalid head exceptions.

On a new module I sent the `AT+CIOBAUD=9600` command and it worked. Permanently!

My module specs:

```
AT+GMR
AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0
Ai-Thinker Technology Co.,Ltd.
Build:1.3.0.2 Sep 11 2015 11:48:04
OK

```

# Answer
> 4 votes
I Connected an FTDI232 module at 115200 baud and could read the specs of the ESP8266 module now:

```
AT+GMR
AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0
Ai-Thinker Technology Co.,Ltd.
Build:1.3.0.2 Sep 11 2015 11:48:04
OK

```

After that I sent the `AT+IPR=9600` command, which first seemed to do the trick. But after reboot of the module, all I got was garbage response, at any baudrate.

**DO NOT SEND AT+IPR=9600 TO YOUR ESP8266(12e) MODULE**

Maybe the `AT+UART_DEF` command - as mentioned by JRobert - works, but I used the `AT+CIOBAUD=9600` command and it worked. Permanently!

I hope this can help others.

# Answer
> 13 votes
Depending on how recent a version of the AT Instruction Set interpreter your chip has, the two instructions you tried may not be valid ones; they are not listed in Espressif's ESP8266 AT Instruction Set document. Searches for either "CIOBAUD" or "IPR" in the current document (version 1.5.3) return no results.

The baud rate commands are now "AT+UART\_CUR" and "AT+UART\_DEF" which configure the entire UART for the current session or the current and future sessions, respectively. The manual's prototype for the command is:

```
AT+UART_DEF=<baudrate>, <databits>, <stopbits>, <parity>, <flow control>
Example:
AT+UART_DEF=115200, 8, 1, 0, 3

```

I have used these and can confirm that they work.

What I've found using software serial is that it can push 115200 baud well enough to send commands to the device (though I wouldn't build an application that depends on it) but it can only read reliably up to 9600 baud. I've been able to change my devices' baud rates from 115200 baud to 9600 over software serial; you just have to expect garbage coming back and ignore it:

```
// Set ESP8266 baud rate to 9600. You only need to do this once per device
set software serial baud to 115200;
send "AT+UART_DEF=9600,8,1,0,0";
set software serial baud to 9600;
// From now on, communicate with your device at 9600 baud.

```

# Answer
> 4 votes
I bricked my Esp with the same command, too. After hours of searching I found a way to reset the bricked esp. https://developer.mbed.org/users/sschocke/code/WiFiLamp/wiki/Updating-ESP8266-Firmware I had to set the baudrate to 115200 instead of 9600, and between the uploading files I had to disconnect the esp from power. I hope that helps you and everybody who did the same and found your post over Google.

# Answer
> 1 votes
Using this firmware: https://developer.mbed.org/users/sschocke/code/WiFiLamp/wiki/Updating-ESP8266-Firmware

and this flasher: http://yaab-arduino.blogspot.com.br/2015/12/flashing-esp8266-firmware-arduino.html i was able to recover my esp 8266 12f

# Answer
> 0 votes
Looks like you are you are having power supply issue. What is your power supply rating ? and try adding a small capacitor between vcc and ground. Also its good idea to update the firmware to 0.9 which has baudrate issue fixed.

You can find new firmware at https://github.com/espressif/esp8266\_at

---
Tags: arduino-nano, esp8266, firmware, baud-rate
---


title: Pixy(CMUcam5) robot Distance code

text:
# Question
Title: Pixy(CMUcam5) robot Distance code
Can anyone help me with the code-ing to allow the robot to stop at a certain distance when the robot is approaching the tracked object. I am trying to implement it as a colour tracking wheel chair. For Example, the motorized wheelchair is able to track the colour of the shirt of the person infront is wearing and follow the person, and at the same time it is able to leave a distance between the person infront and the wheelchair to prevent collision.

the pixy robot : https://learn.adafruit.com/pixy-pet-robot-color-vision-follower-using-pixycam/overview

The code :https://learn.adafruit.com/pixy-pet-robot-color-vision-follower-using-pixycam/the-code

Currently the code is only able to track the object till it reaches the object. But my objective is to let it chase the object, but at the same time, leaving a 1 metre distance away from the object.

Please help me. Thank you

# Answer
Try to play with this one:

```
int forwardSpeed = constrain(400 - (size/256), -100, 400);

```

By changing the value of 256 and 400, not at the same time though, you better use 2 potentiometer to change those values. That's a trial and error though, I hope this will give you an idea.
> 1 votes

# Answer
Old question, but I'd simply use the angle of the Pixy tilt mechanism. If the camera is mounted low (on a wheelchair) and looking up (to see a t-shirt), the angle will be more "up" when the t-shirt is close.

```
void loop()
{
   if(tiltAngle < 45) // Angle in degrees
      moveWheelChairForward();
}

```

However, if someone bends down, the tilt angle will go down, so the wheelchair will ram them! Thus, a proximity sensor is probably still going to be needed.
> 0 votes

---
Tags: programming, arduino-leonardo, robotics
---


title: Multiple GSM shields on one Arduino

text:
# Question
Title: Multiple GSM shields on one Arduino
I am looking for a way to listen for received text messages on multiple numbers. When I came across the Arduino and its shields, I thought to myself this might be the perfect way to do just that.

One of the modules / shields I found on the internet by watching a youtube video is the TC 35 GSM.

I have been reading multiple questions here regarding the "stacking" of shields, and the usual reply is "check what pins / if they are using the same pins". Though these questions were not GSM module specific, and did not include stacking the **same** shields.

So I am very curious if this is possible. Let's say I want to listen to 10 SIM cards at once for received messages, will this be possible by stacking the modules on one Arduino?

Thanks!

# Answer
> 2 votes
The data sheet for the Siemens TC35 says *"The data interface is implemented as a serial asynchronous transmitter and receiver conforming to ITU-T RS-232 Interchange Circuits DCE. It operates at CMOS level (2.65V). All RS-232 signals on the ZIF connector are low active."*

this is actually a low-voltage equivalent of "RS232" serial. Real RS232 uses -12V and +12V signalling for binary 0 and 1 but most modern devices work with logic levels, often inverted (e.g. 0V and ~3.3V).

Most Arduinos support in hardware only a single logic-level serial interface. A few Arduinos, like the Arduino Mega, will support up to four logic-level RS232 interfaces.

Using a software library, you can emulate a serial port over the digital IO pins but the Arduino will quickly run out of processing power if you try to emulate several RS232 interfaces.

> **will this be possible by stacking the modules on one arduino?**

Almost certainly not. I doubt the daughterboard ("shield") designers made provision for that. At the least you'd have to re-route the serial interface to nonstandard pins and check that the power requirements don't exceed what the Arduino can supply.

If you can find a module that communicates over I2C or SPI there might be a better chance of getting it to work.

# Answer
> 2 votes
The short answer is, no, you can't just stack them, but yes, it is possible (though not trivial) to connect ten or more of these to a single Arduino board and have it monitor all of them.

Note that the following explanation is simplified, possibly over-simplified, in the interests of brevity and giving you a general idea of what you're in for if you try this. Many of the details (as I mention below) could easily be one or several questions of their own.

You didn't give the datasheet for the board you're considering, so I'll work from the description of a similar board (though not an Arduino shield) using the same chip, the Cytron Technologies TC35 GSM Development Board.

Arduino shields connect various pins of their chips to pins on the Arduino board. In many (perhaps most) cases you can't have two different devices connected to the same Arduino pin, so if you were just going to plop another board on it would have to have special support for changing the pins it's using (often via jumpers) or being able to have several boards communicating on the same pins. The GSM chip you're considering uses two dedicated pins for serial communication transmit and receive; these are the pins you'll need to rewire if you're going to use multiple boards on a single Arduino.

What kind of rewiring you'll need to do depends on how many you really want. The Arduino Uno has 14 digital I/O pins, two of which are usually used for the USB serial interface to the computer, giving you six devices if you dedicate a pair of pins to each device. Since the communication rate with the boards is quite slow (9600 bps, see below) you could multiplex many of these on one pair of Arduino pins via a number of different techniques (such as using shift registers); this alone is complex enough that a different question could be devoted just to considering the possible choices, with further questions on the details of implementing each choice. You should consider, if you're interfacing with a PC, using multiple Arduino microcontrollers each with only one or a few GSM chips talking to them, talking to a PC via USB, and doing further processing on the PC.

If you're using a lot of boards you'll need to make sure you can supply enough power to them; you may need to use a power source outside the Arduino board itself. An Arduino powered from its USB interface can pull no more than 500 milliamps (because that's the USB limit). If you're using a separate power supply and the Arduino's on-board regulator, the limitation will be based on the electrical and thermal limitations of that regulator; this blog post is one detailed discussion of that.

There's also the issue of level shifting; Arduino boards usually do digital I/O at 5 volts or 3.3 V; this chip looks like it talks at 2.65 V and you or the board you're using will need to handle that. If the board you're using doesn't do appropriate level conversion there are other questions (such as this) that discuss the details of particular level-conversion solutions.

Once you have pins connected to the devices you'll need to talk to them; this involves the lower level "framing" parts of the serial protocol and the higher-level command set.

For framing the GSM chip appears to use the low-speed serial protocol framing that's standard in the computer world; aside from the voltage level difference it's the same as used in RS-232 communications between a computer and a modem or other "serial" device. The setting from the data sheet I used is "9600bps, 8-1-N, No Flow Control" which is slow enough that the microcontroller itself can easily communicate with quite a number of these without any extra hardware using bit banging. A 16 MHz Arduino executes something approaching 16 million instructions per second (most instructions are one clock cycle), giving you over 1500 instructions per bit-time to read a bit from every attached device, do the processing to turn the bits into bytes, and process the resulting messages. If you're careful with your programming, and depending on what you're doing, it shouldn't be too hard to deal with even up to a couple of dozen GSM chips, though this is almost certainly not a trivial programming job that you're going to do with standard Arduino libraries.

The higher level command set is also pretty much the same as old-fashioned computer-modem comunication; the GSM chip (and thus pretty much any board that uses it) talks standard PC-style serial protocol at 9600 bps using the AT command set. You'll see messages such as

```
+CMGR: "REC READ","+60125651453",,"12/07/31,10:0702+32"
Hello

```

when you receive an SMS and similar ones when you send an SMS.

# Answer
> 0 votes
Not directly stacking, no. You could do a dirty trick where you bend the serial pins out sideways, letting the stack handle all the power and ground and wakeup pins and stuff. Then handle the serial communications with each module separately.

The Uno and similar only have a single UART (serial port) each, but you can emulate more with "software serial", aka "bit-bang" techniques. These are full of caveats and I wouldn't wish them on a newbie.

The Mega2560 has four UARTs, so you're getting closer. You'd need to use wires coming off those sideways-bent pins to bring the signals down to the different tx/rx pins per UART, but I could see it working.

You can also add UARTs over SPI/I2C, but that's getting into a good bit of program complexity. Look at the SC16IS750 or the MAX3100 for starters.

(There's also a horrible, horrible hack emerging in my mind: Connect a single transmit line to a demux chip, so you can pick a single TC35 to talk to at any given moment. Bus all the receive lines together with resistors/diodes. Hope you never end up in a situation where two are talking at once.)

---
Tags: arduino-uno, shields, gsm
---


# Question
Title: Can I safely connect my original Arduino Uno to a 19V adapter?
I have an original Arduino Uno R3. According to the specifications the recommended input voltage is 7 to 12 Volt.

However, I have a laptop adapter of 19V that I want to use to power my arduino because it offers more current than the 9V adapter I have as well.

I don't want to damage the Arduino or the DFRobot 2A Motor Shield I'm using. Can I safely plug in the adapter and will it still work correctly?

# Answer
> 3 votes
It's often better to supply separate power to high-current applications (such as motors) rather than taking power off the Arduino. This avoids problems with current and thermal limits of the Arduino on-board power regulator.

Looking at the manual for your board, the motors can be powered by a separate power supply hooked up directly to the motor shield. There's a six-pin header on the board marked VIN and PWRIN. When the jumpers are on the VIN side Arduino-supplied power is used to drive the motors; when the jumpers are on the PWRIN side the motors are supplied with power from the terminal block next to the jumper. (The rest of the board remains powered from the Arduino, but that's usually a negligible amount of current compared to your motors.) A photo in the manual demonstrates the pins set to PWRIN and an external power supply hooked up.

The documentation says you can supply any voltage between 4.8 V and 35 V DC, but **be careful!** What they don't make clear in the documentation (but is clear from the schematic and the L298N datasheet) is that this power is supplied directly to power side of the L298N and the motors without further regulation. The chip can handle up to 50 V DC, so it would be fine with a 35 V input, but you'll want to check that your motors can handle the voltage you want to give them.

If the motors can handle 19 V input, and your 19 V power supply is reasonably well regulated itself (which a laptop computer power supply generally would be), you can use that to power the motors directly through the motor shield and continue using your current power supply to power the Arduino.

(The ST L298 page has further information, including a slightly less readable copy of the data sheet and application notes.)

# Answer
> 4 votes
According to the page you linked:

> The board can operate on an external supply of 6 to 20 volts. If supplied with less than 7V, however, the 5V pin may supply less than five volts and the board may be unstable. If using more than 12V, the voltage regulator may overheat and damage the board. The recommended range is 7 to 12 volts.

So, yes. You can use the 19V external power supply to power the board. However, be aware that the voltage regulator can overheat over time and damage the board.

---
Tags: arduino-uno, power
---


# Question
Title: Getting Bluetooth addresses of connected devices via Arduino Uno?
I want to find all the Bluetooth addresses of connected devices using an HC-05/HC-06 Bluetooth module and an Arduino. I can't find any code related to this. Basically I need the addresses to put in an array. Is it possible to do this with an HC-05 or 06?

# Answer
> 4 votes
The HC-05 has an AT command, `AT+BIND?`, that will tell you which slave device it is connected with currently. Since you can connect to one device only at the same time, your array is going to be a very short one.

`AT+INQ` will provide you with a list of nearby devices, to which it ***can*** connect.

# Answer
> 3 votes
You just have to send the above Bluetooth command via serial port to your Bluetooth module using print command.

For example `yourserial.print("AT+BIND?");` OR `yourserial.print("AT+INQ");` if you are using SoftwareSerial. Otherwise just use `Serial.print("AT+BIND?");` OR `Serial.print("AT+INQ");` when using Rx/Tx pins. That will do the job.

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


# Question
Title: How to restart a counter in a program using a push button in a LDR Tripwire setup
So, trying to configure this code so that when I push the button, the person counter will go to zero and just as it goes, the counter will increase when the LDR will get tripped and again when the button is pressed, the counter will go to 0.

```
#include <LiquidCrystal.h>

int laser=8;
int pushbutton=12;
int flag=0;
int myCounter = 0;
LiquidCrystal lcd(7,6,5,4,3);

void setup()
{
    pinMode(laser,OUTPUT); pinMode(pushbutton,INPUT);
    lcd.begin(16, 2);
    lcd.print("Person Counter:"); lcd.setCursor(0,1);
    lcd.print(0);
}

void loop()
{
    lcd.setCursor(0, 1);
    digitalWrite(laser,HIGH);

    if(analogRead(A0) < 600) //A0= LDR
    {
        flag = 1;
    }

    if(analogRead(A0) > 600 && flag == 1)
    {
        myCounter++;
        delay(200);
        lcd.print(myCounter);
        delay(20);
        flag=0;
    }
}

```

# Answer
> 1 votes
Try out this code. I made some modification and also comment out that things.

```
#include <LiquidCrystal.h>

LiquidCrystal lcd(7, 6, 5, 4, 3);

int laser = 8;
int pushbutton = 12;
int flag = 0;
int myCounter = 0;

void setup()
{
  pinMode(laser,OUTPUT);
  pinMode(pushbutton,INPUT_PULLUP); // Provide pull-up

  lcd.begin(16, 2);
  lcd.print("Person Counter:");
  lcd.setCursor(0,1);
  lcd.print(0);
}

void loop()
{
  lcd.setCursor(0, 1);
  digitalWrite(laser,HIGH);

  if(analogRead(A0) < 600) //A0= LDR
  {
    flag = 1;
  }

  if(analogRead(A0) > 600 && flag == 1)
  {
    myCounter++;
    delay(200);
    lcd.print(myCounter);
    delay(20);
    flag = 0;
  }

  if(digitalRead(pushbutton) == LOW) // When button pressed
  {
    myCounter = 0; // Set counter to 0
  }
}

```

---
Tags: arduino-uno, arduino-ide, button, photoresistor
---


# Question
Title: Working or functionality Serial.begin(9600)
In recent practice, I found out some new things.

`Serial.begin(9600);`

What is mean of this line of code?

Why here, we always write `9600`?

And can we write manually number means instead of 9600 let's say 10000?

# Answer
> 2 votes
`Serial.begin(9600);`

`What is mean of this line of code?`

Serial.begin(9600) doesn't actually print anything.

If you want to print "Hello world!" to the serial monitor then you have to use this line of code. Rather it initializes the serial connection at 9600 bits per second.

It is used for kind of handshaking means both sides of the serial connection (i.e. the Arduino and your computer) need to be set to use the same speed serial connection in order to get any sort of intelligible data. If there's a mismatch between what the two systems think the speed is then the data will be garbled.

`Why here, we always write 9600?`

And 9600 bits per second is the default for the Arduino, and is perfectly adequate for the majority of users, but you could change it to other speeds: Serial.begin(57600) would set the Ardunio to transmit at 57600 bits per second. You'd need to set whatever software you're using on your computer (like the Ardunio IDE's serial monitor) to the same speed in order to see the data being sent.

`And can we write manually number means instead of 9600 let's say 10000?` No, we can't write. There is a specific baud rate available: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200.

# Answer
> 1 votes
```
Serial.begin(9600);

```

This line starts Serial communication with a baud rate of 9600. Serial communication is used to transmit data between your application and external systems (including your PC, other Arduinos, sensors, and other ICs).

Most of the time this is included to allow the application to output information via the Serial Monitor when connected to you PC.

Documentation for this is here: https://www.arduino.cc/en/reference/serial

From the documentation: "For communicating with the computer, use one of these rates: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200." \- source

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


# Question
Title: Can I share the VCC (5V) on my Arduino Pro mini with multiple modules?
Right now I am onto a new project where I am building an obstacle avoiding landrobot.

I use an arduino pro mini as my board and I have a few hc-sr04 sensors here at home. The problem I have right now is that many pins is occupied with other modules, motors and bluetooth.

So right now on my Pro Mini the VCC is occupied by my BLE device and I was wondering if there is a possibility to solder a few wires together so that my BLE device share the same VCC with 4 other hc-sr04 modules? I do this regularly with the GND where I solder multiple wires together and share the GND across different modules which works fine.

I have soldered a wire looking like this:

The idea is to power the arduino itself through the "RAW" pin. I have a power distribution board that connects to my battery/motor and the VIN pin of the PDB goes to the "RAW".

I try to avoid a breadboard to decrease the size as much as possible so if it were to be possible then that would be the optimal solution for this project.

Something I am also wondering is if it is possible to use these hc-sr04 on both the analog pins and also the digital pins. I do not have enough space to fit all the sensor cables on the digital pins but if I use the analog pins also then they all would fit. Is this possible? Each HC-sr04 has two cables that needs to be inserted (Trig and echo) and right now I have 3, 4 free and all the analog pins 0, 1, 2, 3, 4, 5 which is enough to fit them all.

# Answer
Yes, you can do that as long as the total current draw of the modules you attach to VCC doesn't exceed the on-board regulator maximum current output.

The Arduino Pro Mini has a MIC5205 regulator capable of delivering up to 150 mA, which is quite low if you plan to attach many modules to its output. So you should look through your modules datasheets and find out the total current draw, including the Pro Mini board itself, and check that against the 150 mA limit.

According to the HC-SR04 datasheet, each module draws 15 mA. The Arduino Pro Mini itself draws about about 20 mA. The BLE module peak current consumption is 12.5 mA at active RX and 11 mA at active TX, so lets say 25 mA peak current draw for the BLE module.

Everything adds up to a worst case 105 mA peak current draw, within the maximum 150 mA limit. So **it should be fine**, but I would avoid connecting much more modules to that VCC rail.

**ADDED according to your additional question:**

If you run out of digital I/O pins, you can use the analog pins as digital pins if needed.

Additional note (thanks go to @jwpat7 for pointing this out in the comments):

However, this is true only of A0–A5 on most Uno and Nano Micro Arduinos, and not true of A6, A7 (except on -PB MCU models like ATmega168PB and ATmega328PB, where A6, A7 can be used as digital pins).
> 3 votes

# Answer
To be frank you can use even your analog pins as digital pins as the analog pins are also digital pins but they are more enhanced

If you use a common Vcc you may not have enough power left for your board and when you share your ground it doesn't matter a lot as it is the -ve lead of your power source and you may use an external power source
> 2 votes

---
Tags: sensors, power, bluetooth, arduino-pro-mini, current
---


# Question
Title: Will an ATmega2560 board be faster than a Uno for hard real-time data logging?
I am designing a hard real-time data logger. The Uno is a bit marginal in processing speed.

a) Would it be **faster** if I changed to an ATmega2560?

b) On the datasheet, ATMEGA2560 has 135 instructions; it is **4 instructions more** than the ATmega328p.

What are the extra 4 instructions for?

Are they involved in floating point maths?

c) How to select compiler option for **fastest code** at the expense of bigger code size, longer compilation time, etc.?

The system is:

1. Receive data from wireless transceiver chip via hardware SPI port.
2. A good portion of the time is spent on data calculation using floating point maths.
3. Output processed data on serial port (then to PC via the Arduino board USB to Serial chip).
4. Code and RAM size is not an issue, Uno has plenty space left.

# Answer
No, it will not be any faster. The extra instructions are to access the extra flash memory of the 2560. Instructions like `EIJMP` \- *Extended* indirect jump, `EICALL` \- *Extended* indirect call, etc.

The compiler option `-O3` optimises the most, but there are other options you can enable, such as `-funroll-loops` which will cause major code bloat but speed things up. Read the GCC manual pages to boggle at all the millions of optimisation options.

Or... use a faster chip, like an ARM or PIC32.
> 8 votes

# Answer
Use the newest Arduino IDE, because some time ago the 'lto' option was added which is a major optimization for both speed and size.
It is possible to test a few compiler options with the #pragma. Try for example these at the top of the sketch:

```
#pragma GCC optimize("-O3")
#pragma GCC optimize("-ffast-math")

```

The 'fast-math' is dangerous, be careful with it.

The Arduino Zero and Arduino Due are faster but not a lot faster, because they are not fast with analogRead() and with floating point calculations.

A common mistake is that someone asks for a faster Arduino board, but uses a sketch and libraries with a lot of delay() in it. That won't be any faster with an other Arduino board. Have a good look at your code and at the source code of the used libraries.

Have you tried increasing the baudrate for outgoing data ? If that baudrate is slow, the whole sketch is slowed down because the Serial functions will wait until they can write the data into the Serial buffer. The fastest "baudrate" can be achieved with the Leonardo, Micro and Pro Micro boards. They transmit the data directly onto the USB bus without using the baudrate.
> 5 votes

# Answer
In the `platform.txt` file found in `~/Arduino15/packages/arduino/hardware/avr/1.6.17` or similar, you can change the three instances of `-Os` with `-Ofast`. The size of the code can increase dramatically though.
> 3 votes

# Answer
They have very nearly the same instruction set and the same execution speed, so there will be no increase there. If your project spends a significant amount of time in floating-point arithmetic, replacing it with fixed point arithmetic will give you a noticeable speed up. If a few calculations are executed repeatedly (which is typical), you can get most of the advantage by rewriting only that part.

In a nutshell, fixed point arithmetic is what the computer does already, but with an assumed binary point (just like a decimal point) always to the right of the least significant bit. Fixed point arithmetic uses the built-in arithmetic, but you assume the binary point to be wherever you need it, keep track of it during multiplies and divides, and make sure you keep the intermediate results from overflowing.

Search for Fixed Point Arithmetic and you'll find out a whole lot more.
> 1 votes

---
Tags: float, atmega2560, speed
---


# Question
Title: Shield Compatible third party motor driver
I recently purchased an Arduino UNO along with some other hardware. At the time of purchase, I didn't know about Arduino's motor shield and so I purchased a two channel stepper motor driver (2A per channel) that was said to be "Shield Compatible". I recently received my hardware and have been following the introductory tutorials since I'm completely new to the Arduino platform. Things are going well but I didn't receive any documentation with the motor driver. There is a datasheet provided on the vendor's website but it is beyond my current level of competency.

My question: since the driver is said to be "Shield Compatible", does this mean that I can assume that I can interface with it the same way as an authentic Arduino shield. In other words, can I follow the motor shield tutorial on Arduino's website without any risk of damaging hardware and expect the driver I purchased to function properly.

The product that I purchased can be seen here: http://www.robotshop.com/ca/en/dual-bipolar-stepper-motor-controller-arduino.html

# Answer
> 3 votes
You should do you own research as the path followed here did not result in the identically pictured nor identically model numbered item.

You indicated you are using a certain Arduino motor driver board. On that page there is an "made by" or "by" reference to an OEM. On the OEM's web page there is a "Dual Bipolar Stepper Motor Shield for Arduino" but the part number and the picture do not (exactly) match your original link. Regardless, there is what they are calling a "WIKI page" for this (slightly) different motor shield. I scanned this page and the example code. I don't see where any device driver is mentioned. And I don't think the code will compile by its self.

In general, I suggest people who are starting out with Arduino's to stick with well known hardware and software. Even then I have had problems with newly released hardware. Also check if drivers and SDKs have been updated each time you start a project.

Another approach you might entertain is to follow a path starting with the chip used on your shield. It appears to use two DRV8825. (But I cannot be sure as pictures and model numbers do not (exactly) match.) Here is a discussion on the a well known Arduino web site where people are talking about boards with this chip on it.

---
Tags: motor, arduino-motor-shield
---


# Question
Title: Arduino auto power of circuit possible issue with higher voltage agains output pin?
I've use the following circuit to be able to shutting the my Arduino down after some time of it not being used:

I'm now concerned that while you press the button to turn on the Arduino, the 9V from the battery can flow directly to the PIN X (one of the digital pins of the Arduino configured as output). After the Arduino is started the PIN X will be set to high, to keep the Arduino running when the button is released.

Is this a problem which I need to solve? And if yes how. The finished project is intended for a child, so I assume that the on button can be hold for a long time just as it is funny to press on the button. The circuit itself is running fine.

As a possible solution I thought to add a diode between the junction after the R1 and the PIN X. Would this be an ok solution?

The circuit is not my own invention I've found it here: http://educ8s.tv/auto-power-off-arduino-simple-circuit/

# Answer
Having 9 volts reaching pin X through R1 is indeed a problem, one that could destroy transistors in the pin's IO structure. The problem is mentioned in some comments following the video, but no solution is mentioned there. Presumably users of the circuit usually get away with ignoring the problem because it is one of short duration: A few milliseconds after the MCU starts up, it sets pin X to +5 V, which then leads to 4 V at 40 μA being dropped harmlessly across R1. (Note, R1 is 100KΩ rather than 100Ω, per video and its notes.)

One approach to guard against the problem is to place a 5.3–5.7 V zener diode from ground to pin X.

Another way is to use a better and more capable on-off circuit, a Pololu Pushbutton Power Switch #2808. This costs about $4, and is rated for operation from 2.2 V to 20 V at up to 6 A. The board is about 15x18 mm and has a small pushbutton on it, but you can parallel a momentary switch of your own if you like. The pushbutton toggles power on or off. The board also has control inputs called On, Off, and Ctrl, with the first two turning the board on or off.

A big advantage of the #2808 switch is its current draw is small (less than 0.1 μA) when switched off. The circuit illustrated in the link has close to 0.5 mA draw when off, which is enough to run a battery down in a few weeks.
> 1 votes

# Answer
No. It is not possible for a modern IC such as an MCU having I/O protection diodes to enable/disable its own power using a *single* external N-Channel or P-Channel device. The reason is that the path broken by the single switch ends up being partially completed through I/O pin's internal protection diode and your pulldown resistor, and depending on the voltage drop that results across that, partial turn on the FET itself. This is enough to have the processor at least partially on - perhaps not enough to *operate*, but enough to keep consuming battery, and in some cases also enough to make clean startup on manual operation of the power switch unworkable.

To make this work, you need two stages of switching - two fets are a possibility.

However another easy one is to use one of the USB power switches chips intended to be included in the rarely seen "full" USB hubs that have software control of the downstream ports' power. These are hardly ever fitted in the hubs sold, but they exist as a part, are easy to apply, typically have low leakage, and are often specified to operate correctly both substantially below and somewhat above the 5v they would see in a USB application. Most importantly, they are multi-stage solutions in a single package - typically they function as high side switches, but they are enabled by an input going high, and as result, they do not suffer the parasitic partial turn on issue via the MCU's protection diodes in the way that a high side switch enabled by an input going low would. I believe the RT9701 that I used in the past to do this with an ESP8266 is officially discontinued, but still available and likely replaced by newer similar parts.

Given your input voltage, another thing to consider would be using a regulator with an active-high enable input. But realize that a *linear* regulator is an inherently wasteful device, and a lot of the compact switchers don't have very high input voltage allowance.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Press on pressure sensor, then wait 5 seconds, turn on LED
I'm having some trouble wrapping my head around timers in Arduino. I've got a FSR Pressure Sensor and I want it to turn on my NeoPixel LED after pressing on it for 5 seconds. Any help is much appreciated!

My goal: FSRReading \> 1022 then wait 5 seconds, turn on NeoPixel FSRReading \< 1022, then reset timer, turn off NeoPixel

This is what I currently have for my code, I can detect and act on sensor readings, but no timer:

```
#include <Adafruit_NeoPixel.h>
#define PIN 6
#define NUMPIXELS 16
#include "Timer.h"

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

int fsrPin = 9; // FSR is connected to analog 0
int fsrReading; // the analog reading from the FSR resistor divider int LEDbrightness;
int LEDbrightness;
Timer t;

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

void loop(void) {
fsrReading = analogRead(fsrPin);
Serial.println(fsrReading);
Serial.print("Analog reading = ");

// we'll need to change the range from the analog reading (0-1023) down to the range // used by analogWrite (0-255) with map!
LEDbrightness = map(fsrReading, 0, 1023, 0, 255);

if (fsrReading < 10) {
Serial.println(" - No pressure"); } else if (fsrReading < 200) {
Serial.println(" - Light touch"); } else if (fsrReading < 500) {
Serial.println(" - Light squeeze"); } else if (fsrReading < 800) {
Serial.println(" - Medium squeeze"); } else {
Serial.println(" - Big squeeze"); }
delay(50);

for(int i=0;i<NUMPIXELS;i++){

  // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
  if (fsrReading>1022){
  pixels.setPixelColor(i, pixels.Color(0,255,0));
  } else if (fsrReading<1022) {
  pixels.setPixelColor(i, pixels.Color(0,0,0));
  }

  pixels.show(); // This sends the updated pixel color to the hardware.
 }
 }

```

# Answer
The basic concept for tracking timing in the loop() is as follows:

1) when your event occurs, you store the current time in a variable:

```
unsigned long lastReading = 0;
uint8_t waiting = false;

if ( !waiting && fsrReading > 1022 ) {
  lastReading = millis();
  waiting = true;
}

```

2) you compare the lastReading variable against the current time and when enough time has passed, you can perform you timed action. ie:

```
int timeToWait = 5000; // 5 seconds

// are we waiting? and has enough time passed?
if ( waiting && millis() - lastReading > timeToWait ) {
   waiting = false; // reset

   // Light up lights
   ...
}

```

Note: this specific implementation only requires the sensor to rise above 1022 once, then wait 5 seconds before executing the timed action. If you want the sensor reading to be maintained above 1022 for the entire duration then you would add a check for a release with something like:

```
if ( fsrReading < 1022 ) {
  waiting = false; // reset because reading fell below 1022
}

```
> 3 votes

# Answer
> My goal: FSRReading \> 1022 then wait 5 seconds, turn on NeoPixel FSRReading \< 1022, then reset timer, turn off NeoPixel

something like this will do.

```
  static uint32_t pressed_time; //last time the pressure sensor is pressed
  static uint8_t pressed_state=0; //the previous state. '1'->pressed, '0'->not pressed

  if (pressed()) {
    if (!pressed_state)) { //first time the pressure sensor is pressed
      pressed_state = 1;  //pressure sensor has been pressed
      pressed_time = millis(); //take time now
    }
  } else {                //no longer pressed
    pressed_state = 0;  //reset pressed state
    turnOffled();       //turn the led off
  }

  if ((millis() > pressed_time + LED_DLY) && pressed_state) turnOnled();

```

untested code, use at your own risk

edit:

the above code in action, with a minor modification to return the desired led state (active high):

```
    //turn on / off the led pins
    if (led_ctrl()) digitalWrite(LED_PIN, HIGH);    //turn on the led, active high
    else digitalWrite(LED_PIN, LOW);        //turn off the led
}

```

Note: 1. pressed() is active low; 2. the led is programmed to turn on 100ms after the button goes low.

hope it helps.
> 1 votes

---
Tags: arduino-uno, sensors, timers, adafruit, processing-lang
---


# Question
Title: Detecting the light source location using multiple photoresistors
I am not an expert yet, so please forgive any possibly wrong terminology that I may have used.

I am planning to place 6 light sensors in 1 meter (or maybe more) distance from one another, like this (sorry about the bad schematic, I am not an expert, but I hope it makes sense):

simulate this circuit – Schematic created using CircuitLab

I am going to place them in a relatively dark room. My goal is, when I am pointing a flash light towards them to be able to tell which sensor is measuring the highest values (where the light is coming from), and for how long (in milliseconds).

I know how to do the connections and measure values. My questions are two:

1. Which is the most efficient way to detect which of the 4 sensors is recording the higher values? I am assuming I have to compare the values that they are recording. However, I think that if in each loop I sort the captured values, the process might become heavy. I guess I could minimise the comparisons, since for example if LDR1's value is higher than LDR2 and LDR3, I can assume that the light source is cannot be pointing towards LDR6 for example. However, I am thinking that maybe there could be an even more efficient way to detect that (not necessarily in software).
2. Since the room will not be completely dark, the analog pins will record some values even when I am not pointing the flash light towards them. Is there a way to filter that out? I have come across calibration (https://www.arduino.cc/en/tutorial/calibration), but I am not sure whether this is the optimal solution. Please take into account that the light source might not be very strong (but its light will definitely be brighter than the room light).

# Answer
> 7 votes
The answer from Curt Sampson provides several good design considerations, plus the quite-reasonable suggestion that you run some experiments to characterize your LDRs and their placements.

Note that if you want to know which sensor has the highest reading, a simple find-maximum-value loop will do that, without any sorting:

```
int maxR = reading[1], maxS=1;
for (byte i=2; i <= nSensors; ++i) {
  if (reading[i] > maxR) {
    maxR = reading[i];
    maxS = i;
  }
}
// Now we know sensor maxS has max reading, maxR

```

The code above follows the 1–6 numbering scheme given in the question, and assumes that `reading[i]` stands for the reading from sensor `i`.

Code below, however, numbers the sensors and their readings from 0 to 5 instead of from 1 to 6, to allow simpler conditions in `for` loops. From a programming standpoint, it makes sense to call the first sensor 0 if its data is stored in cell 0.

---

**Finding x, y direction of the light**

Assumptions behind the following code are that higher readings indicate more light, and that if necessary some background-lighting calibration has been done, and that background lighting has already been subtracted from readings data. We also assume that maximum readings are less than (2¹⁵)/N, where N is number of sensors.

The point of the following code is to set two variables, `x` and `y`, that represent the relative location of a light source. For example, if `x` and `y` are both positive, the light is above and to the right of the top right LDR. If `x` is negative and `y` is near zero, the light is to the left of the middle-left LDR. If knowing the signs of `x` and `y` is adequate for your purpose, then there's no need to do more arithmetic than shown. On the other hand, if you want to compute some sort of angle, you can use `atan2(y, x)` to compute the direction of the light, in radians.

```
int reading[nSensors];
const int xdir[] = { -1, 1, -1, 1, -1,  1}; // x-direction sensor weights
const int ydir[] = {  1, 1,  0, 0, -1, -1}; // y-direction sensor weights
int x=0, y=0;
for (byte i=0; i < nSensors; ++i) {
  x += xdir[i] * reading[i];
  y += ydir[i] * reading[i];
}

```

---

*Edit 1:* **Tracking the time a light is on**

Issues with light-timing include what levels to start or stop timing at; necessary resolution (milliseconds? minutes?); necessary range (eg, is what happened a minute ago relevant); and when to reset accumulated time data. It may be simplest to track the on times of all the sensors at the same time, then select one of the times or combine some times. Do you want the largest time, the newest time, the newest large time, or the time corresponding to the largest light?

For example, the code below tracks light levels that remain high long enough to register, in smoothed averages, as above some threshold. At intervals, current indications are rotated into bit maps that track the last 16 on-off levels for each LDR, and counts of number-of-ons are updated too.

```
// Initialization ...
uint16_t expAvg[nSensors]={0};  // Exponential averages over time
uint16_t bitMaps[nSensors]={0}; // Track each sensor's last 16 on-off levels
byte onCounts[nSensors]={0};    // Number of recent times sensor avg > threshold
unsigned long prevMilli=millis();
const int markInterval=50;   // ms interval for recording light levels
const int onThreshold=547*16; // Some light-is-on threshold

// In each pass of loop() ...
for (byte i=0; i < nSensors; ++i)
  expAvg[i] = reading[i] + 15*expAvg[i]; // exponential averaging with 1:16 weight

// In loop(), at intervals ...
if (millis()-prevMilli >=  markInterval) {
  prevMilli = millis();
  for (byte i=0; i < nSensors; ++i) {
    onCounts[i] += (expAvg[i] > onThreshold) - (!(bitMaps[i] & 0x8000));
    bitMaps[i] = (bitMaps[i]<<1) | (expAvg[i] > onThreshold);
  }
}

```

# Answer
> 4 votes
There's only one ADC (analog to digital converter) on the ATmega328P; the analog input pins are multiplexed so that you choose which particular pin you want to sample. (See Section 28 of the datasheet for details.)

Taking a sample takes time; how long depends on how you do it. The `analogRead()` function is documented to take about 100 microseconds. Reading your six sensors is thus going to take at least 600 microseconds.

The sample returned is a 10-bit integer and so easily fits into two bytes, or even one byte if you drop the low two bits (which is reasonable for some applications, and probably yours, because they're likely to be more sample error than data anyway). Whether you do that or not, however, you're left with a very tiny amount of data to sort from one set of reads: just six values.

The Arduino runs the ATmega328P at 16 MHz, and most instructions run in single clock, giving you performance approaching 16 instructions per microsecond.

We could work out, based on the type of sort you use, the number of comparisons and swaps you're likely to make in the average and worst cases, but there's no point to that on such a tiny data set because the total time your routine takes is almost certainly going to be dominated by other overhead. So I'm just going to say that the sort will be something on the order of a hundred clock cycles.

That means your sort would add around 6 or 7 microseconds to your 600 microsecond total read time you've got so far, or 1%; you don't have to worry about it at all.

You'll actually spend a lot more time doing other sorts of processing. But it's a pretty fast CPU, as we've seen above, so there's a good chance if you're careful that your loop will still be dominated by the sampling time of the ADC for each of the sensors.

My suggestion is to go ahead and write the thing but record actual timings in your loop for the sampling and the processing. After you've played around with it for a bit you'll have a better idea of the particular costs for each for your particular application and then you can worry about whether or not you need optimization. I suspect you won't.

Regarding the "filtering," that's going to be an integral part of your processing algorithm because the "room light" values can be vastly different from time to time depending on the current lighting in the room. I don't think you want to "filter" anything out, but instead compare the values of all of the photoresistors; at a first guess, similar values from all of them would mean that there's no flashlight and some giving you significantly higher values would indicate that there is one. But my second guess is that a) you'll want your sensors a lot further apart than 1 meter (perhaps in the corners of the room) and b) it's not going to be so simple; you're likely to see fairly different values from the sensors even in a quiescent room. This is where you get to play and experiment to find out how this really works!

It also occurs to me that putting the photoresistors several meters away from the ADC is going to involve a lot of wire, which adds resistance, capacitance and noise, all of which are going to interfere with your measurements. There's not a lot you can do about this; you can play a bit with measuring known-value resistors at the ends of the wires to see how bad the problem is, but if it's terrible you'd probably need to use a separate Arduino for each sensor and have them communicating back to a central place for analysis.

---
Tags: arduino-uno, photoresistor
---


# Question
Title: Power suply for MicroSD card breakout board
I'm developing a project and I need to connect to my Arduino Mini with a SD card breakout board. The problem is that I can't plug it directly to the Arduino since it is already powering some sensors and a BITalino, and I was told that it would, for some reason, be better to connect an external battery to the SD board.

My question is if i can supply this MICROSD CARD BREAKOUT BOARD+ with a 3.7V battery, instead of a 5V.

Thank you!

Description:

* Onboard 5V-\>3V regulator provides 150mA for power-hungry cards
* 3V level shifting means you can use this with ease on either 3V or 5V systems

# Answer
> 1 votes
> My question is if i can suply this MICROSD CARD BREAKOUT BOARD+ with a 3.7V battery, instead of a 5V.

Yes you can supply MICRO SD Card Breakout with 3.7 volt battery as it has onboard voltage regulator which will provide required voltage to the board.

> I was told that it would, for some reason, be better to connect an external battery to the SD board.

Because every sensor will take 3V - 5V as per its requirement. So some time Arduino can not be able to provide 3.3 - 3.5 volt to SD Card board and there could be no data logging or some wrong data logging to SD card. Thus it is advised to do such.

# Answer
> 1 votes
Yes you can give power supply to MICROSD CARD BREAKOUT BOARD from a 3.7V battery It has Onboard LP98x Voltage regulator winch provide 3.3V regulated power supply.

Take reference from here Schematic of MICROSD CARD BREAKOUT BOARD

# Answer
> 1 votes
You just need to bypass the Pro Mini regulator in order to avoid loading it too much, because the uSD Card board already has one.

Instead of connecting the uSD Card breakout board to the VCC pin, connect it to the RAW pin. Provided that your power source (3.7V battery? wall adapter?) can source enough current for the Pro Mini plus the uSD card board (something that's very likely), everything will be fine. No need to add any extra power source.

The regulators in those boards have very similar dropout characteristics (300-400mV).

# Answer
> 1 votes
The "some reason \[it would\] be better to connect an external battery to the SD board" is that you need to make sure that the controller chip and SD card are getting enough power that it can write reliably.

To figure out whether and what kind of external power you need you start with the specifications. The first clue is in the general product description to which you linked; it says that it has an "Onboard 5v-\>3v regulator" that "provides 150mA for power-hungry cards." This is a good start, but you'll see below that we'll need further information from a link on the tutorial page.

Linear power regulators give a fixed voltage output (in this case, 3 V) from a higher voltage input. To work properly they need an input voltage a bit higher than their output voltage; the minimum difference between the two is called the dropout voltage. From the schematic we can see that the board is using an LP298x regulator. A datasheet for a (hopefully typical) part from that series indicates that dropout voltage is 300 mV or 0.3 V. 3.7 V is considerably higher than 3 V + 0.3 V, so you're very likely to be ok in that respect with your external battery. (We also note here that the input voltage can range up to 16 V; we'll use this information later.)

The other thing you need to look at is whether you can supply enough current to the board and card that, under all reasonable circumstances, they can function properly. From the original description you know the board uses a 150 mA regulator which means that the designers expect that you'd never need more than that. (And if you do, the card isn't going to get it anyway.)

For simplicity it's easiest just go go with being able to provide 150 mA or more on the regulator's input, regardless of voltage. (In theory you can supply less power on input if you're giving it a higher voltage, because P = EI, but it's not generally worth the time and effort to go there for a hobbyist project.)

Batteries have a discharge rates known as C rates, and unless you know what you're doing (I don't :-)) your best bet is to stay well within the standard discharge rate as specified by the manufacturer. Adafruit sells a typical 3.7v 1200mAh Lithium Ion Polymer Battery; looking at its datasheet we see that the standard discharge current is 0.5 C5 A, which is 0.5 * 1200 mAh / 1 h = 600 mA, plenty more than you need. So if you're using that battery you'd be safe. (I started out by looking at the 500 mAh battery which has a 0.2 C5 A = 100 mA standard discharge rate; my guess is that that's fine because the maximum discharge rate is 1 C5 A, but this has implications on battery capacity and the like so I'd ask someone first.)

But it would be nice to use your existing power supply for the card rather than use a separate battery, I'm sure. Your best bet for that is the suggestion from Enric Blanco: use an external power supply that can deliver enough current to both the Arduino Pro regulator and the SD Card breakout board regulator that they'll both be happy.

Sadly, Adafruit's Ardiuno Mini product page gives no indication of current requirements. However, a quick look at the v5 schematic we can see that it's using an LP2985AIM5-5.0 regulator and a web search turns up a product page for this that says it's rated at 150 mA.

Add the 150 mA for the Arduino Mini to the 150 mA for the SD card board and you can figure that any external power supply that is giving more than 300 mA at the minimum 7 V input voltage specified for the Arduino Mini should be just fine. The 7 V should also be ok for the SD card board regulator since, even if it's a slightly different model from our spec. sheet, it's unlikely to have a maximum voltage hugely below the 16 V for that part. But you could check the exact part your board is using if you're worried.

---
Tags: power, arduino-pro-mini, sd-card, current
---


title: Substitute for FTDI board?

text:
# Question
Title: Substitute for FTDI board?
I am thinking forward to buy a set of Arduino pro mini. I have a very low budget and I can't think of buying a FTDI board. Is there any substitute for the FTDI board that is compatible with these arduino pro mini.

# Answer
All prices in USD w/ free shipping.

**FT232RL breakout board:**

* Aliexpress: $1.55
* eBay: $1.81

They are probably counterfeit. A Windows driver update (AKA "FTDIgate") at one point "bricked" them but I'm not sure that's an issue anymore. Even if it is it's Windows only and easy enough to work around. I've used these for years on Windows and they work fine for me.

If that's still beyond your budget there are a few other common options. I haven't used these breakout boards but I do have quite a few boards that use the CH340G and they work perfectly once you install the driver. There's a decent chance some of these will also be counterfeit. Some didn't break out the DTR/CTS pin for auto reset but if you're on such a low budget maybe it's worth it to you to press the reset button on every upload to save a few cents. They may not have the standard FTDI header pinout and if so would require you to use jumpers to connect them to the Pro Mini rather than plugging directly into the header.

**PL2303 breakout board:**

* Aliexpress: $0.50
* eBay: $0.74

These don't appear to break out the DTR or CTS pins so they won't do auto-reset.

**CH340G breakout board:**

* Aliexpress: $0.72
* eBay: $0.93

These don't appear to break out the DTR or CTS pins so they won't do auto-reset.

**CP2102 breakout board:**

* Aliexpress $1.00
* eBay: $1.31
> 4 votes

# Answer
Basically, you need any way to talk to the serial interface (on digital pins 0 and 1) on the Pro Mini. Remember that for programming you'll also need to be able to manipulate the reset line on the target board, usually done via DTR.

If you already have an Arduino board with USB, you could write a small sketch that uses that as the interface. Using the SoftwareSerial library or the AltSoftSerial library you could have the USB Arduino talk to the Pro Mini via a couple of data pins and relay the data back and forth. Depending on the Arduino you use and how you program it, it may or may not be able to keep up with 115,200 bps, but rates at or below 57,600 bps should be fine. You'll also need to handle the DTR and CTS signals for programming; this can be done with a couple more data pins.

In general what you're trying to do (whether you go with my solution or another one) is not a beginner project. If you're not familiar enough with Arduino systems to answer the question you posed, I'd strongly suggest buying an Uno, Nano or other board with integrated USB rather than trying to play with the Pro (which is called that for a reason).

If the cost of a single Arduino board is an issue, make sure you're looking around for the cheapest sources. You can find "non-brand" versions of many boards, such as this "Nano" for considerably lower prices than you'll see from the name-brand vendors. They're lower quality and you're not supporting the Arduino ecosystem, but they help when you have a very limited budget.
> 3 votes

---
Tags: usb, arduino-pro-mini
---


# Question
Title: Arduino Pro Mini (5V) Raw Pin and VCC Pin
I am new to the microcontroller world and circuits, so bare with me. I recently bought some 5V arduino pro mini microcontrollers. I have been playing with them and they work fine, I have been powering it from an usb connection.
Now I want to power the board using a 9V battery, I connected the + to the RAW pin and the Ground to the Ground pin on the Arduino.
My question is if I can still use the VCC pins? I understand the board has a voltage regulator that from my understanding it brings down the 9V to 5V. I thought this 5 volts were available through the VCC pin but I connected an LED to it and nothing happens.
I have tried this method with an arduino Uno and it works so I dont know why it doesnt work with the Pro Mini.

# Answer
> 3 votes
As others have pointed out, without a current limiting resistor you may have fried the LED. Thus you might need another LED to test with. On a typical LED with a 1.2 forward voltage drop, a 220 ohm resistor will limit current to about 17 mA (i = v/r.)

forward voltage = supply voltage - LED voltage drop forward voltage = (5.0 - 1.2) = 3.8

current = 3.8V/220ohms = 17 mA.

Check the specs on your LEDs. 1.2 V forward voltage drop is common on little LEDs. Max current of 20 mA is common as well, but it doesn't pay to go all the way to the max. That's the "do not exceed or you may destroy it" level.

# Answer
> 0 votes
One way to figure out the answer to a question like this is to go have a look at the schematic. It's not perhaps not as clear as it could be there, but the VCC output of the regulator is connected to the common VCC bus across the board that's connected to the microcontroller and the JP1 and JP7 headers.

A cheap multimeter can be handy for checking voltages, and would also be able to use it to check the continuity (while the board is unplugged from everything!) between the VCC pin and the output of the regulator.

---
Tags: arduino-uno, battery, arduino-pro-mini
---