# Question
Title: Vcc measurement with internal 1.1V reference fails on 3.3V powered Atmega328
I need to monitor a battery plugged to an ATmega running on standalone mode.

I use the "ATmega on a breadboard (8 MHz internal clock)" bootloader. More info here

When the ATmega is powered with 5V the sketch outputs good values : arround 5100 mV.

But when I power it with 3.3V the sketch gives strange values : arround 178619 mV.

Here is my code Inspired from here

```
void setup()
{
  Serial.begin(9600);
  Serial.println(F("Internal Voltage Sensor"));
}

void loop()
{
  Serial.println( readVcc());
  delay(1000);
}

long readVcc()
{
  long voltage=0;
  uint8_t wADC;

  // Read 1.1V reference against AVcc
  // set the reference to Vcc and the measurement to the internal 1.1V reference
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  ADCSRA |= _BV(ADEN);  // enable the ADC

  delay(20); // Wait for Vref to settle

  ADCSRA |= _BV(ADSC); // Start conversion
  while (bit_is_set(ADCSRA,ADSC)); // measuring

  // Reading register "ADCW" takes care of how to read ADCL first and ADCH then.
  wADC = ADCW;

  voltage = 11253000L / wADC; // Calculate Vcc (in mV); 1125.3 = 1.1*1023*1000
  return voltage; // Vcc in millivolts
}

```

I don't understand what's going on. The returned value with Vcc=3.3V should be lower than with VCC=5V. Something like 3300 mV !

# Answer
Thanks for your answers! Jot gave the solution: wADC must be a uint16\_t.

Here is the corrected code :

```
void setup()
{
  Serial.begin(9600);
  Serial.println(F("Internal Voltage Sensor"));
}

void loop()
{
  Serial.println(readVcc());
  delay(1000);
}

long readVcc()
{
  long voltage=0;
  uint16_t wADC;

  // Read 1.1V reference against AVcc
  // set the reference to Vcc and the measurement to the internal 1.1V reference
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  ADCSRA |= _BV(ADEN);  // enable the ADC

  delay(20); // Wait for Vref to settle

  ADCSRA |= _BV(ADSC); // Start conversion
  while (bit_is_set(ADCSRA,ADSC)); // measuring

  // Reading register "ADCW" takes care of how to read ADCL first and ADCH then.
  wADC = ADCW;

  voltage = 1125300L / wADC; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000
  return voltage; // Vcc in millivolts
}

```
> 2 votes

---
Tags: arduino-ide, atmega328, battery, analogreference
---


title: Ethernet shield compatibility

text:
# Question
Title: Ethernet shield compatibility
Does anyone know if there is an Ethernet shield is compatible with the Arduino Ethernet shield (R3)? The R3 does not seem to be in production anymore and I need a replacement shield. Found some from Velleman, or maybe Ethernet Shield 2?

# Answer
No, it is not compatible. It uses the ENC28J60 chip from Microchip, whereas the others all use the W5100 Wiznet chip. A very different chip.

You can use it if you refactor all your code to use the Ethercard library instead of the Ethernet library.

There are cheap Chinese (or other far east) clones of the Ethernet Shields, that use the W5100 (or a counterfeit copy) that people have varying amounts of luck with if you really need W5100 compatibility. I have one, but have had problems with it starting up properly sometimes and needs a bit of a kick with the reset button.
> 1 votes

---
Tags: ethernet-shield
---


# Question
Title: How to create a log file document which is not editable by a word processor on SD card
I'm using a **Arduino Mega 2560** and **SD card shield** to make an industrial logging panel. Is there any way to write log data document in a **read-only type** file like a **pdf** on SD card so that the contents cannot be edited once created by word processing software? The data has to presented as a document on a windows machine.

Thanks in advance for your time – if I’ve missed out anything, over- or under-emphasized a specific point let me know in the comments.

# Answer
> 2 votes
There is no such thing as a file that cannot be edited.

If a file can be read it can be edited.

However, there are ways of making it possible to know if a file has been edited - i.e., to integrity check the file. To make it *hard* to edit a file and maintain the intrinsic integrity of the file.

The simplest method is to create a checksum of the data in the file and store that in the file as well. If the data is, for example, a CSV file, you could include in each row a checksum of the data in that row as an extra column. If the data gets changed the checksum will no longer match. Of course, that doesn't preclude someone calculating the new checksum and entering that. So maybe adding a checksum of all the checksums at the end of the file as well so you know if any checksums have changed.

Again, it's possible for someone to recalculate that checksum as well.

The most secure method is to digitally sign the file (in the way the PGP or GnuPG does). Without the private key, it's impossible to re-sign the file after modification. However, that kind of operation is comparatively heavyweight and not something an Arduino is particularly suited to doing (I'm not sure if it's even physically possible given the lack of resources an Arduino has).

---
Tags: arduino-uno, arduino-mega, programming, sd-card
---


# Question
Title: PROGMEM doesn't cause Sketch size to change
I'm trying to pinpoint some strange behaviour involving the use of PROGMEM and the size of a Sketch.

I've written a library that contains a number of functions, in addition to several large global byte arrays and 32-bit uint arrays. These arrays are stored in PROGMEM using the pgmspace library. The library compiles fine, and all code works properly when uploaded to an Arduino.

I'm performing testing on the functions using a testing sketch that in turn uses my library. In order to test the performance, I've been switching between using PROGMEM and not using PROGMEM in the library (all arrays are under 2KB). When using PROGMEM, it drops the Global Variable dynamic memory count by the expected amount... but the the sketch program size remains either constant, or seems to arbitrarily increase or decrease by a very small amount, depending on the function. For example, a uint8\_t byte\[256\] array, when moved to the PROGMEM, causes the Global Variable size to go down by about 256 bytes... but the sketch size only increases by about 12 bytes.

Each entry in the array is unique and is accessed, so the compiler shouldn't be optimizing it away. I tried just using avr-size directly on the ELF file, but the sketch size was the same. I can't tell if the data is being stored in PROGMEM all the time (even when not declared as PROGMEM, due to some sort of issue with PROGMEM in libraries?), or if PROGMEM data simply isn't being counted as part of the sketch size, or ??? I have tried moving the functions directly out of the library into the sketch, changing data types, adding/removing static and const declarations... but the lack of change in sketch size continues to confuse me. Any help would be greatly appreciated.

# Answer
all constant data are part of the sketch. where else should they be? in runtime they are loaded into RAM. PROGMEM directive prevents the loading into RAM.
> 5 votes

---
Tags: progmem, sketch-size
---


title: Integer looping in EEPROM Read

text:
# Question
Title: Integer looping in EEPROM Read
I am reading data from a 24LC1025 over I2C with an Arduino and then outputing that data to my PC through the Serial interface. The EEPROM chip is seperated into two pages and at address 65535 \[0x0FFFF\] it switches over to the second page sending \[0x10000 through 0x1FFFF\] I had it working by reading each address with a random read:

```
#include <Wire.h>

byte i2c_eeprom_read_byte( int deviceaddress, unsigned long eeaddress ) {
    byte rdata = 0xFF;
    Wire.beginTransmission(deviceaddress);
    Wire.write((eeaddress >> 8)); // MSB
    Wire.write((eeaddress & 0xFF)); // LSB
    Wire.endTransmission();
    Wire.requestFrom(deviceaddress,1);
    if (Wire.available()) rdata = Wire.read();
    return rdata;
}

void setup() {
  Wire.begin(); // initialise the connection
  Serial.begin(9600);
  delay(100); //add a small delay
  Serial.println("Arduino Group Delay Read Program");

  for (unsigned long i = 0; i < 128000; i++){
    Serial.print(i);
    Serial.print(",");
    byte a = i2c_eeprom_read_byte(0x50, i);
    Serial.println(a, BIN);
  }
}

void loop() {
  //
}

```

To reduce overhead and speed up the process I am now using the code below:

```
#include <Wire.h>

byte bytes[32];

void i2c_eeprom_read_buffer( int deviceaddress, unsigned long eeaddress, byte *buffer, int length ) {
    Wire.beginTransmission(deviceaddress);
    Wire.write((eeaddress >> 8)); // MSB
    Wire.write((eeaddress & 0xFF)); // LSB
    Wire.endTransmission();
    Wire.requestFrom(deviceaddress,length);
    int c = 0;
    for ( c = 0; c < length; c++ )
        if (Wire.available()) buffer[c] = Wire.read();
}

void setup() {
  Wire.setClock(400000); // 400kHz
  Wire.begin(); // initialise the connection
  Serial.begin(250000);
  delay(100); //add a small delay
  Serial.println("Arduino Group Delay Read Program");

  for (unsigned int i = 0; i < 128000;){
    i2c_eeprom_read_buffer(0x50, i, (byte *)bytes, 32);
    for (int j = 0; j < 32; j++){
      Serial.print(i);
      Serial.print(",");
      Serial.println(bytes[j], BIN);
      i++;
    }
  }
}

void loop() {
  //
}

```

Unfortunately, the program now loops at the page boundary back to the start of the address range. Here is a sample of the output:

```
65500,1110100
65501,1101000
65502,1101001
65503,1110011
65504,100000
65505,1101001
65506,1110011
65507,100000
65508,1100100
65509,1100001
65510,1110100
65511,1100001
65512,100000
65513,1100110
65514,1110010
65515,1101111
65516,1101101
65517,100000
65518,1110100
65519,1101000
65520,1100101
65521,100000
65522,1100101
65523,1100101
65524,1110000
65525,1110010
65526,1101111
65527,1101101
65528,0
65529,11111111
65530,11111111
65531,11111111
65532,11111111
65533,11111111
65534,11111111
65535,11111111
0,0
1,0
2,1
3,110000
4,111000
5,111001
6,110110
7,110001
8,111001
9,1000001
10,101110
11,1011000
12,110001
13,110001
14,1010110
15,1011001
16,110001
17,110111
18,110100
19,110001
20,1110100
21,1101000
22,1101001
23,1110011
24,100000
25,1101001
26,1110011
27,100000
28,1100100
29,1100001
30,1110100
31,1100001
32,100000
33,1100110
34,1110010
35,1101111
36,1101101
37,100000
38,1110100
39,1101000
40,1100101
41,100000
42,1100101
43,1100101
44,1110000
45,1110010
46,1101111
47,1101101
48,0
49,111001
50,100010
51,11010010
52,110101
53,1001000
54,11101011
55,11000000
56,110101
57,11101011
58,1011100
59,10010100
60,110101
61,100000
62,10100011
63,1110110
64,10110100
65,10110001
66,1111010
67,11100000
68,10110110
69,101100
70,11010110

```

I could see how an error in the code could cause the second page to display the first page's values, but there is nothing in the code that should cause the counter itself to loop. Any idea what could be causing this?

**Edit: For anyone who is working a similar issue, here is the code that I ended up with once I solved this issue and then dealt with the page boundary problem (line 4):**

```
#include <Wire.h>

byte i2c_eeprom_read_byte( int deviceaddress, unsigned long eeaddress ) {
  byte rdata = 0xFF;
   if( eeaddress > 65535 ){
    deviceaddress = deviceaddress | B00000100;
    eeaddress = eeaddress & 0xFFFF;
    }
  Wire.beginTransmission(deviceaddress);
  Wire.write((eeaddress >> 8));   // MSB
  Wire.write((eeaddress & 0xFF)); // LSB
  Wire.endTransmission();
  Wire.requestFrom(deviceaddress,1);
  if (Wire.available()) rdata = Wire.read();
  return rdata;
}

void setup() {
  Wire.setClock(400000);
  Wire.begin(); // initialise the connection
  Serial.begin(115200);
  delay(100); //add a small delay
  Serial.println("Arduino Group Delay Read Program");

  for (unsigned long i = 0; i < 128000; i++){
    Serial.print(i);
    Serial.print(",");
    byte a = i2c_eeprom_read_byte(0x50, i);
    Serial.println(a, BIN);
  }
}

void loop() {
}

```

Note that this last code will work with the i2c\_eeprom\_read\_buffer function as well as long as you add the if statement starting at line 4.

# Answer
> 2 votes
```
for (unsigned int i = 0; i < 128000;){

```

An `unsigned int` can only count from 0 to 65536 on an 8-bit system... You need that to be an `unsigned long`, or better, a `uint32_t` (better because it's guaranteed to be an unsigned 32-bit value on any platform regardless of how wide its registers are).

---
Tags: arduino-uno, i2c, eeprom
---


title: Confusion with Serial Communication

text:
# Question
Title: Confusion with Serial Communication
Is a buffer used for outputting data from the arduino?

OR

Is the output from the arduino buffered before sending it to Computer?

Is it the same buffer that is used to store the incoming data and the data that we send back from the arduino?

Eg- If am sending a text through the Serial Monitor to the arduino and I am also doing Serial.println("sth") then are they both using the same buffer?

How can i relate Serial buffer with these processes

Please Help!

Arduino Noob

EDIT-1

Can you please explain about the TX buffer overflow

# Answer
> Is it the same buffer that is used to store the incoming data and the data that we send back from the arduino?

there are two buffers RX buffer and TX buffer.

> Is a buffer used for outputting data from the arduino? OR Is the output from the arduino buffered before sending it to Computer?

TX buffer holds the data until they can be send. Data are send from TX buffer by interrupt routine.

> Can you please explain about the TX buffer overflow

TX buffer overflow doesn't happen, because it is easy to handle the situation. The interrupt routine can send the data only at set baud rate. If the program fills the buffer faster then the interrupt empties the buffer, then the TX buffer fills, but the write function knows that the buffer is full and waits in a while cycle until there is space for that one byte to write.
> 0 votes

---
Tags: serial
---


title: Help with Serial.print()

text:
# Question
Title: Help with Serial.print()
How does the Serial.print() transmit the data? Can you please explain this with respect to TX buffers?

Also, **What would happen if i try to output the data that is greater than 64 bytes? How is this transmitted?**

And please explain the difference with Serial.write()

Thanks!

# Answer
> 2 votes
`Serial.print()` feeds the data into the TX buffer one character at a time (through the `Print` class's inherited `.write()` function which `HardwareSerial` implements). If there isn't enough room in the TX buffer for the next character it waits for there to be room available.

Characters are removed one at a time from the TX buffer and sent through the physical UART by the UART's TX interrupt.

To put it in more detail:

* When you call `Serial.print()` it's actually calling `Print.print()`, because `Print` is a parent class of the `HardwareSerial` class.
* `Print.print()` repeatedly calls `Print.write()` for each character to print.
* `Print.write()` is a *pure virtual* function (which means it's only got the definition in the `Print` class and child classes must implement it).
* `HardwareSerial.write()` implements the `Print.write()` function which takes the character and (with possible blocking while waiting for space) adds it to the TX buffer.
* `Serial` is an instance of the `HardwareSerial` class.

---
Tags: serial, serial-data
---


# Question
Title: NeoPixel library performance: Adafruit vs. FastLED
I'm new to these addressable LED things – I just received a 149-LED WS2812B strip today, and I'm experimenting with various approaches. Adafruit's own tutorial says the FastLED library is faster than their Adafruit\_NeoPixel library, so I wanted to test their performance.

I'm running this code on a Nano clone:

```
// Adafruit
#include <Adafruit_NeoPixel.h>
// FastLED
#include <FastLED.h>
// Common
#define NUM_LEDS 149
#define DATA_PIN 6

// Adafruit initialization
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, DATA_PIN, NEO_GRB + NEO_KHZ800);
const uint32_t adaBlack = strip.Color(0, 0, 0);
const uint32_t adaWhite = strip.Color(255, 255, 255);

// FastLED initialization
CRGB leds[NUM_LEDS];

void setup() {
  // Common
  delay(2000);

  // Adafruit setup
  strip.begin();

  // FastLED setup
  FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);

  // Common
  Serial.begin(57600);
}

void loop() {
  unsigned int adafruitMillis = adafruitLoop();
  unsigned int fastLedMillis = fastLedLoop();
  // Yes, this is ugly -- but it works every time
  Serial.print(adafruitMillis);
  Serial.print(",");
  Serial.println(fastLedMillis);
}

unsigned int adafruitLoop()
{
  long unsigned startMillis = millis();
  for (int whiteLed = 0; whiteLed < NUM_LEDS; whiteLed++) {
    strip.setPixelColor(whiteLed, adaWhite);
    strip.show();
    strip.setPixelColor(whiteLed, adaBlack);
  }
  return (unsigned int) millis() - startMillis;
}

unsigned int fastLedLoop()
{
  long unsigned startMillis = millis();
  for(int whiteLed = 0; whiteLed < NUM_LEDS; whiteLed++) {
    leds[whiteLed] = CRGB::White;
    FastLED.show();
    leds[whiteLed] = CRGB::Black;
  }
  return (unsigned int) millis() - startMillis;
}

```

The results are totally disastrous for FastLED (shown in red):

Am I doing something wrong, or is FastLED winning on features, rather than on speed?

For the record, I did check whether the performance hit comes from setting the pixel values or from sending the data – FastLED is faster at setting the pixel values than Adafruit's library, but that doesn't matter because setting *two* pixel values takes 3 ms or less for the entire strip, regardless of the library. Sending the data to the strip takes most of the time, and that's where FastLED lags behind big time (900 ms compared to Adafruit's 200 ms).

# Answer
You can't rely on the timing reported by millis when comparing FastLED and Adafruit's neopixel library. Writing out Neopixel data involves disabling interrupts, which is what the clock uses to advance. FastLED accounts for this and attempts to update the system clock time after writing out led data to account for the amount of time that interrupts were disabled, but the adafruit NeoPixel library doesn't. You need to use something else to compare timing.

(WS2812 data has a pretty strict data rate - 800khz, or about 30µs per rgb led)

(I should know, I wrote FastLED :)
> 11 votes

# Answer
As I understand it, the *Fast* in *FastLED* isn't for sending the data, but for manipulating the array/data that holds the colors. The FastLED library contains many functions optimized for dealing with 8-bit unsigned integers for holding color values, including color addition, 8-bit scaling, partially-defined color palettes (for example, you define 8 waypoints in the palette, but can grab a color from the full 8-bit range and it interpolates on the fly using the fast 8-bit math.

Not just math, but also conversion to/from RGB and HSV realms, etc.

It supports pushing multiple strips at the same time (parallel) by writing to the whole `PORT` instead of just one pin of the 8-pin port, so if you split your strip into multiples, you can really make speed gains in writing to the LEDs.
> 1 votes

---
Tags: neopixel
---


title: Segmentation fault at Serial.begin()

text:
# Question
Title: Segmentation fault at Serial.begin()
I try to communicate with my Arduino clone (Elegoo Uno R3) from Arduino IDE (v1.8.4 installed by `dnf` from repos) at Fedora 27. Compiling and upload of normal example code works well. However, as I try to start any serial communication (e.g. for debug), the compiler fails returning following segfault:

```
"/usr/bin/avr-gcc"  -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p  -o "/tmp/arduino_build_407070/AnalogReadSerial.ino.elf" "/tmp/arduino_build_407070/sketch/AnalogReadSerial.ino.cpp.o" "/tmp/arduino_build_407070/../arduino_cache_983152/core/core_arduino_avr_uno_1621df717313d057c92202babd71649a.a" "-L/tmp/arduino_build_407070" -lm
lto1: internal compiler error: Segmentation fault
Please submit a full bug report,
with preprocessed source if appropriate.
See <https://bugzilla.redhat.com/> for instructions.
lto-wrapper: fatal error: /usr/bin/avr-gcc returned 1 exit status
compilation terminated.
/usr/lib/gcc/avr/6.3.0/../../../../avr/bin/ld: error: lto-wrapper failed
collect2: error: ld returned 1 exit status
exit status 1
Error compiling for board Arduino/Genuino Uno.

```

I found similar issue here https://github.com/sudar/Arduino-Makefile/issues/486 However, that solution deals with Arduino-Makefile software that is little bit complex for me.

I would appreciate any help either how to solve the segfault itself, or how to easily use Arduino-Makefile (I would like to compile from Arduino IDE or any user-friendly IDE).

# Answer
> 1 votes
There's a new version of the avr-gcc package that's currently available in the updates-testing repo that should fix the problem. You can install/update it by enabling the updates-testing repo, or grabbing the rpm from koji (https://koji.fedoraproject.org/koji/buildinfo?buildID=1013122)

---
Tags: serial, arduino-ide, compile
---


title: How to add additional sensors [Arduino]

text:
# Question
Title: How to add additional sensors [Arduino]
I am new to Arduino. I have currently connected a FSR sensor to the TOUT pin of ESP WROOM-02. How do I add additional FSR sensor to ESP WROOM-02?

# Answer
An FSR (Force Sensing Resistor) varies in resistance as force or pressure is applied. Most often such devices are connected to the positive power rail and the ADC input of a embedded micro controller. At the same time a second known fixed resistor is connected to the opposite power rail (ground) and the same ADC input. This forms a resistor divider network where the ADC in the embedded micro controller can measure the force applied to the FSR by measuring the voltage of the resistor divider.

To measure 2 or more FSRs using the same ADC input, consider connecting one lead of each FSR to a digital input/output pin of the embedded micro controller. Then connecting the other lead of each FSR to the ADC input. To measure the force on the 1st FSR, configure the connected digital pin as a high ouput using software. So that all the other FSRs do not influence the measurement, configure all the other digital pins to have high impedance. Often this can be done by programming these other digital pins as inputs. Cycle through all FSRs in a similar fashion using software.
> 2 votes

---
Tags: esp8266, sensors, arduino-ide, pressure
---


title: Garbage value Serial Monitor

text:
# Question
Title: Garbage value Serial Monitor
I am building my own arduino.Here is my code Below. I found code working for Digital Ios like blink example ; analog reading, Problem i am facing in Serial Monitor.Whenever i open Serial monitor i get trash values.I have choose proper crystal & proper values. Please let me know possibility for getting trash values

```
int led = 2;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  Serial.println("Welcome:");
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(100);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(100);               // wait for a second
}

```

# Answer
> 5 votes
One of my projects does this too. I leave it connected to a USB port for power so it can control a room fan. Every 4 seconds it writes a line of data to the serial output. When I open a serial terminal on the computer, I immediately see a short stream of garbage, followed by the next, and all subsequent log outputs, properly displayed. It looks as if the serial-to-USB chip has some data buffered in it which it delivers, but out of sync, as soon as the terminal connection is made, but this is just a guess.

Have you tried resetting your chip while the terminal is connected? When I do this, there are no sync issues and the displayed data is all valid.

Update: If you only ever get garbage from your terminal, then it's likely the terminal and the Arduino aren't matched for one or both of baud-rate or frame-size.

Arduino serial hardware uses an 8N1 frame: 8 data bits, No parity bit, 1 stop bit. Your serial monitor must be set to match this (and it probably is, since this is the most common convention, but worth checking.

Second, the baud rates must match. You've set the Arduino for 9600 baud and your serial monitor program must be also (from your screenshot, it looks like it is).

You said you are using a crystal so it quite unlikely that Arduino's 9600 baud is inaccurate, but this could happen if you were using its internal clock source.

Finally, in the lower left corner of your serial monitor screen shot, it looks like you have selected "No line endings". Serial.println() ends every line with CR/LF. See if that is an available line-ending setting. It is sometimes named "OD OA" (the hex values for Carriage-Return and Line-Feed). Try that setting if it is available.

The serial protocol is one of the oldest communication protocols but it has many variations. (Did someone say "standard"? :-) Everyone gets bitten by it, eventually.

# Answer
> 0 votes
Opening a Serial connection will reset your arduino and restart the whole program. I learned this the hard way when coding a windows serial com-monitor for triggering systemcalls from arduino

---
Tags: arduino-uno, serial, programming, bootloader
---


title: Multiple LED on arduino

text:
# Question
Title: Multiple LED on arduino
I am currently trying to control multiple LEDs with one Arduino Mega 2560 board. However, since each LED needs 3.6 volts and the board only supplies 5V I cannot make more than one light up.

Is there a way to increase to output voltage of the Arduino board ? Or perhaps of using arduino to turn on or off a battery that has a high enough voltage to power multiple LED ?

Thanks for your help

# Answer
Each pin on any Arduino (with some exceptions) can only handle 40mA MAX. Even the 5V and similar output sources can't handle more than 600mA, So I suggest you use them to power a MOSFET or Darlington to connect them in appropriate series and parallel connection counts.

Both the above transistors can handle high voltage, but you need to choose ones that correspond to a voltage that an Arduino can provide.

This is the most robust method if you want all the LEDs to light up at the same time. However for array addressable LEDs you might need extra BJTs coupled with resistors for each led, maybe along with two decided that would be appropriate for your application.
> 3 votes

# Answer
If you connect them in parallel instead of series you'll be able to turn them on and off with 3.6 volts (5 volts through an appropriate dropping resistor), assuming the Arduino can supply the current. Here's a general explanation of the difference.
> 2 votes

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


title: Combining codes for 3 sensors

text:
# Question
Title: Combining codes for 3 sensors
I am trying to combine codes for my 3 sensors: GSR, Pulse sensor, and ECG but I keep getting errors. I have a poor background in coding. I have the 3 codes separately and I'm not the one who wrote them. Here are the new Sketch after Combining the loops and the setups.I didn't get any error after uploading and verifying but I am not getting values in my Serial Monitor

Combined sketch:

```
<!-- language-all: lang-cpp -->

#include <Wire.h>
#include "rgb_lcd.h"
#define ANALOG_IN 2   // analog input pin to display
#define OUTPUT_PIN 10 // test signal output pin
#define PULSE_MS 250  // pulse width in ms

int PulseSensorPurplePin = 1;        // Pulse Sensor PURPLE WIRE connected to ANALOG PIN 0
int LED13 = 13;   //  The on-board Arduion LED
int Signal;                // holds the incoming raw data. Signal value can range from 0-1024
int Threshold = 550;            // Determine which Signal to "count as a beat", and which to ingore.

const int BUZZER=3;
    const int GSR=A0;
    int threshold=0;
    int sensorValue;
    rgb_lcd lcd;

long ms;        // timer in ms
int out = HIGH;     // output level

void setup() {
   pinMode(LED13,OUTPUT);         // pin that will blink to your heartbeat!
   Serial.begin(9600);         // Set's up Serial Communication at certain speed.

   long sum=0;
      //VERIFY VALUE
      lcd.begin(16, 2);
      Serial.begin(9600);
      pinMode(BUZZER,OUTPUT);
      digitalWrite(BUZZER,LOW);
      delay(1000);
//VERIFY VALUE
      for(int i=0;i<500;i++)
      {
      sensorValue=analogRead(GSR);
      sum += sensorValue;
      delay(5);
      }
      threshold = sum/500;
       Serial.print("threshold =");
       Serial.println(threshold);

       pinMode(OUTPUT_PIN, OUTPUT);    // set output pin mode
       Serial.begin(19200);        // initiate serial communication
       digitalWrite(OUTPUT_PIN, out);  // set initial digital output
       ms = millis();          // query current time (in ms)

}

void loop() {
  Signal = analogRead(PulseSensorPurplePin);  // Read the PulseSensor's value.
                                              // Assign this value to the "Signal" variable.

   Serial.println(Signal);                    // Send the Signal value to Serial Plotter.

   if(Signal > Threshold){                          // If the signal is above "550", then "turn-on" Arduino's on-Board LED.
     digitalWrite(LED13,HIGH);
   } else {
     digitalWrite(LED13,LOW);                //  Else, the sigal must be below "550", so "turn-off" this LED.
   }

delay(100);

   int temp;
      sensorValue=analogRead(GSR);
      Serial.print("sensorValue=");
      Serial.println(sensorValue);
      lcd.setCursor(0, 0);
      lcd.print("GSR Value: ");
      lcd.print(sensorValue);
      temp = threshold - sensorValue;
      if(abs(temp)>50)
      {
        sensorValue=analogRead(GSR);
        temp = threshold - sensorValue;
        if(abs(temp)>50){
       digitalWrite(BUZZER,HIGH);
        Serial.println("YES!");
        delay(3000);
        digitalWrite(BUZZER,LOW);
        delay(1000);}
      }

      int val = analogRead(ANALOG_IN);    // read voltage at input pin
  Serial.write( 0xff );         // write value to serial port
  Serial.write( (val >> 8) & 0xff );
  Serial.write( val & 0xff );

  if (millis() >= ms+PULSE_MS) {    // check if pulse width has elapsed
    ms = millis();            // query current time (in ms)
    out = !out;             // invert output value
    digitalWrite(OUTPUT_PIN, out);    // update digital output
  }
}

```

# Answer
In general:

* There can be only one setup, in most cases you can put the code from all three setup's together, but checkout the code does not interfere, i.e. does not use the same pins. In that case, change the pin numbers if possible (and change the circuit accordingly).
* For the loops it can be more tricky:

+ Check how often each loop should be called. If one loop costs e.g. 500 ms that means the other loops will be called less often, which can affect the precision or even good readout of the sensor.
    + If all loops are relatively small and the duration do not matter, you can just call them after each other (rename the loops and call them one by one).
    + If there is a time constraint, than split the lengthy loop in a small part, and call it whenever needed. There is no clear rule for this.

What you can try is:

* Check for reach loop how long it takes
* Than for each loop add a delay with same time as the other loops, thus:
    + Test the duration (average) of loop 1, than of loop 2, than of loop 3. Assume loop1 takes 100, loop2 200 and loop3 300 ms.
    + Test loop1 without calling loop2 and loop3, but just add the delay (200+300=500 ms).
    + Check if it works, if so, it means you can call the other loops without problems.
    + Do the same for loop2 (with 100+300ms delay) and loop3 (100+200ms).
    + If all loops work correctly, than you can call the loop1, loop2, loop3 in sequence.
    + If not, you have to call the loop(s) that do not work either more often or in a different way.
> 0 votes

---
Tags: programming, sensors, code-review
---


# Question
Title: Pair of nRF24L01s ping/pong example sketch works, but using my own code fails after first successful transmit
I have a pair of nRF24L01s connected to a pair of Arduino Unos and I'm using the RF24 library from here: RF24 library. When I run the pingpair example sketch, the radios transmit and receive back and forth just fine. So I tried to program my own very simple example but I'm running into a problem where the first message transmits successfully (and is received successfully), however, subsequent messages fail to send. The call to radio.write() returns false.

I'm using the following code on the 'sender':

```
RF24 radio(9,10);
const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };
uint8_t payload[1];

void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.setRetries(15, 15);
  radio.setPayloadSize(1);
  radio.openWritingPipe(pipes[0]);
}

void loop() {
  payload[0] = 1;
  bool ok = radio.write(payload, 1);
  Serial.println("Status: " + (String) ok);
  delay(200);
}

```

And the following on the 'receiver':

```
RF24 radio(9,10);
const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };
uint8_t payload[1];

void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.setRetries(15, 15);
  radio.setPayloadSize(1);
  radio.openReadingPipe(1, pipes[0]);
  radio.startListening();
  Serial.println("Listening: " );
}

void loop() {
  if (radio.available()) {
    bool done = false;
    while (!done) {
      done = radio.read(payload, 1);
      Serial.println("Got payload: " + (String) payload[0]);
    }
  }
}

```

I'm guessing the problem has to be with my code because the example sketches work, but I can't figure out what the problem is. Again to summarize, when I reset the Arduino, the first call to `radio.write()` returns true and the message is transmitted. After that, subsequent calls to `radio.write()` return false.

Also note that I did try adding a 10uF capacitor across +3.3V and Ground but it did not help.

Thanks for any help.

# Answer
> 1 votes
Comparing your rx against the example, i would suggest not having the while done statement. You could also throw in a few serial.write debug lines in both sketches, to log different parts of the code, to find where its getting stuck.

# Answer
> 1 votes
I was just having this issue. You need to be able to read and write on both ends. You send up sending an ack package back to the sending arduino like in the test sketch.

You ripped that part out.

You need to read back through the example code and line by line understand what the data is doing and why it's doing it that way before you can start using rf24.

The short of it is that the sender will send data and then finish and wait for a response packet before sending the next one. The reciever works much the same way except it always will be listening for incoming data until the sender message ends. Then it in turn will send a reply packet saying that it recieved the first packet.

Make sure that the reciever isn't looping waiting for packets. It should only respond once it recieves something. The sender should have a timeout on it so that it knows that it's messages are failing. This is also incredibly important for debugging so you can see who failed and why.

This is basically tcp at work.

You can also use noack and that's called udp

# Answer
> 0 votes
You should open a reading pipe on the transmitter end because when the reader receives your message it will reply with an acknowledge packet, which is expected by the writer in order to confirm the packet has been delivered. With your current setup, your writer is sending out a packet and expecting to receive the response on an address which is by default configured as a broadcast address.

On the sender side, you also need to start listening after sending the packet and stop listening before sending the new packet.

The transmission protocol works like this:

1. the sender sends a packet in the air and starts waiting for the ack
2. all listeners receive the packet, no matter their receive address
3. each listener check if the sender address matches with any configured reading pipe address
    1. if the address matches then the listener sends back an acknowledge packet to inform the transmission has been accomplished
    2. if the address does not match it discards the packet
4. if the sender receives at least one acknowledge packet then it marks the packet as being sent successfully
5. if the sender doesn't receive the ack packet within the configured time to live then sends the packet again until the retry count has not been reached
6. if the retry count has been reached then it marks the transmission as failed

So change your sender `setup()` and `loop()` functions above with:

```
void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.setRetries(15, 15);
  radio.setPayloadSize(1);
  radio.openWritingPipe(pipes[0]);
  radio.openReadingPipe(1, pipes[1]); // add this
}

void loop() {
  radio.stopListening(); // add this
  payload[0] = 1;
  bool ok = radio.write(payload, 1);
  radio.startListening(); // add this
  Serial.println("Status: " + (String) ok);
  delay(200);
}

```

You might also want to set the writing address on the receiver if you plan to use more than 2 radios, otherwise, you will not be able to distinguish who has acknowledged different packets:

```
radio.openWritingPipe(pipes[1]); // add this to receiver `setup()`

```

---
Tags: arduino-uno, nrf24l01+, code-review
---


title: Store values in array

text:
# Question
Title: Store values in array
I'm trying to implement the "BNO055 9 Axes Motion Shield". There is an existing Arduino sketch GitHub that reads out the Euler data, I changed it a bit to print out quaternion data.

```
#include "NAxisMotion.h"        //Contains the bridge code between the API and the Arduino Environment
#include <Wire.h>

NAxisMotion mySensor;         //Object that for the sensor
unsigned long lastStreamTime = 0;     //To store the last streamed time stamp
const int streamPeriod = 20;          //To stream at 50Hz without using additional timers (time period(ms) =1000/frequency(Hz))

void setup() //This code is executed once
{
  //Peripheral Initialization
  Serial.begin(115200);           //Initialize the Serial Port to view information on the Serial Monitor
  I2C.begin();                    //Initialize I2C communication to the let the library communicate with the sensor.
  //Sensor Initialization
  mySensor.initSensor();          //The I2C Address can be changed here inside this function in the library
  mySensor.setOperationMode(OPERATION_MODE_NDOF);   //Can be configured to other operation modes as desired
  mySensor.setUpdateMode(MANUAL);   //The default is AUTO. Changing to MANUAL requires calling the relevant update functions prior to calling the read functions
  //Setting to MANUAL requires fewer reads to the sensor
}

void loop() //This code is looped forever
{
  if ((millis() - lastStreamTime) >= streamPeriod)
  {
    lastStreamTime = millis();
    mySensor.updateQuat();        //Update the Quat data into the structure of the object
    mySensor.updateCalibStatus();  //Update the Calibration Status

    Serial.print("Time: ");
    Serial.print(lastStreamTime);
    Serial.print("ms ");

    Serial.print(" W: ");
    Serial.print(mySensor.readQuatW());

    Serial.print(" X: ");
    Serial.print(mySensor.readQuatX());

    Serial.print(" Y: ");
    Serial.print(mySensor.readQuatY());

    Serial.print(" Z: ");
    Serial.print(mySensor.readQuatZ());

    Serial.println();
  }
}

```

Here is a snippet of the "NAxisMotion.h" header file:

```
    /*******************************************************************************************
    *Description: This function is used to return the w-axis of the quaternion data
    *Input Parameters: None
    *Return Parameter:
    *   int16_t:    W-axis quaternion data multiplied by 1000 (for 3 decimal places accuracy)
    *******************************************************************************************/
    int16_t readQuatW(void);

    /*******************************************************************************************
    *Description: This function is used to return the x-axis of the quaternion data
    *Input Parameters: None
    *Return Parameter:
    *   int16_t:    X-axis quaternion data multiplied by 1000 (for 3 decimal places accuracy)
    *******************************************************************************************/
    int16_t readQuatX(void);

    /*******************************************************************************************
    *Description: This function is used to return the y-axis of the quaternion data
    *Input Parameters: None
    *Return Parameter:
    *   int16_t:    Y-axis quaternion data multiplied by 1000 (for 3 decimal places accuracy)
    *******************************************************************************************/
    int16_t readQuatY(void);

    /*******************************************************************************************
    *Description: This function is used to return the z-axis of the quaternion data
    *Input Parameters: None
    *Return Parameter:
    *   int16_t:    Z-axis quaternion data multiplied by 1000 (for 3 decimal places accuracy)
    *******************************************************************************************/
    int16_t readQuatZ(void);

```

I understand that the output data type is signed integer, but what syntax do I need to use to store them in an array? Because it seems the only way to access them is through "mySensor.readQuatX()"

# Answer
If I understand correctly you want to store a number of signed integers in an array. Arrays have fixed sizes so you need to know the number of values you want to store.

```
// Global declarations
enum QIndex {WAxis, XAxis, YAxi, ZAxis, MaxIndex};
int16_t qData[MaxValues] = {0};

// Code inside loop
qData[WAxis] = readQuatW();
qData[XAxis] = readQuatX();
qData[YAxis] = readQuatY();
qData[ZAxis] = readQuatZ();

// Pass the array  of values to another function with the declaration
// void SomeFunction (int *ar);
// or
// void SomeFunction (int ar[]);
SomeFunction (qData);

```

Is that what you mean?
> 0 votes

---
Tags: array, data-type, imu
---


# Question
Title: How to find how much data in the transmit buffer?
How do you find how many bytes are currently waiting in the transmit buffer?

I'm trying to diagnose a weird serial disconnection problem with an Arduino Uno and a rosserial node. It works fine for 10-20 minutes, and then mysteriously losing connection. At first, I thought the Arduino was running out of memory, but I'm able to use the MemoryFree library to log available memory, and it never drops below 9051 bytes.

I now want to make sure the problem isn't because the serial buffer is overflowing, from the Arduino trying to send too much data.

# Answer
> 2 votes
If you really want to know (not that it would do you any good) you can use the `Serial.availableForWrite()` function (which returns how much space is left in the buffer) and subtract the returned value from the size of the buffer.

```
int used = 64 - Serial.availableForWrite(); // Assuming a 64 byte buffer

```

I haven't tested it, but you may be able to use `SERIAL_TX_BUFFER_SIZE` instead of the `64` to make it properly portable.

```
int used = SERIAL_TX_BUFFER_SIZE - Serial.availableForWrite(); // Possibly portable

```

# Answer
> 0 votes
> I now want to make sure the problem isn't because the serial buffer is overflowing, from the Arduino trying to send too much data.

If you are using the software serial Arduino library there is a way to check for overflow.

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


title: ESP8266 PHP Web Server

text:
# Question
Title: ESP8266 PHP Web Server
I need my ESP8266 web server to load my website files with `.php` extensions. So far I managed to load `.htm` `.css` and `.js` files from my SD card, but when I upload PHP files on my SD card, they won't run. How can I do that?

# Answer
It sounds like you are trying to put a PHP file on an SD card that the ESP8266 will serve itself.

This is not possible, as no one has, and probably never will, port PHP to the Espressif 8266 platform.

Your device can serve `.htm` `.css` and `.js` files because it's just a matter of streaming the file content to the client. But PHP requires that an application on the server run the PHP code, and then send the resulting output to the client.
> 8 votes

---
Tags: esp8266
---


# Question
Title: (Neopixels) How to keep the pixels of the same colour despite increasing brightness?
I've been doing a fade function for the NeoPixels. However, the moment I have maximum brightness for the pixels, *I noticed there 2 colours even though in my function I have only specified one colour*.

Some strips are one colour and the others are another colour. I specified the colour to be blue for the strips however many strips are blue and the strips nearer the end are green (but closer to a blue-green colour).

Is there any way to keep the colour even when the brightness changes? I've read somewhere online a different colour is seen with different brightness levels i.e. `setPixelColor(brightness, r,g,b)`.

I've also tried FastLED library and followed documentation. However, the lights are not doing what it has said in the codes, I've tried `leds[i].fadeLightBy(200)` and it has given me no result.

My code for the fade function (edited from http://moving-rainbow.readthedocs.io/en/latest/guide/fade-in-and-out/):

```
void fade(uint32_t color) {
  for (int i = 0; i < 255; i++) {
    for (int q = 0; q < strip.numPixels(); q++) {
      strip.setPixelColor(q, Wheel((color) & 255));
    }
    strip.setBrightness(i);
    strip.show();
  }

  //decreasing brightness
  for (int l = 255; l > 255; l--) {
    for (int p = 0; p < strip.numPixels(); p++) {
      strip.setPixelColor(p, Wheel((color) & 255));
    }
    strip.setBrightness(l);
    strip.show();
  }
}

```

The method "Wheel" is from the Arduino Neopixel strandtest example.

```
uint32_t Wheel(byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if (WheelPos < 85) {
    return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
  }
  if (WheelPos < 170) {
    WheelPos -= 85;
    return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
  }
  WheelPos -= 170;
  return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}

```

Any advice on how I should go about doing it?

# Answer
I have some simple NeoPixel fading going on in this example sketch:

```
/*
 *
 * NeoPixels demo - fades colours (in array) up and down
 *
 */

#include <SPI.h>
#include <NeoPixels_SPI.h>

const unsigned int PIXELS = 8; // Number of pixels in the string

void setup()
  {
  ledsetup();
  } // end of setup

float patterns [] [3] = {
  { 1, 0, 0 },  // red
  { 0, 1, 0 },  // green
  { 0, 0, 1 },  // blue
  { 1, 1, 0 },  // yellow
  { 1, 0, 1 },  // magenta
  { 0, 1, 1 },  // cyan
  { 1, 1, 1 },  // white
  { 160.0 / 256, 82.0 / 256, 45.0 / 256 },  // sienna
  { 46.0 / 256, 139.0 / 256, 87.0 / 256 },  // sea green

};

// number of items in an array
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))

void loop()
  {

  for (byte i = 0; i < ARRAY_SIZE (patterns); i++)
    {
    // fade up
    for (byte m = 0; m < 100; m++)
      {
      showColor (PIXELS, patterns [i] [0] * m, patterns [i] [1] * m, patterns [i] [2] * m);
      delay (10);
      } // end of for

    // fade down
    for (byte m = 100; m > 0; m--)
      {
      showColor (PIXELS, patterns [i] [0] * m, patterns [i] [1] * m, patterns [i] [2] * m);
      delay (10);
      } // end of for
    } // end of for each array item

  } // end of loop

```

This is using the simple NeoPixel library that I wrote using the SPI hardware. The library with the exact code above is available here.

Basically the fading is done by multiplying the floating-point values for the R/G/B values by a constant from 0 to 100 (you could make it 0 to 255).

Since the colours themselves are expressed in the range 0 .. 1 then the result of the multiplication would be 0 to 255. To my naked eye the colours seem true at all brightnesses.

To use the library on your Uno just connect +5V, Gnd, and the data pin is MOSI (D11 on the Uno).
> 1 votes

---
Tags: arduino-uno, neopixel
---


# Question
Title: Confusion with two Serial.begin() function calls
Why are there two Serial.begin() function calls? What does that signify? Here is the minimal code i am working on:

```
void setup() {
      Serial.begin(115200);
      Serial.begin(9600);
      Serial.println("Pressure Sensor Test"); Serial.println("");
    }

```

Here is the full Code:

```
#include <SimpleDHT.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP085_U.h>

int pinDHT11 = 2;
Adafruit_BMP085_Unified bmp = Adafruit_BMP085_Unified(10085);

void displaySensorDetails(void)
{
  sensor_t sensor;
  bmp.getSensor(&sensor);
  Serial.println("------------------------");
  Serial.print  ("Sensor:       "); Serial.println(sensor.name);
  Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
  Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
  Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println(" hPa");
  Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println(" hPa");
  Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println(" hPa");
  Serial.println("----------SDNx real time scientific data---------------");
  Serial.println("");
  delay(500);
}

void setup() {
  Serial.begin(115200);
  Serial.begin(9600);
  Serial.println("Pressure Sensor Test"); Serial.println("");
  if(!bmp.begin())
  {
    /* There was a problem detecting the BMP085 ... check your connections */
    Serial.print("  Ooops, no BMP085 detected ... Check your circuit some errors are there!");
    while(1);
  }

  /* Display some basic information on this sensor */
  displaySensorDetails();

}

void loop() {

  Serial.println("===========");
  Serial.println("Sample DHT11...");

  byte temperature = 0;
  byte humidity = 0;
  byte data[40] = {0};
  if (simple_dht11_read(pinDHT11, &temperature, &humidity, data)) {
    Serial.print("Read DHT11 failed");
    return;
  }

  Serial.print("Sample RAW Bits: ");
  simple_dht11_serial_print(data);

  Serial.print("SDNx says you are genius and every thing is OK: ");
  Serial.print((int)temperature); Serial.print(" *C, ");
  Serial.print((int)humidity); Serial.println(" %");

  // DHT11 sampling rate is 1HZ.
  delay(1000);

  sensors_event_t event;
  bmp.getEvent(&event);

  if (event.pressure)
  {

    Serial.print("Pressure:    ");
    Serial.print(event.pressure);
    Serial.println(" hPa");

    float temperature;
    bmp.getTemperature(&temperature);
    Serial.print("Temperature: ");
    Serial.print(temperature);
    Serial.println(" C");

    float seaLevelPressure = SENSORS_PRESSURE_SEALEVELHPA;
    Serial.print("Altitude:    ");
    Serial.print(bmp.pressureToAltitude(seaLevelPressure,
                                        event.pressure));
    Serial.println(" m");
    Serial.println("");
  }
  else
  {
    Serial.println("Sensor error");
  }
  delay(1000);
}

```

# Answer
It looks like a mistake, as Chris says. I can't tell you what will happen but my **guess** is it will work at 9600.

I would recommend that you delete one of the lines to avoid further confusion.
> 3 votes

---
Tags: serial
---


title: Submit data from HTML form to ESP8266

text:
# Question
Title: Submit data from HTML form to ESP8266
I need to submit HTML form from my remote website to my ESP8266 server using `POST` method. I'm looking for something like that :

```
    <form action="my esp8266 IP" method="POST">
        <input type="text" name="foo" value="go">
        <input type="submit">
    </form>

```

Can I use IP address in `action` attribute? How can I detect and print received data on ESP8266 side?

# Answer
> Can I use IP address in action attribute?

Sure, if your ESP8266 is either on the same internal (behind a NAT router) subnet as your web server, or your ESP8266 has a public IP address.

> How can I detect and print received data on ESP8266 side?

By parsing the data as it comes in through the socket.

If your ESP8266 is on your home network and your website is out on the internet somewhere you will have to arrange some form of port forwarding through your router (outside the scope of this site) and have some way of your website tracking your (most likely dynamic) home IP address. Again, outside the scope of this site.

It is much more common to use protocols such as MQTT or another RESTful API to have your ESP8266 check in with a remote server to request updated data and instructions, rather than a web server blindly pushing the information directly to the ESP8266. This is because:

* Putting your ESP8266 directly (or indirectly through port forwarding) on the internet is a security nightmare, and
* Putting all the pieces of the jigsaw together to make it work reliably is not trivial.
> 0 votes

---
Tags: esp8266
---


# Question
Title: Errors trying to set fuses on bare Atmega328p
I have an Atmega328p on a board that I want to program using an Arduino programmer. I've got the programmer working to program other Arduino's over ICSP header, but when trying to use the same settings to avrdude to read/set the fuses of the bare MCU with oscillator I get the following:

```
❯❯❯ avrdude -v -p atmega328p -b 19200 -P /dev/cu.wchusbserial213240 -c stk500v1                                                                                ⏎ master

avrdude: Version 6.3, compiled on Sep 18 2017 at 20:31:51
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/usr/local/Cellar/avrdude/6.3/etc/avrdude.conf"
         User configuration file is "/Users/viktor/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/cu.wchusbserial213240
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.08s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.08s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.08s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

```

I've checked the soldering as good as I can and it seems to be right. I have a 10K pullup on reset, an oscillator with caps. I'm suspecting I might have fried the MCU when soldering or something - is there anything simple I can check?

* All PWR connections check out
* I've checked the oscillator with a scope and it isn't oscillating, but I'm thinking that is normal since it's a bare chip that I'm trying to set the fuses to use the external crystal? The oscillator is at least connected correctly.

# Answer
> 0 votes
It turned out it was a bit of bad soldering on the MCU. This same msg you'll get if just leaving the ICSP floating.

---
Tags: atmega328, avrdude, oscillator-clock, fuses
---


title: Log vs linear pots and the arduino

text:
# Question
Title: Log vs linear pots and the arduino
I have noticed that when I used a log pot from a guitar amp I found, it gives janky results when using it in a motor PWM sketch, but if I use it in a fade sketch, it works. why does log pots give sketchy results when using them in a PWM control sketch, like when using the `map()` function?

# Answer
There are two associated issues here that underly your problem.

Firstly, with a log pot, you get a period of very small changes in resistance followed by a period of massive changes:

(\* a "commercial" log pot is how log pots are usually manufactured - two linear traces of different resistances back to back).

So when turning you get "not much ... not much ... not much ... lots ... even more ... full".

Now couple that with how a motor works. A motor has a "stall current", which is higher than the "run current" (especially the "unloaded" run current). This is the minimum amount of current required to overcome the inertia of the motor and start it spinning. This is, in effect, a lower threshold on the PWM value that you need to exceed before the motor will begin moving (once it's started moving you can go a little below that threshold and it will still move).

With a linear pot it's easy to get to that threshold and stay around it, increasing slowly above it, etc. However, as you can imagine looking at the curve of the log pot above, if the "flatter" area of the pot is below the stall current threshold of the motor, the motor will do nothing until you are well into the sharper up-turn of the curve. The effect of this is you will go from "stopped" to "quite fast" in one jump. It's very very hard to get even close to the stall current threshold.

For instance, if your motor needs a minimum of 30% duty cycle to start it running, that's about a 160 degree turn on the log pot above, compared to just 70 degrees of a linear pot, and the rest of the log pot's PWM range is compressed into a tight space.
> 4 votes

---
Tags: pwm
---


title: variable doesnt have a type name

text:
# Question
Title: variable doesnt have a type name
Why can't i assign the value to a variable outside the function?

```
void setup(){}
int a;
a=12;   //  WHY IS THIS GIVING ME ERROR
void loop(){
}

```

Why the line `a=12` gives me an error? Thanks!

# Answer
> 3 votes
> a=12; // WHY IS THIS GIVING ME ERROR

Because you can't do assignments like that outside of a function.

You can, though, create *and* assign the variable at the same time:

```
int a = 12;

```

That is a declaration of the variable, whereas

```
a = 12;

```

is a procedural statement. Procedural statements cannot be executed in the global scope. They can only be executed inside a function during the execution of the program (the global scope never gets executed).

---
Tags: arduino-uno, variables
---


# Question
Title: Why Ethernet webclient fails to initiate?
I use the Ethernet shield with an Uno and create a web client. If I put a delay like one second for initialization it works fine. However if I wait for it in a while loop (like waiting for the serial, and as mentioned in Arduino docs) it never gets out of the loop that means the client instance is null.

I found this method on Arduino website in an example code:

```
while(!client) { ; } // waiting to get ready

```

Here's the code; if I uncomment it will stay there. Also the same with providing the MAC argument only.

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

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEE };
char server[] = "www.google.com";    // name address for Google (using DNS)

IPAddress ip(192, 168, 1, 213);

EthernetClient client;

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

  Ethernet.begin(mac, ip);
  delay(1000);
  //while(!client){ ; }
  Serial.println(Ethernet.localIP());
}

```

# Answer
Your `while(!client){ ; }` line can never do anything useful.

It is used to wait for a client socket to connect to a remote port. You aren't connecting to a remote port (that `client` object is doing *nothing*), so how it can never succeed.

It's like saying "Do nothing, and tell me when you're done".

I don't know what you hope to achieve with that line of code...
> 0 votes

# Answer
What you write is not a function but a variable. And the variable will not change its value (unless you have some interrupt and it is a global variable).

so you need to change 'client' to some function you want to call, probably 'client.xxx()' where xxx is the name of the function you want to call (possibly with parameters).
> 0 votes

---
Tags: ethernet-shield
---


# Question
Title: Templated class: How to create instance and work with it?
I have created a class like this:

```
#ifndef MyList_h
#define MyList_h

#include "Arduino.h"

template <typename T>
class MyList {
public:
  MyList(void);
  ~MyList(void);

  void addItem(T* item);

  //more stuff

};

#endif

```

And implementation is like this:

```
#include "Arduino.h"
#include "MyList.h"

template<typename T> MyList<T>::MyList(void) {
  // constructor implementation here
}

template<typename T> MyList<T>::~MyList(void) {
  // desctructor implementation here
}

template<typename T> void MyList<T>::addItem(T* item) {
  // function implementation here
}

// ...more stuff

```

In my .ino Sketch I'm doing this (found this solution in a C++ example):

```
#include "MyList.h"
MyList<word>* list = new MyList<word>(); // global scope
//... more stuff

```

But when compiling, Arduino IDE complains:

> Test.ino:5: undefined reference to \`MyList::MyList()'

I googled a bit and found this alternative way for creating the instance:

```
ArrayList<word>* list;

```

Then there's no error, just compiles file. BUT as soon as I want to use this instance (=adding code) like this:

```
list->addItem(i);

```

compiler complains again:

> Test.ino:25: undefined reference to \`MyList::addItem(unsigned int\*)'

What's wrong? Why is this reference undefined?

I tried another way:

```
ArrayList<word> list; // again global scope

```

But then the compiler also tells me:

> Test.ino:5: undefined reference to `MyList<unsigned
>  int>::MyList()' /tmp/ccp8qmCz.ltrans0.ltrans.o: In function` \_GLOBAL\__sub\_D\_list': /....../Test.ino:5: undefined reference to \`MyList::~MyList()'

So, how can I create an instance of my class that uses a template?

---

Environment: Arduino IDE 1.8.3 (I know, I could update...) + Arduino Nano Board.

# Answer
I think I found the solution:

According to: https://stackoverflow.com/questions/8752837/undefined-reference-to-template-class-constructor

--\> Put all implementation in .h file. That's it. No more compler complains, code runs fine.

I think I have to dig deeper into c/c++ development ...
> 1 votes

---
Tags: arduino-nano, class
---


# Question
Title: Arduino doesn't boot unless I short USB pin 1-2 (VCC/Data -)
I've made my own AVR programmer with an Arduino Nano V3 clone. It has been working fine, but yesterday I was trying to program a faulty board that pulled too much current. Was powering via USB and my OSX laptop told me it had disabled it due to pulling too much power.

After that I couldn't power it anymore, not even from a simple phone charger. I thought I had burnt something, but when testing with a DVM I accidentally shorted pin 1 and 2 of the USB connection:

1 - (red) VDC / plus / +5V

2 - (white) Data -

Then it boots up and is powered as long as I have them connected. Without it wont start with any usb connection, laptop or phone charger. Just to show what I mean:

https://photos.app.goo.gl/rtFj6bp3j4SbuYKr1

Why is this and is there something I can do to save this Nano - it seems to be working fine when usb is shorted like this…

Would hate to have to build up another one while waiting for a new programmer from China :)

# Answer
> 1 votes
When you plug the board in, the computer enumerates it. The normal device descriptor (IIRC) requests 50mA. If you are (as you most likely are) drawing more than that then the computer is quite within its rights to turn it off.

By shorting those pins you are preventing it from enumerating, so the computer doesn't know the requested amount, so it assumes (probably) 500mA.

You can achieve the same effect by using a cable with no data wires in it.

# Answer
> 0 votes
It's possible you've blown the voltage regulator. If you happen to have a source of those, like another dead Nano, you can try replacing it to see if that works.

Shorting the +5 to data is likely going to destroy your computers USB controller, so please quit.

---
Tags: arduino-nano, usb, programmer
---


# Question
Title: Sharing serial Rx to read a push button on ESP8266-01
I'd like to know if it's possible, and if so how to use the serial Rx pin in a shared way to read a push button?

I've seen people using it in sort of a dedicated way but my idea is to use it dynamically. Which means it would stay as a standard Rx pin, with a push button sharing it. So the question is, what would happen if the push button was pressed? Would it be possible to detect it from the Rx stream?

# Answer
> 3 votes
I have experimented with my NodeMCU (ESP8266-12F, but the core chip is the same ESP8266EX).

First, the theory: UART is a asynchronous serial protocol. It has a configuration which consits of the baud rate (bits per second), parity bit (enabled or not) and number of stop bits (between 1-2). A common configuration is "9600N1", meaning 9600 bits per second, **n**o parity bit, 1 stop bit.

If you want to trasmit the bitstring `0101 0101` with no parity, 1 stop bit, the RX line voltage will be:

RX line idles in high state (for us: 3.3V). Transmission is started by the start bit, which means that the line is pulled LOW. Then, the bits are transmitted LSB to MSB, followed by parity (if enable) and the stop bits.

I wrote the sketch

```
#include <Arduino.h>

void setup() {
    //use 300 Baud, lol
    Serial.begin(300);
}

void loop() {
    if(Serial.available()) {
        char readChar = (char) Serial.read();
        Serial.println("Read char: " + String(readChar) + " hex " + String((int)readChar, HEX));
    }
}

```

When transmitting a normal "A" (binary: `0100 0001`) over serial, it looks like this in a logic analyzer:

When I connected a pulled-up button the RX line and press, the signal goes as

As one can see, the analyzer sees the pushing down of the button as a start bit, but the timing is way of. The line is pulled back to high much later. The time slot for the stop bit (which must be *1*) was missed, so the logic analyzer displays "FRAMING ERROR". But the UART circuit inside the ESP8266 doesn't seem to care. It reads this as the transmission of a byte of the value "0x00".

Serial output: `Read char: hex 0`

So, in response to the question "what would happen the push button was pressed?" we can say: At this speed of 300 baud (lowest possible setting), the UART received a bogus transmission but still reads it as an incomming `0x00` byte. However, depending on the bouncing of the signal due to the button presses, other received byte values might well be possible. You could be able to de-bounce the button to make the signal more stable, timing wise.

Anyway, you should not make a push button act as a crude UART transmitter if it isn't the absolute last possible solution. Depending on your application, you might be able to use the solution from this question and switch the function of the TXD0 and RXD0 to GPIO (more info). If you know exactly when to expect a button push, switch the pins to GPIO mode before and poll the status of the button (or install an interrupt).

However, as a bottom line: If you have no idea when the button will be pushed, then you will be fundamentally unable to distinguish the cause of the RX line falling low at the time the transition happens. It could be the transmission of some actual data (maybe also the zero-byte), but it could have also been the button.

A I²C GPIO port expander like the MCP23017 (link) would make much more sense, especially if you already have an I2C bus. There are also SPI devices available for this.

---
Tags: serial, esp8266, button, rx-pin
---


# Question
Title: Arduino Uno and Arduino Yun software. Which version of the IDE works with both best?
I have been working with Unos and just started working with Yun. I have 1.86 currently installed but the Yun starts up saying to use 1.5.6-r2 Beta IDE. Should I uninstall 1.8.6 and install 1.5.6-r2?

Thanks for your help.

Lisa

# Answer
The Yun startup was written when the normal IDE didn't support the yun, so you had to use a release candidate of a future version.

Those days are long gone.

Always use the latest version of the IDE.
> 1 votes

---
Tags: arduino-yun, software
---


# Question
Title: Getting "avrdude:stk500_recv(): programmer is not responding" while uploading sketch to Arduino Pro Mini
I recently bought an Arduino Pro Mini(3.3V 328p, 8MHz) along with a CP2102 USB to TTL UART convertor. When I try to upload a sketch to the Pro Mini using it, I get a `avrdude:stk500_recv(): programmer is not responding` error. My connection was like

```
Arduino pro mini                CP2102
TXO  ----------------------------> TXD
RXI  ----------------------------> RXD
VCC  ----------------------------> 3V3
GND  ----------------------------> GND
DTR  ----------------------------> DTR

```

I tried inter-connecting the TXO and RXI pins and had no luck. Also pressing and releasing the reset button on the Pro Mini doesn't seem to work either. I also tried programming it with my Arduino Uno, by removing the 328 and connecting correspondingly. Still no use.

Does any one have any ideas?

# Answer
> 6 votes
rx -\> tx
tx -\> rx

Please check your connections.

# Answer
> 2 votes
I had the same problem and I used a magnifying glass to check the processor. I bought my clones off of eBay and they are using the ATMega168 (3.3V, 8 MHZ) processor. Once I realized my mistake and switched to the correct processor version, the upload was seamless.

I'm using an "FTDI FT232RL USB to TTL Serial Converter Adapter Module 5V and 3.3V For Arduino" for the programming connection, with

* DTS-DTS;
* Rx-Tx;
* Tx-Rx;
* VCC-VCC;
* GND-GND, and;
* GND-CTS.

I didn't even need to use the "reset" workaround of holding down the reset button before pressing the upload button and releasing when the words "Maximum is ..." appear in the output window.

# Answer
> 1 votes
In the Arduino IDE for my Pro Mini I have to select the board: "Arduino Deumilanove or Diecimila"

I'm not sure why this is or if this could cause any potential damage to your Pro Mini but I do know for sure this is the solution I used to program my pro mini and it works every time.

# Answer
> 1 votes
Change baudrate to

```
UPLOAD_RATE=57600

```

in `Makefile` (or via the GUI). I have seen your error many times and this fixes it, albeit on the 5V/16MHz mini USB variant. If 57600 does not work, try other values. I use this rate on my USB serial - may be different on bare Rx/Tx pins.

You have probably not messed up your bootloader, that is rarer than people think. I think your Arduino has some invalid code running, and it keeps resetting until it finds valid code - when I had that problem, I pressed reset just before punching enter for 'make upload'. Even if it does that, you've got perhaps 0.5s to initiate an upload after reset.

Do correct me if I'm wrong.

# Answer
> 1 votes
1. Check connections, make sure RX-TX lines are crossing over.
2. **Arduino** -\> **Preferences** -\> **Show verbose output during** \- check **upload** will give you better visibility what is happening.
3. When Arduino says "Uploading..." briefly press reset. The upload should start.

But one thing that helped me was... try different USB-UART adapter. For some reason the one which looked like (and was) cheap knockoff worked like a charm.

As a general advice, when sourcing parts from Chinese manufacturers I learned to be redundant - I usually order a bit more than I need and from mixed sources.

# Answer
> 0 votes
If this is a cheap clone it may be that there is no bootloader installed. You might try using a programmer or an Arduino as ISP to reprogram the device if this is the case. Using ISP programming will avoid any problem with serial connections as it is using SPI wiring instead and the Arduino IDE allows you to load the necessary bootloader using this method to enable programming over serial. You will need either an ISP programmer or another Arduino however.

# Answer
> 0 votes
You should try another USB port, install the right drivers for the TTL/uart chip and reboot your PC. That worked for me.

---

Also, you should consider getting an arduino nano usb, these have an built in ttl/uart converter, ICSP header and can be placed on a breadboard easily.

# Answer
> 0 votes
The problem is crystal clear in the picture

---
Tags: arduino-ide, arduino-pro-mini
---


# Question
Title: Bluesmirf Mate Silver (RN-42) enter command mode when in HID mode
I am having problems getting the Bluesmirf Mate Silver (RN-42) into command mode once I have switched to HID mode. I have bought a second new Bluesmirf Mate Silver to confirm my issue.

I soldered the Bluesmirf and connecting to Arduino Uno. I used the ‘Example code: Using Command Mode’ from https://learn.sparkfun.com/tutorials/using-the-bluesmirf to successfully enter command mode.

I then entered the following commands in command mode (leaving out the comments):

```
SM,5   // Mode = 5, (any) Auto reconnect
SA,2   // Authentication Mode 2 (SSP, "just works" mode)
S-,myName  // // Set BT Name, This short name with no spaces is Picked up ok on windows
S~,6   // Enable HID on reboot
R,1    // Reboot to lock in perameters

```

Next I use a PC and pair with the bluetooth ‘keyboard’ I have created above. I am able to use the Bluetooth and Arduino sketches to write into notepad on the bluetooth connected PC.

However now I cannot get back into command mode to make changes to the Bluesmirf config. Trying to use the example code above I can see ‘`$$$U,9600,N`’ typed into notepad on the connected PC each time I load the sketch, rather than being used to enter command mode.

How do I get back into command mode after HID mode has been triggered.

# Answer
> 1 votes
I believe that the problem is caused by the mode I entered. According to the datasheet on pg 10 Auto-Connect Master Mode (SM,3) enters high speed mode and this `connection cannot be broken via commands or software break characters`. It goes on to explain that both Auto-Connect DTR Mode (SM,4) and Auto-Connect ANY Mode (SM,5) (which I used) function like Auto-Connect Master Mode (SM,3), so I guess that in these modes the `$$$` escape characters cannot be used to enter command mode either.

I was able to resolve this by performing a hard factory reset on the Bluesmirf Mate Silver (RN-42). I previously tried following a couple of you-tube tutorials that weren't very clear and didn't have any success. I looked at the instructions in this thread titled 'Factory Reset the RN-41 or RN-42' to get me on the right lines.

This worked for me:

1. Connect the Bluesmirf Mate Silver GND pin to GND and disconnected all other pins
2. Connect a wire to 3.3v on Ardunio
3. Load the Ardunio with an empty sketch, and keep it powered on
4. Touch the 3.3v wire repeatedly (3+ times) to the GPIO4/PIO4 connection hole on the Bluesmirf. This is a third of the way down one edge of the board.
5. Factory reset should now be complete - note I didn't see any indication lights during this process.

Then I could wire up the Bluesmirf as normal and use ‘Example code: Using Command Mode’ from https://learn.sparkfun.com/tutorials/using-the-bluesmirf to successfully enter command mode.

---
Tags: arduino-uno, bluetooth, keyboard
---


# Question
Title: Creating a simple menu for Arduino LCD button shield
I am trying to create a very simple menu to use with my lcd keypad shield, I have tried looking into how tutorials say to do this but I don’t really understand them.

Would it be possible to do it by doing something like creating an integer I.e menuTotal, that depending on the what the value of menuTotal is a menu item would display, then have the the up and down buttons add or subtract 1 of the menuTotal value.

Any help you can give would be greatly appreciated.

Liam

# Answer
> 2 votes
Your approach of holding the "current" menu selection and incrementing or decrementing upon external input (button press) is a sound approach.

Consider writing a `drawMenu()` function that draws the screen, based on the current menu. In your program, keep a `bool updateScreen` variable. Then, any time you get an external input that would change the screen, set the `updateScreen` variable to `true`. The actual `drawMenu()` function, after drawing the screen, should reset the `updateScreen` variable back to `false`.

In your `loop()` function, have a section like:

```
loop() {
  // [... other code ...]

  if (updateScreen) {
    drawMenu();
  }

  // [... other code ...]
}

```

In this way, the screen is updated when necessary, and your main loop can keep running, processing input, etc.

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


# Question
Title: Output works on UNO Pin 13, but not on 2?
I am experimenting with IR receive and transmit (basically I want my IOT to be able to turn on the TV, satellite receiver, and set the channel - yes, I am really that lazy).

I can receive and record the remote codes, and I can transmit the codes to an IR LED.

Now for the puzzle. I originally had my IR LED on Pin 13, but to clean things up I moved the output to pin 2 and changed the pin assignment in the sketch. Now it doesn't work. My phone camera shows that the IR LED is pulsing as before, but the appliance code is not working. Moving back to pin 13 and it works again.

So, what could be different between pins 13 or 2? I know that Pin 13 has the built-in LED but since I am setting it to output that shouldn't make a difference.

I am bit-banging to create the 38kHz pulses to the IR LED, so I am wondering if there is a latency difference from pins 2 and 13?

The sketch, since I know someone will ask for it:

```
int IRledPin =  13;
int buttonPin = 4;

void setup()   {
  pinMode(IRledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  digitalWrite(buttonPin, HIGH); // pullup
  Serial.begin(115200);
}

void loop()
{
  if (! digitalRead(buttonPin)) {
    // button down
    Serial.println("Sending IR signal");
    SendCode();
  }
}

// This procedure sends a 38KHz pulse to the IRledPin
// for a # of microseconds.
void pulseIR(long microsecs) {
  // we'll count down from the number of microseconds we are told to wait

  cli();  // this turns off any background interrupts
  while (microsecs > 0) {
    // 38 kHz is about 13 microseconds high and 13 microseconds low
    digitalWrite(IRledPin, HIGH);  // this takes about 3 microseconds
    delayMicroseconds(10);         // hang out for 10 microseconds
    digitalWrite(IRledPin, LOW);   // this also takes about 3 microseconds
    delayMicroseconds(10);         // hang out for 10 microseconds
    // so 26 microseconds altogether

    microsecs -= 26;
  }
  sei();  // this turns interrupts back on
}

void SendCode() {
  // This is the code for my FIOS FF
Serial.println("FIOS- FFwd");
  pulseIR(9220);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(4560);
  pulseIR(520);
  delayMicroseconds(4560);
  pulseIR(540);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(4560);
  pulseIR(520);
  delayMicroseconds(4560);
  pulseIR(540);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(520);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(520);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(4560);
  pulseIR(520);
  delayMicroseconds(4560);
  pulseIR(540);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(22320);
  pulseIR(9200);
  delayMicroseconds(2240);
  pulseIR(540);
  delayMicroseconds(24664);
  pulseIR(9220);
  delayMicroseconds(2240);
  pulseIR(540);
  delayMicroseconds(24684);
  pulseIR(9200);
  delayMicroseconds(2260);
  pulseIR(520);
  delayMicroseconds(24684);
  pulseIR(9200);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(24664);
  pulseIR(9220);
  delayMicroseconds(2260);
  pulseIR(520);

}

```

# Answer
```
void SendCode() {
  // This is the code for my FIOS FF
  Serial.println("FIOS- FFwd");
  pulseIR(9220);
  delayMicroseconds(4540);

```

Personally I would be putting the `cli()` around everything in `SendCode` (apart from the Serial.println) because the serial print will cause interrupts, and they could occur between successive function calls there.

I checked your code using IDE 1.6.9 and got this pulse width for pin 2:

And this pulse width on pin 13:

You'll notice they are virtually identical and that neither show a frequency of 38 kHz. The measured period of 30.71 µs gives a frequency of 32.563 kHz.

Unless your version of the compiler generates different code than mine, I suggest you need to tweak your timing loops.

> I am wondering if there is a latency difference from pins 2 and 13?

No, I think not. The problem may be elsewhere, such as electrical. I suggest you try to measure the frequency of your timing loops using whatever external equipment you have to hand. For example, just call your pulseIR function constantly and measure with a frequency meter. I measured 32.555 kHz on my meter, for example.

---

## Use a timer to generate 38 kHz

You will get a more accurate 38 kHz signal if you use the hardware timers, properly configured. For example:

```
const byte LED = 10;  // Timer 1 "B" output: OC1B
const byte buttonPin = 4;

// Clock frequency divided by 38 kHz frequency desired
const long timer1_OCR1A_Setting = F_CPU / 38000L;

void setup()   {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode (LED, OUTPUT);
  Serial.begin(115200);

  // set up Timer 1 - gives us 38.005 kHz
  // Fast PWM top at OCR1A
  TCCR1A = bit (WGM10) | bit (WGM11);                // fast PWM
  TCCR1B = bit (WGM12) | bit (WGM13) | bit (CS10);   // fast PWM, no prescaler
  OCR1A =  timer1_OCR1A_Setting - 1;                 // zero relative
  OCR1B =  timer1_OCR1A_Setting / 2 - 1;             // duty cycle
}

void loop()
{
 if (! digitalRead(buttonPin)) {
    // button down
    Serial.println("Sending IR signal");
    SendCode();
    delay (200);
  }
}

// This procedure sends a 38KHz pulse to the IRledPin
// for a # of microseconds.
void pulseIR(const unsigned int microsecs) {
  TCCR1A |= bit (COM1B1); // clear OC1B on compare
  delayMicroseconds (microsecs);
  TCCR1A &= ~bit (COM1B1); // don't clear OC1B on compare
  digitalWrite (LED, LOW);
}

void SendCode() {
  // This is the code for my FIOS FF
  Serial.println("FIOS- FFwd");
  noInterrupts ();
  pulseIR(9220);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(4560);
  pulseIR(520);
  delayMicroseconds(4560);
  pulseIR(540);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(4560);
  pulseIR(520);
  delayMicroseconds(4560);
  pulseIR(540);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(520);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(520);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(4560);
  pulseIR(520);
  delayMicroseconds(4560);
  pulseIR(540);
  delayMicroseconds(4540);
  pulseIR(540);
  delayMicroseconds(22320);
  pulseIR(9200);
  delayMicroseconds(2240);
  pulseIR(540);
  delayMicroseconds(24664);
  pulseIR(9220);
  delayMicroseconds(2240);
  pulseIR(540);
  delayMicroseconds(24684);
  pulseIR(9200);
  delayMicroseconds(2260);
  pulseIR(520);
  delayMicroseconds(24684);
  pulseIR(9200);
  delayMicroseconds(2260);
  pulseIR(540);
  delayMicroseconds(24664);
  pulseIR(9220);
  delayMicroseconds(2260);
  pulseIR(520);
  interrupts ();
}

```

This sets up Timer 1 to output 38 kHz, and then for the timing of the pulses you just turn its output on and off.

Note that you have to use D10 on your Uno because that is where Timer 1 outputs to.

---

For more information see my page about timers.

I have a graphic which shows a lot of the useful registers:
> 4 votes

---
Tags: arduino-uno
---


title: Expanding analog inputs to the Arduino

text:
# Question
Title: Expanding analog inputs to the Arduino
I need the Arduino to read about 100 analog inputs. Is this even doable? If not what is the maximum analog inputs I can read into the Arduino (The maximum non trivially would be to use the analog pins that the board already provides).

But can I expand those out? Thanks!!

# Answer
Expanding on part of Majenko's answer, you can use an analog multiplexer like the 74HC4051 to turn one analog port into 8.

Its cousin, the 74HC4067, will multiplex 16 ports. Now with 6 analog inputs on the Arduino Uno, you could have 6 x 16 inputs = 96. The A/B/C controls signals could be paralleled up.

This would let you handle 96 inputs with only 6 extra chips, and pretty simple code. I have code examples on my page about 74HC4051 multiplexer / demultiplexer.

For 8 inputs the code is:

```
// Example of using the 74HC4051 multiplexer/demultiplexer

// Author: Nick Gammon
// Date:   14 March 2013

const byte sensor = A0;  // where the multiplexer in/out port is connected

// the multiplexer address select lines (A/B/C)
const byte addressA = 6; // low-order bit
const byte addressB = 5;
const byte addressC = 4; // high-order bit

void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Starting multiplexer test ...");
  pinMode (addressA, OUTPUT);
  pinMode (addressB, OUTPUT);
  pinMode (addressC, OUTPUT);
  }  // end of setup

int readSensor (const byte which)
  {
  // select correct MUX channel
  digitalWrite (addressA, (which & 1) ? HIGH : LOW);  // low-order bit
  digitalWrite (addressB, (which & 2) ? HIGH : LOW);
  digitalWrite (addressC, (which & 4) ? HIGH : LOW);  // high-order bit
  // now read the sensor
  return analogRead (sensor);
  }  // end of readSensor

void loop ()
  {
  // show all 8 sensor readings
  for (byte i = 0; i < 7; i++)
    {
    Serial.print ("Sensor ");
    Serial.print (i);
    Serial.print (" reads: ");
    Serial.println (readSensor (i));
    }
  delay (1000);
  }  // end of loop

```
> 7 votes

# Answer
There are two methods of doing what you want:

1. Add more ADC channels
2. Multiplex the existing ADC channels

SPI or I2C ADC chips are readily available in a range of resolutions, sampling speeds and number of channels. They are fairly simple to add to any Arduino.

For instance the MCP3208 will give 8 channels of 12-bit resolution on SPI, which means 3 pins (MOSI/MISO/SCK) + 1 per chip (SS). So 1 chip would be 4 pins, 2 chips 5 pins, 3 chips 6 pins, etc.

Adding lots of chips to the SPI bus though can itself be troublesome with the increased capacitance of all those inputs meaning you have to reduce your communication speed somewhat or add extra buffering to drive the bus with more current.

I2C chips can be harder to have lots of them since there are only a limited number of addresses on an I2C bus - plus on many Arduinos the I2C is also two of the analog pins, which you may not want to sacrifice.

The second option involves using analog multiplexers (eg the 4051) to switch different sources in to the existing analog inputs.

A third option which you probably haven't considered is to have multiple arduinos (or other low-cost microcontrollers) each doing some of the sampling and then implementing some kind of communication method between them (or to a single master). This has the added advantage that it's then possible to sample multiple channels at once (one per microcontroller) speeding up your operation somewhat.
> 6 votes

# Answer
I have been exactly working with the same Issue. I need a program that reads 100 Thermistors...Why? well, some times you need it.

I kinda finished that already.

I tried the 74HC4051 multiplexer / demultiplexer. But, for some reason I didn't get the desired result.

First thing you will find...POWER, you will need an external power supply, in my case I just made a voltage divider and connected the thermistor to that power, then just use the Analog port for reading...

I use I2C protocol, 8 arduino Mega 7 slaves and One master. and since send send Integer, float, and blah, blah was kinda not helping I just made it for It can send the Analog reading over I2C and the master makes all the desired conversion.

If you still are interested, I can send you the source code for master and slaves. With this template you can connect up to 50 arduinos and the master will look for every arduino connected in the network and ask for data.

Regards
> 1 votes

---
Tags: adc
---


title: Time remaining with os_timer_t

text:
# Question
Title: Time remaining with os_timer_t
The Ticker library for the ESP chips is quite useful, which wraps a `os_timer_t` object. I'd like to be able to see the time remaining on the timer, is it possible to do that witha `os_timer_t` object?

# Answer
The library just calls `os_timer_setfn` and `os_timer_arm` which will call the callback function after some time. To add the feature to see how many remaining time there is, you would need to extend the library (the `Ticker` class, specifically) to save a timestamp when the timer was started. You can then write a function which returns for how much time is remaining or has passed by doing `uint32_t remaining = timestamp_now() - timestamp_started`.

A good function to hook would be the `_attach_ms` in Ticker.cpp. Add a `uint32_t timestamp_started` variable in the `Timer.h` header for the class. Then set `timestamp_started = system_get_time()` (from `user_interface.h`). Then write a function `uint32_t remainingUs() { return system_get_time() - timestamp_started; }`. Beware of integer overflows -- `system_get_time` returns passed microseconds since µC startup.
> 2 votes

---
Tags: esp8266
---


# Question
Title: Using millis() to time the start / stop of a DC motor
I'm trying to use a DC motor with pinion engaged to a rack gear, and have that motor move a distance, save the distance, delay, reverse, and travel back the same distance from where it started, delay, do it again. I want to start/stop the initial save with a button push, then from those saves, loop the motor movement.

I have considered using a Hall effect sensor or reed switch to count, but it seems a software interrupt or timing is easier using `millis()`. I researched and found that `millis()` cannot be reset, so I'm wondering if this is possible.

I haven't started a sketch, but I got this idea from the BlinkWithoutDelay example sketch included with the Arduino IDE. Like, have the motor positioned at "home" position, button push, start the timer, motor travels to end of work piece, stop the timer, save that forward distance traveled into a variable, reverse the motor, (at this point the timer would be at 0 again for the reverse travel) travel back to "home" save that reversed distance traveled into another variable with a button push, and then use these start/stop values in a loop. So I would save the values with a button pushes, then just loop that.

Or I'm thinking about putting an if or while button push outside the loop with a nested `counter++`, eyeballing the motor travel, once it gets to where I want it, save those counts in variables, then using them in the loop to `analogWrite()` to the motor.

# Answer
You can't reset the `millis()` function, but you can count the amount of milliseconds and stop when necessary: beware though, the positioning might not be as precise as you wish and you have to consider the error will accumulate on the long run.

Nonetheless here is the code:

```
uint16_t duration;
bool direction = true;
void loop() {
  if (duration != 0 and !buttonPressed()) {
    // running back and forth if setup and no "finish" button detect
    uint16_t start = millis(); // reset the timer
    startMotor(direction);
    while (millis() - start < duration && !buttonPressed()) {
      ; // keep going
    }
    direction = !direction; // reverse direction
  } else if (duration == 0) {
    // your motor positioning setup
    while (!buttonPressed()) {
      ; // wait for button to start positioning
    }
    uint16_t start = millis(); // ask for time
    startMotor(true); // run the motor cw
    while (!buttonPressed()) {
      ; wait for button to end positioning
    }
    duration = millis() - start; // store duration
    direction = false; // reverse motor direction
    // next time loop() is executed the motor will go back to home
  }
}
bool buttonPressed() {} // define this to determine if the button has been pressed, safer if you use an interrupt
void startMotor(bool cw) {} // define this to run your motor clockwise or counterclockwise

```
> 1 votes

---
Tags: millis
---


title: What does drawmenu() mean

text:
# Question
Title: What does drawmenu() mean
Can anybody tell me what drawmenu() means, I got an answer on here that has the term on and I don’t quite understand it, I’m very new to this.

Any help you can give will be greatly appreciated.

Liam

# Answer
I gave you that particular answer

The function `drawMenu()` has no meaning. I was suggesting that you **create** a function with that name, whose action is to write text to the LCD with your selected menu item. The name of the function is not relevant. It does not exist until you create it.
> 2 votes

---
Tags: arduino-mega, programming
---


# Question
Title: How well will the Arduino Uno survive in a vacuum?
Im doing some experiments with Pocketlab and Arduino, Vacuum will get to around -30inHg. I tried with my raspberry pi and it just kept dying everytime a vacuum was pulled. The only problem I can image is the arduino heating up.

# Answer
Interesting question. You're right- heat is your enemy. Given the power dissipated by a Pi even when idle I'm not surprised it died. Most chips depend on convection to get rid of heat. A loaded Pi might require a (convective) heat sink and/or fan to keep it's core temperature down to an acceptable level, and that's at normal pressure and temperature. An Arduino -might- be able to work in a vacuum- it can lose some of it's heat through lead conduction- it'll only draw ~.25 watts normally vs 2.5 watts plus for a loaded Pi.

Ultimately it will depend on your application. If you have idle time when you can put the Arduino to sleep that will help keep it cool. If you have a conductive heat sink you can use then that would certainly help.
> 4 votes

---
Tags: arduino-uno
---