# Question
Title: Physical safety: Prevent linear actuator from crushing my fingers
Our project consists of an old wooden barrel, whose top lid is opened/closed with a simple linear actuator. I am a bit afraid that it might crush somebody's fingers while closing.

How could I detect trapped objects effectively?

Elevators often have light barriers, but the problem here is that the opening has a 360° border. Force sensitive resistors seem to be an option too. However, since the border is a circle, I guess applying them would not work too well (folding issues) and look bad on a vintage barrel.

*I'm very sorry if I maybe created a duplicate here and I would like to encourage me to provide links to similar questions. I simply couldn't come up with useful search words for my problem.*

# Answer
> 3 votes
The easiest way to prevent things becoming trapped is to take reasonable steps to prevent things getting near the "danger zone", so a barrier 2 metres around the barrel would be a good start. Probably it would be an impractical idea, but...

A physical barrier of some sort would be the best idea, because that is less likely to suffer a failure than an electronic system (well assuming it has been designed right). If you are using an electronic system then it needs to "fail-safe", when it suffers a failure it must adopt its safe state (barrel open).

You could surround the lid with IR lights and receivers in the lip. They would need to be spaced at a distance where an arm/finger couldn't get between the lid and lip without breaking a beam. This solution would only work over the last few inches, because of the angle of the beams. If all receivers had a signal the it would be safe to close. The problem is the receivers would need to be close together to prevent transgression.

Monitoring the current drawn by the actuator and the position of the actuator might be another. I am assuming that there is an increase in current draw when the lid actually closes, and a similar increase in draw when something is trapped. If the lid isn't fully closed when the current increases then something is trapped.

The final way I can think of is probably the most effective. As the barrel closes don't close it the last few inches, allow it to 'fall' as the actuator descends. This means if there is an object in there the actuator isn't pulling the lid down and the object will hold the lid against gravity. This would be done by having a channel in the mounting block for the actuator 'pin'/ connection point to slide up and down.

OK Its not an electrical solution.

---
Tags: sensors
---


# Question
Title: How to choose between AM230x and DHT22 temperature and humidity sensors?
I'm looking forward to getting an accurate humidity and temperature sensor.

Right when I decided to go with a DHT22 module, I saw AM230x (AM2301, for example).

* How do I choose between DHT22 and AM2301?

# Answer
> 8 votes
The AM2301 and the DHT22(AM2303) are similar in a number of ways, both in price, specs, ranges and power consumption. They are usually cased a bit of a differently, with the DHT22/AM2303 being packaged with four pins (only three are in use), and the AM2301 (formerly called DHT21) is packaged with three cables and a small plug inside of the case.

I would choose based on the usage, if I'm going to use the sensor on a breadboard or a socket (going for the DHT22 pinned version), or if I'm going to have it standalone (the cabled one).

Here are links to the datasheets:

https://kropochev.com/downloads/humidity/AM2301.pdf

https://www.adafruit.com/datasheets/DHT22.pdf

# Answer
> 0 votes
The AM2302 has a built-in pull-up resistor, whereas the DHT22 does not. Apart of that and de different housing they should be technically identical.

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


# Question
Title: What is Clock pin and Data pin, Orientation in Grove LED bar
I'm trying to use Grove LED Bar with Arduino

> Grove – LED Bar is comprised of a 10 segment LED gauge bar and an MY9221 LED controlling chip. It can be used as an indicator for remaining battery life, voltage, water level, music volume or other values that require a gradient display. There are 10 LED bars in the LED bar graph: one red, one yellow, one light green, and seven green bars. Demo code is available to get you up and running quickly. It lights up the LEDs sequentially from red to green, so the entire bar graph is lit up in the end.

In the github example there are `Clock pin`, `Data pin` and `Orientation`.

```
// Arduino Clock pin, Data pin, Orientation
// Grove_LED_Bar bar(7, 6, 0);

```

https://github.com/Seeed-Studio/Grove\_LED\_Bar/blob/master/LP%20examples/BasicControl/BasicControl.ino

But I have no idea what are they. Where can I find the documentation for them?

# Answer
on the LED circuit board there are a few connections, notably DI and DCKI.

The DI pin is the data pint and DCKI is the clock pin.

According to the header orientation is about which way the pins are oriented red-to-green or green-to-red. It affects at which end led 1 is.
> 0 votes

# Answer
**How to connect Grove to your board**

You need a Grove Expansion Board which to attach the Grove modules. The Grove Expansion Board provides the processing power, and the modules offer the input sensors and output actuators of your system. There are many Grove Expansion Board for different platform already, they include Arduino UNO, Particle Phone, BeagleBone board etc.

**Features**

There are intotal 16 grove connectors on the Base Shield, here we use a table to show the details.

**Specification**

Apart from the rich grove connectors, on the board you can also see an RST button, a green LED to indicating power status, ICSP pin, a toggle switch and four row of pinouts. There is no need to explain the RST button and LED, but you really need to know below two features that is very important for your usage.

1.Power Compatible:

Every Grove connector has four wires, one of which is the VCC. However, not every micro-controller main board needs a supply voltage of 5V, some need 3.3V. That's why we add a power toggle switch to Base Shield v2 so that you can select the suitable voltage of the micro-controller main board you are using via this switch.

For example, if you are using Arduino UNO with Base Shield v2, please turn the switch to 5v position; while using Seeeduino Arch with Base Shield v2, please turn the switch to 3.3v.

2.Board Compatible:

The pinout of Base Shield V2 is the same as Arduino Uno R3, however Arduino Uno is not the board one that the Base Shield V2 is compatible with, here we listed the boards that we have confirmed that can be used with Base Shield V2.

```
Arduino Uno

Seeeduino V4.2

Arduino Mega / Seeeduino Mega

Seeduino LoraWan

Arduino Leonardo / Seeeduino Lite

Arduino 101

Arduino Due

Intel Edison

Linkit One

```
> 0 votes

---
Tags: arduino-uno
---


title: Multitasking for music light sculpture

text:
# Question
Title: Multitasking for music light sculpture
First of all, I'm new so please don't think this is dumb. I am creating a light culture with RGB LEDs that should play to programmed music. I have uploaded the following code to a spark fun redbird for now, but will later put it on a arduino mega. My circuit is working fine mostly except for the fact that the lights and music play separately and not next to each other. Note: this is just trial code, I will put my own music and light sequencing in later.

```
const int buzzerPin = 6;    // connect the buzzer to pin 6
const int RED_PIN = 11;
const int GREEN_PIN = 12;
const int BLUE_PIN = 13;
const int RED_PIN2 = 8;
const int GREEN_PIN2 = 9;
const int BLUE_PIN2 = 10;
const int songLength = 18;  // sets the number of notes of the song

const int DISPLAY_TIME = 100;
// Notes is an array of text characters corresponding to the notes
// in your song. A space represents a rest (no tone)

char notes[songLength] = {
  'c', 'd', 'f', 'd', 'a', ' ', 'a', 'g', ' ', 'c', 'd', 'f', 'd', 'g', ' ', 'g', 'f', ' '};

// beats[] is an array of values for each note. A "1" represents a quarter-note,
// "2" a half-note, and "4" a quarter-note.
// Don't forget that the rests (spaces) need a length as well.

int beats[songLength] = {
  1, 1, 1, 1, 1, 1, 4, 4, 2, 1, 1, 1, 1, 1, 1, 4, 4, 2};

int tempo = 113;  // The tempo is how fast to play the song (beats per second).

void setup()
{
  pinMode(buzzerPin, OUTPUT);  // sets the  buzzer pin as an OUTPUT
   pinMode(RED_PIN, OUTPUT);
  pinMode(GREEN_PIN, OUTPUT);
  pinMode(BLUE_PIN, OUTPUT);
   pinMode(RED_PIN2, OUTPUT);
  pinMode(GREEN_PIN2, OUTPUT);
  pinMode(BLUE_PIN2, OUTPUT);
}

void loop()
{
  mainColors();        // Red, Green, Blue, Yellow, Cyan, Purple, White
  int i, duration; //

  for (i = 0; i < songLength; i++) // for loop is used to index through the arrays
  {
    duration = beats[i] * tempo;  // length of note/rest in ms

    if (notes[i] == ' ')          // is this a rest?
      delay(duration);            // then pause for a moment
    else                          // otherwise, play the note
    {
      tone(buzzerPin, frequency(notes[i]), duration);
      delay(duration);            // wait for tone to finish
    }
    delay(tempo/10);              // brief pause between notes
  }

  // We only want to play the song once, so we pause forever
  }
  // If you'd like your song to play over and over, remove the while(true)
  // statement above

int frequency(char note)
{
  int i;
  const int numNotes = 8;  // number of notes we're storing
  char names[numNotes] = {
    'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C'    };
  int frequencies[numNotes] = {
    262, 294, 330, 349, 392, 440, 494, 523    };

  // Now we'll search through the letters in the array, and if
  // we find it, we'll return the frequency for that note.

  for (i = 0; i < numNotes; i++)  // Step through the notes
  {
    if (names[i] == note)         // Is this the one?
    {
      return(frequencies[i]);     // Yes! Return the frequency and exit function.
    }
  }
  return(0);  // We looked through everything and didn't find it,
  // but we still need to return a value, so return 0.
}

void mainColors()
{
  // Red
  digitalWrite(RED_PIN, HIGH);
  digitalWrite(GREEN_PIN, LOW);
  digitalWrite(BLUE_PIN, LOW);
   digitalWrite(RED_PIN2, HIGH);
  digitalWrite(GREEN_PIN2, HIGH);
  digitalWrite(BLUE_PIN2, HIGH);
  delay(DISPLAY_TIME);

  // Green
  digitalWrite(RED_PIN, LOW);
  digitalWrite(GREEN_PIN, HIGH);
  digitalWrite(BLUE_PIN, LOW);
    digitalWrite(RED_PIN2, HIGH);
  digitalWrite(GREEN_PIN2, LOW);
  digitalWrite(BLUE_PIN2, HIGH);
  delay(DISPLAY_TIME);

  // Blue
  digitalWrite(RED_PIN, LOW);
  digitalWrite(GREEN_PIN, LOW);
  digitalWrite(BLUE_PIN, HIGH);
   digitalWrite(RED_PIN2, LOW);
  digitalWrite(GREEN_PIN2, HIGH);
  digitalWrite(BLUE_PIN2, HIGH);
  delay(DISPLAY_TIME);

  // Yellow (Red and Green)
  digitalWrite(RED_PIN, HIGH);
  digitalWrite(GREEN_PIN, HIGH);
  digitalWrite(BLUE_PIN, LOW);
    digitalWrite(RED_PIN2, HIGH);
  digitalWrite(GREEN_PIN2, HIGH);
  digitalWrite(BLUE_PIN2, LOW);
  delay(DISPLAY_TIME);

  // Cyan (Green and Blue)
  digitalWrite(RED_PIN, LOW);
  digitalWrite(GREEN_PIN, HIGH);
  digitalWrite(BLUE_PIN, HIGH);
    digitalWrite(RED_PIN2, LOW);
  digitalWrite(GREEN_PIN2, LOW);
  digitalWrite(BLUE_PIN2, HIGH);
  delay(DISPLAY_TIME);

  // Purple (Red and Blue)
  digitalWrite(RED_PIN, HIGH);
  digitalWrite(GREEN_PIN, LOW);
  digitalWrite(BLUE_PIN, HIGH);
    digitalWrite(RED_PIN2, LOW);
  digitalWrite(GREEN_PIN2, HIGH);
  digitalWrite(BLUE_PIN2, LOW);
  delay(DISPLAY_TIME);

  // White (turn all the LEDs on)
  digitalWrite(RED_PIN, HIGH);
  digitalWrite(GREEN_PIN, HIGH);
  digitalWrite(BLUE_PIN, HIGH);
    digitalWrite(RED_PIN2, HIGH);
  digitalWrite(GREEN_PIN2, LOW);
  digitalWrite(BLUE_PIN2, LOW);
  delay(DISPLAY_TIME);
}

```

# Answer
> 2 votes
You need a *state machine*. It goes like this:

You divide your actions in states. Each state is a collection of actions that must performed in group (sequentially). In your case, you have one state for each note and for each ligth color and a duration.

Now, your score (music + light) is made of a sequence of states:

```
> state 1: Play Fa, Light up RED - Duration 500ms.
> state 2: Play Re, Light down RED - Duration 200ms. ...
>
> state n: Play Fa, Light up BLUE - Duration 250 ms.

```

You have many states; put them in an array and then loop across the array.

The code looks like this:

```
typedef struct {
    int note;  // Musical note
    int color; // Led color
    int length; // Duration in ms
} STATE;

STATE score[] = {
    {0, 0, 0},
    {FA, BLUE, 500},
    [RE, RED, 400},
    ...
   {FA, GREEN, 400}
   };

int state = 0;

void loop()
{
    static unsigned long stateStart = 0;

    if(state == sizeof(score) / sizeof(STATE)) {
        //  reset and start again
        state = 0;
        stateStart = 0;
    }

    if(millis() - stateStart >= score[state].time) {
        // Advance state and play next thing
        state++;
        playNote(score[state].note, duration);
        playColor(score[state].color);
        stateStart = millis();
    }

}

void playNote(int note, duration)
{
    // Play a note.
}

void playColor(int color)
{
    // Light up a color.
}

```

Note: this is just the general idea. You must adapt and adjust things, like how you code note and colors. You better Google "Arduino state machine".

My code probably contains errors, but I gave you a starting point.

You have to implement playNote and playColor.

---
Tags: arduino-mega
---


# Question
Title: How to connect an Arduino and a WAMP server's MySQL database?
I'm trying to connect an Arduino Mega to my WAMP server's database using MySQL connector for attendance logging. But it shows "Connection failed".

What is my WAMP server's IP address?

I connect my laptop and Arduino with a router so:

* My laptop is 192.168.1.2
* My Arduino is 192.168.1.3

I think this is correct.

```
/*
  MySQL Connector/Arduino Example: basic insert
  This example demonstrates how to issue an INSERT query to store data in a
  table. For this, we will create a special database and table for testing.
  The following are the SQL commands you will need to run in order to setup
  your database for running this sketch.

  CREATE DATABASE test_arduino;
  CREATE TABLE test_arduino.hello_arduino (
    num integer primary key auto_increment,
    message char(40),
    recorded timestamp
  );

  Here we see one database and a table with three fields; a primary key that
  is an auto_increment, a string, and a timestamp. This will demonstrate how
  to save a date and time of when the row was inserted, which can help you
  determine when data was recorded or updated.

  INSTRUCTIONS FOR USE

  1) Create the database and table as shown above.
  2) Change the address of the server to the IP address of the MySQL server
  3) Change the user and password to a valid MySQL user and password
  4) Connect a USB cable to your Arduino
  5) Select the correct board and port
  6) Compile and upload the sketch to your Arduino
  7) Once uploaded, open Serial Monitor (use 115200 speed) and observe
  8) After the sketch has run for some time, open a mysql client and issue
     the command: "SELECT * FROM test_arduino.hello_arduino" to see the data
     recorded. Note the field values and how the database handles both the
     auto_increment and timestamp fields for us. You can clear the data with
     "DELETE FROM test_arduino.hello_arduino".

  Note: The MAC address can be anything so long as it is unique on your network.

  Created by: Dr. Charles A. Bell
*/

#include <Ethernet.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server_addr(192, 168, 1, 3); // IP of the MySQL *server* here
char user[] = "root"; // MySQL user login username
char password[] = ""; // MySQL user login password

// Sample query
char INSERT_SQL[] = "INSERT INTO test_arduino.hello_arduino (message) VALUES ('Hello, Arduino!')";

EthernetClient client;
MySQL_Connection conn((Client *)&client);

void setup() {
  Serial.begin(115200);
  while (!Serial); // wait for serial port to connect
  Ethernet.begin(mac_addr);
  Serial.println("Connecting...");
  if (conn.connect(server_addr, 3306, user, password)) {
    Serial.println("Connected Successfully...");
    delay(1000);
  } else
    Serial.println("Connection failed.");
}

void loop() {
  delay(2000);
  Serial.println("Recording data.");
  // Initiate the query class instance
  MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
  // Execute the query
  cur_mem->execute(INSERT_SQL);
  // Note: since there are no results, we do not need to read any data
  // Deleting the cursor also frees up memory used
  delete cur_mem;
}

```

# Answer
> 2 votes
As gre\_gor pointed out, it looks like your connecting to the wrong ip.

Change:

```
IPAddress server_addr(192, 168, 1, 3); // IP of the MySQL *server* here

```

To:

```
IPAddress server_addr(192, 168, 1, 2); // IP of the MySQL *server* here

```

---
Tags: arduino-mega, ethernet-shield
---


# Question
Title: Wiring light sensor OPB704WZ to Arduino Due
I would like to create a tachometer with the light sensor OPB704WZ.

I followed this schema https://tonyrobotdt081.wordpress.com/2014/04/10/report-on-the-light-sensor-opb704wz/ on a bread board (for now), and tried to measure the voltage difference on the signal pin (green on the schema).

Problem is, I don't see a clear difference between a white surface and a black one; It does change if I put the sensor closer or further away, but that's about all I can see.

Is there something else I need to add to my wiring to make the difference between high and low depending on the luminosity more obvious? I know others have been able to use this sensor for the same purpose.

# Answer
> 1 votes
You expect that the white surface to reflect the infrared light and the black surface does not.

Your theory is correct; white surfaces should reflect pretty much all light and the black surface should absorb all light.

The problem is that the black surface is reflecting enough light to turn the photo-transistor on.

The theory is correct but in the real world this is not perfect. For example a white surface is not completely white. Likewise no black surface is completely black.

We also know that a mirror is much better at reflecting light than a white surface. The black surface could be shiny. I am looking at my shiny black monitor stand, and even though it is black I can still see the reflection of the window.

I suggest trying with a number of black surfaces (such as paint, card, cloth) and finding the one that works best. I would imagine that chalk board paint would work well at absorbing and diffusing the infrared light. Also experiment with the distance away from the surface. You may have to move it further away from the surface.

If I am imagining your tachometer right, your sensor will see a reflective surface and then it will see empty space (and then repeat). This should work fine. Give it a try.

---
Tags: sensors
---


title: Arduino Uno SD card fails to initialize

text:
# Question
Title: Arduino Uno SD card fails to initialize
I'm not sure why my SD card fails to initialize when I run my code (below) but works when I just check to see if it is being read by the Arduino with the CardInfo code in the Arduino library.

The data logger is from Adafruit and the sensor that I'm connecting to it is a MaxBotix one. I've tried reseting the SD card and the Arduino and switching out the SD card. When I verify the code in Arduino there are no issues, so I'm not entirely sure why this isn't working. Any help is greatly appreciated. UPDATES: I was able to get it to initalize the SD card by moving

```
if (!SD.begin(chipSelect)) {
  error("Card failed, or not present");
}

```

after the

```
Serial.println().

```

but now it's not saving data or even creating a new document and it's not printing data as a new line. Things went south when I added the averaging portion of the code because before then it was printing data as a new line and the SD card initializing. My time is extremely wrong I'm getting a date like 2165/165/165 165:165:85.

```
#include <SPI.h>
#include <SD.h>
#include <Wire.h>
#include "RTClib.h"
/*
The goal of this code is to collect 10 data points a minute, average them, and store them to an SD card
*/
#define LOG_INTERVAL 6000 // mills between entries (reduce to take more/faster data)
// how many milliseconds before writing the logged data permanently to disk
// set it to the LOG_INTERVAL to write each time (safest)
// set it to 10*LOG_INTERVAL to write all data every 10 datareads, you could lose up to
// the last 10 reads if power is lost but it uses less power and is much faster!
#define SYNC_INTERVAL 1000 // mills between calls to flush() - to write data to the card
uint32_t syncTime = 0; // time of last sync()

#define ECHO_TO_SERIAL   1 // echo data to serial port
#define WAIT_TO_START    0// Wait for serial input in setup()
RTC_DS1307 RTC; // define the Real Time Clock object
// The analog pin that connect to the sensor
const int ultrasonicPin = A0; // declare the input pin for the ultrasonic sensor
unsigned long time;
// for the data logging shield, we use digital pin 10 for the SD cs line
const int chipSelect = 10;
const int numReadings = 10; //define number of samples to keep track of
int readings[numReadings]; //the readings from the analog input
int readIndex = 0; // the index of the current reading
int total = 0; // the running total
int average = 0; // the average
// the logging file
File logfile;

void error(char *str) {
  Serial.print("error: ");
  Serial.println(str);
  // red LED indicates error
  //digitalWrite(redLEDpin, HIGH);
  while(1);
}

void setup() {
  Serial.begin(9600);
  Serial.println();
  //initialize all the readings to 0:
  for(int thisReading = 0; thisReading < numReadings; thisReading++) {
    readings[thisReading] = 0;
    #if WAIT_TO_START
      Serial.println("Type any character to start");
      while (!Serial.available());
    #endif //WAIT_TO_START
    // initialize the SD card
    Serial.print("Initializing SD card...");
    // make sure that the default chip select pin is set to
    // output, even if you don't use it:
    pinMode(10, OUTPUT);
    // see if the card is present and can be initialized:
    if (!SD.begin(chipSelect)) {
      error("Card failed, or not present");
    }
    Serial.println("card initialized.");
    // create a new file
    char filename[] = "LOGGER00.CSV";
    for (uint8_t i = 0; i < 100; i++) {
      filename[6] = i/10 + '0';
      filename[7] = i%10 + '0';
      if (! SD.exists(filename)) {
        // only open a new file if it doesn't exist
        logfile = SD.open(filename, FILE_WRITE);
        break;  // leave the loop!
      }
    }
    if (!logfile) {
      error("couldnt create file");
    }
    Serial.print("Logging to: ");
    Serial.println(filename);
    // connect to RTC
    Wire.begin();
    if (!RTC.begin()) {
      logfile.println("RTC failed");
      #if ECHO_TO_SERIAL
        Serial.println("RTC failed");
      #endif  //ECHO_TO_SERIAL
    }
    logfile.println("millis,stamp,datetime,depth");
    #if ECHO_TO_SERIAL
      Serial.println("millis,stamp,datetime,depth");
    #endif //ECHO_TO_SERIAL
    // If you want to set the aref to something other than 5v
    analogReference(EXTERNAL);
  }
}

void loop() {
  DateTime now;
  // delay for the amount of time we want between readings
  delay((LOG_INTERVAL -1) - (millis() % LOG_INTERVAL));
  // log milliseconds since starting
  uint32_t m = millis();
  logfile.print(m); // milliseconds since start
  logfile.print(", ");
  #if ECHO_TO_SERIAL
    Serial.print(m); // milliseconds since start
    Serial.print(", ");
  #endif
  // fetch the time
  now = RTC.now();
  // log time
  logfile.print(now.unixtime()); // seconds since 1/1/1970
  logfile.print(", ");
  logfile.print('"');
  logfile.print(now.year(), DEC);
  logfile.print("/");
  logfile.print(now.month(), DEC);
  logfile.print("/");
  logfile.print(now.day(), DEC);
  logfile.print(" ");
  logfile.print(now.hour(), DEC);
  logfile.print(":");
  logfile.print(now.minute(), DEC);
  logfile.print(":");
  logfile.print(now.second(), DEC);
  logfile.print('"');
  #if ECHO_TO_SERIAL
    Serial.print(now.unixtime()); // seconds since 1/1/1970
    Serial.print(", ");
    Serial.print('"');
    Serial.print(now.year(), DEC);
    Serial.print("/");
    Serial.print(now.month(), DEC);
    Serial.print("/");
    Serial.print(now.day(), DEC);
    Serial.print(" ");
    Serial.print(now.hour(), DEC);
    Serial.print(":");
    Serial.print(now.minute(), DEC);
    Serial.print(":");
    Serial.print(now.second(), DEC);
    Serial.print('"');
  #endif //ECHO_TO_SERIAL
  analogRead(ultrasonicPin);
  delay(10);
  int value = analogRead(ultrasonicPin);
  for (int i=0; i < 50; i++) {
    if (millis() < 60000*(++i)) {
      // subtract the last reading:
      total = total - readings[readIndex];
      //read from the sensor:
      readings[readIndex] = analogRead(ultrasonicPin);
      // add the reading to the total:
      total = total + readings[readIndex];
      //advance to the next position in the array:
      readIndex = readIndex + 1;
      //if we're at the end of the array
      if (readIndex >= numReadings) {
        //wrap around to the beginning:
        readIndex = 0;
      }
      //calculate the average:
      average = total / numReadings;
      delay(6000);
    } else if (millis() == 60000*(++i)) {
      logfile.print(",");
      logfile.print(average);
      Serial.print("Ultrasonic Reading = ");
      Serial.println(average);
      //Serial.print("Time: ");
      //time = millis();
      //prints time since program started
      //Serial.println(time);
      //wait a second so as not to send massive amounts of data
      // Now we write data to disk! Don't sync too often - requires 2048 bytes of I/O to SD card
      // which uses a bunch of power and takes time
      if ((millis() - syncTime) < SYNC_INTERVAL) return;
      syncTime = millis();
      delay(100);
    }
  }
}
// this reads in cm

```

# Answer
> 1 votes
You cannot initialize the SD card more than once. Pull this code out of the `for` loop:

```
if (!SD.begin(chipSelect)) {
  error("Card failed, or not present");
}

```

Put it after the `Serial.println()`.

# Answer
> 0 votes
Make a new sketch that initialize the SD Card and write data to it, without loop.

If this doesn't works,maybe the sdcard is damage.

So, as shash-dev says,initialize the SD card before you start the for cicle and after the Serial.printl().

---
Tags: arduino-uno, datalogging
---


title: How to restart USB subsystem?

text:
# Question
Title: How to restart USB subsystem?
I'm developing on the Arduino platform (ESP8266 with USB -\> serial) and sometimes the USB port that is being used stops working and gets frozen. Then I need to plug the device into another USB port. It happens again and once all the USB ports stop working I have to restart the machine, which is really annoying.

As far as I remember there is a command that can restart the USB subsystem individually, but I can't remember. How to restart USBs without restarting the entire system? Thanks.

I'm using Mac OS X Sierra.

# Answer
> 1 votes
You are using a USB to UART adaptor. The Arduino has no concept of what that is - it just sends and receives UART data. The adaptor is completely separate and the Arduino can do absolutely noting at all with it.

If you are powering the whole circuit through that adaptor it may well be that it only requests 50mA from the computer. If you draw more than that (which you most likely are) the computer is free to shut the port down. It sounds like that may be what is happening.

What can you do? Well, two things:

1. Use an adaptor that requests enough current for your needs (may be hard to find)
2. Power your circuit separately using another power source.

Of the two I would suggest external power.

# Answer
> 0 votes
You're probably thinking of `kext[un]load`.

```
sudo kextunload /Library/Extensions/SiLabsUSBDriver.kext
sudo kextload /Library/Extensions/SiLabsUSBDriver.kext

```

---
Tags: serial, usb, mac-os
---


# Question
Title: Example code and documentation on using Firmata communication in native Java
I have been trying for some time to get documentation on using Java and a Firmata client library for the communication between a PC and an Arduino. Please note I want to use Java only, i.e., not Processing.

Up to now I used the excellent Haskell library hArduino for Firmata communication with Arduino boards.

Now I am teaching a Java course at the university as a PhD student. Therefore I need to use Java. However, compared to Haskell there are no centralized libraries, packages, documentation as with Haskell.

So I used Google to find more information on using Firmata client libraries for Java. Unfortunately, the search results are polluted with irrelevant results about Processing and Javascript. Therefore I ask here.

According to the Firmata client library page, there are two Java client libraries. However, only 4ntoine seems to be up to date, while the Javarduino project seems abandoned.

So I guess the standard way is to use the "4ntoine" Java client library. Or are there other options?

(I am not interested in Processing or Javascript.)

*Question: Where do I find up-to-date documentation and example code on using Firmata client libraries for Java?*

# Answer
> 1 votes
Maybe this can work for you. Some months ago i used RXTXcomm library \[1\] to send Arduino data to a Program i made in java and store in in a file, it works fine with some issues:

* I made the Java programm in linux but just works in java 6, so in the windows pc of the client i installed that version, i don't know if works with java7 or java8 in windows.
* Java programm reads data from Arduino sketch with Serial.print() function, Arduino continously is using this function, i lose some data, so i had to put a short delay to java programm get all data send by Arduino.

\[1\] http://rxtx.qbang.org/wiki/index.php/Main\_Page

# Answer
> 0 votes
Maybe JArduino can give you some useful information. Check the native code in jardunio.core.

---
Tags: serial, library, communication, firmata
---


# Question
Title: Arduino Due custom platform for school and library installation
I have made a custom-development hardware for our school, where you can plug in an Arduino Due. It is mainly for driving all kind of motors and reading sensor signals. Therefore I added a custom SAM board into board.h based on a copy of the Arduino Due. Furthermore I need a global PWM frequency on all PWM Channels of 20 kHz. So I also changed the variants.h file.

(I have not found a solution that is setting all the underling Timer/Counters for PWM on the Due Pins 2, 3, 4, 5, 6, 7, 8, 13 to 20 kHz by user code, I think this is only possible with the variants.h file - because some timers can not be reset after they where set within the Arduino IDE once)

**The Question now:** Today all students have to find and modify their variants.h file, which can be located almost anywhere! (Sometimes it is located in the support packages of Matlab...).

Is there an easy solution to give the students one .zip containing the Arduino IDE already with the custom Board included? There is the Arduino IDE working without installation for download on the Arduino website. But how can I add my custom SAM board to it?

# Answer
1. Exit the Arduino IDE.
2. Create a folder in the Arduino IDE installation folder named `portable`. This will cause the Arduino IDE to run in portable mode.
3. Start the Arduino IDE.
4. Tools \> Board \> Boards Manager
5. Wait for the download to finish.
6. Click on "Arduino SAM Boards".
7. Click "Install".
8. Wait for installation to finish.
9. Make your modifications to the Arduino SAM Boards hardware package installed at `{Arduino IDE installation folder}/portable/packages/arduino/hardware/sam`.
10. If necessary, configure **File \> Preferences** to your liking.
11. Exit the Arduino IDE.
12. Zip the Arduino IDE installation folder.

When you run the Arduino IDE in portable mode it causes hardware packages installed via Boards Manager to be installed to the portable folder, rather than a folder outside the Arduino IDE installation folder. It also stores preferences.txt in the portable folder. This means you can supply a .zip file that contains a copy of the Arduino IDE with the customized Arduino SAM Boards package already installed.

By default it will also set the sketchbook folder to be there but that can be changed via **File \> Preferences \> Sketchbook location** if you like.
> 1 votes

---
Tags: arduino-ide, c++, pwm, frequency
---


# Question
Title: I2C device responding, but data is nacked
I'm working on a project where I have to communicate to several devices over I2C using a Genuino 101. Now I'm trying to get data off the bus but `wire.available()` stays at 0, even though my trace clearly shows there's data being sent.

with the following timings

Because the wire is never available my readbuf will always be empty.

```
Rdbuf[0] is: 0 Hex is: 0
Rdbuf[1] is: 0 Hex is: 0

```

I'm using the following code to read from the I2C bus.

```
void i2cRead(unsigned char device, unsigned char memory, int len, unsigned char * rdBuf) {
  ushort memstart = memory;
  bool available = true;;
  while (len > 0 && available) {
    available = false;
    ushort blockSize;
    /*If the number of bytes is smaller than the block size, read that size*/
    (len < RD_BLCK_SIZE) ? blockSize = len : blockSize = RD_BLCK_SIZE;
    Wire.beginTransmission(static_cast<int>(device));
    //send i2c START command
    Wire.write(memory);
    //Write memory address
    Wire.endTransmission();
    //send i2c STOP command
    Wire.requestFrom(static_cast<int>(device), blockSize,true);
    //Request blockSize bytes from the device
    /* for every byte in the response add that byte to the read buffer */
    while (Wire.available() && (len != 0)) {
      available = true;
      rdBuf[memory - memstart] = Wire.read();
      memory++;
      len--;
    }
  }
}

```

I'm not quite sure what I'm doing wrong, any help would be much appreciated.

# Edit:

Below is an image of the current (minimal) setup. On the left there's the board with the ADC and multiplexer visible.

The third set of wires goes to my protocol analyzer.

# Answer
> 1 votes
Since this has been reopened i figured i'd post what the problem was, in the end and what i did to fix it.

it turns out, that even though the documentation of the Curie tells us to apply a level shifter for i2c communications, this level shifter is already in-place on the genuino 101.

skimming over the documentation of the 101, i had overlooked this. The fix, in the end was removing the level shifter.

# Answer
> 0 votes
You want to get the resulting code working, but you should do small minimal tests.

Start with the i2c scanner.
Connect only one sensor, and if it is detected, add more sensors.

How long are the wires, and what is the value of the pullup resistors ?
Perhaps you have too many modules with sensors, and the total pullup value it too low. The I2C bus is specified for maximum 3mA pull down current.

Do you have a more common 3.3V Arduino board ? For example the Arduino Due or the Arduino Zero ?

---
Tags: c++, i2c, 101
---


title: floor( 1.0f ) bugged?

text:
# Question
Title: floor( 1.0f ) bugged?
I just displayed the value for floor( 1.0f ) and surprisingly, it's 0.

Anyone knows about that? Is there a fix in libc expected any time soon?

I've been looking at libc::floor.s but it's a bit dodgy and 1) I don't want to break my other existing code and 2) don't have time for that so I'll add an epsilon at the moment (but that defeats the purpose of floor)...

Thanks for posting any fix or idea on how to bypass the issue.

# Answer
I ran this sketch:

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

void loop() {
  Serial.println(floor(1.0f));
}

```

It outputs "1.0"
> 5 votes

---
Tags: c++
---


# Question
Title: How does the microcontroller know which clock to use?
I had seen some tutorials on how to assemble an Arduino on a breadboard. They all just place the external crystal oscillator according to the circuit and then, just burn the bootloader and it starts working. According to my little knowledge the fuse bits have to be set before using the external clock.

My question is - How does the microcontroller know which clock to use internal or external? Is there any setting already in the bootloader that tells the microcontroller to use the external clock?

# Answer
> 8 votes
Burning the bootloader via the Arduino IDE also sets the fuse bits according to its configuration files.

---
Tags: avr
---


# Question
Title: Is there any way I can light up a candle with an Arduino?
I want to make a candle flame light up triggered by a microcontroller. Is it possible? I only want to light it up. Not turn it down. Moreover, this is for a one-time use so the candle burning down and becoming shorter is not a problem.

# Answer
A simple solution is too use nichrome wire which when a current is passes through it will heat up. You could wrap some of this wire around the wick on the candle and then power it either straight from your arduino or you could include a capacitor. This is much safer than some of the other methods which use potentially dangerous high voltages.

I tested the nichrome wire approach and it works! See following video clip. 2 Ohm resistance and 19V for 1 second. https://1drv.ms/v/s!AvcBubMtAczvifYZwoESAhUodOoqRA
> 2 votes

# Answer
If you have a circuit, you can switch it on and off using a microcontroller.

So what you need is a circuit which can light a candle. Have a look at these:

DIY arc lighter

CCFL Inverter becomes an Arc Lighter?

I predict your main problem will be dealing with the fact that candles get shorter as they burn.
> 1 votes

# Answer
Use two rods at either side of the candle, and engineer two motors to slide op and down these rods. Meccano kung-fu.

Use limit switches to detect the highest and lowest positions for both motors. Mount a LED on one motor, and a laser (5 mW red is plenty). From the bottom, have both motors ascend, until the LED can receive data transmitted by the laser. Yes, you can most certainly use a laser diode for Serial.print.

When at the right height, engage gasburner. You can use an LDR (shielded against light from the sides with heatshrink) to check if the candle has been lit - shortly after disengaging gasburner. You will need a reading prior to each ignition.

Let me know how that works out.
> 1 votes

# Answer
Functioning proof of concept.

Ni-chrome wire from hair dryer, approximately 2 Ohms, powered by 19 V for about 1 second. video of proof of concept. Lots to work out still, but this obviously can work.
> 1 votes

# Answer
Have you considered using a servo with a high torque, and a piezo-electric butane lighter?

The high torque would be required to push the lighter button as these tend to be rather stiff. Also, they do not always work on the first press and so a few attempts by the servo may be required. A Dynamixel AX-12A could do the job, but pricey, and could be overkill.

To save some money and time, measure the torque required to push the lighter button first and then get a servo/actuator to match.

Alternatively, use a gas oven lighter, again in conjunction with a linear actuator.
> 0 votes

---
Tags: arduino-uno, electronics
---


# Question
Title: Chinese CH340 Arduino Uno - Burning stand allone chip
I followed regular tutorial and I was able to burn boot-loader on my standalone ATM328 chip, but because I'm using this CH340 UNO and example is with regular UNO, I can't just remove the chip from there (CH340 UNO) and upload the code directly to my new standalone chip trough that board.

So what I tried was to use my FTDI cable, so I hooked up GND, RX, TX and VCC for my breadboard from there, but when I tried to upload a sketch I keep getting that message that programmer is not responding.

So I was wondering, is there a way to use this Chinese board to upload sketch to my new chip without de-soldering the chip from that board as option one.

As option two what I'm doing wrong with FTDI cable and why I'm not able to upload sketch directly like that? I saw some comments related to some auto-reset that needs to be implemented but I'm not following that part, not sure what I need to hookup extra for that...

UPDATE

Here's how my board look like:

**Update 2:**

**OK, everything works great now! I just needed one pull-up resistor for reset pin.**

Thanks everyone!

# Answer
> 0 votes
You said:

It just need a pull-up resistor for the reset pin!

---
Tags: ftdi, firmware
---


# Question
Title: How to send data from ThingSpeak to ESP-8266 (Arduino) using ThingHTTP?
I have made an Arduino kit that acts as a weather station. It sends sensors data (DHT11 & LDR) to the ThingSpeak web server.

Now I want to perform some actions based on the data on the ThingSpeak server (like if temperature exceeds a limit turn on the fan, etc).

I've searched and I found that there's a React app on ThingSpeak, which will trigger events if data exceeds some values.

The problem where I got stuck is that I want to send a signal from the ThingSpeak web server to my ESP8266 (Arduino) to turn on/off the device connected to a relay on Arduino.

I've figured out that there's also a ThingHTTP feature which sends HTTP requests. But I don't know how to send requests/signals to my kit to perform some actions.

I've already spent 2 months building this project, and now I'm stuck in the last part. Please give your valuable suggestions and solutions.

# Answer
> 1 votes
For sending information to/from Arduino best option is MQTT. It's lightweight and very simple to use.

While your Arduinos are using MQTT to send info and receive commands (like changing thresholds), your Web server has access to the same information in real time. You can format it and present it in any way you like, without any Arduino participation.

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


# Question
Title: Why does analog sensor "hum" when plugged into common ground?
I have the ground for an SD card module, LED, and piezo sensor all plugged into the same ground rail. When doing this I get a low "hum" in the piezo readings where instead of reading ground voltage (0) when there's no vibration, it cycles between 4 and 6.

However, when I switch the piezo's ground onto ground rail connected to different ground pin on my Arduino, the hum goes away. If I keep the piezo on original ground and move the SD card module's ground, the hum comes back.

I'm very new to electronics, so I'm wonder what's going on?

EDIT: Here's a diagram of the circuit.

# Answer
@Milliways remarked:

> You have a ground loop. Without seeing the actual physical layout it is impossible to determine the cause. This is a common problem in audio circuits. Fixing this is as much an art as a science. The usual solutions involve a single earthing point, earthing at one end only or in extreme cases common mode rejection techniques.
>
> Yours is an idealised diagram. These kind of problems are often related to the physical layout e.g. parallel wire runs. I agree that there appears to be nothing amiss. As I stated this is a black art. I would suggest separating the low level analog circuit from the rest of the wiring - i.e. DO NOT share any earth cabling with any other circuit. This appears to be what you have done when it worked. You should also minimise any other source of interference by using twisted wires to the sensor.
> 1 votes

---
Tags: analogread, sd-card, piezo
---


# Question
Title: Powering 3.3V Arduino and 12V peripherals from single 12V power supply?
Given:

* I have some home alarm peripherals (motion detectors, glass break sensors) which operate at 12V and draw a nominal current of 20mA when in alarm state.
* I have a Particle Photon (3.3V logic level) which will accept up to 5.6V on its VIN pin.
* I have a 12V @ 2A switching power supply.

Can someone describe to me an efficient circuit which would allow me to power all of the peripherals @ 12V and the Arduino (Particle Photon) at 3.3ishV?

I have on hand an LM7805 linear regulator, which I believe will work, but will be inefficient. I also have on hand a DC-DC step down converter (4.5V-28V IN, 0.8V-20V OUT @ 2A) but I am a novice and don't know how to use it for the scenario described here.

# Answer
@Majenko remarked:

Put 12V on the IN, connect the OUT to a volt meter, twiddle the knob till it reads 5V. Disconnect the volt meter. Connect it to the VIN of your photon.

@loopforever added:

For the 3.3V Arduino (Photon) current draw will not exceed 500mA. For the 4x 12V peripherals, if all were in an "alarm" state simultaneously, current draw will not exceed 110mA.

@Dampmaskin added:

Dropping 8.7V at 500mA wastes 4.35W so OK you're right, that is inefficient. A buck converter is probably the best approach then

@SDsolar added:

If you use a screw-terminal barrier block you can have both 12V and your lower voltages available at the same time
> 1 votes

---
Tags: power, voltage-level
---


title: How to drive a 4bit GLCD?

text:
# Question
Title: How to drive a 4bit GLCD?
i've got a huge (about 6 x 23 cm) graphics LCD. I used my multimeter and the datasheet the LCD driver chips (6 x KS0104 and 2 x KS0103) to get the pinout. It has the following pins: GND, M, FCS (not 100% shure), CL1, CL2, D0-3, VDD and a ground for the metal part.

My problem is that i dont know how i can drive a 4bit GLCD with an Arduino because i didnt found a library which can do this (e.g. OpenGLCD supports only the KS0104 which is an 8 bit controller)

# Answer
> 0 votes
@MikaelPatel answered your question in the comments:

> That gives a total of 54K pixels. And with 4-bit per pixel, two pixels in a byte, 27K byte to store a packed off-screen bitmap. Even an Arduino Mega would have too little memory for that. This might explain why there are no supporting library for that device.

---
Tags: library, lcd, display
---


title: Arduino UNO suddenly stops responding

text:
# Question
Title: Arduino UNO suddenly stops responding
I wrote this simple script to control a servo over serial comm -

```
#include <Servo.h>
Servo steeringServo;
char data = ' ';

void setup() {
  steeringServo.attach(9);
  Serial.begin(115200);

}

void loop() {
  if(Serial.available()){
    data = Serial.read();
  }

  if(data =='L'){
    steeringServo.write(50);
  }
  else if(data == 'R'){
    steeringServo.write(135);
  }
  else if(data == 'S'){
    steeringServo.write(90);
  }

}

```

It was working fine, I was sending values through a python script. I turned my Arduino off and after a while I come back and reconnect all stuff exactly the way it was, but now my Arduino isn't responding! I tried sending values through the serial monitor to the above sketch but nothing happens! I tried another code which takes values over serial comm and that didn't work as well. The Arduino just receives the values but doesn't do what its supposed to when it receives.

Not only this, I tried uploading the sweep sketch and that didn't work either. Everything is connected exactly the way it was when stuff was fine.

What has gone wrong with my Arduino?

**UPDATE**
The Arduino works fine if the values are sent through my script.

**UPDATE 2**
The Arduino works fine if the values are sent through puTTY.

# Answer
You never reset `data`. Every time you enter `loop`, data keep the last value you read.

You don't need to test `data` in every `loop`, only after you read something:

```
void loop()
{
    if(Serial.available()) {
        data = Serial.read();

        if(data =='L') {
            steeringServo.write(50);
        } else if(data == 'R') {
            steeringServo.write(135);
        } else if(data == 'S') {
            steeringServo.write(90);
        }
    }

```

I'm afraid that there are additional problems with the servo library: some implementations (looking at Servo-master) disable interrupts, which mess with your Serial port.
> 2 votes

---
Tags: arduino-uno, serial, sketch, python
---


# Question
Title: Pressing button stops listening on nrf24l01
I have been tinkering for 2 days to manage send and receive between 2 arduinos. My code is bellow:

Arduino 1:

```
#include <SPI.h>
#include <RF24.h>
#include "printf.h"
#define LED 2
#define RF_CS 8
#define RF_CSN 9
RF24 radio(8,9);
String datargb = "rgb: 000000005";
char chartosend;
char inchar;
String inradio;
int endchar = '~';
void check_radio(void);
void setup() {
  // put your setup code here, to run once:
Serial.begin(115200);
  printf_begin();
  radio.begin();
  radio.setRetries(15,15);
  radio.openWritingPipe(0x080C600C01LL);
  radio.openReadingPipe(1,0x080C600C71LL);
  radio.setPALevel(RF24_PA_MAX);
  radio.setAutoAck(true);
  radio.printDetails();
  attachInterrupt(0, check_radio, FALLING);
  radio.stopListening();
}

void loop() {
  // put your main code here, to run repeatedly:
int lnth = datargb.length();
  for(int i=0; i<lnth; i++){
      chartosend=datargb.charAt(i);

      while(!radio.write( &chartosend, sizeof(chartosend) )){}

      Serial.println("sent");
  }
  radio.write(&endchar,1);
}
void check_radio(void){

  bool tx,fail,rx;
  radio.whatHappened(tx,fail,rx);

  if(rx){
    Serial.println("interrupt!!");
radio.startListening();
    radio.read( &inchar, sizeof(inchar) );
    inradio+=inchar;
    Serial.println(inchar);
    if(inradio.endsWith("~")){
      Serial.println(inradio);

      if(inradio.startsWith("rgb: ")){
        analogWrite(6,inradio.substring(5,8).toInt());
        analogWrite(9,inradio.substring(8,11).toInt());
        analogWrite(5,inradio.substring(11,14).toInt());
      }
      inradio = "";
      radio.stopListening();
    }
  }
}

```

Arduino 2:

```
#include <SPI.h>
//#include <nRF24L01.h>
#include <RF24.h>
#include "printf.h"
//#include <RF24_config.h>
RF24 radio(8,10);
char data;
char chartosend;
char endchar = '~';
String inradio;
void check_radio(void);
String datargb = "To mounti tis manas tou nrf24";
void setup() {
  // put your setup code here, to run once:
  pinMode(9, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, INPUT);
  attachInterrupt(1, check_radio, FALLING);
  Serial.begin(115200);
  printf_begin();
  radio.begin();
   //radio.setRetries(2,15);
    // open pipe for writing
    radio.openReadingPipe(1,0x080C600C01LL);
    radio.openWritingPipe(0x080C600C71LL);
    radio.setPALevel(RF24_PA_MAX);
    radio.startListening();
    radio.printDetails();
    radio.setAutoAck(true);
}

void loop() {
  // put your main code here, to run repeatedly:
if(digitalRead(7)==HIGH){
  radio.stopListening();
  for(int i=0; i<28; i++){
      chartosend=datargb.charAt(i);
      while(!radio.write( &chartosend, sizeof(chartosend) )){}
      //Serial.println("sent");
  }
  radio.write(&endchar,1);

  while(digitalRead(7)==HIGH){}
  radio.startListening();
}
}
void check_radio(void){

  bool tx,fail,rx;
  radio.whatHappened(tx,fail,rx);

  if(rx){
    Serial.println("interrupt!!");
//radio.startListening();
    radio.read( &data, sizeof(data) );
    inradio+=data;
    Serial.println(data);
    if(inradio.endsWith("~")){
      Serial.println(inradio);

      if(inradio.startsWith("rgb: ")){
        analogWrite(6,inradio.substring(5,8).toInt());
        analogWrite(9,inradio.substring(8,11).toInt());
        analogWrite(5,inradio.substring(11,14).toInt());
      }
      inradio = "";
      //radio.stopListening();
    }
  }
}

```

Arduino 2 receives all data from ar1 but when I press the button attached to the pin 7 arduino 2 stops listening and only sends the first character of the string.

# Answer
> 0 votes
@Gerber remarked:

There is probably a death-lock situation where both arduino's are trying to send data the the other, while both aren't listening. So both are waiting for the other to ack. Like I said at your previous question. Why not send all rgb data in one packet. Also, there is no need to call `radio.stopListening`.

You send one char, and wait for and ACK. Then you send the next char and wait for an ACK. If the other unit doesn't process the message, the buffer will will up after 3 messages, and it will no longer send an ACK (because the buffer is full), and you while loop will hang

---
Tags: arduino-pro-mini, button, nrf24l01+
---


# Question
Title: ESP8266 (D1 mini) fails to upload sketches
My Setup: 3.3v LiFePo battery attached to G and 3.3 pins. Serial-USB connected.

Result: During the following code the blue on-board LED blinked rapidly for a few seconds then went off. I unplugged it to see if it was programmed but the Blink Sketch didn't run. Any help would be greatly appreciated.

```
Sketch uses 222,205 bytes (21%) of program storage space. Maximum is 1,044,464 bytes.
Global variables use 31,572 bytes (38%) of dynamic memory, leaving 50,348 bytes for local variables. Maximum is 81,920 bytes.
C:\Users\jhoxie\AppData\Local\Arduino15\packages\esp8266\tools\esptool\0.4.9/esptool.exe -vv -cd nodemcu -cb 115200 -cp COM3 -ca 0x00000 -cf C:\Users\jhoxie\AppData\Local\Temp\arduino_build_351972/Blink.ino.bin
**(Everything below this line was highlighted in red)**
esptool v0.4.9 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to nodemcu
    setting baudrate from 115200 to 115200
    setting port from COM1 to COM3
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    espcomm_upload_mem
    setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
Uploading 226352 bytes from C:\Users\jhoxie\AppData\Local\Temp\arduino_build_351972/Blink.ino.bin to flash at 0x00000000
    erasing flash
    size: 037430 address: 000000
    first_sector_index: 0
    total_sector_count: 56
    head_sector_count: 16
    adjusted_sector_count: 40
    erase_size: 028000
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    setting serial port timeouts to 15000 ms
    setting serial port timeouts to 1000 ms
    espcomm_send_command: receiving 2 bytes of data
    writing flash
................................................................................ [ 36% ]
................................................................................ [ 72% ]
..............................................................                   [ 100% ]
starting app without reboot
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2 bytes of data
closing bootloader
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete

```

# Answer
Thank you for your input. Especially the tip on connecting the battery while connected to usb \[tttapa\] I finally got it to work by changing the baud rate and messing around with the settings(i.e. board in IDE). I believe I got it to work with the "WeMos D1 R2 & Mini" board whereas I was using the generic esp8266 board.
> 1 votes

---
Tags: esp8266, uploading
---


# Question
Title: Arduino Mega 2560 LED is dim when powered from digital output
My circuit is a simple one, I am using an arduino atmega 2560. One 5mm red LED connected in series with a 150 ohm resistor. If I didn't make some kind of goof, a red LED has a voltage drop of 2 volts and operates at 20 ma. So my calculations were, 5-2=3volts. 3V/150=20 mA. So I put a 150 ohm resistor. My code to control it is the following:

```
int red = 48;

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

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

```

When I run the code the red LED is dimly lit, when connected to the 5V on the board it lights brightly. When I measured the voltage between pin48 and ground I got 1.7 volts. When connected directly to the 5V and GND the voltage between them is 4.95V. Measuring a pin with nothing connected set at HIGH results in a 4.99V reading. Is my board malfunctioning or have I missed something?

# Answer
> 1 votes
The `pinMode()` arguments are backwards. As it is the LED is powered through the input pullup resistor, which is about 20-50kohm.

---
Tags: led
---


title: Space needed for local String variable

text:
# Question
Title: Space needed for local String variable
I tried to run this code on my Arduino Uno clone (which has no function so far and is a shortend version of my programm):

```
String rules [16][5] ={
   {"B0 B5", "", "", "cs S0", "", },
   [...]
};

void setup() {
  Serial.begin(9600);
  String foo = "bar";
  Serial.println(foo);
}

void loop() {
}

```

I left the `rules` array out, but it is quite big. It isn't used yet, but it contains rules how to react on certain situations (which should be used later).

As the Arduino IDE gives the following after complilig:

```
Sketch uses 4316 bytes (13%) of program storage space. Maximum is 32256 bytes.
Global variables use 1174 bytes (57%) of dynamic memory, leaving 874 bytes for local variables. Maximum is 2048 bytes.

```

When I run this sketch there is nothing on the serial monitor. If it works, there should appear `bar`, but it does not. The Arduino sends only a linebreak over the serial, but no text.

When I remove some characters from that array so that there are about 900 bytes the script works and prints `bar` to the serial monitor.

So, aren't 874 bytes not enough to store a three-character string? Why does it need 900 bytes to store such a short string?

# Answer
You are requesting 80 String objects.

Each String object allocates memory to store its data. When you provide a string constant that string constant data's length is used for the allocated data size (including the NULL character at the end), and the string constant data copied in.

On top of that you have a bunch of other data that is needed for the String class to do its work. The total size of a String object is 6 bytes.

So the memory you need for your array of Strings can be calculated as:

* Let C be the total number of characters in all the string constants
* Let N be the number of String objects in the array
* Let T be the total number of bytes.

T = N * 6 + C + N

With no string constant data that would be:

```
T = 80 * 6 + 80

```

That's 560 bytes already, before you even start thinking about putting in the string constant data.

Also you may like to add to that the fact that the compiler *may* (though I am not certain on this) be also copying the string constants into RAM first because they aren't forced into PROGMEM with the F() macro.

So since you only have 2KiB of RAM to begin with, and a quarter of that is instantly gobbled up with your array, you can see how things might not be too happy.

Oh, and the String's internal storage is allocated at run time, not compile time, so the compiler can't know that it'll overflow - only when you run the program will it overflow and things go horribly wrong.

So you need to ask yourself "Why do I even want an array of String objects?" and the answer is most certainly: "Under no circumstances do you ever want an array of String objects". In fact I am a strong advocate of *never* using String objects ever, for any reason whatsoever.

If your data is constant there is absolutely no reason to store it as String objects. It's constant. It should remain constant. Copying it into a String object means it's no longer constant and wastes many many resources.
> 2 votes

---
Tags: arduino-uno, programming, array, variables, sram
---


# Question
Title: How to reset an arduino while being able to know which button has been pressed?
## Context

I keep the board in sleep mode and want to wake it with different buttons. I need to know which button has been pushed on boot.

In the following schematic, **SW-R** is actually used to reset the board.

If I hold **SW-D5** or **SW-D6** *while* pushing **SW-R**, the code can detect which button I pushed.

## Problem

I don't want to have to push 2 buttons at the same time and, *being new to electronic*, I don't know how to wires things up so it reset and set a pin to HIGH simultaneously.

## Question

How can I reset the board and trigger a HIGH on an IO corresponding to a button while it boot?

Considering the HIGH only need to be hold for less than a second, can it be simply achieved with capacitors and/or transistors? If so, how? Or any other suggestion?

simulate this circuit – Schematic created using CircuitLab

The actual code example only contain 1 button but I'll have many.

```
#include <Spi.h>
#include <Arduino.h>
#include <ESP8266WiFi.h>

int buttonPin = D5;

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(BUILTIN_LED, OUTPUT);

  int buttonValueAtBoot = digitalRead(buttonPin);
  Serial.begin(115200);
  Serial.println();

  if (buttonValueAtBoot == HIGH) {
    // I want to trigger this code pushing only 1 button
    // should also work with many buttons
    Serial.println("button was pressed");
  }

  digitalWrite(BUILTIN_LED, HIGH);
}

void loop() {
  delay(5000);
  ESP.deepSleep(0);
}

```

# Answer
Just found that I can change pins behavior. Inverting things a little bit, I can get my pins to work as LOW instead of as HIGH.

That way, I only need 1 button to trigger a reset and change pin status. Plus, grounding the reset is done temporarily because of the capacitor, which is what I need.

Here is the new schema

simulate this circuit – Schematic created using CircuitLab

## New code

```
#include <Spi.h>
#include <Arduino.h>
#include <ESP8266WiFi.h>

int buttonPin = D5;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(BUILTIN_LED, OUTPUT);

  int buttonValueAtBoot = digitalRead(buttonPin);
  Serial.begin(115200);
  Serial.println();

  if (buttonValueAtBoot == LOW) {
    Serial.println("button was pressed");
    digitalWrite(BUILTIN_LED, HIGH);
  }

  // Avoid problem when the button is hold
  while (digitalRead(buttonPin) == LOW) {
    // wait before going to deepsleep
    // or the capacitor will be drained
    delay(1);
  }

  Serial.println("going to sleep");
  ESP.deepSleep(0);
}

void loop() {
}

```
> 0 votes

---
Tags: button, reset, switch, system-design
---


# Question
Title: Arduino pro mini not compiling after changing fuse to 128khz
I used Arduino UNO as ISP to change the fuse setting of Arduino Pro Mini. Using avrdude cmd, I successfully changed it to 8MHz setting. Due to curiosity, I decided to try changing it to 128kHz. But that ends up me being unable to further program it. The Pro Mini still works but just cant change fuse through avrdude cmd, burn bootloader and upload. Does 128kHz really leave atmega328p like that?

On one computer, the below error appears.

```
avrdude: stk500_recv(): programmer is not responding

```

On another computer, the below error appears

```
avrdude: Expected signature for ATmega328P is 1E 95 0F
Double check chip, or use -F to override this check
Wrong microcontroller found. Did you select the right board from the Tools > Board menu?

```

There are actually more errors because I trial and error different ways to solve it, i.e Nick Rammon's Atmega\_Board\_Programmer, cmd command with varying parameters (baud rate, programmer), inserting capacitor on UNO. But I dont remember every one of them because the `not in sync:resp=0x..` differs from time to time

There is one method which I have not try, high voltage programming mode. I would try it out if it was detachable but atmega328p on Pro Mini is SMD. Is it possible to high voltage program on Pro Mini? Ultimately I am stuck.

Ignoring what I have done, I would once again like to try out every method you guys recommend. Hopefully everything can be step by step and the thing I want to know most is the setting of '`Board`', '`Processor`' and '`Programmer`' in Tools.

I would give my best response possible to you guys who is willing to help me out. Thank you

# Answer
> 0 votes
Thanks to Ignacio, I found an answer. If anyone ever burn the fuse to 128kHz, got stuck there and wish to revert back to normal speed, download this sketch. Note that I am using Arduino UNO as ISP and Arduino Pro Mini as the target board

If you read the comment in the sketch carefully, you will see `How to proceed:`. The below is what I did.

1. Remove any pin connection on Arduino UNO
2. Plug Arduino UNO to PC
3. Open the downloaded sketch and uncomment `#define LOW_SPEED`
4. On Arduino IDE `Tools` menu, make sure settings are: `Board: Arduino/Genuino UNO`, `Programmer: AVRISP mkII` and upload the code
5. After uploading, unplug Arduino UNO from PC
6. Connect Pro Mini to UNO, making sure there is capacitor between reset and ground pin on UNO
7. Plug Arduino UNO to PC
8. Open CMD and type `avrdude -P com5 -b 19200 -c avrisp -p m328p -U lfuse:w:0xFF:m -U hfuse:w:0xDA:m -U efuse:w:0x05:m`. Change `com5` to your UNO com port. The fuse are default Pro Mini setting.
9. You should see `avrdude: safemode: Fuses OK <E:05, H:DA, L:FF>`. Unplug UNO from PC
10. Remove pin connection on Arduino UNO
11. Plug Arduino UNO to PC
12. Now comment `#define LOW_SPEED` and upload the code.
13. After uploading, unplug Arduino UNO from PC
14. Connect Pro Mini to UNO like before and plug to PC
15. On Arduino IDE `Tools` menu, make sure settings are: `Board: Arduino Pro or Pro Mini`, `Atmega328 (5V, 16MHz)`,`Programmer: Arduino as ISP`
16. Burn Bootloader and it is complete

Apologies for lengthy and repetitive steps. Many solutions skip many steps which leaves me in doubt. So I do not want that to happen to other people. Though I won't go into the details of setting up avrdude CMD in step 8.

# Answer
> 0 votes
At that clock rate each programming clock cycle must be at least 3 system clock cycles, which means that the programmer either must use a *much* slower SPI rate, 42kHz or less, or it must provide an external pulse train to clock the device manually. Modify the ArduinoISP sketch to either use a slower clock or to provide an external clock to the target.

---
Tags: atmega328, arduino-pro-mini, avrdude, compilation-errors
---


# Question
Title: How to keep a pin LOW for a small amount of time after pushing a button and while device is booting?
## Context

I keep the board in deepsleep mode and want to wake it with different buttons. I need to know which button has been pushed on boot. The board is immediately put back in deepsleep mode afterward.

I've been able to reset the board and pull a pin LOW at the same time. (see circuit below). The reset pin is momentarily pulled low so it reset the board effectively.

I'm not an electronic engineer, just a hobbyist, so any other method to do something are always welcome.

## Problem

With the actual code/circuit, I *need* to hold the button until the device boot up so it can detect button was pushed but **I would like to be able to just push the button quickly** instead of having to hold it.

## Question

How to add some sort of delay that will "hold" the **SW-D5** button until the board boot?

Or anything that keep my D5 pin LOW for a short amount of time after the button has been pushed?

I think something in the range of 500 to 1000 milliseconds would be enough.

## My actual circuit

simulate this circuit – Schematic created using CircuitLab

## My code

```
#include <Spi.h>
#include <Arduino.h>
#include <ESP8266WiFi.h>

int buttonPin = D5;

void setup() {
  // Read pin value as soon as possible after boot
  pinMode(buttonPin, INPUT_PULLUP);
  int buttonValueAtBoot = digitalRead(buttonPin);

  pinMode(BUILTIN_LED, OUTPUT);
  Serial.begin(115200);
  Serial.println();

  if (buttonValueAtBoot == LOW) {
    Serial.println("D5 was pressed");

    // Do something useful here like making an HTTP request.
    digitalWrite(BUILTIN_LED, LOW);
  }

  // Avoid problem when the button is being hold
  while (digitalRead(buttonPin) == LOW) {
    // wait before going to deepsleep
    // or the capacitor will be drained
    delay(1);
  }

  Serial.println("going to sleep");
  ESP.deepSleep(0);
}

void loop() {
}

```

# Answer
A simple RC network should do the job.

simulate this circuit – Schematic created using CircuitLab

Ok. A quick explanation of what we have here. C1 and R1 are the same as you have at the moment for your reset circuit. R1 is the existing pullup resistor in the Wemos. R3 recharges the C1 when the button is released. It's effectively the pullup for the button.

D2 is to separate the two parts of the circuit. It prevents R3 from charging the capacitor C2.

The magic happens with C2 and R2. Pressing SW1 discharges C2, and the GPIO goes low. When you release SW1 C2 charges up again through R2. When the voltage across C2 rises to the VIH of the GPIO the GPIO will go high.

D1 is to protect the GPIO from the negative pulse you can get from C2 as it discharges.

Here's a simulation. Top line is the GPIO, bottom is RESET.

VIH for the ESP8266 is 0.75VIO, so 75% of 3.3V, or 2.475V.

The charge time of the capacitor C2 is calculated as T=RC, where T is the time taken to charge up to 63% of the supply voltage (2.08V)

With the shown values the time taken to rise to 63% of 3.3V will be 10,000 x 0.0001 seconds, or 1 second. So to get to 75% it will take a little longer than 1 second. 75% is about 1.4T, so if T is 1 as in the above equation then it will take 1.4 seconds (1 * 1.4) to rise enough for the GPIO to register as HIGH.

Note these times are all from the moment you *release* the button. Reset has already happened before that time.

Also the internal pullup of the GPIO should be **disabled** otherwise it will also charge the capacitor and the charge time will be reduced. Since you don't know that resistor value it then becomes impossible to calculate what the charge time will be. Simplest to just disable it and only use the external resistor R2.
> 2 votes

---
Tags: esp8266, pins, reset, capacitors
---


# Question
Title: Limit to number of sensors attached to Arduino
Is there any limitation on how many sensors can be attached to one Arduino board? I am making elderly smart ban and I want to use GPS, GSM, gyroscope, pulse sensor, temperature sensor and I2C OLED. Right now I have only gyroscope, pulse sensor and GPS connected to Arduino Uno but I would like to add more stuff and also I am considering using Arduino Nano or only ATmega328P chip for finished product. My main concern is power.

# Answer
> 1 votes
There is no answer that can be given to you that is "correct". However, there are things for you to consider in your design process:

1. Can you fit all the code in flash, and the required variables in RAM?
2. Does the chip have all the IO you need, and can you use the required internal / interfacing peripherals in the right combinations to satisfy your requirements
3. Do the devices fit within your power budget (battery capacity, required run-time, power regulation efficiency).

The Arduino is just a component. It belongs in a circuit, and that circuit is what determines everything else. The ATMega328P has certain power requirements, as do all the other components in your circuit. It is up to you to design the right power system to provide that power with the right efficiency and power saving options (switching off circuit segments when not needed to save power), etc.

For prototyping and experimenting the Arduino provides a rudimentary power supply which is wildly inefficient. Not recommended for any battery powered scenario or any high current usage.

---
Tags: arduino-uno
---


# Question
Title: Error declaring two-dimensional array: 'x' was not declared in this scope
I'm trying to declare a 2-D array where each letter in the alphabet is keyed to a corresponding LED in my LED strip. But when I try to declare the array, Arduino flags the values and gives me a "not declared in this scope" error. I have no idea why. Am I missing a library or is it incorrect syntax?

Some of the places I've looked say to make sure it's declared globally. I've declared the array before void setup but it still doesn't work. Here's what I've got before void setup:

```
#include <Adafruit_NeoPixel.h>

#ifdef __AVR__
  #include <avr/power.h>
#endif

#define PIN 6

// Parameter 1 = number of pixels in strip
// Parameter 2 = Arduino pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
//   NEO_RGBW    Pixels are wired for RGBW bitstream (NeoPixel RGBW products)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(50, PIN, NEO_GRB + NEO_KHZ800);

//Create a 2-D array to store each letter and
//its corresponding LED number
char charKey[26][2]={
  {a, 0},
  {b, 2},
  {c, 4},
  {d, 6},
  {e, 8},
  {f, 20},
  {g, 18},
  {h, 16},
  {i, 14},
  {j, 12},
  {k, 10},
  {l, 22},
  {m, 24},
  {n, 26},
  {o, 28},
  {p, 30},
  {q, 40},
  {r, 38},
  {s, 36},
  {t, 34},
  {u, 32},
  {v, 42},
  {w, 44},
  {x, 46},
  {y, 48},
  {z, 50}
};

```

# Answer
Without quotes, a, b, c etc. are just names. You didn't declare any of them, so the compiler complains. Put single quotes around the letters to let the compiler know that they are char literals.
> 0 votes

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


title: Arduino industrial 101 digital pins

text:
# Question
Title: Arduino industrial 101 digital pins
I don't see anything that has been clear about which digital pins map to which physical ones. If someone could point me in the right direction it would be a big help.

For exampleThrough trial and error, i've found that if i set digital pin 3 in the Arduino IDE, it is mapped to D0 on J6, but surely this is documented somewhere?

# Answer
I found what i was looking for on the arduino github repository.

Arduino/hardware/arduino/avr/variants/
> 0 votes

---
Tags: pins, 101
---


# Question
Title: Can I control a cellphone's lcd (+touch screen)?
I had an Xperia txt pro just laying around and tried to revive it. I burned it like an idiot using 5v in the battery pins by accident :/ So I decided to read it apart and got to the lcd, can I use my Arduino Mega to control it? Bc I have no idea how to use it.

These are the pins

# Answer
> 3 votes
No. For two reasons:

1. You will struggle to find the pinout of the TFT (or even identify the model). It will have most likely been custom made for the phone.
2. The Arduino doesn't have a GPU to drive it. Arduinos need a TFT with built in GPU since they lack the resources to drive one directly.

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


# Question
Title: A/C doesn't detect IR codes sent from Arduino
I have an IR receiver and an IR LED I got from a kit (I don't have the datasheets for them).
I uploaded an Arduino sketch to record my A/Cs IR codes. Those were NEC encoded 32bit integers.
After recording the codes, I tried retransmitting them. The A/C unit failed to detect the signals.
Troubleshooting a bit, I sent the code from the Arduino the receiver sketch from the previous step - it received them successfully.

All the above steps used the IRRemote Arduino library

The question is, what could explain this behavior? A few possibilities I had in mind:

1. IR frequency. Could it be that the detection circuit worked with the default settings but transmitting wouldn't?
2. IR wavelength. Any chance the A/C side doesn't detect my IR pulses at all?
3. Decoding/Encoding of the NEC protocol in IRRemote. If there is no standard for the NEC protocol, the Arduino and A/C implementation might be a little different.

# Answer
Hi i have done the same thing. I was using this to get the AC codes for the GREE AC. I find it with two weeks struggle and a forum called AnalysIR. If you find any issue in this code below or method let me know.

AC codes are usually long and those doesn't come right with the code which you used above so i am giving you the sample code to run in the Arduino sketch so that you can test.

```
   #define LEDPIN 13
  //you may increase this value on Arduinos with greater than 2k SRAM
  #define maxLen 800

       volatile  unsigned int irBuffer[maxLen];
       //stores timings - volatile because changed by ISR
       volatile unsigned int x = 0;
       //Pointer thru irBuffer - volatile because changed by ISR

     void setup() {
     Serial.begin(115200); //change BAUD rate as required
     attachInterrupt(0, rxIR_Interrupt_Handler, CHANGE);
    //set up ISR for receiving IR signal
     }

 void loop() {
   // put your main code here, to run repeatedly:

   Serial.println(F("Press the button on the remote now - once only"));
    delay(5000); // pause 5 secs
  if (x) { //if a signal is captured
digitalWrite(LEDPIN, HIGH);//visual indicator that signal received
Serial.println();
Serial.print(F("Raw: (")); //dump raw header format - for library
Serial.print((x - 1));
Serial.print(F(") "));
detachInterrupt(0);//stop interrupts & capture until finshed here

for (int i = 1; i < x; i++) { //now dump the times
  if (!(i & 0x1)) Serial.print(F("-"));
  Serial.print(irBuffer[i] - irBuffer[i - 1]);
  Serial.print(F(", "));
                     }

   x = 0;
   Serial.println();
   Serial.println();
   digitalWrite(LEDPIN, LOW);//end of visual indicator, for this time
   attachInterrupt(0, rxIR_Interrupt_Handler, CHANGE);//re-enable ISR for            receiving IR signal
        }

      }

  void rxIR_Interrupt_Handler() {
    if (x > maxLen) return; //ignore if irBuffer is already full
     irBuffer[x++] = micros(); //just continually record the time-stamp of signal transitions

    }

```

Once this is done you will get the right code to send it to the AC.

**A little Tricky part**

once you will receive the codes of raw values you will have to little modify it for example i got the raw values and i converted it into the array.

**What i received for example** Raw (16): -27750, 4464, 696, 1612, 692, 516, 688, 516, 688, 1620, 692, 512, 692, 1612, 696, 1612, 692, 512, 692, 516, 688, 1616, 696, 1612, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 1612, 692, 1612, 692, 516, 688, 516, 692, 516, 688, 516, 688, 516, 692, 1612, 692, 516, 688, 1620, 688, 516, 688, 520, 684, 1620, 660, 544, 664, 19960, 628, 1680, 628, 1676, 628, 580, 628, 1676, 628, 580, 624, 580, 628, 576, 628, 580, 628, 584, 620, 576, 628, 580, 628, 576, 628, 576, 628, 580, 624, 1680, 628, 580, 624, 580, 628, 580, 624, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 1680, 624, 580, 628, 1676, 628, 1680, 628

**To Convert the above raw values into array remove first value which is -27750 and put 3800 instead of that.** Below is the array sample.\**

unsigned int data\[\] = {3800, 4464, 696, 1612, 692, 516, 688, 516, 688, 1620, 692, 512, 692, 1612, 696, 1612, 692, 512, 692, 516, 688, 1616, 696, 1612, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 1612, 692, 1612, 692, 516, 688, 516, 692, 516, 688, 516, 688, 516, 692, 1612, 692, 516, 688, 1620, 688, 516, 688, 520, 684, 1620, 660, 544, 664, 19960, 628, 1680, 628, 1676, 628, 580, 628, 1676, 628, 580, 624, 580, 628, 576, 628, 580, 628, 584, 620, 576, 628, 580, 628, 576, 628, 576, 628, 580, 624, 1680, 628, 580, 624, 580, 628, 580, 624, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 1680, 624, 580, 628, 1676, 628, 1680, 628, };

**Now sending these values to the IR transmitter use this code below.**

```
      #include<IRremote.h>
       IRsend irsend;
       int KHz = 38;                    // default frequency

      unsigned int data[] = {3800, 4464, 696, 1612, 692, 516, 688, 516, 688, 1620, 692, 512, 692, 1612, 696, 1612, 692, 512, 692, 516, 688, 1616, 696, 1612, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 1612, 692, 1612, 692, 516, 688, 516, 692, 516, 688, 516, 688, 516, 692, 1612, 692, 516, 688, 1620, 688, 516, 688, 520, 684, 1620, 660, 544, 664, 19960, 628, 1680, 628, 1676, 628, 580, 628, 1676, 628, 580, 624, 580, 628, 576, 628, 580, 628, 584, 620, 576, 628, 580, 628, 576, 628, 576, 628, 580, 624, 1680, 628, 580, 624, 580, 628, 580, 624, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 1680, 624, 580, 628, 1676, 628, 1680, 628,
        };

    void setup()
   {
     Serial.begin(9600);
     irsend.enableIROut(38);
   }

    void loop()
   {

    for (int i=0; i<1 ; i++){
    irsend.sendRaw(data, sizeof(data) / sizeof(int),38 );
    delay(40);
          }

 }

```
> 1 votes

---
Tags: ir, home-automation
---


# Question
Title: Can't upload arduino code on the board due to some programmer issues
As I connected my arduino-uno board and made sure of the "Board" selected, and the "Port" selected as well. There is a problem while uploading, I tried updating the arduino IDE, reinstalling all the arduino drivers, I tried to borrow a new arduino board from a friend and I am 100% sure it is working.

The message I get from the IDE:

```
Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x1d
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x1d

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

```

Thanks in advance!

# Answer
I faced the same problem while uploading.

avrdude: stk500\_recv(): programmer is not responding avrdude: stk500\_recv(): programmer is not responding

To solve that I changed my port to another USB port and I selected the particular port, Its uploaded successfully. But it's in MacBook not in Windows.

Try this once, by changing the port.
> 1 votes

# Answer
Try changing baud rate to 9600.

Another thing to check is the chip your Uno has. My Uno has the atmega328. Make sure you select that board.
> 0 votes

---
Tags: arduino-uno, arduino-ide
---


# Question
Title: How to determine which pins_arduino.h file is used?
For some applications I need access to the registers that control the output/input and high/low state of pins. For example pin 10 on a adalogger is `PORTB` with a mask of `_BV(6)`. This information can be found in `pins_arduino.h`. For some boards many variants get installed. I turned on verbose compiling and looked through the output there as well as looking through `boards.txt` and `platform.txt`. In that output I see an include to a directory with a `pins_arduino.h` file but there is nothing in that file but a definition for `BUILTIN_LED`.

When I run a function like `digitalWrite(13,HIGH);` how does it know which registers to use for pin 13? Since my board has this pin, and `digitalWrite(13, HIGH);` makes an LED light up ... it's working.

# Answer
> 3 votes
In the boards.txt file for the core in question you have a line for each board:

```
xxxx.build.variant=yyyy

```

where yyyy is the name of the folder in variants for the board.

For instance, the Uno, has:

```
uno.build.variant=standard

```

which relates to:

```
variants/standard

```

with the `pins_arduino.h` file in it for that board.

---
Tags: arduino-ide, pins, port-mapping
---


# Question
Title: Throughput and BER test with nRF24L01+ radio and Teensy microcontroller
I am trying to modify the example given in the this page to a basic throughput and BER test with two nRF24L01+ and Teensy 3.0 modules.

I want to modify the nrf24l01\_send\_string example in a way that I can remove the powerUp powerDown and delay and transmit the next packet purely based on the ACK received from the receiver. The problem is RF24 class does not seem to have a method to transmit ACK (not ACK+Payload) and the datasheet does give any information on the structure of the ACK message. The example works when powerUp and powerDown are removed, but I need to modify it to measure throughput by removing the delay.

# Answer
@Gerben remarked:

> You can't send the ACK manually. The module itself sends the ACK automatically (if enabled that is), once it receives the package. This way the sending module only need to be listening for the ACK for the shortest amount of time, reducing power usage. To attach data to the ACK package you need the writeAckPayload function. But you have to prepare this before any package is received
> 1 votes

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


# Question
Title: Unable to compare two integer values in Arduino Mega
I wrote Arduino code (code is given at the end) to compare two integer values. The steps I took was:

1. Give input to DC motor to rotate it using serial port. Input was: `G254`
2. Then I store it in `XX` string and using `XX.remove(0,1);` I removed `G` from `G254`. `XX` now become `254`
3. Then I used `Serial1.println("P");` to get position of motor after rotation. I stored this value in `ZZ` string using `String ZZ = Serial1.readString();`. `ZZ` will be `P254`.
4. And using `XX.remove(0,1);` I removed `P` from `P254`. `ZZ` now become `254`.
5. Now, I convert both `XX` and `ZZ` into integer from string using `XX.toInt(); ZZ.toInt();` .
6. After that, I compare both values using:

> ```
> if (XX == ZZ)
> {
>     Serial.println("BOTH ARE EQUAL");
> }
> else
> {
>     Serial.println("BOTH ARE NOT EQUAL");
> }
>
> ```

But it shows `BOTH ARE NOT EQUAL` which is not true. I want to know where I'm making a mistake?

Code I used:

```
void setup() {
    // put your setup code here, to run once:
    Serial.begin(9600);
    Serial1.begin(9600);

    pinMode(13, OUTPUT);
}

void loop() {
    // put your main code here, to run repeatedly:
    if (Serial.available() > 0)
    {
        Serial1.println(Serial.readString());

        String  XX = Serial1.readString();
        XX.remove(0,1);

        Serial1.println("P");

        String  ZZ = Serial1.readString();
        ZZ.remove(0,1);

        XX.toInt();
        ZZ.toInt();
        Serial.println(ZZ);
        Serial.println(XX);
        Serial.println(typeof(XX));

        if (XX == ZZ)
        {
            Serial.println("BOTH ARE EQUAL");
        }
        else
        {
             Serial.println("BOTH ARE NOT EQUAL");
        }
    }
}

```

Thanks.

# Answer
> 0 votes
You should use

```
 int x = XX.toInt()

```

Without the int x = part, the string is converted and the result (the integer) is not used.

Also comparing strings should be done with the strcmp function. The problem is that if you compare two strings, you compare the pointers to those strings and two strings can have equal texts but (probably) not equal addresses.

# Answer
> 0 votes
There are several issues with your code.

First, never assume that Serial.readString() will returns you a complete String; it can time out and return nothing, or return just an incomplete value.

`Serial.available() > 0` doesn't imply that the reading is complete ...

Second, Serial.readString() returns everything, include the possible \r\n at the end of the string.

Here is a little sketch that shows a `toInt` implementation fit for you case. Run this sketch to see how it works.

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

void loop() {
  String x = Serial.readString();
  Serial.print(x); Serial.print("=");
  Serial.println(myToInt(x));
}

int myToInt(String x) {
  char* p = x.c_str();
  int val = 0;

  while(*p != 0 && !isdigit(*p)) {
    p++;
  }

  while (*p != 0 && isdigit(*p)) {
    val = val * 10 + (*p - '0');
    p++;
  }
  return val;
}

```

---
Tags: serial, arduino-mega, data-type
---


title: Pull EN pin of regulator to ground

text:
# Question
Title: Pull EN pin of regulator to ground
I have an Adafruit Huzzah Feather with ESP8266 board, but I think my question will apply to most all boards (as most all have an onboard regulator). Most regulators have an Enable pin (EN) as does my Adafruit board. Apparently, I can shut down the regulator by pulling this pin low. I have a specific application where an external device will provide a high signal to me when I want the device to turn on, otherwise, I want it off at all times. So, what I have is a 1k resistor pulling the EN pin low, to ground. I tried other values 10-20k but they did not pull enough low to shut down the regulator. For example, 20k pulled me down from 3.3V to 2.6V but the regulator stayed on. On the other hand, 1k pulls me down to .3V on the EN pin and this shuts it down.

Then, when the external device gives me the high signal, which I have also tied to the EN pin, this will pull it back up and turn on the regulator.

This seems to be working just fine, but I wanted to ask if this sounds reasonable (I know this is a general question but I want to know if there is a better way). A specific, related question would be am I wasting too much power by using a 1k resistor when powered up or pulled high since some of the supply current will be dumped via the 1k resistor to ground.

UPDATE: In looking at the schematic on the Adafruit site, it appears that they have pulled EN to the input via a 10k resistor. So, I am fighting that which is probably why values over 10k do not pull it down enough to turn off. If I was doing the board design, I would have reversed this and pulled EN low by default but this is not the case when using the off the shelf board. So, I guess any value below 10k should work, like 4.7k? I guess I could also remove their pull up if I wanted to get really crazy. Thoughts on all of this?

Thanks!

# Answer
> 1 votes
A better solution would be to use a PNP transistor to control the EN pin. A PNP is ON when the input to it is LOW (or lower than the collector minus 0.7V, that is).

Take this circuit, for instance:

simulate this circuit – Schematic created using CircuitLab

When the GPIO is HIGH the transistor Q1 is turned off (GPIO \>= VCC-0.7). Also if the GPIO pin is disconnected it is turned off because R3 pulls it up to VCC.

Set the GPIO LOW and Q1 turns on since the base is now lower than VCC-0.7V. With Q1 turned on it connects the EN pin to ground, so it becomes LOW.

If you replace the PNP with an NPN (there's more chance you have one in your bits box) you can basically invert the logic:

simulate this circuit

Now when the GPIO is LOW or pulled *down* by R3 Q1 is off and EN is pulled HIGH. Set the GPIO HIGH and Q1 turns on and connects EN to ground setting it LOW.

In both these scenarios the EN pin defaults to HIGH. If you want it to default to LOW until you activate the GPIO pin (i.e., during bootloader operation when the GPIO is in INPUT mode) you can reverse R3 so it becomes a pull-down (for the PNP) or a pull-up (for the NPN).

---
Tags: power
---