# Question
Title: ISR and multiplexing- time required to execute the code in Arduino
Below is an Arduino sketch for a basic animation, taken from the book *Beginning Arduino* by Michael McRoberts. Also, the connections have been shown. From what I have read elsewhere, this is the standard kind of code used to drive a LED dot matrix using the 595 shift registry, or the like (for example the MAX7219). Regarding the functioning of the code, I have two questions.

1. **For what percentage of the time will the LED stay lit?** In the `screenupdate()` there are no set delays. Hence, each row will stay lit only for the time it takes for the Arduino to execute the remaining loop and come back with the updated row values. How do we know for what time will the LEDs be lit, and hence predict their brightness, or for what can we do to set a particular value for this?
2. As I understand from the code, it works assuming that the ISR will fire as the code is running and will include all stages of the `led[]`. Although in this case it is not much significant, but how do we know that the ISR will fire including all the stages?If say we are updating each row of the matrix, to give a scroll effect, we would need the ISR to fire after each modification. How do we ensure this? If the ISR is too frequent, it may not let the code run. Or if it is too dispersed, the code may skip lines giving a jagged animation. Also, since the code would have some periodicity, is it not possible that some LED rows are always skipped? How do we determine the time of ISR firing perfect for the code or modify the code to ensure these do not happen(except trial and error)?

```
#include <TimerOne.h>

int latchPin = 8; //Pin connected to Pin 12 of 74HC595 (Latch)
int clockPin = 12; //Pin connected to Pin 11 of 74HC595 (Clock)
int dataPin = 11; //Pin connected to Pin 14 of 74HC595 (Data)
byte led[8]; // 8 element unsigned integer array to hold the sprite

void setup() {
  // set the 3 digital pins to outputs
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  // Load the binary representation of the image into the array
  led[0] = B11111111;
  led[1] = B10000001;
  led[2] = B10111101;
  led[3] = B10100101;
  led[4] = B10100101;
  led[5] = B10111101;
  led[6] = B10000001;
  led[7] = B11111111;
  // set a timer of length 10000 microseconds (1/100th of a second)
  // and attach the screenUpdate function to the interrupt timer
  Timer1.initialize(10000);
  Timer1.attachInterrupt(screenUpdate);
}

// invert each row of the binary image and wait 1/4 second
void loop() {
  for (int i = 0; i < 8; i++) {
    led[i] = ~led[i];
  }
  delay (250);
}

// Display the image
void screenUpdate() {
  byte row = B10000000; // row 1
  for (byte k = 0; k < 8; k++) {
    shiftOut(dataPin, clockPin, LSBFIRST, led[k] ); // LED array
    shiftOut(dataPin, clockPin, LSBFIRST, ~row); // row binary number (active low)
    // latch low to high to output data
    digitalWrite(latchPin, LOW);
    digitalWrite(latchPin, HIGH);
    // bitshift right
    row = row >> 1;
  }
  // Turn all rows off until next interrupt
  shiftOut(dataPin, clockPin, LSBFIRST, 0);
  shiftOut(dataPin, clockPin, LSBFIRST, ~0);
  // latch low to high to output data
  digitalWrite(latchPin, LOW);
  digitalWrite(latchPin, HIGH);
}

```

***ADDENDUM***

In the above code, I tried putting `Serial.println(micros())` in the `screenUpdate()` loop, but I git a very confusing results in which the time displayed seemed to increase and then decrease randomly. **I did not understand why**. Has it got to do something with ISRs? Sorry for the apparently clumsy question.

I executed the following code (from the same book) out, which includes a MAX7219 driver (with the usual setup) and creates scrollable text. It worked perfectly well. And I just want to understand how this ISR and multiplexing go together, and how do we make sure the frequency is appropriate. More of an academic question rather than a practical one.

```
#include <avr/pgmspace.h>
#include <TimerOne.h>
int DataPin = 2; // Pin 1 on MAX
int LoadPin = 3; // Pin 12 on MAX
int ClockPin = 4; // Pin 13 on MAX
byte buffer[8];
#define SCAN_LIMIT_REG 0x0B
#define DECODE_MODE_REG 0x09
#define SHUTDOWN_REG 0x0C
#define INTENSITY_REG 0x0A
static byte font[][8] PROGMEM = {
// The printable ASCII characters only (32-126)
}
void clearDisplay() {
for (byte x=0; x<8; x++) {
buffer[x] = B00000000;
}
screenUpdate();
}
void initMAX7219() {
pinMode(DataPin, OUTPUT);
pinMode(LoadPin, OUTPUT);
pinMode(ClockPin, OUTPUT);
clearDisplay();
writeData(SCAN_LIMIT_REG, B00000111); // scan limit set to 0:7
writeData(DECODE_MODE_REG, B00000000); // decode mode off
writeData(SHUTDOWN_REG, B00000001); // Set shutdown register to normal operation
intensity(15); // Values 0 to 15 only (4 bit)
}
void intensity(int intensity) {
writeData(INTENSITY_REG, intensity); //B0001010 is the Intensity Register
}
void writeData(byte msb, byte lsb) {
digitalWrite(LoadPin, LOW); // set loadpin ready to receive data
shiftOut(DataPin, ClockPin, MSBFIRST, (msb));
shiftOut(DataPin, ClockPin, MSBFIRST, (lsb));
digitalWrite(LoadPin, HIGH); // latch the data
}
void scroll(char myString[], int rate) {
byte firstChrRow, secondChrRow;
byte ledOutput;
byte chrIndex = 0; // Initialise the string position index
byte Char1, Char2;
byte scrollBit = 0;
byte strLength = 0;
unsigned long time;
unsigned long counter;
while (myString[strLength]) { // Increment count till we reach the end of the string
strLength++;}
counter = millis();
while (chrIndex < (strLength)) {
time = millis();
if (time > (counter + rate)) {
Char1 = constrain(myString[chrIndex],32,126);
Char2 = constrain(myString[chrIndex+1],32,126);
for (byte y= 0; y<8; y++) {
firstChrRow = pgm_read_byte(&font[Char1 - 32][y]);
secondChrRow = (pgm_read_byte(&font[Char2 - 32][y])) << 1
ledOutput = (firstChrRow << scrollBit)
| (secondChrRow >> (8 - scrollBit) );
buffer[y] = ledOutput;
}
scrollBit++;
if (scrollBit > 6) {
scrollBit = 0;
chrIndex++;
}
counter = millis();
}
}
}
void screenUpdate() {
for (byte row = 0; row < 8; row++) {
writeData(row+1, buffer[row]);
}
}
void setup() {
initMAX7219();
Timer1.initialize(10000); // initialize timer1 and set interrupt period
Timer1.attachInterrupt(screenUpdate);
Serial.begin(9600);
}
void loop() {
clearDisplay();
scroll(" BEGINNING ARDUINO ", 45);
scroll(" Chapter 7 - LED Displays ", 45);
scroll(" HELLO WORLD!!! :) ", 45);
}

```

# Answer
> 2 votes
I think the code is likely wrong.

the code is called every 10ms, each time refreshing all columns and all rows and then immediately overwriting them all. so you should just see a quick flicker.

the typical way to approach this is to have a static variable to remember the row (or column) to be lit, and then load up the corresponding data for that row + columns when the display routine is called.

blanking isn't necessary for hc595.

edit: 1/21/2017.

now that I have a little bit more time, I would just add to the comments above.

we know the issues, as outlined above. here is a confirmation of it, in a simulation.

I ran your original code on an arduino uno. U2 is the shift register connected to the led matrix's rows (active low), and U3 to the columns (active high).

two things are obvious: 1. the code is invoked every 10ms; 2. the code for the most part resets the display: other than when the code is updating all rows / columns (the first half of the screenUpdate()), rows are high (inactive) and the columns are low (inactive), thanks to the display being reset by the bottom of the screenUpdate() routine.

the net result is that you for the most part don't see anything being displayed on the led, other than very fast flickers.

here is the solution: rewrite screenUpdate(), as below:

```
// Display the image - alternate routine
void screenUpdate2(void) {
    static unsigned char row = 0; // start with row 0
    //for (byte k = 0; k < 8; k++) {
        shiftOut(dataPin, clockPin, LSBFIRST, led[row] ); // LED array
        shiftOut(dataPin, clockPin, LSBFIRST, ~(1<<row)); // row binary number (active low)
        // latch low to high to output data
        digitalWrite(latchPin, LOW);
        digitalWrite(latchPin, HIGH);
        // bitshift right
        //row = row >> 1;
        row = (row==7)?0:(row+1);
    //}
    // Turn all rows off until next interrupt
    //shiftOut(dataPin, clockPin, LSBFIRST, 0);
    //shiftOut(dataPin, clockPin, LSBFIRST, ~0);
    // latch low to high to output data
    //digitalWrite(latchPin, LOW);
    //digitalWrite(latchPin, HIGH);
}

```

the updated routine, screenUpdate2(), utilizes a static variable, row, to remember the current row to be displayed. it shifts out the column data, and sets up the row to be activated, and then strikes out the display to the led matrix. after that, it updates row for the next invokation.

here is how it works in the simulation:

hope it helps.

post-it: if the main loop has good execution time (short, and fairly deterministic), you can run screenUpdate2() in the loop and it will work as well. running it through an interrupt provides better consistency.

edit: 1/21/2017 v2

short after posting the above, a couple sharp eyed individuals noticed that the output data seems to be flipped (more noticeable at 320ms in the simulation posted above). good catch.

that's due to the following lines in the main loop:

```
for (int i=0; i<8; i++) {
    led[i]= ~led[i];
}
delay (250);

```

I'm not sure what its purpose was in the original code - creating a blinking effect? - but if you comment out those lines, you will see that the execution would be as you would have expected:

you will find that the values match exactly what's in the led\[\] array.

you can think of led\[\] as a ram display buffer that stores information to be displayed. all your application code needs to do is to manipulate / update it in the main loop. the display routine, when called by the timer isr, will update that for you periodically, in a fully transparent and carefree manner.

I tend to utilize this approach with a lot of things. Thus having a hook to a timer to execute a piece of code is a valuable tool for a programmer to have.

edit: 1/21/2017 v3

I was asked how long screenUpdate() and screenUpdate() will run on an arduino (16MIPS): screenUpdate() takes about 2.1ms to run, and screenUpdate2() about 0.2ms. those numbers will determine the upper-end of the display update frequency.

# Answer
> 2 votes
*(In a comment the asker mentioned they're not sure of the "usual approach", so I've provided this answer to hopefully help clarify)*

Here is my code for using a single 595 to drive the columns, and hooking up the rows to the Arduino pins themselves. Here I demonstrate a clear delay in each row update, as well as another delay before the image changes. I hope this helps clear up your confusion, and I apologize for not have a 2 595 setup handy (though I have 2 595s so if this doesn't help you, I'd be more than happy to set it up...), but it should be easy to adapt for a second 595. This supports a variable amount of width and height.

I also answered this assuming you just want the dotmatrix display functioning correctly, and I didn't focus on ISR. On first glance I see no delay in the row updating on the ISR version, or a delay when setting the latch pin and the whole thing seems pretty confusing. Honestly I think it might work in a perfect universe but I'm not sure (it wouldn't, as the other answer said, you'll probably just maybe observe a flicker and one row being lit). If this isn't an X Y problem and you really need ISR, I can answer that too, it just seems like we're getting into a lot of questions at once here...

```
// Pin connected to ST_CP of 74HC595
const int latchPin = 8;
// Pin connected to SH_CP of 74HC595
const int clockPin = 12;
// Pin connected to DS of 74HC595
const int dataPin = 11;
// The pin of the first row of your display
const int row1Pin = 2; // WARNING: All future rows are assumed to be row1Pin + n
// The amount of rows your display has
const int HEIGHT = 3;
// The amount of columns your display has
const int WIDTH = 2;
// The reset pin of 74HC595 (not required as it isn't used, but this pin is pulled low)
const int resetPin = 9;
// Variable used to keep track of currently lit up row
int currentRow = 0;
// Array of rows
int rows[] = {0b11,
              0b01,
              0b11};
unsigned long lastChange = 0;

void setup() {
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(resetPin, OUTPUT);
  digitalWrite(resetPin, LOW);
}

/* I don't think this works, but it might with a much higher delay.
void reset() {
  pinMode(resetPin, INPUT);
  delayMicroseconds(1);
  pinMode(resetPin, OUTPUT);
  digitalWrite(resetPin, LOW);
}
*/

// enableRow changes the currently enabled row for future calls, it also changes
// the pinMode on the previous row to "INPUT", disabling all lights on that row.
void enableRow(int row) {
  if (currentRow != 0) {
    pinMode(currentRow, INPUT);
  }
  currentRow = row;
}

// This is a quick function to test one single LED or row on your dotmatrix display (I should have documented this one better but pass an incremeneting number to it and you'll see what it does...).
void lightOne(int pos) {
  enableRow(row1Pin + int(pos / (WIDTH+1)));
  shiftOut(dataPin, clockPin, MSBFIRST, 1 + pos % (WIDTH+1));
}

// This function draws the display stored in "rows".
void displayRows() {
  for (int i = 0; i < HEIGHT; i++) {
    digitalWrite(latchPin, LOW);
    enableRow(row1Pin+i);
    // shift out the bits:
    shiftOut(dataPin, clockPin, MSBFIRST, rows[HEIGHT-i-1]);
    digitalWrite(latchPin, HIGH);
    pinMode(currentRow, OUTPUT);   // set the current row's pin as OUTPUT
    digitalWrite(currentRow, LOW); // output LOW on currentRow to complete light's circuit and display
    delay(3); // time in ms to hold each row lit
  }
}

void loop() {
  displayRows();
  if (lastChange+1000 /* 1000ms between changes */ < millis()) {
    for (int i = 0; i < HEIGHT; i++) {
      rows[i] = random(4);
    }
    lastChange = millis();
  }
}

```

---
Tags: arduino-uno, led, time, isr, max7219
---


# Question
Title: Connect 9 V battery to Arduino Mega 2560 directly?
Is it safe to connect a 9 volt battery to an Arduino Mega 2560 directly to power it?

# Answer
> 3 votes
Yes. On this page, you can see that you can safely connect 7-12V to the VIN pin.

Furthermore, you can simultaneously connect the USB; your Arduino will automatically draw power from the appropriate source.

Note that the power supply jack pin is connected to the Vin pin through a diode. Do **not** connect a battery *and* an external power supply, since a sufficiently high power supply voltage will try to charge your battery, which may be bad news for the battery.

# Answer
> 0 votes
**DO NOT CONNECT IT TO Vcc, CONNECT IT TO VIn.**

By connecting it to VIn, your 9V will go from the battery, though the VReg, and then to your Arduino. This is what you **HAVE** to do. By connecting it directly to the Arduino Vcc pin, you are basicly frying it.

Note that once the battery has gone bellow 7V, it might start getting unsafe because you are not giving the Arduino enough power.

# Answer
> 0 votes
Yes.

Batteries are acceptable power sources for the Arduino Mega and other Arduino boards. I've used them for years for various applications where access to AC is inconvenient, impractical, or nearly impossible.

The Mega page on the Arduino site also explicitly permits battery power.

**Helpful Guidelines**

Here are some important criteria to meet.

* The Voltage is within the published range for the Arduino model you are using, which is 7 to 12 Volts DC for the Mega 2560
* The positive of the battery supply connected to Vin (NOT any of the other power pins)
* The negative of the battery supply is connected to Gnd
* Critical applications don't run under the assumption that the battery will never drop below the required 7 Volts
* The header is never plugged in backwards or in the wrong location, which would likely damage the Arduino circuitry

**Connection Safety Using Plug and Jack**

If you are connecting and disconnecting the Arduino from your battery frequently or you just want .

See the Power section of the page to make sure you never plug in the header wrong, you can connect your battery supply to the Arduino board's existing power jack. When connecting a battery supply to an Arduino compatible plug, you can ensure that the plug's inner conductor is positive in Voltage relative to the outer sheath using a Voltmeter.

**Battery Use in Robotics and Flight Control**

A 9V battery will eventually drop in Voltage below 7V, upon which the operation of the board may fail at any time, so you may want to add more 9V batteries in parallel to extend your battery supply's life 1.

Another approach common in robotics or flight control applications, to preemptively avoid erratic behavior as the battery drains below operational thresholds, is to use the low voltage detection features of the CPU. The Atmel CPU used by the Arduino Mega 2560 has a Brown-Out Detection feature. The Atmel CPU for the Due and other boards have under-voltage detection too.

A simpler approach for critical applications is a resistor divider on an analog input is another related approach.

.....

\[1\] Batteries may vary in Voltage when purchased, but some small variance above or below 9V hurts neither the batteries nor the Arduino. They will equalize themselves without dissipating (wasting) much energy, so you will get close to N times the battery life, where N is the number of 9V batteries in parallel. See this Electronics StackExchange Q&A and this battery company article for more information.

---
Tags: arduino-mega, battery
---


# Question
Title: Analog output doesn't work for just 2 LEDs [Arduino Mega]
I am having a problem with an Arduino Mega 2560.

Everything works fine, the ultrasonic sensors work fine, and the other LEDs work fine. Although there is 2 LEDs who do not work right and when I do `analogWrite()`, they actually do `digitalWrite()`. I have tried to attach these two LEDs to a potentiometer (potentiometer works fine, values are tested) but it always does `digitalWrite()` not `analogWrite()`.

I have tested the LEDs and potentiometer on an Arduino Uno in PWM pins and analog pin and yes it does work very well.

Please mind that these LEDs are attached to analog pins. Why is this? Because I do not have anymore PWM pins available to use and so I have to use analog pins. No way I can rearrange this.

Here is part of the code (only part otherwise it's too long, most of my pins are taken):

```
//Leds//

int led = A4;
int ledUV = A3;

//Potentiometer//

int potReading;
int potPin = A2;
int lightDim;

void setup(){

    Serial.begin(9600);

    pinMode(led, OUTPUT);
    pinMode(ledUV, OUTPUT);

    pinMode(potPin, INPUT);

}

void loop(){

    potReading = analogRead(potPin);
    lightDim = (255./1023.)*potReading;

    analogWrite(led, lightDim);
//  analogWrite(ledUV, lightDim);
//  Serial.println("pot: ");
//  Serial.println(potReading);
//  Serial.println(" ");
    Serial.println("dim: ");
    Serial.println(lightDim);
//  analogWrite(led, 255);
//  analogWrite(ledUV, 255);

}

```

# Answer
> 0 votes
Reference: `analogWrite()`

The pins 2 - 13 and 44 - 46 are the PWM pins for `analogWrite()`.

That means you have 15 PWM pins. Did you use them all?

You could add a module with more PWM outputs. Search for: Arduino 16 channel PWM

The Arduino Mega does not have analog outputs, only digital PWM outputs.

# Answer
> 4 votes
Analog pins an only *read* analog values, not *write* them.

`analogWrite()` is a deceptive name. It should really be `PWMWrite()` since all it does is PWM. And that, of course, needs PWM pins.

---
Tags: arduino-mega, pins, potentiometer, analogwrite
---


# Question
Title: Problems with transmission between ATtiny85 and Arduino Uno with 433MHz RF modules and Manchester
I am trying to transmit from an ATtiny85 running at 16MHz internal clock to an Arduino Uno with the Manchester Library.

The problem is that the Arduino is not receiving any data.

I have hooked an oscilloscope to the ATAD/DATA pin of the transmitter, and I can see data being transmitted. I have also done the same thing on the DATA pin of the receiver, and it shows data being received. But the Arduino Uno is not detecting anything.

I have tried having an Arduino Uno sending data to itself, which does work, but the data gets dropped very often.

Here is the source code of the transmitter:

```
#include <Manchester.h>

#define TX_PIN 3  //pin where your transmitter is connected

uint16_t transmit_data = 2761;

void setup() {
  pinMode(1,OUTPUT);
 man.setupTransmit(TX_PIN, MAN_1200);
}

void loop() {
  digitalWrite(1,HIGH);
  man.transmit(transmit_data);
  delay(200);
  digitalWrite(1,LOW);
  delay(200);
}

```

And this is the code on the receiver:

```
#include "Manchester.h"

#define RX_PIN 4
#define BUFFER_SIZE 22

uint8_t buffer[BUFFER_SIZE];

void setup() {
  Serial.begin(9600);
  man.setupReceive(RX_PIN, MAN_1200);
  man.beginReceiveArray(BUFFER_SIZE, buffer);
}

void loop() {
  if (man.receiveComplete()) {
    uint8_t receivedSize = 0;
    // do something with the data in 'buffer' here before you start receiving to the same buffer again
    receivedSize = buffer[0];
    for(uint8_t i=1; i<receivedSize; i++)
      Serial.write(buffer[i]);
    Serial.println();
    man.beginReceiveArray(BUFFER_SIZE, buffer);
  }
}

```

This is the code I used to test with only the Arduino Uno:

```
#include <Manchester.h>

#define RX_PIN 7
#define TX_PIN 8  //pin where your transmitter is connected

uint16_t transmit_data = 2761;
int lastTransmit = 0;

void setup() {
  Serial.begin(9600);
  man.setupReceive(RX_PIN, MAN_1200);
  man.setupTransmit(TX_PIN, MAN_1200);
  man.beginReceive();
}

void loop() {
  if (millis() - lastTransmit > 200) {
    man.transmit(transmit_data);
    lastTransmit = millis();
  }

  if (man.receiveComplete()) {
    uint16_t m = man.getMessage();
    Serial.println(m);
    man.beginReceive();
    //start listening for next message right after you retrieve the message
  }
}

```

# Answer
> 1 votes
You set **receivedSize** to zero at instantiation, then load it with buffer\[0\], which also appears to be zero. You should check that value to ensure it's correct and that it's at least 2 as 1 isn't less than. Otherwise when you go into the loop, i is 1 and **receivedSize** is zero (i is \> **receivedSize**.) So it fails to enter the loop, so no write.

```
uint8_t receivedSize = 0;

receivedSize = buffer[0];
for (uint8_t i = 1; i < receivedSize; i++)
     Serial.write(buffer[i]);

```

There may also be a logic problem. If you receive one byte, the **receivedSize** will be 1 and it still won't print. Keep in mind that the array goes from 0 to limit and your 'data' lives starting in buffer\[1\]. Meaning if 6 characters are in the buffer only 5 (1 thru 5) will print. It may be much more clear to add the index at the position 'buffer\[i + 1\]' then the i can run it's normal 0 to n.

---
Tags: arduino-uno, attiny, rf
---


title: Arduino as a custom I2C slave device

text:
# Question
Title: Arduino as a custom I2C slave device
I'm trying to interface with a master I2C device that doesn't exactly follow the normal I2C protocol.

The only difference really is in the read request. A "normal" I2C read operation looks like this (\[M\]aster, \[S\]lave):

```
S | SLA+R | ACK | Data | Ack | Data ...some number of bytes... Nack | P
^M  ^M      ^S    ^S     ^M    ^S                              ^M     ^M

```

But this device expects to do a read like this:

```
S | SLA+R | ACK | Data | Ack | Data | Ack | Data | Ack | P
^M  ^M      ^S    ^M     ^S    ^S     ^M    ^S     ^M    ^M

```

Essentially a read request goes to the slave device, and then the master sends an 8-bit register address, and then the master expects 2 data bytes back from the slave with the Master responding with an ACK on both.

I've been able to set up a master device to do this style of protocol pretty easily by just manipulating the I2C registers directly. But I can't seem to find a way to get the slave device to accept that it is going to receive a data byte after it has been selected by a SLA+R, which leads to a bus contention problem and the slave not giving the master an ACK.

Is this possible to do with the built in I2C hardware on the Atmel chips? Is there any alternative if it can't (bit-banging)?

# Answer
> 1 votes
I'm missing something on the bus operation. Pretty much whenever I get NAK'd I know I need to redo the operation. On the i2c bus it should be an ACK'd or NAK'd on every byte.

Usually you send the address of the device then the command. So the master initially sends the address, which is ACK'd and then the master sends the command that it wants executed. Your diagram has the slave answering when it's the master that's required to give it an operation?

Here's a good document on it... :)

Philips I2C Document

---
Tags: i2c
---


# Question
Title: 5V power supply negative terminal connection
I am currently developing some basic led board using Arduino Uno R3. Basically, the LEDs are connected in parallel so that 5V DC supply can light up about 3 LED. Each LED has its resistor and its connected to 3 Arduino digital pin where I ground it by using digitalWrite(pins, LOW). Each ground on the schematic is the Arduino digitalWrite(LOW). My question is where should the negative of the 5V should be connected?

Also, if I wanted to measure the voltage of the LED, where should I connect my probe so that analogRead() can read the voltage?

Thanks and sorry if my explanation is not correct since it's my first time using this site.

simulate this circuit – Schematic created using CircuitLab

# Answer
> 1 votes
The Arduino common, normally referred to as ground, although it is usually only accidentally grounded through external connection. In general **ALL** connections should have a common "ground".

You can not measure voltage across the LED given the circuit you have listed. (You could read the voltage at both ends and subtract.)

If you swap the LED and resistor you can get an approximation of the LED voltage (actually LED + Arduino pin) from the junction of LED and resistor.

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


title: ESP8266 as WiFi monitor

text:
# Question
Title: ESP8266 as WiFi monitor
I'm about to buy two ESP8266 modules. I want them to use as an auto deauth device. The first module will monitor my WiFi router's packet transmission. If a certain device receive loads of packets from my router (which hogs my network) the second module will deauth that device or flood "forged" packets. There will be a threshold so a simple web browsing will not trigger the deauth process from the second module. Btw. My router doesn't support traffic shaping & QoS. Only a different kind of QoS (DHCP & IPP/TOS) which is useless because my ISP doesn't support it.

# Answer
You're going to face significant challenges with this.

The ESP Arduino API doesn't let you run in promiscuous mode (which you'd need in order to see other people's traffic), and the APIs are all set up for you to create nice well-behaved traffic, not spoofed packets.

I strongly suspect the hardware can do it, but you're going to be making significant changes to the IP stack. The code is all open, so you're free to dig in and see what you can do (I've done a similar thing myself, as I needed some lower-level information than was made available in the API).

So feasibility is determine by your skill level (C, C++ and IP stack and protocols) and available time.

Something like a Raspberry Pi Zero and a suitable USB wifi dongle would probably be a quicker path at similar cost, as there are Linux tools to do a lot of this stuff.
> 0 votes

---
Tags: esp8266, wifi
---


# Question
Title: Convert LIRC config file to Arduino IR remote command
I have a LED 24 button remote with a few broken buttons and I want to simulate all the buttons with an esp8266 using an IR remote library.

I would like to know if someone can help me translate the LIRC config file with all the functional buttons to an ESP lib command. I have 2 lircd.conf files of the same remote (everything worked on a raspberry) and I'm using the same circuit on an ESP8266 (wemos d1 mini pin D5 and D6).

lircd.conf 1

```
begin remote

  name  lumina
  bits           16
  flags SPACE_ENC|CONST_LENGTH
  eps            30
  aeps          100

  header       8860  4530
  one           508  1724
  zero          508   607
  ptrail        508
  repeat       8863  2301
  pre_data_bits   16
  pre_data       0xFF
  gap          107224
  toggle_bit_mask 0x0

      begin codes
          PWR_ON                   0xB04F
          PWR_OFF                  0xF807
          LI_LOW                   0xB847
          LI_HI                    0x906F
          R                        0x9867
          G                        0xD827
          B                        0x8877
          W                        0xA857
          R1                       0xE817
          R2                       0x02FD
          B4                       0xF00F
          G1                       0x48B7
          B1                       0x6897
          FLASH                    0xB24D
          STROBE                   0x00FF
          FADE                     0x58A7
          SMOOTH                   0x30CF
          G2                       0x32CD
          R3                       0x50AF
          R4                       0x38C7
          G3                       0x7887
          G4                       0x28D7
          B2                       0x20DF
          B3                       0x708F
      end codes

end remote

```

lircd.conf 2

```
begin remote

  name  lumina
  bits           16
  flags SPACE_ENC|CONST_LENGTH
  eps            30
  aeps          100

  header       8861  4525
  one           515  1718
  zero          515   600
  ptrail        516
  repeat       8865  2291
  pre_data_bits   16
  pre_data       0xFF
  gap          107235
  toggle_bit_mask 0x0

      begin codes
          B1                       0x6897
          PWR_ON                   0xB04F
          PWR_OFF                  0xF807
          LI_LOW                   0xB847
          LI_HI                    0x906F
          R                        0x9867
          G                        0xD827
          B                        0x8877
          W                        0xA857
          R1                       0x9867
      end codes

end remote

```

Output from a few buttons read from the esp using the IRremoteESP8266 library .

```
F0C41643
4039382595
Unknown encoding: F0C41643 (32 bits)
Raw (68): 8850 -4550 550 -650 550 -650 550 -650 500 -650 550 -600 550 -650 550 -650 550 -600 550 -1750 550 -1750 500 -1750 500 -1750 550 -1750 500 -1750 550 -1750 550 -1750 500 -1750 500 -650 500 -1750 550 -1750 550 -650 550 -650 500 -650 550 -650 550 -650 550 -1750 550 -650 500 -600 550 -1750 500 -1750 550 -1750 550 -1750 500
------------------

A3C8EDDB
2747854299
Unknown encoding: A3C8EDDB (32 bits)
Raw (68): 8900 -4550 550 -650 550 -600 550 -650 550 -650 550 -600 550 -650 550 -600 550 -600 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -650 550 -1750 550 -650 550 -1750 550 -650 550 -600 550 -600 550 -650 550 -1750 550 -650 550 -1750 550 -650 550 -1750 550 -1750 550 -1750 550
------------------

86B0E697
2259740311
Unknown encoding: 86B0E697 (32 bits)
Raw (68): 8900 -4550 550 -600 550 -650 550 -650 550 -600 550 -600 550 -650 550 -600 550 -600 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -600 550 -1750 550 -1750 550 -600 550 -600 550 -650 550 -650 550 -600 550 -1750 550 -600 550 -650 550 -1750 550 -1750 550 -1750 550
------------------

A3C8EDDB
2747854299
Unknown encoding: A3C8EDDB (32 bits)
Raw (68): 8900 -4550 550 -650 550 -600 550 -650 550 -600 550 -650 500 -650 550 -600 550 -650 550 -1750 550 -1750 500 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -1750 550 -650 550 -1750 550 -650 550 -1750 550 -650 550 -600 550 -650 500 -650 550 -1750 550 -650 500 -1750 550 -650 550 -1750 550 -1750 550 -1750 500

```

# Answer
> 1 votes
Looks like is just plain NEC IR protocol. So use something like `irsend.sendNEC(0xB04F, 16)` for POWER\_ON.

---
Tags: esp8266, ir, remote-control, convert
---


# Question
Title: How can I make this button toggle the position of a servo?
I am trying to make something so when I press the button it sets the position of the servo to 50 and then when I press it again, it sets it to 150. The button is momentary not a toggle switch. This is what I have come up with so far. I would also like to account for button bounce. Hope someone can help. Thanks in advance!

```
#include <Servo.h>

Servo myservo;  // create servo object to control a servo

// variables will change:
int pos = 0; // variable to store the servo position
int buttonState = 0; // variable for reading the pushbutton status
int button_mode = 1; // Variable for the button's current state.
// button_mode = 1 when the button is up, and 0 when the button is pressed.
// This variable is 'static' and persists because it is declared outside a function.

void setup() {
  myservo.attach(8); // attaches the servo on pin 9 to the servo object
  Serial.begin(9600); // Initialize the Serial port at 9600 baud.
  pinMode(9,INPUT); // Set Digital pin 9 to an input so it can monitor the button.
}

void loop() {
  buttonState = digitalRead(9);
  if ((digitalRead(9) == LOW) && (button_mode == 1)) {
    // Check Digital pin 9 to see if it's pressed.
    pos = 150; //set servo position variable to 150
    myservo.write(pos); //set servo postion to 'pos'
    delay(1000); // wait 1 second
    button_mode = 0; // Button was up before, but is pressed now. Set the button to pressed
    Serial.println("Button has been pressed."); // and report that to the serial monitor.
  } else if ((digitalRead(9) == HIGH) && (button_mode == 0)) {
    pos = 50;
    myservo.write(pos);
    delay(1000);
    button_mode = 1; // Button was down before, but is released now. Set the button to
    Serial.println("Button has been released"); // released and report that to the serial monitor.
  }
  delay(100); //small delay to account for button bounce
}

```

# Answer
> 0 votes
The code is not well structured. Here is what I would do:

```
if (button_pressed()) { //test to see if button is pressed
  button_state +=1; //increment button
  if (button_stat & 0x01) {//if lsb set
    myservo.write(SERVO_POS1); //set servo position 1
  } else {
    myservo.write(SERVO_POS2); //set servo position 2
  }
}

```

You can debounce if you wish in button\_pressed().

# Answer
> 1 votes
Do something like this:

```
int angles[2] = {0,180}
bool state = 0;

```

then:

```
if(button == PRESSED)
  state = !state;

```

finnally, to control the servo:

```
Servo.write(angles[state]);

```

---
Tags: arduino-uno, servo, button, switch, debounce
---


# Question
Title: Controling pump while displaying moisture value on a LCD at the same time with soil moisture sensor?
I'm new with Arduino (and I'm not very good at English). Recently with Arduino Nano I have tested:

* Control water pump based on soil moisture (using relay) (1)
* Display soil moiture (in percent) on a Nokia 5110 LCD (2)

Now I'm combining 2 codes to control water pump while always displaying moisture value (in percent) on LCD. However, after I have uploaded the code an Arduino Nano, the LCD showed nothing.

When I touched the sensor (changed moisture value) the first time, the LCD showed up, but when I touched the sensor the second time (changed moisture value again), the LCD went blank. The relay and pump still work fine, so I think the problem comes from LCD's code.

Here's my code (1):

```
const int VAL_PROBE = 0;
int RELAY1 = A1;
const int MOISTURE_LEVEL = 250;

void setup()
{
  Serial.begin(9600);
  pinMode (2, INPUT);
  pinMode(A0, INPUT);
  pinMode(RELAY1, OUTPUT);
}

void loop()
{
  int moisture = analogRead(VAL_PROBE);
  Serial.print("Moisture = ");
  Serial.println(moisture);

  if(moisture < MOISTURE_LEVEL)
  {
    digitalWrite(RELAY1,0);           // turn on relay
    Serial.println("Light ON");
  }
  else
  {
    digitalWrite(RELAY1,1);          // turn off relay
    Serial.println("Light OFF");
  }
}

```

The code (2)(got it from the Internet):

```
    //////////////////////////////////////////////
   //        Arduino Soil Moisture Sensor      //
  //            with NOKIA 5110 LCD           //
 //           http://www.educ8s.tv           //
//////////////////////////////////////////////

#include <LCD5110_Graph.h> // THE LIBRARY I AM USING IS THIS:  http://www.rinkydinkelectronics.com/library.php?id=47

LCD5110 lcd(8,9,10,12,11);

extern unsigned char BigNumbers[];
extern uint8_t ui[];

int sensorPin = A0;
int sensorValue = 0;
int percent = 0;
String percentString ="0";
int stringLength = 0;

void setup() {
  lcd.InitLCD();
  lcd.setFont(BigNumbers);
  delay(1000);
}

void loop() {
  lcd.clrScr();
  lcd.drawBitmap(0, 0, ui, 84, 48);
  sensorValue = analogRead(sensorPin);
  percent = convertToPercent(sensorValue);
  percentString = String(percent);
  stringLength = percentString.length();
  displayPercent(stringLength);

  lcd.update();
  delay(1000);
}

int convertToPercent(int value)
{
  int percentValue = 0;
  percentValue = map(value, 1023, 350, 0, 100);
  if(percentValue>100)
    percentValue = 100;
  return percentValue;
}

void displayPercent(int length)
{
  switch(length)
  {
    case 1:  lcd.print(percentString,38,19); break;
    case 2:  lcd.print(percentString,24,19); break;
    case 3:  lcd.print(percentString,10,19); break;
    default:  lcd.print(percentString,0,19); break;
  }
}

```

And my combined code:

```
const int VAL_PROBE = 0;
int RELAY1 = A1;
const int MOISTURE_LEVEL = 250; // Mức độ ẩm cố định là 250
#include <LCD5110_Graph.h>

LCD5110 lcd(8,9,10,12,11);

extern unsigned char BigNumbers[];
extern uint8_t ui[];

int sensorPin = A0;
int MoistureValue = 0;
int percent = 0;
String percentString ="0";
int stringLength = 0;

void setup()
{
  Serial.begin(9600);//Mở cổng Serial ở mức 9600
  pinMode (2, INPUT);
  pinMode(A0, INPUT);
  pinMode (12, OUTPUT);
  pinMode(RELAY1, OUTPUT);
  lcd.InitLCD();
  lcd.setFont(BigNumbers);
  delay(1000);
}

void loop()
{
  lcd.clrScr();
  lcd.drawBitmap(0, 0, ui, 84, 48); // hiển thị giao diện màn hình
  MoistureValue = analogRead(sensorPin); // đọc giá trị từ cảm biến

  percent = convertToPercent(MoistureValue);
  percentString = String(percent);
  stringLength = percentString.length();
  displayPercent(stringLength);

  lcd.update(); // cập nhật màn hình
  delay(1000); // mỗi 1 giây

  int moisture = analogRead(VAL_PROBE);
  Serial.print("Moisture = ");
  Serial.println(moisture);

  if(moisture < MOISTURE_LEVEL)
  {
    digitalWrite(12,HIGH);
    digitalWrite(RELAY1,0);           // bật relay
    Serial.println("Light ON");
  }
  else
  {
    digitalWrite(12,LOW);
    digitalWrite(RELAY1,1);          // tắt relay
    Serial.println("Light OFF");
  }
}

int convertToPercent(int value) // đổi giá trị cảm biến sang phần trăm
{
  int percentValue = 0;
  percentValue = map(value, 1023, 350, 0, 100);
  if(percentValue>100)
    percentValue = 100;
  return percentValue;
}

void displayPercent(int length) // hiển thị phần trăm ra màn hình
{
  switch(length)
  {
    case 1:  lcd.print(percentString,38,19); break;
    case 2:  lcd.print(percentString,24,19); break;
    case 3:  lcd.print(percentString,10,19); break;
    default:  lcd.print(percentString,0,19); break;
  }
}

```

Any advice?

# Answer
> 1 votes
I think the problem is with

```
digitalWrite(12,HIGH);

```

and

```
digitalWrite(12,LOW);

```

Pin 12 is used by the LCD. Changing it's output will reset the LCD. I'm not sure why you put it there to begin with, as it wasn't part of any of the two sketches.

# Answer
> 0 votes
in cases like this where you are combining multiple pieces of code together, a simpler approach would be to rename that:

```
//set up 1
void setup1(void) {
...
}

//loop 1
void loop1(void) {
...
}

//set up 2
void setup2(void) {
...
}

//loop 2
void loop2(void) {
...
}

...

//combined setup
void setup(void) {
  setup1();
  setup2();
  ...
}

//combined loop
void loop(void) {
  loop1();
  loop2();
  ...
}

```

that's much easier to track than to manually copy-and-paste them.

---
Tags: arduino-uno, arduino-nano, lcd
---


# Question
Title: Arduino to ESP8266 (SoftwareSerial) communication, does not receive full data
I have an Arduino Uno and an ESP8266, connected over serial through ESP8266 pin GPIO\_2 (which is set as RX over espsoftwareserial) and 11 on Uno (which is set as TX over SoftwareSerial). I am trying to send data in this format:

**\<0.000000:0.000000:0.000000:0.000000:0.000000:0.000000:24.50:24.50:1.49\>**

It is \< char then number with six floats, separator :, and again... 9 times

I am using:

Arduino UNO code:

```
SoftwareSerial ARD_ESP(10, 11); // RX, TX

totalVolume[0] = 0.000000;
totalVolume[1] = 0.000000;
totalVolume[2] = 0.000000;
flowRate[0] = 0.000000;
flowRate[1] = 0.000000;
flowRate[2] = 0.000000;
float temperature_cold_value = 24.50;
float temperature_hot_value = 24.50;
float propane_gas_value = 1.49;

void setup()
{
   ARD_ESP.begin(57600);
   Serial.begin(9600);
}
void loop()
{
if (millis() - previousMillis_esp_post > 5000 && run_state_metering == 1)
     {
          ARD_ESP.print("<");
          ARD_ESP.print(totalVolume[0],6);
          ARD_ESP.print(":");
          ARD_ESP.print(totalVolume[1],6);
          ARD_ESP.print(":");
          ARD_ESP.print(totalVolume[2],6);
          ARD_ESP.print(":");
          ARD_ESP.print(flowRate[0],6);
          ARD_ESP.print(":");
          ARD_ESP.print(flowRate[1],6);
          ARD_ESP.print(":");
          ARD_ESP.print(flowRate[2],6);
          ARD_ESP.print(":");
          ARD_ESP.print(temperature_cold_value,2);
          ARD_ESP.print(":");
          ARD_ESP.print(temperature_hot_value,2);
          ARD_ESP.print(":");
          ARD_ESP.print(propane_gas_value,2);
          ARD_ESP.print(">");

          Serial.print("<");
          Serial.print(totalVolume[0],6);
          Serial.print(":");
          Serial.print(totalVolume[1],6);
          Serial.print(":");
          Serial.print(totalVolume[2],6);
          Serial.print(":");
          Serial.print(flowRate[0],6);
          Serial.print(":");
          Serial.print(flowRate[1],6);
          Serial.print(":");
          Serial.print(flowRate[2],6);
          Serial.print(":");
          Serial.print(temperature_cold_value,2);
          Serial.print(":");
          Serial.print(temperature_hot_value,2);
          Serial.print(":");
          Serial.print(propane_gas_value,2);
          Serial.print(">");
          Serial.print("");

          previousMillis_esp_post = millis();
     }

```

ESP8266 code: (it's programmed with Arduino IDE)

```
#include <ESP8266WiFi.h>
#include <SoftwareSerial.h>
#include <string.h>

SoftwareSerial ARD_ESP(2, SW_SERIAL_UNUSED_PIN);

const byte numChars = 32;
char receivedChars[numChars];
boolean newData = false;

String sensor_1_total_volume;
String sensor_2_total_volume;
String sensor_1_flow_rate;
String sensor_2_flow_rate;
String temperature_cold_value;
String temperature_hot_value;
String propane_butane_gas_value;
String mereni_token = "xxxxx";

void setup() {

  Serial.begin(115200);
  ARD_ESP.begin(57600);
  delay(10);
}

void loop() {

  recvWithStartEndMarkers();
  showNewData();

  sensor_1_total_volume = getValue(receivedChars, ':', 0);
  sensor_2_total_volume = getValue(receivedChars, ':', 1);
  sensor_1_flow_rate = getValue(receivedChars, ':', 2);
  sensor_2_flow_rate = getValue(receivedChars, ':', 3);
  temperature_cold_value = getValue(receivedChars, ':', 4);
  temperature_hot_value = getValue(receivedChars, ':', 5);
  propane_butane_gas_value = getValue(receivedChars, ':', 6);

}

void recvWithStartEndMarkers() {
    static boolean recvInProgress = false;
    static byte ndx = 0;
    char startMarker = '<';
    char endMarker = '>';
    char rc;

    while (ARD_ESP.available() > 0 && newData == false) {
        rc = ARD_ESP.read();

        if (recvInProgress == true) {
            if (rc != endMarker) {
                receivedChars[ndx] = rc;
                ndx++;
                if (ndx >= numChars) {
                    ndx = numChars - 1;
                }
            }
            else {
                receivedChars[ndx] = '\0'; // terminate the string
                recvInProgress = false;
                ndx = 0;
                newData = true;
            }
        }

        else if (rc == startMarker) {
            recvInProgress = true;
        }
    }
}

void showNewData() {
    if (newData == true) {
        Serial.print("This arrived: (unparsed)");
        Serial.println(receivedChars);
        Serial.println("DATA sensors: (parsed)");
        Serial.println(sensor_1_total_volume);
        Serial.println(sensor_2_total_volume);
        Serial.println(sensor_1_flow_rate);
        Serial.println(sensor_2_flow_rate);
        Serial.println(temperature_cold_value);
        Serial.println(temperature_hot_value);
        Serial.println(propane_butane_gas_value);
        Serial.println(mereni_token);
        newData = false;
    }
}

String getValue(String data, char separator, int index)
{
    int found = 0;
    int strIndex[] = { 0, -1 };
    int maxIndex = data.length() - 1;

    for (int i = 0; i <= maxIndex && found <= index; i++) {
        if (data.charAt(i) == separator || i == maxIndex) {
            found++;
            strIndex[0] = strIndex[1] + 1;
            strIndex[1] = (i == maxIndex) ? i+1 : i;
        }
    }
    return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}

```

It works fine, but ESP receive only three values, another 6 does not. I have tried to change bitrate to 57600, but thats not help. I think that there is a problem with speed or waiting for full data.

Can you help me ? Many Thanks.

Here is the output from ESP:

```
This arrived: (unparsed)0.000000:0.000000:0.000000:0.00
DATA sensors: (parsed)
0.000000
0.000000
0.000000
0.004

xxxx

```

# Answer
> 0 votes
You are sending number+'.'+6 float +separator = 9 char at least.

You are sending 9x this, 81 char at least. Plus '\<\>' and maybe some more chars...

And you store it in 32 char long buffer. Somehow it does not fit all inside, who knows why? :(

As you can see, you got like 32 chars only of the full transmission. Try to set `numChars` to something like 100 and try again. See, if it is better.

(Also I would use pattern

```
      ARD_ESP.print("<");
      Serial.print("<");
      ARD_ESP.print(totalVolume[0],6);
      Serial.print(totalVolume[0],6);
      ARD_ESP.print(":");
      Serial.print(":");

```

to leave the ESP more time to process stored data, but it is probabelly not problem now)

---
Tags: arduino-uno, serial, esp8266, communication, softwareserial
---


title: Qduino Mini bricked?

text:
# Question
Title: Qduino Mini bricked?
So I have been experimenting with keyboard inputs and I think I may have accidentally put a loop in my code that never actually ends the keyboard input thus not allowing me to upload any sketches to fix the problem.

Here is the error code I got when I tried to upload a blank into the qduino:

```
Arduino: 1.8.1 (Windows Store 1.8.1.0) (Windows 10), Board: "Qduino Mini"

Build options changed, rebuilding all
Sketch uses 4136 bytes (14%) of program storage space. Maximum is 28672 bytes.
Global variables use 148 bytes (5%) of dynamic memory, leaving 2412 bytes for local variables. Maximum is 2560 bytes.
An error occurred while uploading the sketch
processing.app.SerialException: Error opening serial port 'COM11'.
    at processing.app.Serial.<init>(Serial.java:125)
    at processing.app.Serial.<init>(Serial.java:66)
    at processing.app.SerialMonitor$3.<init>(SerialMonitor.java:93)
    at processing.app.SerialMonitor.open(SerialMonitor.java:93)
    at processing.app.AbstractMonitor.resume(AbstractMonitor.java:110)
    at processing.app.Editor.resumeOrCloseSerialMonitor(Editor.java:2240)
    at processing.app.Editor.access$2400(Editor.java:77)
    at processing.app.Editor$DefaultExportAppHandler.run(Editor.java:2315)
    at java.lang.Thread.run(Thread.java:745)
Caused by: jssc.SerialPortException: Port name - COM11; Method name - openPort(); Exception type - Port busy.
    at jssc.SerialPort.openPort(SerialPort.java:164)
    at processing.app.Serial.<init>(Serial.java:114)
    ... 8 more
Error opening serial port 'COM11'.

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

```

# Answer
> 1 votes
Ok strange, just after posting this the qduino decided to flash a different light on me so I try to upload again and it works... So apperantly just by keeping the qduino connected for some time it will start to work again...

---
Tags: programming, hardware, keyboard, arduino-mini
---


# Question
Title: Use an Arduino to "intercept" transparently serial communication to Grbl?
I need to have an Arduino "spying" on communications between the PC and another Arduino with GRBL. The goal is to intercept a couple of GCode commands and act on them instead of Grbl.

My first step is to attempt to be as transparent as possible, but so far, I am not getting from Grbl the clear answer I expect. For example, I get `Grbl 1.1d [?2???B???u5` instead of `Grbl 1.1d ['$' for help]`

Here is my code so far.

```
#include <SoftwareSerial.h>

int PortOneTX = 10;
int PortOneRX = 11;

const String USB = "USB";
const String GRBL = "GRBL";

char endOfLine = '\n';

SoftwareSerial portOne(PortOneRX, PortOneTX);

String grblBytes = "";
String USBBytes = "";

void setup()
{
    Serial.begin(115200);
    while (!Serial)
    {
        ; // Do nothing, just wait till we are connected through USB
    }
    portOne.begin(115200);
    portOne.write("\r\n");
    delay(2);       ;
}

String stringtoWrite = "";

void loop()
{
    if (portOne.available() > 0)//while (portOne.available())
    {
        stringtoWrite = portOne.readStringUntil(endOfLine);
        for (int i = 0; i < stringtoWrite.length(); i++)
        {
            Serial.write(stringtoWrite[i]);
        }
        Serial.write(endOfLine);

    }
    if (Serial.available() > 0)//while (Serial.available())
    {
        stringtoWrite = Serial.readStringUntil(endOfLine);
        for (int i = 0; i < stringtoWrite.length(); i++)
        {
            portOne.write(stringtoWrite[i]);
        }
        portOne.write(endOfLine);

    }
}

```

I feel that I should be using events instead of if (serial.available) in the loop, but I am not sure how to go about it. I thought it would be easy!

Anyway, as I want Grbl-Panel to work totally transparently, I need this first step to be Ok before doing anything else.

Thanks for your help.

# Answer
I finally solved my problem by buying an Arduino Due! It was a problem of speed, not of code. The Uno is just not powerfull enough to read an write to Software Serial at 115200 Bauds, or even 9600, which I tried.

The Due has absolutly no problem. I made a small code test to intercept "words" coming form "USB" To "GRBL", and it works just as expected, while GCODE is send (using Grbl-Panel on the PC) through the Due (USB) to the Uno (Grbl).

It's the very first time I solve what I thought to be a code problem by an hardware solution.

BTW, in case anyone wonder, yes, I am using a level shifter between the 2.
> 3 votes

---
Tags: serial, softwareserial, software
---


# Question
Title: How can i provide enough power on an UNO to use the HC-12 wireless module?
Scenario: The Uno is being powered by USB for programming, and the HC-12 wireless communications module is wired correctly. But it will not work.

In reading through the web literature, it is mentioned that to use the HC-12 in the high-power (100 mW) mode requires a power supply in excess of what the laptop's USB port will provide.

I am finding nothing on Stackexchange that addresses this issue.

So the question is, how do I get the power to run the Uno with the HC-12? I need to be able to periodically update the programming and test it while that auxiliary power is applied, and need to know it is safe to do so.

# Answer
There two options I have found that work well.

First is a simple wall-wart that provides 12 Volts to a barrel connector, like for a CCTV camera.

Or, if I want to run the Uno from a separate higher-amperage USB charging port I have found that there are "USB A Male to CCTV male" cables that work.

Doing the latter means the Uno is running at 5V instead of utilizing the on-board regulator to drop a higher-voltage input, which only matters if your circuit expects to find more than 5 Volts on the Vin pin (although that is not supposed to be an output pin, of course).

Through thorough experimentation I've proven that both methods work.

The best part is that the Uno can easily tolerate having both CCTV-style power and also being plugged into the laptop for programming and testing (like using the serial monitor).

Lesson learned: The HC-12 simply will not work without auxiliary power, and it is safe to provide such power while also plugging the serial port into a laptop.
> 1 votes

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


# Question
Title: Flash an ESC Through Serial USB without Arduino Interrupting the Signal
So I have four Electronic Speed Controllers (ESC's), each connected to a motor. I am building a drone with an Arduino UNO board as my flight controller. For convenience, I have soldered the signal wires on each of the four ESC's onto the bottom of the Arduino where the Arduino's pin headers are soldered on. The serial ground pins on the ESC's are soldered to the ground pins on the Arduino.

The ESC's I am using can be found here.

In order to change settings on my ESC's, I am trying to use this Turnigy USB linker to connected to the BLHeli software on my computer. The linker has a signal and a ground wire for Serial Communication, as well as a positive wire (I think this is just to fit the connector on ESC's with a BEC, but mine are OPTO, and have none). To connect the USB Linker to an ESC, I should be able to plug it into appropriate female pin headers on the Arduino using some breadboard-type jumper cables.

At least that's what I thought...

Whenever I try to connect to an ESC with the BLHeli software, I get a message: *Please Connect ESC and power up or cycle power.*

Earlier, I was able to make the connection and change the settings on my ESC's when they weren't connected to the Arduino board, but now that they are soldered and hot-glued on there, they won't work. So the question is: **What is the Arduino doing to the Serial connection, and how can I fix it without desoldering my ESC's whenever I need to change some settings?**

Now before you ask:

* Yes, the ESC is powered up and connected to a motor. It gives me a happy beeping sound.
* Yes, I definitely have the signal and ground wires connected correctly. I have been trying to figure this out for days, and have even tried switching them.
* The Arduino is turned off when I try to connect an ESC to the USB Linker.
* Only one ESC is powered on at a time.

Maybe the Arduino has some kind of protection circuit for the IC that is messing up the signal, or maybe the ESC's have something similar that's messing it up too, because some of the ground wires are connected together. I'm going to have a very difficult time figuring this out myself, so hopefully someone out there has an idea of what's going on.

Thanks for any help you have to offer.

-- Ember

# Answer
As far as I can tell, it is not possible to program a Turnigy Multistar ESC while it is connected in parallel to any pins on an Arduino. Whether the Arduino is off, or the pins are set to input, output, HIGH, or LOW, the signal is disrupted somehow.

**Solution:** Don't do what I did and solder the ESC's to your Arduino unless you want to de-solder them to change settings. Sticking some wires into the Arduino's pin headers will not make a strong connection, so I would recommend *soldering some sort of strong JST connectors to the pins on the Arduino.*

Hope this all helped, and good luck,

-- Ember
> 0 votes

# Answer
I can offer general advice without reference to specific implementations.

By driving the Arduino pins when it is powered off you are potentially exceeding it's maximum rated specifications for voltage on any ping, and possibly for current into a pin, and you risk damaging it.
When the Arduino is powered down its Vdd pin and power supply rail will be at about 0.0 volts and will be loaded to ground by power supply capacitors and various other items connected to Vdd - including the OUTPUT of the Vdd voltage regulator in many cases.
Each Arduino pin is connected to the Vdd rail by a body / protection diode. To drive the pin high you must also raise Vdd to high-1 diode drop and must drive the Vdd rail load from your signal line via the body diode.
If your programmer has the ability to do this there is a reasonable chance that you may damage the body diode. For extra points, a very capable signal input MIGHT damage the Arduino's voltage regulator and possibly other on board devices - but I'd think that to be unlikely.

The technically best solution is to disconnect the Arduino's relevant pins when programming. As you obviously would rather not do that, then ...

**Probable solution:** If you power on the Arduino and run a program which ensures that the relevant pins are set to input mode then it should work as required. IF the Arduino default program sets the relevant pins to inputs then just powering it on should suffice, but odds are that the serial port pins are not both configured as inputs.
If the Arduino has a USB to serial port IC or other devices connected to the pins in question then you will need to also ensure that they do not load the pin excessively and that they will not be damaged by programming signals. eg if you were trying to drive the Arduinos serial RX\_in pin which was connected to the TX\_out pin of a USB-Serial IC then the programmer would be attempting to drive the USB-serial output pin and this must be dealt with in some way.

**Checklist:**

* Is there something else connected to this pin.

If so

* What state is it in during ESC programming
* Will it be damaged by programming
* Will it affect programming.
* What action is thus needed.
> 1 votes

---
Tags: serial, drone
---


# Question
Title: Which tft works on both Arduino Uno and Raspberry pi
Ideally I'd like a 2.8 inch and it to be touch screen. But most of all I'd rather it work on both boards without much hassle.

# Answer
Well any display can work on both of the boards if you can adjust the voltage levels right there is a display which was made for old Nokia phones and it is called nokia-5110-3310 and is dirt cheap display and it can be used with both Arduino or raspberry pi or any other board which support the protocol here is a link for quick reference.

Adafruit link to the library
> 1 votes

# Answer
adafruit has a resistive touch screen which is 2.8" and works on most boards. Its 30 dollars and works well. It has instructions and all and libraries which you can use. Plug it into a breadboard, connect the jumpers and you're all set.

https://www.adafruit.com/product/1770

on the other hand, Elegoo has made a very similar product, which can also be used on most boards if you plug it into a breadboard, but it is specially designed for the UNO. You can plug it straight into the UNO board, without the need of breadboards. This comes with a instructional DVD and is only 12 dollars on Amazon. It is also a resistive screen and basically the same product.

https://www.amazon.com/gp/product/B01EUVJYME/ref=oh\_aui\_detailpage\_o04\_s01?ie=UTF8&psc=1

Good luck!
> 0 votes

---
Tags: arduino-uno, raspberrypi, tft
---


# Question
Title: Serial.print start prints unreadable character without any reason
I wrote the following code. The idea is to execute some AT command on my ESP-01 module. The problem is that first command is execute without problem, the second sometimes but the reply on AT+GMR is the following: AT

```
OK
AT+GMR

AT version:1.1/0.0(May 11 3016 18:09:57)
SDK version:1.5.ar.0
AR)�WS�TZ�j
C�j�L�AZCA�O�C�

FINE

```

The problem is that, after some thing that I don't understand, the formatting (maybe the baud change?) gone wrong. Then the reply of the following commands became unreadable. Any idea why it happens?

```
#include <SoftwareSerial.h>
#define DEBUG true
SoftwareSerial wifi(2,3);

void setup() {
   Serial.begin(115200);
   wifi.begin(115200);
   sendCommand("AT\r\n", 2000);
   sendCommand("AT+GMR\r\n",2000);
   sendCommand("AT+CWMODE=2\r\n", 2000);
   sendCommand("AT\r\n", 2000);
   Serial.print("\n\nFINE");
}

void loop() {}

String sendCommand(String cmd, int timeout){
   wifi.print(cmd);
   return readSerial(timeout);
 }

 String readSerial(int timeout){
   long int time = millis();
   String res = "";
   while( (time+timeout) > millis() ){
        while(wifi.available()){
          char c = wifi.read();
           res += c;
        }
    }
    if(DEBUG)
       Serial.print(res);

    return res;
 }

```

# Answer
The problem was about high baud for SoftwareSerial. Changing it to 9600 the problem disappears.
> 1 votes

# Answer
Take a look at the connections check the all the connections properly i also had the same problem
> 0 votes

---
Tags: serial
---


# Question
Title: Which external programmers work reliably with Arduino Mega?
When looking for alternate external programmers (ISPs), I am noticing that many are not Arduino Mega 2560 compatible (e.g. Pocket AVR Programmer, USBtinyISP).

I am looking for a reliable external programmer for the Arduino Mega that is compatible with the Arduino IDE. What are my options? Currently I have been struggling with the retired ArduinoISP programmer, which doesn't look like its going to work. **Does anyone have proven experience with a given programmer and a Mega?**

The suggested AVR-mkII doesn't seem to be available anymore either.

# Answer
> 2 votes
I have successfully used Arduino as ISP (not to be confused with Arduino ISP) on a Mega clone that has a funky FTDI-clone onboard, and would not let me upload bootloader through serial. This worked fine, and is cheap.

# Answer
> -1 votes
a test would be if any of those programmers mentioned about could program a big file (64KB+).

if I were you, I would look into that instead.

---
Tags: arduino-mega, isp, programmer
---


# Question
Title: dns lookup only works with DHCP and not with static setup (EtherCard library)
When I use DHCP with `ether.dhcpSetup()` the DNS lookup for NTP `ether.dnsLookup("0.pool.ntp.org")` works fine, but when I use a static setup (because my Android app needs to know the IP address) with `ether.staticSetup(myip);` then this returns false and I don't get an IP address from the NTP pool. How come?

I have an Arduino Nano ATmega328 with a ENC28j60 ethernet shield, and therefore use the EtherCard libray.

Full MWE:

```
#include <EtherCard.h>      // https://github.com/jcw/ethercard
#include <Time.h>           // http://www.arduino.cc/playground/Code/Time

static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };
static byte myip[] = {192, 168, 2, 106};
const char poolNTP[] PROGMEM = "0.pool.ntp.org"; //pool to get time server from
uint8_t ntpMyPort = 123; //port for the time server, no idea why needed

byte Ethernet::buffer[700];

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

 //do not forget to add the extra '10' argument because of this ethernet shield
  if (ether.begin(sizeof Ethernet::buffer, mymac, 10) == 0) {
    Serial.println(F("Failed to access Ethernet controller"));
  }

  //static setup
  ether.staticSetup(myip);
  ether.printIp("Address: http://", ether.myip);

 //this works
//  if (!ether.dhcpSetup())
//    Serial.println(F("DHCP failed"));

  //Find ip address of a time server from the pool
  if (!ether.dnsLookup(poolNTP)) {
    Serial.println("DNS failed"); //with static setup this line is executed, not so with DHCP
  }
  ether.printIp("Lookup IP   : ", ether.hisip);
}

void loop () {}

```

# Answer
DHCP does more than just give you your IP address: it also gives you the Net Mask, the Gateway IP address, and the DNS Server IP address. If you don't call `dhcpSetup()`, you'll have to do it yourself.

According to the `EtherCard` documentation, you can do that as follows:

```
const static uint8_t ip[] = {192,168,0,100}; // Example
const static uint8_t gw[] = {192,168,0,254}; // Example
const static uint8_t dns[] = {192,168,0,1};  // Example

...

if (!ether.staticSetup(ip, gw, dns)
{
    // handle failure to configure static IP address
    // (current implementation always returns true!)
}

```
> 1 votes

# Answer
the documentation of ethercard.h and examples doesn't fit the actual version of *ethercard* very well.

for static ip setup use:

```
ether.staticSetup(myip, gwip, dnsip, netmask);

```

then the dnslookup works. most examples use the old **mymask** name, that is replaced by **netmask**
> 1 votes

---
Tags: ethernet
---


title: LCD displays wrong temperature

text:
# Question
Title: LCD displays wrong temperature
Hi I have a program that does not work right as I aspect:

```
v = tempC;
h = tempC * 10;
h = h % 10;
memset(stempCA, 0, sizeof(stempCA));
sprintf(stempCA, "%+.2d.%d", v, h);

```

it works fine on positive temperature "+11.22" but not for negative values : "-02.-1"

where is my mistake? thanx

# Answer
I think, that -1%10=-1, not 9 as you would like. I use

```
if (tempC<0) {print'-';tempC=-tempC;};
print tempC as usual for positive numbers

```
> 1 votes

---
Tags: arduino-mega
---


# Question
Title: Error: Cannot find module 'serialport'. node.js, Arduino Yun
I carefully followed Andy Sigler's tutorial on how to setup node.js on Arduino Yun. But I'm getting this error "Cannot find module 'serialport'". my node.js file is in mnt/sda1/arduino/node folder. and I have installed node-serialport successfully through ssh. Kindly helpc

# Answer
> 0 votes
I solved the problem by following these steps:

Make a folder node\_modules in mnt/sda1/

cd /mnt/sda1

wget http://wiki.linino.org/lib/exe/fetch.php?media=wiki:serialport-1.6.1\_mips-25-ubuntu.tar.gz -O serialport-1.6.1\_mips-25-ubuntu.tar.gz

run $ tar xvf serialport-1.6.1\_mips-25-ubuntu.tar.gz -C /mnt/sda1/node\_modules

---
Tags: serial, arduino-yun, node.js
---


# Question
Title: Why is integer-to-string not working in this sketch?
I am using a Pro Mini to read analog values and to send them via serial.

Goal of the sketch is to stream these values to Serial as fast as possible, to obtain a steady stream of at least 1000 readings per second. For this reason I reduced the ADC prescaler and I increased serial speed.

I tested sending binary values with Serial.write and it works (it's the fastest), I tested Serial.print (it's the slowest), and I tested an optimised conversion integer-to-string (found on StackOverflow) in association with Serial.write.

This optimised conversion is faster than Serial.print (it would allow me to send the full strings within the given timeframe), but it gives me wrong values. I cannot understand why it happens, the code looks fine to my not-so-expert eye.

A correct stream as sent by Serial.print would be (spaces added for clarity):

```
3075 \t 2800 \t 4132 \n

```

"Wrong values" means that the last value gets repeated for all the three columns:

```
4132 \t 4132 \t 4132 \n

```

What is the issue in my code regarding the int2str conversion?

Since I cannot get one measurement taken and sent every 500 us, I would like to use the optimised routine to get plaintext readings at 1000 us intervals.

The source code follows. I cut out the function slimADC because it was tested as working, while I left all the 3 methods for sending data via serial: binary, optimised, Serial.print.

```
#include <digitalWriteFast.h>

volatile unsigned long previousMicros, currentMicros;

#define SAMPLES 8
volatile unsigned int valuesX;
volatile unsigned int valuesY;
volatile unsigned int valuesZ;

char* x;
char* y;
char* z;

void setup() {
// set pins, ADC prescaler and initialise ADC
  pinModeFast(A0, INPUT);
  pinModeFast(A1, INPUT);
  pinModeFast(A2, INPUT);
  ADCSRA &= ~(bit (ADPS0) | bit (ADPS1) | bit (ADPS2)); // clear bits
  ADCSRA |= bit (ADPS0) | bit (ADPS2);  // 32: 32 us per ADC
  slimADC(0);
  slimADC(0);

// initialise Serial
  Serial.begin(250000);
  Serial.write("\n");
  Serial.write("\n");
  previousMicros = 0;
}

void loop() {
  currentMicros = micros();
  if ((currentMicros - previousMicros) < 1000) { return; }
  previousMicros = currentMicros;

// ADC readings, repeated SAMPLES times
  valuesX = 0;
  valuesY = 0;
  valuesZ = 0;
  for (uint8_t i = 1; i < SAMPLES; i++) {  // 8*3*32=768 us
    valuesX += slimADC(0);
    valuesY += slimADC(1);
    valuesZ += slimADC(2);
  }

// SERIAL TRANSMISSION

// fastest
//  Serial.write(valuesX / 256);
//  Serial.write(valuesX % 256);
//  Serial.write("\t");
//  Serial.write(valuesY / 256);
//  Serial.write(valuesY % 256);
//  Serial.write("\t");
//  Serial.write(valuesZ / 256);
//  Serial.write(valuesZ % 256);
//  Serial.write("\n");

// good
  x = int2str( valuesX );
  y = int2str( valuesY );
  z = int2str( valuesZ );
  Serial.write(x);
  Serial.write("\t");
  Serial.write(y);
  Serial.write("\t");
  Serial.write(z);
  Serial.write("\n");

// slowest
//  Serial.print(valuesX);
//  Serial.print("\t");
//  Serial.print(valuesY);
//  Serial.print("\t");
//  Serial.print(valuesZ);
//  Serial.print("\n");
}

static int slimADC(uint8_t pin) { ... }

char _int2str[7];
char* int2str( register int i ) {
  register unsigned char L = 1;
  register char c;
  register boolean m = false;
  register char b;  // lower-byte of i
  // negative
  if ( i < 0 ) {
    _int2str[ 0 ] = '-';
    i = -i;
  }
  else L = 0;
  // ten-thousands
  if( i > 9999 ) {
    c = i < 20000 ? 1
      : i < 30000 ? 2
      : 3;
    _int2str[ L++ ] = c + 48;
    i -= c * 10000;
    m = true;
  }
  // thousands
  if( i > 999 ) {
    c = i < 5000
      ? ( i < 3000
          ? ( i < 2000 ? 1 : 2 )
          :   i < 4000 ? 3 : 4
        )
      : i < 8000
        ? ( i < 6000
            ? 5
            : i < 7000 ? 6 : 7
          )
        : i < 9000 ? 8 : 9;
    _int2str[ L++ ] = c + 48;
    i -= c * 1000;
    m = true;
  }
  else if( m ) _int2str[ L++ ] = '0';
  // hundreds
  if( i > 99 ) {
    c = i < 500
      ? ( i < 300
          ? ( i < 200 ? 1 : 2 )
          :   i < 400 ? 3 : 4
        )
      : i < 800
        ? ( i < 600
            ? 5
            : i < 700 ? 6 : 7
          )
        : i < 900 ? 8 : 9;
    _int2str[ L++ ] = c + 48;
    i -= c * 100;
    m = true;
  }
  else if( m ) _int2str[ L++ ] = '0';
  // decades (check on lower byte to optimize code)
  b = char( i );
  if( b > 9 ) {
    c = b < 50
      ? ( b < 30
          ? ( b < 20 ? 1 : 2 )
          :   b < 40 ? 3 : 4
        )
      : b < 80
        ? ( i < 60
            ? 5
            : i < 70 ? 6 : 7
          )
        : i < 90 ? 8 : 9;
    _int2str[ L++ ] = c + 48;
    b -= c * 10;
    m = true;
  }
  else if( m ) _int2str[ L++ ] = '0';
  // last digit
  _int2str[ L++ ] = b + 48;
  // null terminator
  _int2str[ L ] = 0;
  return _int2str;
}

```

**Appendix**

The bare ADC conversions take about 768 us.

With binary data I am sending via serial 3x uint16\_t plus one end of line and two tabs, meaning 9 characters per reading. At 250 kbps 8N1 the minimum time required is 324 us. Using RealTerm (for Win) I can see that I get a stram of 9k chars/s, as expected.

With Serial.print I am sending 4x string\[4\] (readings are always between 1000 and 9999), plus tabs and newline, meaning 15 bytes per reading. RealTerm however gives me an incoming stream of 11-12k chars/s, therefore Serial.print is too slow.

The optimised int-to-string function (even without modifying it to avoid checking for negative and for \>9999, not needed in my case) still sends 15 bytes per reading, and RealTerm also shows me an actual stream of 15k chars/s, as expected.

# Answer
> 2 votes
it took me a while and i'm still not 100% sure if I got you right. I think you have two questions:

> 1) how to speed up the entire execution?

the serial routines will be your biggest bottleneck. I would suggest that a) you speed up the baud rate; and b) you try to use a tx interrupt here.

> 2) why isn't the int2str() routine working?

because int2str() stores the converted string in a buffer (\_int2str\[\]), which is subsequently destroyed by conversions. so for it to work, you should do something like this:

```
  serial.write(int2str(x)); serial.write("\t");
  serial.write(int2str(y)); serial.write("\t");
  serial.write(int2str(z)); serial.write("\n");

```

BTW, int2str() can be written a lot better than it is now.

edit: to add an alternate int2str() implementaton.

```
//positive and negative numbers
//int is 16-bit type
char *int2str2(int i) {
    static char _int2str[7];
    unsigned char tmp, str_len=0;       //converted string starts at _int2str[0]

    //process the sign
    if (i&0x8000/*<0*/) {
      _int2str[str_len++]='-';          //insert leading '-'
      i=-i;                             //make the number positive
    };

    //convert the next position (10,000)
    tmp = 0;                            //reset tmp
    while (i >= 10000) {
      i-=10000;                         //decrement i
      tmp+=1;                           //increment counter
    }
    _int2str[str_len++] = tmp + '0';    //form the msb

    //convert the next position (1,000)
    tmp = 0;                            //reset tmp
    while (i >= 1000) {
      i-=1000;                          //decrement i
      tmp+=1;                           //increment counter
    }
    _int2str[str_len++] = tmp + '0';    //form the msb

    //convert the next position (100)
    tmp = 0;                            //reset tmp
    while (i >= 100) {
      i-=100;                           //decrement i
      tmp+=1;                           //increment counter
    }
    _int2str[str_len++] = tmp + '0';    //form the msb

    //convert the next position (10)
    tmp = 0;                            //reset tmp
    while (i >= 10) {
      i-=10;                            //decrement i
      tmp+=1;                           //increment counter
    }
    _int2str[str_len++] = tmp + '0';    //form the msb

    //convert the lsb
    //tmp = 0;                          //reset tmp
    //while (i >= 100000ul) {
    //  i-=100000ul;                        //decrement i
    //  tmp+=1;                         //increment counter
    //}
    tmp = i;
    _int2str[str_len++] = tmp + '0';    //form the msb

    return _int2str;
}

```

here is what I would use. I benchmark against yours, converting numbers from 0 to 32767. total cycle count for yours is 10.5 million and 7.0 million for mine. Now, the actual performance will depend on a lot of factors, like your chips, compilers (I used IAR AVR), and optimization settings, to name a few.

Note: the routine was written as a generic one. if you are only converting 10-bit numbers (from a 10-bit adc for example), it can be greatly simplified, and execution time greatly shortened: \<160K cumulative cycles converting numbers from 0 to 1023.

---
Tags: serial, string, code-optimization, debug
---


# Question
Title: What does an arduino sketch translate to before compilation?
I've been experimenting with Arduino on both esp8266 and AVR chips. The structure of the `.ino` file usually looks like this:

```
#include "Arduino.h"
#include "ESP8266WiFi.h"
##Some includes

void setup()
{
...
##Will be only run once at the begining.
}

void loop()
{
##Runs this code in a constant loop
}

```

My assumption is that somewhere behind simplification, before the compilation takes place, there is a `full blown source file`. It includes the platform specific initialization and contains the calls to `setup()` and `loop()`. When I say `full blown source file` I mean something that can be passed to the compiler and will compile given that the dependencies are met.

My questions are:

* Is this assumption correct?
* If so, can someone share an example on how does the `full blown source file` look like, and where did you get it from?

# Answer
The Arduino core libraries (which are nothing more than a bunch of C/C++ files - there is no such thing as the "Arduino" programming language), are compiled along with your source code. These files include all of the initialisation routines and function definitions for things like `digitalWrite` and so forth.

There is a `main.cpp` file that gets compiled which is pretty much nothing more than:

```
#include "Arduino.h"

int main(void) {
    //Initialise timers and things (internal)
    init();
    //Your initialisation stuff (setup)
    setup();
    //Loop forever
    for (;;) {
        //Calling your loop function
        loop();
    }
}

```

In terms of what your `.ino` file becomes, it is basically just copied to a temporary build directory and renamed to `.cpp`. There are some minor changes made, which is basically to just copy all of the function declarations and place them at the top of the file.

This process is actually why if you use your own header file which has some `typedef` in it which you then use in a function call, the code will break because the declarations get added above the `#include` statements meaning the custom type is used before it is defined.

If you go to the preferences you can tell it to enable verbosity during compilation. This will actually show you exactly what is being compiled. It will also give you the path to the temporary build directory in which you will find the `.cpp` file with the same name as your `.ino` file.
> 6 votes

# Answer
C++ (the actual language/compiler that is used) is a multiple-compilation-unit language. There is no single source file, but rather a bundle of compiled source files, that are linked together to create the executable (or downloadable image).

In you case the user sketch provides the `setup()` and `loop()` functions, which are called from another source file, which is provided by the Arduino IDE.
> 0 votes

---
Tags: avr, esp8266
---


# Question
Title: Why adding a LED between Pin 3 and Ground causes LCD display not to show text?
For a project of mine I am programming an Arduino UNO to show information I get from some sensors on an LCD display.

As a first step I setup Arduino to show "Hello, world!" on the LCD, which worked.

For "decorative" reasons I wanted to add some LEDs between the resistors that I placed in series between PIN 3 (V0) of the LCD and ground (about 1.5K Ohm total resistance).

I first of all added one LED between the last resistor and ground. To my surprise this causes the LCD display not to show "Hello, world!" any more. As you can see the current is flowing (the LED is lit), but I can't understand why the LCD does not show the text.

Can you help me understand what's going on? I know very little of electronics and I am learning it by doing, so I would appreciate an answer that is good for a beginner!

# Answer
> 1 votes
In a typical 1602 LCD pinout, pin 3 or V0 is the contrast setting for the display. It usually is set to a voltage near ground, often by using a 10K pot with ends connected to Vdd and Vss with wiper to V0.

By putting an LED in series with your resistors (that apparently go to ground) you've either disconnected V0 from ground or have raised its voltage by the LED voltage. This reduces contrast to the point that characters aren't visible even though they are on the display.

The LED backlight remains on and at the same brightness as before because it is driven via pins 15 and 16, independent of all other display settings.

*Edit 1:* I haven't duplicated your circuit to take measurements, so at the moment don't know for sure; but (in resistors-only case) V0 from pin 3 on the 1602 LCD board apparently sources some small current through your 1500 Ω to ground. When you add an LED it can disconnect V0 from ground or can raise its voltage by the LED voltage, as follows: firstly, if the LED cathode faces V0 and V0 is positive, no current will flow through the diode, thus disconnecting V0. Secondly, if the LED anode faces V0 and V0 is positive, current will flow through the LED. If the LED lights at all, most of its Vf characteristic voltage (typically between 3 and 4 volts for a green LED) will appear across it. Thus, V0 sits at close to Vf plus whatever drops across the resistors.

\*The same as for other diodes, LED forward current increases exponentially with voltage (Ref: wikipedia on LED physics) hence voltage change is tiny over large changes in current when an LED is emitting light. In other words, if the LED is lighting up, its voltage will be close (ie within a few dozen millivolts) to its characteristic band gap voltage. See petervis.com's led-resistor-calculator for a "Chart by Colour" that shows characteristic Vf forward voltages.

# Answer
> 0 votes
> Can you help me understand what's going on?

that pin controls the contrast and it needs to be 3.5 - 4.x volt (typical) below Vcc. an led in conduction would drop 2 - 3v, depending on the led, making that pin's potential much closer to Vcc -\> minimum contrast so you cannot see the text being displayed.

---
Tags: arduino-uno, led, lcd
---


# Question
Title: How to handle multiple simultaneous Arduino development environments?
I am developing for several different target microcontrollers (on OS X 10.11), which requires some unique combinations of (Arduino) IDE version, library versions, USB drivers, support software, etc.

What are the pros and cons of using separate logged-in users for each environment as opposed to using Virtual Machines? Are there other methods commonly in use to separate environments, and also keep the environments archived for any legacy needs?

Update: I also have a desire to keep these environments as standard as possible: installing released components (e.g., IDE, drivers) and customizing IDE app settings, but trying to avoid source-level forks. This is for my own sanity, and to give best chance of replicating the environment in the future.

# Answer
> 3 votes
I'm yet to see evidence that there is a sound or comprehensive way to do this, so would be pleased to read better suggestions. As for why you would want to, there are a number of board support plugins/extensions that are moderately functional on some recent Arduino versions, but partially or entirely incompatible with others.

You can achieve a very limited partial version segregation by creating a new sketchbook folder for each version, which would host your libraries and hardware folders.

To get the IDE to pick this up, you could have a custom preferences file (rather than `preferences.txt`) with that sketchbook location set. You can specify the file to use on the command line, for example:

```
/opt/arduino-1.6.8/arduino --preferences-file ~/.arduino15/alternate.txt

```

However, there is still quite a bit related to extra board support and similar stored in the settings folder, and at present that is hard coded to the same "Arduino15" or ".arduino15" path for all recent versions.

This hard-coding of the settings folder is implemented in the version of `Platform.java` applicable to the operating system you are running under, so it is not clear how you could change this except at the source level, by modifying the jar, or by playing file-system level tricks with the operating system (process-unique mounts, etc).

# Answer
> 3 votes
I ended up running `arduino-buider`, available in Arduino IDE 1.6.6 and newer.

When laying out your project, put a `libraries/` and `hardware/` folder along side your sketch directory, like so:

```
YourHipProject/
    Makefile
    hardware/
        Vendor/arch/{boards.txt,platform.txt}
    libraries/
        SomethingUseful/
        NoIdeaHowThisWorks/
    ProjectSketch/
        ProjectSketch.ino
        othersource.cpp

```

The `hardware/` directory is only needed if you need support for 3rd party boards. Then, in the `Makefile`:

```
ARDUINO_DIR ?= /opt/arduino-1.6.13 # need to set this for your environment

.PHONY: ProjectSketch

ProjectSketch:
    arduino-builder -compile -verbose \
        -hardware $(ARDUINO_DIR)/hardware \
        -tools $(ARDUINO_DIR)/tools-builder \
        -tools $(ARDUINO_DIR)/hardware/tools/avr \
        -built-in-libraries $(ARDUINO_DIR)/libraries \
        -hardware ./hardware \
        -libraries ./libraries \
        -fqbn=Vendor:arch:board \
        ./ProjectSketch/ProjectSketch.ino

```

`ARDUINO_DIR` needs to point to where your Arduino is installed, be sure to set `-fqbn=` correctly too.

Running `make` should compile the firmware from `ProjectSketch/` with the accompanying libraries and hardware definitions. Also, with verbose compile output enabled, the Arduino IDE will show you how it runs `arduino-builder`.

---
Tags: arduino-ide
---


# Question
Title: Arduino read PWM duty cycle value with input (analog / digital)
I am working on comparing autopilots like Ardupilot, CC3D, KK2.1.5. The comparision is about system reactions/behaviors that it gives during flight. For this purpose, I need to read the PWM duty cycle (like osilascopes - the PWM frequency can be vary from 50 to 430 Hz) values from autopilot card. There are 4 command input PWMs and 4 esc control PWMs for a typical quadrotor. **I have to read 8 duty cycle values with digital/analog input pins.** How do I measure duty cycle of 8 PWM signals? Also, is digital or analogue measurement precise and faster?

*Note about **attachInterrupt** command: According to arduino.cc AtMega328 series have **2** interrupts, Arduino ATmega 2560 series have **7** interrupts.*

# Answer
The code shown in my answer to question 18183, “Read RC receiver channels using Interrupt instead of PulseIn”. That answer has code to read four channels of RC PWM. It can easily be adapted to work with eight channels. It has an ISR that runs when selected pins change. It sorts out which channel(s) changed, and stores the value of `micros()` at each change.

Also see my answer to question 19106, “Can external interrupts be OR'd together on the '328 (Uno)?” That answer includes a sketch for generating appropriate ISR code. My answer to question 32572, “How to detect the direction of a rotary encoder?”, shows another instance.

Digital input, as used in the code mentioned above, takes under a microsecond ten microseconds in the ISR. As noted in dannyf's comment, unrolling the `for` loop and (where possible) using constants instead of variables can reduce the in-ISR time to 3.4 μs. Note, ISR entry and exit still add several microseconds.

10-bit analog input, on the other hand, will take around 104 microseconds per reading, a time comparable to some of the pulse widths you'll be measuring. So it isn't fast enough. If degraded ADC accuracy is acceptable, decreasing the ADC-clock scale factor as explained in a webpage at microsmart.co.za can get AD conversion time down to 20 μs. This is around three times as long as digital input takes, so rather slow.
> 2 votes

# Answer
if done in analog, run the pwm through a lpf and perform an adc on the output;

if done in digital, use a timer's capture function, or use external interrupt / pin change interrupt to capture the timing off a time base.
> 0 votes

---
Tags: pwm, analogread, digital-in
---


title: Blend Micro uploading sketch

text:
# Question
Title: Blend Micro uploading sketch
I have just got the Blend Micro board. After following the getting started tutorial I can't manage to upload sketches on the board. Now, in Arduino v. 1.0.6 I see the voices

* Blend
* Blend Micro 3.3V/8Mhz
* Blend Micro 3.3V/16Mhz (Overclock) as in this picture:

While the L Led is switch on if I upload the sketch the TX and RX leds stay off. The modified Arduino IDE says "Done uploading". As port I choose /dev/tty.Bluetooth-Serial-1 and I don't see any other port and I think this is critical.

But if I open the Android BLE application BLE Controller, after tried to upload the **BLEControllerSketch** (from RBL\_nRF8001 libraries) it finds the board but print the error **No Response from the BLE Controller sketch**. If I try with **SimpleChat** example and the SimpleChat Android application if finds the board but prints only "Hello World" and nothing else if I send strings from the android app.

Any kind of advice?

EDIT

I am on a Mac 1.8.5. I have tried also with Codebender, but anything change: I can't see the `/dev/tty.usb*` in the listed ports

# Answer
Did you follow the setup exactly? In particular, did you modify `main.cpp` to have this:

```
#if defined(BLEND_MICRO_8MHZ)
    // As the F_CPU = 8000000UL, the USB core make the PLLCSR = 0x02
    // But the external xtal is 16000000Hz, so correct it here.
    PLLCSR |= 0x10;             // Need 16 MHz xtal
    while (!(PLLCSR & (1<<PLOCK)));     // wait for lock pll
#elif defined(BLEND_MICRO_16MHZ)
    // The CPU clock in bootloader is 8MHz, change to 16MHz for sketches to run (i.e. overclock running at 3.3v).
    CLKPR = 0x80;
    CLKPR = 0;
#endif

```

If not, what happens is once the sketch starts the USB stops working and you can't see the serial port due to the clock speed being incorrect. This is why you can only see `/dev/tty.Bluetooth-Serial-1` in the port list.

1. Modify `main.cpp` according to http://redbearlab.com/getting-started-blendmicro
2. Press the reset button on the Blend Micro, then quickly select *Tools* -\> *Serial Port* in the Arduino IDE. The Blend Micro serial port should be there because the boot loader is still running. It will be named like `/dev/tty.usb????????`
3. Select that serial port. Compile your code. Now press reset at the same time as pressing upload. Your sketch will upload and the serial port should now be present when the sketch is running.

**Update: The Timing Tricks**

Note: Blend Micro is basically the same as Arduino Leonardo.

This is the timing:

1. The reset button is pressed.
2. The ATMega32u4 restarts. It jumps to the bootstrap loader code.
3. The bootstrap loader starts up the USB as a CDC device (serial port) and waits for firmware upload instructions. (Pulsing L LED)
4. If no upload instructions are received within a certain time (8 seconds?), it jumps to the application code.
5. The application code starts up the USB as a CDC device again.However, since the oscillator (clock) on the Blend Micro is different to the Leonardo, it requires the modifications above, otherwise the USB clock will wrong, and the USB won't work.

If the modifications above were not done, Step 3 is the only time when the USB is working and the serial port can be selected in the Arduino software.
> 1 votes

# Answer
For anyone else who is having an issue with this. What worked for me, was replacing the cable with a shorter cable. I could of been using a charging only usb cable or the cable was long enough to not upload correctly.
> 1 votes

---
Tags: serial, uploading, bluetooth
---


title: Failing to write to SD card using SD.h

text:
# Question
Title: Failing to write to SD card using SD.h
Using a knockoff Arduino Nano (pinout seems to be the same), I would like to record data to an external SD card. I have everything hooked up (correctly I think) but I continue to fail to initialize the card using `SD.begin()`.

Here's a snippet of code that I'm running to do this:

```
//Wire and MS5803_I2C libraries for communicating with the pressure sensor.

#include <Wire.h>
#include <SparkFun_MS5803_I2C.h>
// For the SD card reader.
#include <SPI.h>
#include <SD.h>

const int chipSelect = 4;

void setup(void) {
  Serial.begin(9600); // Set baud rate.
  pinMode(10, OUTPUT); // Set data output pin for the SD card reader.
  digitalWrite(10, HIGH);
 // see if the card is present and can be initialized:
 if (!SD.begin(10)) {
   Serial.println("Card failed, or not present");
   // don't do anything more:
   return;
 }
 Serial.println("card initialized.");
  delay(500);  // Wait half a second before continuing.
}

void loop(void) {
  Serial.println("Hello Library!");
  delay(100000);
}

```

Here's the Nano pinout:

And a picture of the circuit.

# Answer
> 1 votes
The Sparkfun pressure sensor has a 3.3V chip and a SD memory card is also 3.3V. Your Arduino Nano is probably a 5V board. How did you connect those to the board ?

When your Nano board is 5V, you need a SD module with a level shifter for the signals.

To make it work, test either the SD or the sensor and try to make it work. When testing the SD, don't connect the sensor and don't even include the sensor library.

# Answer
> 0 votes
Is it my eyes or there's nothing connected to D4...?

```
const int chipSelect = 4;

```

Your chipSelect/CS pin seems connected to D10.

---
Tags: arduino-nano, sd-card
---


# Question
Title: Trouble while using Arduino DUE as programmer
I'm trying to use the arduino DUE board as a AVR Programmer. My target device is atmega328p. After uploading the ArduinoISP into the DUE Board. I've tried to let a pin toggle using the following code:

```
#define F_CPU 10000000
#include <avr/io.h>
#include <util/delay.h>

int main (){
    DDRD |= (1<< PD7);
    for(;;){
        PORTD ^= (1<< PD7);
        _delay_ms(1000);
    }
    return 0;
}

```

I want to use the internal oscillator and based this example I've adjust the makefile:

```
DEVICE     = atmega328p
CLOCK      = 8000000
PROGRAMMER = -c arduino -P COM10 -b 19200
OBJECTS    = main.o
FUSES      = -U lfuse:w:0x62:m -U hfuse:w:0xd9:m -U efuse:w:0xff:m

```

the problem that I have is that when run :

```
make flash

```

I get the following :

and yes the port COM10 is definitely correct.

does anyone have a suggestion how to solve this ?

thanks in advance !

# Answer
> 0 votes
There error you have is from *avrdude* failing to get a communication link established to the 'programmer' (which manipulates the target.)

Here is a link that may help with the connection

Stk500 error

Here is another relative link that may help

Arduino ISP on DUE

Best of luck.

---
Tags: arduino-due, avrdude, arduinoisp
---


# Question
Title: How to power an Arduino Uno with 3 1.5V batteries?
I have an **Arduino Uno** *(a SainSmart model, actually)*. I intend to power it with three 1.5V batteries. I measured them and they yield 4.67V in total. The Arduino requires 5V.

# The question is, if the arduino will work this way.

I'm not powering complicated microcontroller components here. These components are used:

* A buzzer
* An LED
* A unit of 4 seven segment displays
* A couple of buttons as input elements

If the volume or brightness of these components is slightly decreased, it doesn't matter at all. But I would like to know if it will work in the first place.

# And also...

Where exactly do I plug the power source in? The power jack, the USB jack, pins, somewhere else?

---

**The schematic looks like this**, just to illustrate it. I'm not a good drawer, but you'll get the idea...

# Answer
> 11 votes
The Arduino doesn't *require* 5V.

The Atmel chip on the board *requires* somewhere between 1.8V and 5.5V, the Arduino just happens to have chosen 5V as a good common widely used voltage to run at.

If you provide a voltage within that range to the +5V pin the board will operate. There's a couple of caveats though:

* Anything below about 4V will mean the 3.3V regulator won't be working right, so the 3.3V pin won't be functioning properly
* At lower voltages the Atmel chip can't operate reliably at higher frequencies, which is why 3.3V Arduino boards operate at 8MHz instead of 16Mhz.

So 3 x AA batteries is a perfect power source for running the Arduino, direct into the 5V pin. Just make sure that you don't power it any other way at the same time or you'll be pumping 5V into your batteries. You may want to add a Schottky diode in series with your battery + (between battery + and the 5V pin) to stop that ever causing a problem. Choose one with a very low forward voltage drop though, otherwise you could end up dropping too much of your precious voltage over the diode.

By the way, when you're powering it from USB the 5V could be anywhere between 4.75V and 5.25V.

# Answer
> 3 votes
As per @Majenko's answer, yes, this will work fine.

Some caveats: the Atmel chip at the center of the Arduino has brown-out detection - if it drops below a certain voltage, the chip will shut down. This voltage is selectable: 4.3v, 2.7v, 1.8v, or off. The factory default for the chip is "off", I found a reference that the Uno sets this at 2.7V.

Also, if you are powering anything else with your battery, e.g. a motor, the voltage is will drop - if it drops below the brownout, the arduino will shut down (usually also shutting down the external device, causing the voltage to rise again, causing it to power up again). An LED (with a correct resistor) should be fine.

# Answer
> 3 votes
For battery-operated Arduino Uno's I recommend thinking bigger (in terms of power, not physical size).

I power several by using 3x 18650 batteries in series, (providing about 14 Volts, connected to a 4x USB 5 Volt module.

The Unos are connected to power by a standard USB cable (into the programming port), and then you also have 3 other 5V USB charging or power ports available.

Or you can get a small converter unit that provides just one 5V USB.

Either way, bringing the power to the UNO is as simple as using the programming cable that comes with the board.

Or you can use any other converter and use wires to bring in Vin and GND.

You don't need to use 3 of the 18650s. 2 will do fine. Or 4 in series/parallel for longer battery life. No converter would be needed but again you would need wires to bring the voltage into the Unos.

18650s are very common, and are inexpensive. They pack a whole lot more mAh than any AA battery you will find.

One warning about buying 18650s: There are Chinese companies that advertise 9,800 mA batteries. Don't believe it. 3,000 is about the max any reputable manufacturer will claim.

# Answer
> 2 votes
You can power the Arduino via the 5V pin - but you need make sure you disconnect it when you are connected via USB - ie. don't power both the 5V pin and via the USB.

Any even better way is to power it from the USB socket - I use those emergency Phone battery packs, but you could cut up a usb cable and use that - this is a much better socket fit to use than the 5v pin and more energy efficient than passing a higher voltage through the 9V supply.

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