# Question
Title: Confusion with storage of declared variables and volatile
I read that **volatile** is used when we want to store variables in SRAM.

But aren't all the variables in a code are stored in SRAM anyway?

And what makes it an advantage sometimes for variables(like volatile) to be stored in SRAM?

# Answer
> 4 votes
That's just plain incorrect.

The `volatile` keyword tells the compiler that the value of that variable may change at any time, and that therefore it must re-read the value every time you use it in your code.

If you don't use `volatile`, the compiler may choose to make an optimisation.

Consider this code:

```
int b = 7;
a = b + b;

```

The compiler can see that 'b' is always 7 -- it is assigned the value 7 and nobody ever changes it. The compiler may choose to optimise this to the equivalent of

```
a = 14;

```

But if you do this:

```
volatile int b = 7;
a = b + b;

```

then the compiler MUST read `b` twice from memory.

Why would you want to do that? Perhaps you have an interrupt which might change the value of `b`. Perhaps your interrupt changes the value of 'b' every time you press a button. You need the code to really check the value of `b` every time it calculates `a`, and not rely on it always being 7.

Here is a fuller explanation.

# Answer
> 1 votes
Technically, variables can be stored anywhere, in SRAM, eeprom or enev flash.

However, without doing anything special, variables are stored in SRAM.

Thee votike attribute is just that, it tells the compiler that the variable could change its value and the compiler shouldn't assume that values obtained from prior access is valid now. This forces the compiler to re-read the variable on demand.

---
Tags: sram
---


# Question
Title: Where is Arduino.h on a Mac? Can I download a copy if missing?
I have installed the IDE on a Mac. It works great. I want to use Eclipse as an editor only. Some files I have include "Arduino.h". Where is this file? I cannot find it.

If it is built in to the tools can I download a copy of this file(s)?

# Answer
> 3 votes
On a Mac the Arduino.h file is within the Arduino application itself. It's not that easy to get to without resorting to the command line.

You also need far more than just Arduino.h - you need the entirety of the Arduino AVR core, which is a collection of .h, .c and .cpp files. They are all together in the application.

You would probably be best off getting them from the github repository (https://github.com/arduino/Arduino) - the files you need are all under `hardware/arduino/avr`

On your Mac you may find them as `/Applications/Arduino.app/Contents/Resources/hardware/arduino/avr` or somewhere similar (not entirely sure where it puts it within the app).

# Answer
> 0 votes
I've don't have a Mac, so I can't test this, but on the Arduino Forum they say find the file `Wiring.h` and create an empty file called Arduino.h in the same folder.

I don't know if that's the right approach, but it should get you to the next error, which may well be some system constant is not defined. If it does work you could go to github for the IDE (don't know exactly where that is) and download `Arduino.h` from there and stick it alongside `Wiring.h`.

# Answer
> 0 votes
Generally, if you need to find a file you can open a terminal and type

```
locate myfile.dat

```

This looks in a database (rather than searching the disk), which you may need to update by typing

```
sudo updatedb                       // on linux
sudo /usr/libexec/locate.updatedb   // on Mac

```

# Answer
> 0 votes
There simply is no "Arduino.h" file. Basically there are multiple platforms (the most common in Arduino world is the Arduino AVR platform). Each platform can contain multiple cores (but mostly only contains 1) and each core contains a "Arduino.h" file.

So to find the Arduino.h file you need to identify the board. The board gives you the platform and the core. Based on those the Arduino.h file is in the folder \[platform installation folder\]/cores/\[core\].

The \[platform installation folder\] is dependent on how the platform was installed on your system. For instance arduino avr comes with the Arduino IDE and as such it is installed in the app like majenko explained.

If it is installed by the boards manager on Linux, the Arduino IDE uses `~/.arduino15/packages/[provider]/hardware/[architecture]/[version]` and if I'm not mistaken the same location is used on Mac.

You can also point to a folder location where additional hardware is installed.

A word on Eclipse and Arduino. There are quite a few options to run compile Arduino sketches in Eclipse. Depending on the tool it goes from easy to pretty complex.

I personally advise to use Sloeber from sloeber.io as I am the developer.

---
Tags: mac-os, eclipse
---


title: Teensy lc linker script question

text:
# Question
Title: Teensy lc linker script question
I am under the impression that the origin of RAM on a Cortex M is 0x20000000. However, in the linker file for it, the ORIGIN of RAM is set to 0x1FFFF800. Is that an error, or is there a reason for the discrepancy?

# Answer
> 2 votes
The Cortex M does not "have RAM at 0x2000000". The Cortex M is just a CPU. It is down to the chip manufacturer where they choose to place RAM in the memory map.

In the case of the MKL26Z64VFT4 used on the Teensy LC:

> The on-chip SRAM is a single contiguous block split into two ranges: 1/4 is allocated to SRAM\_L, and 3/4 is allocated to SRAM\_U. Regardless of the block size, the SRAM is implemented such that:
>
> * SRAM\_L is anchored to 0x1FFF\_FFFF and occupies the space before this ending address.
> * SRAM\_U is anchored to 0x2000\_0000 and occupies the space after this beginning address.
>
> Valid address ranges for SRAM\_L and SRAM\_U are then defined as:
>
> * SRAM\_L = \[0x2000\_0000–(SRAM\_size/4)\] to 0x1FFF\_FFFF
> * SRAM\_U = 0x2000\_0000 to \[0x2000\_0000+(SRAM\_size\*(3/4))-1\]

Since there is 8kB of SRAM, 2kB is below 0x2000000 and 6kB is above 0x20000000. 2kB is 0x800. 0x2000000 - 0x800 = 0x1FFFF800.

---
Tags: teensy
---


title: Mains-Frequency Clock Library

text:
# Question
Title: Mains-Frequency Clock Library
I have an arduino thing, and the hardware I plan to connect to it (a triac zero-crossing based dimmer) provides a synchronization signal from the mains power phase it connects to.

Main power does of course vary some from the nominal 60Hz, however the exact frequency gets adjusted over the course of the day to ensure there are almost exactly 5184000 cycles per day and pretty much exactly 36288000 cycles per week, and is used by mains-powered wall clocks to keep time.

Since my application will need to keep accurate time-of-day across weeks or months without adjustment, it would be advantageous to be able to use this time source.

I can of course write my own code to increment a counter every time the arduino receives a pulse, but if a library that can handle this already exists, I would prefer to use that, in particular since then I won't have to write code to track days and months, handle DST, or any of that stuff.

What libraries exist (if any) to handle timekeeping based on a fixed-pulse-rate input source?

# Answer
Counting the pulses is child's play and doesn't need a library (hint: use an interrupt input and increment a counter). From that count you can use TimeLib.h to convert seconds since 01/01/1970 to an actual time. Or just do simple division to convert seconds (`count/50`) into minutes, hours, whatever division you want.
> 1 votes

---
Tags: library, time
---


# Question
Title: Do I need to use the PWM pins in order to control brushless motors Arduino Uno?
I am building a quadcopter with this schematic:

It works very good but i have the pins on 3,5,6,9 = PWM pins. Is it possible to use "regular" pins instead? I will add more modules later on so i will most likely run out of PWM pins.

I could of course try it right now but i want to ask first so i could potentially avoid to destroy any items!

# Answer
No, you need to use PWM in order to control the ESCs which, in turn, control the motors. If you need more PWMs you might add daugtherboard based on other ICs which might provide additional PWM outputs via I2C or serial interface.

In some non critical conditions (ESCs **are** critical for a quadcopter) you can simulate PWM by switching a plain digital pin HIGH and LOW very quickly, but that is not as reliable as using hardware PWM.
> 2 votes

---
Tags: arduino-uno, motor, drone
---


# Question
Title: Wiring a potentiometer to control a 9V battery powering 2 LEDs in series
I am trying to build an array of LEDs where their brightness is controlled by a potentiometer. The LCD will display the percentage of brightness based on the potentiometer. I am able to successfully control the brightness of a circuit with only one LED. However, I am having trouble with 2 two LEDs in series (which are in parallel with other sets of 2 LEDs in series). And I believe the problem is that the Arduino is only supplying enough voltage to power one LED (maybe \< 5V). How can I properly wire a 9V battery to this circuit in which the potentiometer can control the amount voltage coming from this battery? Are Arduinos only capable of controlling \<5V with a potentiometer?

Here is my code:

```
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int potPin = A0;
int ledPin = 6;
int potValue = 0;

void setup() {
  pinMode(potPin, INPUT);
  pinMode(ledPin, OUTPUT);
  lcd.begin(16, 2);
  lcd.print("Potentiometer");
}

void loop() {
  potValue = (analogRead(potPin)/10.02);
  analogWrite(ledPin, potValue);
  lcd.setCursor(0,1);
  lcd.print(potValue);
  lcd.print("%");
  delay(100);
  lcd.print(" ");
  delay(1);
}

```

And here is a picture of my circuit setup:

# Answer
Yes, Arduino is a 5V microcontroller, meaning it can directly control 5V circuits only. You might incur in problems also trying to deal with 3.3V circuits, even if Arduino is pretty friendly to 3.3V counterparts.

That does not mean though you cannot control higher voltage circuits, just not directly. Actually if anything above 6V is connected to an Arduino PIN you will blow that pin and potentially others which are logically connected within the MCU, so be aware.

To control higher voltage circuits you have multiple options, in your case you are probably interested into using a BJT transistor, an 2N2222 might do.

simulate this circuit – Schematic created using CircuitLab

Please note the values of R1 and R2 must be adjusted to the LEDs you are using depending on their Vf (forward voltage drop) and the maximum current you want to provide.
> 3 votes

---
Tags: led, lcd, potentiometer
---


# Question
Title: Arduino can't find my custom library: fatal error, Motor.h not found etc
I have been working on a project building a robot and using my own custom-built libraries to control it. However after converting all my old code into libraries Arduino can't find them.

Everything thing I have seen says to save them in the 'libraries' folder in with the sketches in MyDocuments and to reboot the Arduino Environment so it will recognize them.

Did that.

It even recognizes them in the sketch menu as libraries that can be imported. However, when I click on them to be included, a new blank line is entered into the sketch instead of an include statement. Perhaps this is some clue? I am really out of ideas at this point as to what I have done wrong.

# Answer
I wanted to vote for the answer from trpropst, but I don't seem to be authorised to do so.

I had the same problem as Caleb. It turned out that the problem was that the user library directory /Arduino/libraries/ contained a library with a missing ".h" file. The Arduino IDE stopped loading the user libraries when it reached the library with the missing ".h" file.

i.e.

the folder "/Arduino/libraries/libraryA" existed

the file "/Arduino/libraries/libraryA/libraryA.h" existed

but the file "/Arduino/libraries/libraryA/libraryA.h" had an include

"#include \<libraryB\>" for which the folder "/Arduino/libraries/libraryB" existed but it did not contain a file "/Arduino/libraries/libraryB/libraryB.h"

I was trying to compile a program using libraryC, but not using libraryA or libraryB. I guess the lesson is do not develop libraries using the production tool chain.

edited to print \< and \> correctly
> 1 votes

# Answer
I had the same symptom described here. In my case, there was a broken link in my libraries directory. Removing that link made the problem go away. It seems that you need to be careful that there is nothing in that directory that could cause the IDE to have difficulty parsing it.

I saw this on a Linux environment (the original poster didn't specify the OS but the reference to "MyDocuments" sounds like Windows). The link I referenced was a symbolic link I had created to a custom library that I subsequently moved, breaking the link.
> 0 votes

---
Tags: library
---


title: Delay between multiple analogReads

text:
# Question
Title: Delay between multiple analogReads
I'm trying to read 4 analog inputs (1kHz speed). I changed the prescaler to 16 for my Arduino Leonardo according to this link. I then tried to read the analog pins and I used the following code to display the time and the readings:

---

```
#define FASTADC 1
// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif
double t = 0;
void setup() {
  int start;
  int i;
  #if FASTADC
  // set prescale to 16
  sbi(ADCSRA, ADPS2);
  cbi(ADCSRA, ADPS1);
  cbi(ADCSRA, ADPS0);
  #endif

  Serial.begin(9600);
  Serial.print("ADCTEST: ");
  start = millis();
  for (i = 0 ; i < 1000 ; i++)
    analogRead(0);
  Serial.print(millis() - start);
  Serial.println(" msec (1000 calls)");
}

// the loop routine runs over and over again forever:
void loop() {
  // print out the value you read:
  t = millis() / 1000;
  Serial.print(t);
  Serial.print('\t');
  Serial.print(analogRead(A0)); delay(1);
  Serial.print('\t');
  Serial.print(analogRead(A1)); delay(1);
  Serial.print('\t');
  Serial.print(analogRead(A2)); delay(1);
  Serial.print('\t');
  Serial.println(analogRead(A3)); delay(1);
}

```

I connected 2V from the DC supply to all the 4 channels and the readings were similar. I used the output from the serial monitor and pasted the readings for 1 sec in Excel to see the frequency. With a 9600 baud rate and no delay between the readings I got 200 Hz (for the 4 analog inputs).

Why is that happening? And is there a relationship between the sampling frequency and the baud rate? Is my way of finding the frequency correct? If not what's the right way?

Finally, I'll be plotting the readings in Matlab, so I guess this will affect the sampling frequency. How can I control it so that I'm sampling with 1kHz rate for all the channels?

Here is the screenshot of the readings from the 4 channels (2V input).

Summarizing everything, I need to know the following:

1. The effect of adding a delay between every two readings on the accuracy of the readings and the sampling frequency.
2. How to find the best sampling frequency for every input and how to control it?
3. Will using Matlab to plot the data affect the sampling frequency?

Thanks.

EDIT: I accepted the answer below, if anyone has the same problem , please make sure that you change the prescaler as I mentioned above for the best results.

# Answer
> 2 votes
At first I thought that the main problem was not that you too slow at sampling, but that you were too slow at transmitting the data. As Edgar already stated, at 9600 b/s you need 22.88ms to send a line, so the maximum frequency is less than 50Hz.

However as you experienced, the speed you are getting is 200Hz. This is because that calculation is right in the case of a real serial interface. Arduino Leonardo, on the other hand, emulates the serial interface. But.. There is no such thing as baud rate. If you look at the CDC emulation source code you will see that the baud rate you pass to the `begin` function is ignored.

So... Why is it still slow? Because you are using the `delay` function! You are waiting for 1ms every time you perform an acquisition, and then you still have to perform all the sending. This has two errors embedded: 1) using the `delay` function breaks the timing - better use a timer - and 2) you are too slow.

Now, if you want a 1kHz sampling (or any delay multiple of 1ms) you already have a timer running (so you can just use that):

```
#define INTERVAL_LENGTH_US 1000UL

unsigned long previousMicros;

void loop()
{
    unsigned long currentMicros = micros();

    if ((currentMicros - previousMicros) >= INTERVAL_LENGTH_US)
    {
        previousMicros += INTERVAL_LENGTH_US;

        int val_a0 = analogRead(A0);
        int val_a1 = analogRead(A1);
        int val_a2 = analogRead(A2);
        int val_a3 = analogRead(A3);

        Serial.print(((double)currentMicros) / 1000000UL, 1); // 1 is the number of decimals to print
        Serial.print('\t');
        Serial.print(val_a0);
        Serial.print('\t');
        Serial.print(val_a1);

        Serial.print('\t');
        Serial.print(val_a2);
        Serial.print('\t');
        Serial.println(val_a3);
    }
}

```

NOTE: The `millis()` function is replaced by `micros()` according to Edgar's and Nick's comments.

Change just the define to change the sample time. Now its set to 1000us (i.e. 1ms, so 1kHz), but don't go much higher otherwise you will have to check accurately the sampling time and the transfer speed. The `t` variable is not needed anymore.

Just a side note: this will also fix the bug in your code that prevents the program to display the current timing (instead of printing 2.5 it prints 2.0).

~~If you need a faster sample rate you should use another timer to get the correct timing, but again avoid delays.~~ Not needed anymore

# Answer
> 1 votes
Two ways to sample at or near a given frequency:

1. Select the right ADC clock prescaler. This has some limitations and may not get you too the precise sampling frequency.
2. Use a timer to trigger the sampling. Can be done in either. Hardware or software. It is the most flexible way here, especially if coupled with the ADC isr.

# Answer
> 0 votes
I tried your program on my Arduino Uno with similar results : it prints about 44 lines per second. Then I did the math:

Each line consists of 22 characters, including the CR and LF at the end. Each character is transmitted as 10 bits (8 data bits, one start bit and one stop bit). At 9600 bits/second, each bit takes 0.104 ms to be transmitted. All this amounts to 22.88 ms per line (22 × 10 × 0.104), or about 43.7 printed lines per second, on average.

Now, since you are using a Leonardo, things could be a little different, as the Leonardo does not use a real serial port, but a virtual one. You may still try to increase the baud rate to see if it makes any difference.

# Answer
> 0 votes
A few recommendations to get good performance out of the Arduino boards.

* Maximize your analogResolution if the default is not already the max (as in the case of the Due.)
* If possible, use a simple oscillator instead of a constant Voltage source. If you can create a sine or triangle wave with its peaks within the Arduino's input voltage range, you can plot something more interesting than a straight line.
* There is no need to do any analogReads in setup(), and you DON'T want to do anything with the Serial object in setup() except configure it. (There is an under-the-hood reason for that.)
* To get good sample rates from the Arduino boards, don't convert to text until MUCH later in the data flow. TO try this SIGNIFICANT speed optimization, declare an array of 4 elements of type unsigned int, another array of 12 elements of type unsigned char, and an unsigned long to hold the time.
* In loop(), start by assigning micros() to the unsigned long
* Then **call the four analogReads in an uninterrupted sequence**, assigning them to the four elements of the unsigned int array.
* Then copy the four bytes from the unsigned long and the eight bytes from the four unsigned ints into the 12 elements of the unsigned char array. You will need to use the C++ shift right operator "\>\> 4" and the "(unsigned char)" type conversion to do this part.
* Then, still in loop(), call Serial.write(byteArray, 12) once to send the time and digital representations all at once (in the byte order you specified) through the serial connection.
* Place delayMicroseconds at the very end of the loop to get a higher resolution delay between loop iterations.
* On the other side of the serial connection (the workstation or laptop) use dd or some other low level transfer program (instead of a terminal emulator) to copy from the binary 12-byte sample vectors from the serial device that your workstation or laptop uses to access the serial connection to a binary file.

The above eliminates several bottlenecks typical of the newbie example programs. The issue remaining is that, to optimize speed, you never converted the raw binary data vectors to a tab-delimited text file that MATLAB or GnuPlot can read with ease.

A simple C, Java, or Python program can then read the 12 byte vectors and convert the byte groups of 4, 2, 2, 2, and 2 back into the 32 bit time stamp and the four 16 bit unsigned channel values in a loop. The byte order is what you chose in your Arduino sketch. You will need to use the left shift operator and bitwise and and or operations to reconstruct the time stamp and four channel values. At the end of this loop, you can write these values as a single tab-delimited line coresponding to the current binary input vector. Iterate through all the vectors to get a complete tab-delimited data file.

You can experiment with different delayMicrosecond values to get different sample rates, and you can calculate our baud rate to stay ahead of the sampling so that the program could theoretically run indefinitely without backing up the Serial buffer on the Arduino side. Each Arduino analogRead and Serial object has its own maximum speed, which you can find by experimentation.

---
Tags: arduino-leonardo, frequency
---


# Question
Title: Which Arduino is the most suitable for my project?
I've started to prototype something using an Arduino Mega and Yún Shield.

It's simple. It reads an ADC at 50Hz and sends data to a server through a socket. But because of that combination, I need to use Bridge to send data through the socket. It's very slow.

Should I change the Arduino Mega for a Leonardo or a Due to get better performance?

Here is my code, maybe I did something wrong.

Arduino code:

```
#include <Bridge.h>
#include <Process.h>
#include <Time.h>
#include <TimeLib.h>
#include <stdlib.h>

boolean interruptFlag = 0;
int HD = A0;
int HG = A1;
int CD = A2;
int CG = A3;
int ECG = A5;
String analogSignals = "";
static char outstr[15];
int count = 0;
float x = 0.0;

void setup() {
  // Bridge startup.
  Bridge.begin();
  // Initialize Bridge values.
  Bridge.put("data", "");
  noInterrupts(); // Stop interrupts.
  TCCR1A = 0; // Set entire TCCR1A register to 0.
  TCCR1B = 0; // Same for TCCR1B.
  TCNT1  = 0; // Initialize counter value to 0.
  // Set compare match register for 50Hz increments.
  OCR1A = 39999; // = 16000000 / (8 * 50) - 1 (must be <65536)
  // Turn on CTC mode.
  TCCR1B |= (1 << WGM12);
  // Set CS12, CS11 and CS10 bits for 64 prescaler.
  TCCR1B |= (0 << CS12) | (1 << CS11) | (1 << CS10);
  // Enable timer compare interrupt.
  TIMSK1 |= (1 << OCIE1A);
  interrupts(); // Allow interrupts.
  // Launch Python script.
  /*Process p;
  p.begin("python");
  p.addParameter("/root/test/send.py");
  p.run();*/
}

ISR(TIMER1_COMPA_vect) {
  if (!interruptFlag) {
    interruptFlag = 1;
  }
}

void loop() {
  if (interruptFlag) {
    writeAnalogSignals();
    interruptFlag = 0;
  }
}

void writeAnalogSignals() {
  String HDReading = convertToVoltage(analogRead(HD));
  String HGReading = convertToVoltage(analogRead(HG));
  String CDReading = convertToVoltage(analogRead(CD));
  String CGReading = convertToVoltage(analogRead(CG));
  String ECGReading = convertToVoltage(analogRead(ECG));
  if (analogSignals.length() == 0) {
    analogSignals =  String(x, 2) + ";" + HDReading + ";" + HGReading + ";" + CDReading + ";" + CGReading + ";0.0;0.0;" + ECGReading;
  } else {
    analogSignals += "|" + String(x, 2) + ";" + HDReading + ";" + HGReading + ";" + CDReading + ";" + CGReading + ";0.0;0.0;" + ECGReading;
  }
  x += 0.02;
  count += 1;
  if (count >= 50) {
    Bridge.put("data", analogSignals);
    analogSignals = "";
    count = 0;
  }
}
// Convert the analog reading to voltage.
String convertToVoltage(int analogSignal) {
  dtostrf(analogSignal * (5.0 / 1023),8, 6, outstr);
  return outstr;
}

```

Python code:

```
import socket
import sys
import getopt
import time

def main(argv):
    try:
        sys.path.insert(0, '/usr/lib/python2.7/bridge/')
        from bridgeclient import BridgeClient as bridgeclient
        # Create a UDP socket.
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        server_address = ('192.168.1.100', 9050)
        bridge = bridgeclient()
        previous = ""

        # Send data
        while 1:
            data = bridge.get("data")
            if data != previous:
                sent = sock.sendto(data, server_address)
                previous = data
            time.sleep(0.5)

    finally:
        sock.close()

```

# Answer
Both Mega 2560 and Due can handle 4 channels of 1,440 samples per second A-to-D and the least significant byte of the system time stamp sent as a continuous stream of vectors through the USB port to Linux.

In the lab I train at, we see almost no variance in time increment between samples or between receiver read operations, indicating that the bottleneck is our deliberate delays between samples.

The Due is running at full resolution too and communicates via the native port. The receiver process is running in normal user process priority, not boosted for real time.

We use C++ for both endpoints, the embedded Arduino code and the receiver, but the C++ on the Arduino side runs just as fast as the same loop in Arduino sketch language. Python low-level reads are generally able to handle this same level of throughput with ease too, so it is not likely that your hardware or speed goals that are the problem.

I can see a few design issues right away.

1. Don't use libraries for what one can do in just a few low level lines of code.
2. Don't place numbers in strings. Keep them as numbers.
3. Send the numbers as messages placed carefully into byte arrays using bitwise operations.
4. Don't convert raw samples to voltages on the Arduino. That can be done in the receiver or elsewhere on the Linux side.
5. Most importantly, find the various code examples that people posted on the Arduino blogs when testing USB baud rates (speed).

The lab engineers started with that speed testing code, replicated the throughput published with it, and then added A-to-D conversion and other features one step at a time.

It is recommended that you place the code under version control and then, with each change, test the speed again. That way you'll notice any bottleneck you introduce immediately and can see the exact changes that must have caused it.
> 4 votes

# Answer
The Bridge running in Python in Linux is the biggest problem. Open a terminal (for example with putty) and run `top` to see the CPU usage. Try to keep it under 50%.

A few parameters at 5 times per second with `Bridge.put()` is possible, but I don't recommend it, because of the CPU load in Linux. The 50Hz is way too much. Beside that you have also a Python script to send them to a server.

There is about 30 MB of fast RAM storage in /tmp and more storage if you add an SD memory card. You could do a test to write the data to a file, and upload the file every few seconds.

If you really need 50Hz, then I suggest to try the Raspberry Pi (or the ESP8266, as mentioned).

The `dtostrf()` function does not return a String, but a buffer. You could easily get rid of the Strings, to have more time in the Arduino. A good use of`millis()` is just as accurate as a timer. I think you can do the same without the hardware timer and without the interrupt.

**ADDED:** Chris Stratton pointed out that the Bridge is not the problem, so I did a small test.

Using 4 values with short names (like: "temp"). Writing them with `Bridge.put()` every second, and reading them in a webpage via `zepto.min.js` every second is a CPU load of 6% for `python -u bridge.py`.

Writing them 50 times per second and reading 1 time per second is a CPU load of 25% for the bridge.

Writing them 50 times per second and reading them 50 times per second does not change a lot, it adds extra load for uhttpd, resulting in a total of about 60 to 70%. That is still okay to run commands from a terminal.

This 'clean' test is different from my previous tests. It is therefore indeed possible to send data through the Bridge at 50 times per second. Sorry for my wrong answer.
> 1 votes

# Answer
> Should I change the Arduino Mega for a Leonardo or a Due to get better performance?

You didn't quite say what kind of performance gains you had in mind. Looking at your code, it doesn't have any particular needs to justify a fancier Arduino.

With that said, I wanted to highlight one particular aspect of ATmega32u / Leonardo that in my view made it a particularly interesting chip for mixed signal application: its ADC unit features a PGA (1x, 10x, 200x) in differential mode with bipolar readings.

it can be quite handy for some applications.
> 0 votes

# Answer
@JonathanAnctil, @ChrisStratton, I have done some more tests, and the Bridge.put takes an average of 7 milliseconds in the sketch. For 5 values at a rate of 50Hz, that alone takes 1.7 seconds. The Bridge can not keep up with that rate, but the overall cpu load in linux is still under 50%. Therefor the cpu load does not indicate if everything is running okay.

Because I was looking at the cpu load, I took the wrong assumption that it was possible. These tests confirm my previous experiences that the Bridge is too slow.

I have installed extra packages in linux, but I think they will not influence the slow Bridge.put.

With more tests with Bridge.put I learned that Bridge.put takes 4ms, plus 0.3ms per character for the key name and the value text, plus the delay caused by things running at the other side of the Bridge in linux.

The value must be a zero terminated string, it is not possible to send binary data. Suppose turning it into readable hex values, then 20 bytes are needed for the value. With the key name as a single character, and a value of 20 bytes, it takes 10 ms. However, then the values have to be retrieved (and converted) at the other side of the Bridge. I assume that Python will also slow down the Bridge.put, just like Javascript does.

This is my test sketch.

```
// Showing the webpage on the other side of the Bridge with zepto.min.js
// and 50 updates per seconds slows down the sketch, because the Bridge.put
// in the sketch will take a lot more time.
// A Bridge.put takes about 7 to 260 ms when the webpage is in a browser
// with 50Hz updates.
// A Bridge.put takes about 7 ms when the webpage is not shown in a browser.
// A itoa takes about 13 us.
//
// When showing the webpage with 50Hz updates:
//     Only the counter : 43 seconds for 1000 counts = 23 Hz
//     With 6 analog inputs and the free ram : 342 seconds for 1000 counts = 3 Hz
// When showing the webpage with once per 5 seconds updates:
//     Only the counter : 20 seconds for 974 counts = 49 Hz
//     With 6 analog inputs and the free ram : 50 seconds for 985 counts = 20 Hz

#include <Bridge.h>

Process yunProcess;

unsigned long previousMillis;

#define NUM_PINS 6
const int pins[NUM_PINS] = { A0, A1, A2, A3, A4, A5, };
const char * names[NUM_PINS] = { "A0", "A1", "A2", "A3", "A4", "A5" };

void setup()
{
//  SerialUSB.begin(115200);
//  while(!SerialUSB);
//  SerialUSB.println("Started");
  Bridge.begin();
//  SerialUSB.println("Bridge is running");
}

void loop()
{
  unsigned long currentMillis = millis();

  // A software timer of 50Hz.
  if(currentMillis - previousMillis >= 20UL)
  {
    previousMillis = currentMillis;

    // The fastest way to turn an integer into text is with itoa.
    // The function itoa takes about 13us.
    // A buffer is used for itoa.
    char buffer[20];

    for(int i=0; i<NUM_PINS; i++)
    {
      int adc = analogRead(pins[i]);
      itoa(adc, buffer, 10);
      Bridge.put(names[i], buffer);
    }

    int freeram = freeRam();
    itoa(freeram, buffer, 10);
    Bridge.put("freeRam", buffer);

    // a counter.
    static int count;
    count++;
    itoa(count, buffer, 10);
//    unsigned long t1 = micros();
    Bridge.put("counter", buffer);
//    unsigned long t2 = micros();
//    SerialUSB.println(t2 - t1);

//    SerialUSB.println(count);
  }
}

int freeRam ()
{
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

```

And my test webpage is:

```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
<script type="text/javascript" src="zepto.min.js"></script>
<script type="text/javascript">

function refresh()
{
  $.getJSON("/data/get", function(json)
  {
    document.getElementById('myA0').innerHTML=json.value.A0;
    document.getElementById('myA1').innerHTML=json.value.A1;
    document.getElementById('myA2').innerHTML=json.value.A2;
    document.getElementById('myA3').innerHTML=json.value.A3;
    document.getElementById('myA4').innerHTML=json.value.A4;
    document.getElementById('myA5').innerHTML=json.value.A5;
    document.getElementById('myfreeRam').innerHTML=json.value.freeRam;
    document.getElementById('mycounter').innerHTML=json.value.counter;
  });
}

</script>
</head>

<!-- a function to refresh some values -->
<body onload="setInterval(refresh, 1000);">

<br>
<a href="/data/get">Show JSON data</a><br>
<br>

Analog Input A0 = <span id='myA0'>---</span><br>
Analog Input A1 = <span id='myA1'>---</span><br>
Analog Input A2 = <span id='myA2'>---</span><br>
Analog Input A3 = <span id='myA3'>---</span><br>
Analog Input A4 = <span id='myA4'>---</span><br>
Analog Input A5 = <span id='myA5'>---</span><br>
freeRam = <span id='myfreeRam'>---</span><br>
counter = <span id='mycounter'>---</span><br>

</body>
</html>

```
> 0 votes

---
Tags: arduino-mega, arduino-yun, python
---


# Question
Title: Can I use Arduino to generate a 0 to 15V analog output?
Is it possible to use the analog output pin with some circuit to generate a 0 to 15V analog output?

# Answer
The Arduino cannot directly produce anything more than 5V.

You can use PWM and a Low-Pass Filter to produce an analog waveform between 0 and 5V, which you can then amplify using a suitable non-inverting buffer with 3x gain (op-amp), which will boost the voltage to 15V. Whether that is suitable for your needs, though, since the current will generally be quite low (most op-amps have a high output impedance) is unknown.

If you want a cleaner waveform you can attach or create a DAC which produces discrete output voltages (again between 0 and 5V) which you then amplify similarly.

simulate this circuit – Schematic created using CircuitLab

R3 and C1 form the low-pass filter and should be sized according to the frequency ranges you want to filter and keep. Note that many op-amps that can cope with the higher voltages you need aren't *rail-to-rail* which means you will have to use a higher power supply voltage than you want to output to leave some headroom. Similarly the 0V will be clipped and will never go below a certain voltage. If you want to get right down to 0V you will need a negative power supply to feed the V- supply of the op-amp (which is currently connected to ground in this schematic). That would allow the output to drop right down to 0V.
> 3 votes

# Answer
The Arduino does not have any "analog output pin". There are analog inputs, and you can generate a variable output with `PWM` pins.

Whether the latter meets your needs depends on your (unstated) requirements.
> 1 votes

---
Tags: analogwrite
---


# Question
Title: Flash Esp-01 and Esp-12 using NodeMCU module
I am building a test IOT architecture. At the moment I do have a NodeMCU "Amica" V1 module (more will come) and some ESP-01. I have not yet tried to flash the ESP-01 because the MCU is just so user friendly, while buying 6 MCU is more pricey than .

I was wondering, if I do de-solder the ESP-12 from the NodeMCU and then connect a female receptacle for the ESP-01 to the now empty MCU breakout board, would i be able to flash the ESP-01 from the Arduino IDE? Would it maintain the automatic Reset and Flash pulls (as on the stock ESP-12)? Will it also work with a pogo-pin assembly to flash other ESP-07/12 ?

Approximate answers and thoughts are well accepted, thank you very much.

# Answer
> 2 votes
On this site there's a description of how to use a USB-serial adapter to flash a ESP-01 with the Arduino IDE. I'm not very familiar with the NodeMCU boards, but I imagine that they contain a USB-serial chip, and thus it *is* possible to desolder the ESP-12 and connect a ESP-01 (with cables or an adapter with pogo-pins) and program it that way. I'm not sure about the Reset/Flash pulls, but I imagine that it could be possible, study the pinouts for the ESP-12 and ESP-01 and circuitry for flashing (see the link). I did flash my ESP-01 this way, before I got other ESP8266 boards.

I would only do this operation if I was very handy with a soldering iron and the NodeMCU/ESP-12 was something that could go to waste if anything went wrong.

I think picking up a 3.3V LDO and USB-serial (3.3v!) breakout much easier, and more failproof, so that's what I'd recommend.

---
Tags: esp8266, nodemcu
---


# Question
Title: What is the best board for setting up an SSH protocol to an Arduino?
I currently have a project using an Arduino R3, set up across the room from my computer. This has become quite annoying, as every time I want to push something to the Arduino I have to get up and move either the computer or the Arduino to another location, plug it in, and hope my code works the first time, lest I have to repeat the test over and over again. I am trying to set up an SSH server between my Raspberry Pi 2 and computer so I can just push new sketches over SSH, however, I use my Pi 2 for other projects occasionally and want to purchase a second board specifically for this purpose. Is there a good, cheap, board with wifi built in (besides the Pi 3) that I could use for this? Any suggestions?

# Answer
Sounds like you want an Arduino Yun instead of an Uno. Or a Dragino Yun Shield that turns your Uno into a Yun.
> 1 votes

# Answer
If you get it working on the Pi2, could you just drop in a Pi Zero ($5) and a cheap USB network adapter ($2)?

Note that your question title asks for "best", but you don't define your criteria. Reading between the lines I suspect "cheapest and adequate" is what you mean.
> 0 votes

# Answer
You could swap out the Arduino for a ESP012, not sure it meets your I/O needs. The new ESPs support over wifi firmware uploads.
> 0 votes

---
Tags: arduino-uno, sketch, uploading, ssh
---


title: Writing to a SPI memory

text:
# Question
Title: Writing to a SPI memory
Recently I salvaged a BIOS chip (EN25QH16) which has 2 Megabytes of memory (8192 pages, 256 bytes/page). I followed this instructables and it works. I double checked the opcodes because the code is for a `Winbond` chip, mine is `Eon` and of course, they're the same (standards?). All commands worked as it should. I modified the code that writes `Hello World` string to a page. I tried the command but it returns (from the memory) `Hello Worlb`. This is the snap of the serial monitor:

I erased the chip just to make sure and ran the command `test_write` (which I added). It wrote `48 65 6c 6c 6f 20 57 6f 72 6c 00 62 03 0b 00 0b 00` which is in ASCII `Hello Worlb` and I don't know why that happened. Btw this is the modified code:

```
/*
    windbond_serial_debug.cpp
    A simple program for the Arduino IDE to help familiarize you with
    using WinBond flash memory; can also be used to download the entire
    contents of a flash chip to a file via a serial port interface.

    Important bits of the code: the low-level flash functions (which
    implement the timing diagrams in the datasheet), and a simple
    serial-port command interface that allows you to talk to your
    UNO with any generic terminal application (even the command line).

    Copyright 2014, Peter J. Torelli

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>

Revisions:
    rev 2 - 21-SEP-2014.
    User 'fiaskow' pointed out that driving the WEL instruction after
    program and erase w/o waiting for the op to finish may be corrupting
    execution. Removed this code (also not needed b/c the WEL is already
    cleared after page write or chip erase).
*/

#include <SPI.h>
// SS:   pin 10
// MOSI: pin 11
// MISO: pin 12
// SCK:  pin 13

// WinBond flash commands
#define WB_WRITE_ENABLE       0x06
#define WB_WRITE_DISABLE      0x04
#define WB_CHIP_ERASE         0xc7
#define WB_READ_STATUS_REG_1  0x05
#define WB_READ_DATA          0x03
#define WB_PAGE_PROGRAM       0x02
#define WB_JEDEC_ID           0x9f

/*
 * These global variables enable assembly of the user serial
 * input command.
 */
boolean g_command_ready(false);
String g_command;

/*
 * print_page_bytes() is a simple helperf function that formats 256
 * bytes of data into an easier to read grid.
 */
void print_page_bytes(byte *page_buffer) {
  char buf[10];
  for (int i = 0; i < 16; ++i) {
    for (int j = 0; j < 16; ++j) {
      sprintf(buf, "%02x", page_buffer[i * 16 + j]);
      Serial.print(buf);
    }
    Serial.println();
  }
}

/*
================================================================================
User Interface Routines
The functions below map to user commands. They wrap the low-level calls with
print/debug statements for readability.
================================================================================
*/

/*
 * The JEDEC ID is fairly generic, I use this function to verify the setup
 * is working properly.
 */
void get_jedec_id(void) {
  Serial.println("command: get_jedec_id");
  byte b1, b2, b3;
  _get_jedec_id(&b1, &b2, &b3);
  char buf[128];
  sprintf(buf, "Manufacturer ID: %02xh\nMemory Type: %02xh\nCapacity: %02xh",
    b1, b2, b3);
  Serial.println(buf);
  Serial.println("Ready");
}

void chip_erase(void) {
  Serial.println("command: chip_erase");
  _chip_erase();
  Serial.println("Ready");
}

void read_page(unsigned int page_number) {
  char buf[80];
  sprintf(buf, "command: read_page(%04xh)", page_number);
  Serial.println(buf);
  byte page_buffer[256];
  _read_page(page_number, page_buffer);
  print_page_bytes(page_buffer);
  Serial.println("Ready");
}

void delayed_read_all_pages(void) {
  delay(5000);
  read_all_pages();
  }

void read_all_pages(void) {
  Serial.println("command: read_all_pages");
  byte page_buffer[256];
  for (int i = 0; i < 4096; ++i) {
    _read_page(i, page_buffer);
    print_page_bytes(page_buffer);
  }
  Serial.println("Ready");
}

void write_byte(word page, byte offset, byte databyte) {
  char buf[80];
  sprintf(buf, "command: write_byte(%04xh, %04xh, %02xh)", page, offset, databyte);
  Serial.println(buf);
  byte page_data[256];
  _read_page(page, page_data);
  page_data[offset] = databyte;
  _write_page(page, page_data);
  Serial.println("Ready");
}

/*
================================================================================
Low-Level Device Routines
The functions below perform the lowest-level interactions with the flash device.
They match the timing diagrams of the datahsheet. They are called by wrapper
functions which provide a little more feedback to the user. I made them stand-
alone functions so they can be re-used. Each function corresponds to a flash
instruction opcode.
================================================================================
*/

/*
 * See the timing diagram in section 9.2.35 of the
 * data sheet, "Read JEDEC ID (9Fh)".
 */
void _get_jedec_id(byte *b1, byte *b2, byte *b3) {
  digitalWrite(SS, HIGH);
  digitalWrite(SS, LOW);
  SPI.transfer(WB_JEDEC_ID);
  *b1 = SPI.transfer(0); // manufacturer id
  *b2 = SPI.transfer(0); // memory type
  *b3 = SPI.transfer(0); // capacity
  digitalWrite(SS, HIGH);
  not_busy();
}

/*
 * See the timing diagram in section 9.2.26 of the
 * data sheet, "Chip Erase (C7h / 06h)". (Note:
 * either opcode works.)
 */
void _chip_erase(void) {
  digitalWrite(SS, HIGH);
  digitalWrite(SS, LOW);
  SPI.transfer(WB_WRITE_ENABLE);
  digitalWrite(SS, HIGH);
  digitalWrite(SS, LOW);
  SPI.transfer(WB_CHIP_ERASE);
  digitalWrite(SS, HIGH);
  /* See notes on rev 2
  digitalWrite(SS, LOW);
  SPI.transfer(WB_WRITE_DISABLE);
  digitalWrite(SS, HIGH);
  */
  not_busy();
}
void _write_test(void) {
  String sampleText = "Hello World";
  byte data[sampleText.length()];
  sampleText.getBytes(data, sizeof(data));
  _write_page(0,data);
  }
/*
 * See the timing diagram in section 9.2.10 of the
 * data sheet, "Read Data (03h)".
 */
void _read_page(word page_number, byte *page_buffer) {
  digitalWrite(SS, HIGH);
  digitalWrite(SS, LOW);
  SPI.transfer(WB_READ_DATA);
  // Construct the 24-bit address from the 16-bit page
  // number and 0x00, since we will read 256 bytes (one
  // page).
  SPI.transfer((page_number >> 8) & 0xFF);
  SPI.transfer((page_number >> 0) & 0xFF);
  SPI.transfer(0);
  for (int i = 0; i < 256; ++i) {
    page_buffer[i] = SPI.transfer(0);
  }
  digitalWrite(SS, HIGH);
  not_busy();
}

/*
 * See the timing diagram in section 9.2.21 of the
 * data sheet, "Page Program (02h)".
 */
void _write_page(word page_number, byte *page_buffer) {
  digitalWrite(SS, HIGH);
  digitalWrite(SS, LOW);
  SPI.transfer(WB_WRITE_ENABLE);
  digitalWrite(SS, HIGH);
  digitalWrite(SS, LOW);
  SPI.transfer(WB_PAGE_PROGRAM);
  SPI.transfer((page_number >>  8) & 0xFF);
  SPI.transfer((page_number >>  0) & 0xFF);
  SPI.transfer(0);
  for (int i = 0; i < 256; ++i) {
    SPI.transfer(page_buffer[i]);
  }
  digitalWrite(SS, HIGH);
  /* See notes on rev 2
  digitalWrite(SS, LOW);
  SPI.transfer(WB_WRITE_DISABLE);
  digitalWrite(SS, HIGH);
  */
  not_busy();
}

/*
 * not_busy() polls the status bit of the device until it
 * completes the current operation. Most operations finish
 * in a few hundred microseconds or less, but chip erase
 * may take 500+ms. Finish all operations with this poll.
 *
 * See section 9.2.8 of the datasheet
 */
void not_busy(void) {
  digitalWrite(SS, HIGH);
  digitalWrite(SS, LOW);
  SPI.transfer(WB_READ_STATUS_REG_1);
  while (SPI.transfer(0) & 1) {};
  digitalWrite(SS, HIGH);
}

/*
 * This handy built-in callback function alerts the UNO
 * whenever a serial event occurs. In our case, we check
 * for available input data and concatenate a command
 * string, setting a boolean used by the loop() routine
 * as a dispatch trigger.
 */
void serialEvent() {
  char c;
  while (Serial.available()) {
    c = (char)Serial.read();
    if (c == ';') {
      g_command_ready = true;
    }
    else {
      g_command += c;
    }
  }
}

void setup(void) {
  SPI.begin();
  SPI.setDataMode(0);
  SPI.setBitOrder(MSBFIRST);
  Serial.begin(9600);
  Serial.println("");
  Serial.println("Ready");
}

/*
 * loop() dispatches the commands compiled by the serialEvent
 * parser callback. Some commands take multiple arguments, so
 * I have to split up the strings with some messy manipulation.
 */
void loop(void) {
  if (g_command_ready) {
    if (g_command == "get_jedec_id") {
      get_jedec_id();
    }
    else if (g_command == "test_write") {
      Serial.println("Custom command: test_write");
      _write_test();
      }
    else if (g_command == "chip_erase") {
      chip_erase();
    }
    else if (g_command == "read_all_pages") {
      read_all_pages();
    }
    else if (g_command == "delayed_read_all_pages") {
      Serial.println("Custom command: delayed_read_all_pages");
      delayed_read_all_pages();
      }
    // A one-parameter command...
    else if (g_command.startsWith("read_page")) {
      int pos = g_command.indexOf(" ");
      if (pos == -1) {
        Serial.println("Error: Command 'read_page' expects an int operand");
      } else {
        word page = (word)g_command.substring(pos).toInt();
        read_page(page);
      }
    }
    // A three-parameter command..
    else if (g_command.startsWith("write_byte")) {
      word pageno;
      byte offset;
      byte data;

      String args[3];
      for (int i = 0; i < 3; ++i) {
        int pos = g_command.indexOf(" ");
        if (pos == -1) {
          Serial.println("Syntax error in write_byte");
          goto done;
        }
        args[i] = g_command.substring(pos + 1);
        g_command = args[i];
      }
      pageno = (word)args[0].toInt();
      offset = (byte)args[1].toInt();
      data = (byte)args[2].toInt();
      write_byte(pageno, offset, data);
    }
    else {
      Serial.print("Invalid command sent: ");
      Serial.println(g_command);
      g_command = "";
    }
done:
    g_command = "";
    g_command_ready = false;
  }
}

```

# Answer
> 2 votes
Strings in C are terminated with a null byte - so the string "A" is in fact two bytes: the 'A' followed by a null.

Your `_write_test()` function counts only the characters in the string, and hence allocates one byte too few. It should be:

```
void _write_test(void) {
  String sampleText = "Hello World";
  byte data[sampleText.length()+1];
  sampleText.getBytes(data, sizeof(data));
  // See text below before calling write_page()
}

```

But then we hit the issue of how much data `write_page()` will write. It doesn't have any way of knowing how much data you are passing in - it just gets a pointer. Looking at its implementation we can see that it writes exactly 256 bytes, so we need to pass in a buffer of 256 bytes.

```
void _write_test(void) {
  String sampleText = "Hello World";
  byte data[256];
  sampleText.getBytes(data, sizeof(data));
  _write_page(0,data);
  }

```

(If we pass in a smaller buffer we're leaving it up to chance what will happen. The Arduino doesn't have much protection so probably you'll just write garbage, but maybe, just maybe, you'll get unlucky and some weird crash will happen.)

---
Tags: arduino-nano, spi, memory
---


title: Confusion in the use of byte variable

text:
# Question
Title: Confusion in the use of byte variable
A byte stores an 8-bit unsigned number, from 0 to 255.

I can understand the following line:

```
byte b = B10010;  // "B" is the binary formatter (B10010 = 18 decimal)

```

But I also saw a use such as:

```
volatile byte state = LOW;

```

What does the last line mean here? Is that special for Arduino? I mean LOW is not a 8 bit unsigned number. LOW is not a number here.

# Answer
> 4 votes
There is probably somewhere else, like this:

```
#define LOW 0

```

Which means the pre-processor turns your line from this:

```
volatile byte state = LOW;

```

into this:

```
volatile byte state = 0;

```

There is nothing arduino-specific here, just the use of standard C/C++ features.

# Answer
> 2 votes
It is common practise in C/C++ to define certain much-used constants at the beginning of the code.

```
#define true 1

```

this means that every time you write true in your code, the compiler will see it as 1.

The arduino IDE comes with a few constants predefined:

* true = 1
* false = 0
* HIGH = 1
* LOW = 0
* ...

# Answer
> 0 votes
In the same way that you can do

```
int blarb = 12;
#define wibble 73

```

you can do

```
int FOO = 73;
#define BINKY 99

```

or even

```
int LOW = 0;
#define HIGH 1

```

So in the line

```
volatile byte state = LOW;

```

someone has created some sort of numerical constant with the name `LOW`.

You can read all about various constants provided for you here.

---
Tags: variables
---


# Question
Title: Arduino Uno, BLE Bluetooth Shield and Braccio Arm Shield
I'm running the Uno board and want to connect the BLE Bluetooth shield (http://redbearlab.com/bleshield/) to control the Braccio Arm I have.

When I sit the Braccio Arm Shield on the Uno everything works - I can control the Arm.

When I sit the Bluetooth Shield on the Uno, everything works I can find the device and connect to it using the IOS App.

When I sit all 3 together, I can still control the arm but can no longer find the Bluetooth device.

Any ideas as to why this is?

# Answer
> 2 votes
Be aware that the BLE Shield is using a SPI interface therefore on Arduino Uno the SPI bus uses pins 10 (SS), 11 (MOSI), 12 (MISO), and 13 (SCK) and the Nordic’s ACI requires two hand-shake signals, RDYN and REQN, two additional pins will be used (pins 8 & 9 in the default settings), from BLEshield Therefore the BLE shield uses 6 pins e the Braccio uses almost all Arduino Uno pins. Conclusion, you probably can't have both shields together as the Arduino Uno hasn't enough pins.

You can try an Arduino MEGA and adapt the shields connections wiring them together using different pins for the Braccio interface for example

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


# Question
Title: 5V 1A vs 5V 5A power supply for 6 LED + Arduino
If I want to power up 6 normal 3mm LED with the appropriate series limiting resistor, do I need the 5V with **1A** or **5A** power supply? Same goes to the Arduino, if I want to power it externally, do I go for the **1A** or **5A**?

# Answer
Depending on your led, it will draw 10 to 20mA for a standard led. Thats 0.010 to 0.020A. Multiply this by 6 and you see that a 1A power supply will be enough.

Your arduino, when driving those leds, will also use a few mA. So you can power everything with a 1A power supply.
> 2 votes

# Answer
Both will work, but **go with 1A!!!**

It is more forgiving if a short happens.

A 5A short circuit will make sparks that might be dangerous.
> 0 votes

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


# Question
Title: Weird formatting behavior with sprintf function
I don't know why but since yesterday, my Arduino sketch returns weird data. I've check eaches inputs and the returns values are ok.

But that line:

```
sprintf(read, "%d;%d;%d;%d;%d;%d;%d;%d\r", x, analogRead(HD), analogRead(HG), analogRead(CD), analogRead(CG), 0, 0, analogRead(ECG));

```

returns something like this:

```
3000;0;110;291;263;230;0;0 (It's like the analog reads are shift from 1 position to the right)

```

It's suppose to return something like this:

```
3000;110;291;263;230;0;0;245

```

Here is my sketch:

```
int HD = A0;
int HG = A1;
int CD = A2;
int CG = A3;
int ECG = A5;

volatile boolean interruptFlag = 0;
char read[45];
char signal[2048];
volatile int count = 0;
volatile long x = 0;

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

  noInterrupts(); // Stop interrupts.

  TCCR1A = 0; // Set entire TCCR1A register to 0.
  TCCR1B = 0; // Same for TCCR1B.
  TCNT1  = 0; // Initialize counter value to 0.

  // Set compare match register for 50Hz increments.
  OCR1A = 39999; // = 16000000 / (8 * 50) - 1 (must be <65536)

  // Turn on CTC mode.
  TCCR1B |= (1 << WGM12);
  // Set CS12, CS11 and CS10 bits for 64 prescaler.
  TCCR1B |= (0 << CS12) | (1 << CS11) | (1 << CS10);
  // Enable timer compare interrupt.
  TIMSK1 |= (1 << OCIE1A);

  interrupts(); // Allow interrupts.
}

ISR(TIMER1_COMPA_vect){
  if (!interruptFlag){
    interruptFlag = 1;
  }
}

void loop() {
  if (interruptFlag){
    writeAnalogSignals();
    count++;
    interruptFlag = 0;
  }
}

void writeAnalogSignals() {
  if (strlen(read) == 0) {
    sprintf(read, "%d;%d;%d;%d;%d;%d;%d;%d\r", x, analogRead(HD), analogRead(HG), analogRead(CD), analogRead(CG), 0, 0, analogRead(ECG));
  } else {
    sprintf(read, "|%d;%d;%d;%d;%d;%d;%d;%d\r", x, analogRead(HD), analogRead(HG), analogRead(CD), analogRead(CG), 0, 0, analogRead(ECG));
  }
  strcat(signal, read);

  x += 2;

  if (count >= 50) {
    Serial.print(signal);
    signal[0] = 0;
    count = 0;
  }
}

```

# Answer
Sometimes the sprintf can be used instead of 20 lines of code. In this case an array with integers and a loop with Serial.print would be better as Majenko already wrote.

When you do use the sprintf, a shift in the data means that one of the parameters has too many or too little bytes. The sprintf does not know the size of the parameter and the parameter will not be converted to a different type. When you use "%d", you have to put two bytes on the stack. Since your 'x' is 4 bytes, all those 4 bytes will be put onto the stack. The first "%d" reads two bytes of 'x' and the second "%d" read the other two bytes of 'x'. That is why it is shifted.

For a data rate of 50Hz, I suggest to raise the baudrate to 115200.

Using millis() for the 50Hz will result into the same timing accuracy as you have now. You don't need the timer and you don't need the interrupt. See the BlinkWithouDelay example and use 20ms as an interval.
> 2 votes

---
Tags: arduino-mega, c++, c
---


title: Make Arduino Executable File

text:
# Question
Title: Make Arduino Executable File
On a Pi, to execute a C++ code, you'll need a Makefile.

Is there an equivalent with the Arduino? Where I have some valid C++ files to upload without the IDE's help, but instead with an executable?

# Answer
> 2 votes
Whether you compile manually with a Makefile (or Arduino-Builder) or in the IDE, the end result is a HEX file. This is a text file describing the data to load into the flash memory.

You then use avrdude to install it into the Arduino - either from the IDE or by running it manually (or specifying it in your Makefile, etc).

A Makefile doesn't produce an executable. A Makefile is merely a recipe - a set of instructions - telling the `make` program which programs to run (gcc, avr-gcc, etc) and in what order (and with what flags) to compile your code.

There are many Arduino Makefile projects out there that do it all for you.

# Answer
> 1 votes
Take a look at platformio.org. It Provides a simple CLI environment to compile, upload and monitor.

---
Tags: c++, arduino-ide, uploading
---


title: Arduino two Ethernet shields

text:
# Question
Title: Arduino two Ethernet shields
Is it possible to connect two Ethernet shields to arduino? And if yes, how can I distinguish them in the code?

# Answer
The ENC28J60 Shields have a Chip-Select-Pin (CS) so you could select between the two shields with this.

I'm using the EN28j60 with the Ethercard library and I'm not sure if this could handle two Ethernet shields because you have to **set the CS pin at init on the first call in the function**, and can't change it at runtime.
> 4 votes

---
Tags: ethernet
---


title: Slowly increase speed using PWM arduino

text:
# Question
Title: Slowly increase speed using PWM arduino
I'm trying to control the speed of a DC motor using PWM. Here is my code so far:

```
int motor = 9;
int fadeValue = 5;

void setup() {
  pinMode(motor, OUTPUT);
}

void loop() {
  for (int fadeValue = 5 ; fadeValue <= 245; fadeValue += 10) {
    analogWrite(motor, fadeValue);
    delay(100);
  if (fadeValue==245) {
    fadeValue=255;
    break;
  }
}

```

I want the motor to slowly increase it speed then stay high. However, the loop keep repeating.

Thanks in advance guys.

# Answer
> 1 votes
If you dont want the code to repeat at the maximum, just add a condition to the loop. Your solution could look like this:

```
int fadeValue = 5;

void loop()
{
    if (fadeValue < 255)
    {
        if (fadeValue >= 245)
        {
            fadeValue = 255;
        }
        else
        {
            fadeValue++;
        }
        analogWrite(motor, fadeValue);
        delay(100);
    }

    //Other code here
}

```

By setting `FadeValue` to another value, the fade will start again from the new value until the maximum.

# Answer
> 1 votes
Could you also change the order the loop is in? So the code would look like this instead:

```
void loop() {
  if (fadeValue == 245) {
    fadeValue=255;
    analogWrite(motor, fadeValue);  // motor will stay at highest value
    }
  else {
      for (int fadeValue = 5 ; fadeValue <= 245; fadeValue += 10) {
        analogWrite(motor, fadeValue);
        delay(100);
        }
  }
}

```

So now, the loop will run until fadeValue == 245, at which point the loop will not advance to the for loop because the "if" in the if/else statement is satisfied. I'm not actually sure if this will work, but it's an idea.

# Answer
> 0 votes
> However, the loop keep repeating.

That's the whole point of loop(). If you want some code to run only once after the program starts put it in `setup()`:

```
int motor = 9;
int fadeValue = 5;

void setup() {
  pinMode(motor, OUTPUT);

  for (int fadeValue = 5 ; fadeValue <= 245; fadeValue += 10) {
    analogWrite(motor, fadeValue);
    delay(100);
    if (fadeValue == 245)
    {
      fadeValue = 255;
      break;
    }
  }
}

void loop() {
}

```

# Answer
> 0 votes
it can be put in the loop(): putting it in the setup(), if the speed-up period is long, isn't practical or feasible in some applications.

you can use a loop counter or time counter to slow down the ramp-up without tying down the mcu, like this:

```
  time_now = time(); //take a reading of current time. or millies()
  if (time_now < TIME_RAMPUP) { //still need to ramp it up
    if (time_now > time_prev) { //need to increment motor speed
      time_prev+=TIME_INC;
      motor_dc+=PWM_STEP;  // you may wish to bound the dc here
      analogWrite(MOTOR_PIN, motor_dc); //increase dc
    }
  }

```

# Answer
> 0 votes
If you want void loop() to only run once and don't want to put your code into setup() for some odd reason, just as an infinite while loop at the end with a delay inside like this:

```
void loop()
{
  for (int fadeValue = 5 ; fadeValue <= 245; fadeValue += 10)
{
    analogWrite(motor, fadeValue);
    delay(100);
  if (fadeValue==245)
{
    fadeValue=255;
    break;
  }

While(1)
    Delay(1000);

}

```

---
Tags: pwm
---


title: 'content' is not captured

text:
# Question
Title: 'content' is not captured
I try to make a variable that can be modified from the server, using and ESP8266.

```
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char* ssid = "********";
const char* password = "*********";

ESP8266WebServer server(80);

const int led = 13;

void handleRoot() {
    digitalWrite(led, 1);
    server.send(200, "text/plain", "hello from esp8266!");
    digitalWrite(led, 0);
}

void handleNotFound() {
    digitalWrite(led, 1);
    String message = "File Not Found\n\n";
    message += "URI: ";
    message += server.uri();
    message += "\nMethod: ";
    message += (server.method() == HTTP_GET)?"GET":"POST";
    message += "\nArguments: ";
    message += server.args();
    message += "\n";

    for (uint8_t i=0; i<server.args(); i++){
        message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
    }

    server.send(404, "text/plain", message);
        digitalWrite(led, 0);
    }
}

void setup(void) {
    pinMode(led, OUTPUT);
    digitalWrite(led, 0);
    Serial.begin(115200);
    WiFi.begin(ssid, password);
    Serial.println("");

    // Wait for connection
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }

    Serial.println("");
    Serial.print("Connected to ");
    Serial.println(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());

    if (MDNS.begin("esp8266")) {
        Serial.println("MDNS responder started");
    }

    String content = "Basic";
    content += "<html><body><form action='action_page.php' method='POST'><br>";
    content += "User:<input type='text' name='USERNAME' placeholder='user name'>       <br>";
    content += "<input type='submit' name='SUBMIT' value='Submit'></form><br>";

    server.on("/led", [](){
        server.send(200, "text/html", content);
        Serial.println(USERNAME);
    }

    server.on("/", handleRoot);

    server.on("/inline", [](){
        server.send(200, "text/plain", "this works as well");
    });

    server.onNotFound(handleNotFound);
    server.begin();
    Serial.println("HTTP server started");
}

void loop(void){
    server.handleClient();
}

```

When I compile it, it says

> 'content' is not captured

I thought it may be from the input, and I tried to name it "Basic" for the start, but it still failed.

# Answer
> 3 votes
Let's look at a simpler example:

```
void setup ()
{
  String content = "Basic";

  attachInterrupt (digitalPinToInterrupt (2),
                   []()
  {
    Serial.println(content);
  },

  FALLING );

}  // end of setup

void loop () { }

```

This gives the error:

```
/tmp/arduino_modified_sketch_182173/sketch_jan25a.ino: In lambda function:
sketch_jan25a:8: error: 'content' is not captured
     Serial.println(content);

```

Why? Because you are using a local variable `content` in a lambda function which runs at global scope. That is, `content` is not available to it, because it is inside `setup`.

To capture it, you can put it in the capture list:

```
  attachInterrupt (digitalPinToInterrupt (2),
                   [content]()  // capture content

```

However I found that my example doesn't compile even then.

---

I think the reason for that can be found here: Lambda Functions in C++11 - the Definitive Guide

> **How are Lambda Closures Implemented?**
>
> So how does the magic of variable capture really work? It turns out that the way lambdas are implemented is by creating a small class; this class overloads the operator(), so that it acts just like a function. A lambda function is an instance of this class; when the class is constructed, any variables in the surrounding enviroment are passed into the constructor of the lambda function class and saved as member variables.

You can't pass an instance of a class to `attachInterrupt` because there is a hidden `*this` variable that needs to be passed to class instances, and ISRs don't do that.

Now your example isn't an ISR, but probably the same remarks apply.

---

I don't think there is an enormous amount of point of using lambda functions here. If you must, move `content` inside the lambda, since that is where you are using it.

Or failing that, make it global scope.

---

The closest I could get to something that compiled was:

```
void setup ()
{
  const int content = 42;

  attachInterrupt (digitalPinToInterrupt (2),
                   [=]()
  {
    Serial.println(content);
  },

  FALLING );

}  // end of setup

void loop () { }

```

Honestly though, I think using lambda functions here just makes your code obscure.

# Answer
> 0 votes
Are you looking at the last compiler error ? The first one is the most most important one. In the preferences, the compiler output can be turned on to show more. Then scroll up to see the first compiler error. The compiler has troubles with the \`\` at the very end of your sketch.

---
Tags: c++, esp8266, web-server, variables
---


# Question
Title: Moving average sticks in fictitious zeroes for the first readings. This delays accuracy
My 9/10 Moving Average inserts zeroes for the first 9 readings. For example, if the first voltage reading is 100, the first moving average given is 10. That is the average of 9 zeroes and one 100. How can I get the moving average to only use actual readings from the adc? Or how can I get the moving average to wait until at least 10 readings are finished before starting its calculations?

```
#include <SPI.h>
#include <SoftwareSerial.h>
#include <math.h>
#include <ads1262.h>

#define PGA 1 // Programmable Gain = 1
#define VREF 2.50 // Internal reference of 2.048V
#define VFSR VREF/PGA
#define FSR (((long int)1<<23)-1)

ads1262 PC_ADS1262; // class

float volt_V=0;
float volt_mV=0;
float MovingAverage=0;
volatile int i;
volatile char SPI_RX_Buff[10];
volatile long ads1262_rx_Data[10];
volatile static int SPI_RX_Buff_Count = 0;
volatile char *SPI_RX_Buff_Ptr;
volatile int Responsebyte = false;
volatile signed long sads1262Count = 0;
volatile signed long uads1262Count=0;
double resolution;

void setup() {
  // initalize the  data ready and chip select pins:
  pinMode(ADS1262_DRDY_PIN, INPUT); //data ready input line
  pinMode(ADS1262_CS_PIN, OUTPUT); //chip enable output line
  pinMode(ADS1262_START_PIN, OUTPUT);  // start
  pinMode(ADS1262_PWDN_PIN, OUTPUT); // Power down output
  Serial.begin(9600);
  //initalize ADS1292 slave
  PC_ADS1262.ads1262_Init(); // initialise ads1262
  Serial.println("ads1262 Initialised successfully....");
}

void loop() {
  volatile int i, data;
  if((digitalRead(ADS1262_DRDY_PIN)) == LOW) {
    // monitor Data   ready(DRDY pin)
    SPI_RX_Buff_Ptr = PC_ADS1262.ads1262_Read_Data();
    // read 6 bytes conversion register
    Responsebyte = true;
  }
  if(Responsebyte == true) {
    for(i = 0; i <5; i++) {
      SPI_RX_Buff[SPI_RX_Buff_Count++] = *(SPI_RX_Buff_Ptr + i);
    }
    Responsebyte = false;
  }
  if(SPI_RX_Buff_Count >= 5) {
    ads1262_rx_Data[0]= (unsigned char)SPI_RX_Buff[1];
    // read 4 bytes adc count
    ads1262_rx_Data[1]= (unsigned char)SPI_RX_Buff[2];
    ads1262_rx_Data[2]= (unsigned char)SPI_RX_Buff[3];
    ads1262_rx_Data[3]= (unsigned char)SPI_RX_Buff[4];
    uads1262Count = (signed long) (((unsigned long)ads1262_rx_Data[0]<<24)| ((unsigned long)ads1262_rx_Data[1]<<16)|(ads1262_rx_Data[2]<<8)|        ads1262_rx_Data[3]);
    //get the raw 32-bit adc count out by shifting
    sads1262Count = (signed long) (uads1262Count);
    // get signed value
    resolution = (double)((double)VREF/pow(2,31));
    //resolution=  Vref/(2^n-1) , Vref=2.5, n=no of bits
    volt_V = (resolution)*(float)sads1262Count;
    // voltage = resolution * adc count
    MovingAverage = (9*MovingAverage + volt_V)/10;
    Serial.print(MovingAverage,8);
  }
  SPI_RX_Buff_Count = 0;
}

float mapfloat(float x, float in_min, float in_max, float out_min, float out_max) {
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

```

# Answer
> 1 votes
There are essentially two ways of initializing a low pass filter. The first is to let it initialize itself “naturally” by feeding it data until it reaches its steady state. This is the approach of jwpat7's answer, and it works really well with FIR filters, like a plain moving average.

Your exponentially-weighted moving average, however, is an IIR filter. Given constant input, it converges *asymptotically* to its steady state. After feeding it 10 values, it will only have reached 65% of the steady state (exactly 1 − 0.910), thus you may want to feed it significantly more than 10 points. E.g., you should give it 22 points if you want it to be 90% initialized.

The other approach is to provision a specific initialization procedure that sets the internal state of the filter to what it would have been had it processed an infinite stream of constant values. This is actually really easy to do with this particular filter, as we only have to set the output equal to its first input. Here is the self-initializing filter written as a function (this keeps the code cleaner):

```
static float movingAverage(float x)
{
  static bool initialized;
  static float output;

  // Initialize the filter as if this input had been on forever.
  if (!initialized) {
    output = x;
    initialized = true;
  }

  output += 0.1 * (x - output);
  return output;
}

```

You loose the benefit of the averaging on the very first data points, but in return you have a simple to use self-initializing filter.

Unrelated to your question, I looked at your code and fond so many confusing and useless statements that I felt compelled to remove all that cruft. I did not test the simplified version though:

```
#include <ads1262.h>

const float VREF = 2.50;  // Internal reference

ads1262 PC_ADS1262;  // ADC object

void setup() {
  // initialize the  data ready and chip select pins:
  pinMode(ADS1262_DRDY_PIN,  INPUT);   // data ready input line
  pinMode(ADS1262_CS_PIN,    OUTPUT);  // chip enable output line
  pinMode(ADS1262_START_PIN, OUTPUT);  // start
  pinMode(ADS1262_PWDN_PIN,  OUTPUT);  // power down output
  Serial.begin(9600);

  // initialize ADS1292 slave
  PC_ADS1262.ads1262_Init();
  Serial.println("ads1262 Initialised successfully....");
}

static float movingAverage(float x) { ... }  // as before

void loop() {
  // Nothing to do unless data ready is asserted.
  if (digitalRead(ADS1262_DRDY_PIN) == HIGH) return;

  // Get a reading and convert to voltage.
  uint8_t *buffer = (uint8_t *) PC_ADS1262.ads1262_Read_Data();
  signed long reading = (uint32_t) buffer[1] << 24
                      | (uint32_t) buffer[2] << 16
                      | (uint32_t) buffer[3] <<  8
                      | (uint32_t) buffer[4] <<  0;
  float voltage = VREF / (1UL<<31) * reading;

  // Report a smoothed-out reading.
  Serial.println(movingAverage(voltage), 8);
}

```

# Answer
> 1 votes
Perhaps the easiest way to take in at least 10 readings before beginning to output results is to set a counter to 10 and count it down, as illustrated in following code.

```
byte startup=10;
void loop() {
  stuff_to_await_DRDY_and_compute_volt_V();
  MovingAverage = (9*MovingAverage + volt_V)/10;
  if (startup)
    --startup;  // Don't use MovingAverage during startup cycles
  else {        // Now we are done with startup...
    Serial.print(MovingAverage,8);
    other_stuff_with_new_data();
  }
}

```

As hinted at in a comment to the question, declaring all your variables `volatile` isn't necessary. You should declare variables that are shared between threads, or between an ISR and `loop()`, `volatile`, but to declare other variables as `volatile` is in general a coding-style error that will confuse whoever maintains the code. Spurious `volatile` declarations also may increase code size slightly, as it prevents one-time evaluation of expressions that are used exactly the same way multiple times, and it prevents code motion like moving constant expressions out of loops.

The following code rewrites severak parts of your sketch. It uses some pointer arithmetic to avoid the tedious assignments and shifting found in your code. It removes several extraneous casts because many of the type promotions and conversions coerced by your casts happen automatically anyway. This code has not been tested; if it has problems, please point them out and I'll edit accordingly.

```
#include <SPI.h>
#include <SoftwareSerial.h>
#include <math.h>
#include <ads1262.h>
#define PGA 1 // Programmable Gain = 1
#define VREF 2.50 // Internal reference of 2.048V
#define VFSR VREF/PGA
#define FSR (((long int)1<<23)-1)
ads1262 PC_ADS1262; // class
float volt_V=0;
float volt_mV=0;
float MovingAverage=0;
byte SPI_RX_Buff[10];
byte SPI_RX_Buff_Count = 0;
char *SPI_RX_Buff_Ptr;
void setup() {
  // initalize the  data ready and chip select pins:
  pinMode(ADS1262_DRDY_PIN, INPUT); //data ready input line
  pinMode(ADS1262_CS_PIN, OUTPUT); //chip enable output line
  pinMode(ADS1262_START_PIN, OUTPUT);  // start
  pinMode(ADS1262_PWDN_PIN, OUTPUT); // Power down output
  Serial.begin(9600);
  //initalize ADS1292 slave
  PC_ADS1262.ads1262_Init(); // initialise ads1262
  Serial.println("ads1262 Initialised successfully....");
}

byte startup=10;
void loop() {
  double resolution;
  long *ads1262Count;
  if((digitalRead(ADS1262_DRDY_PIN)) == LOW) { // Is data ready?
    resolution = (double)VREF/pow(2,31);  // Vref/(2^n-1), Vref=2.5
    // Get address of 6-byte conversion-data buffer
    SPI_RX_Buff_Ptr = PC_ADS1262.ads1262_Read_Data();
    // Copy address of SPI_RX_Buff_Ptr[1] to ads1262Count
    ads1262Count = SPI_RX_Buff_Ptr+1;
    // Dereference ads1262Count pointer to get 4-byte signed value
    volt_V = *ads1262Count * resolution;
    MovingAverage = (9*MovingAverage + volt_V)/10;
    if (startup)
      --startup; // Don't use MovingAverage during startup cycles
    else {       // Now we are done with startup...
      Serial.print(MovingAverage,8);
      other_stuff_with_new_data();
    }
  }
  SPI_RX_Buff_Count = 0;
}

```

# Answer
> 1 votes
The simplest method is just to go "I have only taken one reading, therefore I only need to look at one reading". I.e., after your first reading you have 100/1. After your second reading you have (100+100)/2. After your 3726482374th reading you have (100+100+100+100+100+100+100+100+100+100)/10.

I have a fully templated library that works in exactly that way - it returns the rolling average (amongst other things) of only the samples you have actually fed it.

---
Tags: arduino-uno
---


# Question
Title: I can send AT Commands, but cannot upload sketch to ESP8266 via Generic ESP Module
I can send AT commands to the ESP8266 - 01 but I am not able to upload the sketch.

I have connected TX-RX of module to TX-RX of Arduino, GND to GND, CH\_PD, RST and VCC to 3.3V.

Here is the code I'm trying to upload -

```
#include <ESP8266WiFi.h>

const char* ssid = "ssid";
const char* password = "password";

void setup() {
  Serial.begin(115200);
  delay(10);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println(".");
    Serial.println("Connected to ");
    Serial.println(ssid);
  }
}

void loop() {
  Serial.println("Hello, Internet");
  delay(1000);
  Serial.println("IP Address");
  Serial.println(WiFi.localIP());
  delay(2000);
}

```

Here is the error I am getting.

```
Arduino: 1.8.1 (Windows 8.1), Board: "Generic ESP8266 Module, 80 MHz, 40MHz, DIO, 115200, 512K (64K SPIFFS), ck, Disabled, None"

Sketch uses 225921 bytes (52%) of program storage space. Maximum is 434160 bytes.
Global variables use 31864 bytes (38%) of dynamic memory, leaving 50056 bytes for local variables. Maximum is 81920 bytes.
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

```

Please suggest something.

# Answer
In order to put the ESP into programming mode, you need to connect GPIO0 to ground as you power it up.

(I have a push button attached to my proto board for this purpose.)
> 1 votes

# Answer
Every implementation that I've seen connects TX-\>RX & RX-\>TX when going between devices. :)
> 0 votes

---
Tags: arduino-uno, arduino-ide, esp8266, wifi
---


# Question
Title: Using Arduino to detect when a sensor is on and off and display time elapsed
I would like to know if I can use a pressure sensor with an Arduino. The code will detect when the sensor is on, will start a timer, stop when the sensor is off, and display the time elapsed.

Here is the code for the timer:

```
int main(void) {
  LARGE_INTEGER frequency; // ticks per second
  LARGE_INTEGER t1,t2; // ticks
  double elapsedTime;
  // get ticks per second
  QueryPerformanceFrequency(&frequency);
  // start timer
  QueryPerformanceCounter(&t1);
  //the code for sensorwill be written here
  QueryPerformanceCounter(&t2);
  elapsedTime = (t2.QuadPart - t1.QuadPart) * 1000.0 / frequency.QuadPart;
  printf("\nElapsed time : %lf ms.\n", elapsedTime );
  return 0;
}

```

# Answer
> 2 votes
You can easily do this in Arduino.

However I've noticed that you've written the code in C with the Windows functions. Why not write the Arduino code and use what the Arduino already has available, which is the `millis()` and `micros()` functions? The only problem with the `micros()` function is that it will overflow after 70 minutes.

The other thing to mention is how will you know when your sensor is on? One way would be to constantly read the value and set a threshold so that you can see whether the pressure sensor is under pressure or not.

Most of the code for this can be extracted from the various Arduino examples that are on the website.

For the pressure sensor threshold you can use the Arduino AnalogInput example and add an *if* statement after the analog read and combine that with the `millis()` function from the Arduino BlinkWithoutDelay example:

```
int sensorPin = A0; // Choose whichever analog pin you like
int sensorValue = 0;
int flagA = 0;
// flag is used just to indicate if timer has started or stopped

unsigned long startTime;
unsigned long stopTime;
unsigned long elapsedTime;

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

void loop() {
  sensorValue = analogRead(sensorPin);
  // read the value from the sensor
  if(flagA == 0  && sensorValue > xxx) then {
    // if above threshold run timer
    startTime = millis();
    flagA = 1;
  }
  if(flagA == 1 && sensorValue < xxx) then {
    // if falls below threshold stop timer
    stopTime = millis();
    elapsedTime = stopTime - startTime;
    Serial.print("Elapsed time = ");
    // Put your print function in here
    Serial.print(elapsedTime);
    Serial.println(" ms");
    flagA = 0;
  }

```

# Answer
> 0 votes
Fairly easy, as basically you just need to time stamp the events from the sensor.

You can create a time base for the stamping. Triggering for the stamping can be done via polling, external or pin hanger I terrupts, or capture. To list a few.

---
Tags: timers, pressure
---


# Question
Title: Strange characters after typing an AT command in serial monitor
I'm trying to test AT commands (I am working with an Arduino Uno and a GSM/GPRS SIM900 shield; my system is ubuntu 14.10) . Yesterday when I was testing , all ran well.. For example after typing AT+SAPBR=3,1,"APN","ooredoo" in the serial monitor it showed me OK.. but But now it shows me strange characters.

This is my code

```
    #include <SoftwareSerial.h>
    SoftwareSerial GPRS(2,3);

void setup() {
  // put your setup code here, to run once:
 GPRS.begin(9600);
  Serial.begin(9600);
 Serial.write("start");

}

void loop() {

  // put your main code here, to run repeatedly:
     while(GPRS.available())
     Serial.write(GPRS.read());

  while(Serial.available())
    GPRS.write(Serial.read());

}

```

And this it is the result of AT+SAPBR=3,1,"APN","ooredoo" typed in the serial monitor

Thank you for helping me

# Answer
for those who have this issue, i resolve this by changing the speed baud of my GPRS Shield :

```
GPRS.begin(2400);
Serial.begin(9600);

```

and if you want to test AT command directly on the serial monitor you must use 2400 anywhere

```
GPRS.begin(2400);
    Serial.begin(2400);

```

and don't forget to change also the speed on the serial monitor to 2400 I hope this will help someone
> 1 votes

---
Tags: arduino-uno, gsm, softwareserial
---


# Question
Title: Problem using HC-12 graphical configuration utility, invalid responses
I'm trying to use this utility \[first time\] to config a pair of HC-12s to a different channel, as I already have the default address in use. It's a very handy utility, though I can find almost no reference to it via Google.

I found reference to the command here: http://www.thebackshed.com/forum/forum\_posts.asp?TID=8246&PN=1

When I use to change the channel, i get 5 error messages of the form: invalid response(1), invalid response(3.2), invalid response(3.3), invalid response(3.4), invalid response(3.5)

I am running on Windows 10 x6, using a standard USB cable to an Uno. The wiring config is as follows: VCC to 5v, GND to GND, RXD to pin 4, TXD to pin 5, Set to pin 6

I've also tried connecting the Set pin to GND, as I don't know whether this is necessary or not.

The board also has an 1N4007 diode in series with the power line, and a 1000uf capacitor twixt 5v and GND. Nothing else.

There is a sample program at: http://www.allaboutcircuits.com/projects/understanding-and-implementing-the-hc-12-wireless-transceiver-module/

that should accomplish the same function via use of line commands and I shall try that next. However, the configuration utility is so handy that I would like to have it in my kit of useful tools.

Seeking: Assistance with the graphical configuration utility by someone who knows more than I, or perhaps a better alternative.

# Answer
the 'SET' pin needs to be connected to ground to place (and keep) the HC-12 in setup mode. when this is done you should be able to click on the "check configuration" button and receive a popup response containing the device's current configuration.

if the popup response contains no configuration data then either the HC-12 is not in setup mode ('SET' pin not grounded), or the usb to serial bridge you are using is not working. check the bridge by disconnecting the HC-12 and shorting together TxD and RxD on the bridge. you can use any terminal emulator to check loopback is working.

feel free to join the backshed forums and ask further questions about the HC-12.

cheers, robert rozee (author of the HC-12 config utility)
> 2 votes

---
Tags: wireless
---


# Question
Title: Can't able to detect Square wave from 74HC14
In my recent project, I want square wave which length vary according our timing. And this square wave is take reference as a another square wave.

For that, I made Square wave with help of Arduino.

Here, it's code.

```
int kPinSqrOut = 13;

void setup()
{
   pinMode(kPinSqrOut, OUTPUT);
}

void loop()
{
  digitalWrite(kPinSqrOut, HIGH);
  delay(1000);
  digitalWrite(kPinSqrOut, LOW);
  delay(2000);

```

}

This is just simple HIGH and LOW one pin of arduino and we get Square wave.

Oscilloscope output :

Now based on this, I'm getting Square wave which length can be able to vary.

Here, it's code.

```
const uint8_t button_pin = 2;
const uint8_t kPin = 3;

void setup()
{
   pinMode(button_pin, INPUT_PULLUP);
   pinMode(kPin, OUTPUT);
   Serial.begin(9600);
}

void loop()
{
   static int last_button_state = LOW;
   static unsigned int push_count;
   static unsigned long last_press_time;
   int button_state = digitalRead(button_pin);
   unsigned long now = millis();

  // Record when the button is pressed.
  if(last_button_state == LOW && button_state == HIGH)
  {
    push_count++;
    last_press_time = now;

    digitalWrite(kPin, HIGH);
    delay(20);
    digitalWrite(kPin, LOW);
  }

  // Report when the button is released.
  if(last_button_state == HIGH && button_state == LOW)
  {
    unsigned long push_duration = now - last_press_time;
    if (push_duration < 10)   // discard bounce
    {
        push_count--;
    }
    else
    {
       Serial.print(F("pushes: "));
       Serial.print(push_count);
       Serial.print(F(", duration: "));
       Serial.print(push_duration);
       Serial.println(F(" ms"));
    }
  }

  last_button_state = button_state;
}

```

And Serial Monitor output :

```
pushes: 1,    duration: 1001
pushes: 2,    duration: 1000
pushes: 3,    duration: 1001
pushes: 4,    duration: 1002
pushes: 5,    duration: 1001

```

ve So, basically what I'm try to do. One Arduino generate Square wave and another Arduino take this Square wave as Input and calculate it's length and also generate another Square wave based on first one.

Here, I just detect HIGH state of Square wave and according that generate another Square wave which length vary.

Oscilloscope output :

Ideally, all this things work fine. Now, when I apply this things in real implement then not working.

Here, it my square wave(upper one) from 74HC14. But not getting another square wave based on that.

So, give me some suggestion.

# Answer
> 1 votes
The only issue in your code is due to the delay in the pin control. You can solve it this way:

```
void loop()
{
    static int last_button_state = LOW;
    static unsigned int push_count;
    static unsigned long last_press_time;
    static bool kPinPressed = false;
    int button_state = digitalRead(button_pin);
    unsigned long now = millis();

    // Record when the button is pressed.
    if(last_button_state == LOW && button_state == HIGH)
    {
        push_count++;
        last_press_time = now;

        digitalWrite(kPin, HIGH);
        kPinPressed = true;
    }

    if ((kPinPressed) && ((now - last_press_time) >= 20))
    {
        digitalWrite(kPin, LOW);
        kPinPressed = false;
    }

    ...
}

```

So you turn on the output, then after 20ms you turn it off.

There are just a couple of things not clear for me. What is the last picture? What are the yellow and pink traces? Why is it not behaving correctly? What are the readings on the serial interface?

And most important... What is the time scale? Is it really 10ms/div?

# Answer
> 0 votes
Your code. Is designed to work with slow inputs and you are feeding it a much faster input than it can handle.

Solution 1. Use interrupts. Solution 2. Speed up the main loop execution if you insist on polling.

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


# Question
Title: At what frequency/rate does the digitalRead function read an input?
Consider the following code:

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

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
  }
  else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}

```

The line **buttonState = digitalRead(buttonPin);** checks the input voltage.

But how is that checked internally?

I mean at what rate the input is checked?

# Answer
> 3 votes
> When I get time, I will provide more definitive answers.

I did follow through with this, and the result is here, towards the end of the page: https://dannyelectronics.wordpress.com/2016/05/01/the-price-of-avr-arduino/

the short answer is: digitalRead() takes 4.9us to execute on a 16MIPS Arduino Uno, or 79 ticks (=instructions).

the fastest you can read digitalRead() is then 200KHz (= 1/4.9us).

Hope it helps.

# Answer
> 3 votes
It read a port just like it reads memory (to which it's mapped.) So speed is how fast an instruction can read memory. EEPROM is a different animal.

Might get it a little faster by replacing

buttonState = digitalRead(buttonPin);
with
buttonState = PORTB & \_BV(buttonPin);

Assuming it's PORTB that you are using. This will alleviate at least one function call, I would think, and will generate a single instruction to read the port into the variable. It may require an instruction to load the variable address, but that's up to the compiler. The replacement may be more trouble porting to other micros. Normally you don't see a variable as a parameter although legal, usually a constant in a #define.

\_BV(INPUT\_PIN\_X) is a macro (BV is for 'bit value') that expands to
(1 \<\< INPUT\_PIN\_X)

dannyf times seem quick to me, but it sounds like he's done the testing. Is he taking into account the complete function call as part of the time? I run at 1Mhz normally, so it's more difficult to relate.

Take Majenko advice and start reading the generated assembler :)

Best of luck.

# Answer
> 2 votes
That depends on the frequency your Arduino runs at.

It's basically once per iteration of the loop, and that depends on everything that is happening in the loop.

You can examine the assembly language output of the compiler (disassemble the .elf file using `avr-objdump -h -S <elf file>`) and count the number of clock cycles per iteration (the datasheet has the number of clock cycles per instruction). However that is tedious.

If you want to read the input at a specific frequency then you should do it using a timer interrupt.

---
Tags: digital-in
---