# Question
Title: Measuring frequency of 3-wire 12V fan on Arduino Uno
I am using a PC 12V fan (40x40mm), which I control speed with voltage (with adjustable power supply). I would like to measure the frequency of the fan with Arduino and read it on serial monitor.

I've googled over some results and I came across `pulseIn()`, which I don't quite understand. I've also used this code, which I found here, but it doesn't work for me. I've added `serial.print` and delay line.

My output of this program is: "0000000" etc. and nothing else.

My goal is to set the frequency of the fan to around 50-500 Hz somewhere.

```
int pin = 7;
unsigned long duration;

void setup() {
  Serial.begin(9600);
  pinMode(pin, INPUT);
}

void loop()
{
  duration = pulseIn(pin, HIGH);
  Serial.print(duration);
  delay(1);
}

```

My schematics:

# Answer
> 1 votes
The `pulseIn` measures the duration of a high pulse on the pin. The reference page explains it as well as I ever could. If there is a specific thing you don't understand from it, please ask. However, I don't think it will achieve what you want.

The circuitry in the fan connects the third (yellow?) wire to ground twice per revolution of the fan. To make this into a "pulse" you need to pull the pin high. Twice per revolution, the fan will pull it low.

What you now have is a signal which, for every revolution of the fan, goes `HIGH`, `LOW`, `HIGH`, `LOW`. We want to measure the time from one rising edge to the next. This is the time for half a rotation of the fan.

Here's some untested code:

```
// Wait for signal to go low
while (HIGH==digitalRead(pin)) { /* Do nothing */ }

// Start timing
unsigned long start_time = micros();

// Wait for signal to go high and low again
while (LOW==digitalRead(pin)) { /* Do nothing */ }
while (HIGH==digitalRead(pin)) { /* Do nothing */ }

// Stop timing
unsigned long end_time = micros();

// How long did that take?
unsigned long duration  = end_time - start_time;

```

That code can be improved in various ways but I hope it will let you understand what's going on.

That tells us how LONG half a cycle takes. You can easily find how long a whole cycle would take -- double it. If you want the frequency in revolutions-per-minute, you need to work out how many whole cycles you can get in a minute, which is the same as the number of half-cycles in half a minute:

```
unsigned long rpm = 30000000L / duration;

```

---
Tags: arduino-uno, frequency
---


title: Multiple I2C devices on Arduino

text:
# Question
Title: Multiple I2C devices on Arduino
I'm design a custom PCB based around the Arduino Zero/Adafruit Feather M0. The plan is to use a few I2C devices. I just had a few questions about whether I've designed the board correctly.

You'll see that I've used 10k resistors on each devices's SDA and SCL lines, but is this necessary? I've seen it mentioned on a few online documents for certain breakout boards etc...

Also, are the devices just connected in parallel? Are there any considerations I need to make when using 3 I2C devices like this?

# Answer
> You'll see that I've used 10k resistors on each devices's SDA and SCL lines, but is this necessary? I've seen it mentioned on a few online documents for certain breakout boards etc...

You should have just two 3.3K resistors - one on the SDA and one on the SCL lines. However all your 10K resistors in parallel will equate to about the same thing - just taking up 3x the space.

> Also, are the devices just connected in parallel?

Yes, it's a simple multi-drop bus.

> Are there any considerations I need to make when using 3 I2C devices like this?

Not really, no. The frequencies in use are generally too low to require any specific layout considerations. Just try to keep vias to a minimum and don't snake the traces around the board too far.
> 1 votes

---
Tags: i2c, arduino-zero
---


# Question
Title: Can I code in Arduino depending up on LED status?
I have to count the blinkings of an LED. For that

```
IF (LED = ON)
{
    COUNT=COUNT++
}
Else
{
}

```

Can I code like this algorithm? In Arduino is it possible?

# Answer
Yes, you can make an arduino detect and count LED blinking. You will need some kind of light sensor, such as a photodiode or photoresistor.

Also, you would need to code in C++, and the example pseudo-code you presented is not C or C++.

As you proceed with your project, you may ask more questions here, of a more specific nature. As it stands, your question is very broad.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Reading input from digital pins 36, 37, 38 in Arduino Mega 2560 is giving a problem
I wrote a program to read digital input from pins 36, 37, 38 and print on LCD when they go HIGH. I've connected those pins to a switch to test.

The program looks like this:

```
#include "LiquidCrystal.h"

// initialize the library by providing the nuber of pins to it
LiquidCrystal lcd(8,9,4,5,6,7);
int vswr,th,od,a;

void setup() {
  pinMode(36,INPUT);//SENSING VSWR
  pinMode(37,INPUT);//SENSING THERMAL
  pinMode(38,INPUT);//SENSING OVER DRIVE
  pinMode(35,OUTPUT);//BYTE_CTRL SIGNAL TO SHUTDOWN
  digitalWrite(35,LOW);
}

void loop() {
  vswr = digitalRead(36);
  th= digitalRead(37);
  od = digitalRead(38);
  lcd.begin(16,2);
  // set cursor position to start of first line on the LCD
  lcd.setCursor(0,0);
  if (vswr==1) {
    lcd.write("vswr");
    digitalWrite(35,HIGH);
    delay(2000);
  }
  if (th==1) {
    lcd.write("thermal");
    digitalWrite(35,HIGH);
    delay(2000);
  }
  if (od==1) {
    lcd.write("over drive");
    digitalWrite(35,HIGH);
    delay(2000);
  }
}

```

When I run this, the LCD continuously displays:\**

> vswrthermaloverdrive

Even though none of the pins are high.

When I use Pins 11, 12, 13 instead of 36, 37, 38 it works fine. I already used pins 11,12,13 for some other purpose. Why is this happening? And how do I solve this problem?

# Answer
I expect the problem is in the circuit. To be sure, put a serial print statement directly after reading the inputs, to be sure the input values are read correctly.

See the remark of using INPUT or INPUT\_PULLUP from Jot below.

The following is just a more compact way of writing your loop (and does not fix your problem):

```
void process(int pin, char* text)
{
    if (digitalRead(pin) == HIGH) // Use HIGH instead of 1
    {
       lcd.write(text);
       digitalWrite(35, HIGH);
       delay(2000);
    }
}

void loop()
{
    lcd.begin(16,2);
    // set cursor position to start of first line on the LCD
    lcd.setCursor(0,0);

    process(36, "vswr");
    process(37, "thermal");
    process(38, "overdrive");
}

```

Also, I would add the delay at the end (after the three calls of process). And instead of hard coded values 36, 37 and 38 use 3 constants/defines.
> 1 votes

# Answer
Another thing, only pin == HIGH writes something to the LCD, the message does not magically go away when pin == LOW

Also, about the logic for pin 35, what should happen when alarm goes away? Maybe pin 35 should be low again?

Code suggestion:

```
void process(int pin, char* text)
{
    if (digitalRead(pin) == HIGH) // Use HIGH instead of 1
    {
       lcd.write(text);
       digitalWrite(35, HIGH);
    }
    else
    {
       lcd.write("      ");
    }
}

```
> 0 votes

---
Tags: arduino-mega, digital-in
---


title: nRF24L01 pipe question

text:
# Question
Title: nRF24L01 pipe question
I am looking through the example code found here. I know there are 6 pipes that the nRF24L01 module can use but I've been searching the internet for the address designations and have been able to find nothing. More specifically on line 37, is there a reference for where the author is getting 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL?

Thanks.

# Answer
> 5 votes
As most of the people have posted, the values for the pipe are arbitrary, but must follow the rules per the API:

> Pipes 1-5 should share the first 32 bits. Only the least significant byte should be unique, e.g.

Before I answer your question, I think an explanation on Hex and Decimal values are needed.

The 40 bit hexadecimal is a number representation of base 16. A decimal is of base 10. So you can convert a Hex Value to Decimal. As this is out of scope for the question, you can google on how to convert from one to another. There are some online converters:

Hex to Decimal Converter

You will see when you convert the Hex value to decimal, that its just a number representation. When you convert, you drop the `0x` and `LL`. As stated the `0x` indicates the value is a hex value and `LL` means type Long Long.

So to answer your question, use the a converter to find a hex number like:

```
F0F0F0F0A1
F0F0F0F0A2
F0F0F0F0B4
F0F0F0F0E9

```

Just change the last 2 digits (least significant bit):

```
Pipes 1-5 should share the first 32 bits. Only the least significant byte should be unique, e.g.
   openReadingPipe(1,0xF0F0F0F0AA);
   openReadingPipe(2,0xF0F0F0F066);

```

Add the `0x` and `LL`

```
0xF0F0F0F0A1LL
0xF0F0F0F0A2LL
0xF0F0F0F0B4LL
0xF0F0F0F0E9LL

```

All should work.

I am no expert on hex, as I am learning, so if I am incorrect, then please someone correct me.

Finally, the nRF24L01 datasheet makes the following point that the choice of address is not completely arbitrary:

> Note: Addresses where the level shifts only one time (that is, 000FFFFFFF) can often be detected in noise and can give a false detection, which may give a raised Packet Error Rate. Addresses as a continuation of the preamble (hi-low toggling) also raises the Packet Error Rate.

# Answer
> 2 votes
The values `0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL` are arbitrary values and define the adresses of the senders and receivers to talk to.

If you use the Mirf library

```
Mirf.setRADDR((byte *)"serv1");

```

they can be also strings like `serv1`.

`RF24` uses

```
write_register(RX_ADDR_P0, &value, 5);
write_register(TX_ADDR, &value, 5);

```

# Answer
> 2 votes
There's something that everyone forgets to tell you:

Pipes at **receiver** should be shortened after the first one

```
const uint64_t pipe01 = 0xE8E8F0F0A1LL;
const uint64_t pipe02 = 0xA2LL;
const uint64_t pipe03 = 0xA3LL;
const uint64_t pipe04 = 0xA4LL;
const uint64_t pipe05 = 0xA5LL;
const uint64_t pipe06 = 0xA6LL;

radio.openReadingPipe(1, pipe01);
radio.openReadingPipe(2, pipe02);
radio.openReadingPipe(3, pipe03);
radio.openReadingPipe(4, pipe04);
radio.openReadingPipe(5, pipe05);

```

Pipes at **transmitter** should be

```
const uint64_t pipe01 = 0xE8E8F0F0A1LL;
const uint64_t pipe02 = 0xE8E8F0F0A2LL;
const uint64_t pipe03 = 0xE8E8F0F0A3LL;
const uint64_t pipe04 = 0xE8E8F0F0A4LL;
const uint64_t pipe05 = 0xE8E8F0F0A5LL;
const uint64_t pipe06 = 0xE8E8F0F0A6LL;

uint64_t setPipeToSend = pipe01; // or pipe02 or pipe03 or pipe04 or pipe05
radio.openWritingPipe(setPipeToSend );

```

If you want to know which pipe's message has come, use

```
  uint8_t someVariable;
    if (radio.available(&someVariable))
    {
       Serial.print("pipe number ");
       Serial.printLn(someVariable);
    }

```

Also **pipe number 6** is used for receiving **acknowledge** messages.

In addition, the initialization code must have `radio.enableDynamicPayloads();` This one works well for me:

```
    radio.begin();
    //radio.setChannel(0x57); //if set should be the same at the both sides
    radio.setPALevel(RF24_PA_LOW);  // "LOW" is more stable mode
    radio.enableAckPayload(); //for autoanswers
    radio.openWritingPipe(pipe01); //for sending
    //link pipe numbers to the pipe addresses
    //radio.openReadingPipe(1, pipe01); // I use pipe01 for sending
    radio.openReadingPipe(2, pipe02);
    radio.openReadingPipe(3, pipe03);
    radio.openReadingPipe(4, pipe04);
    radio.openReadingPipe(5, pipe05);
    radio.enableDynamicPayloads(); //must have for multi pipe receiving
    radio.startListening();  //start listening

```

Good luck...

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


# Question
Title: Stepper motor shield compatibilty question
I recently bought Adafruit's motor shield v2 only to find out it can only support upto 12v.

So I'm on the look out for another shield & found this one Arduino Dual L6470 Stepper Motor Shield

I have an Arduino Mega & the documentation says it is fully compatible with the UNO.

Will there an issue using this shield with a Mega? Or if anyone else can point me at a decent stepper controller?

# Answer
> 1 votes
That is an SPI based device, and it doesn't use the (now considered standard) 6-pin ICSP header for SPI.

Therefore it will only directly work on boards that have the SPI pins available on pins 10-13 of the digital headers.

To use it with other boards you will need to manually route the SPI pins to the right places using wires.

# Answer
> 0 votes
Just so you know, the L6470 is a pretty sophisticated and high-performance driver with lots of options to tweak, but it is a voltage-mode driver that requires some tuning for best results (otherwise, expect to generate some heat). There is a separate ST microelectronics application note, not mentioned in the L6470 datasheet, that describes some tuning guidelines - but it's written for an engineering audience.

There is also a SparkFun version of the L6470 out there.

---
Tags: arduino-mega, stepper
---


# Question
Title: How can I write an integer to a Mifare RFID card using the RFID library?
I'm a beginner to C++ and I'm clearly missing some fundamental knowledge of data types. As such, I'm struggling to adapt the examples in the miguelbalboa/rfid library to my use case. I'm simply trying to write an integer to a 13.56Mhz RFID tag. Ideally I'd like to optimize the data so as to be quick to read (it seems fully reading these cards can take a while and I'd like to read the integer, an ID, as quickly as possible).

So on to my actual questions... what is the data type shown in this block of example code (shown below) and how can I turn an integer into the same data type? Finally, how should I read this saved value back into the familiar integer data type?

```
byte dataBlock[]    = {
    0x01, 0x02, 0x03, 0x04, //  1,  2,   3,  4,
    0x05, 0x06, 0x07, 0x08, //  5,  6,   7,  8,
    0x09, 0x0a, 0xff, 0x0b, //  9, 10, 255, 11,
    0x0c, 0x0d, 0x0e, 0x0f  // 12, 13, 14, 15
};

```

# Answer
The `dataBlock[]` variable is an array of bytes. One byte can represent an integer ranging from -128 to 127, or a positive integer ranging from 0 to 255. If your integer value will always be in one of those ranges, then you can just put your integer in the first element of the array and zero out the remaining.

```
byte dataBlock[]    = {
    0x01, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00
};

```

(That saves a value of 1 to the first element, and zeros to the rest. If you want to change the first element:

```
dataBlock[0] = yourValue;

```

If your integer is a 2-byte integer, as is typically found in Arduino with type `int`, you need to split your value into the high byte and low byte:

```
dataBlock[0] = (byte)(yourValue & 0xFF); // Low byte
dataBlock[1] = (byte)(yourValue >> 8);   // High byte

```

Then you write the data block as per the example. To get your 2-byte integer value back:

```
yourValue = ((int)dataBlock[1])<<8 | dataBlock[0];  // Shift high byte, OR with low byte.

```
> 1 votes

# Answer
Well, the example is using the `MIFARE_Write` and `MIFARE_Read` functions. These functions, as explained in the library, accept at least 16 bytes, so the 16-bytes buffer is the smallest you can read/write. Consequently I suggest you, if you don't have any additional data, to use 16-bytes IDs (you get a much wider code space).

If you strictly want to use 2 or 4-bytes integers, the first solution which comes to my mind is jose's one, so manually split the int in two (or the long in four) bytes and store them in the array. For instance

```
// Big endian format
dataBlock[idx]   = (byte)(intValue >> 8); // Byte 1
dataBlock[idx+1] = (byte)(intValue);      // Byte 0
// or
dataBlock[idx]   = (byte)(longValue >> 24); // Byte 3
dataBlock[idx+1] = (byte)(longValue >> 16); // Byte 2
dataBlock[idx+2] = (byte)(longValue >> 8);  // Byte 1
dataBlock[idx+3] = (byte)(longValue);       // Byte 0

// Little endian format
dataBlock[idx]   = (byte)(intValue);      // Byte 0
dataBlock[idx+1] = (byte)(intValue >> 8); // Byte 1
// or
dataBlock[idx]   = (byte)(longValue);       // Byte 0
dataBlock[idx+1] = (byte)(longValue >> 8);  // Byte 1
dataBlock[idx+2] = (byte)(longValue >> 16); // Byte 2
dataBlock[idx+3] = (byte)(longValue >> 24); // Byte 3

```

NOTE: `idx` can be any value; the easiest approach is to put the int at the beginning (so substitute `idx` with 0) This is the safest way to handle this, since the endianness is explicit. You can, however, trust the compiler and use its implicit handling of multi-byte variables in this way:

```
*((int*)(&datablock[idx])) = intValue;
// or
*((long*)(&datablock[idx])) = longValue;

```

You take the cell where you want to put the beginning of the data, get its pointer, cast it to the pointer type you need, then write inside that pointer the value you want. Please note, however, that cells idx and idx+1 in the case of an int, or idx to idx+3 for long, will be written. If your array ends, you will pollute the memory in unpredictible ways (just like if you write `dataBlock[18] = something` when dataBlock has 16 cells).

Note you cannot control the endianness of the byte array, but if you always use the same device to read and write you should not worry. FYI, at present the compiler used by Arduino IDE is little endian.

Note also that, for `idx = 0`, `(&datablock[idx])` can be simplified in `(datablock)`.

To read back the data, you have the following ways

```
// Big endian format
intValue = (((int)dataBlock[idx]) << 8) | dataBlock[idx+1];
// or
longValue = (((long)dataBlock[idx]) << 24) | (((long)dataBlock[idx+1]) << 16) | (((long)dataBlock[idx+2]) << 8) | dataBlock[idx+3];

// Little endian format
intValue = (((int)dataBlock[idx+1]) << 8) | dataBlock[idx];
// or
longValue = (((long)dataBlock[idx+3]) << 24) | (((long)dataBlock[idx+2]) << 16) | (((long)dataBlock[idx+1]) << 8) | dataBlock[idx];

```

Or, in the last case,

```
intValue = *((int*)(&datablock[idx]));
// or
longValue = *((long*)(&datablock[idx]));

```
> 0 votes

---
Tags: c++, rfid, data-type
---


title: ESP8266 returning 400 bad request

text:
# Question
Title: ESP8266 returning 400 bad request
I am trying to get JSON data from my website using an HTTP GET request, but I'm getting a 400 bad request error. Can someone let me know why am I getting this error and how to fix that? I am tired of looking at online resources.

I am trying to fetch data from www.himalayavats.com/to\_fetch/system\_info.json

I am using this code:

```
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

SoftwareSerial ESP8266 (rxPin, txPin);

unsigned long lastTimeMillis = 0;

void setup() {
  sendData("AT+RST\r\n",1000, true);
  Serial.begin(9600);
  ESP8266.begin(9600);
  delay(2000);
  connectToWifi();
}

void connectToWifi() {
  String ssid = "moto g";
  String pass = "hvats555";
  sendData("AT+CWMODE=1\r\n", 3000, true); // Configure as client
  sendData("AT+CWJAP=\"moto g\",\"hvats555\"\r\n", 5000, true);  // Connects to wifi
}

String sendData(String command, const int timeout, boolean debug) {
  String response = "";
  ESP8266.print(command); // send the read character to ESP8266
  long int time = millis();
  while( (time+timeout) > millis() ) {
    while(ESP8266.available()) {
      // The ESP has data so display its output to serial window
      char c = ESP8266.read(); // read the next character
      response+=c;
    }
  }
  if(debug) {
    Serial.print(response);
  }
  return response;
}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {
  if (millis() - lastTimeMillis > 30000) {
    lastTimeMillis = millis();
    ESP8266.println("AT+CIPMUX=1");
    delay(1000);
    printResponse();
    ESP8266.println("AT+CIPSTART=4,\"TCP\",\"himalayavats.com\", 80");
    delay(1000);
    printResponse();
    String cmd = "GET /to_fetch/system_info.json HTTP/1.1";
    ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
    delay(1000);
    ESP8266.println(cmd);
    delay(1000);
    ESP8266.println("");
  }

  if (ESP8266.available()) {
    Serial.write(ESP8266.read());
  }
}

```

I get this response every time:

```
AT+CWMODE=1

OK
AT+CWJAP="moto g","hvats555"

WIFI DISCONNECT
WIFI CONNECTED
WIFI GOT IP

OK
AT+CIPMUX=1

OK

AT+CIPSTART=4,"TCP","himalayavats.com",80

4,CONNECT

OK

AT+CIPSEND=4,43

OK
>
Recv 43 bytes

SEND OK

+IPD,4,1370:HTTP/1.1 400 Bad Request
Date: Tue, 19 Dec 2017 08:30:21 GMT
Server: Apache
Accept-Ranges: bytes
Vary: Accept-Encoding,User-Agent
Connection: close
Content-Type: text/html

```

My JSON file on the website looks like this:

```
{"power" : "high"}

```

# Answer
Take a look at the HTTP specification:

```
Request       = Request-Line              ; Section 5.1
                *(( general-header        ; Section 4.5
                 | request-header         ; Section 5.3
                 | entity-header ) CRLF)  ; Section 7.1
                CRLF
                [ message-body ]          ; Section 4.3

Request-Line  = Method SP Request-URI SP HTTP-Version CRLF

```

You don't send the CRLF (carriage return, line feed) at the end of your request line and at the end of the header at the same time of the request. Why the delay?

You also miss the obligatory host header.

```
Host = "Host" ":" host [ ":" port ] ; Section 3.2.2

```
> 2 votes

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


title: Arduino parsing JSON

text:
# Question
Title: Arduino parsing JSON
I have created an API in Ruby on Rails and it send the following JSON response:

```
{"sun_position":{"altitude":"32.46","azimuth":"223.93"}}

```

I'm able to successfully hit the API and store the response. But when I try to parse it and store data it gives me an error. I have used the Arduino JSON library.

The code for parsing the JSON is as follows:

```
bool parseSunPosData(char* content, SunPosData* sunPos) {
  StaticJsonBuffer<JSONBUFFER_SIZE> jsonBuffer;
  JsonObject& root = jsonBuffer.parseObject(content);
  Serial.println("In parse fuc");
  Serial.println(content);
  Serial.println("==============");
  if (!root.success()) {
    Serial.println("JSON parsing failed!");
    return false;
  }

```

And the output on the serial monitor is as follows:

> In parse fuc 38
>
> {"sun\_position":{"altitude":"32.46","azimuth":"223.93"}} 0
>
> ==============
>
> JSON parsing failed! Disconnect

My guess is it can't parse the data due to the numbers 38 and zero printing... I don't know what that is and what it is.

PS: New to Arduino coding.

# Answer
> 2 votes
you have the HTTP chunked transfer encoding numbers in the content. 38 is the length of the body and it is on the first line of the HTTP body and 0 marks the end. maybe try using ArduinoHttpClient library for HTTP

---
Tags: arduino-mega, json
---


# Question
Title: How does Arduino UNO deal with bit shifting?
Explanatory comment: I'm a beginner. I'm examining the feasibly of bit shifting to the right 6 places to divide up the range of the Arduino ADC (has a range of 0 to 1023) to something much smaller. Such that any number in the ADC registers, between 0 and 63 produces a value of 0, a number between 64 and 127 a 1, between 128 and 191 a 2, between 192 and 255 a 3, etc. There is a change every 64 increase in the initial number.

I think this is possible to do. But some doubt has been expressed I think.

As far as I have determined, after right shifting 6 places to the right the following values of numbers are resident in the ADC registers: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15.

I wish you to consider, is there anything in the way Arduino's IDE works, or with the nature of the initial number in the register (signed/unsigned) that makes the results I have indicated false. I think, that the initial number will be unsigned, just guessing.

# Answer
There are two types of right-shift in C - logical and arithmetic.

GCC (which is the compiler the Arduino IDE uses) selects which one to use depending on whether the type you are shifting is signed or not:

* If it's signed then use an arithmetic shift
* If it's unsigned then use a logical shift

In a logical shift, the value is literally shifted to the right padding the left side with zeros. An arithmetic shift, however, shifts and *extends the sign*. I.e., it performs an arithmetical "divide by 2". That means if you right shift a negative value to still have a negative value (Note: this behaviour is implementation specific, so is only applicable to GCC. For other compilers in other situations you will have to check the documentation of that compiler).

So if you store the results of `analogRead()` in an unsigned integer variable `>> N` will right shift the value `N` times. If you store it in a signed integer it will divide the value by 2 `N` times.

For a positive value, which the results of `analogRead()` will be, the end result is the same - divide by 2 `N` times.

So if you right-shift 6 times you reduce a 10-bit value down to (10-6) 4 bits. 24 is 16, so you get 16 possible values. 24-1 is 15, so you get values 0-15 in your final value.
> 1 votes

---
Tags: bit
---


title: digitalRead keeps giving 1

text:
# Question
Title: digitalRead keeps giving 1
I am new to arduino programming and I have bought arduino UNO a few days ago.

I am trying to read the value of pin 4 using `digitalRead` with pinMode INPUT\_PULLUP but it keeps giving me 1 even when the pin 4 is not connected to anything.

Here is the code:

```
void setup() {
  pinMode(2,OUTPUT);
  pinMode(4,INPUT_PULLUP);
  Serial.begin(9600);
  digitalWrite(2,HIGH);
}

void loop() {
  Serial.print(digitalRead(4));
  Serial.print('\n');
  delay(150);
}

```

Pin 2 is connected to one side of the button and Pin 4 is connected to other side of the button. According to condition, when the button should be off , the value should be 0 and when the button should be on , the value should be 1 , but the value is 1 even when I press the button is off or on.

On the other way , if I replace `INPUT_PULLUP` with `INPUT` then the value is floating.

Why the value with INPUT\_PULLUP is 1?

# Answer
> 6 votes
You have set Pin 2 to `HIGH`, which is 5V. You have set Pin 4 to `INPUT_PULLUP`, which means if no signal is driving it, it will be `HIGH`.

You have connected a button between Pins 2 and 4. So, if you don't press the button, the input is pulled `HIGH`. And if you do press the button, Pin 2 is driving it `HIGH`.

# Answer
> 3 votes
There are to simple options how to connect a simple button. You mixed them.

Better option is connect the button between pin with INPUT\_PULLUP and ground. The pin is HIGH when the button is open and LOW when the button grounds the pin. This option is better because if you disconnect the button, the pin is still pulled up to HIGH and not floating.

If you connect the button with a pull-down circuit, then the pin is HIGH when the button is pressed and LOW when the button is open, but when you disconnect the circuit, the pin floats and the sketch reads chaos.

# Answer
> 0 votes
This looks as it is operating as wired and programmed. When the button is open, the INPUT\_PULLUP is pulling pin 4 to HIGH, and when the button is closed & shorted to pin 2, the `digitalWrite(2,HIGH)` would also pull the pin 4 to HIGH.

Maybe you want `digitalWrite(2,LOW)` so that connecting pin 4 to pin 2 through the button would pull pin 4 low.

---
Tags: digital, input
---


# Question
Title: M0 pro: SPI communication, code works on Uno, but not in M0. Using ICSP port
I am trying to establish a communication between a sensor and a M0 -pro using SPI. The code :

```
    #include <SPI.h>

    unsigned int result  = 0;
    void readAngle();

    void setup() {
      Serial.begin(9600);
      SPI.setBitOrder(MSBFIRST);
      SPI.setClockDivider(SPI_CLOCK_DIV8); //sets the clock speed for data transfer, slowed down 8 times
      SPI.setDataMode (SPI_MODE1);

      digitalWrite(11,HIGH);
      pinMode(11,OUTPUT);

      SPI.begin();
      SerialUSB.println("First Try");
}

    void loop() {
      readAngle();
      SerialUSB.println(result);
      delay(500);

}

    void readAngle(){
        digitalWrite(11,LOW); //Turn SS on, start communication
        result = SPI.transfer16(0xFFFF); // the read command and the response received
        result = (result << 2) >> 2; // get rid of the last 2 bits, error(14) + parity(15)
        digitalWrite(11,HIGH); //Turn SS of

}

```

The code works perfectly with an UNO, but with M0, it event doesnt print the first `SerialUSB.println("First Try");`. The moment i erase the lines that have SPI commands in it, the serial monitor starts working again. As i said in the titel i am using the ICSP port on M0. I use the native usb port to programm.

I think i am missing something very basic. I checked many different forum posts, but there is no indication of M0 requiring other SPI commands. Any help is much appriciated.

PS: i didnt go into detail with the sensor and its datasheet because since it works fine with uno, the cause of the problem should be it.

# Answer
Which version of the Arduino IDE are you using ? If its an older one, try to get the latest one, sometimes that solves issues like the one you have.
> 0 votes

# Answer
You must declare that the pin as an output before you use it.

Do this by using the `pinMode()` function, like this:

```
pinMode(11, OUTPUT);          // sets the digital pin 11 as output

```

Add the above line at the beginning of your `setup()` function.
> 0 votes

---
Tags: arduino-uno, communication, spi, arduino-zero
---


title: Arduino Yun connection problems

text:
# Question
Title: Arduino Yun connection problems
I followed this guide and evertything works until I'm at chapter Configuring the onboard WiFi.

I can see the arduino as an AP.

And I can connect with it. However when entering the IP adress *192.168.240.1* or *arduino.local* it does not give me the login page. When using the IP adress I get: the site is not accessable screen. Using *arduino.local* gives me a page that loads forever for a long time before giving me the exact same result.

I have looked on different forums for a solution. This one said that I should download bonjour and bonjour browser because they use the same port (port 5353). After installing the bonjour browser I should be seeing a connection called .arduino.\_tcp but I don't see that. In fact I often can't see any connection what so ever.

and sometimes I can see a few connections but none of those are the arduino.

I have tried to ping with the arduino on the adress *192.168.240.1* but all I got was a time out.

```
Pinging 192.168.240.1 with 32 bytes of data:
Request timed out.

```

**Edit** : I managed to get the bonjour browser to work all the time, by installing itunes. It also shows the arduino.

# Answer
You have to find IP address of your Yùn on your local network. What I do in this case: \- look on the Home router if you can see your Yùn and it's ip, or, \- there is a sketch in Arduino Ide / exemple / bridge / wifi status which can help you to get ip, or \- open the Arduino Ide software, upload serialTerminal sketch and open serial monitor. It allows you to access the Linux part of the Yùn and type 'ifconfig' to get the IP from the Yùn.
> 1 votes

---
Tags: wifi, arduino-yun
---


title: ESP8266 Missing data from Serial

text:
# Question
Title: ESP8266 Missing data from Serial
I'm trying to read all the available access points nearby with an ESP8266 module.

Whenever I try to read all the available data from the ESP module and write it to the Monitor Serial it truncates text. Text often also a bit messed up.

I'm using an Arduino Uno with the following scheme (I'm using pins 2 & 3 NOT 1 & 0):

```
#include <SoftwareSerial.h>

SoftwareSerial esp8266(2, 3);

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);

  esp8266.begin(115200);
}

void loop() {
  while(esp8266.available()) {
     Serial.write(esp8266.read());
  }

  while(Serial.available()) {
    esp8266.write(Serial.read());
  }
}

```

The code prints something like the following:

```
AT+CWLAP

+CWLAP:(3,#SBanaan",-73,"4c:09:d4:d5:d6:f2",1,,2,0)
+CWLAP:(3,"UPC24923"CH7"0,L5-:d6Ai0:,
,,f5
44"f"CZ7f1
4-"6:0:4-95
,5-3d0

```

# Answer
> 1 votes
As @JoseCanUC has mentioned SoftwareSerial is not reliable at 115200 baud. This is because the bytes are sometimes too close together for the Arduino to start receiving a new one when the start bit arrives, and so the byte starts being received part way through, thus corrupting it.

You should investigate setting the baud rate of the ESP8266 to 9600, although this itself comes with its own set of pitfalls. You should be prepared to re-flash the AT firmware to reset the baud rate if it all goes wrong. I would seriously suggest investing in one of the many cheap USB programming adaptors for the ESP-01 on eBay, since it makes working with these devices so much simpler. It also opens up the possibility of creating and installing your own firmware for the ESP8266 instead of using the somewhat clunky AT firmware interface.

# Answer
> 2 votes
For `SoftwareSerial`, at 115200 bps data rate is not going to be reliable. Try 9600 bps.

# Answer
> 1 votes
I'm a bit confused by your diagram showing no ATmega chip on the Uno board, but you posted Uno code that should properly communicate with your ESP (except for the baud rate being too high for SoftwareSerial).

See my answer to another ESP question for how to change the ESP's baud rate, especially the code fragment at the bottom of that answer.

Changing the ESPs parameters is not difficult as long as its AT firmware is intact (which it will be if you haven't attempted to re-flash the device). Changing baud rate is only slightly tricky, in that once the Uno has told the ESP to change its baud rate, the Uno must also change its baud rate to match before you can re-establish communication with it.

---
Tags: esp8266
---


# Question
Title: Does analogueRead() change the way a number is represented etc?
Explanatory Comment: The ADC conversion result is a 10 bit number and is placed in two 8 bit registers: ADCH & ADCL. AnalogueRead() reads the output of the ADC. This, I believe is an unsigned number. But, generally taken as only a positive number.

I'm interested in what changes, if any, take place to the number (in it's representation, interpretation, or construction or whatever) when analogueRead() reads the number and presumably makes something of it, or sends it or stores it somewhere.

# Answer
There is no change in representation. `analogRead()` reads two I/O registers, `ADCL` and `ADCH`, which on the Uno are memory-mapped to addresses `0x0078` and `0x0079` respectively. It returns the result in a register pair, `r24` and `r25`, which per the AVR C calling conventions is the standard way of returning a 16-bit number. Thus, `r24` holds the value read from `ADCL`, and `r25` the value read from `ADCH`. That's it. No conversion whatsoever.

There is a change in interpretation... of sorts. The function is declared as returning an `int`, which on the AVR is a 16-bit *signed* integer, whereas it could be argued that the I/O registers contain an unsigned number. However, since the sign bit will always be zero, the signed/unsigned distinction is moot: either way the result will be interpreted as a number between 0 and 1023.

---

**Edit**: As a clarification: the `ADC` register (which is another name for the `ADCL`/`ADCH` register pair) is a 16-bit I/O register. At the end of a conversion, it holds the 10-bit result right-adjusted into this 16-bit space, zero-padded on the left, as follows:

```
-------- ADCH --------- --------- ADCL --------
0  0  0  0  0  0  r9 r8 r7 r6 r5 r4 r3 r2 r1 r0
----------------- ADC (16 bits) ---------------

```

where the bits r9..r0 represent the 10-bit conversion result. Since the MSB is zero, it is irrelevant whether you interpret it as a sign bit or as a regular unsigned bit.

Just for completeness, it could be noted that it is possible (though not through the Arduino core library) to configure the ADC to left-adjust the result, as follows:

```
-------- ADCH --------- --------- ADCL --------
r9 r8 r7 r6 r5 r4 r3 r2 r1 r0 0  0  0  0  0  0
----------------- ADC (16 bits) ---------------

```

In this case, the MSB could be one, at it would obviously be incorrect to interpret it as a sign bit.

As a side note, the avr-libc defines `ADC` as `(*(volatile uint16_t *)(0x78))`, which is unsigned. And it makes sense considering that, unlike the users of Arduino core, the users of avr-libc are supposed to know they have the choice to get a left-adjusted result.
> 2 votes

# Answer
It doesn't change anything, it just combines the two 8-bit register values to one 16-bit integer.

You can just look it up in the source code for analogRead.

```
int analogRead(uint8_t pin)
{
    uint8_t low, high;

[...]

    // we have to read ADCL first; doing so locks both ADCL
    // and ADCH until ADCH is read.  reading ADCL second would
    // cause the results of each conversion to be discarded,
    // as ADCL and ADCH would be locked when it completed.
    low  = ADCL;
    high = ADCH;

[...]

    // combine the two bytes
    return (high << 8) | low;
}

```
> 1 votes

# Answer
I assume you mean AnalogRead, see AnalogRead.

What it effectively does is mapping 0 to 5V to values 0 to 1,023. The unit is thus 5/1,024 V. What this number means depend on the ADC used.

Probably the two bytes (ADCH as most significant bits and ADCL as least significant bits) contain this 0-1,023 value.
> 0 votes

---
Tags: arduino-uno
---


title: NodeMCU v1 keeps dropping out

text:
# Question
Title: NodeMCU v1 keeps dropping out
I've created a homebridge server on a Raspberry Pi Zero and have configured it to use my NodeMCU v1 (Esp - 12E Module) as an accessory to control RGB strip lights.

All works normally until you don't use the home kit to control the lights for certain amount of time (~30 seconds). My iPhone says that the accessory is non responsive until I force a command to happen, this after some time activates the accessory and goes back to normal.

Is there a way of keeping the NodeMCU active to HTTP responses all the time?

The code I have used is a mashup of a tutorial I used but I've modified it with some more features. (All coded in Arduino)

```
//NodeMCU RGB-Controller for Homebridge & HomeKit (Siri)

#include <ESP8266WiFi.h>
#include <math.h>

#define redPin 13 //D7 - Red channel
#define grnPin 12 //D6 - Green channel
#define bluPin 14 //D5 - Blue channel
#define white 5 //D1 - Blue channel

WiFiServer server(80); //Set server port

String readString;           //String to hold incoming request
String hexString = "000000"; //Define inititial color here (hex value), 080100 would be a calm warmtone i.e.

int state;

int r;
int g;
int b;

float R;
float G;
float B;

int x;
int V;

///// WiFi SETTINGS - Replace with your values /////////////////
const char* ssid = "xxxxxxx";
const char* password = "xxxxxxx";
IPAddress ip(192,168,1,234);      // set a fixed IP for the NodeMCU
IPAddress gateway(192,168,1,1);  // Your router IP
IPAddress subnet(255,255,255,0); // Subnet mask
////////////////////////////////////////////////////////////////////

void WiFiStart() {
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  WiFi.config(ip, gateway, subnet); //Set a fixed IP. You can comment this out and set it in your router instead.
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print("_");
  }
  Serial.println();
  Serial.println("Done");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println("");

  server.begin();
}

void allOff() {
  state = 0;
  analogWrite(redPin, 0);
  analogWrite(grnPin, 0);
  analogWrite(bluPin, 0);
}

//Write requested hex-color to the pins (10bit pwm)
void setHex() {
  state = 1;
  long number = (long) strtol( &hexString[0], NULL, 16);
  r = number >> 16;
  g = number >> 8 & 0xFF;
  b = number & 0xFF;
  r = map(r, 0, 255, 0, 1023);  //added for 10bit pwm
  g = map(g, 0, 255, 0, 1023);  //added for 10bit pwm
  b = map(b, 0, 255, 0, 1023);  //added for 10bit pwm
  analogWrite(redPin, (r));
  analogWrite(grnPin, (g));
  analogWrite(bluPin, (b));
}

//Compute current brightness value

//For serial debugging only
void showValues() {

  Serial.print("Status on/off: ");
  Serial.println(state);
  Serial.print("RGB color: ");
  Serial.print(r);
  Serial.print(".");
  Serial.print(g);
  Serial.print(".");
  Serial.println(b);
  Serial.print("Hex color: ");
  Serial.println(hexString);

  Serial.print("Brightness: ");
  Serial.println(V);
  Serial.println("");

}

void setup(){
  Serial.begin(9600);
  delay(1);
  pinMode(redPin, OUTPUT);  //declaration added
  pinMode(grnPin, OUTPUT);  //declaration added
  pinMode(bluPin, OUTPUT);  //declaration added
  setHex(); //Set initial color after booting. Value defined above
  WiFi.mode(WIFI_STA);
  WiFiStart();
  //showValues(); //Uncomment for serial output
}

void loop() {
  //Reconnect on lost WiFi connection (superfluous - will reconnect anyway)
  if (WiFi.status() != WL_CONNECTED) {
    WiFiStart();
  }

  WiFiClient client = server.available();

  if (!client) {
    return;
  }

  while(client.connected() && !client.available()) {
    delay(1);
  }

  //Respond on certain Homebridge HTTP requests
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        if (readString.length() < 100) {
          readString += c;
        }
        if (c == '\n') {
          Serial.print("Request: "); //Uncomment for serial output
          Serial.println(readString); //Uncomment for serial output

          //Send reponse
         client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();

          //On
          if(readString.indexOf("on") >0) {
            setHex();
            Serial.println("on");
            showValues();
          }

          if(readString.indexOf("xw") >0) {

            Serial.println("won");
            analogWrite(white, 1024);
          }

          if(readString.indexOf("yw") >0) {

            Serial.println("woff");
            analogWrite(white, 0);
          }

          //Off
          if(readString.indexOf("off") >0) {
            allOff();
            showValues();
          }

          //Set color
          if(readString.indexOf("set") >0) {
            hexString = "";
            hexString = (readString.substring(9,15));
            setHex();
            //showValues();
          }

          //Status on/off
          if(readString.indexOf("status") >0) {
          client.println(state);
          }

          //Status color (hex)
          if(readString.indexOf("color") >0) {
          client.println(hexString);
          }

          //Status brightness (%)
          if(readString.indexOf("bright") >0) {

          client.println(V);
          }

          delay(1);
          client.stop();
          readString="";
        }
      }
    }
  }
}

```

# Answer
> 2 votes
You are probably running out of RAM because you are using the `String` object instead of a fixed-size char\[\] buffer. This code, in particular:

```
if (readString.length() < 100) {
  readString += c;
}

```

Concatenating `String` objects using the overloaded plus operator allocates a whole new block of RAM for the new, longer string. It frees the previous memory, but since you keep adding one character at a time, new strings won't be able to be put into the once-used RAM.

You should instead use C-style strings (character arrays) and the standard functions for managing them, such as `strnlen()` and `strncat()`, etc. Note, I am suggesting the versions of string functions with a `maxlen` parameter, which helps avoid bugs due to unterminated strings.

---
Tags: nodemcu
---


title: DHT11 Sensor Code Fatal Error

text:
# Question
Title: DHT11 Sensor Code Fatal Error
I recently tried using Hobbyist.co.nz's guide on the DHT11 sensor. I installed the Adafruit\_Sensor and DHT11 Sensor libraries, but it keeps returning with a fatal error.

Here is the code and the error:

```
#include <dht.h>

#define dht_dpin A0 //no ; here. Set equal to channel sensor is on

dht DHT;

void setup(){
  Serial.begin(9600);
  delay(300);//Let system settle
  Serial.println("Humidity and temperature\n\n");
  delay(700);//Wait rest of 1000ms recommended delay before
  //accessing sensor
}//end "setup()"

void loop(){
  //This is the "heart" of the program.
  DHT.read11(dht_dpin);

    Serial.print("Current humidity = ");
    Serial.print(DHT.humidity);
    Serial.print("%  ");
    Serial.print("temperature = ");
    Serial.print(DHT.temperature);
    Serial.println("C  ");
  delay(800);//Don't try to access too frequently... in theory
  //should be once per two seconds, fastest,
  //but seems to work after 0.8 second.
}// end loop()

```

> ```
> C:\Users\XXXXXX\Documents\Arduino\sketch_dec19c\sketch_dec19c.ino:2:17:
>
> ```
>
> fatal error: dht.h: No such file or directory
>
> ```
> #include <dht.h>
>
> ```

# Answer
The examples I can see from Adafruit say

```
#include "DHT.h"

```

or

```
#include <DHT.h>

```

But you wrote

```
#include <dht.h>

```

They aren't the same.

Further, the examples for the Adafruit library show usage like:

```
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

```

But you call `DHT.temperature` and `DHT.humidity`.

If you are meaning to use the Adafruit library, you have to write your code according to their documentation.

Also of note, you have defined the type of the object as `dht` and the name as `DHT`, but for Adafruit, the type is `DHT`.

**EDIT:**

The example on the website you note has a downloadable zip file for the DHT library they use. You cannot assume that all libraries for interfacing a certain sensor will all have the same programming interface.
> 4 votes

---
Tags: arduino-uno, sensors, temperature-sensor
---


# Question
Title: How to use a microSD card reader with SCK instead of CLK?
I've bought this microSD reader/writer: http://www.ebay.com/itm/131132034753

I've found only one tutorial, where the pins are similar to my pins, but in the example there is a CLK instead of SCK: https://learn.sparkfun.com/tutorials/microsd-shield-and-sd-breakout-hookup-guide

The pins on my MicroSD reader are:

* CS
* SCK
* MOSI
* MISO
* VCC
* GND

# Answer
SCK stands for **S**PI **C**loc**K**

CLK stands for SPI **CL**oc**K**

Two different acronyms for the same thing.
> 11 votes

# Answer
It's common practice for speakers/writers to use the generic term: "clock" (CLK) for various different situations. This clearly being a *serial* interface we don't need to specifically say **S**erial clo**CK** each time the signal mentioned, as it's more of a mouthful than saying "clock".

In this case consider "CLK" and "SCK" as fully interchangeable.
> 2 votes

---
Tags: sd-card
---


# Question
Title: Consequences of dynamically changing input/output configurations of digital pin?
I am creating an IC checker for a large chunk of the 74ls series (basic TTL logic chips), which means that I have 14 pins running to the IC to verify its functionality. One pin is power (+5V) and another ground (GND), which are both consistently in the same seven and fourteen pin positions respectively, but the remaining 12 are various inputs and outputs that vary depending on the IC type.

With that stated, will there be any consequences to dynamically reconfiguring a pin from input to output -- or vice versa -- as different IC types are selected? Weird behavior or electrical failure? What if the IC remains plugged in while the the pins reconfigure? What if said IC is powered on and providing power to a pin as it reconfigures?

If you were curious, I am using a joystick and LCD display as an interface to selecting the appropriate IC to check.

# Answer
> 1 votes
There's no problem reconfiguring pins. It happens all the time. One example is with ping sensors where the pin is used as an output to send the ping and then switched to an input to wait for the response. The only caveat is that you must be sure what you're connected to. For instance, if you set a pin to OUTPUT and LOW and it just happens to be connected to a HIGH OUTPUT then you just fried your board.

---
Tags: arduino-uno, pins, digital
---


title: Solution for two software serials

text:
# Question
Title: Solution for two software serials
I've been working a while on a project using 3 Arduino Nanos, linked together using this tutorial Nick Gammon.

As I am not experienced with Arduino programming, I was making it step by step.

First I get all devices in one network, then managed to get the correct data sent from the correct device to one receiver. I added a Nextion display to visualize the received data. Then I have some physical buttons and some relays as well.

So far everything went fine until today. I wanted to send a command from the Nextion to the Arduino. Only then I realized that when using multiple software serial ports, only one can receive data at a time.

In my case I have an RS485 on SoftwareSerial and the Nextion.

I'm feeling a bit upset now, as I soldered everything on a prototyping board as nice as I can. I tried to move the Nextion on to hardware serial, as that was quite easy to access, but the result was inconsistent.

Please, can someone suggest me how to change my project's hardware and what I need to program (Software Serial or Hardware Serial) to make it to work? Basically I am looking for the right direction now, when I will get that I can figure out the rest by myself.

# Answer
Hardware serial, on the face of it, should be the more reliable because it uses hardware that can run simultaneously with other code. It uses interrupts to transfer a received byte from its internal register into program RAM.

Software serial, on the other hand, is somewhat more timing-dependent because it uses timing loops to detect each bit at the correct time. In order to do this, it turns off hardware interrupts in order to ensure that each timing loop runs at the expected speed.

If you use Software serial at the same time as hardware serial, the fact that Software serial turns off interrupts may mean that the processor doesn't get a chance to transfer the most recent byte from the serial hardware to RAM.

A work-around, if possible, is to use Software serial at the fastest possible baud rate. That means that interrupts are turned off for a shorter time. When they are turned back on the processor can recover the most recent hardware serial byte.

Thus, if you have two devices using serial, put the faster one onto Software serial, to reduce the time that interrupts are off.

RS485 does not, per se, specify a transfer rate. It is a balanced electrical protocol, which is designed to minimize the impact of noise over long cable runs.
> 0 votes

---
Tags: serial, softwareserial
---


# Question
Title: Can we use analog input pins as a parameter of analogWrite() for PWM?
```
int led = A1;

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

void loop() {
  analogWrite(led, 188.7);
  delay(100);
  analogWrite(led ,0);
  delay(100);
}

```

Like this and it works! I mean I am getting the exact voltage as calculated while mapping 5V between 0-255

# Answer
On the Nano, only the pins D3, D5, D6, D9, D10 and D11 are PWM-capable. If you try to `analogWrite()` to any other pin, you will get either 0 V (if you write any value less than 128) or 5 V (for any other value).

If you get 3.7 V when 5 V is expected, that's because either your power supply is too weak, or you are putting too a heavy load on the pin.
> 1 votes

---
Tags: arduino-nano, atmega328
---


# Question
Title: Need to control 2 DC motors powered using arduino mini and l298n from about range of 100m
I need to control 2 DC motors which are arranged with arduino mini and L298N module from a distance of 100m wirelessly, what is the easiest and cheapest way of doing so?I checked RC controllers and xbee but they are way too expensive! Any help will be appreciated!

# Answer
The cheapest way is probably using nRF24L01+, a 2.4 GHz transceiver. It should be possible to communicate over 100 m, using a slow speed and without any obstacles in between. If you need a better/faster communication, either use a version with an external antenna and/or use other frequences (using different transceivers, below 1 GHz). The last options are more expensive.
> 0 votes

---
Tags: motor, arduino-pro-mini, wireless
---


# Question
Title: How to call an interrupt when any one of the 12 defined digital inputs go high?
I'm using an Arduino Mega 2560 board. I need to sense 12 digital pins (**pins 36-47**) coming from another board continuously and display power when they are low.

When any of the 12 pins go HIGH, an interrupt must be created. In the ISR part, I'll be making one new digital pin (**PIN 35**) go HIGH (this is initialized as low in setup function).

To reset from interrupt, I need to press the **"#"** key in the keypad. This should make PIN 35 go low again and program should function normally again.

This is my code without using Interrupt.

```
#include "LiquidCrystal.h"
#include <Keypad.h>

// initialize the library by providing the nuber of pins to it
LiquidCrystal lcd(8,9,4,5,6,7);
 const byte ROWS = 4; // four rows
const byte COLS = 3; // three columns
char keys[ROWS][COLS] = {
 {'1','2','3'},
 {'4','5','6'},
 {'7','8','9'},
 {'*','0','#'}
};
byte rowPins[ROWS] = {22, 24, 26, 28}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {30, 32, 34};     //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
float fwd_voltage = 0.0,rev_voltage = 0.0;
float fpower,rpower;
int sensorValue=0;

void setup() {
  int i;
  for (i=36;i<48;i++) {
    pinMode(i,INPUT);
  }
  pinMode (35, OUTPUT);
  digitalWrite(35,LOW);
}

void reset () {
  while(1) {
    lcd.begin(16,2);
    lcd.setCursor(0,0);
    lcd.print("press # to reset");
    char key = keypad.getKey();
    if (key=='#') {
      digitalWrite(35, LOW);
      break;
    }
  }
}

void process(int pin, char* text) {
  if (digitalRead(pin) == HIGH && digitalRead(35)==LOW) {
    // Use HIGH instead of 1
    lcd.print(text);
    digitalWrite(35, HIGH);
    reset ();
  } else {
    int analog_value = analogRead(A0);//reading forward voltage
    int analog_valuer = analogRead(A1);//reading reverse voltage
    fwd_voltage = (analog_value * 5.0) / 1024.0;
    rev_voltage = (analog_valuer * 5.0) / 1024.0;
    fpower =  ((fwd_voltage)*(fwd_voltage)*10000);
    rpower = ((rev_voltage)*(rev_voltage)*10000);
    lcd.setCursor(0,1);
    lcd.print("REV= ");
    lcd.print(rpower);
    lcd.print("W");
    delay(500);
    lcd.setCursor(0, 0);
    lcd.print("FWD= ");
    lcd.print(fpower);
    lcd.print("W");
    delay(500);
  }
}

void loop() {
  lcd.begin(16,2);
  // set cursor position to start of first line on the LCD
  lcd.setCursor(0,0);
  process(36, "vswr");
  process(37, "thermal");
  process(38, "overdrive");
  process(39, "A1-B1 fault");
  process(40, "A1-B2 fault");
  process(41, "A1-B3 fault");
  process(42, "A1-B4 fault");
  process(43, "A2-B1 fault");
  process(44, "A2-B2 fault");
  process(45, "A2-B3 fault");
  process(46, "A2-B4 fault");
  process(47, "driver fault");
}

```

How do I modify the program to add an interrupt so that my board works faster and efficiently? BTW I'm new to programming so there might be some mistakes in the program and also I didn't write the program small and efficient.

The interrupt service routine should consist of this part of the above program:

```
lcd.print(text);
digitalWrite(35, HIGH);
reset ();

```

My interrupt should detect this part of the program.

```
if (digitalRead(pin) == HIGH && digitalRead(35)==LOW)

```

# Answer
You are kind of unlucky. The ATmega2560 MCU has 32 pins capable of generating interrupts (counting the INTn and PCINTn, not sure all of them are routed to board headers), but none of the pins you have chosen is interrupt-capable.

I suggest you combine your 12 signals, using external logic, into a single interrupt signal. You would then, in the ISR, sort out which individual signal triggered the interrupt. A pair of 74HC4075 chips should be enough to OR together the 12 inputs.
> 1 votes

# Answer
Get rid of the 2 `delay` calls in your `process()` function. You are just needing to display the error text, so you don’t really need interrupt speed.

You have a 1s delay In total for every time you call the `process()` function. That doesn’t seem necessary.
> 1 votes

---
Tags: arduino-mega, interrupt
---


# Question
Title: Read analog signal over the SPI bus using MCP3201 ADC and Arduino Uno
It is possible to use the SPI bus when the **Vref** of MCP3201 ADC is 2.5V? On the setup i just finished, I used two linear regulators: **5V -\> 3.3V** to power the *MCP602* op-amps and *MCP3201* ADC, and another one **5v -\> 2.5V** for the Vref. Everyone recommends to connect the Vref from MCP3201 to Arduino's 5V but this does not apply in my case.

The green connector is connected to **GND** and ADC's **Dout** where the measured voltage fluctuates from 0.180V when i touch the sensor and his shield, to 0.6V when i'm not touching those parts. I have no ideea if this is a normal behaviour but everything looks fine to me. Voltage measured at the output of A4 ( MCP3201 +IN ) is **0.85V** and the current **Iref** is **1mA**(through the yellow jumper) as they recommend.

Sorry if these details are a bit off-topic but i think they are relevant to the ADC role in this setup.

# Answer
> It is possible to use the SPI bus when the Vref of MCP3201 ADC is 2.5V?

Of course it is. VREF is purely a reference voltage for taking measurements. It has no other role.

If you look at the functional block diagram from the datasheet:

You can plainly see that VREF is only connected to the DAC that is used as part of the SAR feedback loop. Everything else is fed from VDD
> 1 votes

---
Tags: adc
---


# Question
Title: Change the sequence of LEDs with button press
I am new to arduino. I have created a circuit , here is the image:

I want something that as I press the button the sequence of LEDs will change and as I press the button again , the sequence will change again.

I programmed code as following but it don't works correctly:

```
int led1 = 11;
int led2 = 10;

int output = 2;
int input = 4;
int mode = 0;

void setup() {
  pinMode(led1,OUTPUT);
  pinMode(led2,OUTPUT);
  pinMode(output,OUTPUT);
  pinMode(input,INPUT_PULLUP);
  digitalWrite(output,LOW);

}

void loop() {
  while(mode == 0 && digitalRead(input) == 1){
    digitalWrite(led1,HIGH);
    digitalWrite(led2,HIGH);
    delay(100);
    digitalWrite(led1,LOW);
    delay(100);
    digitalWrite(led1,HIGH);
    delay(100);
    digitalWrite(led2,LOW);
    delay(100);
    digitalWrite(led2,HIGH);
  }
  if(digitalRead(output) == 0){
    mode++;
    if(mode >= 2){mode = 0;}
  }
  while(mode == 1 && digitalRead(input) == 1){
    analogWrite(led1,255);
    delay(400);
    analogWrite(led1,150);
    delay(400);
    analogWrite(led2,255);
    delay(400);
    analogWrite(led2,150);
  }

}

```

According to the above code , two leds led1 and led2 are connected with arduino. When the button is off the both LEDs turns on then led1 turns off then turn on again , next time led2 turns off and turns on again.As the button will be pressed , brightness of led1 will be less than the brightness of led2 and then will again be equal to the brightness of led2, then brightness of led2 will be less than the brightness of led1 and then will be equal to the brightness of led1. But as I press the button , nothing happens but the led1 and led2 keeps turning on and off . However sometimes when I press the button then it works.

What is the problem with my code and how to solve it?

# Answer
There are a few issues with your wiring.

* As already stated in comments, you should not connect the battery to the 5V input of the Arduino. Use the “Vin” input instead.
* You should put a current-limiting resistor in series with each of your LEDs. Any value in the range 330 Ω – 1 kΩ should be fine. Your Arduino (and your LEDs) will last longer if you stop abusing it!
* There is no point in using two digital IO pins to read a button. Just connect the button between a digital input and GND. Alternatively, you can wire it like in Holmez's answer, but that requires an extra wire and a resistor.

And there are two main issues with your code:

* You forgot to debounce the button. Mechanical button are bouncy. The easiest way to debounce them is to use a ready-made library like, e.g., Bounce2.
* You are using `delay()`, which means you cannot respond to user input while your Arduino is busy delaying. You should manage your timings with `milis()` instead, as explained in the Blink Without Delay Arduino tutorial.

Here is my take at your problem. This is based on the finite state machine programming pattern, with a state defined by two variables. There is a `mode` variable used to keep track of whether we are in “digital” or in “analog” mode. And there is a “phase” variable used to keep track of the phase along the blinking pattern. Phases 0 through 3 correspond to (LED1/LED2) in the states: (HIGH/HIGH), (LOW/HIGH), (HIGH/HIGH), (HIGH/LOW). Note that, for simplicity, the LEDs are controlled with `analogWrite()`, even in “digital” mode.

```
#include <Bounce2.h>

const uint8_t BUTTON_PIN = 4;
const uint8_t LED1 = 11;
const uint8_t LED2 = 10;

Bounce button;

void setup()
{
    button.attach(BUTTON_PIN, INPUT_PULLUP);
    pinMode(LED1, OUTPUT);
    pinMode(LED2, OUTPUT);
    analogWrite(LED1, 255);
    analogWrite(LED2, 255);
}

/*
 * Vary the LED brightnesses along the following pattern:
 *
 *  phase:   0   1   2   3   0
 *          ___     ___________
 *  LED1:      \___/
 *          ___________     ___
 *  LED2:              \___/
 */
void loop()
{
    static enum { DIGITAL, ANALOG } mode = DIGITAL;
    static uint8_t phase = 0;
    static uint16_t phase_duration = 100;
    static uint8_t low_level = 0;
    static uint16_t last_change = 0;

    // Switch modes on button presses.
    button.update();
    if (button.fell()) {
        switch (mode) {
            case DIGITAL:
                mode = ANALOG;
                low_level = 150;
                phase_duration = 400;
                break;
            case ANALOG:
                mode = DIGITAL;
                low_level = 0;
                phase_duration = 100;
                break;
        }

        // Set initial phase.
        phase = 0;
        last_change = millis();
        analogWrite(LED1, 255);
        analogWrite(LED2, 255);
    }

    // Switch phase after phase_duration elapsed.
    if (millis() - last_change >= phase_duration) {
        last_change += phase_duration;
        phase = (phase + 1) % 4;
        switch (phase) {
            case 0:
                analogWrite(LED2, 255);
                break;
            case 1:
                analogWrite(LED1, low_level);
                break;
            case 2:
                analogWrite(LED1, 255);
                break;
            case 3:
                analogWrite(LED2, low_level);
                break;
        }
    }
}

```
> 1 votes

# Answer
Use a boolean:

```
boolean blink = false;
if(digitalRead(output) == 1){
    blink = !blink;
}

if(blink == true){
    digitalWrite(led1,HIGH);
    digitalWrite(led2,HIGH);
    delay(100);
    digitalWrite(led1,LOW);
    delay(100);
    digitalWrite(led1,HIGH);
    delay(100);
    digitalWrite(led2,LOW);
    delay(100);
    digitalWrite(led2,HIGH);
}else{
    analogWrite(led1,255);
    delay(400);
    analogWrite(led1,150);
    delay(400);
    analogWrite(led2,255);
    delay(400);
    analogWrite(led2,150);
}

```
> 0 votes

# Answer
There are several issues that I can see. To start with, you have the button wired to 2 pins, one configured as an input and one as an output. Starting out, you should connect the button as in the example below.

This will read LOW until the button is pressed.

~~I suspect in your case that because your using in INPUT\_PULLUP, your button will read HIGH when the button isn't pressed, but will continue to read HIGH even after the button is pressed - which leads to the second issue of your first while loop - because mode is initialised to 0, and the button is always reading HIGH, the condition for your while loop will always be true, consequently, the loop will never exist.~~

The next issue (if you change the code so the first while loop does exit) is that you're trying to do a digitalRead on an OUTPUT pin - as an OUTPUT pin, it will never detect the state of the button.

Another issue will be that when you press the button and the if statement is reached (because digitalRead(input) == 0), even if the button is pressed for the shortest time, the loop function will be run several times, and the if statement will be run several times which will effectively result in the mode containing either 0 or 1 almost at random.

While the best way to fix this is with an interrupt (another lesson for another day), a simple way is something like this:

```
    int buttonPressedProcessed = 0; // an indicator so we know if the button press has been processed.

void setup() {
    ...
}

void loop() {
  while(mode == 0 && digitalRead(input) == 1){
    buttonPressedProcessed = 0; // reset button pressed and processed indicator
    ...
  }
        // check also the button pressed and processed indicator
  if(digitalRead(input) == 0 && buttonPressedProcessed == 0){
    buttonPressedProcessed = 1; // set button pressed and processed indicator
    mode++;
    if(mode >= 2){mode = 0;}
  }
  while(mode == 1 && digitalRead(input) == 1){
    buttonPressedProcessed = 0; // reset button pressed and processed indicator
    ...
  }
}

```
> 0 votes

---
Tags: led, button
---


# Question
Title: How to read Serial data when multiple functions are Running?
I want to **halt the execution** of that code, when arduino is receiving **serial data** for the execution. Right now the Serial data runs when the other code has completed its execution. How can I do it ?

```
void loop() {
    dmd.setBrightness(brighVal); // set the brightness to led matrix
    scroll();  //function to scroll message

}
void serialEvent() {
  while (Serial.available()) {
    Jsondata = Serial.readString(); //reading json data from APP
    DynamicJsonBuffer jsonBuffer;
    Serial.println(Jsondata);
    JsonObject& root = jsonBuffer.parseObject(Jsondata);
    if (root.containsKey("BiM")) {
      brighVal = root["BiM"];
      switch (brighVal) {   // set's the value of brightness according to brighVal
        case 0:
          brighVal = 2;
          break;
        case 1:
          brighVal = 10;
          break;
        case 2 :
          brighVal = 25;
          break;
        case 3 :
          brighVal = 200;
          break;
      }
    }
  }
}
void scroll() {
  dmd.clearScreen( true );
  dmd.selectFont(Arial_Black_16);
  dmd.drawMarquee("Scrolling Text", 17, (32 * DISPLAYS_ACROSS) - 1, 0);
  long start = millis();
  long timer = start;
  boolean ret = false;
  while (!ret) {
    if ((timer + 30) < millis()) {
      ret = dmd.stepMarquee(-1, 0);
      timer = millis();
    }
  }
}

```

# Answer
> 7 votes
Then let scroll return immediately

```
void scroll() {
    static long timer = 0;
    static boolean scroll = true;
    if(scroll){
        dmd.clearScreen( true );
        dmd.selectFont(Arial_Black_16);
        dmd.drawMarquee("Scrolling Text", 17, (32 * DISPLAYS_ACROSS) - 1, 0);
        scroll = false;
        timer = millis()
    }else {
        if ((millis() - timer) > 30)  {
            scroll = dmd.stepMarquee(-1, 0);
            timer = millis();
        }
    }
}

```

The `static` keyword means that the value of the variable will be kept across calls.

I used the fact that it will be called in a loop to remove the while loop inside. I split the function up into 2 parts: The reset and the update. We first run the reset to init the marquee. After the reset it will set the boolean so the next time it will enter the update part. Then I used the exit condition of the original loop to make it reenter the update part next time.

---
Tags: serial
---


# Question
Title: How to read ASCII values from AT24C32 IC using Arduino? And what is serial.begin(?) in that EEPROM?
```
#include<Wire.h>
#include<Eeprom24C32_64.h>
#define EEPROM_ADDRESS 0x000

void setup() {
  Serial.begin(9600);
  eeprom.initialize();
  const word address = 0x000;
  const byte count = 94;
  byte inputBytes[count] = { 0 };
  byte outputBytes[count] = { 0 };
  Serial.println("Read bytes from EEPROM memory...");
  eeprom.readBytes(address, count, outputBytes);
  Serial.println("Read bytes:");
  for (byte i = 0; i < count; i++) {
    Serial.write(outputBytes[i]);
    Serial.print(" ");
  }
  Serial.println("");
}

void loop() {
}

```

Next code... I have tried many sketches.

```
#include <EEPROM.h>

void setup () {
  Serial.begin (115200);
  Serial.println ();
  for (int addr = 0x0000; addr < 0x0010; addr++) {
    Serial.print ("Address = ");
    Serial.print (addr, HEX);
    Serial.print (", value = ");
    Serial.println (EEPROM.read(addr), HEX);
  }
}  // end of setup

void loop () {
}

```

And most of the sketches check the internal EEPROM of the Arduino, not the external, stored on address 0x000. I want to read data from external AT24C32.

# Answer
> 1 votes
You have to know what the I2C address of your EEPROM is. Right now you have

```
#define EEPROM_ADDRESS 0x000

```

The example from the library you cite has this:

```
/**************************************************************************//**
 * \def EEPROM_ADDRESS
 * \brief Address of EEPROM memory on TWI bus.
 ******************************************************************************/
#define EEPROM_ADDRESS 0x50

```

Then, you have to create an instance of the `Eeprom24C32_64` object:

```
static Eeprom24C32_64 eeprom(EEPROM_ADDRESS);

```

That sets up the object for the EEPROM on the right I2C address, so you can later use the `eeprom` object to read and write.

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


title: Fill an Array with Values

text:
# Question
Title: Fill an Array with Values
I have a function in which I change the pinMode on many of my Arduino's pins based on a passed in mode. I first construct an array of bytes specifying each pin to be an input or an output and then I iterate through the array to set all the pins.

```
void pinout(byte mode) {
  switch(mode) {
    case 0: char pins[13] = {'O','O','I','I','O','I','I','I','I','O','I','I','O'}; break;
    case 1: char pins[13] = {'O','I','I','O','O','I','O','O','I','O','I','O','I'}; break;
  //etc..
  }
  for(byte i = 0; i <= 13; i++) {
    if(pins[i] == 'I') pinMode(i, INPUT);
    else pinMode(i, OUTPUT);
  }
}

```

However, since the array is defined inside the switch statement, I loose scope of the pins array when I move onto the for loop. I tried defining the `pins[]` outside of the switch statement, but then I am confused on how to populate it efficiently. These all threw errors when I tried to populate the variable inside the switch statement:

```
pins[0,1,2,3,...,12,13] = {...};
pins[13] = {...};
pins[] = {...};
pins = {...};

```

I know I could go through each entry individually, but this could be rather inefficient use of memory and computational power as I add more cases. Any ideas?

# Answer
> 1 votes
Since your values are all constant you can define them all as constant values and just select between them. The simplest way is to add an extra dimension to your arrays:

```
const char pins[2][13] =
    {'O','O','I','I','O','I','I','I','I','O','I','I','O'},
    {'O','I','I','O','O','I','O','O','I','O','I','O','I'}
};

for(byte i = 0; i < 13; i++) {
    if(pins[mode][i] == 'I') pinMode(i, INPUT);
    else pinMode(i, OUTPUT);
}

```

**(Note: An array of size 13 has entries 0-12.)**

However, that is very inefficient. Since you only have two states, I and O, and there are only 13 entries, you can store each array as a single 16-bit value:

```
const uint16_t pins[2] = {
    0b0110111101100,
    0b1010100100110
};

for(byte i = 0; i < 13; i++) {
    if((pins[mode] & (1 << i)) pinMode(i, INPUT);
    else pinMode(i, OUTPUT);
}

```

**(Note: the data is stored backwards - pin 0 is on the right, pin 12 on the left.)**

# Answer
> 0 votes
> I know I could go through each entry individually, but this could be rather inefficient use of memory and computational power as I add more cases.

The compiler produces assembly/machine code that takes the same effort to load the array, so it's not that inefficient. The bracket arrangement is just a construct for easier to read code.

---
Tags: arduino-uno, pins, array, variables
---


title: Reading a varying voltage into Arduino

text:
# Question
Title: Reading a varying voltage into Arduino
Using an Arduino Nano and a current transformer (CT), I'm trying to sense the current flowing through a 120 V 60 Hz line.

**Circuit**

CT outputs `0-1 V` according to its specifications. This output is biased `AREF/2` = 2.5 V.

**`analogRead` Values**

The x-axis represents the index number of the ADC sample, while the y-axis represent the ADC value (0-1024). Sampling rate is about 9 kHz. Peak-to-peak difference is about 1026 samples.

Is this waveform what you would expect from the CT? Why are there regions where the values are flat, rather than varying continuously?

Furthermore, if we look at the curve part of the plot, why is Arduino reading values both above `512` and below `512` alternately? It reads a value above `512`, then a value below `512`, then a value above `512` and so on.

Time taken for an `analogRead` was measured to be 110 microseconds for my setup and there are 1026 samples between the waveform peaks. That means there will be about 9 peaks in 1 second, although I would expect 60 peaks since we are sensing a 60 Hz line. What do you make out of this? There's a capacitor, `C1`, in the circuit, would it have anything to do with this?

Are these analogRead values suitable to be used to calculate the RMS voltage, and hence the RMS current passing through the wire being sensed? The final goal of this is to calculate the power usage after determining the RMS current flowing through the wire.

**Sketch used to get values for plot**

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

void loop() {
   double sensorValue = analogRead(1);
   Serial.println(sensorValue)
}

```

**Actual `analogRead` data points in the bump regions**

```
487
534
487
535
488
537
484
536
487
538
486
536
484
540
484
539
485
540
483
540
484
541
481
539
481
540
484
540
480
543
484
539
481
540
484
541
486
542
485
538
485
538
488
535
489
534
491
530
491
529
493
531
492
526
498
526
499
524
499
520
503
518
502
518
507

```

---

**Plot of analogRead values**

The analogRead values are now stored in a buffer before being transmitted over Serial. There are now 55 ADC datapoints making up 1 period. Considering the analogRead time is 110 µs, each cycle takes 6.05 ms, giving us a frequency of 165 Hz! What may have gone wrong?

```
void loop() {
    double sensorValue = analogRead(1);
    char buf[32];

    dtostrf(sensorValue, 8, 2, buf);
    value = buf;

    if (stop == 0) {
        if (i < 10000) {
            message += ',';
            message += value;
            i++;
        }
        else {
            stop = 1;
            Serial.println(message);
        }
    }
}

```

# Answer
Regarding your measurements, I would completely disregard the first set with Serial.println() in the loop. I would exepect the timing of this to be unreliable.

Your second set of data that you captured in a buffer looks correct, but your Frequency Estimation / timing may be wrong. I would invert a Digital Output at each loop iteration. You can measure the frequency of that with a Multimeter and your ADC sample rate would be twice that value.

For a PC or laptop power supply that's quite a common current waveform.

Without effective Power Factor Correction the current signal shown below would be quite typical (source: http://www.nlvocables.com/blog/?p=300)

You will need to calculate RMS values and it would be wise to filter the signal.

Here's an instructable I wrote on how to build and code an Arduino Yun based Electricity Monitor with Cloud Support / Temboo and Google Drive. It should be of some help to you.
> 5 votes

# Answer
if you are measuring a resistive load I would say that the burden resistor you have chosen is wrong, there are some cheap CT's on ebay (SCT-013-xxx) that have versions with and without the burden resistors, these work well for their price but you must read the datasheet. the SCT-013-000 requires a 20R resistor to get 1V out with a 100A load, if this resistor is wrong you can get a severely distorted waveform when measuring higher currents (similar to those you have provided), you would expect the signal to distort more the lower the burden resistor value but this is not the case with CT's.
> 0 votes

---
Tags: programming, sensors, power, voltage-level, arduino-nano
---


# Question
Title: Lost AT+ commands on ESP8266 after flashing with "blink" sketch
I set my ESP8266 ESP-01 to flash mode and uploaded the example blink sketch on the arduino IDE esp example options. I know can no longer communicate with the ESP8266 using AT+ commands. I also cannot flash the device and can only receive the following message under baud 74880

" ets Jan 8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 1264, room 16 tail 0 chksum 0x0f csum 0x0f ~ld "

Anyone know how to fix this? Thanks.

# Answer
Thank you Juraj!

I had attempted to update the firmware multiple times and after 6hrs of trying was giving up. I really thought I had trashed my ESP-01. My post here was my last attempt to resolve the issue. I tend to have a problem of not asking for help until I'm frustrated. I saw your comment, and even though I had already attempted to reflash with new firmware I realized that you knew something I did not, and hopefully I could still salvage the ESP-01. So I downloaded documents about the esp8266 and decided to give it another try. What I found is my ignorance had let me believe that the esp-01 was broken when it was functioning as it should. Anytime you upload new firmware it will replace the old (including the at commands, but that's what it suppose to do). I then found this page that brought to my attention the mistake I was making. I was flashing the files to the wrong address, and there are multiple locations where the "blank" file needs to be flashed to. So all is back to normal. At commands have returned. Now I have to remove them again to upload my program :).

https://www.allaboutcircuits.com/projects/flashing-the-ESP-01-firmware-to-SDK-v2.0.0-is-easier-now

I almost forgot to mention, I also had to hard wire my GPIO0 pin to ground before flashing. I was originally pulling GPIO0 to ground with a button. However, even though the serial console showed that I had booted in flash mode the flash tool failed. Only after hardwiring the GPIO0 to ground would the flash tool work.
> 2 votes

# Answer
on Windows use Espressif Flash Download Tool to flash the AT firmware. Everything is on Espressif's site
> 1 votes

---
Tags: esp8266
---


# Question
Title: RFID + LCD + Arduino Mega 2560 = RFID not printing correctly
My Arduino Mega isn't printing the RFID card's tag it simply prints the card's 2 digits at a time but deletes the previous prints. Can I get help with this?

```
#include <SPI.h>
#include <MFRC522.h>
#include <Servo.h>
#include <LiquidCrystal.h>

Servo myservo;  //creates servo to control

const int rs = 26, en = 27, d4 = 28, d5 = 29, d6 = 31, d7 = 30;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

#define SS_PIN 53
#define RST_PIN 5
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
int R=3;
int G=8;
int B=6;

void setup() {
  lcd.begin(16, 2);
  Serial.begin(9600);   // Initiate a serial communication
  SPI.begin();      // Initiate  SPI bus
  mfrc522.PCD_Init();   // Initiate MFRC522
  Serial.println("Approximate your card to the reader...");
  lcd.print("Place your card");
  lcd.setCursor(0, 1);
  lcd.print("Near reader");
  lcd.setCursor(0, 0);
  myservo.attach(7);//attatches servo to pin 7
  myservo.write(179);
}

void loop() {
  analogWrite(B, 255);
  // Look for new cards
  if (!mfrc522.PICC_IsNewCardPresent()) {
    return;
  }
  // Select one of the cards
  if (!mfrc522.PICC_ReadCardSerial()) {
    return;
  }
  //Show UID on serial monitor
  Serial.print("UID tag :");
  byte letter;
  String content= "";
  for (byte i = 0; i < mfrc522.uid.size; i++) {
     lcd.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     lcd.print(mfrc522.uid.uidByte[i], HEX);
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
     lcd.setCursor(0, 0);
  }
  delay(1000);
  lcd.clear();
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "4F 60 3C D9") {
    //change here the UID of the card/cards that you want to give access
    Serial.println("Authorized access");
    lcd.print("Authorized");
    analogWrite(B, 0);
    tone(4, 900, 100);
    lcd.clear();
    Serial.println("Unlocking...");
    lcd.print("Unlocking...");
    lcd.clear();
    analogWrite(R, 255);
    analogWrite(G, 127);
    delay(1000);
    myservo.write(100);
    delay(15);
    Serial.println("Unlocked");
    lcd.print("Unlocked");
    lcd.clear();
    analogWrite(R, 0);
    analogWrite(G, 255);
    delay(5000);
    Serial.println("Relocking...");
    lcd.print("Relocking...");
    lcd.clear();
    analogWrite(R, 255);
    analogWrite(G, 127);
    delay(1000);
    myservo.write(179);
    delay(15);
    Serial.println("Locked");
    lcd.print("Locked");
    lcd.clear();
    analogWrite(R, 0);
    analogWrite(G, 0);
    delay(100);
  } else {
    Serial.println("Checking Card");
    lcd.print("Checking Card");
    lcd.setCursor(0, 1);
    delay(100);
    lcd.clear();
    Serial.println("Access denied");
    lcd.print("Access denied");
    analogWrite(B, 0);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(100);
  }
 lcd.clear();
 Serial.println("Ready");
 lcd.print("Ready");
}

```

# Answer
> 0 votes
OK i fixed it. It is now this :

```
#include <SPI.h>
#include <MFRC522.h>
#include <Servo.h>
#include <LiquidCrystal.h>

Servo myservo;  //creates servo to control

const int rs = 44, en = 45, d4 = 46, d5 = 47, d6 = 49, d7 = 48;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

#define SS_PIN 53
#define RST_PIN 5
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
int R=3;
int G=8;
int B=6;

void setup()
{
  lcd.begin(16, 2);
  Serial.begin(9600);   // Initiate a serial communication
  SPI.begin();      // Initiate  SPI bus
  mfrc522.PCD_Init();   // Initiate MFRC522
  Serial.println("Place your card near reader");
  lcd.print("Place your card");
  lcd.setCursor(0, 1);
  lcd.print("Near reader");
  lcd.setCursor(0, 0);
  myservo.attach(7);//attatches servo to pin 7
  myservo.write(179);
}
void loop()
{
  analogWrite(B, 255);
  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    return;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())
  {
    return;
  }
  //Show UID on serial monitor
  lcd.clear();
  Serial.print("UID tag :");
  lcd.print("ID:");
  byte letter;
  String content= "";
  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
     Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     Serial.print(mfrc522.uid.uidByte[i], HEX);
     lcd.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     lcd.print(mfrc522.uid.uidByte[i], HEX);
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "4F 60 3C D9") //change here the UID of the card/cards that you want to give access
  {
    delay(5000);
    lcd.clear();
    Serial.println("Scanning Database");
    lcd.print("Scanning");
    lcd.setCursor(0, 1);
    lcd.print("Database");
    lcd.setCursor(0, 0);
    delay(5000);
    lcd.clear();
    Serial.println("Authorized access");
     lcd.print("Authorized");
    analogWrite(B, 0);
    tone(4, 900, 100);
    lcd.clear();
    Serial.println("Unlocking...");
    lcd.print("Unlocking...");
    lcd.clear();
    analogWrite(R, 255);
    analogWrite(G, 127);
    delay(1000);
    myservo.write(100);
    delay(15);
    Serial.println("Unlocked");
    lcd.print("Unlocked");
    delay(5000);
    lcd.clear();
    analogWrite(R, 0);
    analogWrite(G, 255);
    Serial.println("Relocking...");
    lcd.print("Relocking...");
    delay(1000);
    lcd.clear();
    analogWrite(R, 255);
    analogWrite(G, 127);
    myservo.write(179);
    delay(15);
    Serial.println("Locked");
    lcd.print("Locked");
    delay(100);
    lcd.clear();
    analogWrite(R, 0);
    analogWrite(G, 0);
  }else{
    delay(1000);
    lcd.clear();
    Serial.println("Scanning Database");
    lcd.print("Scanning Databas");
    delay(5000);
    lcd.clear();
    Serial.println("Access denied");
    lcd.print("Access denied");
    analogWrite(B, 0);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(500);
    tone(4, 1900, 1000);
    analogWrite(R, 255);
    delay(500);
    analogWrite(R, 0);
    delay(100);
  }
 lcd.clear();
 Serial.println("Ready");
 lcd.print("Ready");
}

```

had to remove the `lcd.setCursor(0, 1);` from line 57.

---
Tags: lcd, rfid
---


title: Battery life with Nano v3

text:
# Question
Title: Battery life with Nano v3
Easy secret knock detector to trigger anything with only an Arduino and a few cheap components

First of all I need to state that I'm new to Arduino and electronics in general. My question is about a project where the Nano is being powered up with a 12v rechargeable li-ion 2800 mAh battery on pins VIN and GND.

I'm using the 5v Nano pin to power a SRD-05VDC-SL-C relay along with the ground pin from the Nano. The IN pin on the relay is from the D11 pin on the Nano. So far so good. I'm also using the same 12v battery to power up a solenoid latch, which energizes for just a few seconds.

When I tested this setup (less the relay AND solenoid) for battery life, my volt meter read 9.8v and 1 hour later 2.8v. causing the Nano to go off.

How can I increase battery life?

This is the link to the code I used:

I'm not having an issue with the code or the operation of the setup but the battery life is unacceptable.

# Answer
Something is wrong with your setup. I don't have a Nano to hand to test, but it would consume similar current to a Uno (probably less) which is around 50 mA. Thus, using a 2800 mAh battery you should have a life of 2800/50 = 56 hours.

Li-ion batteries come in multiples of cells, where individual cells have a nominal voltage of 3.6V (thus you probably have three cells giving 10.8V). Deeply discharged they will have a voltage of 3.0V per cell (a total of 9V for your three cells). If you started at 9.8V as you stated, then the cells would have been 90% discharged already which probably accounts for the short running time.

Assuming you haven't wired it in a strange way (and it would help to show the wiring and possibly a photo) I suggest you try with a fully-charged battery.

---

Another helpful thing to do would be to measure the current consumption of the battery using a multimeter. Make sure you read up on how to measure current with a meter or you may damage something (example here).

The basic idea is shown in this photo:

The meter is placed in *series* with the battery and the Arduino. The negative side of the battery goes to the Arduino in the usual way. The positive side of the battery goes into the "milliamps" input of the meter (which is set to 200 mA range in my case) and then the common (black) lead from the voltmeter goes to the positive (Vin) side of the Arduino.

You can see that in this particular case, with a 9V battery, the Arduino is consuming 57.7 mA. I don't quite believe that reading as re-measuring with a more expensive meter gave a reading of 51.1 mA. Still, that gives you a ball-park figure. And it shows that spending a bit more on a better meter gives you more accurate results. :)

---

I have a page about power saving and you can also refer to the Wikipedia page about Li-ion batteries.

---

> my volt meter read 9.8v and 1 hour later 2.8v. causing the Nano to go off.

For a 12V Li-ion battery get down to 2.8V there is something seriously wrong with its protection circuitry. It should cut the battery out at 3V per cell, that is at 9V if you have 3 cells in series.
> 2 votes

---
Tags: power, arduino-nano, battery
---


# Question
Title: Weird result printing an array using a loop
first of all I'm sorry for my english.

My problem is that I want to use an array of numbers on a function, but I'm getting a weird result inside a for loop. Doing some tests I've seen that it happens even in the simplest sketch so I should be doing something wrong.

I've created a two level int and I want to iterate through the second level using a for loop. Outside the for loop all data gotten from that array is OK, but just inside the loop I'm just getting garbage as if the array was not initialized.

My simple sketch is this:

```
const int number_small[][14] PROGMEM = {
  {124, 124, 387, 387, 399, 399, 443, 443, 483, 483, 387, 387, 124, 124},
};

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

  Serial.print(String(number_small[0][0]) + "\n");
  Serial.print(String(number_small[0][1]) + "\n");
  Serial.print(String(number_small[0][2]) + "\n");
  Serial.print(String(number_small[0][3]) + "\n");
  Serial.print(String(number_small[0][4]) + "\n");
  Serial.print(String(number_small[0][5]) + "\n");
  Serial.print(String(number_small[0][6]) + "\n");
  Serial.print(String(number_small[0][7]) + "\n");
  Serial.print(String(number_small[0][8]) + "\n");
  Serial.print(String(number_small[0][9]) + "\n");
  Serial.print(String(number_small[0][10]) + "\n");
  Serial.print(String(number_small[0][11]) + "\n");
  Serial.print(String(number_small[0][12]) + "\n");
  Serial.print(String(number_small[0][13]) + "\n\n\n");

  for (int i = 0; i<14; i++){
    Serial.print("I: " + String(i) + " - " + String(number_small[0][i]) + "\n");
  }
}

void loop() {
}

```

And the output is:

```
124
124
387
387
399
399
443
443
483
483
387
387
124
124

I: 0 - 0
I: 1 - 184
I: 2 - 0
I: 3 - 1
I: 4 - 0
I: 5 - -18248
I: 6 - -18248
I: 7 - -18248
I: 8 - 0
I: 9 - 135
I: 10 - 0
I: 11 - 0
I: 12 - 769
I: 13 - 0

```

What I'm doing wrong?,

Thanks!!

# Answer
Constants like `String(number_small[0][0])` are optimized by compiler during the build (=compile time).

However that's not the case of loop. So you have to use specific functions for reading values from `PROGMEM` in the runtime:

```
for (int i = 0; i<14; i++){
  Serial.print("I: ");
  Serial.print(i);
  Serial.print(" - ");
  Serial.println((int)pgm_read_word(number_small[0]+i));
}

```

Btw: Don't use string concatenations. These are extremely hungry for the memory. See Majenko's article: The Evils of Arduino Strings
> 2 votes

# Answer
I was sure that I was doing something wrong and yes... Finally I did another test (storing the array on SRAM instead on PROGMEM) and it worked, so I've changed my "research direction" and I've found the solution.

With my initial sketch I was reading the PROGMEM from outside the loop, but from inside the loop what i read is the SDRAM, so I've to use the **pgm\_read** functions to force to read from PROGMEM, and now finally is working:

> pgm\_read\_word(number\_small\[0\] + i)

```
const int number_small[][14] PROGMEM = {
  {124, 124, 387, 387, 399, 399, 443, 443, 483, 483, 387, 387, 124, 124},
};

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

  Serial.print(String(number_small[0][0]) + "\n");
  Serial.print(String(number_small[0][1]) + "\n");
  Serial.print(String(number_small[0][2]) + "\n");
  Serial.print(String(number_small[0][3]) + "\n");
  Serial.print(String(number_small[0][4]) + "\n");
  Serial.print(String(number_small[0][5]) + "\n");
  Serial.print(String(number_small[0][6]) + "\n");
  Serial.print(String(number_small[0][7]) + "\n");
  Serial.print(String(number_small[0][8]) + "\n");
  Serial.print(String(number_small[0][9]) + "\n");
  Serial.print(String(number_small[0][10]) + "\n");
  Serial.print(String(number_small[0][11]) + "\n");
  Serial.print(String(number_small[0][12]) + "\n");
  Serial.print(String(number_small[0][13]) + "\n\n\n");

  int i;
  for (i = 0; i<14; i++){
    Serial.print("I: " + String(i) + " - " + String(pgm_read_word(number_small[0] + i)) + "\n");
  }
}

void loop() {
}

```

Thanks and greetings!!
> 1 votes

# Answer
I refined your own answer:

* No need to use String to print a numeric value; just print the value.
* No need to add "\n" add the end of `print`, use `println`instead.
* No need to concatenate strings for printing; just print them one by one.
* In a `for` loop, declare the control variable *inside*

Code

```
const int ITEMS = 14;
const int number_small[][ITEMS] PROGMEM = {
  {124, 124, 387, 387, 399, 399, 443, 443, 483, 483, 387, 387, 124, 124},
};

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

  for (int i=0; i < ITEMS; i++) {
    Serial.println(pgm_read_word(number_small[0]+i));
  }
  Serial.println();  Serial.println();
  for (int i = 0; i < ITEMS; i++){
    Serial.print("I: "); Serial.print(i); Serial.print(" - " );
    Serial.println(pgm_read_word(number_small[0] + i));
  }
}

void loop() {
}

```
> 1 votes

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


# Question
Title: Can we use serial.begin command anywhere in code?
When to use this command? What difference it would create if I add this command in loop function, setup function and declaration section?

# Answer
You cannot call `Serial.begin()` in a declaration. Like any program instruction, you can only use it from within a function. As stated in Juraj's answer, you can call it as many times as you want. However, most often it only makes sense to do this in `setup()`, in order to initialize the serial link once and for all at the beginning of your program. Why would you ever want to do this initialization multiple times?

Thinking about it, I can see two possible scenarios:

1. Your UART is connected, through a suitable transceiver, to an RS-485 bus. You have several slaves on this bus that require different UART configurations (different baud rates, or number of data bits, or parity). Then, each time you want to address one slave, you first set your UART to the configuration suitable for that particular slave. In this kind of situation, however, it would be more convenient to arrange for all the slaves to share the same UART configuration, if at all possible.
2. Your UART is connected to a device that continually sends data you are not interested in. This could be, e.g., a GPS module. Since you don't want your program to be interrupted every time a character is received, you keep the UART disabled. Only when you do want the data you enable it with `Serial.begin()`, you read as much as you need, then you disable it again with `Serial.end()`.

There may be other situations, but I bet they are all quite atypical scenarios. The common practice is to call `Serial.begin()` once in `setup()`, and have the UART enable from there on.
> 2 votes

# Answer
Serial.begin sets the baud rate. And the baud rate is important to the other side of the line. You can use Serial.begin where you need it, only care that the other side of the line has that baud rate too.

I use Serial1.end and Serial1.begin to change the baudrate in a Firmata sketch for Uno WiFi. Some seconds after the start the sketch detects esp flashing sequence on Serial. If detected, the sketch switches the baudrate of Serial1 from Firmata's optimal 57600 to bridge the flashing of esp at 230400 baud.
> 0 votes

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