# Question
Title: Simon Says Project - Can't go from random lights to user input
I'm new to using an Arduino and I am attempting the Simon Says game. Right now, I do not understand why my program will not go from activating the random lights to the user input. Currently it is flashing all the lights three times like I want it to, but then it will flash three random lights and then go straight to flashing every light, right to left (which is the indicator that the wrong button was pushed).

I am working in Tinkercad/circuits.io and have had the physical implementation looked at, and it is good. I just can't figure out the code. Anything will help, thanks!

```
// Defining LEDs and buttons.
int leds[] = {12, 10, 7, 4};
int buttons[] = {11, 9, 6, 3};

const int max = 40;
int lightArr[max]; // Array with full patterns of LEDs.
int currArr[max];
int gameState = 0;
int level = 1;
int count = 0; // Counter for every sequence of iterating over the
random array of ints (LEDs).
int buttonPressed = -1;
int correct = 1;

void setup() {
  pinMode(leds[0], OUTPUT);
  pinMode(leds[1], OUTPUT);
  pinMode(leds[2], OUTPUT);
  pinMode(leds[3], OUTPUT);
  pinMode(buttons[0], INPUT);
  pinMode(buttons[1], INPUT);
  pinMode(buttons[2], INPUT);
  pinMode(buttons[3], INPUT);
  randomSeed(analogRead(0));
  allOn();
}

void loop() {
  if (gameState == 0) {
    resetGame();
  } else if (gameState == 1) {
    play();
  } else if (gameState == 2) {
    gameOver();
  }
}

void resetGame() {
  if (level == 1) {
  // Setting up a sequence of random lights.
    for (int i = 0; i < 40; i++) {
      lightArr[i] = random(0,4);
    }
  }
  level = 1;
  gameState = 1;
}

void play() {
  while (correct == 1) {
    showPattern();
    int correct = userInput();
  }
}

void showPattern() {
  for (int i = 0; i < level; i++) {
    delay(500);
    digitalWrite(leds[lightArr[i]], 1);
    delay(500);
    digitalWrite(leds[lightArr[i]], 0);
    delay(500);
  }
}

int userInput() {
  for (int i = 0; i < level; i++) {
    int buttonPressed = readOneButton();
    digitalWrite(leds[buttonPressed], 1);
    delay(500);
    digitalWrite(leds[buttonPressed], 0);
    delay(500);
    if (lightArr[i] != buttonPressed) {
      // User button pressed.
      gameState = 2;
      correct = 0;
    }
  }
}

void gameOver() {
  for (int i = 0; i < 3; i++) {
    digitalWrite(leds[0], 1);
    delay(150);
    digitalWrite(leds[0], 0);
    delay(150);
    digitalWrite(leds[1], 1);
    delay(150);
    digitalWrite(leds[1], 0);
    delay(150);
    digitalWrite(leds[2], 1);
    delay(150);
    digitalWrite(leds[2], 0);
    delay(150);
    digitalWrite(leds[3], 1);
    delay(150);
    digitalWrite(leds[3], 0);
    delay(150);
  }
  gameState = 0;
}

int readOneButton() {
  if (digitalRead(buttons[0])) {
    return 0; // Button: Red
  } else if (digitalRead(buttons[1])) {
    return 1; // Button: Green
  } else if (digitalRead(buttons[2])) {
    return 2; // Button: Blue
  } else if (digitalRead(buttons[3])) {
    return 3; // Button: Yellow
  }
}

void allOn() {
  for (int i = 0; i < 3; i++) {
    digitalWrite(leds[0], 1);
    digitalWrite(leds[1], 1);
    digitalWrite(leds[2], 1);
    digitalWrite(leds[3], 1);
    delay(500);
    digitalWrite(leds[0], 0);
    digitalWrite(leds[1], 0);
    digitalWrite(leds[2], 0);
    digitalWrite(leds[3], 0);
    delay(500);
  }
}

```

# Answer
```
void play() {
  while (correct == 1) {
    showPattern();
    int correct = userInput();
  }
}

```

Why do you create a new variable called correct and put the value form userInput in that? Why don't you put the return from userInput into the variable named correct that you already have? Two variables with the same name in the same scope is NEVER a good idea. The original correct will never be changed here so this becomes an infinite loop.

Next, look at readOneButton. It will take the Arduino just a few microseconds to run through that for loop and the whole userInput function. Unless you are super duper fast at getting that button pressed, it is just going to decide that you didn't press any buttons. You don't have a case in there for no button pressed, so it is going to return 0. You should probably wait until the user presses a button before you decide whether he is right or wrong.
> 0 votes

---
Tags: input
---


title: Arduino Mega Wifi Shield Timeout Error

text:
# Question
Title: Arduino Mega Wifi Shield Timeout Error
I got an Arduino Mega(not original) and also a Wifi shield, when ever I try to upload my code to it, I get this error:

```
Sketch uses 5504 bytes (2%) of program storage space. Maximum is 253952 bytes.
Global variables use 704 bytes (8%) of dynamic memory, leaving 7488 bytes for local variables. Maximum is 8192 bytes.
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer
An error occurred while uploading the sketch

```

Without the shield on it works perfectly, but as soon as I plug it in it stops working, I tried uploading the code without shield and placing the shield but this way the serial port didn't work.

The shield I bought is:
**ESP8266 ESP-12E UART WIFI Module Wireless Shield Converter For Arduino UNO Mega**

**Edit:** If there is anything connected to the arduino it wont upload, it is not just the shield, I can't get my OLED to work either. Also tried using the shield on my UNO and I get the same result.

# Answer
> 0 votes
via Google I found this helpful site which has an answer that might help. It is not the same question as yours, but it explains what the dip switches are for

How to connect Wi-Fi shield ESP-12E-ESP8266-UART-WIFI-Wireless-Shield with Arduino

It seems that *IF* you have what is pictured a 'shield' version of the board, as opposed to a 'shaild' version, then when you plug it in to an uno it will stop the uno working, because of the serial connection from the ESP on shield pins 0 and 1. I don't know where these pins are going on your mega, but it might be the same issue. This page recommends bending the pins out the way and wiring them to other pins - Which is at your risk. You could trial it by wiring the whole shield to the mega and seeing if it worked.

https://claus.bloggt.es/2017/02/26/arduino-esp8266-wifi-shield-elecshop-ml-by-wangtongze-comparison/

---
Tags: arduino-mega, wifi, shields
---


# Question
Title: Arduino Nano v3: is it possible to PCM + AltSoftSerial?
I wonder is it possible to change PCM.h 's lib use of 16-bit timer1 to another 8-bit? Now I'm getting

```
libraries\AltSoftSerial\AltSoftSerial.cpp.o (symbol from plugin): In function `AltSoftSerial::read()':

(.text+0x0): multiple definition of `__vector_11'

libraries\PCM\PCM.c.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1

```

when compiling

```
#include <PCM.h>
#include <AltSoftSerial.h>

```

An attempt to avoid XY problem: make AltSoftSerial work alongside with PCM-alike library on Arduino Nano v3 without SD.

I'm poorly familiar with timers and interrupts, so I'll be very grateful for any advice and suggestion!

# Answer
It is not easy to make PCM sounds with the Arduino Uno or Nano. A few libraries can do that, but they use two timers: Timer1 and Timer2. Timer0 is already in use by Arduino. When using those libraries, the Arduino Nano is almost completely occupied to make sounds.

A software serial port also requires a lot from the Arduino Nano. The AltSoftSerial uses Timer1.

Those two will never work together. It is not possible.
For what do you need the serial port ?
Could that be done in a different way ?

The normal SoftwareSerial does not use a timer, but because it also occupies the Arduino Nano a lot, using SoftwareSerial together with a PCM sound at the same time will not work. Perhaps if you carefully design the sketch and never use them at the same time, it might work. I doubt if it will be reliable.

A better option is to swap the Arduino Nano for an Arduino Micro. Then you have a extra hardware serial port and you don't need the AltSoftSerial anymore. The library to make PCM sounds has to be compatible with the Arduino Micro. I suppose that not every PCM library is compatible.

The best option is to use a MP3 shield. Then you can send a command to play a MP3 sound. If you use a MP3 shield with a Arduino Micro or Arduino Leonardo or Arduino Mega 2560 or Arduino Zero or Arduino Due, then you have a extra hardware serial port and you don't need libraries that occupy the most of the Arduino board, and your sketch will be a normal sketch that does normal things.
> 0 votes

---
Tags: arduino-nano, interrupt, timers
---


title: How do i fill the second byte?

text:
# Question
Title: How do i fill the second byte?
I am using I2C communications to control a AD5694RBRUZ (http://www.analog.com/media/en/technical-documentation/data-sheets/AD5696R\_5695R\_5694R.pdf) with my Arduino Nano. If i enter two bytes it wil Wire.write only the first line from top to bottom. In the datasheet it is shown that you muust first fill the command byte, then the high and last the low byte. How can i fill the low byte? I have now scraped the idea to input two bytes separately and decided to input one uint16\_t byte. How do i fill the low byte at the same time as the high byte, or if it possible how to input the uint16\_t value?

My code is as follows:

```
#include <Wire.h>

#define Address 0x0D

void setup()
{
Serial.begin(9600);
Wire.begin();
AddressWrite(0x3F,0x05B0);
Serial.print ("Biti = ");
Serial.println (AddressRead(0x01));
}

void loop()
{
}

void AddressWrite (byte Naslov, uint16_t Cifra1)
{
byte Hi, Lo;
Hi = highByte(Cifra1);
Lo = lowByte(Cifra1);
Wire.beginTransmission(Address);
Wire.write(Naslov);
Wire.write(Cifra1);
Wire.endTransmission();
Serial.print ("Biti Hi = ");
Serial.println (Hi);
Serial.print ("Biti Lo = ");
Serial.println (Lo);
Serial.print ("Biti Cifra = ");
Serial.println (Cifra1);
}

byte AddressRead (byte naslov)
{
Wire.beginTransmission(Address);
Wire.write(naslov);

Wire.requestFrom(Address,2);

while(!Wire.available())
  {
  }

return Wire.read();
}

```

Thank you for your time and help.

# Answer
> 0 votes
You can use a number of Wire.write to write data. The AD5694R should get three bytes and two bytes can be read from it. There is a "multiple dac readback sequence", but that is an extra.

Your AddressWrite requires an extra Wire.write.
Your AddressRead is missing a Wire.endTransmission and the `while(!Wire.available())` should be removed.

```
void AddressWrite (byte Naslov, uint16_t Cifra1)
{
  byte Hi, Lo;
  Hi = highByte(Cifra1);
  Lo = lowByte(Cifra1);

  Wire.beginTransmission(Address);
  Wire.write(Naslov);       // command byte
  Wire.write(Hi);           // msb first
  Wire.write(Lo);           // lsb second
  Wire.endTransmission();
}

uint16_t AddressRead (byte naslov)
{
  Wire.beginTransmission(Address);
  Wire.write(naslov);       // command byte
  Wire.endTransmission(false);  // repeated start

  uint16_t hi, lo, result;
  Wire.requestFrom(Address,2);
  hi = Wire.read();
  lo = Wire.read();
  result = word(hi,lo);
  return result;
}

```

I have added a repeated start, because that is according to the datasheet.

Could you make the names more according to the datasheet ? For example 'command' or 'commandByte' instead of 'Naslow'. And perhaps better names for the functions, for example 'writeAD5694R' instead of 'AddressWrite'.

---
Tags: arduino-nano, i2c, adc
---


# Question
Title: RadioHead library nrf24 sending and receiving struct data problem
I am using RadioHead library for the communication between nrf24l01. I am sharing the snippet of my code below because the code is too huge. The problem i am facing here is on the receiver side i am not be able see the data i am sending , it is showing squares and not the proper characters. my output showing to me is :

name :?!

skill :

Sender Code :

```
struct DataHolder {
  String name;
  String skill;
};

DataHolder dh;

RH_NRF24 nrf24(10, 9);

//THIS METHOD I AM USING TO SEND DATA FROM SENDER NRF
void sendtonrf(){

 dh.name = "xyz";
 dh.skill = "classA";

 nrf24.send((uint8_t *)&dh, sizeof(dh));

}

```

receiver code:

```
struct DataHolder {
String name;
String skill;
};

 DataHolder dh;

 void loop{

 if (nrf24.available()) {

  uint8_t buf[RH_NRF24_MAX_MESSAGE_LEN];
  uint8_t len = sizeof(buf);

    if (nrf24.recv(buf, &len)) {

    String str1 = (((DataHolder*)buf))->name;
    String str2 = ((DataHolder*)buf)->skill;
    Serial.println("name :" + str1);
    Serial.println("skill :" + str2);

    }
 }
}

```

# Answer
Your problem is that you are working with pointers. You have a pointer to a block of memory with some text in it, then you take that pointer, get the address of the variable that stores it, convert it to a pointer to an 8-bit value, and send that. Which of course won't work.

Instead you need to send the *content* of the memory the pointer points to:

```
nrf24.send((uint8_t *)strm, strlen(strm));

```

`strm` is *already* a pointer, you don't need to convert it to a pointer with `&` \- that just confuses things and gives you a pointer to a pointer, which in this context is garbage.

A `struct` made up of `String` objects will not do what you think it does. A `String` object does not contain the string itself. Instead it just allocates an external block of RAM (from the *heap*) using `malloc()` and holds a pointer to that memory. If you try transferring a `struct` which contains `String` objects all you will be sending is the data associated directly with those `String` objects, including the pointer to the string content, which is completely meaningless to the remote end.

Instead you will either have to send the strings separately along with their length and some identifier to say what the string is, or rebuild the string content into a fixed size buffer.

Personally I would use a fixed size buffer. In this method you change your `struct` so it contains two character arrays with a fixed size. For instance:

```
struct DataHolder {
    char name[10]; // Room for 9 characters + NULL
    char skill[10]; // Room for 9 characters + NULL
};

```

Then copy your string data into it:

```
struct DataHolder data;

strncpy(data.name, "Fred", 10); // Maximum 10 bytes
strncpy(data.skill, "ClassA", 10); // Again, max 10 bytes.

Now you can send the struct in its entirety:

nrf24.send((uint8_t *)&data, sizeof(struct DataHolder));

```

The data sent (and indeed the data held in the Arduino's RAM) will be:

```
Fred\0\?\?\?\?\?ClassA\0\?\?\?

```

Where `\?` represents any possible character (undefined, basically, and depends on how the variable was created - if it's global it'll be all 0, if it's on the stack then it will be whatever was in that block of memory beforehand) and `\0` is the standard C end of string NULL character (ASCII 0).

For receiving it's exactly the same. Use the same struct, and go:

```
struct DataHolder data;

int len;
if (nrf24.recv((uint8_t *)&data, &len)) {
    // Do something with data.name and data.skill
}

```

Or you can use a buffer and a pointer, which may be safer since you have no chance of overrunning the buffer with a message coming in that is bigger than the data structure size:

```
struct DataHolder *data;
uint8_t buf[RH_NRF24_MAX_MESSAGE_LEN];

if (nrf24.recv(buf, &len)) {
    data = (struct DataHolder *)buf;
    // Do something with data->name and data->skill
}

```

Note the change from `.` to `->` for the struct access since it's now a pointer.

Also note that you don't want your `struct` to be any bigger than your maximum packet size. To send anything bigger you will have to chunk the data up and send it in little bits.
> 2 votes

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


# Question
Title: Help adding 3 more on/off switches so that I can control 4 LEDs
This code is working fine to switch on/off one LED. Can anyone help me add 3 more on/off buttons so that I can control 4 LEDs?

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

byte mac[] = {
  0xDE , 0xAD , 0xBE , 0xEF , 0xFE , 0xED
};
byte ip[] = {
  192 , 168 , 2 , 20
};
byte gateway[] = {
  192 , 168 , 2 , 1
};
byte subnet[] = {
  255 , 255 , 255, 0
};
EthernetServer server(80);
String richiesta;
int pinLed = 9;

void setup() {
  Ethernet.begin(mac,ip,gateway,subnet);
  pinMode(pinLed,OUTPUT);
  Serial.begin(9600);
  richiesta = "";
}

void loop() {
  EthernetClient client = server.available();
  if(client) {
    Serial.println("Tujse na ho payega");
    while(client.connected()) {
      if(client.available()) {
        char c = client.read();
        richiesta.concat(c);
        if(c == '\n') {
          Serial.print(richiesta);
          if(richiesta.indexOf("Led=1")>0) {
            Serial.println("Pin will be high");
            digitalWrite(pinLed,HIGH);
          } else {
            Serial.println("Pin will be low");
            digitalWrite(pinLed,LOW);
          }
          client.println("HTTP/1.1 200 ok");
          client.println("Content-Type: text/html");
          client.println();
          client.println("<head><title> Home Automation</title></head>");
          client.print("<body> <a href='/?Led=1'>ButtonOn </a> <a href='/?Led=0'>Buttonoff </a></body>");
          client.stop();
          richiesta = "";
        }
      }
    }
  }
}

```

# Answer
> 0 votes
The html you send must be changes to add the buttons:

```
client.print("<body> <a href='/?Led1=1'>Button1On </a> <a href='/?Led1=0'>Button1off </a>");
client.print("<a href='/?Led2=1'>Button2On </a> <a href='/?Led2=0'>Button2off </a>");
client.print("<a href='/?Led3=1'>Button3On </a> <a href='/?Led3=0'>Button3off </a>");
client.print("<a href='/?Led4=1'>Button4On </a> <a href='/?Led4=0'>Button4off </a></body>");

```

Then you need to add some ifs:

```
  if(richiesta.indexOf("Led1=1")>0) {
    Serial.println("Pin1 will be high");
    digitalWrite(pin1Led,HIGH);
  } else if(richiesta.indexOf("Led1=0")>0){
    Serial.println("Pin1 will be low");
    digitalWrite(pin1Led,LOW);
  }
  if(richiesta.indexOf("Led2=1")>0) {
    Serial.println("Pin2 will be high");
    digitalWrite(pin2Led,HIGH);
  } else if(richiesta.indexOf("Led2=0")>0){
    Serial.println("Pin2 will be low");
    digitalWrite(pin2Led,LOW);
  }
  //etc.

```

you can use arrays and loops to avoid the repeated code each time.

# Answer
> 0 votes
Use arrays, one for switches, one for leds. I don't see the code for leds in your code.

Note that you need 8 pins (4 for switches, 4 for leds).

Initialize them, e.g.

int switchPins\[\] = { 2, 3, 4, 5 };

Same for leds

```
int ledPins[] = {6, 7, 8, 9};

```

To access them, use a for loop:

```
for (int iLed = 0; iLed < 4; i++)
{
   digitalWrite(ledPins[iLed], HIGH);
}

```

Because 4 might be used a lot, consider them making const or define:

```
#define NR_OF_LEDS 4

for (int iLed = 0; iLed < NR_OF_LEDS; i++)
{
   digitalWrite(ledPins[iLed], HIGH);
}

```

or use the length of the array

```
for (int iLed = 0; iLed < sizeof(ledPins) / sizeof(int); i++)
{
   digitalWrite(ledPins[iLed], HIGH);
}

```

---
Tags: arduino-uno, programming, sketch, ethernet-shield
---


# Question
Title: A beginner lost at sea, Arduino looking at the sun
I am working on trying to make a LED strip respond to natural Light levels for a sculpture. I have reached a problem in trying to get the code to work when sending PWM to the light strip. Thank you for any suggestions!

```
const int analogInPin = A0;
const int analogOutPin = 9;

int sensorValue = 0;
int outputValue = 0;

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

void loop() {
  sensorValue = analogRead(analogInPin);
  outputValue = map(sensorValue, 0, 1023, 0, 500);
  analogWrite(analogOutPin, outputValue);
  Serial.print("sensor = ");
  Serial.print(sensorValue);
  Serial.print("\t output = ");
  Serial.println(outputValue);
  delay(2);
}

```

I am using an NTE 2908 N-channel.

# Answer
> 0 votes
You'd better post also the schematic, but I'm pretty sure you just messed up the circuit.

I think you just put the ground connection for the LED strip in the wrong pin (AREF). If you look, the top-most blue wire goes to the third pin from above in the right connector (which is AREF) instead of the fourth one (which is GND). Move this and it should work

Otherwise, put the schematic on the question

# Answer
> -1 votes
How about `pinMode (analogOutPin, OUTPUT);` ?

---
Tags: arduino-uno, led, analogwrite
---


# Question
Title: Arduino mega board 5v pin does not gives 5v when 7.5v is applied through external source
I gave 7.5v to the arduino mega board through battery. 5v pin in the board gives me the same voltage as input. Earlier it was working fine now it is giving problem.Please let me know the solution as soon as possible.

Thanks and regards, Thippeswamy

# Answer
> 1 votes
If you apply 7.5V to the power barrel jack and the 5V pin is 7.5V then your Arduino board is broken. Don't connect it to a computer. Don't use it anymore.

# Answer
> 0 votes
It is highly likely that you have destroyed your Arduino. This can happen in a number of ways. Rugged Circuits has a great article on 10 ways you can destroy the Arduino.

The giveaway is that you are measuring 7.5V on the 5V pin. Most likely the voltage regulator has blown. Page 355 of the ATMega2560 datasheet says the absolute maximum voltage for the chip is 6.0V, so this also means that the microcontroller is blown as well. It is most likely unsalvageable.

Go out and buy yourself a new one. Before you turn it on, check the wiring is correct.

We have all let the magic smoke out at some point.

---
Tags: arduino-mega, power, usb, pins, hardware
---


# Question
Title: Arduino (or clone) powered with one or two AA batteries or one CR2032, but still able to give +3.3V or +5V
Are there Arduinos (or clones) that can be **powered with one or two AA batteries or one CR2032 3V battery**? (it would sleep 99% of the day, and only send a few bytes per day)

If so, will they also have a +3.3V or even +5V output (produced by an internal step-up chip) that can be used by another chip?

(I know it might sound like having one's cake and eat it too, but maybe it exists?)

# Answer
The modern low voltage versions of a bare ATmega chip can run from either 2xAA or a lithium coin cell - you wouldn't want to use a voltage regulator, as that is not only unnecessary but introduces losses but increases the required input voltage by its `dropout` meaning your circuit will fail earlier in the discharge curve that in it would without.

Bypassing the regulator on an Arduino Mini style of board is possible. You probably do not want a board with an on-board USB-serial solution.

You'll need to make sure the clock rate is low enough for operation at the rated voltage (and for sleep efficiency). This might involve using the fuse for the internal oscillator and ignoring a crystal/resonator that might be present, though if your board was originally intended for 3.3v operation it might be okay.

You will also need to set the brownout detector to the lowest voltage or disable it entirely - this again is in the fuses.

A boost converter to a higher voltage is *possible* but may not be a good idea, especially from a coin cell. This is because to supply 1 milliamp at 5v, a boost converter must draw 2 milliamps at 2.5v - and then a bit more, to account for its own losses. If you go shopping for a boost converter to use, make sure it has an enable, look at the quiescent power consumption when disabled and enabled without load, and look at the minimum input voltage.
> 3 votes

---
Tags: power, voltage-level, battery, clones
---


# Question
Title: How do you post json data to HTTPS endpoint from ESP8266MOD?
Board: ESP8266MOD module from AI Thinker.

Using ArduinoHttpClient I am unable to send a post message to an Azure IOT Hub endpoint. The endpoint is listening on 443 and expects a shared key passed via a custom header.

The error I get is "Connection Timed Out"

Here is the brief sketch

```
char serverAddress[] = "myapp.azure-devices.net";
int port = 443;
string sig = "Azure shared access signature";
HttpClient client = HttpClient(wifiClient, serverAddress, port);
  String jsonPayload = payload; // passed into this function
  client.beginRequest();
  String contentType = "application/json";
  client.post("/devices/deviceId/messages/events?api-version=2016-02-03");
  client.sendHeader(HTTP_HEADER_CONTENT_TYPE, contentType);
  client.sendHeader("Authorization", sig);
  client.sendHeader(HTTP_HEADER_CONTENT_LENGTH, jsonPayload.length());
  client.beginBody();
  client.print(jsonPayload);
  client.endRequest();

  statusCode = client.responseStatusCode();
  response = client.responseBody();

```

The Status Code is -3 indicating a Timeout

I then created a simple REST API that accepts the JSON. Hosted it as an Azure website on port 80.

The board is able to connect to this HTTP endpoint

Question(s): 1. Is the board underpowered to handle HTTPS? 2. Is creating an HTTP proxy the only option? 3. Am I not using the right library?

Thanks

# Answer
> 2 votes
You are only making an HTTP request to an HTTPS server. It's not going to work.

AFAIK there is no direct support for HTTPS in the ESP8266 libraries, but there is support for SSL, and you can then manually create an HTTP request over that - as detailed in the HTTPSRequest.ino example.

# Answer
> 2 votes
Thanks to @Majenko I was able to find the right solution.

The resolution is here

Essentially, a secure WiFiClient needs to be created and used in the HttpClient constructor

1. Paste the HTTPS URL You are trying to connect to, in a browser window and grab the SHA1 Fingerprint of the certificate
2. Create aninstance of WifiClientSecure
3. Call Connect on WifiClientSecure passing in the HTTPS URL and Port number
4. Upon successful connection, call the Verify method of WifiClientSecure to verify the fingerprint.
5. Pass the fingerprint from setp1 and URL to this method
6. Use the WifiClientSecure instance when creating an instance of HttpClient.

Hope this helps.

---
Tags: esp8266, web-service
---


# Question
Title: Is it possible to use SPI on Redbot Mainboard?
My students use the Sparkfun RedBot Inventor's Kit for their final design projects. The documentation about this board isn't great. There are connectors to SPI pins (they are not soldered to headers, but they exist, see diagram below); however the bumpers and wheel encoders use pins 10 and 11, which are pins used in SPI communication.

My question is: is it possible to solder headers into that SPI socket and use SPI communication without interfering with the bumpers and wheel encoders (for example if my students want to hook up a 7-segment display to show the RedBot's speed)?

# Answer
> 1 votes
From the silkscreen on the board you appear to be either mistaken or already re-purposing signals - pins 10 and 11 are labeled as used for Servo position command PWM, not for sensor input.

Therefore, as long as you don't use those signals for servos (or ignore the labeling and use them for something else) there should be no issue using pins 11, 12, and 13 in the ordinary manner for SPI, by finding them in any available place on the board, including the 6-pin ISP connector your identify.

If you did need to use pins 11 and 12 for another purpose you could still "bit-bang" "software SPI" on any other available set of four pins.

It is also vaguely possible that you could share functions by connecting bumper switches through resistors - when the software is driving those signals as SPI outputs, it will dominate the resistors, but at other times it can re-purpose the pins as inputs to read the bumper switch state. However this may require modification of Arduino library code to accomplish repeated mode switching.

---
Tags: atmega328, spi
---


# Question
Title: How to control a DC motor via Arduino Uno as a slave and Mega 2560 as master?
Hi I want to control a DC motor using Arduino mega2560 and Arduino Uno as a slave. Mega have to process data from an ultrasonic sensor(measuring distance) and control the motor based on the input. I tried to google but couldn't find a better tutorial or code. I'm using Adafruit motor shield l293d. I have the idea about the wiring part just need a simple code.

```
Eg:

 if( distance < 20) {
   //send signal to slave to run the motor forward
 }else {
   //send signal to slave to stop the motor
 }

```

# Answer
Serial is quite easy to implement and use the `SoftSerial`.

Example code for serial can be found in the Arduino IDE under the menu:

```
File | Examples | 04. Communication

```
> 1 votes

---
Tags: arduino-uno, arduino-mega, motor
---


title: Frequency will not change

text:
# Question
Title: Frequency will not change
I am working on a project where I am trying to get an input signal filtered according to its frequency. I checked the signal before it went into my DSP algorithm to see where the problem was and I found that the frequency was remaining the same no matter if I put in 30Hz 120Hz or 58kHz. This leads me to think I have a problem with the sampling rate. Does that sound like it is the actual issue? Or am I barking up the wrong tree?

I was just using the readADC command to read in the data

```
void setup()          //Setup Function to intialise ADC and Serial Communication
{
DDRC=0x00;            //PORTC as INPUT
DDRD=0xFF;            //PORTD is OUTPUT
DDRD=0xFF;
for(i=0;i<N;i++)
  {
    InitADC();
    a=ReadADC(4);
    x[i]=a;
  }
  Serial.begin(9600);
}

```

# Answer
I am not sure how you are sampling the frequency because you have not shown us your code.

At work we use a ATMega328P to sample frequency. This is done in 2 different ways:

1. We use the pin that counts (using an internal counter) every time it transitions (ie from low to high and from high to low). After 1 second that counter is read and then that counter is cleared. With the number read in, it is divided by 2 to get the frequency.
2. We use another pin that counts every time it transitions from low to high. From memory the counter is not very large so we count the number of times it overflows. When the 1 second interrupt fires we multiply out the number of overflows by the counters capacity. Lastly the remainder from the counter is added to the result to get the frequency. Again the counter is cleared.

The above examples use the AVR's internal counters. A less efficient way of getting the frequency is to have an interrupt to count the number of times a pin changes. Again this can be read and reset at one second intervals. This slows the overall execution of the program down when very high frequencies ( \> 40K Hz) are being presented on the input.
> 1 votes

---
Tags: arduino-uno, signal-processing
---


# Question
Title: How do you make an Arduino count down timer?
I want to make a countdown timer with a LilyPad Arduino for 3 seconds with red (1 second), then orange(1 second), then yellow (1 second), then green (3 seconds), all being triggered by a button. I want to check to see if I have the right code. I am a self taught programmer, so apologies if this is a little messy. (or a lot)

```
#include <Adafruit_NeoPixel.h>
const int inputPin = 3;

void setup() {
  // put your setup code here, to run once:
  pinMode(inputPin, INPUT_PULLUP);
  strip.begin();
  strip.show();
}

void loop() {
  // put your main code here, to run repeatedly:
  If (digitalRead (inputPin) == LOW) {
    For (int i = 0; i < 12; I++) {
      Int pixelNum1 = 1;
      strip.setPixelColor( pixelNum1, 244, 0, 0);
      strip.show();
      delay (27);
      pixelNum1 ++;
    }

    For (int i = 0; i < 24; I++) {
      Int pixelNum2 = 1;
      strip.setPixelColor( pixelNum, 247, 247, 0)
      strip.show();
      delay (27);
      pixelNum ++;
    }

    For (int i = 0; i < 12; I++) {
      Int pixelNum3 = 1;
      strip.setPixelColor( pixelNum, 0, 247, 41)
      strip.show();
      delay (27);
      pixelNum ++;
    }
  }
}

```

# Answer
> 1 votes
```
For (int i = 0; i < 12; I++) {
      Int pixelNum1 = 1;
      strip.setPixelColor( pixelNum1, 244, 0, 0);
      strip.show();
      delay (27);
      pixelNum1 ++;
    }

```

Assuming you fix the upper-case lower-case issues here first, you've still got a scope issue. Since pixelNum1 is defined inside the for loop, it will go out of scope at the end of the for loop. So it will be 1 on every iteration and it won't increment like you seem to think it will.

Why don't you just get rid of it altogether and use i+1 instead?

# Answer
> 1 votes
In addition to what has already been said, I would add these two recommendations:

1. Do not repeat yourself. If you are repeating the same code, only with different data, then put that data into an array and loop through it.
2. Define all your constants at the beginning, instead of having them as “magic numbers” within the code itself.

Note that those are only good programming practices. They are not critical for the functioning of your code, but they make it easier to read and to maintain.

Applying those recommendations, here is my throw at this. Note that the `Color` struct is only meant to make it easier to define colors as constants:

```
#include <Adafruit_NeoPixel.h>

struct Color {
    uint8_t r, g, b;
};

const uint8_t  INPUT_PIN  =  3;
const uint8_t  STRIP_PIN  =  6;
const int      LED_COUNT  = 12;
const uint32_t LED_DELAY  = 27;
const int      NUM_COLORS =  4;
const Color    COLORS[NUM_COLORS] = {
                   {244,   0,  0},  // red
                   {247, 122,  0},  // orange
                   {247, 247,  0},  // yellow
                   {  0, 247, 41}   // green
               };

Adafruit_NeoPixel strip(LED_COUNT, STRIP_PIN);

void setup()
{
    pinMode(INPUT_PIN, INPUT_PULLUP);
    strip.begin();
    strip.show();
}

void loop()
{
    // Nothing to do until the button is pressed.
    if (digitalRead(INPUT_PIN) == HIGH)
        return;

    // Cycle through the colors.
    for (int i = 0; i < NUM_COLORS; i++) {
        Color color = COLORS[i];
        for (int led = 0; led < LED_COUNT; led++) {
            strip.setPixelColor(led, color.r, color.g, color.b);
            strip.show();
            delay(LED_DELAY);
        }
    }

    // Switch off.
    strip.clear();
    strip.show();
}

```

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


title: Arduino Laser Trip Wire with Analytics

text:
# Question
Title: Arduino Laser Trip Wire with Analytics
I've done this laser trip wire: http://www.instructables.com/id/Another-Arduino-Laser-Tripwire/

Got it working, and now I'd like to send info to analytics - to measure how many times I enter the kitchen...

I tried to take bits of code and add it to my code from: http://bigsnarf.wordpress.com/2013/12/24/arduino-sensor-python-and-google-analytics/ and one more which I can't post due to permissions....

but neither will work and adding this code breaks my basic functionality (I know as I measure it via the buzzer, it stops responding once I add this new code...

Is there anyone able to help?

---

Here is my basic working code for the laser trip wire that makes buzzer noise if someone walks through it:

```
/*
Jonathan Robson Feb 09.
Laser tripwire activates a buzzer. adapted from
http://www.instructables.com/id/Arduino_Laser_Tripwire/
*/

int buzzPin = 11; // buzzer connected to digital pin 11

void setup() {
  pinMode(buzzPin, OUTPUT); // sets the digital pin as output
}

void loop(){
  if(analogRead(0) < 850){ // this number depends on calibration of the photocell
    digitalWrite(buzzPin, HIGH); // turns buzzer on
    delay(1000); // waits for 1 second
    digitalWrite(buzzPin, LOW); // turns buzzer off
  } else{
    digitalWrite(buzzPin, LOW);
  }
}

```

Here is the code with analytics additions I’ve added:

```
/*
Jonathan Robson Feb 09.
Laser tripwire activates a buzzer. adapted from
http://www.instructables.com/id/Arduino_Laser_Tripwire/
*/
#include <SPI.h>
#include <Ethernet.h>

byte mac[]     = {  0x0C, 0xD2, 0x92, 0xAC, 0x75, 0x0B };

// To skip the DNS
IPAddress server(173,194,40,97); // www.google-analytics.com => 173.194.40.97
EthernetClient client;

int buzzPin = 11; // buzzer connected to digital pin 11

// Global switch (debug mode without API call)
boolean netword_enabled = true;

int sendEventToGA() {
  int responseCode      = 0;

  if (!netword_enabled) {
    return responseCode;
  }

  // open the connection
  if (client.connect(server, 80)) {
    int responseSize      = 0;
    int responseSizeMax   = 1024;
    char response[1024];
    String eventData = "v=1&tid=UA-51525058-1&cid=123&t=event&ec=home%20movement&ea=door%20open&el=bedroom"; // Refer to the Google documentation

    Serial.println("Connection opened!");

    // Write the HTTP request to the Client
    client.println("POST /collect HTTP/1.1");
    client.println("Host: www.google-analytics.com");
    client.print("Content-Length: ");
    client.println(eventData.length());
    client.println("Content-Type:application/x-www-form-urlencoded");
    client.println();
    client.println(eventData);

    Serial.println("Request sent.");

    // Wait a little bit
    delay(1000);

    // Read the response, looking for the Response Code.
    while (client.available() && client.connected() && responseCode < 100 && responseSize < responseSizeMax) {

      response[responseSize] = client.read();
      responseSize++;
      response[responseSize] = '\0'; // Set manualy the end of string char

      // Here is the magic!
      sscanf (response, "HTTP/1.%*d %d", &responseCode);

      Serial.print("HTTP code ");
      Serial.print(responseCode);
      Serial.print(" founded in ");
      Serial.println(response);
    }
  }

  Serial.println("End of communications.");

  client.stop();
  return responseCode;
}

void setup() {
  pinMode(buzzPin, OUTPUT); // sets the digital pin as output
  Serial.begin(9600);

  // start the Ethernet connection
  if (netword_enabled && Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");

    // no point in carrying on, so do nothing forevermore:
    for(;;)
      ;
  }

  // give the Ethernet shield a second to initialize:
  delay(1000);
}

void loop(){
  int responseCode;
  if(analogRead(0) < 850){ // this number depends on calibration of the photocell
    digitalWrite(buzzPin, HIGH); // turns buzzer on
    responseCode = sendEventToGA();
    delay(1000); // waits for 1 second
    digitalWrite(buzzPin, LOW); // turns buzzer off
  } else{
    digitalWrite(buzzPin, LOW);
  }
}

```

# Answer
> 1 votes
As with any piece of code that doesn't work, it is very easy to troubleshoot using the `Serial.println()` statement.

The big clue here is that the buzzer turns on but never turns off. Go ahead and add unique `Serial.println()` statements between each statement in the `loop()` function.

My guess is that the `digitalWrite(buzzPin, HIGH)` executes but it never exits the `sendEventToGA()` function.

If this is the case, then go ahead and add unique `Serial.println()` statements in between each line of the `sendEventToGA()` code.

Again, my guess is that the code goes into the `while()` statement and never comes out. This while statement is waiting for a response from the server. If you never get a response it won't exit.

Perhaps add a timeout or determine why Google Analytics isn't returning a response.

Help on the topic can be found at the Arduino Libraries reference pages:

---
Tags: arduino-uno
---


# Question
Title: How to connect mini jack output to arduino mini pro and send sound to it?
I would like to connect arduino mini pro to mini jack output and send sound through it.

What would I need here, how can I connect the mini jack to arduino and how to send data of sounds (any library?) to that connected output?

**EDIT**

The sound source will be a music file ( streamed via bluetooth). I would like to be able to connect this output to a speaker and play (stream) music via bluetooth.

**EDIT**

Either mono or stereo will be good for me. My plan is to: stream the music via bluetooth to bluetooth module (for now I think about HC-06), send that data stream through arduino mini pro to the output mini jack.

Do I need in that case some kind of mp3/other format decoder module like VS1003B on ebay ?

# Answer
> 1 votes
The Arduino Uno / Mini Pro is not really the right tool for the job. It has no native audio output such as a 3.5mm jack.

Having said that I am sure it can be done - but it won't be the best quality sound. I have no doubt that it can be achieved with one of the following methods:

The Arduino Due and the Arduino M0 / M0 Pro both have inbuilt DAC's, meaning that they can output analog signals which can be used to drive a speaker circuit.

Another option is to use a Raspberry Pi which has a native 3.5mm audio jack.

---
Tags: bluetooth, audio
---


# Question
Title: Getting no such directory file error when compiling
I recently got my wifi module and connected it to my Uno. I am now trying to send a http request. I have the code that comes with the esp8266wifi library in which it demonstrates and gives an example on how to send a http request. This is the code:

CODE.

I am getting the following error

```
    Arduino: 1.8.4 (Windows 8.1), Board: "Arduino/Genuino Uno"

In file included from C:\Users\Yasmeen\Documents\Arduino\libraries\ESP8266WiFi\src/ESP8266WiFi.h:33:0,

                 from C:\Users\Yasmeen\AppData\Local\Temp\arduino_modified_sketch_200757\HTTPSRequest.ino:14:

C:\Users\Yasmeen\Documents\Arduino\libraries\ESP8266WiFi\src/ESP8266WiFiType.h:26:19: fatal error: queue.h: No such file or directory

 #include <queue.h>

                   ^

compilation terminated.

exit status 1
Error compiling for board Arduino/Genuino Uno.

```

Obviously it seems to be an file path error but I'm not sure why. I've imported the library through the Arduino IDE.. But maybe the way I aquired the library was wrong? What I did was download the esp8266wifi folder (here) and zipped the file and imported it.. is that okay to do?

# Answer
> 3 votes
The ESP8266WiFi library is for programming the ESP8266 directly. You are trying to compile source code for the ESP8266 for the Arduino UNO, that obviously won't work.

A Beginner's Guide to the ESP8266

---
Tags: arduino-uno, arduino-mega
---


# Question
Title: How to setup an I2C bus which stays valid if a slave is powered down or fails?
I have setup an I2C bus between 3 Arduinos (Master, Slave1 and Slave2) by connecting all 3 A4 pins together, all 3 A5 pins together and one GND pin of each Arduino to a common ground line. The 3 Arduinos are currently being powered by independent USB power supplies, but I intend to power all of them from one single power supply using their Vin pins.

The slaves use the Wire library: Slave1 is at address 0x07 and Slave2 at 0x08. The Master uses the I2C library by Wayne Truchsess, because this library has timeout functionality. Master polls Slave1 and 100 ms later, polls Slave2. If either Slave is unavailable, Master should still read the other Slave (this is why Master doesn't work with the Wire library).

However, even though Master doesn't get locked-up, it can't read one Slave if the other gets powered down but left connected. If I cut the power of Slave1, Master becomes unable to read data from Slave2 until I physically disconnect Slave1. If I disconnect Slave1, Master is immediately able to read from Slave2 again. I2C scanning suggests the whole bus becomes invalid when a Slave is powered down (SCL and/or SDA turned low?).

From what I have been reading, this is not a software issue but an electronics circuitry problem: leaking current related to Slave1 and Slave2 having some diodes, something that perhaps could be solved with some transistors or N-FETs which would act like check-valves? Please advise.

P.S.: I have very little background in electronics and English is not my first language.

# Answer
> 2 votes
> From what I have been reading, this is not a software issue but an electronics circuitry problem: leaking current related to Slave1 and Slave2 having some diodes, something that perhaps could be solved with some transistors or N-FETs which would act like check-valves? Please advise.

A nice solution to this problem is to use I2C Bus Isolation with TI TCA4311A Hot Swappable 2-Wire Bus Buffers alt. Analog Devices ADUM1250.

Please see the EEVblog Electronics Community Forum for further details and discussion.

Cheers!

# Answer
> 2 votes
> The 3 Arduinos are currently being powered by independent USB power supplies, but I intend to power all of them from one single power supply using their Vin pins.

I think your problem here is that if you power down one Arduino, it isn't really powered down, because it will get "parasitic power" from the I2C line, particularly from the pull-up resistors which should be there. The protection diodes (internal to the processor) will allow power to flow from the A4 and A5 pins to the Vcc pin of the chip, which will then power up, probably in some sort of indeterminate state.

Since you are planning to power them from the same supply anyway, your problem should simply go away when you do that. Connecting a device with active inputs to a circuit (ie. a voltage present) when the device itself is not powered up, is not recommended. Exceptions would be devices that are specifically designed to handle that, for example, commercially produced printers via their USB input.

# Answer
> 0 votes
An I2C bus should use open drain lines or open collector drivers AND there should be only 1 (one) pull up resistor for each of the 2 I2C wires. In this way, should a slave fail, it will not effect the I2C bus.

An Arduino does not truly have an open collector driven pin. Instead people have been clever and either set the pin connected to an I2C line low pulling the I2C bus low or as an input allowing the I2C bus to float high through the pull up resistor. In this way multiple I2C devices (Arduino or not) can share the bus.

However, if you power down an Arduino, it can no longer operate in this manner. In fact it will likely appear as a load or path to ground and effect the normal operation of the I2C bus.

In the end, I2C is designed for chips (usually) on the same board so that they can talk with one another. It would follow that they are all powered off the same supply. It is an unlikely scenario for power to fail for only one device on the board.

Alternatives:

There are protocols designed to go between devices (as in separately located and separately powered). RS485 is one such protocol and has been around for years. A quick search show both sheilds made specifically for Arduinos as well as tutorials using generic RS485 interfaces.

# Answer
> 0 votes
Mikael has the correct answer above.

I had this same issue when using two Megas communicating over I2C, along with other items running on the I2C bus. I needed the system to continue running if one Mega went down due to loss of power. The other Mega should detect it and execute some abort commands for my mission.

Initially I wired the Megas up on the same I2C bus, just as I would any other device. When I unplugged one Mega, the other would freeze the next time it tried to address another device on the bus.

The solution was to use a hot-swappable I2C buffer. I used this one, and everything worked immediately without issue after wiring it up: http://www.mouser.com/search/ProductDetail.aspx?r=595-TCA4311ADR

To integrate the SOIC-8 package onto a standard DIP breadboard for Arduinos, I used an adapter from Adafruit.

Cheers and good luck

Chris

High Altitude Photography Platform 360 video from a jet-stabilized platform at the edge of space http://hialtphoto.blogspot.com

Facebook @hialtphoto

---
Tags: i2c
---


title: Floating-point without FPU

text:
# Question
Title: Floating-point without FPU
Since a Floating Point Unit (FPU) is not present in Arduino Uno, I wanted to know how float operations are performed. If it is simulated as integer operations, I want to know how exactly the simulation is done.

# Answer
> 4 votes
As I said in my comment, all float operations are implemented in software. As a simple test, I compiled the following program:

```
volatile float x, y, z;

int main(void)
{
    z = x + y;
    return 0;
}

```

The compiler translated the sum operation into a call to `__addsf3`. This function extends its arguments to `flt40_t` format (non-standard 40 bits float), calls `__addsf3x` to do the 40-bit addition, then calls `__fp_round` to convert the result into the standard `float` format. `__addsf3x` also makes a few library calls of its own. In the end, the addition pulled the following functions into the compiled program: `__subsf3`, `__addsf3`, `__addsf3x`, `__fp_inf`, `__fp_nan`, `__fp_pscA`, `__fp_pscB`, `__fp_round`, `__fp_split3`, `__fp_splitA`, `__fp_zero` and `__fp_szero`.

All these functions are provided by the avr-libc. You can find them in the libm/fplib directory. See for example the files:

# Answer
> 1 votes
software emulation. The float is decomposed into sign, exponent and mantissa and then integer operations are used to do the actual math.

Addition and subtraction means shifting the mantissas to a common magnitude, adding/subtracting them and then checking the highest set bit for the new exponent.

Multiplication means adding the exponents and multiplying the mantissas. Division is subtracting.

---
Tags: arduino-uno, float
---


# Question
Title: Analog pins as output by using digitalWrite
I am making a triac-controlled light dimmer. To control the triac I want to use pins A4 or A5, because others are occupied. I have tried the following functions and methods, but nothing seems to put the pins to HIGH state:

```
 1. pinMode(A4, OUTPUT);
    digitalWrite(A4, HIGH);
 2. pinMode(18,OUTPUT);
    digitalWrite(18,HIGH);
 3. DDRC |= (1 << DDC4);
    PORTC |= (1 << PC4);

```

I have tried the same things with A5 and other A# pins to no avail. The only pin that works is A0. Only when the triac is connected to it, the lamp lights on.

Is this a valid way to set analog pins?

```
void setup(){
  pinMode(A4, OUTPUT);
}

void loop(){
  digitalWrite(A4, HIGH);
}

```
* Edit: My code was quite messy, it appears that some other functions prevented from using pins A4 or A5. It is working now.
* It was the DS1307Emulator library. After initialization I had to use `DS1307Emulator.busDisconnect();` Didn't know it uses I2C.

# Answer
> 0 votes
My code was quite messy, it appears that some other functions prevented from using pins A4 or A5. It is working now. It was the DS1307Emulator library. After initialization I had to use DS1307Emulator.busDisconnect(); Didn't know it uses I2C.

---
Tags: atmega328, digitalwrite
---


title: Recognize Morse-like code words

text:
# Question
Title: Recognize Morse-like code words
In a line there're voltage levels representing words of dots and dashes. In particular, the device is intended to raise an output each time a given pattern of five short/long signals (say 1s and 2s durations, respectively) is recognized (and restart if nothing comes in for a given time). A sort of Morse code recognizer (Arduino Uno preferred, but others are also OK) would be a good starting point. Any hint is welcome, I'm new in this community.

# Answer
> 1 votes
Use a GPIO of an Arduino and check (at the speed you need) the HIGH/LOW state.

Depending on the speed at which is sent, you can check the dots and dashes being sent, e.g. by keeping a timer since the last change checking if it is a short or long 'HIGH'.

You have to sample often enough to check if there is a drop (between dots/dashes).

---
Tags: arduino-uno
---


title: Operating system on Atmel 328 Arduino?

text:
# Question
Title: Operating system on Atmel 328 Arduino?
Is it possible to use some sort of multitasking OS like ScmRTOS on Arduino based on Atmel 328 chip?

# Answer
You can use FreeRTOS on the AVR family:
> 2 votes

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


title: Is there a way to shift through sensors

text:
# Question
Title: Is there a way to shift through sensors
We are doing a project and have to use around 25 temperature sensors. Is there a way to shift through them on one Arduino similar to using a shift-register?

It is a set of analog sensors in a fridge.

# Answer
As I mentioned in the comments, one way to do this is to use a multiplexer.

You haven't said which temperature sensors you are planning to use, so I'll illustrate this example using the TMP36 Analogue temperature sensor.

Now, if you were using just one of these, the connection would be trivial:

But you want more sensors than available pins. That's where the multiplexer comes in.

I'm going to illustrate this using 16 sensors and the Sparkfun 16-channel multiplexer breakout board which is based on the 74HC4067 multiplexer. For 25 sensors, you could use a 32-channel multiplexer (like the Analogue Devices ADG732, for example), or just combine two 16-channel multiplexers (which is probably cheaper, but requires a little more care in the wiring).

\[If your soldering skills are OK, I wouldn't even bother with the Sparkfun breakout board myself. It's pretty simple to connect something like this on protoboard, or make your own PCB.\]

The 16 sensors are connected to pins Y0 - Y15 on the 74HC4067 (pins C0 - C15 on the Sparkfun board). **Take care** to note which sensor is connected to which pin!

With 16 inputs, we need 4 bits to address them. The address pins are labelled S0 - S3. The Sparkfun datasheet for their breakout board includes a Truth Table mapping the addresses to the inputs:

The input from the selected device becomes the output from the multiplexer (pin Z on the 74HC4067; the SIG pin on the Sparkfun breakout board).

The diagram below shows one way of connecting 16 TMP36 analogue temperature sensors to an Arduino Nano using the Sparkfun breakout board:

Note the mapping chosen for the address pins:

* D5 -\> S0
* D4 -\> S1
* D3 -\> S2
* D2 -\> S3

This makes the drawing layout simpler, but may not be the most intuitive mapping when you come to write your code. My advice is to assign meaningful labels to the pin-mappings in your code, **and document that decision with comments!** (I'm sure that I'm probably preaching to the choir here, but this may help someone reading this in the future to avoid some of the pitfalls.)

Now, you cycle through a loop:

```
while true {
    increment the address to be written to pins D5-D2 (note the order)
    read the input on A0
    <do whatever you need to do with the temperature reading>
}

```

And Robert is the male relative of your choice.
> 5 votes

# Answer
Have you looked at OneWire temperature sensors? You connect them to a bus IC and the bus IC to your Mcu. This allows you to multiplex many sensors.

You can also forego the master bus IC and just bit bang using a GPIO pin. The Arduino OneWire library uses this approach.

You can learn a lot about from this one wire sensors tutorial.
> 4 votes

# Answer
Another way to do this is with a series of actual shift registers (74HC595 or similar, daisy-chained.)

The shift register outputs drive a transistor. Each transistor has its collector connected to the temperature sensor, and the emitters are all collected into a single Arduino input. Depending on the number you shift into the shift register, you can pick any of the temperature sensors you want to query.

The LED in this simplified schematic actually represents the Arduino input pin. Shift a 2 into the register to query T1; 4 to query T2; 8 to query T3, and so on.
> 2 votes

# Answer
If you are using analog sensors, consider using the CD4051B analog multiplexer (link to data sheet). It's great for expanding analog I/O pins.
> 2 votes

---
Tags: arduino-nano, temperature-sensor, shift-register
---


# Question
Title: Is it possible to recover an Arduino if it does not wake up after putting it to sleep
I have an ATTiny85 controlling the power to a number of devices. When I first power on it will power the devices via a mosfet. Take the readings it needs to and then puts itself to sleep for 15 minutes then wake up and repeat.

My question is, because I am using the Watchdog timer to put it to sleep, I can't use the reset functionality of the watchdog (ie wdt\_Reset). So is there anyway to detect a lock or hang if the ATTiny85 never wakes up for some reason or would I need additional hardware to check for this. If so what kind of circuit would I need.

Thanks

# Answer
> So is there anyway to detect a lock or hang if the ATTiny85 never wakes up for some reason or would I need additional hardware to check for this. If so what kind of circuit would I need.

The whole point of the watchdog timer is to wake (or reset) the chip after a certain (short) time. You don't really need a second watchdog timer to wake the processor if the first one fails.

I made a temperature and humidity sensor which is battery powered, and which uses the watchdog timer to wake it and take readings (which sounds like what you are doing). It has been running for a number of years now (over four) and it has never "hung".
> 1 votes

# Answer
Not sure what you mean by "using the watchdog to put it to sleep". You can sleep with or without the watchdog enabled, and you can even use the watchdog to both wake you with an interrupt and also reset in case of a lockup. Check out section 8.5.2 in the datasheet...

> If WDE is set, WDIE is automatically cleared by hardware when a time-out occurs. This is useful for keeping the Watchdog Reset security while using the interrupt. After the WDIE bit is cleared, the next time-out will generate a reset. To avoid the Watchdog Reset, WDIE must be set after each interrupt.
> 2 votes

---
Tags: arduino-uno, attiny, sleep
---


# Question
Title: What sensor is used to judge transparency?
I want to create a system to separate between an aluminum can and a plastic bottle.

Both are lightweight, so I'm thinking of using the transparency property, meaning that the can is not transparent, but the plastic bottle is.

Will the light sensor work out?

Or would you suggest me another type of sensor I should use?

# Answer
A light sensor should work. Another option would be an inductive Sensor to detect the Aluminium Can. And if you need to know if there is a Can in your sensor area you can combine it with an IR (or capacitive) Sensor, which should detect both Can types.

So it would be something like this:

```
if(IRdetect == true){
  if(inductive == true){
    type = alu;
  }else{
    type = plastic;
  }
}else{
  // no Can
}

```

Some cheap sensors as Example:
> 1 votes

# Answer
A light sensor should work. If the aluminium can reflect much light, you can consider putting the light and light sensor on the same side, close together.

If not, put the light and light sensor of opposite sides so the light beam goes through the bottle.
> 0 votes

---
Tags: arduino-uno, sensors
---


title: Attach Interrupt problem

text:
# Question
Title: Attach Interrupt problem
I'm just learning how to use the Arduino Uno and I'm trying to control the speed of an AC fan. I made a sketch of this project on proteus but the triac seems not to be responding. I guess there's a problem with the attachInterrupt part of the code. Here's the code:

```
#define triacPulse 5
#define interruptPin 2

//button event
#define button1 6

void setup() {
  // put your setup code here, to run once:
  pinMode(button1, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(button1==HIGH){
    attachInterrupt(0, triacControl, FALLING);
  }
}

void triacControl()
{
  delay(5);   //delay for 5 milliseconds
  digitalWrite(triacPulse, HIGH);
  delay(5);

  digitalWrite(triacPulse, LOW);
}

```

Thanks for the answer in advance

# Answer
First of all your if statement will always be false. You ask if 6 equals 1 (from arduino.h). It schould be `digitalRead(button1) == HIGH`. Also it looks like your button should start an impulse of 5ms. Am I right? In this case you will attach the Interrupt to the Button. Also don't put delays in the Interrupt function. Another thing, that isn't important in small Projects only for you, is to increase the readability by typing "define constants" uppercase, so you know where to find them and that they aren't changeable variables (For this reason HIGH, LOW, INPUT, RISING, ... are all uppercase).

All in all the code should be look like this:

```
#define BUTTON1PIN          6
#define TRIACPIN            5
#define TRIACPULSE          5                       // [ms]

bool doPulse = false;
long triacStartTime = 0;

void setup(){
  pinMode(BUTTON1PIN, INPUT);
  pinMode(TRIACPIN, OUTPUT);
  attachInterrupt(BUTTON1PIN, pulseISR, RISING);    // attach a Interrupt once!
                                                    // pulseISR is called everytime the button is pressed
                                                    // ISR: Interrupt service Routine (only for Readability)
}

void loop(){
  if(doPulse){
    digitalWrite(TRIACPIN, HIGH);
    triacStartTime = millis();
    doPulse = false;
  }
  if(millis() > triacStartTime + TRIACPULSE){        // Shut down after 5 ms
    digitalWrite(TRIACPIN, LOW);
  }
}

void pulseISR(){
  doPulse = true;                                    // NO delays in ISR! And as short as possible
}

```
> 2 votes

---
Tags: interrupt
---


# Question
Title: Will I be able send a HTTP request using the Arduino Yún?
After spending countless hours trying to get my wifi module to work only to fail, I've decided I might as well get an Arduino with built-in wifi.

Would I be able to send HTTP requests (GET, POST etc) straight out of the box or would I have to configure and connect some additional components/modules to the board?

Also, I plan on connecting a thermistor and a GPS module to the Arduino. When the thermistor reaches a certain level, it sends the GPS coordinates of my server. Is this possible in terms of practicality and voltage? And would I be able to write a sketch using the Arduino board or would I have to switch the board to something like 'Generic ESP8266 Module' (something we have to do if we want to program the ESP8266 using the Arduino IDE).

# Answer
> 1 votes
Looking at your other two questions as well I see you have had limited success with a ESP8266. I have never used a Yun, but I haven't seen much good stuff about them on here. If you want a Linux based none real time system then you may as well get a PI.

Most people seem to think the way to use an ESP8266 is to hook it up to an Arduino and use it as a 'serial over wifi' link. You can do that, but its like owning a Porsche and Kia and always using the Kia on Motorway journeys. The ESP8266 is an 80MHz chip with 0.5 MByte of RAM, and you could program it in just the same way as an Arduino if you download the board support package. It does have only 10 Digital pins and 1 Analog (which I think has lower resolution that the Arduino), but that's where the Arduino comes in. If you need to hook up lots of pins, then stick the Arduino on the I2C bus as a slave to the ESP.

Now I suspect you have an ESP-01 board and are wondering what the \[heck\] I am talking about, 10 pins. The number '01' is the number of GPIO pins that are taken to the edge of the board, so really you want to look at ESP-12E or ESP-13E boards (they still cost about the same $1). You might want to look at a Wemos D1 or a Node MCU. Both are fully fledge dev boards, jus plug in the USB and away you go.

So to answer your question:

Get a Wemos D1, hook the hardware up like you wood the Arduino (thermistor and GPS - via SoftwareSerial) and then either code a web server to run on the Wemos or Get it to Post message to you favourite server (see examples for details of either approach)

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


title: Power source for arduino project

text:
# Question
Title: Power source for arduino project
The project is to make a 4WD car using arduino uno(clone) and four toy dc motors. I am using a adafruit motor shield v1.2(clone). The car is required to run autonomously, please suggest batteries for the arduino and the shield. Also when I am using external power connector for arduino, all the motors start at different timing.

# Answer
I've been using usb power packs.

* Easy to source (can be found in all electronics stores and many general stores).
* Come in many sizes (500mAh to 20,000 mAh are common).
* Rechargable, usually by using a generic phone changer with a usb micro connector.
* Not costly.
* Quite roubust.
* Most Arduino boards and many motor driver boards are designed to be powered from usb.

Make sure you get one that is rated for enough current for your project.
> 4 votes

# Answer
Car batteries are wonderful, and almost never explode. A badly mistreated Li-{Fe,Po,Ion}, however... ouch. Otherwise use banks of NiMh/NiCd.

If you don’t fear death, use Li-Ion batteries with a TP4056 + DW01A IC, it can handle charging from USB, and provides over-discharge protection, so your batteries don’t die. https://www.addicore.com/TP4056-Charger-and-Protection-Module-p/ad310.htm It also has current limiting built-in.
> 1 votes

---
Tags: power
---


# Question
Title: How To Communicate Three NodeMcu In Access Point Mode
I'm working on project which for example 3 nodemcu connected with eachother in a line(1 connected to 2 and 2 connected to 3) and they are all in access-point mode (they are all server) and now my problem is how to communicate between 1 to 2 and 2 to 3 i have tried tcp but its for server-client

any help would be appreciated

# Answer
> 0 votes
Look at the WiFi library. The function WiFi.mode() can set your NodeMCU as access point, station or both access point and station (WIFI\_AP, WIFI\_STA, WIFI\_AP\_STA or WIFI\_OFF).

In the mode WIFI\_AP\_STA, your NodeMCU works both as access point and as a station independently; no need for special considerations.

You still need to know the IP address of each NodeMCU to make them to talk to each other. You can configure things to get fixed IP for each NodeMCU as a station.

---
Tags: esp8266, wifi, communication, nodemcu
---


title: HC-SR04 calibration conditions

text:
# Question
Title: HC-SR04 calibration conditions
As is known, the speed of sound depends of temperature and Relative Humidity. I'm trying to calibrate HC-SR04 sensor taking account these factors.

In SparkFun page there is no mention about environmental conditions in calibration (only is informed that speed of sound is 340 m/s). I found a paper with some calibration, but again it is no mention of original conditions.

I'm using the time elapsed per response to calculate distance in Arduino with access to a temperature & humidity chamber, so I want to recreate the calibration conditions to probe if the sensor is accurate.

Anyone know the environmental conditions of HC-SR04 calibration?

# Answer
The HC-SR04 is not calibrated, nor does it take any measurements.

All it does is allow *software* on a connected microcontroller or system like an Arduino to measure the sum of the round trip time delay and some small internal offset delay, and from this calculate distance.

As the timing and calculation are entirely in *your* program, calibration is entirely up to you.

Under known conditions you could measure both a short and a long distance. This would give you a slope and intercept - the slope from the speed of sound (which should not depend on the device at all, only on the conditions and your timing reference), and the intercept or offset, having to do with latencies in the system.

You could then cross-check at other distances, but under fixed conditions behavior should be linear.

As there is some initial ringing of the sender which can couple to the receiver and be mistaken for an echo, there will be a minimum distance below which you cannot reliably take a reading - as a guess, this is more than 5 cm, but you'll have to see, and it may even vary a little from unit to unit.

*To a degree, it's a little bit amazing that these even work. They use an RS232 level shifter to generate transmit pulses, and it's been alleged that the receive circuit is horribly mistuned, not really matching the emitted frequency at all... but despite that they do seem to work fairly well*.
> 3 votes

---
Tags: sensors, calibration
---


title: Need help with my urgent problem

text:
# Question
Title: Need help with my urgent problem
Today I found a problem in my project, here is the video of problem

https://streamable.com/wamm9

code MASTER : https://www.dropbox.com/s/l4x3zwzv6szrs50/MASTER.ino?dl=0

```
#include <Wire.h>

const int BUTTON1 = 5;
const int BUTTON2 = 6;
int buttonchoose;

void setup() {
  // put your setup code here, to run once:
  pinMode(BUTTON1, INPUT);
  pinMode(BUTTON2, INPUT);
  Wire.begin();
  Serial.begin(9600);
}

void loop() {
  Serial.println("You want turn X motor");
  Serial.println("1-YES  2-NO");
  buttonchoose = fonctioninput();
  delay(500);
  if (buttonchoose == 1) {
    //Turn motor x for onerevolution
    Wire.beginTransmission(8); // transmit to device #8
    Wire.write('X'); // send M (milk)
    Wire.endTransmission();    // stop transmitting
    Serial.println("send X");
  }
  Serial.println("You want turn Y motor");
  Serial.println("1-YES  2-NO");
  buttonchoose = fonctioninput();
  delay(500);
  if (buttonchoose == 1) {
    //Turn motor Y for onerevolution
    Wire.beginTransmission(8); // transmit to device #8
    Wire.write('Y'); // send M (milk)
    Wire.endTransmission();    // stop transmitting
    Serial.println("send Y");
  }

  Serial.println("You want turn Z motor");
  Serial.println("1-YES  2-NO");
  buttonchoose = fonctioninput();
  delay(500);
  if (buttonchoose == 1) {
    //Turn motor Z for onerevolution
    Wire.beginTransmission(8); // transmit to device #8
    Wire.write('Z'); // send M (milk)
    Wire.endTransmission();    // stop transmitting
    Serial.println("send Z");
  }
}

int fonctioninput() {
  int val1 = 0;
  int val2 = 0;
  int buttonreturn = 0;
  while ( (val1 - val2) == 0) {
    val1 = digitalRead(BUTTON1);
    val2 = digitalRead(BUTTON2);
  }

  if (val1 == 1) {
    buttonreturn = 1;
  }
  else {
    buttonreturn = 2;
  }
  return buttonreturn;
}

```

code SLAVE : https://www.dropbox.com/s/2lg8ogjep80gtsa/SLAVE.ino?dl=0

```
#include <Wire.h>
#include <Stepper.h>

const int stepsPerRevolution = 64;
int led = A0;
Stepper motorX(stepsPerRevolution, 2, 3, 4, 5);
Stepper motorY(stepsPerRevolution, 6, 7, 8, 9);
Stepper motorZ(stepsPerRevolution, 10, 11, 12, 13);

void setup() {
  Wire.begin(8);
  // Wire.onRequest(requestEvent);
  Wire.onReceive(receiveEvent);

  pinMode(led, OUTPUT);
  motorX.setSpeed(60);
  motorY.setSpeed(60);
  motorZ.setSpeed(60);
  Serial.begin(9600);
}

void loop() {}

void receiveEvent(int howMany) {

  char choose;

  while (Wire.available() > 0) {
    //initialization
    choose = 'A';
    choose = Wire.read();

    if (choose == 'X')    {
      Serial.println("TURN MOTOR X");

      turnX();
    }
    else if (choose == 'Y') {
      Serial.println("TURN MOTOR Y");
      turnY();
    }
    else if (choose == 'Z') {
      Serial.println("TURN MOTOR Z");
      turnZ();
    }
  }
  analogWrite(led, 1020);
  delay(300);
  analogWrite(led, 0);
}

void turnX() {
  motorX.step(stepsPerRevolution);
}

void turnY() {
  motorY.step(stepsPerRevolution);
}

void turnZ() {
  motorZ.step(stepsPerRevolution);
}

```

When I choose yes to turn a motor it works well but the other motors that is after does not work. I want the other motors to turn if I choose yes even if the previous motor is running. Please, I need your URGENT help because my project is blocked :(

# Answer
The step function from the Stepper library is blocking. So it can only run one motor at a time. You need a different stepper library that is non-blocking. Try AccelStepper.
> 2 votes

---
Tags: arduino-uno, programming, motor, stepper
---


# Question
Title: Compilation Error in nodeMCU along with oneWire temperature sensor ds18b20, and 2x16 LCD display (not I2C)
I am using nodeMCU along with oneWire temperature sensor ds18b20, and 2x16 LCD display (not I2C). I am using Arduino IDE to program nodeMCU. I am getting a compilation error:

```
C:\Program Files (x86)\Arduino\libraries\OneWire/OneWire.h:108:2: error: #error "Please define I/O register types here"
#error "Please define I/O register types here"
^
exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

```

What is meant by: "Please define I/O register types here"? Thank you for the help.

# Answer
> 4 votes
It appears you're using an outdated version of the OneWire library that does not support ESP8266. Please follow these instructions to upgrade to the latest release of the library:

1. Sketch \> Include library \> Manage libraries...
2. Wait for the download to finish.
3. In the "Filter your search..." box, type "onewire".
4. Click on the "OneWire" entry.
5. Click the "Update" button.
6. Wait for the installation to finish.
7. Click the "Close button.

The recent releases of the OneWire library have support for ESP8266 so this should solve your compilation issue.

---
Tags: nodemcu, 1-wire, ds18b20, compilation-errors
---


# Question
Title: There is an error stating that "exit status 1 expected unqualified-id before 'if'. This project is used to turn on/off LED and magnetic door
```
* /
#define CUSTOM_SETTINGS
#define INCLUDE_KEYPAD_SHIELD

/* Include 1Sheeld library. */
#include <OneSheeld.h>

/* Define an iterator. */
int iterations = 0;

/* A name for the LockPin on pin D2. */
int lockPin = 2;
int ledRed = A5;
int ledGreen = A4;

/* A name for the switch led on pin D5. */
const int lampuPin = 5;
const int ledlampu = A0;

// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
int stateBefore = 0;
int i = 0;
int j = 0;

void setup() {
  /* Start communication. */
  OneSheeld.begin();
  /* Set the LED & LOCK as output. */
  pinMode(lockPin, OUTPUT);
  pinMode(ledRed, OUTPUT);
  pinMode(ledGreen, OUTPUT);
  /* Set the LampuPin pin as output. */
  pinMode(lampuPin, INPUT);
  /* Set the LED pin as output. */
  pinMode(ledlampu, OUTPUT);
}

void loop() {
  //======Lampu Rumah=======
  // read the state of the pushbutton value:
  buttonState = digitalRead(lampuPin);
  if (buttonState != stateBefore) {
    if (buttonState == HIGH and i == 0) {
      digitalWrite (ledlampu, HIGH);
      j = 1;
    } else if (buttonState == LOW and j == 1) {
      i = 1;
    } else if (buttonState == HIGH and i == 1) {
      digitalWrite (ledlampu, LOW);
      j = 0;
    } else if (buttonState == LOW and j == 0) {
      i = 0;
    }
  }
  stateBefore = buttonState;
}

//======Pintu Hadapan Rumah=======
/* Check if "1" is pressed, iterate one time. */
if (iterations == 0 && isOnePressed()) {
  iterations++;
} else if (iterations == 1 && isTwoPressed()) {
  /* Check if "2" is pressed, iterate one time. */
  iterations++;
} else if (iterations == 2 && isThreePressed()) {
  /* Check if "3" is pressed, iterate one time. */
  iterations++;
} else if (iterations == 3 && isFourPressed()) {
  /* Check if "4" is pressed, iterate one time. */
  iterations++;
} else if (isOtherButtonPressed()) {
  /* Check if any other button is pressed, reset iterations. */
  iterations = 0;
}
if (iterations == 4) {
  /* Check if the number of iterations is 4, blink the LED. */
  digitalWrite(lockPin, LOW);
  digitalWrite(ledGreen, HIGH);
  digitalWrite(ledRed, LOW);
  OneSheeld.delay(6000);
  digitalWrite(lockPin, HIGH);
  digitalWrite(ledRed, HIGH);
  digitalWrite(ledGreen, LOW);
  OneSheeld.delay(1000);
  /* Reset the iterator. */
  iterations = 0;
}

/* Helper functions check if a certain button is pressed by checking its row and column. */

boolean isOnePressed() {
  return Keypad.isRowPressed(0) && Keypad.isColumnPressed(0);
}

boolean isTwoPressed() {
  return Keypad.isRowPressed(0) && Keypad.isColumnPressed(1);
}

boolean isThreePressed() {
  return Keypad.isRowPressed(0) && Keypad.isColumnPressed(2);
}

boolean isFourPressed() {
  return Keypad.isRowPressed(1) && Keypad.isColumnPressed(0);
}

boolean isOtherButtonPressed() {
  return ((Keypad.isAnyColumnPressed() || Keypad.isAnyColumnPressed()) && !isOnePressed() && !isTwoPressed() && !isThreePressed() && !isFourPressed());
}

```

# Answer
> 4 votes
You got an extra closing brace after this line.

```
stateBefore = buttonState;
}

```

It ends the loop function so the next if is outside any function and illegal. Hit Control-T in the IDE to auto-format the code and it will line up the indention and that will help you spot these sorts of errors.

---
Tags: arduino-uno
---


# Question
Title: Arduino with ATmega32U4 low power but keep Serial1 working
I am looking for a low power solution for my ATmega32U4. It uses Serial1 to communicate with Bluetooth, so I need to have it active. When I receive data from Serial1, I want to power up the Arduino, do some magic, and then power it off...

# Answer
For Power Down/Standby Mode you would have to use an Interrupt Pin to reactive the MCU. If you do not mind possible loss of the first character you could connect an Interrupt Pin to Serial1 RX and wake up on the first start bit.

The startup delay (i.e. time until UART is up and working) may impact the first character received. You could always start off by sending a number of null character as a "wake up call"; classical break sequence.

Cheers!

Ref. ATmega16/32U4, Chap. 7. Power Management and Sleep Modes.
> 2 votes

---
Tags: power, library, battery, atmega32u4
---


# Question
Title: ERROR on SIM900AT comand HTTPDATA (POST method)
Good day community, I have a project which is VEHICLE GPS Tracker and I'm using Arduino Mega, NEO GPS6MV2 and SIM900. I'm using SIM900 to send the GPS coordinates on a web server. I'm using the POST method and SIM900 is capable of this by using AT commands. I will also save the coordinates on a MySQL database. My problem here is I can't send the data on the MySQL database. As you can see on the latter part of the commands, it response "ERROR".  That's why the coordinates failed to enter on the database. This is what I have on the database: What do you think is the problem here?

# Answer
1. If you say you are going to send 90 characters you **must** send 90 characters. No more, no less. I count 70 there.
2. You have to send them immediately the modem responds `DOWNLOAD` otherwise it times out (10 seconds) and you get `ERROR`. It looks to me like you're not sending anything (except maybe a blank line) for those 10 seconds and only trying to send once it has errored.
> 0 votes

---
Tags: gsm, datalogging, http, tcpip
---


# Question
Title: Does an Arduino 101 come with bluetooth HID capabilities?
I would like to prototype an Ergodox-like keyboard. My take on this good design would be to affix each half of the keyboard to my chair's armrests, so that the arms are always in a natural relaxed position. In order to achieve this, bluetooth capabilities seem necessary in order to avoid cable mayhem each time I move the chair.

I am aware that the Arduino Leonardo has USB-HID capabilities, but will that translate to the additional USB module that would be required? I saw that Adafruit has an EZ-key bluetooth module that seems to fit the bill, but even so, it would require more cabling and complexity, for a project that is already very near my threshold (or above it).

What would be easy is if the Arduino 101 had HID capabilities. I would just need to solder the matrix of keys, and almost be done. Does it?

Thanks for your attention.

# Answer
The Arduino 101 has HID capabilities. I found example code for using the Arduino 101 as a keyboard, as well as some other discussions saying that the Arduino 101 has HID capabilities.

Here is some example code on GitHub.
> 2 votes

---
Tags: bluetooth
---


# Question
Title: Can Arduino post multiple sensor data to one Google Spreadsheet?
Let's say I have one MQ5 gas sensor at home and one MQ135 gas sensor at the park. They are wirelessly hooked to Arduino.

My questions are:

Can Arduino post the data from two or more sensors to one Google Spreadsheet and organize it in two different charts?

Can only one Arduino accomplish this?

If not, what are the alternatives?

# Answer
> 2 votes
Not directly but with addon service like Pushingbox, temboo and so on it can.

If you google on your topic there are a ton of ways to do it!

---
Tags: arduino-uno, sensors, wireless, documentation
---


# Question
Title: 2 sensors, add delay between each reading
I have two temperature sensors, an MCP9808 and a DS18B20, connected to an arduino and I've read that it could be advantageous to set a small delay between temperature readings. What I wonder is where I should set the delay, in the setup function:

```
tempsensor.begin();                           //initialize communication with mcp9808
sensors.begin();                              //initialize communication with dc18b20
readSensors();

```

or the readSensors function?:

```
temp = tempsensor.readTempC();              //read current temperature and save value inside "temp"
sensors.requestTemperatures();              // Send the command to get temperatures
temp2 = sensors.getTempCByIndex(0);

```

As you can probably tell I am very new to all of this, intuition tells me that I should set the delay within the readSensors function.

Any alternative suggestions about how I should be readings temperature data from two different sensors connected to one arduino would be appreciated.

**EDIT**
after re-reading question and based on first answer I haven't made it unequivocally clear my intention; I want to delay the time between the mcp9808 and the ds18b20 temperature readings, so that it waits X seconds between each. I have read that this may help to reduce noise.

# Answer
The essence of your question is actually about managing processor to processor communications. As the temperature sensors you have chosen appear as peripheral processors which communicate to your processor over SMBus (MCP9808) or 1-Wire bus (DS18B20).

Both temperature sensors actually abstract you from the details of (likely) thermistor Analog to Digital Conversion (ADC) sampling and (likely) exponential averaging over multiple samples in order to reduce noise by providing a digital communication interface. As you can see, there may be many steps taken before the temperature data is available over the digital communication interface. Each step takes a finite amount of time.

In almost all cases there is a microprocessor busy at work inside the temperature probe. How well that processor's code is written dictates how much you can (skip reading the MCP9808 and DS18B20 specification sheet(s) and) "abuse" the protocol.

If you ask for the data faster then the temperature probe can obtain a new sample, in the best case, it is likely you will be supplied with duplicate values or values clearly designated as errors. In the worst case, you may get back incorrect values indistinguishable from normal values. Read the specification sheets and consider the source of the parts.

All this said, it may be that the 2 libraries you have chosen to use are not compatible. Yes, one library is using the SMBus / I2C approach and the other is using the 1-Wire bus approach. However, if both libraries use any single Arduino resource (for example a hardware timer or a hardware interrupt) at the same time, they may interfere with one another.

To test this, comment out the instantiation and code for one of the approaches and see if the other begins working as you expected in the first place. Then repeat the experiment commenting out the other.

In the end, it is almost always better to use as few libraries as possible when assembling software for an Arduino. There may be some effort to make some libraries work together. But it is impractical to test all library combinations. For this specific case, using several temperature devices of the same type (all using the same serial bus) and assigning different addresses to each would allow you to restrict your self to only including / using one library.
> 1 votes

# Answer
> I've read that it could be advantageous to set a small delay between temperature readings

Although temperature is typically a measure that changes slowly in time, there is nothing in programming/device side preventing you from making readings in short intervals; unless this added time is necessary to prevent issues on other tasks, but so it should be not related to that.
> 1 votes

---
Tags: temperature-sensor, temperature
---


title: Audio.h Library Issues

text:
# Question
Title: Audio.h Library Issues
I'm trying to incorporate audio into my Arduino project for the first time, and have been have a lot of issues. I originally couldn't get the Audio library to work, but after installing it through the Arduino application, I figured the Audio.h library would work fine. However, it spit out this error:

> WARNING: library Audio claims to run on (sam) architecture(s) and may be incompatible with your current board which runs on (avr) architecture(s). In file included from /Documents/Arduino/libraries/Audio/src/Audio.h:16:0, from /Documents/Arduino/boxgame/boxgame.ino:1:

Then it lists plenty of syntax issues, none of which have to do with my code. I think it's giving errors from the library, but I'm not really sure what's happening. Here's an example of one of the slew of errors:

> /Users/tschadius/Documents/Arduino/libraries/Audio/src/DAC.h:37:2: error: 'IRQn\_Type' does not name a type IRQn\_Type isrId;

Any ideas as to how I can fix this? The error message goes on for quite a while, but none of them appear to be from my code that I've written.

Thanks!

# Answer
> 2 votes
Occasionally people do not realize how many platforms the Arduino paradigm has been ported to. In almost all cases the ported to platform far exceeds the features found on an Arduino Uno. So there exists a considerable amount of software that can not run on an Arduino Uno or on an Arduino Uno with out additional hardware. But, usually, such software is surrounded by "text", "web-pages" and other "readme" type files explaining the situation.

For the Arduino Audio library, the web-page says this:

> Audio
>
> Compatible with Arduino Due only
>
> The Audio library enables an Arduino Due board to play back .wav files from a storage device like an SD card.
>
> The Due uses the DAC0 and DAC1 pins to play sounds.

---
Tags: arduino-uno, audio
---


title: Using Interrupt on Arduino

text:
# Question
Title: Using Interrupt on Arduino
I'm currently working on a project in which I'm supposed to make an Arduino car dodge any kinds of obstacles. I know how to do without using Interruptions but as I was searching online I found out that this is something that is used and would turn out better. Is it really possible? And if so, I don't exactly grasp the concept of using it to make (for example) the car stop once it senses an object. I know that it is supposed to be the first thing it will do if I program it that way but, can I program how the Interrupt will act upon the machine? And if so, how exactly?

Thanks

# Answer
Interrupts help if an event needs to be dealt with over the time period of a few processor clock cycles. Such as the deployment of air bags. If the accumulated delay of not responding in a few processor clock cycles adds up to considerable error. Such as a Real Time Clock (RTC). Or, if an event is so short that it might be missed during periodic polling (checking). Such as counting flashes of lighting during a storm.

If this type of response time is not needed, interrupts may be more trouble than they are worth.

This is because interrupts can stop the processor from executing the normal program and force it to execute the interrupt program. This can be very confusing to new programmers. At any moment an interrupt may stop their program and possibly erase or change what that program was working on. Both the program that is running and the interrupt program need to be written to tolerate this processor behavior.

It is almost always easier to "poll" the state of obstacle sensors (in this case) rather than tying its state to an "interrupt". Using the Arduino paradigm, the purposes of the loop() entry point is to do just this. A function which will be called over and over again. Each time it is called you can "poll" the sensor and cause the model car to vier around an obstacle.
> 1 votes

# Answer
See How do interrupts work on the Arduino Uno and similar boards?

> I was searching online I found out that this is something that is used and would turn out better. Is it really possible?

That's very vague. *What* did you find online?

> And if so, I don't exactly grasp the concept of using it to make (for example) the car stop once it senses an object.

Set a flag in the interrupt, which you detect in your main loop. In the main loop make the car stop when the flag becomes true.
> 0 votes

# Answer
> Is it really possible?

anything is possible.

> And if so, I don't exactly grasp the concept of using it to make (for example) the car stop once it senses an object.

all an interrupt does is to take the execution to a different place. in practical terms, an interrupt would execute some quick functions and set some flags for the main loop to execute.

interrupts are critical to embedded engineering and it is very difficult for a real-world code to run without interrupts.
> 0 votes

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


# Question
Title: How do I know the IP address assigned to an ESP8266?
I have programmed an ESP8266 using the circuit and program below. I tried to open the SerialMonitor once the program is uploaded to the ESP8266. I am getting an error when I am trying to open the SerialMonitor.

> Error opening serial port 'COM5'. (Incorrect serial port)

What is the way to get the IP address assigned to the ESP8266?

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

//SSID and Password of your wifi router
const char* ssid = "Moto";
const char* password = "reset1234";

ESP8266WebServer server(80);

void setup() {
  Serial.begin(9600);
  WiFi.begin(ssid, password); //Connect to your WiFi router
  Serial.println("");
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  //If connection successful show IP address in serial monitor
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //IP address assigned to your ESP
  server.begin(); //Start server
  Serial.println("HTTP server started");
}

void loop() {
  server.handleClient(); //Handle client requests
}

```

# Answer
> 4 votes
If you give your board a name with

```
WiFi.hostname("MyESP8266");

```

(for example) you can then look on your router in the section that lists DHCP assignments (on my Netgear it's *Attached Devices*). That should then show you the IP address of all the attached devices, including the ESP8266 which you will easily identify by its name.

Another option is to use mDNS. Look at some of the examples that come with the ESP8266 core and libraries to see how.

# Answer
> 1 votes
I used the app "Fing" on my phone. It shows you the devices that are connected to your WiFi. After entering all freacking IP adress aviable, found that the last one was the one of my esp8266 and a beautiful window saying "hello from esp8266!" appeared.

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


# Question
Title: Cannot spin motor 28BYJ-48 with controller board ULN2003APG
I'm a beginner with Arduino. I managed to grasp the basic understanding and try to use each component/shield that came with my Arduino kit.

I'm unable to use the following component:

* Step Motor 28BYJ-48
* Step Motor controller board ULN2003APG

I connected the Arduino to the ULN2003APG and put some coding such that I can see that the ULN2003APG's LED turned on from 1, 2, 3, 4, 1, 2, 3, 4, and so on. So this is as expected as per programming below.

**My issue:**

1. I noticed the LED in the ULN2003APG is not as bright as a regular LED.
2. Once I plugged in the 28BYJ-48 to the ULN2003APG, the ULN2003APG's LED all off.
3. The motor (28BYJ-48) doesn't spin - at all.
4. I tried to spin the motor with my 2 fingers, it seems pretty heavy - is this normal?

**Is this a faulty ULN2003APG or is it a faulty 28BYJ-48 or is it a faulty programming? please help.**

Program:

```
#include <Stepper.h>

int pin1=8;
int pin2=9;
int pin3=10;
int pin4=11;
int _step=0;
void setup() {
    Serial.begin(9600);
    pinMode(pin1, INPUT);
    pinMode(pin2, INPUT);
    pinMode(pin3, INPUT);
    pinMode(pin4, INPUT);
}

void loop() {
  switch (_step){
    case 0:
      digitalWrite (pin1, HIGH);
      digitalWrite (pin2, LOW);
      digitalWrite (pin3, LOW);
      digitalWrite (pin4, LOW);
      break;
    case 1:
      digitalWrite (pin1, LOW);
      digitalWrite (pin2, HIGH);
      digitalWrite (pin3, LOW);
      digitalWrite (pin4, LOW);
      break;
    case 2:
      digitalWrite (pin1, LOW);
      digitalWrite (pin2, LOW);
      digitalWrite (pin3, HIGH);
      digitalWrite (pin4, LOW);
      break;
    case 3:
      digitalWrite (pin1, LOW);
      digitalWrite (pin2, LOW);
      digitalWrite (pin3, LOW);
      digitalWrite (pin4, HIGH);
      break;
  }
  _step ++;
  if (_step == 4){
    _step = 0;
  }
  Serial.println(_step);
  delay(250);

}

```

# Answer
> 1 votes
What happens if you change

```
pinMode(pin1, INPUT);
pinMode(pin1, INPUT); // Pin 2 ?
pinMode(pin3, INPUT);
pinMode(pin4, INPUT);

```

to

```
pinMode(pin1, OUTPUT);
pinMode(pin2, OUTPUT);
pinMode(pin3, OUTPUT);
pinMode(pin4, OUTPUT);

```

Answer for Q1 - Q3. You are using pinMode as an input. Using digitalWrite() on an INPUT will enable (HIGH) or disable (LOW) the internal pullup resistor on the input pin. The pin will not be able to "source" enough current to operate the stepper motor.

A4. The stepper motor has a "mechanical" 1/64 gear ratio. This is why it is hard to turn by hand.

Here are 2 pages that will help you to understand the issue: https://www.arduino.cc/en/Reference/PinMode and https://www.arduino.cc/en/Reference/DigitalWrite.

---
Tags: motor
---