title: Manually Declare Global Variable

text:
# Question
Title: Manually Declare Global Variable
Is it possible to manually declare a global variable that is inside of a function. The only current way I know how to do so is to declare that variable within the `setup()` function or simply outside of any function, but I was hoping there was a way to manually declare a variable as global so that I may call one variable from within one function in another function.

# Answer
You need to research 'Scope'.

Your variable has to be at the same level as all functions that will use it. So at a simple level the answer has to be no.

```
int variableOne = 0;
void setup ()
{
  variableOne = 1;
}
void loop ()
{
  variableOne = 2;
}

```

The above code will work, but if you move `int variableOne = 0;` inside either function then it won't work, because the variable will not be in scope in the other function.

You can use parameters to functions.

```
void AFunction (const int& variable);

```

Will let you pass a single integer value to the function from the parent. You can't change that value, because of the `const` qualifier. If you remove the const then the `&` means pass the parameter by reference, which means you are passing in a reference (pointer) to the variable in the parent function and you can change it. A better way to change the parent's value is to return a value from the call.

```
int AFunction (const int& variable);

```

So you could use this like this:

```
int AFunction (const int& variable)
{
  return (++variable);
}
void loop (void)
{
  int value = 0;
  value = AFunction(value);
  // value now == 1.
}

```

You could use a Singleton class, but this is hardcore and I'm not sure you would see any real benefit on an Arduino. A class is a grouping of related function and variables that you see in libraries and a Singleton class means there will only ever be one during the lifetime of the program. In this way you can declare an instance of the class (i.e. `CSingleInstanceClass onlyOne;`) and then retrieve/set data from the setup and loop function, i.e.

```
void setup ()
{
  CSingleInstanceClass onlyOne;  // Single instance class
  onlyOne.SetVariableOne (1);
}
void loop ()
{
  CSingleInstanceClass onlyOne;  // Single instance class
  Serial.println(onlyOne.GetVariableOne());// Prints 1
}

```

Hope that helps.
> 6 votes

# Answer
> even though I understand this takes up a bit of dynamic memory

There is no way around that. They have to go somewhere and that place is RAM (exception: constants could be stored in flash).

Another variation (which goes beyond your question) is that a parent function could declare and build a collection of data in a local array or struct and pass a pointer to it to any sub-functions. It still takes RAM, but it will be on the parent function's stack, so only for the duration of parent function's execution(s); it will be released when the parent function exits.
> 2 votes

# Answer
Please note that 'Scope' of a variable is limited inside the block ( *a block starts at **{** and ends at **}*** ), and that variable cant be accessed outside the block.

consider **life time** of a variable as well. using the keyword **static** may can help you some times. refer this link.
> 0 votes

---
Tags: variables
---


# Question
Title: Is it possible to move a servo without knowing it's current position?
My Servo has already been built into my project, and I can't remove it without damaging many other things. During the process of inserting it, it was turned by hand. So I don't know at what position it is in. It turns a potentiometer that doesn't rotate fully. So I'm worried that if I just set a degree it could turn too far and damage the potentiometer or the servo.

What should I do to find the current position? Is it even possible?

# Answer
> 5 votes
A normal servo is an absolute positioning device. The position of the servo is directly proportional to the length in time of the sync pulse. This means if you tell the servo to be in a given position, it will seek that position with out regard to the initial position. It will simply figure out which way to go on it's own and stop when it gets there.

I should add, that in all likely hood, when you manually moved the servo you moved the positioning potentiometer inside the servo. So it is expected that if the servo is told to go to a particular angle, it will still go to the same angle as it did before you manually moved it.

# Answer
> 0 votes
Yes. Servo can rotate to a particular angle irrespective of previous position.

But you may face an issue here if you rotated the shaft manually by hand (when servo is not powered), and if you reassembled the shaft to the servo in a different orientation. Actually it is really hard to re assemble a removed shaft to the same angle position.

---
Tags: arduino-uno, servo
---


title: Power ESP01 in forest

text:
# Question
Title: Power ESP01 in forest
I want to do WiFi GeoChaching box. I'll use cheap ESP01, but problem is it will work in forest 24/7 in cycle of 1 min of work 5 in deep sleep and waiting for those who will find that. How I can get power?

# Answer
I think that in this case you will need multiple solutions for generating the power.

1. You need to know how much power you need. This depends on you solution, I can't help there.
2. You need a backup battery, ideally one that doesn't mind constant trickle charge and deep discharge. Sealed lead acid are probably the best.
3. Your battery must have enough power over a long enough time.
4. You need a power generator, wind, solar, water, chemical. And they should all have a common interface so you GeoCache is modular, so the GeoCaches can be plugged into any of the power sources, maybe even more than one source.

The problem with the power source is it is going to be a visual clue to where the cache is, probably also an audio clue. The battery, if SLA, is going to be a great big lump that could be dangerous if damaged. The caches are not going to be cheap, just because of the power source and battery, so I hope you have deep pockets.

Rather than looking for a ESP01+BT4 module look for any microprocessor with BT built in, it maybe a better way to go.
> 1 votes

---
Tags: power, wifi
---


# Question
Title: [Arduino UNO]Receive Serial Data from multiple sources
I have the following system:

As a master, I have an Arduino UNO Chip, more specifically an Atmel MEGA328P. The important thing is that this microcontroller has only one hardware Serial port, and that port is used to communicate with a WiFi adapter.

The problem I'm facing with is that I want to receive data from a Compass and a GPS modules. Booth send data via Serial protocol. The 328p Chip have only one serial which is busy!

**I can't use SoftwareSerial as I don't want any delay on master board!** I can't also use Arduino Mega2560 which have 3 Serial ports as its sizes are too big.

So there are are my approaches:

1. Using MCP4725 I2C DAC for Compass, but what we do with GPS?
2. Using and intermediate Arduino UNO Chip? On that chip I could use Software serial but how to transfer data to MASTER using only digital and analogic pins? Maybe using 10 pins to implement a parallel transfer?
3. Perhaps there is possible to convert Compass and GPS data to analogic then transfer to MASTER?

Anyway, what possibilities would I have to play around?

# Answer
> 1 votes
This answer summarizes the possibilities:

1) `HardwareSerial` is always best. You are using that for WiFi.

2) `AltSoftSerial` is the best software serial library, but it requires pins 8 & 9. Very efficient and non-blocking! Strongly recommended for the GPS connection.

3) `NeoSWSerial` is next best, but it supports only 9600, 19200 and 38400. It is non-blocking on receive, so it could be used for the GPS connection.

4) `SoftwareSerial` is the worst. :P Not suitable for the GPS connection, as you have discovered.

I'll also mention my GPS library, NeoGPS. It is smaller and faster than other libraries, and there are examples that show how to make it run *during* the RX character interrupt, saving even more time. It can also be configured for just the messages and fields that you actually use, saving RAM, program space and execution time.

# Answer
> 0 votes
I think softserials are working based pinchange interrupt. This wont make you any significant delay i hop.Or you should go gps or wifi modules with SPI or IIC interface.

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


title: Set EEPROM from PC before program

text:
# Question
Title: Set EEPROM from PC before program
I have been working on an arduino program, which has gotten rather large. I am close to hitting the 32k limit on Flash for my ATmega328p. I would like lower my program size by saving some of my many string literals into EEPROM.

All of the example programs on the EEPROM page suggest loading them in at runtime, in which case they would take up flash memory anyways! What I am wondering, is if there is a way to write to EEPROM from my PC, THEN load the arduino program which will access those values. Do I need some external hardware to do this?

Thanks for your help!

-sam

# Answer
The simplest way would be to have **two** sketches.

One that will store all the strings into EEPROM.

After that you can upload the second actual sketch that uses the values stored in EEPROM.

You only need to upload the first sketch if any of the strings change.

There is a way to upload a hex directly to the EEPROM using avrdude, but you'd have to use the commandline, and also have some way of generating this hex file containing all these strings.
> 4 votes

# Answer
I think here is a confusion about the three types of memory. EEPROM, FLASH and SRAM are completely separate. EEPROM is like your file storage. FLASH contains you program and static values. SRAM is the memory the program is working with.

Static values are loaded from FLASH into SRAM upon start unless you declare your static content not to load automatically by using the according Macro `PROGMEM`. In that case it does not eat up your SRAM until you manually read it from FLASH into SRAM. `#include <avr/pgmspace.h>` is used for this (pgmspace.h).

EEPROM is not loaded automatically and therefore must be read explicitly. `#include <avr/eeprom.h>` contains all the functionality (eeprom.h).

I'm not sure about the Arduino IDE but with avrdude you can program the EEPROM separately without having the values been predefined in your program. The third example in the AVRdude manual shows how to flash the program, eeprom and fuses at once.
> 3 votes

# Answer
You don't need two sketches:

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

char e2str[] EEMEM = "Hello, world!\n";

void setup()
{
    Serial.begin(9600);
    uint8_t *ptr = reinterpret_cast<uint8_t *>(e2str);
    while (true)
    {
        char c = eeprom_read_byte(ptr++);
        if (c == '\0') break;
        Serial.write(c);
    }
}

void loop() {}

```

Compile (Sketch\>Verify/Compile) the source above and you should find file named `<sketch-name>.ino.eep` in project's build directory.

For Arduino Nano, you can just run `avrdude` with `-U eeprom:w:<path-to-eep-file>:i` option before Sketch\>Upload.

For Arduino Uno, however, you must first program it's EEPROM using programmer, since Optiboot doesn't support writing to EEPROM. ~~Or you can burn it with Arduino Nano bootloader once (Tools\>Board\>Arduino Nano, Tools\>Processor\>ATmega328, Tools\>Burn Bootloader) and then use the procedure for Arduino Nano.~~ (Arduino Uno and Nano bootloaders use different baud rates).
> 2 votes

---
Tags: eeprom, code-optimization, flash
---


# Question
Title: Sensirion library for SHT7x humidity sensor
I have following code (and it works great!) for SHT75 Sensirion sensor.

```
/*
 * Example code for SHT1x or SHT7x sensors demonstrating blocking calls
 * for temperature and humidity measurement in the setup routine and
 * non-blocking calls in the main loop.  The pin 13 LED is flashed as a
 * background task while temperature and humidity measurements are made.
 * In addition, the sensor may be placed in low resolution mode by
 * uncommenting the status register write call in setup().
 */

#include <Sensirion.h>

const uint8_t dataPin =  2;            // SHT serial data
const uint8_t sclkPin =  3;            // SHT serial clock
const uint8_t ledPin  = 13;            // Arduino built-in LED
const uint32_t TRHSTEP   = 3000UL;     // Sensor query period
const uint32_t BLINKSTEP =  250UL;     // LED blink period

Sensirion sht = Sensirion(dataPin, sclkPin);

uint16_t rawData;
float temperature;
float humidity;
float dewpoint;

byte shtState = 0;
byte ledState = 0;

unsigned long curMillis;               // Time interval tracking
unsigned long trhMillis = 0;
unsigned long blinkMillis = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  delay(15);                           // Wait at least 11 ms before first cmd
//  sht.writeSR(LOW_RES);                // Set sensor to low resolution
  sht.measTemp(&rawData);              // Maps to: sht.meas(TEMP, &rawData, BLOCK)
  temperature = sht.calcTemp(rawData);
  sht.measHumi(&rawData);              // Maps to: sht.meas(HUMI, &rawData, BLOCK)
  humidity = sht.calcHumi(rawData, temperature);
  dewpoint = sht.calcDewpoint(humidity, temperature);
  logData();
}

void loop()
{
  curMillis = millis();

  if (curMillis - blinkMillis >= BLINKSTEP) {    // Time to toggle the LED state?
    ledState ^= 1;
    digitalWrite(ledPin, ledState);
    blinkMillis = curMillis;
  }

  switch (shtState) {
  case 0:
    if (curMillis - trhMillis >= TRHSTEP) {      // Start new temp/humi measurement?
      sht.meas(TEMP, &rawData, NONBLOCK);
      shtState++;
      trhMillis = curMillis;
    }
    break;
  case 1:
    if (sht.measRdy()) {                         // Process temperature measurement?
      temperature = sht.calcTemp(rawData);
      sht.meas(HUMI, &rawData, NONBLOCK);
      shtState++;
    }
    break;
  case 2:
    if (sht.measRdy()) {                         // Process humidity measurement?
      humidity = sht.calcHumi(rawData, temperature);
      dewpoint = sht.calcDewpoint(humidity, temperature);
      shtState = 0;
      logData();
    }
    break;
  default:
    Serial.println("How did I get here?");
    break;
  }
}

void logData() {
  Serial.print("Temperature = ");   Serial.print(temperature);
  Serial.print(" C, Humidity = ");  Serial.print(humidity);
  Serial.print(" %, Dewpoint = ");  Serial.print(dewpoint);
  Serial.println(" C");
}

```

How can I extend it for ***two*** sensors (by using of another pins, of course)?

# Answer
> 1 votes
You simply create a second instance of the object with different pins and store the result in a different set of variables. Any extra logic of when to do what is purely down to you.

---
Tags: temperature-sensor
---


# Question
Title: Is the Arduino bootloader really the Atmel bootloader? Can I use Flip to upload?
I've been asked to do a small project using an Ada BlueFruit board. It has a ATMega32U4. The 32U4 comes from the factory with a bootloader pre-installed. I've never used an Arduino before, but I have used AVR a bit in the past. Is the Arduino bootloader actually the one that came pre flashed from the factory? Does it even matter if it's the same bootloader as far as Flip is concerned?

Can I use the Flip batchisp utility to load my application code? We don't have a programmer handy and I don't want to muck up the bootloader on the board.

It's my understanding that the Arduino IDE tool chain does a bit of preprocessing "behind your back". I'd much rather continue writing straight AVR code in Atmel Studio. Is there anything I need to take into account when writing my application code? For example, do I need to do anything when compiling my app code, or when uploading it, to ensure it doesn't try to write to the memory addresses in the bootloader's range?

# Answer
> 1 votes
> Is the Arduino bootloader actually the one that came pre flashed from the factory?

You would have to ask Adafruit that.

> It's my understanding that the Arduino IDE tool chain does a bit of preprocessing "behind your back". Is there anything I need to take into account when writing my application code?

The things you are talking about is generation of function prototypes, that sort of thing. It's nothing you really need to worry about.

> For example, do I need to do anything when compiling my app code, or when uploading it, to ensure it doesn't try to write to the memory addresses in the bootloader's range?

No, it would be crazy for the IDE to overwrite the bootloader. Then you wouldn't be able to use it again. In fact, to change the bootloader needs special hardware. You need to connect a programmer to the ICSP pins.

---

> I just want to know if I need to do anything special during linking to ensure there's no memory address conflicts

I doubt you need to worry about that, as long as you ensure that whatever tool you are using knows to allow room for the bootloader.

> and if I can use the Flip tool to upload

I don't see why not. Or you could use the dfu-programmer as I describe in my post How to flash the USB chip on the Arduino Uno.

# Answer
> 2 votes
Arduino uses a different (second) bootloader, next to the DFU one that build into the 32u4.

# Answer
> 2 votes
> I'd much rather continue writing straight AVR code in Atmel Studio.

The Arduino IDE allows you be lazy about #includes and forward references to functions, but it won't get in your way if you choose to write correct code.

I write standard C/C++ and switch back and forth between Eclipse (no over-helpful pre-processing) and the Arduino IDE. The Arduino IDE knows better; it just CYA (covers your assumptions :) in case you don't.

---
Tags: programming, avr, adafruit
---


title: Controlling an OSX app by Arduino

text:
# Question
Title: Controlling an OSX app by Arduino
I am trying to control an app on OSX with an Arduino Uno. Specifically, I would like to start and stop play of an MP3 on iTunes, or a track on Spotify, using an Arduino connected to the Apple computer with USB.

Any suggestions would be greatly appreciated.

# Answer
> 0 votes
I am now having Screen output to log.txt, and the following applescript works just great!

set trigger to 1

set stopString to ""

repeat until (stopString = "stop")

set testTxt to paragraphs of (read POSIX file "/Users/fed/log.txt") set countTxt to (count of testTxt) - 1 set lastLine to item countTxt of testTxt
if lastLine contains "Start MP3" and trigger is 1 then tell application "Spotify" to playpause set trigger to 0 end if

if lastLine does not contain "Start MP3" then set trigger to 1 end if

if lastLine contains "Stop Loop" then set stopString to "stop" end if end repeat

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


# Question
Title: Communication Protocol Best Practices and Patterns
Every time I design a serial protocol to be used between two arduinos, I feel a bit like I'm reinventing a wheel. I wonder if there are any best practices or patterns people follow. This question is less about the actual code, but more about the format of the messages.

For example, if I wanted to tell an arduino to flash it's first LED 3 times I might send:

```
^L1,F3\n

```
* '^': starts a new command
* 'L': Defines the command, (L: target this command to an LED)
* '1': Target the first LED
* ',': Command line separator, new value in this message to follow
* 'F': Flash sub-command
* '3': 3 times (Flash the LED three times)
* '\n': End the command

Thoughts? How do you usually approach writing a new serial protocol? What about if I wanted to send a query from arduino 1 to arduino 2 and then receive a response?

# Answer
> 16 votes
There are a lot of ways to write a serial protocol depending on what functionality you might want and how much error checking you need.

Some of the common things you see in point to point protocols are:

**End of message**

The simplest ASCII protocols just have an end of message character sequence, often `\r` or `\n` as this is what gets printed when the enter key is hit. Binary protocols might use `0x03` or some other common byte.

**Start of message**

The problem with just having end of message is that you don't know what other bytes have already been received when you send your message. These bytes would then be prefixed to the message and cause it to be interpreted wrongly. For example, if the Arduino just woke from sleep there might be some garbage in the serial buffer. To get around this you have a start of message sequence. In your example, `^`, in binary protocols often `0x02`

**Error Checking**

If the message can be corrupted we need some error checking. This could be a checksum or a CRC error or something else.

**Escape Characters**

It could be that the checksum adds to a control character, such as the 'start of message' or 'end of message' byte, or the message contains a value equal to a control character. The solution is to introduce an escape character. The escape character is placed before a *modified* control character so that the actual control character is not present. E.g. if a start character is 0x02, using the escape character 0x10 we can send the *value* 0x02 in the message as the byte pair 0x10 0x12 (byte XOR control character)

**Packet number**

If a message is corrupted we could request a resend with a nack or retry message, but if multiple messages have been sent then only the latest message can be resent. Instead the packet can be given a number that rolls over after a certain number of messages. For example, if this number is 16, the transmitting device can store the last 16 messages send and if any were corrupted the receiving device can request a resend using the packet number.

**Length**

Often in binary protocols you see a length byte which tells the receiving device how many characters are in the message. This adds another level of error checking as if the correct number of bytes were not received then there was an error.

***Arduino specific***

When coming up with a protocol for Arduino the first consideration is how reliable is the communications channel. If you are sending over most wireless mediums, XBee, WiFi, etc, there is already built in error checking and retries and thus no point in putting these in your protocol. If you are sending over RS422 for a couple of kilometres then it will be necessary. The things I would include are the start of message and end of message characters, as you have. My typical implementation looks something like:

`>messageType,data1,data2,…,dataN\n`

Delimiting the data parts with a comma allows for easy parsing, and the message is sent using ASCII. ASCII protocols are great because you can type messages into the serial monitor.

If you want a binary protocol, maybe to shorten the message sizes, you will have to implement escaping if a data byte can be the same as a control byte. Binary control characters are better for systems where the full spectrum of error checking and retries is desired. The payload can still be ASCII if desired.

# Answer
> 10 votes
I do not have any formal expertise on serial protocols, but I've used them quite a few times, and more or less settled on this scheme:

(Packet header)(ID byte)(data)(fletcher16 checksum)(Packet Footer)

I usually make the header 2 bytes and the Footer 1 byte. My parser will dump everything when it sees a new packet header, and attempt to parse the message if it sees a footer. If the checksum fails, it will not ditch the message, but continue adding until the footer character is found and a checksum succeeds. That way the footer only needs to be one byte since collisions don't disrupt the message.

The ID is arbitrary, sometimes with the length of the data section being the bottom nibble (4 bits). A second length bit could be used but I normally don't bother since the length does not need to be known to parse correctly, so seeing the right length come through for a given ID is just more confirmation that the message was correct.

The fletcher16 checksum is a 2 byte checksum with nearly the same quality as CRC but is much easier to implement. some details here. The code can be as simple as this:

```
for(int i=0; i < bufSize; i++ ){
   sum1 = (sum1 + buffer[i]) % 255;
   sum2 = (sum2 + sum1) % 255;
}
uint16_t checksum = (((uint16_t)sum1)<<8) | sum2;

```

I've also used a call and respone system for critical messages, Where the PC will send a message every 500ms or so until it gets an OK message with a checksum of the whole original message as data (including the original checksum).

This scheme is, of course, not well suited for being typed into a terminal like your example would be. Your protocol seems pretty good for being limited to ASCII and I'm sure is easier for a quick project that you want to be able to directly read and send messages. For larger projects it is nice to have the density of a binary protocol and the security of a checksum.

# Answer
> 4 votes
If you're into standards, then you may take a look at ASN.1 / BER TLV encoding. ASN.1 is a language used to describe data structures, made specifically for communication. BER is a TLV method of encoding the data structured using ASN.1. Problem is that ASN.1 encoding may be tricky at best. Creating a full fledged ASN.1 compiler is a project in itself (and a particularly tricky one at that, think *months*).

---

It's probably better to keep just the TLV structure. TLV basically consists of three elements: a tag, a length and a value field. The tag defines the type of the data (text string, octet string, integer etc.) and the length the length *of the value*.

In BER the T also denotes if the value is a set of TLV structures itself (a constructed node) or directly a value (a primitive node). That way you can create a tree in binary, much like XML (but without the XML overhead).

Example:

```
TT LL VV
02 01 FF

```

is an integer (tag `02`) with a length of the value of 1 (length `01`) and value -1 (value `FF`). In ASN.1 / BER the integers are sign big endian numbers, but you can of course use your own format.

```
TT LL (TT LL VV, TT LL VV VV)
30 07  02 01 FF  02 02 00 FF

```

is a sequence (a list) with length 7 containing *two* integers, one with value -1 and one with value 255. The two integer encodings together make up the value of the sequence.

You can simply toss this into an online decoder too, aint that nice?

---

You can also use indefinite length in BER which will allow you to stream data. In that case you do need to parse your tree correctly though. I'd consider it an advanced topic, you need to know about breadth first and depth first parsing, for one.

---

Using a TLV scheme basically allows you to think of any kind of data structure and encode it. ASN.1 goes a lot further than that, giving you unique identifiers (OID's), choices (a lot like C-unions), includes of other ASN.1 structures etc. etc. but that may be overkill for your project. Probably the best well known ASN.1-defined structures today are the certificates used by your browser.

# Answer
> 0 votes
If not, you've got the basics covered. Your commands can be created and read by both humans and machines which is a big plus. You might add a checksum to detect a mal-formed command or one damaged in transit, especially if your channel includes long cable or a radio link.

If you need industrial strength (your device mustn't cause or allow someone to get hurt or die; you need high data rates, fault recovery, missing packet detection etc.) then look to some of the standard protocols and design practices.

---
Tags: serial
---


title: NodeMCU : Input pullup in A0

text:
# Question
Title: NodeMCU : Input pullup in A0
I am trying to port a simple project I have working in an Arduino UNO to a NodeMCU but I am stuck as I am using the analog gpio to receive the input from some buttons, I am always getting always low values (between 0 and 5) while in the working arduino sketch I get values from 0 to 1023.

I have tried deactivating the wifi while trying to retrieve the values, but I got no luck trying that, as I have read that sometimes the NodeMCU A0 gpio malfunctions when the wifi is not sleeping.

I am setting up the gpio in the setup method like this:

```
void setup(void){
    pinMode(sensorPin, INPUT_PULLUP);
    ...

```

And my sensorPin variable is declared in the beginning of the sketch

```
int sensorPin = A0;

```

Any ideas why when I read the value in the NodeMCU I don't get the same behaviour as in an Arduino board?

# Answer
As stated by Majenko in the comments, I thought that all MCUs analog gpios had a pullup resistor built in, so I have been able to solve the problem using an external pullup, in this case connecting a 10K resistor like in the diagram:

.

Special thanks to Majenko for his time and patience. Cheers!
> 3 votes

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


title: External power supply?

text:
# Question
Title: External power supply?
I have a project where I'm looking to power 120 RGB LEDs in a strip (WS2812B).

Obviously an Arduino Micro cannot supply this amount of current so I'm looking to use an external 5V/4A switching power supply (wall-wart) to power the LED's as well as the Arduino.

My question is, can I just split the power from the wall-wart providing 5v\_reg directly to the 5V pin on the Arduino Micro and 5v\_reg to the LEDs Vss?

It it necessary to use extra bypass capacitors in this case?

# Answer
> My question is, can I just split the power from the wall-wart providing 5v\_reg directly to the 5V pin on the Arduino Micro and 5v\_reg to the LEDs Vss?

Yes. As long as it is a clean regulated 5V supply.

> It it necessary to use extra bypass capacitors in this case?

No.
> 3 votes

---
Tags: power, arduino-micro
---


# Question
Title: Arduino + CO2 + humidity + noise + temperature sensors on one board
I'm looking for an Arduino board that include this sensors out of the box:

* CO2
* Humidity
* Noise
* Temperature

I've found here Using the Waspmote Sensor Board something that could be enough, but I'm searching for more options.

I did a lot of searches on the Internet without good results.

Any suggestions?

# Answer
> 1 votes
For humidity and temperature you can plug the DHT11 or DHT22 to your arduino. DHT11 is cheaper but you'll get a more precise value with DHT22.

For noise you have ready made PCB like these : here You'll only have to plug it to GND, 5V and analog input.

For CO2 this is more complicate. There is a cheap but very unprecise option, using a MQ135 sensor, here is a tutorial: here Otherwise there are better sensors like the K30 but they are much more expensive.

---
Tags: sensors
---


# Question
Title: Supplying power to arduino by 5V and 2A adapter
Can I power my Arduino using a 5V/2A adapter by connecting it through the USB port?

More precisely, I have to run a module requiring 200mA but the aim is to make the laptop independent.

# Answer
Amps are not "forced" through a circuit like volts are. A closed circuit draws as much power (in amps) as it needs, so the only problem you could ever have is having too *little* current and not too much. Seeing as your module draws 200ma 2 amps to power it is plenty.
> 1 votes

# Answer
I'm not quite sure what the second half of your question is saying, but:

> can i power my Arduino by 5 volt 2 amp adapter by connecting it through the usb port

Yes, you can.
> 0 votes

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


# Question
Title: What is the variable pot exactly for in arduino sensors boards?
I have a MQ135 gas sensor from keyestudio, and a light sensor from a chinese manufacturer. They are both on their own PCB with resistors, small eeprom and a variable pot.

Turning the variable pot fine tune the calibration of the sensor, but is there anyone who could explain me exactly what is it doing? Does it have an effect on signal amplification? or only adding more or less resistance to the signal output by the light sensor in order to fine tune the reading ?

# Answer
> 1 votes
If the resistance is higher, your LDR (light sensor) will respond in smaller increments or decrements to the same light changes. Analog inputs have 10 bit (0-1023) resolution, which is fine, but LDRs can be tricky (their sensitivity varies), so a pot is useful for prototyping the resistance you need to wire it up with in your project.

# Answer
> 0 votes
It's for sensitivity adjustment.

---
Tags: sensors
---


title: User-Agent question

text:
# Question
Title: User-Agent question
I've seen a few different User-Agents used in demo sketches and am curious as to what the various User-Agent options are and how to determine which one to use.

For example...
`User-Agent: Mozilla/4.0`
`User-Agent: Arduino/1.0`
`User-Agent: ESP8266`
`User-Agent: ArduinoWiFi/1.1`

I've used Arduino/1.0 successfully with an Uno/WiFi101 but want to use an ESP8266 now. Do I continue using Arduino/1.0 or switch to ESP8266 (Arduino IDE 1.6.5)?

When would someone use Mozilla?

Any guidance is appreciated.

# Answer
> 3 votes
You can use anything you like. It's used by the remote server to (try and) determine what browser you're using in order to give you the best visual experience. On an Arduino you really don't care about the visual experience. You don't even *need* to provide a `User-Agent` field, but it is courteous to do so.

---
Tags: arduino-uno, c++, esp8266, networking
---


# Question
Title: Extracting a specific sequence of characters from an array
I have a character array called `storebuffer` that contains data from a POST submission and its in the format `ssid=abcdef&pswd=ghijk`. I wanted to extract everything after `ssid=` into one array called `acqSSID` and the portion after `&pswd=` into another array called `acqPaswd`. I tried using this but it does not seem to be working. MAX\_STORE\_BUFFER\_LEN is 255. Can anyone help?

```
int ctr = 0;
for (ctr = 5; ctr < MAX_STORE_BUFFER_LEN; ctr++)
{
  if ( (storebuffer[ctr] == '&') && (storebuffer[ctr+1] == 'p') && (storebuffer[ctr+2] == 's') && (storebuffer[ctr+3] == 'w') && (storebuffer[ctr+4] == 'd') && (storebuffer[ctr+5] == '=') )
  {
    break;
  }
  acqSSID[ctr] = storebuffer[ctr];
}

Serial.print("acqSSID: ");
Serial.println(acqSSID);
Serial.print("ctr: ");
Serial.println(ctr);

```

# Answer
> 1 votes
You can simply chop it up in place without requiring more than a few extra bytes of RAM using `strtok()`:

```
char storebuffer[] = "ssid=abcdef&pswd=ghijk";

// Slice it into two parts around the &:
char *lefthalf = strtok(storebuffer, "&");
if (lefthalf != NULL) { // We found a & and split the string OK
    char *righthalf = strtok(NULL, "&");

    // Now you can slice each half around the =
    char *ssidtag = strtok(lefthalf, "=");
    char *ssid = strtok(NULL, "=");
    char *pswdtag = strtok(righthalf, "=");
    char *pswdtag = strtok(NULL, "=");

    Serial.print("SSID: ");
    Serial.println(ssid);
    Serial.print("Password: ");
    Serial.println(pswd);
}

```

The existing string gets chopped up and the pointers point to different places:

```
ssid\0abcdef\0pswd\0ghijk
^     ^       ^     ^
1     2       3     4

1: ssidtag
2: ssid
3: pswdtag
4: pswd

```

# Answer
> 0 votes
Rather than `acqSSID[ctr] = storebuffer[ctr];`, say (eg) `acqSSID[ctr-5] = storebuffer[ctr];`. Also, after the break but before printing `acqSSID`, say `acqSSID[ctr-5] = 0;` to terminate the string.

Note, rather than coding a literal 5, you might say `enum { acqOffset=5 };` up front, and subsequently use `acqOffset` in place of the literal.

---
Tags: arduino-yun, array
---


# Question
Title: Delaying pushbutton input to microcontroller while it's busy processing I/O
I am trying to create my own home automation using Arduino. I am using shift register for reading input(via push buttons) and writing output to led's. I am using SPI interface to communicate with shift registers.

Apart from SPI Arduino also deals with I2C devices. When push button is clicked Arduino ISR is invoked via pin 2, which then checks exact button that was pushed and takes action accordingly. The functionality currently works well with one small problem.

Sometimes when push button is clicked Arduino ignores the button press. After debugging for some time I observed that it happens when Arduino is busy with I2C communication with other devices.

I would like to know if it is possible to temporarily delay the push button input while Arduino busy with I2C communication? or is it possible to prioratize interrupt handling over I2C communication?

Below is the simplified code

```
#include <SPI.h>
#include <Wire.h>
byte Input=1;
volatile byte Check=1;
volatile byte Output=1;

int j;
//Pin connected to ST_CP of 74HC595
int latchPin = 8;
//Pin connected to SH_CP of 74HC595
int clockPin = 13;
////Pin connected to DS of 74HC595
int dataPin = 11;

int interruptPin=2;

int espPin=7;

char arduinoStatus[100]="\0";

 void pin_read(){

    for(j=0; j<50; j++)
    delayMicroseconds(1000);

    Check=1;
    for(j=0; j<8; j++){
      digitalWrite(latchPin, LOW);
      delayMicroseconds(500);

     SPI.transfer(Check);
     SPI.transfer(Output);

     digitalWrite(latchPin, HIGH);

     delayMicroseconds(500);
    if(digitalRead(interruptPin)==HIGH){
      //Serial.println(Check);

      if(bitRead(Output, j)==1)
      bitWrite(Output, j, 0);
      else
      bitWrite(Output, j, 1);
    }//dig check

    Check = Check<<1;

    }

    digitalWrite(latchPin, LOW);
    delayMicroseconds(500);
    SPI.transfer(255); //to push buttons
    SPI.transfer(Output); //to LEDs

    digitalWrite(latchPin, HIGH);
    delayMicroseconds(500);

}//pin_read

void setup() {
  //set pins to output so you can control the shift register
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(espPin, OUTPUT);
  pinMode(interruptPin, INPUT);//Input from buttons

  delay(1000);
  // the LEDs don't change while you're sending in bits:
    digitalWrite(latchPin, LOW);
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  SPI.setClockDivider(SPI_CLOCK_DIV2);
  SPI.begin();
  SPI.transfer(255);
  SPI.transfer(255);
   //take the latch pin high so the LEDs will light up:
    digitalWrite(latchPin, HIGH);

    Serial.begin(115200);
    attachInterrupt(0, pin_read, RISING);

    Wire.begin(8);                // join i2c bus with address #8
  Wire.onRequest(requestEvent); // register event
  Wire.onReceive(receiveEvent);

  Serial.println("Initialized...");
}

void loop() {
  Serial.println("Interrupting...");
 digitalWrite(espPin, HIGH);

 while(digitalRead(interruptPin)==HIGH){}
  delayMicroseconds(500);
 digitalWrite(espPin, LOW);
 delayMicroseconds(500);
 Serial.println("Done...");
Serial.print("Output:");
Serial.println(Output);
delay(3000);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  int i=0;
  Serial.println("received::");
  while (Wire.available()) { // loop through all
    char c = Wire.read(); // receive byte as a character
    arduinoStatus[i++]=c;

    Serial.print(c);         // print the character

  }
  arduinoStatus[i]='\0';
  Serial.println("###");
}

// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent() {
  Serial.println("Sending...");
  Wire.write("hello"); // respond with message of 6 bytes
  Wire.write(Output);
  Serial.println("Sent");
  // as expected by master
}

```

# Answer
Without looking any further than the first `delaymicroseconds()` command I would say that that's where the trouble lies. The `delay()` functions are very handy for getting the beginner's first LED to blink and are a big problem after that. The problem is that the CPU is completely tied up during the delay and can't do anything else other than interrupts and you only have a limited supply of those. Your button press is missed.

You need to develop your own timers in the code and keep the main loop running constantly checking on each pass to see if the delay is complete.
> 1 votes

# Answer
What about polling the buttons periodically instead of using an interrupt? If you check them every 10 ms or so, you should still be able to detect a button press reliably. Connecting buttons to interrupt inputs is not necessarily the best idea due to contact bounce - this can cause a number of back-to-back interrupts. My guess is that interrupts are being disabled during some part of your code and when the interrupt pin level changes during that period, it gets ignored.
> 0 votes

---
Tags: i2c, spi
---


# Question
Title: can i unplug my Arduino project when i'm done installing the libraries and it still work the way it did when it is plugged in
can i unplug my Arduino project when i'm done installing the libraries and it still work the way it did when it is plugged in

# Answer
Once you compile and upload your arduino sketch and any libraries it uses, your code is stored in nonvolatile memory inside the processor. You can unplug your arduino and power it up later and it will run your code again with out any help from your computer.
> 2 votes

---
Tags: arduino-uno, atmega328
---


# Question
Title: Problem with wrapping Adafruit Motor Controller function calls in a class
I'm working on an Arduino robot and I ran into a problem when reorganizing my code. I have an Adafruit Motor Shield v2.3 connected to an Arduino Uno. My robot can be controlled using a bluetooth connection (BlueSMIRF module) or it can be told to avoid obstacles using an ultra sonic range finder.

Everything worked fine and the robot moved nicely until I decided I wanted to organize the code better, so that my code for moving the robot would be in a separate class, my code for servo movement also in a class as well as my code for the logic for movement (received bluetooth command - do this, or avoid obstacles like so, etc.). Suddenly, none of the motors respond or just one.

I'm not sure if I have a problem with my C++ and passing pointers to my functions or what is going on...

Here is my main .ino file, its relevant parts, I left out stuff that concerns the bluetooth connection etc. And yes, I know the hardcoded include paths look ugly, I'll figure out what to do with includes at some point... :

```
// bluetoothRobot.ino

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include <Servo.h>
#include <SonarSRF08.h>
#include <SoftwareSerial.h>
#include <MemoryFree.h>
#include "utility/Adafruit_PWMServoDriver.h"

#include "\Users\Jarno\Arduino\bluetoothOhjausBot\MotorController.h"
#include "\Users\Jarno\Arduino\bluetoothOhjausBot\AvoidObstacleController.h"
#include "\Users\Jarno\Arduino\bluetoothOhjausBot\MemoryFree-master\MemoryFree.h"

MotorController* motorController;

Adafruit_MotorShield AFMS = Adafruit_MotorShield();

Adafruit_DCMotor *rightRearMotor = AFMS.getMotor(1);
Adafruit_DCMotor *leftRearMotor = AFMS.getMotor(2);
Adafruit_DCMotor *rightFrontMotor = AFMS.getMotor(3);
Adafruit_DCMotor *leftFrontMotor = AFMS.getMotor(4);

void setup()
{
    motorController->start(&AFMS, leftRearMotor, leftFrontMotor, rightFrontMotor, rightRearMotor);
    AFMS.begin();
}

void loop()
{
    if(bluetooth.available())  {
        char command = (char) bluetooth.read();

        if (controlMode == 2) {
            motorController->executeBluetoothCommand(command);
        }
    }
}

```

Here is my MotorController.h:

```
// MotorController.h

#ifndef MotorController_h
#define MotorController_h

#include "Arduino.h"
#include <Wire.h>
#include <Adafruit_MotorShield.h>

class MotorController {
    public:
      int executeBluetoothCommand(char command);
      void start(Adafruit_MotorShield *AFMS, Adafruit_DCMotor *rightRearMotor, Adafruit_DCMotor *leftRearMotor, Adafruit_DCMotor *rightFrontMotor, Adafruit_DCMotor *leftFrontMotor);
      void turnRight();
      void turnLeft();
      void moveForward();
      void moveBackward();
      void stopRobot();
      void setRobotSpeed(int leftWheelsSpeed, int rightWheelsSpeed);
    private:
      Adafruit_MotorShield* AFMS;
      Adafruit_DCMotor* leftRearMotor;
      Adafruit_DCMotor* rightRearMotor;
      Adafruit_DCMotor* rightFrontMotor;
      Adafruit_DCMotor* leftFrontMotor;
  };

#endif

```

And here is MotorController.cpp:

```
// MotorController.cpp

#include "\Users\Jarno\Arduino\bluetoothOhjausBot\MotorController.h"

void MotorController::start(Adafruit_MotorShield *shield, Adafruit_DCMotor *rrm, Adafruit_DCMotor *lrm, Adafruit_DCMotor *rfm, Adafruit_DCMotor *lfm) {
      AFMS = shield;
      rightRearMotor = rrm;
      leftRearMotor = lrm;
      rightFrontMotor = rfm;
      leftFrontMotor = lfm;
      setRobotSpeed(80,80);
  }
int MotorController::executeBluetoothCommand(char command) {
        switch(command) {
            case 'F':
              moveForward();
              break;

            case 'B':
              moveBackward();
              break;

            case 'L':
              turnLeft();
              break;

            case 'R':
              turnRight();
              break;

            case 'S':
              stopRobot();
              break;

            /*case 'W':
              stopRobot();
              controlMode = 1;
              tiltServoAngle = 120;
              panServoAngle = 90;
              motorController.setPanAndTilt(panServoAngle, tiltServoAngle);
            */
            default:
              return -1;
              }
    return 0;

}
void MotorController::setRobotSpeed(int leftWheelsSpeed, int rightWheelsSpeed) {
        leftFrontMotor->setSpeed(leftWheelsSpeed);
        leftRearMotor->setSpeed(leftWheelsSpeed);
        rightRearMotor->setSpeed(rightWheelsSpeed);
        rightFrontMotor->setSpeed(rightWheelsSpeed);
  }
void MotorController::moveForward() {

        setRobotSpeed(80,80);
        leftRearMotor->run(FORWARD);
        rightRearMotor->run(FORWARD);
        leftFrontMotor->run(FORWARD);
        rightFrontMotor->run(FORWARD);

  }

void MotorController::moveBackward() {
        leftRearMotor->run(BACKWARD);
        rightRearMotor->run(BACKWARD);
        rightFrontMotor->run(BACKWARD);
        leftFrontMotor->run(BACKWARD);
        setRobotSpeed(80,80);
  }

void MotorController::turnLeft() {
        leftRearMotor->run(BACKWARD);
        rightRearMotor->run(FORWARD);
        rightFrontMotor->run(FORWARD);
        leftFrontMotor->run(BACKWARD);
        setRobotSpeed(80, 80);
  }

void MotorController::turnRight() {
        leftRearMotor->run(FORWARD);
        rightRearMotor->run(BACKWARD);
        rightFrontMotor->run(BACKWARD);
        leftFrontMotor->run(FORWARD);
        setRobotSpeed(80, 80);

  }

void MotorController::stopRobot() {
        leftRearMotor->run(RELEASE);
        rightRearMotor->run(RELEASE);
        rightFrontMotor->run(RELEASE);
        leftFrontMotor->run(RELEASE);
  }

```

I used to have a constructor for MotorController with the Motor Shield library `AFMS.begin()` call in it and all. But this caused the Arduino to constantly reset for some reason. I coudn't understand why but I moved the motor configurations and call to `begin()` to my .ino file where the problem doesn't occur.

**Problem:** What happens with the code as it is, is which ever pointer to motor is passed last seems to work and that particular motor turns but the others won't. If I comment out the call to `setRobotSpeed` in `MotorController::start`, nothing happens with any motor even though speed is also set in the relevant functions.

As said, the robot worked fine when the code was in my .ino file. Although, for some reason I had to call the Motor Shield library's `begin()` function always before any other commands to motors. So it was called every time the user told the robot to move forward, move backward etc. Otherwise nothing happened with the motors. Now, if I add a call `AFMS->run()` to my MotorController.cpp, the Arduino starts to constantly reset...

Also, none of the other stuff (blueSMIRF, the range finder code etc.) should interfere since they were also there when it worked and I even commented out that stuff.

I'm baffled. Maybe its some silly mistake with my C++? Or is there really something weird going on here?

Any help would be much appreciated, I've spent hours trying to figure this thing out! Thanks in advance!

# Answer
> 0 votes
The obvious issue in your current code is that `motorController` is a pointer to your class but I don't see any place it was instantiated properly.

Hence, it points **anywhere** the first time you use it, which can explain resets of the MCU.

Now, either you keep it as a pointer:

```
MotorController* motorController;

```

**And then you instantiate it in place**:

```
MotorController* motorController = new MotorController();

```

**Or you can also instantiate it in `setup()` as first line (ie before it is used anywhere else)**:

```
void setup() {
    motorController = new MotorController();
    ...
}

```

**However**, for reasons discussed elsewhere on this site, I would not use dynamic allocation but **I'd rather define `motorController` as an instance of `MotorController` instead of a pointer**:

```
MotorController motorController;

```

Now everywhere you were using `motorController->xxx` you'll have to replace it it with `motorController.xxx`.

That should remove the most important bug of your current code (I can-'t tell if there are other issues but this one must be fixed in priority).

# Answer
> 0 votes
One thing about instantiating classes before `setup()` is called is that `init()` (which you don't see) may undo all of your careful setup.

Your code starts:

```
Adafruit_DCMotor *rightRearMotor = AFMS.getMotor(1);
Adafruit_DCMotor *leftRearMotor = AFMS.getMotor(2);
Adafruit_DCMotor *rightFrontMotor = AFMS.getMotor(3);
Adafruit_DCMotor *leftFrontMotor = AFMS.getMotor(4);

```

but these are constructed before `setup()`. And then you call `MotorController::start()` with those values. You haven't provided the code for `AFMS::getMotor()` \- so it may be doing things internally that is undone by `init()`.

Instead of creating the whole pointer, why not do this:

```
const byte rightRearMotor = 1;
const byte leftRearMotor = 2;
const byte rightFrontMotor = 3;
const byte leftFrontMotor = 4;

```

and then callig `AFMS.getMotor()` inside `MotorController::start()`:

```
void MotorController::start(Adafruit_MotorShield *shield,
                            byte rrm, byte lrm, byte rfm, byte lfm) {
    AFMS = shield;
    rightRearMotor = AFMS.getMotor(rrm);
    leftRearMotor = AFMS.getMotor(lrm);
    rightFrontMotor = AFMS.getMotor(rfm);
    leftFrontMotor = AFMS.getMotor(lfm);
    setRobotSpeed(80,80);
}

```

---
Tags: motor, adafruit, arduino-motor-shield, pointer
---


title: NFC 'dynamic' UID database

text:
# Question
Title: NFC 'dynamic' UID database
Hi SE (and Majenko in particular, if I'm lucky) - I have a setup with an SD module (on SPI) and an Elechouse PN532 NFC reader (on I2C). I would like to use a master tag to enter MASTER MODE \[sic\] to add tags if they are not present in a file on my SD card, or remove tags which are present in the same file. I am currently checking tag UID against a hardcoded master UID, and it works well enough for now. What trips me up is making the tag database in the most arduino-friendly way. How would you advise me to do this in the most spartan way? And when removing existing tags from the database, how would you suggest I update it, to remove unwanted UIDs? I am using a flat text database now, but it could be a binary file - I am just puzzled by what is the best method to remove an entry(line) from a file using SD library.

# Answer
You got me ;)

Since a UID is a fixed size you don't need to think in "lines", only in bytes.

The most efficient way of storing the UIDs is as pure bytes. I am not familiar with that specific card and reader combination, but I will assume as an example an 8 byte UID (though this all holds true for any other length you care to choose).

You treat your file on SD card like a kind of database with a number of records in it. Each record is the exact same size (8 bytes in this case) . To read or write a specific record you just "seek" to the record number multiplied by the record size - so multiples of 8 in this example.

```
myFile.seek(recordNumber * 8);

```

If `.seek()` returns `false` then you have reached the end of the file.

So to find a tag you can:

```
myFile.seek(0); // Start at the beginning of the file
int recno = 0;
char foundUID[8];
bool found = false;
while (myFile.read(foundUID, 8)) {
    if (strncmp(foundUID, myUID, 8) == 0) { // 8 bytes match
        found = true;
        break;
    }
    recno++;
}

```

At the end of that `found` will be `true` if there is a match, and `recno` will be set to the record number. Now the magic begins...

If it has been found and you want to delete it, think again. That's a very wasteful idea. Instead you just want to "invalidate" it - that is, replace the UID in the database with something the UID can never be - all 0xFF is a good choice. Simply:

```
myFile.seek(recno * 8);
for (int i = 0; i < 8; i++) {
    myFile.write(0xFF);
}

```

Now the tag has gone from the database. You may want to add a filter at the card reading phase to stop anyone using a card that has a UID of all 0xFF, of course.

Now for adding a new card... This is where the fun starts. You could just add 8 bytes to the end of the file, but then the file will grow and grow and grow. Instead, you can first search through the file for a tag entry that is all 0xFF and replace that data with your new UID. Just the same as when you deleted it - seek to 8x the record number and write 8 bytes.

It might help to write a function to wrap the tag seeking routine so you can easily call it multiple times from multiple places. Returning the record number would be most useful - and you could return -1 if it's not found.

If you really want it to be plain text you can do the exact same thing but work with the ASCII representation of the UID bytes instead of the raw values - maybe as HEX. So your 8 byte records would become 18 bytes (16 bytes for 2 ASCII characters per UID byte, plus two for the `\r\n` line ending). Doing the conversion between bytes and text and back to bytes again though is wasteful if you don't really need it.

---

In case you're wondering why I recommended 0xFF as the deleted tag fill value and not 0x00 or anything else, it is simply because when you erase flash memory it is set to 0xFF. When you change the contents of a block on an SD card the block is read, it is modified in memory, the block is then erased (the whole lot set to 0xFF), then the modified block re-written back to the card. The act of erasing the block slightly damages it as it forces electrons through bits they don't really want to go through to make it all 0xFF. By setting your empty records to 0xFF, when it comes time to filling them again, the flash doesn't have to work as hard to erase that block since those bits are already in the erased state. Therefore the lifetime of the flash card should be extended slightly.
> 3 votes

---
Tags: arduino-uno, sd-card, rfid
---


# Question
Title: Receiving live astronomical coordinates on Arduino Mega using telnet and ESP8266 wifi module
I'd like to receive on my arduino live coordinates of planets of solar system. Because there are already websites listing every planet coordinates, I thought it would be easier to just use a wifi module (in my case an ESP8266) and connect the arduino to one of these website.

I have the option of getting it from this website, but I have no idea how to do that.

The other way of doing it may be to connect to Horizon via their telnet server at this adress :telnet://horizons.jpl.nasa.gov:6775

Though I know how establish a connection with this server on my computer using Putty, I have no idea how to connect my arduino to it, execute commands, and, more importantly, get data (RA and DEC) of every solar system main objects.

This is my first time using Arduino wifi module, so I have no experience with it, and I don't know what it is capable of.

Thanks a lot for your attention,

Thomas

# Answer
> 0 votes
That telnet interface is an interactive service. Getting an Arduino to interact with it is not an easy task - certainly not a task for a beginner with no experience of network programming.

A much easier task is to *scrape* the website since that just returns text which you then need to search through a bit at a time looking for the information you need.

---
Tags: arduino-mega, wifi, communication
---


title: interrupting an interrupt

text:
# Question
Title: interrupting an interrupt
What should be expected if the code in the timer interrupt ISR does not finish before the interrupt is called again? For example Timer0 ISR(TIMER0\_COMPA\_vect){} on the Uno. This is for debugging purposes in a complex program. Thanks.

# Answer
> 7 votes
1. the timer will set the Timer Interrupt Flag (TIFR0 register)
2. The ISR will be called, and the flag will be cleared
3. you do some long calculations or something
4. the timer will match OCR0A, and set the interrupt flag again.
5. you calculations are done, and the ISR function will end.
6. the uC will jump back to the main loop code, and execute 2 1 instructions.
7. The uC will see the flag, and call the ISR again. As per step 2.

PS please note that by default the ISR macro will turn off global interrupt (cli) at the beginning of the function, and set it back at the end. You can re-enable interrupts inside the ISR, but you have to be very careful here, as interrupts can be nested, and cause stack-overflows.

You can re-enable interrupts inside the ISR, but that only means other interrupt may interrupt this ISR, but never the same vector. (i.e. only one ISR per vector can run at the same time). So in your case the timer ISR can't be interrupted by the same timer interrupt.

# Answer
> 2 votes
It won't be called until the current interrupt is finished. As soon as the current interrupt function returns the pending interrupt would trigger and call the ISR again.

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


title: Strange adding behaviour

text:
# Question
Title: Strange adding behaviour
I have an Arduino Nano and was adding up some values `2^i from 0..7`:

```
void setup() {
  Serial.begin(9600);
  int i,k;
  k = 0;
  for (i=0;i<8;i++){
     k += pow(2, i);
     Serial.println(k);
  }
}

```

Those numbers should sum up to `255`, but that's the output:

```
1
3
6
13
28
59
122
249

```

Is my Arduino not working or what can be the reason for this behaviour?

# Answer
No, there is nothing "wrong" there. In fact it's the expected results.

The problem here is that `pow()` returns a float, and some numbers just can't be represented with floating point. When that floating point value is converted to an integer it truncates the decimal portion leaving you with the wrong integer value.

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

    int t = 0;
    for (int i = 0; i < 8; i++) {
        float f = pow(2, i);
        int d = f;
        t += f;
        Serial.print("2^");
        Serial.print(i);
        Serial.print(": float = ");
        Serial.print(f, 10);
        Serial.print(" int = ");
        Serial.print(d);
        Serial.print(" total = ");
        Serial.println(t);
    }
}

void loop() {
}

2^0: float = 1.0000000000 int = 1 total = 1
2^1: float = 2.0000000000 int = 2 total = 3
2^2: float = 3.9999995231 int = 3 total = 6
2^3: float = 7.9999980926 int = 7 total = 13
2^4: float = 15.9999961853 int = 15 total = 28
2^5: float = 31.9999885559 int = 31 total = 59
2^6: float = 63.9999771118 int = 63 total = 122
2^7: float = 127.9999542236 int = 127 total = 249

```

Instead you should use bit-shifting to perform the same operation on an integer:

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

    int t = 0;
    for (int i = 0; i < 8; i++) {
        int d = 1 << i;
        t += d;
        Serial.print("1<<");
        Serial.print(i);
        Serial.print(": int = ");
        Serial.print(d);
        Serial.print(" total = ");
        Serial.println(t);
    }
}

void loop() {
}

1<<0: int = 1 total = 1
1<<1: int = 2 total = 3
1<<2: int = 4 total = 7
1<<3: int = 8 total = 15
1<<4: int = 16 total = 31
1<<5: int = 32 total = 63
1<<6: int = 64 total = 127
1<<7: int = 128 total = 255

```
> 3 votes

# Answer
Granted that integer arithmetic is a computationally better approach to this problem; if your intent was to learn to use floating point and float to int conversions, then you need to round up the floating result before the conversion truncates it. As you saw in @Majenko's example, the floating results are close but not quite exact. In your own example, you'd change

```
k += pow(2, i);

```

to

```
p = pow(2, i); k += (p < 0. ? -0.5 : 0.5);

```

to so the float would truncate to the nearest int instead to the next lower int.
> 0 votes

---
Tags: c++
---


# Question
Title: Why is one LED more luminous (brighter) than the other?
Given that there is a circuit with two pins (12 and 10) from an Uno providing power to LEDs on two separate branches, why is the yellow LED dimmer than the green LED? (Please see below image.) To my understanding, the branches attach to GND in parallel, so the LEDs should be equally bright.

If it helps, the two branches are programmed so one LED is off when the other is on and vice versa, with a 1s interval between changing pin state. This isn't a PWM thing as using pin 8 instead of 10 makes no difference.

# Answer
Just like men, all LEDs have been made different.

Practically, that means two different LEDs (one green and one yellow for instance) will have different brightnesses (more precisely, **luminous intensities**) when they are traversed by the same current (**forward current**).

LED luminous intensity is a function of the current that traverses it (among other factors).

If you want the same brightness for those 2 LEDs, then you'll have to:

1. Get both LEDs datasheets (should be a couple of A4 pages for each)
2. Find the luminous intensity/forward current function curve in each
3. Determine which brightness you want for both
4. Deduce the current for each
5. Calculate the resistor value to get that current for each

Then you will have to use two different resistors values in your wiring, based on calculations of step 5.

**Simpler,** you could just replace one of your 2 resistors with one small pot that you can use to tune brightness of the second LED until it fits brightness of the first one.

**Be careful with pot manipulation though,** as a 0 resistance would probably grill your LED (and potentially the Arduino pin it is wired to).
> 1 votes

---
Tags: arduino-uno, led, pins, pwm
---


# Question
Title: Switch statements with Bluetooth serial input not working
I am trying to control the brightness of an LED using PWM. I am also trying to make it so that when I click a button on my bluetooth app, I can get it to change the frequency of the PWM pin.

For changing the frequency, I am changing the value of the timers. When I click "30 HZ" on my bluetooth app, I am sending a value of "A", 122 HZ = "B" etc..

I hooked up a oscilloscope and changing the frequency does work.

The problem is that when I click a button, it receives A or B etc.. but it doesn't enter the switch statement every time. It is very laggy. It will also receive inaccurate numbers at times.

I think I need something in differentiating between various serial inputs? (one for choosing frequency and one for the duty cycle of the LEDs)? and also being able to enter the switch statements and then staying in there until another char is received.

Below is my code and I would appreciate any help!

```
const int pwmPin = 11;
const int TurnLightPin = 13;

int ledState = LOW; // ledState used to set the LED
unsigned long previousMillis = 0;  // will store last time LED was updated
const long interval = 500;  // interval at which to blink (milliseconds)
int dutyCycle = 0;

char state =' ';

void setup() {
  // put your setup code here, to run once:
  //Change register values to adjust PWM frequency for PWM Pins 3 and 11:

  //TCCR2B = TCCR2B & B11111000 | B00000100;    // set timer 2 divisor to           64 for PWM frequency of   490.20 Hz (The DEFAULT)
  //TCCR2B = TCCR2B & B11111000 | B00000101;    // set timer 2 divisor to      128 for PWM frequency of   245.10 Hz
  //TCCR2B = TCCR2B & B11111000 | B00000110;    // set timer 2 divisor to   256 for PWM frequency of   122.55 Hz
  //TCCR2B = TCCR2B & B11111000 | B00000111;    // set timer 2 divisor to  1024 for PWM frequency of    30.64 Hz  pinMode(TurnLightPin, OUTPUT);

  pinMode(TurnLightPin, OUTPUT);
  pinMode(pwmPin, OUTPUT);

  Serial.begin(9600); // Default baudrate of bluetooth -- 9600 bits/second
  Serial.println("HC-06 Bluetooth connected!!!");
  Serial.flush();

}

void loop() {

  // check to see if it's time to blink the LED; that is, if the
  // difference between the current time and last time you blinked
  // the LED is bigger than the interval at which you want to
  // blink the LED.
  unsigned long currentMillis = millis();

   if (currentMillis - previousMillis >= interval) {
     // save the last time you blinked the LED
     previousMillis = currentMillis;

     // if the LED is off turn it on and vice-versa:
     if (ledState == LOW) {
       ledState = HIGH;
     } else {
       ledState = LOW;
   }

   // set the LED with the ledState of the variable:
  digitalWrite(TurnLightPin, ledState);
}

 //PWM Stuff:

while(Serial.available()){

   // if (Serial.available() > 0){
  state = Serial.read();
  Serial.print("State received - Before Switch Statement: ");
  Serial.println(state);
  //}

switch (state) {

case 'A':

  TCCR2B = TCCR2B & B11111000 | B00000111;    // set timer 2 divisor to  1024 for PWM frequency of    30.64 Hz

  while(Serial.available() && (Serial.read() != 'B' || Serial.read() != 'C' || Serial.read() != 'D')){

    dutyCycle = Serial.parseInt();
    int pwmValue = (dutyCycle * 2.55 ); // Multiplied by 2.55 b/c sending a  value between 0-100 and max PWM value is 255
  //AnalogWrite takes two arguments: (pin to write to, and value b/w 0-255)
    analogWrite(pwmPin, pwmValue); //Sets the pin to the value received
    Serial.print("A-30 HZ - PWMValue:");
    Serial.println(pwmValue);
    Serial.print("A-30 HZ - State:");
    Serial.println(state);
    }

    state = ' ';
    break;

case 'B':
    TCCR2B = TCCR2B & B11111000 | B00000110;    // set timer 2 divisor to   256 for PWM frequency of   122.55 Hz

    while(Serial.available() && (Serial.read() != 'A' || Serial.read() != 'C' || Serial.read() != 'D')){

    dutyCycle = Serial.parseInt();
    int pwmValue = (dutyCycle * 2.55 ); // Multiplied by 2.55 b/c sending a value between 0-100 and max PWM value is 255
  //AnalogWrite takes two arguments: (pin to write to, and value b/w 0-255)
    analogWrite(pwmPin, pwmValue); //Sets the pin to the value received
    Serial.print("B-122 HZ - PWMValue:");
    Serial.println(pwmValue);
    Serial.print("B-122 HZ - State:");
    Serial.println(state);
  }

  state = ' ';

  break;

case 'C':

   TCCR2B = TCCR2B & B11111000 | B00000101;    // set timer 2 divisor to   128 for PWM frequency of   245.10 Hz

    while(Serial.available() && (Serial.read() != 'A' || Serial.read() != 'B' || Serial.read() != 'D')){

    dutyCycle = Serial.parseInt();
    int pwmValue = (dutyCycle * 2.55 ); // Multiplied by 2.55 b/c sending a value between 0-100 and max PWM value is 255
   //AnalogWrite takes two arguments: (pin to write to, and value b/w 0-255)
    analogWrite(pwmPin, pwmValue); //Sets the pin to the value received
    Serial.print("C-245 HZ - PWMValue:");
    Serial.println(pwmValue);
    Serial.print("C-245 HZ - State:");
    Serial.println(state);
  }

  state = ' ';

  break;

case 'D':

    TCCR2B = TCCR2B & B11111000 | B00000100;    // set timer 2 divisor to    64 for PWM frequency of   490.20 Hz (The DEFAULT)

    while(Serial.available() && (Serial.read() != 'A' || Serial.read() != 'B' || Serial.read() != 'C')){

      dutyCycle = Serial.parseInt();
      int pwmValue = (dutyCycle * 2.55 ); // Multiplied by 2.55 b/c sending a value between 0-100 and max PWM value is 255
    //AnalogWrite takes two arguments: (pin to write to, and value b/w 0-255)
      analogWrite(pwmPin, pwmValue); //Sets the pin to the value received
      Serial.print("D-490 HZ - PWMValue:");
      Serial.println(pwmValue);
      Serial.print("D-490 HZ - State:");
      Serial.println(state);
    }

    state = ' ';

    break;
default:

  TCCR2B = TCCR2B & B11111000 | B00000110;    // set timer 2 divisor to   256 for PWM frequency of   122.55 Hz

  while(Serial.available()){

    dutyCycle = Serial.parseInt();
    int pwmValue = (dutyCycle * 2.55 ); // Multiplied by 2.55 b/c sending a  value between 0-100 and max PWM value is 255
    //AnalogWrite takes two arguments: (pin to write to, and value b/w 0-255)
    analogWrite(pwmPin, pwmValue); //Sets the pin to the value received
    Serial.print("default - PWMValue:");
    Serial.println(pwmValue);
    Serial.print("Default - State:");
    Serial.println(state);
  }

  state = ' ';

  break;
    }//End of Switch Statement
  } // End of While loop for PWM
} // End of void Loop

```

---

# Answer
I don't like your serial parser at all. Lots of whiles, reads, places to get stuck in...

For example mine looks like:

```
void loop() {

  if (Serial.available()) {
    int ch = Serial.peek(); // check first character in buffer

    switch (ch) {
      case 'a' ... 'd':
        TCCR2B &= 0b11111000; // mask out prescaler (turn off timer 2)
        TCCR2B |= 0b111 - (ch - 'a'); // a => 7, b => 6, c => 5, d => 4
        Serial.read(); // remove character from buffer
        Serial.println(TCCR2B, HEX);
        break;

      case 'A' ... 'D':
        TCCR2B &= 0b11111000; // mask out prescaler (turn off timer 2)
        TCCR2B |= 0b111 - (ch - 'A'); // A => 7, B => 6, C => 5, D => 4
        Serial.read(); // remove character from buffer
        Serial.println(TCCR2B, HEX);
        break;

      case '0' ... '9':
        dutyCycle = Serial.parseInt();
        analogWrite(pwmPin, (int)(dutyCycle*2.55));
        Serial.println(dutyCycle);
        break;

      default:
        Serial.read(); // some invalid character? Drop it
        break;
    }
  }
}

```

However it needs some extra character after number (needed by parseInt)
> 1 votes

# Answer
i had major issues with ws2812 and the hm-10, and i couldn't get a great solution for it, and although your setup is different, it may help…

my solution was to stop things that were interrupting the interrupt, in this case, the leds, so to create;

```
void dataLow () {
  // drop the power on the data pins for the leds
  digitalWrite(DATA_PINA, LOW);
  digitalWrite(DATA_PINB, LOW);
  Serial.println("DATA_PINS - LOW");
}

void dataHigh () {
  // turn the power back on for the leds
  digitalWrite(DATA_PINA, HIGH);
  digitalWrite(DATA_PINB, HIGH);
  Serial.println("DATA_PINS - HIGH");
}

```

and then to clean the data. i was looking for 2 numerical characters, and if i got anything else, then dump the data.

```
bluetooth.listen();
while (bluetooth.available() > 0) {
    dataLow();
    char inChar = bluetooth.read();
      // if its a character, add it to the string
      if (isDigit(inChar)) {
        inString += (char)inChar;
      }
      // if the string is longer than 2, truncate and return nothing
      if(inString.length() > 2) {
        inString[2] = '\0';
      }
      // if the serial recieves bluetooth end of line /n print string data out
      if (inChar == '\n') {
        Serial.print("String: "); Serial.println(inString.toInt());
        program=inString.toInt();
        inString = "";
        dataHigh();
      }
      // read user input from serial monitor
      if (Serial.available()){
        delay(10); // The DELAY!
        bluetooth.write(Serial.read());
      }
  }

```

it was still twitchy, but it mostly works.
> 0 votes

---
Tags: led, bluetooth, pwm, switch
---


title: Arduino Uno VIN 2A

text:
# Question
Title: Arduino Uno VIN 2A
Trying to get started with the Arduino, so I'm trying to do something kinda simple. I'm following this tutorial: Build Your Own Dynamic Ambient Lighting For A Media Center

However, I'm still confused about one, most likely simple and self-explainatory, thing: Take a look at this image \- is that DC connector on the bottom left the one that's one my Arduino? Do I simply have to connect the 12V wire from the RGB LED stripe to Vin?

After using google for a bit, I read this: `the diode and trace width are other limiting factors. The diode is rated at 1 amp and the board traces can't handle much above 2 amp.`
Does that mean I can only use 1A because of the diode? If so, why does it matter how much the board traces can handle?

I'm trying to power a 12V 2A RGB LED stripe.

I'd appreciate your help and I hope this is the correct subreddit to ask that. :S

# Answer
No, that connector is a completely separate one.

You can connect a power supply to the on-board power socket of the Arduino and take power out from the VIN pin to power other things. However the *total current* that is used by both the Arduino *and* whatever you power from it *cannot* exceed 1A.

So to have more than 1A available you have to have the power connected externally to the Arduino. That doesn't mean that the Arduino can't share that power, just that the Arduino can't *provide* that power.

You can connect the +12V of the LED strip to VIN on the Arduino as long as the 12V power supply is connected to the LED strip not to the Arduino - that way the power for the Arduino comes *from* your external circuit.
> 2 votes

# Answer
It will be dangerous to take 12V from VIN pin. Please have a look at following picture. That is the diode you mentioned. the diode can burn out if the current get exceeded.

there are three ways to solve this.

1. Use two different supplies. Use a 6V battery(or 5V USB power) to power arduino and 12v supply for LED strip. You should connect both grounds( grounds of supplies)

2. Solder a wire from bottom(from the point shown in picture) of arduino board for 12v
    3. connect 12v power directly to VIN (not by using power jack)
> 0 votes

---
Tags: power, current
---


title: connecting two keypad with arduino

text:
# Question
Title: connecting two keypad with arduino
I am pretty new to arduino.I am working on a project which requires comparison of two keypad inputs to operate a relay using arduino. I have found lot of info on connecting single keypad but none about connecting two keypad inputs.So how can i connect two keypad and a relay to arduino?Thanx in advance.

# Answer
> 2 votes
It should be no problems as long as you can get enough digital inputs into the Arduino. Search for the library KeyPad, it lets you define the pins that control each row and column and so you could use 2 2\*2 keypads quite easily.

I think Keypad is very easy to use, but if you get stuck, just show what code you have so far and describe the problem and people will help you.

---
Tags: arduino-uno, relay
---


title: Arduino which library for led 4x20

text:
# Question
Title: Arduino which library for led 4x20
I am having an Arduino Uno and I want to add a LCD to it. My LCD is a C2042A with I2C shield on it. I tried the LiquidCrystal\_I2C library but it doesnt work. I am not getting any errors the LCD is just not showing the text. I just used the example code 'Hello World' from the library. I only changed the adress from 0x27 to 0x63 because I found that with the I2C scanner.

So all in all the LCD is connected right. It shows I2C mode which is also fine and it is find by the I2C Scanner code. Which library do I have to use that it will work? http://www.wentztech.com/filevault/Electronics/Arduino/

# Answer
> 1 votes
0x63 is the correct address - the module is at 0xC6 which is the 8-bit equivalent of 0x63 (0x63 shifted left once for the read/write bit to be added).

The LCD03 uses its own custom I2C protocol, not compatible with the "normal" I2C LCD library. Instead you have to use their own special commands.

The commands are detailed here: http://www.robot-electronics.co.uk/htm/Lcd03tech.htm

There may be a library available that wraps those commands, I don't know, but you can just use the Wire library to send the commands you need to send.

---
Tags: arduino-uno, i2c, lcd
---


# Question
Title: How to power Arduino and shields with 4 rechargeable AA batteries?
To start, I am a software guy, and I really want to ensure I not going to destroy any components. I previously looked at power through a USB power bank, but the issue with these is that they turn themselves off with low current pull.

My question is: I have a number of Arduino shields and would like to power them with 4 rechargeable AA batteries, and therefore would like some advice on what to use without frying any electronics.

The rechargeable batteries I have are these 1.2V AA (NiMH). Going on their rated value they should supply 4.8V. Testing the 4 batteries in serial gives me 5.3V overall, or around 1.325V per battery at full charge.

So if the batteries provide more than 5V, I cannot safely plug them into the 5V pin on the Arduino. But if the batteries could potentially provide around 4.8V to 5.5V plugging them into VIN means that the voltage regulator will take too much power, reducing the overall voltage to be too low for all of the shields (Which require 5V). What should I do in this situation?

This is a list of the current equipment that will require power:

The shields will be stacked on top of each other.

# Answer
Most 5V devices will function fine at up to 5.5V - however, check the datasheets for the major components and modules on the boards.

The main thing to watch though is that a 3.3V device, which can normally communicate fine with a 5V one, may not be able to. The problem is that the logic HIGH signal from the 3.3V device may be below the threshold for a logic HIGH on the Arduino:

```
V_IH = 0.6Vcc = 0.6 x 5 = 3V

V_IH = 0.6Vcc = 0.6 x 5.5 = 3.3V

```

Thus a 3.3V device would have to output at the very minimum 3.3V as a logic HIGH in order for it to register as one on the Arduino, which may be a problem...

You can easily drop the battery voltage by 0.7V though by inserting a single silicon diode (such as the trusty 1N4001) in series with the batteries. That will take your voltage down from your measured 5.3V down to 4.6V which will improve matters somewhat.

However, it is important to note that you have so far measured the *open circuit* voltage of the batteries. That is, the voltage with no load on them. The voltage will most likely be lower once they are actively driving the Arduino etc.

The Arduino itself will be fine running off 5.3V, so I suggest you power just the Arduino direct into the 5V pin from the batteries and measure the actual voltage while powering the Arduino. That will give you a more accurate voltage reading. Then, if needed, you can add the diode to drop it by 0.7V.
> 1 votes

---
Tags: power, shields, battery
---


# Question
Title: Turning a DC motor a set number of Rotations using an encoder
I'm using an arduino UNO, and i want to turn a motor a set number of revolutions, i'm trying to read the clicks of the encoder which has a resolution of 360 clicks/ revolution, my logic is that i count the number of clicks until i get to the desired number which represents the the number of revolutions * the resolution of the encoder:

1 revolution ==\> 360 clicks
5 revolutions ==\> 360\*5 (desired number)

i'm a beginner with arduino so here is my code:

```
volatile int counter=0;
int motor=5;  // motor is connected to pin 5

void setup(){
  pinMode(motor,OUTPUT);
  attachInterrupt(0, count,RISING); // attaching encoder on interrupt 0
}

void loop(){
  while(counter< 360*5){
    analogWrite(motor,255);
  }
}

void count(){
  counter++;
}

```

This code is not working at all, how can i fix it?

# Answer
You never tell the motor to stop.

```
void loop(){
   while(counter< 360*5){
     analogWrite(motor,255);
   }
   analogWrite(motor, 0); //add something like this or whatever could stop it
   //you may want to disable the counter now too
}

```

However, even with that change you are likely a long way from having a working, or at least reliable system - see other issues in my comment on the question.
> 2 votes

# Answer
Since the Encoder resolution is high, the Arduino Uno misses some pulses hence you could not get the accurate reading from it. You could use the hardware quadrature decoder in Arduine Due board which can easily read the encoder values.

Here is a code which can only be executed in arduino Due to Read one quadrature encoder. How to configure 2nd Quadrature Decoder IO pins in Arduino IDE
> 0 votes

---
Tags: arduino-uno, rotary-encoder
---


# Question
Title: How to interface an arduino to load sensor with darlington transistor?
I have a load sensor for measuring weights , it has for wires labelled E+,E-,S+,S-. I assume S means sensor and E means excitation and the power is sent into E+ and E-. The output of any load sensor would be the order of typically millivolts if it takes a load (depending on the weight of the load of course) so I guess amplifying it with a darlington would make its output useful for an interface to an arduino. What would be a generic circuit using a darlington transistor (e.g. a TIP 120) that can make the load sensor output useful for building an interface to an arduino with the minimal number of components? Ans this circuit is to be as simple as possible. Im trying to build a circuit with the components I have which does include a tip 120 and I have a lot of other common components.

# Answer
What you have there is (or sounds like) a full wheatstone bridge.

You require either a special amplifier (such as the HX711) or a highly sensitive and accurate differential ADC (such as the MCP3428 \- (on a shield)).
> 0 votes

---
Tags: arduino-nano
---


# Question
Title: How to configure 2nd Quadrature Decoder IO pins in Arduino IDE
I am working to read two quadrature encoders using a single Arduino DUE, as part of my summer vacations project. According to the following link http://atmel.force.com/support/servlet/fileField?id=0BEG0000000HRvP, the SAM3X8E has 2 quadrature decoders in it. Now I am not being able to understand how can I initialize this second quadrature decoder. According to **Quadrature Decoder QDEC for SAM3/4 Devices\_ApplicationNote\_AT11483** *Pg16* we have to first configure the IOPINS for QDEC1. I have to do that same task in Arduino IDE instead of Atmel Studio.

This is the code that I have found and works well to read encoder using QDEC0. However, I now need to read the encoder using the second quadrature decoder, whose input pins are TIOA6 , TIOB6 which correspond to Pin 5 and 4 of Arduino DUE. After reading the Atmel SAM3X datasheet, I think I should change "TC0" with "TC2" to make the second decoder work. However, this doesn't work. I think it does not work because channel 2 is busy in time base calculations. In Application Note *5.52* **QDEC Speed Measurement Mode** point 2 says to Initialize TC0, TC1, TC2. If I wanted to used other encoder which timer instance will be used.

```
/*
** Quadrature Encoder on Arduino Due in "Speed Mode"
** Will not work on other Arduino types because of a specific hardware requirement.
**
** @bungle99 / 2014-02-28
**
** Many thanks to @Designservicecorp (notably post #32 and post #42) that gave me the base to work from.
**
** Uses *hardware* to do the heavy lifting of interpreting the Encoder output, which gives it significant
** advantage over other Arduino's for this use case. Eg many people have reported their Unos maxing out
** or skipping counts when interpretting high RPMs, whereas people using the Due in hardware mode have
** reported better success with high RPMs.
**
** This particular example puts the hardware into "Speed" mode, whereas other examples in this thread use
** "Position" mode (see posts 32, 42). The one example in the thread that attempts Speed calcs uses Position
** Mode and uses an interrupt on the Z Index axis to manually apply a time period (needed to caculate speed)
** on each rotation.
**
** This code below has been used in tests (using Lego NXT and a gear train for driving / comparison) to
** ~3,500 RPM with a 1,024 PPR Encoder (4 x 1,024 Edges). The Arduino didn't seem to struggle and the
** numbers (eg RPM) matched fairly closely with the Lego (eg as a sanity check, the calcs in the code look
** correct).
**
** I bought one of these encoders, which seems ok;
**
**   * http://proto-pic.co.uk/rotary-encoder-1024-p-r-quadrature/
**
** Great service from proto-pic. The encoder specs are officially
**
**   * http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Robotics/E6B2Encoders.pdf
**
** But look an awful lot like this one too (which is easier to read)
**
**   * http://www.ia.omron.com/product/item/e6b27032r/index.html
**
** Note that this Encoder is rated at 5V min. I've successully powered it off the 5V Arduino pin header,
** and it doesn't work off the 3.3V one. At 5V, the outputs need to be run through some resistors to bring
** them into tolerance of the Arduino inputs.
**
** The inputs are 2 and 13 (and optionally A6 for the index).
**
** The test hardware (some Lego NXT servos and gear train) was unable to turn any faster (more gears
** stalled the servos) - eg the Arduino Due was not the limiting factor. At this speed, the Due Hardware
** is dealing with approx 238,000 edges per second.
**
** This example offloads the speed calculation onto the hardware, meaning no interrupt is required.
** In addition, the index is not required either, so it allows speeds to be seen even for rotations that
** don't pass the index marker (for example, slow rotations needing a speed before a complete rotation).
** That said, index is available if you want it and the docs suggest you can still use it (and others) as
** interrupt if you wish.
**
** NB There appears to be a myriad of features on the Chip that have not been touched. Eg you can still add
** interrupts to this code to do other things; eg passing the Z index, direction changes. There are also
** filters available if your encoder suffers from noise (eg vibrations). All this is available to play with
** another day :)
**
** Code appears to work, but no guarantees. Understand it. Test it. Feedback to the group. YMMV. Don't blame
** me if it doesn't work or expolodes!
*/

const int ENCODER_EDGES_PER_ROTATION = 3200;  // this depends on your encoder
const int ENCODER_SAMPLES_PER_SECOND = 10;        // this will need to be tuned depending on your use case...
const int LOOP_DELAY_MS = 1 * 1000;               // ... as will this (see comments in main code)

void setup() {

  Serial.begin(115200);
  delay(10);

  // Setup Quadrature Encoder
  // http://www.atmel.com/Images/doc11057.pdf
  // Section 37 p869
  // Section 37.6.14 p885
  // Section 37.6.14.2 p890 Position and Rotation Measurement
  // Section 37.6.14.5 p891 Speed Measurement (what this is about)

  REG_PMC_PCER0 = PMC_PCER0_PID27
                | PMC_PCER0_PID28
                | PMC_PCER0_PID29;

  // Setup a channel in waveform mode (eg an input into the encoder to trigger the time based sampling)
  // Note some of the choices here impact calculations below and if you change them, you need to change
  // the next section to suit.
  // Section 37.7.11 p906 (also refer to Section 37.6.14.5 p891 for detail of what to set)
  REG_TC0_CMR2 = TC_CMR_TCCLKS_TIMER_CLOCK4
               | TC_CMR_WAVE
               | TC_CMR_ACPC_TOGGLE
               | TC_CMR_WAVSEL_UP_RC;

  // Now define the sample period, using the clock chosen above as the basis
  // Note that REG_TC0_CMR2 above is using CLOCK4; this is an 128 divisor. You need to change the
  // divisor below if you change the clock above. You could change the input clock and the RC mode to
  // suit your app (eg how many pulses are you  expecting - depends on encoder type
  // and slowest/normal/fastest rotation speed and what you want to do with the result).
  // Section 37.6.14.5 p891 notes you need to set this up, otherwise 0 comes out all the time :-)
  REG_TC0_RC2 = F_CPU / 128 / ENCODER_SAMPLES_PER_SECOND;

  // Setup a channel in capture mode
  // Section 37.7.10 p904 (also refer to Section 37.6.14.5 p891 for detail of what to set)
  REG_TC0_CMR0 = TC_CMR_ABETRG
               | TC_CMR_LDRA_EDGE
               | TC_CMR_LDRB_EDGE
               | TC_CMR_ETRGEDG_EDGE
               | TC_CMR_CPCTRG;

  // Enable features, noting Speed not Position is chosen
  // Section 37.7.2 p895 (also refer to Section 37.6.14.5 p891 for detail of what to set)

// 37.7.2 TC Block Mode Register
  REG_TC0_BMR = TC_BMR_QDEN
              | TC_BMR_SPEEDEN
              | TC_BMR_EDGPHA; //Pg 896

/*EDGPHA: EDGe on PHA count mode
0: edges are detected on both PHA and PHB.
1: edges are detected on PHA only.*/

  // Set everything going
  REG_TC0_CCR0 = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC0_CCR1 = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC0_CCR2 = TC_CCR_CLKEN | TC_CCR_SWTRG;
}

void loop() {

  int iIndexCount = REG_TC0_CV1;  // Don't need this, but manual notes its available
  int iSpeedPPP = REG_TC0_RA0;    // This is what we're really after (speed in Pulses Per sample Period)

  // which we can convert to rps or rpm easily
  double dSpeedRPS = ((iSpeedPPP / (ENCODER_EDGES_PER_ROTATION * 1.0)) * ENCODER_SAMPLES_PER_SECOND);
  double dSpeedRPM =  dSpeedRPS * 60;

  Serial.print("Speed ppp: ");
  Serial.print(iSpeedPPP);
  Serial.print(", ");
  Serial.print("Speed rps: ");
  Serial.print(dSpeedRPS);
  Serial.print(", ");
  Serial.print("Speed rpm: ");
  Serial.print(dSpeedRPM);
  Serial.print(", ");
  Serial.print("Indexes: ");
  Serial.print(iIndexCount);
  Serial.print(". ");
  Serial.println();

  // Slow down the main loop noting the Encoder can update independently in the background (we're
  // effectively polling it to find out the latest and greatest info on each loop around).
  delay(LOOP_DELAY_MS);
}

```

Additionally I wanted to ask what is the difference between REG\_TC0\_CMR2 REG\_TC0\_CMR0 and REG\_TC0\_CMR1 ? Two of them are used in the above code.

Motor with Encoder I am using is:

# Answer
TC blocks are pretty much identical (except TC1 doesn't have wired some signals to pins)

So you have to copy registers containing `*_TC0_* =` and replace TC0 to TC2.

Plus PC25 and PC24 should be set to its alternate function PIO\_PERIPH\_B. Something like this:

```
  PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC25B_TIOA6, PIO_DEFAULT);
  PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC26B_TIOB6, PIO_DEFAULT);

```

Also TC6, TC7 and TC8 clocks must be enabled by:

```
REG_PMC_PCER1 = PMC_PCER1_PID33 | PMC_PCER1_PID34 | PMC_PCER1_PID35;

```

And TC\_CMR0..2 are Channel Mode Registers for one of three timers/counters in one TC block. Again, these are the same, but WAVE mode dependent.

Full configuration:

```
  REG_PMC_PCER0 = PMC_PCER0_PID27 | PMC_PCER0_PID28 | PMC_PCER0_PID29;
  REG_PMC_PCER1 = PMC_PCER1_PID33 | PMC_PCER1_PID34 | PMC_PCER1_PID35;

  PIO_Configure(PIOB, PIO_PERIPH_B, PIO_PB25B_TIOA0, PIO_DEFAULT); // arduino pin 2
  PIO_Configure(PIOB, PIO_PERIPH_B, PIO_PB27B_TIOB0, PIO_DEFAULT); // arduino pin 13

  REG_TC0_CMR2  = TC_CMR_TCCLKS_TIMER_CLOCK4 | TC_CMR_WAVE | TC_CMR_ACPC_TOGGLE | TC_CMR_WAVSEL_UP_RC;
  REG_TC0_RC2   = F_CPU / 128 / 1;
  REG_TC0_CMR0  = TC_CMR_ABETRG | TC_CMR_LDRA_EDGE | TC_CMR_LDRB_EDGE | TC_CMR_ETRGEDG_EDGE | TC_CMR_CPCTRG;
  REG_TC0_BMR   = TC_BMR_QDEN | TC_BMR_SPEEDEN /*| TC_BMR_EDGPHA*/;
  REG_TC0_CCR0  = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC0_CCR1  = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC0_CCR2  = TC_CCR_CLKEN | TC_CCR_SWTRG;

  PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC25B_TIOA6, PIO_DEFAULT); // arduino pin 5
  PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC26B_TIOB6, PIO_DEFAULT); // arduino pin 4

  REG_TC2_CMR2  = TC_CMR_TCCLKS_TIMER_CLOCK4 | TC_CMR_WAVE | TC_CMR_ACPC_TOGGLE | TC_CMR_WAVSEL_UP_RC;
  REG_TC2_RC2   = F_CPU / 128 / 10;
  REG_TC2_CMR0  = TC_CMR_ABETRG | TC_CMR_LDRA_EDGE | TC_CMR_LDRB_EDGE | TC_CMR_ETRGEDG_EDGE | TC_CMR_CPCTRG;
  REG_TC2_BMR   = TC_BMR_QDEN | TC_BMR_POSEN /*| TC_BMR_EDGPHA*/;
  REG_TC2_CCR0  = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC2_CCR1  = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC2_CCR2  = TC_CCR_CLKEN | TC_CCR_SWTRG;

```
> 1 votes

---
Tags: arduino-ide, arduino-due, atmel-studio, rotary-encoder, assembly
---


# Question
Title: How do I find names of components I don't know?
I recently started with Arduino and I have my starter kit. However, there are some strange looking components I can't recognize. Is there some way to find out the names of these components?

# Answer
The Arduino webpage has a section about their Starter Kits, including pictures (and technical specs if you scroll down the page). Particularly, if you go to the Arduino store, there is a sub-menu for components - for example, for actuators (there are more categories to the left of the image).

There is a blog by Aaron Eiche, Arduino Starter Rundown, that if you scroll down, there is a chart that labels the main components.

There are several websites that have pages that identify components by image - an example is the uCHobby webpage Identifying Electronic Components, with pictorial menus of the main types of components.

In Google images, searching "arduino starter kit components" yields a considerable amount of labelled component charts.
> 3 votes

# Answer
A slightly more general answer to this question would be to browse the catalogue of a component supplier. Printed catalogues seem to be becoming rarer (Maplin used to sell a catalogue, but it seems to be discontinued this year), but RS and Farnell still seem to have printed ones.

I'm not suggesting you find specific components by searching the catalogue, but skimming through a catalogue will give you an idea about some of the components that do exist, and will help you to narrow things down a little.
> 1 votes

---
Tags: components
---


title: How to convert bool array to byte?

text:
# Question
Title: How to convert bool array to byte?
I have following problem: I'm reading 8 bit signal from one Arduino pin and store all informatin in bool array. Now I want to convert this array to single byte in decimal. How to do this?

I've tried this:

```
bool ID[8] = {0, 0, 0, 0, 0, 0, 1, 1};
int recivedID = int(ID);

```

and

```
bool ID[8] = {0, 0, 0, 0, 0, 0, 1, 1};
int recivedID = ID.toInt();

```

non works.

# Answer
> 0 votes
try with this:

```
int recivedID = ID[0] | (ID[1] << 1) | (ID[2] << 2) | (ID[3] << 3) | (ID[4] << 4) | (ID[5] << 5) | (ID[6] << 6) | (ID[7] << 7);

```

which is the same as

```
int recivedID = 0;
for(int i=0; i<8; i++){
   recivedID |= ID[i] << i;
}

```

I haven't tested it though.

# Answer
> 1 votes
```
byte BoolArrayToByte(bool boolArray[8])
{
  byte result = 0;

  for(int i = 0; i < 8; i++)
  {
    if(boolArray[i])
    {
      result = result | (1 << i);
    }
  }

  return result;
}

```

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


title: Start to build a robot

text:
# Question
Title: Start to build a robot
I would like to start with a very simple robot, which should be based on an arduino uno. I already have an uno and made the decision fpr my robot chassie: https://www.roboter-bausatz.de/en/diy-electronics/kits/robotic-kits/97/2wd-motor-smart-car-chassis-fuer-roboter-mit-getriebemotor-und-batteriebox

Additionally I want to by an ultrasonic distance sensor and a infrared sensor. What else do I need to start ? Only a DC motor driver or anything else?

Thanks in advance LStrike

# Answer
You'll need:

* Emergency switch (it should be easy to cut the power off, even for small robots)
* A chassis (you've found one already)
* Motors (Obviously)
* Motor control (Probably a dual H-bridge, think if you need reverse or not.)
* Power (powering on (single use) batteries may not be your best option)
* Controller (Arduino Uno, or something smaller or faster)
* Sensors (Can be anything, depending on the requirements)

A way to communicate with the robot is also nice, often wireless (bluetooth/wifi/443mhz).

And also, it will be nice if the robot fits some kind of purpose, but this could be added later. You could think of the robot having to pick up and carry something, extinguish a flame etc.

I advise to check out one of the many tutorials on building a robot, they often have a detailed parts list (sometimes even shopping links).
> 0 votes

---
Tags: arduino-uno, motor, robotics
---


title: Compilation Error

text:
# Question
Title: Compilation Error
Hi everyone I seem to have run into a problem while uploading a library to the board. I managed to import the library to Arduino Uno, however, i could not upload it

Please Help :)

Thanks in Advance

This is the error i received:

```
Arduino: 1.6.11 Hourly Build 2016/08/05 02:12 (Mac OS X), Board: "Arduino/Genuino Uno"

In file included from /Users/pendukenipandeni/Documents/Arduino/SimpleTimer/SimpleTimer.ino:1:0:
/Users/pendukenipandeni/Documents/Arduino/libraries/SimpleTimer-master/SimpleTimer.h:37:22: fatal error: functional: No such file or directory
 #include <functional>
                      ^
compilation terminated.
exit status 1
Error compiling for board Arduino/Genuino Uno.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

# Answer
I managed to fix this by simply downloading and uploading a different SimpleTimer Library from https://github.com/jfturcot/SimpleTimer
> 2 votes

---
Tags: arduino-uno, compile
---


title: Serial characters are corrupted

text:
# Question
Title: Serial characters are corrupted
I try to send an "a" string via serial with

```
Serial.println("a");

```

and I receive "Oy=" in Ascii or {4F}{79}{3D} in Hexa.

Where should I start investigating? What could be wrong? Baudrate is 9600 on all sides.

PS: I suspect the cable. Any hints how to check it?

# Answer
> 1 votes
On your setup function

```
Serial.begin(115200);//<- 115200 is the baud rate, serial monitor must match this speed
while(!Serial);//<-- wait for Serial to be ready

```

see: https://electronics.stackexchange.com/questions/9264/what-standard-uart-rates-are-there for more baud rates

---
Tags: serial, arduino-mega
---


# Question
Title: How is IF( object ) evaluated? Follows from SD card example sketch
The "DumpFile.ino" example sketch from the SD library tries to open a file off an SD card, read its contents, and write them to the Serial Monitor. I am confused in how the following `if()` statement is evaluated:

```
File dataFile = SD.open("datalog.txt");

if (dataFile) {
// read and print, then close
}
else {
// print error message
}

```

There must be some implicit conversion on `dataFile` which depends on whether or not `SD.open("myFile.txt")` was successful. I would like to understand how this implicit conversion occurs. Which property of the `File` object determines if the `if()` statement evaulates `true` or `false`?

# Answer
> 1 votes
There is an operator bool which does the test:

```
File::operator bool() {
  if (_file)
    return  _file->isOpen();
  return false;
}

```

When used inside an `if` the compiler invokes the `operator bool()` which does the test you see above.

---
Tags: c++, sd-card
---