# Question
Title: compilation terminated. exit status 1 error compiling for board arduino/genuino uno
hi i have done this code for my uno R3 and i cant upload it any suggestions

```
#include"DHT.h"
#define DHTPIN 8
#define DHTTYPE DHT11
DHT dht( DHTPIN,DHTTYPE);
const int ledPin=13
int piesoPin=9
void setup(){
  serial.begin(9600);
  pinMode(ledPin,OUTPUT);
  pinMode(piezoPin,OUTPUT);
  delay(5000);
}
void loop(){
  int t=dht.readTemperature();
  int h=dht.readHumidity();
  Serial.print(t);
  if(t>26){
    digitalWrite(ledPin,HIGH);
    digitalWrite(piezopin,HIGH);
    {TONE(9,3047,400);
    delay(1000);
    noTone(8);
    delay(100);
    }
    delay(1000);
    Serial.print("ON T=");
  }
  else(digitalWrite(piezoPin,LOW);
  digitalWrite(LEDpIN,LOW);
  Serial.print("OFF,T=");
  }}

```

# Answer
Two errors I see is a typo and missing semicolons.

```
const int ledPin=13
int piesoPin=9

```

Should be

```
const int ledPin=13;
int piezoPin=9;

```

Also I see a unnecessary { and } but this cannot cause a compilation error.

Check the delays, when the temperature is higher than 26 degrees you have more delay than when not, maybe this is intended, maybe not.

However, you probably typed over the code, so maybe there are more errors, please add the exact error text and line in your question.
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: passing arrays via function returns wrong values
I am trying to use the values of an array in some other function, but when I return via a function the contents is wrong.

This is the external function file I'm trying to use

```
#include "Arrayreturner.h"

Arrayreturner::Arrayreturner() { }

void Arrayreturner::setResults(int* res, int size) {
 int temp[size];

 for(int i=0;i<size;i++) {
  temp[i] = res[i];
 }

 results = temp;

}

int* Arrayreturner::getResults() {
  return results;
}

```

This is the header file

```
#ifndef ARRAYRETURNER_H
#define ARRAYRETURNER_H

#include <Arduino.h>
#include <Wire.h>

class Arrayreturner {
public: // some public definitions first

 Arrayreturner();

void setResults(int* res, int size);
int* getResults();
int* results;

};

#endif

```

And here is the main program

```
#include <Arduino.h>
#include "Arrayreturner.h"

Arrayreturner data;

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

}

int* returnArray(int arr[]) {
 // int arr[] = { 3, 5, 6, 7, 9 };
 int *p = arr;

 // Serial.print("rA: ");
 // for(int i=0;i<5;i++) {
 //   Serial.print(p[i]); Serial.print(" ");
 // } Serial.println("");
 return p;
}

Arrayreturner testfunc() {
 Arrayreturner data;
 int arr[] = { 2,4,6,8,10};

 data.setResults(arr, 5);

 return data;
}

void loop() {

  int arr[] = { 3, 5, 6, 7, 9 };
  // int *p = arr;
  // int (*ptr)[5] = &arr;

 // Serial.print("p: ");
 // for(int i=0;i<5;i++) {
 //   Serial.print(p[i]); Serial.print(" ");
 // } Serial.println("");

 // int* p1;
 // p1 = returnArray(arr);
 // Serial.print("p1: ");
 // for(int i=0;i<5;i++) {
 //   Serial.print(p1[i]); Serial.print(" ");
 // } Serial.println("");

 // data.setResults(arr, 5);

 // int* res = data.getResults();
 //
 // Serial.print("res: ");
 // for(int i=0;i<5;i++) {
 //   Serial.print(res[i]); Serial.print(" ");
 // } Serial.println(" ");

 Arrayreturner ar = testfunc();
 int* res = ar.getResults();
 Serial.print("res: ");
 for(int i=0;i<5;i++) {
   Serial.print(res[i]); Serial.print(" ");
 } Serial.println(" ");

 Serial.println("--------------");

  delay(2000);

```

}

There is probably something wrong with the pointer declaration, but I cant figure it out.

Thanks for the help

# Answer
This is a C language question. You copy a local array created on the stack of the testfunc() to other array created on the stack of Arrayreturner::setResults(). Then you store a pointer of the second array into member variable results. But that pointer is not valid when the function setResults() returns and the array on the stack is destroyed.

Normal way is to create an array, pass it as parameter to the function and let the function fill it.
> 0 votes

# Answer
Your arrays are declared locally to the functions. You cannot return local arrays from a function - as soon as you return the arrays no longer exist.
> 0 votes

---
Tags: array, pointer
---


# Question
Title: How to randomize the delay in Arduino Stepper code?
How does one add a random DELAY between 10 and 20 seconds?

For example in the following stepper logic I have a delay of 11 seconds - expressed in milliseconds as: delay(11000).

What would I need to add (or modify) so this is randomized between 10 and 20 seconds?

```
//#define IN1  8
//#define IN2  9
//#define IN3  10
//#define IN4  11

int Steps = 0;
boolean Direction = true;
unsigned long last_time;
unsigned long currentMillis ;
int steps_left=4095;
long time;

void setup()
{
Serial.begin(115200);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);

}
void loop()
{
  while(steps_left>0){
  currentMillis = micros();
  if(currentMillis-last_time>=1000){
  stepper(1);
  time=time+micros()-last_time;
  last_time=micros();
  steps_left--;
  }
  }
   Serial.println(time);
  Serial.println("Wait...!");
  delay(11000);                     // delay timing
  Direction=!Direction;
  steps_left=4095;
}

```

Forgive the appearance of the code. Everytime I post it gets butchered. Hopefully it's understandable.

# Answer
In `setup()`, add

```
randomSeed(analogRead(0));

```

This reads the value of an analog input pin, which if not connected, will float to relatively random values between 0 and 1023. This "seeds" the random number generator so the pattern of random numbers you will get later doesn't always give the same results each time you start the sketch.

In your `delay()` call, just replace the fixed value with a call to the `random(min, max)` function, as:

```
delay(random(10000, 20000));

```
> 4 votes

---
Tags: arduino-uno, stepper, timing
---


# Question
Title: how to read all line except the first line?
is there a way to read only 2nd up to the last line except for the first line?

here's my sample code

```
File myFile;
char cr;
void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  // re-open the file for reading:
  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");

    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Serial.write(myFile.read());

    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop() {
  // nothing happens after setup
}

```

# Answer
> 3 votes
skip first line

```
bool firstLine = true;
while (myFile.available()) {
  int c = myFile.read();
  if (firstLine) {
    if (c == '\n') {
      firstLine = false;
    }
  } else {
    Serial.write(c);
  }
}

```

# Answer
> 3 votes
Why don't you do reads for the first line, ignore them and start the while thus:

```
while (myFile.available() && (myFile.read() != '\n') {}; // Empty while body
while (myFile.available()) {
  Serial.write(myFile.read());
}

```

---
Tags: arduino-uno
---


title: Custom atmega32u4 board crystal issue

text:
# Question
Title: Custom atmega32u4 board crystal issue
So I built an custom board based on the Atmega32u4. Schematics attached.

I managed to burn a bootloader for Pro Micro using Arduino Uno as an ISP.

The issue I have is that the board is dead when powered and to bring it to life I have to short pin1 of my crystal with VCC for a second. I discovered it by mistake..

The crystal I'm using is an Epson X1G004451000212.

Any idea why is this happening?

# Answer
> 1 votes
That's a Crystal Oscillator, not a crystal. Take the 22pF caps off to start.

Did you set the fuses to use an external clock source, vs a crystal with the internal oscillator driver (where the caps would be needed)?

Is the part oriented the correct way so it receives power and Gnd correctly?

Also, is it's performance any better than if you had just used a crytal?

https://support.epson.biz/td/api/doc\_check.php?dl=brief\_SG7050CAN&lang=en

vs these with +/- 10ppm stability (is that the same +/- 10 x 10 ^ -6 ?, which would b be better than 25 to 100 x 10 ^ -6) https://www.digikey.com/products/en/crystals-oscillators-resonators/crystals/171?k=crystal&k=&pkeyword=crystal&pv1989=0&pv183=6185&pv2150=u16MHz&pv253=19&FV=ffe000ab&quantity=0&ColumnSort=0&page=1&stock=1&pageSize=25

---
Tags: arduino-leonardo, atmega32u4
---


# Question
Title: shift register 74HC595 enable specific pin
Its driving me crazy for some couple of days now and i don't get the answer. I'm busy to setup a irrigation system with a shift register 74HC595 and a 8 channel relay board. I see a lot of sketches where it looks like you can turn a specific relay on but i dont get the clue.

I like to turn on a specific relay based on a button press. Is it possible to turn on a specific relay based on the representing button?

Im using the shiftOut option. The code im using now is :

```
//#define BLYNK_DEBUG
#define BLYNK_PRINT Serial

#include <ArduinoOTA.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <TimeLib.h>
#include <WidgetRTC.h>

#include <ESP_SSD1306.h>    // Modification of Adafruit_SSD1306 for ESP8266 compatibility -> https://github.com/somhi/ESP_SSD1306
#include <Adafruit_GFX.h>   // Needs a little change in original Adafruit library (See README.txt file) --> https://github.com/adafruit/Adafruit-GFX-Library
#include <SPI.h>            // For SPI comm (needed for not getting compile error)

#include "settings_base.h"
#include "globals.h"
//#include "functions.h"
//#include "blynk_writes.h"

//Pin connected to ST_CP of 74HC595
const int latchPin = 15; //D8
//Pin connected to SH_CP of 74HC595
const int clockPin = 14; //D5
//Pin connected to DS of 74HC595
const int dataPin = 13; // D7

int totalRelays = 2; // Number of relays
int relayState = 0; // default state = off
int relayArr[] = {12, 16}; // Pins on the Wemos
char vbutton1 = V1; char vbutton2 = V2;
char relayVButtons[] = {V1,V2};
int zone = 0;
int relayVButton = 0;
byte data;
byte dataArray[10];

/*
   SETUP
*/
  BLYNK_WRITE(V1)
  {
    // Get the state of the VButton
    relayVButton = param.asInt();
    relayControl(relayVButton, 12, 49); // Test led on Wemos pin
    //int bitToSet = 49;

    Serial.println("V1 pressed");
  }

  BLYNK_WRITE(V2)
  {
    // Get the state of the VButton
    relayVButton = param.asInt();
    relayControl(relayVButton, 16, 50); // Test led on Wemos pin
    Serial.println("V2 pressed");
  }

void setup() {

  pinMode(dataPin, OUTPUT);   // All 3 pins are output
  pinMode(clockPin, OUTPUT);
  pinMode(latchPin, OUTPUT);

  // Do some loop through all the relays and buttons for pinMode
  for (int i=0; i<=totalRelays; i++){
    pinMode(relayArr[i], OUTPUT);
    digitalWrite(relayArr[i], 0);
    pinMode(relayVButtons[i], INPUT);
  }

  // COMMUNICATIONS
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  // CONNECT TO BLYNK
  Blynk.begin(AUTH, WIFI_SSID, WIFI_PASS);
  while (Blynk.connect() == false) {}
  // OVER THE AIR UPDATES
  ArduinoOTA.setHostname(OTA_HOSTNAME);
  ArduinoOTA.begin();

  Serial.println(F("Blynk v" BLYNK_VERSION ": Device started"));
}
/*
   LOOP
*/
void loop() {
  Blynk.run();
  ArduinoOTA.handle();
  timer.run();
}

void relayControl(int onoff, int relayNumber, int bitToSet){
if(onoff == 1) // Virtual button set to on
    {
      digitalWrite(relayNumber, HIGH); // set Wemos pin on HIGH (for test)
      registerWrite(bitToSet, HIGH);
      relayState = 1;
    }
    else
    {
      digitalWrite(relayNumber, LOW); // set Wemos pin on HIGH (for test)
      registerWrite(bitToSet, LOW);
      relayState = 0;
    }
}
void registerWrite(int whichPin, int whichState) {
// the bits you want to send
  byte bitsToSend = 0;

  // turn off the output so the pins don't light up
  // while you're shifting bits:
  digitalWrite(latchPin, LOW);

  // turn on the next highest bit in bitsToSend:
  bitWrite(bitsToSend, whichPin, whichState);

  // shift the bits out:
  shiftOut(dataPin, clockPin, MSBFIRST, bitsToSend);

    // turn on the output so the LEDs can light up:
  digitalWrite(latchPin, HIGH);

}

```

Sander

---

i've change the code. Now the result is the led is turning on but only one led. After pressing led 2 the other one is turning on.. Im not able to turn them off.

```
//#define BLYNK_DEBUG
#define BLYNK_PRINT Serial

#include <ArduinoOTA.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <TimeLib.h>
#include <WidgetRTC.h>

#include <ESP_SSD1306.h>    // Modification of Adafruit_SSD1306 for ESP8266 compatibility -> https://github.com/somhi/ESP_SSD1306
#include <Adafruit_GFX.h>   // Needs a little change in original Adafruit library (See README.txt file) --> https://github.com/adafruit/Adafruit-GFX-Library
#include <SPI.h>            // For SPI comm (needed for not getting compile error)

#include "settings_base.h"
#include "globals.h"
//#include "functions.h"
//#include "blynk_writes.h"

//Pin connected to ST_CP of 74HC595
const int latchPin = 15; //D8
//Pin connected to SH_CP of 74HC595
const int clockPin = 14; //D5
//Pin connected to DS of 74HC595
const int dataPin = 13; // D7

int totalRelays = 2; // Number of relays
int relayState = 0; // default state = off
int relayArr[] = {12, 16}; // Pins on the Wemos
char vbutton1 = V1; char vbutton2 = V2;
char relayVButtons[] = {V1,V2};
int zone = 0;
int relayVButton = 0;

/*
   SETUP
*/
  BLYNK_WRITE(V1)
  {
    // Get the state of the VButton
    relayVButton = param.asInt();
    relayControl(relayVButton, 12, 1); // Test led on Wemos pin
    //int bitToSet = 49;

    Serial.println("V1 pressed");
  }

  BLYNK_WRITE(V2)
  {
    // Get the state of the VButton
    relayVButton = param.asInt();
    relayControl(relayVButton, 16, 4); // Test led on Wemos pin
    Serial.println("V2 pressed");
  }

void setup() {

  pinMode(dataPin, OUTPUT);   // All 3 pins are output
  pinMode(clockPin, OUTPUT);
  pinMode(latchPin, OUTPUT);

  // Do some loop through all the relays and buttons for pinMode
  for (int i=0; i<=totalRelays; i++){
    pinMode(relayArr[i], OUTPUT);
    digitalWrite(relayArr[i], 0);
    pinMode(relayVButtons[i], INPUT);
  }

  // COMMUNICATIONS
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  // CONNECT TO BLYNK
  Blynk.begin(AUTH, WIFI_SSID, WIFI_PASS);
  while (Blynk.connect() == false) {}
  // OVER THE AIR UPDATES
  ArduinoOTA.setHostname(OTA_HOSTNAME);
  ArduinoOTA.begin();

  Serial.println(F("Blynk v" BLYNK_VERSION ": Device started"));
}
/*
   LOOP
*/
void loop() {
  Blynk.run();
  ArduinoOTA.handle();
  timer.run();
}

void relayControl(int onoff, int relayNumber, int bitToSet){
if(onoff == 1) // Virtual button set to on
    {
      digitalWrite(relayNumber, HIGH); // set Wemos pin on HIGH (for test)
      registerWrite(bitToSet);
      Serial.println(bitToSet);
      relayState = 1;
    }
    else
    {
      digitalWrite(relayNumber, LOW); // set Wemos pin on HIGH (for test)
      registerWrite(bitToSet);
      relayState = 0;
    }
}
void registerWrite(int whichPin) {
// the bits you want to send
   uint8_t data = 1<<whichPin ;
  // turn off the output so the pins don't light up
  // while you're shifting bits:
  digitalWrite(latchPin, LOW);

  // shift the bits out:
  shiftOut(dataPin, clockPin, MSBFIRST, data);

    // turn on the output so the LEDs can light up:
  digitalWrite(latchPin, HIGH);

}

```

---

Im using the shiftOut option. The code im using now is :

```
//#define BLYNK_DEBUG
#define BLYNK_PRINT Serial

#include <ArduinoOTA.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <TimeLib.h>
#include <WidgetRTC.h>

#include <ESP_SSD1306.h>    // Modification of Adafruit_SSD1306 for ESP8266 compatibility -> https://github.com/somhi/ESP_SSD1306
#include <Adafruit_GFX.h>   // Needs a little change in original Adafruit library (See README.txt file) --> https://github.com/adafruit/Adafruit-GFX-Library
#include <SPI.h>            // For SPI comm (needed for not getting compile error)

#include "settings_base.h"
#include "globals.h"
//#include "functions.h"
//#include "blynk_writes.h"

//Pin connected to ST_CP of 74HC595
const int latchPin = 15; //D8
//Pin connected to SH_CP of 74HC595
const int clockPin = 14; //D5
//Pin connected to DS of 74HC595
const int dataPin = 13; // D7

int totalRelays = 2; // Number of relays
int relayState = 0; // default state = off
int relayArr[] = {12, 16}; // Pins on the Wemos
char vbutton1 = V1; char vbutton2 = V2;
char relayVButtons[] = {V1,V2};
int zone = 0;
int relayVButton = 0;
byte data;
byte dataArray[10];

/*
   SETUP
*/
  BLYNK_WRITE(V1)
  {
    // Get the state of the VButton
    relayVButton = param.asInt();
    relayControl(relayVButton, 12, 49); // Test led on Wemos pin
    //int bitToSet = 49;

    Serial.println("V1 pressed");
  }

  BLYNK_WRITE(V2)
  {
    // Get the state of the VButton
    relayVButton = param.asInt();
    relayControl(relayVButton, 16, 50); // Test led on Wemos pin
    Serial.println("V2 pressed");
  }

void setup() {

  pinMode(dataPin, OUTPUT);   // All 3 pins are output
  pinMode(clockPin, OUTPUT);
  pinMode(latchPin, OUTPUT);

  // Do some loop through all the relays and buttons for pinMode
  for (int i=0; i<=totalRelays; i++){
    pinMode(relayArr[i], OUTPUT);
    digitalWrite(relayArr[i], 0);
    pinMode(relayVButtons[i], INPUT);
  }

  // COMMUNICATIONS
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  // CONNECT TO BLYNK
  Blynk.begin(AUTH, WIFI_SSID, WIFI_PASS);
  while (Blynk.connect() == false) {}
  // OVER THE AIR UPDATES
  ArduinoOTA.setHostname(OTA_HOSTNAME);
  ArduinoOTA.begin();

  Serial.println(F("Blynk v" BLYNK_VERSION ": Device started"));
}
/*
   LOOP
*/
void loop() {
  Blynk.run();
  ArduinoOTA.handle();
  timer.run();
}

void relayControl(int onoff, int relayNumber, int bitToSet){
if(onoff == 1) // Virtual button set to on
    {
      digitalWrite(relayNumber, HIGH); // set Wemos pin on HIGH (for test)
      registerWrite(bitToSet, HIGH);
      relayState = 1;
    }
    else
    {
      digitalWrite(relayNumber, LOW); // set Wemos pin on HIGH (for test)
      registerWrite(bitToSet, LOW);
      relayState = 0;
    }
}
void registerWrite(int whichPin, int whichState) {
// the bits you want to send
  byte bitsToSend = 0;

  // turn off the output so the pins don't light up
  // while you're shifting bits:
  digitalWrite(latchPin, LOW);

  // turn on the next highest bit in bitsToSend:
  bitWrite(bitsToSend, whichPin, whichState);

  // shift the bits out:
  shiftOut(dataPin, clockPin, MSBFIRST, bitsToSend);

    // turn on the output so the LEDs can light up:
  digitalWrite(latchPin, HIGH);

}

```

# Answer
Working from `shiftOut()` backwards:

Parameters for `shiftOut()`:

> **Syntax**
>
> `shiftOut(dataPin, clockPin, bitOrder, value)`
>
> **Parameters**
>
> `dataPin`: the pin on which to output each bit (int)
>
> `clockPin`: the pin to toggle once the dataPin has been set to the correct value (int)
>
> `bitOrder`: which order to shift out the bits; either MSBFIRST or LSBFIRST. (Most Significant Bit First, or, Least Significant Bit First)
>
> `value`: the data to shift out. (byte)

The important part to notice is the `value` parameter, which is one 8-bit value, and along with the `dataPin` and `clockPin`, sets the 8 registers of the shift register to the 8 bits shifted in. Then, as you have in your code, you pull the `latchPin` high to latch the register values to the output pins.

Binary values can be represented in C++ as `b00001010`, where the `b` prefix notes that the number following is in binary notation, and not "one-thousand ten". If the least-significant bit refers to relay-0 and the most-significant bit refers to relay-7, then to turn on relay-0, you would make sure the last digit (least-signficant) is a one: `b00000001`. To turn on relays 0 and 1, send 'b00000011', and so on.

In your `registerWrite()` function, you call `shiftOut(dataPin, clockPin, MSBFIRST, bitsToSend);`, thus `bitsToSend` should be an 8-bit value, with each bit representing the state of one of the 8 relays on your relay board.

within `registerWrite()`, `bitsToSend` is set by the `bitWrite()` function, which sets the bit number identified by `whichPin` to the value represented by `whichState`, which are both parameters passed in from the function call. It's worth noting that `bitsToSend` is initialized to `b00000000` and `bitWrite()` is called only once, and so there can be at most **one** bit turned on in the value to write; and thus only one relay active at a time.

`registerWrite()` is called from within `relayControl()`, and the `whichPin` value in `registerWrite()` comes from the `bitToSet` value in `relayControl()`, which in turn is called by the `BLYNK_WRITE(V1)` or `BLYNK_WRITE(V2)` functions. In both of those functions, you pass `49` or `50` as the `bitToSet` parameter, but there are only 8 bits in a byte, so the value passed should be between 0 and 7. You cannot set bit 49 of an 8-bit value.

Probably `relayControl()` should be called with a value between 0 and 7 for the last parameter.

---

**EDIT Based on New Code**

Your latest code shows some changes to the `registerWrite()` function:

```
void registerWrite(int whichPin) {

```

You have removed the parameter which contains the value to write to the particular bit position. Now you have no way to tell the function whether to turn the pin on or off.

```
// the bits you want to send
   uint8_t data = 1<<whichPin ;

```

By shifting a `1` to a particular bit position, you have no way to clear a bit, which is probably why you now cannot get an LED to turn off except by turning on the alternate LED.

```
  // turn off the output so the pins don't light up
  // while you're shifting bits:
  digitalWrite(latchPin, LOW);

  // shift the bits out:
  shiftOut(dataPin, clockPin, MSBFIRST, data);

    // turn on the output so the LEDs can light up:
  digitalWrite(latchPin, HIGH);
}

```

If you wish to maintain the current state of bits, you will need to declare `data` as a `static` variable, which means that it's value is retained even when the function ends and is again available when the function is called again. Further, by using the assignment (`=`) operator, all you are able to do is overwrite the existing data with the new data, erasing the previous data.

You can use the `bitSet()` and `bitClear()` functions to set (make equal to 1) and clear (make equal to zero) individual bits in a byte.

A new `registerWrite()` function might look like:

```
void registerWrite(int whichPin, int pinValue) {
  // the bits you want to send
  static uint8_t data;

  if (pinValue==1) {
    bitSet(data, whichPin);    // Turn on the bit at whichPin
  } else {
    bitClear(data, whichPin);  // Turn off the bit at whichPin
  }

  // turn off the output so the pins don't light up
  // while you're shifting bits:
  digitalWrite(latchPin, LOW);

  // shift the bits out:
  shiftOut(dataPin, clockPin, MSBFIRST, data);

    // turn on the output so the LEDs can light up:
  digitalWrite(latchPin, HIGH);
}

```

You noted you have been frustrated for days working on this, and your code examples have mixed coding conventions, so perhaps you are finding many different code examples and trying various ones until you find something that works. I would encourage you, however, to take it slow and read through each line of code you have and make sure you understand exactly what it does, and be sure you can explain to yourself why each statement or command is there. This will help you to see the path of execution for your code and be able to diagnose bugs and come up with solutions that directly fix the problem, rather than swapping and and out a multitude of snippets from websites and forums.
> 1 votes

# Answer
You already had SPI in use. You can connect SCK to SRCLK, MOSI to Serial data in, and pick a pin for RCLK. D10 needs to be an output for the device to be SPI master. If it's used already, use that.

Then simply clock in the needed data:

```
digitalWrite (rclk, LOW);
SPI.transfer (yourData);
digitalWrite (rclk, HIGH); // outputs update on this rising edge

```

MRCLR connects to +5, OE/ connects to Gnd.

```
SPI.begin();

```

in setup() turns on the defaults of 4 MHz clock rate, MSBFIRST, and SPI Mode 0, that's all you need.
> 0 votes

---
Tags: esp8266, relay, shift-register
---


title: Flickering LED when servo moves

text:
# Question
Title: Flickering LED when servo moves
I just got to play around with Arduino lately so I'm really new on this stuff and sorry for the grammar error.

I got a work where I need to turn the LED on all the time, my plan is to add a slow fade in and fade out later but the problem occurs when I add the servo.

Everytime servo starts moving slowly or fast the LED kinda flickering/dim like it lost power and come back to normal after the servo stops moving.

Here's the scheme I used and the code, I only change some delay to 5ms and so to test it out but no matter what the led is keep flickering.

Im using nano v.3 clone if its matter.

```
#include <Servo.h>
Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 100;    // variable to store the servo position
int ledpin3 = 3;

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  pinMode(ledpin3, OUTPUT);
}

void loop() {
  digitalWrite(ledpin3, HIGH);
  delay(1000);

  for (pos = 99; pos <= 150; pos += 1) { // goes from 0 degrees to 180 degrees
                                         // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable ‘pos’
    delay(15);                       // waits 15ms for the servo to reach the position
  }

  for (pos = 150; pos >= 30; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable ‘pos’
    delay(15);                       // waits 15ms for the servo to reach the position
  }

  for (pos = 30; pos <= 99; pos += 1) { // goes from 0 degrees to 180 degrees
                                        // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable ‘pos’
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

```

# Answer
If you are powering the arduino via usb try not to do that or plug it in to an usb 3.0 (and higher) port. The reason for this is that the servo draws a lot of power and the standard usb 2.0 with 0.5A can't handle the load and you got an voltage drop. And in that period of time the led goes off. usb 3.0 (and higher) can handle up to 1.5A so this souldn't be an error.
> 2 votes

---
Tags: arduino-nano, led, servo
---


# Question
Title: Using a analog multiplexer to use 9 serial input sensors?
I have 9 sensors, they will send a datastring to my Arduino through Tx/Rx (every 3½ seconds, pre-programmed). The only problem is that there's only one Tx/Rx port on an Arduino Uno. Is it possible to use an analog multiplexer to "make" more Serial ports? Because the sensors send something every 3½ seconds, there's no need to be fast.

EDIT: It's a Temperature and Relative Humidity Sensor

# Answer
> 3 votes
No. Not unless you can change your communication protocol to be a "call-and-response" protocol.

Basically, the problem is this: *when* do you switch to *which* serial device? Unless all the devices have their timing synchronised there is no way of knowing - so how do you control your analogue multiplexer in that situation...? You can't.

You would need to have some method of the master switching the multiplexer to a specific peripheral, then send a message to that peripheral saying "Send me your data now".

You would be better off investigating other boards with more UART ports, such as the Mega2560, and having multiple boards.

The Mega2560 has 4 UART ports. You can have 4 sensors per board (5, if you want to use SoftwareSerial or, better, AltSoftSerial), so you could get away with two boards.

One board acts as normal, communicating on the UART ports to 4 sensors, and also acts as an I2C or SPI master (the choice is yours). The second board communicates to 4 more sensors on UARTs and one further on using AltSoftSerial etc. It also acts as an I2C or SPI slave device.

The "slave" board just runs autonomously gathering data from the sensors it is directly connected to and storing those values. The "master" then periodically asks the "slave" board for the latest data.

# Answer
> 1 votes
Thanks for the answer and my apologies for the late answer. I just tried a multiplexer, because some people said that I would work. I can receive info from all the 9 sensors. The sensor sends a datastring and I filter the temperature and relative humidity and then I switch to the next sensor. It works quite well, the only problem is that you can't request the datastring, so you should wait till the datatstring is sent

---
Tags: serial
---


# Question
Title: Where can I find a central repository of all available Arduino libraries?
Currently; when I start a new Arduino project with some new hardware, the first thing I do is to look for 3rd-party libraries that bring Arduino support for this hardware.

The first places I look are:

Generally I find either no support library or several different libraries (it's quite rare to find only one) in different locations with different levels of documentation, different levels of testing...

Once I have found the library I need (sometimes I need to try several), I download it to my Arduino libraries folder, I use it and I forget it.

I find this process cumbersome:

* manual search with different possible options, not always well documented
* manual download and install to Arduino libraries
* no version control in the process (all versions of a library have the same name and thus cannot coexist in the Arduino library folder).

I wish there was a central repository with all available libraries for arduino, with:

* description (supported hardware, supported boards)
* source code
* documentation
* versions

And a tool (Arduino IDE or external) to access this repository at project build time.

A kind of maven for Arduino in fact.

I have seen several discussions once took place on Arduino forum, but it seems they led nowhere:

Are there other options, that are made it to something usable (from the community or individuals, why not)?

# Answer
Since this question was first asked, there is now the Arduino Library Manager, built into the Arduino IDE. There you can search for and install libraries.

There is information about how the library manager works here: https://github.com/arduino/Arduino/wiki/Library-Manager-FAQ

There isn't however an official website listing the libraries, so I recently created this unofficial site, based on the same data in the Arduino Library Manager:

http://www.arduinolibraries.info/
> 6 votes

# Answer
The Arduino Playground LibraryList and the standard library list appear to be the official pages for that.
> 3 votes

# Answer
There is none. Unfortunately, you will have to manually search for each library you are interested in.

If you are interested in creating such a central repository, while it would be awesome, this is not the correct forum in which to do it.
> 2 votes

# Answer
If you want to create such a registry yourself, you may want to take a look at npm, the package manager of Node.js, which is open-source and very similar in scope to want you describe. Npm is both:

1. a central registry with metadata about each library:
    * name, description, keywords, homepage, author, contributors
    * version number, in principle complying with semantic versioning
    * URL of source repository (svn, git, github, gitlab, bitbucket...)
    * compatibility information (in this case it's about the versions of Node)
    * license
    * dependencies
2. a command-line tool for:
    * searching the registry
    * downloading and installing packages, recursively following their dependencies
    * publishing and updating your own packages on the registry.

See for example the page of a popular library, and the JSON file holding its metadata.
> 1 votes

# Answer
Arduino IDE and associated libraries are included as installable software in most OS repositories. Unfortunately the versions in these repositories is usually several months or even years out-of-date. This would seem that the real problem is in getting OS repository managers to incorporate new releases as they become available.

This problem is compounded when your OS version has not been updated to the latest release, because this forces you to use an outdated software repository.

While not a perfect answer, you should probably insure that you are using the latest release of your OS, and then encourage the repository managers for that OS to incorporate the latest version of Arduino IDE.

An alternative would be to go to the Arduino.org homepage and follow instructions to download and install the latest IDE and associated libraries. This will probably be in the form of a .tar.gz file so you will need to know how to unzip, untar, and build the necessary software.
> 0 votes

# Answer
I think, that your wish will not come true. I hope for it, because having only one place for all Arduino libriaries, with no libraries allowed not be there and all those libraries would be forced to stand all commercial standards of quality, testing and documentation (+code quality, effectivity and readability) would mean, that only professionals and similary qualified teams would be allowed to publish some Arduino library and it all would be governed by one single entity, which would enforce removing functionally duplicate or similar libraries. And such entity would soner or later became evil.

I like the Arduino for being free and that also means, that I am free to write library for support of some features (which I want to use) of some hardware (which I have, plan to buy or want to make myself - even highly experimental and maybe unstable, but fun for me).

With your Big Central Authority being effective, I would just choose another free platform, rather then be sued for lesser than perfect and commercially certified outcome of my hobby playing with electronics and forced to work for their, NOT my goals on MY free time.

And if your Big Central Athority would not force me to forced free labor work for them, then what would you do about my library enabling one special use of some common hardware, and about me sharing it to anyone want it, even if it does not solve all the HW functionality fully in proffesional matter and documented only so much as I would be comfortabe to spend my own free time with documentation. And what if there would arise another library for the same HW, which would enable another part of functionality or would use another API and another approach to the whole problematic?

Namely I bought some multi 7-segment module and there was "official library" for it from its manufacturer. I made another library for the same module. What now? Should be my library be in the Central Repository as "the only one library for this HW" or should be there the "official one from manufacturer"? Note, that if there were both of them, than it would break your requested "one and only one" library point. If you disallow the manufacturer one, then "the only one" would be missing a lot of features, as integrated buffer for numbers, simple object interface, simple example, how to use it and there would be hard dependency on one specific timer and generic non-object, just functional API, which would require user to break integers to single digits somehow - does not sound too good. If you disallow my library, then user would have the above, but his display would refresh only 10x per second with blinking and leaving ghosts of other digits all over place, while fully utilise processor and the documentation would be mainly in chinese. And the user would miss refresh rate 100x per second with nearly no usage of processor, nice clean digits AND characters (potetially also user defined). - Also not good.

In current state of chaos user (maybe you or anyone else) can use the library, that is better fit for his needs (be it simplicity and native integer support, or be it clean fast refresh and low CPU usage) or combine both together, making third with fast refresh AND simple integer manipulation AND user defined charset, WITH nice object API and rich documentation. It only needs one person with some time and dedication make it easy for beginers and some english skills and basic knowledge of objects and how are "official Arduino libraries" packed, so the IDE can easily import them. (And such person should do it and contribute it to Arduino library packager).

I would not do it - for my needs is functional API far better and simpler to use, take less bytes from memory and less CPU cycles and I have no urge to improve the library in ways I would not use. Also I do not use Arduino IDE, I use simple Makefile to build and upload the programs, so I can easily use good text editor (vim in my case) and have not to fight with IDE-Notepad-parody.

Under Big Central Authority enforsing your model I would not care about using Arduino at all and you will be stuck with the chinese version, if any at all (as it would not make it there for lack of good english documentation and proper package format too).
> 0 votes

# Answer
http://downloads.arduino.cc/libraries/library\_index.json provides a list of all libraries available in Arduino Library Manager.

I used this file to create https://github.com/scls19fr/arduino\_libraries\_search It's a Python Pandas script to search for Arduino libraries matching some keywords and to output to Excel file

You can also find Arduino libraries using:
> 0 votes

---
Tags: library
---


title: External Flash Memory File System

text:
# Question
Title: External Flash Memory File System
I'm building a weather data collector and I want to be able to dump that weather data somewhere. I've considered the options, and since I'm going to be storing a fairly small amount of data (in the megabyte range) I don't want to use SD cards (also SD cards are expensive). I've heard of use of NAND flash memory chips (like the W25Q32), and I was hoping that I could possibly interact with them in a simple way (since most ways require writing to each individual address). Is there possibly a way to build a file system within one of these small flash memory chips and interact with them as simply as interacting with an SD card?

TLDR: I want to interact with a flash memory chip easily to store basic ASCII data

# Answer
> 2 votes
This lib offers a means of reading and writing ASCII arrays to flash devices. This would be a simple solution for such a data logger requirements. It's ASCII orientated.

https://github.com/schinken/Flash

# Answer
> 2 votes
I don't think you need a file system: that is usually needed when you want to manage *many* files. Your weather data log sounds like a single file.

What you seem to need is to access EEPROM as a *stream*, exactly like you would for an open file. There are stream wrappers around some EEPROM libraries, e.g. this one for ESP. I suggest you check it out and see if you can adapt it to the EEPROM library you use.

# Answer
> -1 votes
There is a way to do this. Using a $2 adaptor from eBay, you can hook it up to a micro sd card. An sad card for $4 can store 128mb of data, which is plenty for you.

Arduino Storage Tutorial with weather

128mb Micro Sd card

---
Tags: datalogging, flash, memory
---


title: Cannot run WiFi sketch on ESP-01

text:
# Question
Title: Cannot run WiFi sketch on ESP-01
I can upload simple sketch on my ESP-01 like:

```
void setup() {
  Serial.begin(115200);
  Serial.println("Hello there");
}
void loop() {
  Serial.println("Hello from loop");
  delay(1000);
}

```

I also ran successfully the sample ESPWebServer -\> HelloServer

But if just modify my sketch to include `#include <ESP8266WiFi.h>`

```
#include <ESP8266WiFi.h>

void setup() {
  Serial.begin(115200);
  Serial.println("Hello there");
}
void loop() {
  Serial.println("Hello from loop");
  delay(1000);
}

```

I got this result in the serial monitor:

```
  ets Jan  8 2013,rst cause:4, boot mode:(3,7)

wdt reset
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
vbb28d4a3
~ld

```

My ESP-01 is connected to my computer through FT232RL FTDI with the following cabling:

* FTDI GND - GND
* ESP TX - FTDI RX
* ESP RX - FTDI TX
* ESP VCC - VCC 3.3V
* ESP GND - GND
* ESP CH\_PD - VCC
* ESP GPIO2 - VCC
* ESP GPI00 - GND to upload sketch, VCC to run sketch

Here is a picture of my cabling (the USB of both the TTL and power supply MB102 are connected to my laptop):

Also, regularly my sketch fails to load correctly:

-Sometimes it does not load at all and I get this after compilation before uploading starts:

```
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

```

\- Sometimes it fails at the end of the upload:

```
Uploading 256064 bytes from C:\Users\20000263\AppData\Local\Temp\arduino_build_32221/ESP01-Basic.ino.bin to flash at 0x00000000
................................................................................ [ 31% ]
................................................................................ [ 63% ]
................................................................................ [ 95% ]
..........warning: espcomm_send_command: didn't receive command response
warning: espcomm_send_command(FLASH_DOWNLOAD_DATA) failed
warning: espcomm_send_command: wrong direction/command: 0x01 0x03, expected 0x01 0x04
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

```

Any idea about what is wrong ?

# Answer
FTDI adapters often don't provide enough current to run the power-hungry wifi features of the ESP8266. So as soon as you fire up wifi, you brownout the chip and cause it to reset.

Use a battery, a dedicated ESP8266 flasher, a 3.3v LDO, or something besides the on-board 3.3v connection the USB-Serial adapter provides.
> 1 votes

---
Tags: esp8266
---


# Question
Title: WS2812 - First are white and then they turn red/yellow/orange near the end
I'm trying to power about 150 WS2812 LEDs from my ESP8266 NodeMCU board (running NeoPixel Arduino code). The first few LEDs are white, but about half way down, the LEDs turn yellow, then they turn orange, and at the end they're basically red.

Could this be caused because of the power draw? The strip itself is currently drawing about 900 mAh, and I am powering the ESP8266 with a 1.5A 5v supply. The LEDs are running off 3.3v directly from the ESP8266.

Also, after like 2 minutes, the LEDs turn off completely. The board never disconnects from my WiFi. They just turn off. I can turn them on again right after.

# Answer
> 5 votes
See Powering NeoPixels.

> Each individual NeoPixel draws up to 60 milliamps at maximum brightness white (red + green + blue).
>
> ...
>
> To estimate power supply needs, multiply the number of pixels by 20, then divide the result by 1,000 for the “rule of thumb” power supply rating in Amps. Or use 60 (instead of 20) if you want to guarantee an absolute margin of safety for all situations. For example:

So you need at least 3 amps or even **9 amps** for absolute safety.

> The LEDs are running off 3.3v directly from the ESP8266.

I doubt it is designed for that. The internal traces won't be designed to handle maybe 5 amps.

---

To avoid colour degradation through the strip you could use multiple power supplies (to avoid the voltage dropping due to the resistance over the strip). You would connect the grounds (and connect the data wires of course) but break the +5V line in the middle and insert another power supply.

However one (fairly powerful) supply **directly connected to the NeoPixels** might do the trick. That is, not through the ESP8266.

Also see NeoPixels Revealed: How to (not need to) generate precisely timed signals.

On that page:

> **Q**: In the video, when the entire strip is lit full white, it looks like the far end has a orange tint to it. Is this an artifact of the camera or something?
>
> **A**: Wow, you are very perceptive! Yes, the string did start to get orange at the end at full power. I actually didn’t just run out of apartment when making this long string – I also ran out of power supplies. I had 3 supplies, each 10amps. This is almost enough, but not when every single LED is full brightness white. When that happens, the voltage at the very end of the strip starts to get too low and the LEDs start looking pallid. Why orange? Because blue LEDs need the highest voltage drop to light so when the voltage sags they are the first to go followed by the greens – leaving yellows to oranges and ultimately red.

(He had 1000 pixels). So this guy used 3 separate 10 amp power supplies!

# Answer
> 1 votes
From the Adafruit Uberguide. https://learn.adafruit.com/adafruit-neopixel-uberguide/power

I am experiencing the same issue. This is the solution I found.

> Distributing Power The longer a wire is, the more resistance it has. The more resistance, the more voltage drops along its length. If voltage drops too far, the color of NeoPixels can be affected.
>
> Consider a full 4 meter reel of NeoPixels. With 5V applied at one end of the strip, for those pixels closest to this end, power traverses only a few inches of copper. But at the far end of the strip, power traverses 8 meters of copper — 4 meters out on the +5V line, 4 meters back on the ground line. Those furthest pixels will be tinted brown due to the voltage drop (blue and green LEDs require higher voltage than red).
>
> leds\_brownout.jpg
>
> Pro Tip: NeoPixels don’t care what end they receive power from. Though data moves in only one direction, electricity can go either way. You can connect power at the head, the tail, in the middle, or ideally distribute it to several points. For best color consistency, aim for 1 meter or less distance from any pixel to a power connection. With larger NeoPixel setups, think of power distribution as branches of a tree rather than one continuous line.
>
> leds\_nobrown.jpg

# Answer
> -1 votes
Just incase anyone else has the problem,

You need to connect the strip as a ring by returning the tail end to the psu,

Electricity basics !!!!

---
Tags: esp8266, led, voltage-level, current
---


title: for() loop doesn't seem to break?

text:
# Question
Title: for() loop doesn't seem to break?
So I'm quite new to the whole Arduino coding but constructed a sketch that does work, but I think it doesn't work properly. So I'd love to get some advice on how to improve it.

This script is currently running on a Wemos ESP8266 chip attached to a 1 meter WS2812 144 LED strip.

My questions:

1. The loop is set to break when fadein is higher then 254. When I try to break it at `fadein == 255` the loop doesn't work anymore as it the fadein value directly jumps to 255. Why?
2. When I set the delay to zero the led flicker due to too fast updating. however, this flickering continues even after the for loop is broken, which makes me conclude that the for loop is still running even when the break is applied.

Of course this is no longer an issue when the delay is set higher (as it is supposed to be) but it still seems a waste of processing power to keep the for loop active while it's not doing anything new anymore how can i completely stop the loop from being executed?
3. How can this be done differently / more effective?

The code

```
#define FASTLED_ALLOW_INTERRUPTS 0                                    //fix jitter in led strip
#include <FastLED.h>                                                  //add fastled lib
#define NUM_LEDS 144                                                  //set number of leds
#define DATA_PIN D4                                                   //set data pin leds

CRGB ledStrip[NUM_LEDS];                                              //init led strip
int fadeIn = 8;                                                       //init fade in counter
int led = 0;                                                          //init led counter

void setup() {
  Serial.begin(115200);                                               //setup comm channel
  FastLED.addLeds<WS2811,DATA_PIN, RGB>(ledStrip, NUM_LEDS);          //setup ledstrip config
}

void loop()
{
for (int led = 0; led < NUM_LEDS; led++) {                            //move led up the strip till max count is reached
    ledStrip[led] = CHSV( 0+led*1.77, 255, 225);                      //set animated led hue value to make a rainbow
    FastLED.show();                                                   //show led color
    ledStrip[led] = CHSV( 0+led*1.77, 255, fadeIn);                   //set non animated led hue to same hue value while increasing the fade value
    delay(3);
    if (fadeIn > 254) {                                               //if the fadeIn value exceed 254
      break;                                                          //stop led animation
    }
}

    if (led = 144 && fadeIn < 254) {                                   //when the 144th led is reached and the fadein value is less then 255
      fadeIn+=16;                                                      //increase fadeIn value with 16
    }
    if (led = 144 && fadeIn < 255) {                                   //when the 144th led is reached and fadeIn is smaller then 255 show debug messages
      Serial.println(led);                                             //print led counter value
      Serial.println(fadeIn);                                          //print fadein value
    }
    if (fadeIn > 255) {                                                 //if the fadeIn value exceed 255
      fadeIn = 255;                                                     //clamp fadeIn value to 255

    }

}

```

# Answer
> 3 votes
1. Consider the sequence of values of "fadeIn". It starts at 8 and in incremented by 16. So: 8, 24, ... 248, 264, ... . It is never exactly 255. So you never break out of your "for" loop.
2. There is only 1 delay in your example code. It is difficult to associate the described behavior in your question and the location of the delay.
3. Arduino programming is actually C and C++ programming. Developed at Bell Labs, this language has been around for decades and there are countless books on the subject. Rather than rewriting your program (someone might yet still do this) I would recommend leaning C programming and if you want to write Arduino library software then C++ programming as well.

# Answer
> 2 votes
This is doing an assignment, not the comparison you are expecting

```
if (led = 144

```

Need == for the comparison

# Answer
> 0 votes
You close your `for()` loop right after the if statement that contains the break. No where in that `for()` loop do you change `fadeIn`, so there is nothing to break out of.

If you move the `}` that closes the for loop to below the code that changes `fadeIn`, then the `break` has an opportunity to be executed:

```
void loop() {
  for (int led = 0; led < NUM_LEDS; led++) {                            //move led up the strip till max count is reached
    ledStrip[led] = CHSV( 0+led*1.77, 255, 225);                      //set animated led hue value to make a rainbow
    FastLED.show();                                                   //show led color
    ledStrip[led] = CHSV( 0+led*1.77, 255, fadeIn);                   //set non animated led hue to same hue value while increasing the fade value
    delay(3);
    if (fadeIn > 254) {                                               //if the fadeIn value exceed 254
      break;                                                          //stop led animation
    }

    if (led = 144 && fadeIn < 254) {                                   //when the 144th led is reached and the fadein value is less then 255
      fadeIn+=16;                                                      //increase fadeIn value with 16
    }
    if (led = 144 && fadeIn < 255) {                                   //when the 144th led is reached and fadeIn is smaller then 255 show debug messages
      Serial.println(led);                                             //print led counter value
      Serial.println(fadeIn);                                          //print fadein value
    }
    if (fadeIn > 255) {                                                 //if the fadeIn value exceed 255
      fadeIn = 255;                                                     //clamp fadeIn value to 255
    }
  }
}

```

# Answer
> 0 votes
Ok, thanks for all your help, found the solution to make it stable. I think I got thrown off by the fact the led = 144 did (magically) seem to work outside the loop but led == 144 didn't work at all.

turns out i was counting the leds wrong (it's from 0-143 instead of 1-144) and that made all the other pieces fall into place.

tnx

```
#define FASTLED_ALLOW_INTERRUPTS 0                                    //fix jitter in led strip
#include <FastLED.h>                                                  //add fastled lib
#define NUM_LEDS 144                                                  //set number of leds
#define DATA_PIN D4                                                   //set data pin leds

CRGB ledStrip[NUM_LEDS];                                              //init led strip
int fadeIn = 8;                                                       //init fadein value
int fadeIncr = 16;                                                    //init fadein increments

void setup() {
  Serial.begin(115200);                                               //setup comm channel
  FastLED.addLeds<WS2811,DATA_PIN, RGB>(ledStrip, NUM_LEDS);          //setup ledstrip config
}

void loop()
{
for (int led = 0; led < NUM_LEDS; led++) {                            //move led up the strip till max count is reached
    ledStrip[led] = CHSV( 0+led*1.77, 255, 225);                      //set animated led hue value to make a rainbow
    FastLED.show();                                                   //show led color
    ledStrip[led] = CHSV( 0+led*1.77, 255, fadeIn);                   //set non animated led hue to same hue value while increasing the fade value
    delay(1);
    if (led == 143) {                                                  //when the 144th led is reached and the fadein value is less then 255
      fadeIn+=(fadeIncr);                                              //increase fadeIn value with 16
      fadeIn=constrain(fadeIn, 0, 255);                                // clip value range
        Serial.println(led);                                           //print led counter value
        Serial.println(fadeIn);                                        //print fadein
    }
    if (fadeIn == 255) {                                               //if the fadeIn value exceed 255
      break;                                                           //stop led animation
    }
  }
}

```

---
Tags: esp8266, rgb-led, loop, led-strip
---


# Question
Title: Checking a jumper between two pins on Arduino
I'm in the process of making a tag scanner (which transfers the tag ID to the computer), and I figured I'd use an Arduino Micro for that and just use the keyboard function on it to save myself a whole lot of hassle. From what I've read, however, having the keyboard open all the time can make it tricky to program it.

I figured my solution would be to use two of the pins as a jumper check, and have some code in the setup to read the input pin; if the circuit is closed between them, the keyboard function never activates, and if it's open, the Arduino will act as a keyboard. That way I should be able to put the jumper on if I need to program it, and leave it off if I just want it to run.

Unfortunately, I've never really done anything like this before, and I don't really want to just start plugging things around and run the risk of damaging my board. I've read around a bit, but I figured I wanted to bounce my ideas off of someone before I try it.

First, would you recommend a different approach? I did see a question that used the internal pullup resistor to check if a jumper connected it to ground, but since I only want to make this check once, is that a good route to go?

Secondly, if I connect it between two pins, am I correct in thinking I'd need a resistor between them (the Arduino website suggested 470ohm to 1kohm when connecting to other devices, so I'm guessing this would be a good number)? How would I set the pins up to make this work; should I put one pin as output and the other as input, and just read the input pin (after which I'd simply turn the output pin off), or would I need to add additional connections?

Thirdly, since this will use the USB port on the Arduino that is used to program it, is there a way to wipe the code from the Arduino in case of Serious Bugs, or is it possible to "brick" the board by tying up the USB permanently? I mean, I'll definitely make use of the Serial connection to test the output (and also to test the above jumper), so I think the odds are small enough to try it anyway, but... better safe than sorry?

# Answer
First of all, welcome here. Usually questions should contain, well, only one question ;)

In any case the usual circuit with buttons (a jumper can be seen as a button) are these ones:

simulate this circuit – Schematic created using CircuitLab

In the left case, usually the arduino pin is "pulled down" by the resistor when the button is not pressed (or the jumper is not present), so it will read "LOW". When the button is pressed, the arduino will see a "HIGH" value, since the button is "stronger" than the resistor and is able to force its value. The resistor is called "pull-down".

In the right case, the voltages are inverted. You read a "HIGH" value when the button is not pressed, and a "LOW" value when it is. The resistor is called "pull-up" for obvious reasons.

The resistor is needed because you need to have a "weak" component that can pull the arduino pin to a voltage value; it needs to be weak, so the button can override it.

The arduino, however, as a very common feature, called "internal weak pull-up" on the digital pins. This means that internally there is already the possibility to enable a weak resistor pulling the voltage to +5V. For this reason, what you need is to just connect the jumper to ground and read it.

simulate this circuit

You will need, in your setup, to set the pin as INPUT\_PULLUP, and then check the value you read:

```
const byte jumperPin = 2;

void setup() {
  pinMode(jumperPin, INPUT_PULLUP);
}

void loop() {
  if (digitalRead(jumperPin) == LOW)
  {
    // Jumper is inserted
  }
  else
  {
    // Jumper is not inserted
  }
}

```

This is what the `DigitalInputPullup` example is for...

Regarding your other question, there is a connector on every board named ICSP (of if there isn't, you should have access to the ICSP pins from somewhere else). This connector is used to flash the bootloader again (or to flash a program with an external programmer). You will need a atmel programmer to restore the original bootloader and "unbrick" it.

Luckily any arduino board can be used for this task; you will just need to download on another board the sketch `ArduinoISP` (already included in Arduino IDE) and you can use it to flash. There is plenty of tutorials online to do it. So to "unbrick" it you will just need another arduino board
> 8 votes

# Answer
First off, the premise:

> having the keyboard open all the time can make it tricky to program

is completely false.

The problems that people experience with programming are when the Arduino is *sending keystrokes all the time without external stimulus*. This makes it tricky to do *anything* \- not just program. Just like it's hard to write a letter when you have a cat walking all over your keyboard.

So as long as you aren't just sending keypresses all the time, and only send them when you actually read a card, there is no problem for you to try and fix.

Secondly, the idea:

> use two of the pins as a jumper check, and have some code in the setup to read the input pin; if the circuit is closed between them, the keyboard function never activates, and if it's open, the Arduino will act as a keyboard.

is overly complex and meaningless. If all you want to do is check a state of "set" or "not set" using some external "device", what you're talking about is a *button*, or a *switch*. You don't need two pins for that - only one. And there's a myriad of tutorials available on the internet showing you in detail how to read the state of a button (or switch). (Hint: use a pin set to INPUT\_PULLUP and connect that pin to GND to "activate" it. Include a small \[100Ω\] resistor for safety if you like).

So in summary:

1. Unless you're being really daft in your program, there is no problem to solve.
2. You are over-thinking your solution.
> 6 votes

---
Tags: pins
---


title: Arduino uno, VIN and 12 volts

text:
# Question
Title: Arduino uno, VIN and 12 volts
I have an arduino Uno with a motor shield attached I would like to drive 2 12 volt dc motors. Can I just attach a 12 volt power supply to the arduino Uno?

I ask because if I can attach a 12 volt power supply to the uno, I would like to also try and drive some leds from the Uno as well. I remember that the VIN jumper needs to be connected if connecting a power supply through the Arduino uno. There is also a pin labeled VIN.

If I can connect a 12 volt power supply to the arduino uno, can I power the leds from the vin pin.

# Answer
Possibly. It depends exactly *what* it is you want to drive.

When you connect 12V to the barrel jack you get about 11.3V out of the VIN pin. This is because there is a diode in series with the barrel jack to protect against reverse polarity connections. This loses some voltage (could be as much as 0.7V).

Also that diode is rated at 1A maximum. So you can't drive anything that would need more than 1A (including the current needed by the Arduino and shield components).
> 3 votes

# Answer
That depends on the motor shield - for some motor shields you have to cut a circuit path (or unset a jumper) to separate the power for the motors from arduino's power!
> 0 votes

---
Tags: arduino-uno
---


title: 1-10 volt analog signal

text:
# Question
Title: 1-10 volt analog signal
I have an Arduino project where I am using an ESP8266 (Wemos D1 mini) powered via USB. I want/need to output an analog voltage from 0 to 10V.

**Goal:**
A solution that is pre-made (eg a shield or sparkfun type module) or easy to build circuit that does not require a new power supply (besides the ones I have which is 3.3V and 5V, thanks to Wemos USB power).

Many devices allow you to control them using a 1-10V signal. I have two LED drivers at home that I would like to interface with: specs1, specs2.

What would be the easiest solution to generate a 1-10 Volt signal? Is there a module I can use?

I read about Op-amps but I don't yet have the knowledge to build one myself. Another method is a DAC, but that seems to require a separate 10 Volt power supply.

# Answer
> 4 votes
You do not need a DAC. In this 'regulation cases' PWM on digitalPin is used. See analogWrite Arduino function.

I use Grove MOSFET module to have PWM of desired voltage. The MCU generates a 3.3 V PWM. MOSFET module gets in my case 5 V as input voltage. You would use 10 V as Vin. MOSFET switches the 10 V line on and off at 'PWM speed' resulting in 10 V PWM.

As 10 V source you could use a 'boost' converter, to convert 5 V to 10 V.

This is the schema of the Grove MOSFET module:

# Answer
> 3 votes
The ADM660, link below,

> is a charge-pump voltage converter that can be used to either invert the input supply voltage giving VOUT = -VIN or double it (ADM660 only) giving VOUT = 2 x VIN.

It accepts an input range between 1.5V-7V so if you use the 5V from the Wemos USB power you'll be able to reach the desired 10V for your application, and it's cheap :)

http://www.analog.com/media/en/technical-documentation/data-sheets/ADM660\_8660.pdf

---
Tags: esp8266, power, pwm
---


# Question
Title: Arduino Mega and gyroscope erroneous values
I have Arduino mega2560 and MPU6050.

I connected to Vcc pin of the gyro to +5V on the mega, the SDA to SDA pin, SDL to SDL pin, AD0 and GND to 2 GND pins.

I used this code:

```
#include<Wire.h>

const int MPU=0x68; //I2C address of MPU
int GyX,GyY,GyZ;
float pitch=0;
float roll=0;
float yaw=0;

float v_pitch;
float v_roll;
float v_yaw;
float a_pitch;
float a_roll;
float a_yaw;

void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU);
  Wire.write(0x6B); //power management register 1
  Wire.write(0);
  Wire.endTransmission(true);
  Serial.begin(9600);
}

void loop() {
  Wire.beginTransmission(MPU);
  Wire.write(0x43);
  Wire.endTransmission(false);
  Wire.requestFrom(MPU,6,true);
  GyX=Wire.read()<<8|Wire.read();
  GyY=Wire.read()<<8|Wire.read();
  GyZ=Wire.read()<<8|Wire.read();
  v_pitch=(GyX/131);
  if(v_pitch==-1) {
    v_pitch=0;
  }
  v_roll=(GyY/131);
  if(v_roll==1) {
    v_roll=0;
  }
  v_yaw=GyZ/131;
  a_pitch=(v_pitch*0.046);
  a_roll=(v_roll*0.046);
  a_yaw=(v_yaw*0.045);
  pitch= pitch + a_pitch; roll= roll + a_roll;
  yaw= yaw + a_yaw;
  Serial.print(" | pitch = ");
  Serial.print(pitch);
  Serial.print(" | roll = ");
  Serial.print(roll);
  Serial.print(" | yaw = ");
  Serial.println(yaw);
}

```

But the values I am reading are not angles at all, plus when I move the X axes for 45 degrees, the value is not like that at all.

I don't want to use the pre made library as I want to understand how to read from Gyroscope. Any ideas?

# Answer
> 1 votes
It is possible to use your sketch and get angle information. It is not very accurate and it drifts.

I started with your sketch, and improved it until I had the angle. The `Serial.println` functions take time and they are printed too often. To measure the interval between the samples, I used `millis`.

This test is done with:

* arduino M0 board (with 3.3v i2c bus)
* gy-521 module with onboard voltage regulator, but no level shifter
* vcc of the gy-521 module connected to 5v (because of the voltage regulator)

The arduino M0 is faster than the arduino mega or uno.

```
// test with arduino M0 board
#include <Wire.h>

#define SER SerialUSB    // 'Serial' for arduino Uno, 'SerialUSB' for Leonardo and Arduino M0

const int MPU = 0x68;   // I2C address of MPU

int16_t x_offset = 0;
int16_t y_offset = 0;
int16_t z_offset = 0;

float pitch = 0.0;
float roll  = 0.0;
float yaw   = 0.0;

unsigned long previousMillisSample;
unsigned long previousMillisOutput;
const unsigned long intervalOutput = 500;  // half a second update to serial monitor

void setup() {
  SER.begin(9600);
  while(!SER);         // wait for serial monitor to open for Leonardo and M0
  SER.println("Angle from gyro");

  Wire.begin();

  Wire.beginTransmission(MPU);
  Wire.write(0x6B); //power management register 1
  Wire.write(0);
  Wire.endTransmission();

  // get the values of the gyro and use them as offset
  GetXYZ(x_offset, y_offset, z_offset);
}

void loop() {

  int16_t GyX;
  int16_t GyY;
  int16_t GyZ;

  GetXYZ(GyX, GyY, GyZ);

  unsigned long currentMillisSample = millis();  // time in millis when this sample is taken

  // remove offset
  GyX -= x_offset;
  GyY -= y_offset;
  GyZ -= z_offset;

  float v_pitch = float(GyX) / 131.0;    // convert to float and calculate degrees
  float v_roll  = float(GyY) / 131.0;
  float v_yaw   = float(GyZ) / 131.0;

  // calculate time in milliseconds between previous and current sample
  unsigned long t = currentMillisSample - previousMillisSample;

  // time in seconds as a float
  float float_t = float(t) / 1000.0;

  // adjust the number of degrees during the time
  float a_pitch = v_pitch * float_t;
  float a_roll  = v_roll  * float_t;
  float a_yaw   = v_yaw   * float_t;

  // remember the time in millis when the sample was taken for the next time
  previousMillisSample = currentMillisSample;

  pitch += a_pitch;
  roll  += a_roll;
  yaw   += a_yaw;

  // Once in a while, print the output
  if(millis() - previousMillisOutput >= intervalOutput) {
    previousMillisOutput = millis();

    SER.print("pitch = ");
    SER.print(pitch);
    SER.print(" | roll = ");
    SER.print(roll);
    SER.print(" | yaw = ");
    SER.println(yaw);
  }
}

void GetXYZ( int16_t &x, int16_t &y, int16_t &z) {
  // Get the gyro values
  Wire.beginTransmission(MPU);
  Wire.write(0x43);     // first register of gyro values
  Wire.endTransmission(false);

  Wire.requestFrom(MPU,6);
  x = Wire.read() << 8 | Wire.read();
  y = Wire.read() << 8 | Wire.read();
  z = Wire.read() << 8 | Wire.read();
}

```

Can you try this sketch? It drifts between 10 and 60 degrees per 5 minutes. That is a lot. I think the sensor is better than that, so that means the sketch is far from perfect.

---
Tags: arduino-mega, accelerometer, mpu6050, gyroscope, atmega2560
---


# Question
Title: problem with reading PS3 controller buttons
I'm working on a camera slider mount with an X stepper (to move along slider), Y stepper (pan left right) and Z stepper (tilt up down). All of this is being controlled by a PS3 controller (PS3BT library).

I've implemented a feature in which all three steppers move from one saved position to other and then back again.. this keeps repeating infinitely. It works fine - except I can't stop it - it's more of a programming issue I think. Here's the code in question

```
// MultiStepper instance - at the top somewhere
MultiStepper StepperControl;

void loop(){
    if(PS3.getButtonClick(START)){ // START to start movement between two POS's.
        Serial.print("\n Starting Movement between POS1 and POS2");
        while(!PS3.getButtonClick(CROSS)){
          StepperControl.moveTo(POS1); // go to POS1
          StepperControl.runSpeedToPosition();
          delay(200);
          StepperControl.moveTo(POS2); // go to POS2
          StepperControl.runSpeedToPosition();
          delay(200);
        }
      }
}

```

My issue is that pressed X (cross) on the keypad, doesn't quit out of the loop. What I feel is happening is that the loop is running too fast and all the moveTo() commands are stacking on top of each other. And so, even if I do press X, too many moveTo() commands have already happened and it just keeps running those "queued" commands.

I've also tried putting an if statement inside the while loop that breaks out of the loop when CROSS is pressed - no luck.

// This isn't the entire code, just the parts I think are relevant.

# Answer
The `while(!PS3.getButtonClick(CROSS))` is only checked once per loop, so your system will complete a move to POS1, wait 200ms, complete a move to POS2, and wait another 200ms before it can check the controller for another button press.

`runSpeedToPosition()` is "blocking", which means NOTHING else can happen while it is doing it's task.

Instead, you probably want to avoid blocking functions and set up a finite state machine and use the `run()` function of `AccelStepper`, which you should call as often as you can and it will move the stepper one step toward the target position, if it's not yet at the target position.

The following rewrite is not tested, but the general structure should show you how you can change the way the program is written. You should think of the `loop()` function running and completing a million times a second, and each time through, you check the **state** (that is, on what step is the system currently on) and act accordingly. Change to a new state when appropriate.

In the example, there are 5 states, corresponding to all possible combinations of what your program could be doing:

* STOPPED: the initial state, the stepper has no target
* RUNTO1: the stepper is moving toward POS1, but hasn't reached it yet
* WAIT1: the stepper has reached POS1 and is now waiting for a specified delay before moving to the next state. This state uses the process shown in the BlinkWithoutDelay standard Arduino example sketch for delaying without blocking.
* RUNTO2: the stepper is moving toward POS2, but hasn't reached it yet
* WAIT2: the stepper has reached POS2 and is now waiting for the next state

You can also see the situations where a state is changed:

* When **START** is pressed, set a new target position and enter the `RUNTO1` state
* When **CROSS** is pressed, stop all stepper action and enter the `STOPPED` state
* When in `RUNTO1` or `RUNTO2`, and the distanceToGo() is zero, enter to the corresponding `WAITn` state
* When in the `WAITn` state and the specified time has elapsed, enter the corresponding next `RUNTOn` state.

Example:

```
#define POS1 80
#define POS2 0

const uint16_t DELAY = 200;
enum stepperstates {STOPPED, RUNTO1, WAIT1, RUNTO2, WAIT2};

[...]

void loop() {
  static uint16_t last_millis;
  static stepperstates xStepState;
  if (PS3.getButtonClick(START)){
    xStepState = RUNTO1;
    StepperControl.moveTo(POS1); // go to POS1
    Serial.print("\n Starting Movement between POS1 and POS2");
  }
  if (PS3.getButtonClick(CROSS)) {
    xStepState = STOPPED;
  }

  StepperControl.run();

  switch (xStepState) {
    case STOPPED:
      StepperControl.stop();
      break;
    case RUNTO1:
      if (StepperControl.distanceToGo()==0) {
        xStepState = WAIT1;
        last_millis = millis();
      }
      break;
    case WAIT1:
      if (millis() - last_millis >= DELAY) {
        xStepState = RUNTO2;
        StepperControl.moveTo(POS2);
      }
      break;
    case RUNTO2:
      if (StepperControl.distanceToGo()==0) {
        xStepState = WAIT2;
        last_millis = millis();
      }
      break;
    case WAIT2:
      if (millis() - last_millis >= DELAY) {
        xStepState = RUNTO1;
        StepperControl.moveTo(POS1);
      }
      break;
  }
}

```
> 1 votes

---
Tags: stepper
---


# Question
Title: Sending PUBX commands to GPS Board (Ublox NEO-6M) through SoftwareSerial
I am having trouble parsing NMEA sentences coming from a GY-NEO6MV2 board (https://www.cytron.io/p-gps-neo6mv2), using the TinyGPS (https://github.com/mikalhart/TinyGPS) library. The GPS board itself is connected to an Arduino Pro Mini 3v3 8MHz (ATmega328)

First of all, to start debugging I want to disable all NMEA sentences other than GGA and RMC (which are the only ones I need for this project)

According to the manual, this can be done by sending PUBX commands through the SoftwareSerial (no need for binary UBX)

I am doing this in the following way

```
#include <SoftwareSerial.h>
#include <TinyGPS.h>

// GPS SoftwareSerial
// Shares pins with (MISO 12/ MOSI 11) used for SPI

#define GPS_RX_PIN 12
#define GPS_TX_PIN 11

TinyGPS gps;
SoftwareSerial GPSSerial(GPS_RX_PIN, GPS_TX_PIN);

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

      GPSSerial.print("$PUBX,40,GLL,0,0,0,0*5C\r\n");
      GPSSerial.print("$PUBX,40,ZDA,0,0,0,0*44\r\n");
      GPSSerial.print("$PUBX,40,VTG,0,0,0,0*5E\r\n");
      GPSSerial.print("$PUBX,40,GSV,0,0,0,0*59\r\n");
      GPSSerial.print("$PUBX,40,GSA,0,0,0,0*4E\r\n");
}

void loop()
{
// ...
}

```

However, the GPS board will not respond to these commands and keep sending all the NMEA sentences.

FWIW, this is the original code I'm building my project on - https://github.com/billygr/arduino-aprs-tracker/blob/master/arduino-aprs-tracker.ino

Any thoughts would be appreciated...

# Answer
> 1 votes
I've tried your code sending those PUBX commands to a ublox module and they work successfully for me.

There are a lot of fakes about on the internet using AT6558 chips repackaged as ublox. Check the GPTXT messages that are output when the GPS module is powered up to see if its really a ublox module or a fake one like this:

```
$GPTXT,01,01,02,MA=CASIC*27
$GPTXT,01,01,02,HW=ATGM332D,0080113573899*18
$GPTXT,01,01,02,IC=AT6558-5N-31-0C500000,J7M911C-B2-008827*50
$GPTXT,01,01,02,SW=URANUS4,V4.3.0.5*18

```

---
Tags: serial, softwareserial, arduino-pro-mini, gps, tinygps
---


# Question
Title: INPUT_PULLUP not work for D8 in my NodeMCU v3
I changed my arduino NodeMCU application pin mode to use INPUT\_PULLUP mode instead of INPUT. D8 input pin is not working as expected, I is always in LOW even the button is pressed or not.

I have 3 input pins (D2, D7, D8), when I changed to internal pull up resistor, I removed each external resistors from input and changed the circuit accourding to this: https://www.arduino.cc/en/Tutorial/InputPullupSerial

D2 and D7 works well, but D8 is not. I checked with a volage between GND and pins:

* when button on D2, D7 is not pressed: 2.95 - 3 V
* when button on D8 is not pressed: 0.8 V
* when button on D2, D7, D8 is pressed: 0V (as expected)

You can see my code in github: https://github.com/kisdaniel/HomeDashboardGarageDoorOpener

# Answer
Pin D8 is esp8266 pin 15. This pin is one of the boot configuration pins and for use on a dev board, it must be pulled down at boot. So the NodeMcu has a pull down circuit on this pin and internal pullup is weaker then this external pulldown.
> 7 votes

---
Tags: pins, nodemcu
---


# Question
Title: How do I select Sensor using chip 74HC138 on Wemos D1 Mini?
I have a project for my graduate degree.

It's about Monitoring Temperature and Humidity using Message Queuing Telemetry Transport on Serial NodeJS. To get sensor data to Wemos D1 Mini and NodeJS had done, also on my MQTT had done. My lecturer wants to get data from two sensors at the edges of the room, he suggests using a 74HC138. I'm using this 74HC138 Datasheet and I'm using this BME280 Library.

This is my schematic:

This is my code:

```
#include <BME280.h>

const uint32_t SERIAL_SPEED = 115200;
const uint8_t SCK_PIN = D5;
const uint8_t MISO_PIN = D6;
const uint8_t MOSI_PIN = D7;
const uint8_t SPI_CS1_PIN = 15;
const uint8_t SPI_CS2_PIN = 14;
const uint8_t GPIO[3] = {D1, D2, D3};

static int32_t temperature, humidity, pressure;
int i;

BME280_Class   BME280;

void setup() {
  Serial.begin(SERIAL_SPEED);
  pinMode(SCK_PIN, OUTPUT);
  pinMode(MOSI_PIN, OUTPUT);
  pinMode(MISO_PIN, INPUT);

  SPI.begin();
  SPI.setBitOrder(LSBFIRST);

  Serial.println(F("condition before loop = "));
  //status_pin();
  for (i = 0; i < 3; i++) {
    pinMode(GPIO[i], INPUT);
    digitalWrite(GPIO[i], HIGH);
  }
  pinMode(SPI_CS1_PIN, OUTPUT);
  pinMode(SPI_CS2_PIN, OUTPUT);

  Serial.println(F("Starting Hardware SPIDemo example program for BME280"));
  Serial.print(F("- Initializing BME280 sensor\n"));

  if ( (!BME280.begin(SPI_CS1_PIN) && (!BME280.begin(SPI_CS2_PIN) ) {
    Serial.println(F("-  Unable to find BME280. Waiting 3 seconds."));
    delay(3000);
  }

  BME280.mode(SleepMode);
  Serial.print(F("- Sensor detected in operating mode \""));
  Serial.print(BME280.mode());
  Serial.println(F("\"."));
  if (BME280.mode() == 0) {
    Serial.print(F("- Turning sensor to normal mode, mode is now \""));
    Serial.print(BME280.mode(NormalMode));
    Serial.println("\"");
  }
  Serial.println(F("- Setting 16x oversampling for all sensors"));
  BME280.setOversampling(TemperatureSensor, Oversample16);
  BME280.setOversampling(HumiditySensor,   Oversample16);
  BME280.setOversampling(PressureSensor,   Oversample16);
  Serial.println(F("- Setting IIR filter to maximum value of 16 samples"));
  BME280.iirFilter(IIR16);
  Serial.println(F("- Setting time between measurements to 1 second"));
  BME280.inactiveTime(inactive1000ms);
  Serial.print(F("- Each measurement cycle will take "));
  Serial.print(BME280.measurementTime(MaximumMeasure) / 1000);
  Serial.println(F("ms.\n\n"));
}

void loop() {
  static uint8_t loopCounter = 0;
  byte pin1 = 0x74;
  byte pin2 = 0x71;

  if ( BME280.begin(SPI_CS1_PIN) == 1 ) {
    selpin(pin1);
    Serial.println(F(" Data Bme = "));
  } else if ( BME280.begin(SPI_CS2_PIN) == 1 ) {
    selpin(pin2);
    Serial.println(F(" Data Bme = "));
    printdata();
  }

  if (++loopCounter % 10 == 0) {
    Serial.print(F("\n- Turning "));
    if (BME280.getOversampling(HumiditySensor) == 0) {
      BME280.setOversampling(HumiditySensor, Oversample16);
      Serial.print(F("ON"));
    } else  {
      BME280.setOversampling(HumiditySensor, SensorOff);
      Serial.print(F("OFF"));
    }
    Serial.println(F(" humidity sensing"));
    Serial.print(F("- Each measurement cycle will now take "));
    Serial.print(BME280.measurementTime(MaximumMeasure) / 1000.0);
    Serial.println(F("ms.\n"));
  }

  Serial.println(F("condition after loop = "));
  //status_pin();
  Serial.println();

}

float altitude(const float seaLevel = 1013.25) {
  int32_t temp, hum, press;
  BME280.getSensorData(temp, hum, press);
  float Altitude = 44330.0 * (1.0 - pow(((float)press / 100.0) / seaLevel, 0.1903));
  return (Altitude);
}

void printdata () {
  BME280.getSensorData(temperature, humidity, pressure);
  Serial.print(F("Temperature : "));
  Serial.print(temperature / 100.0);
  Serial.println(F(" *C"));
  if (BME280.getOversampling(HumiditySensor) != 0) {
    Serial.print(F("Humidity : "));
    Serial.print(humidity / 100.0);
    Serial.println(F(" %"));
  }
  Serial.print(F("Pressure : "));
  Serial.print(pressure / 100.0);
  Serial.println(F(" hPa"));
  Serial.print(F("Altitude : "));
  Serial.print(altitude());
  Serial.println(F(" m"));
  Serial.println();
  delay(5000);
}

```

Serial output always says `Unable to find BME280. Waiting 3 seconds.` I know it's because `CS` pin cannot detect. I think something is missing my code.

**SOLVED**

Thanks to my pal @Majenko, I'm out of the 74HC138 stock but i have 74HC139, i think that's same to me, i tried advice from @Majenko early morning after i make assembly of my board own for define Chip Select Wemos to my enable pin and get back my missing code whom not understand me.

**See below** for verbose log of uploading my sketch.

**See below** for serial monitor.

Thanks.

# Answer
> 3 votes
Using a 74HC138 in this situation is both pointless and wasteful. You're using 3 pins (or 4 - see below) to drive a chip to select between 2 pins. That's wasting one more pin than you would by directly driving the CS pins.

The only time it would make sense would be if you were wanting to connect with 5 or more devices, in which case you would get a saving in the number of pins used.

Anyway - what you are missing from your code is absolutely everything to do with the 74HC138. First off, you're using a library which assumes the CS pins are directly connected to the MCU. Second, there is no code to set the A/B/C pins to the right state to select an output.

If you really *must* use the 74HC138 I would suggest:

* Use the same CS pin in your code for every BMS280 instance.
* Connect that CS pin to G2A on the 74HC138
* Use the following procedure to access a sensor:
    1. Select the correct output on the 74HC138 by setting the A/B/C pins to the binary representation of the output you want
    2. Perform the BME280 operations you want on the relevant instance

simulate this circuit – Schematic created using CircuitLab

The CS pin you passed to the BME280 instances will control the state of the currently selected output on the 74HC138, turning it into a demultiplexer controlled by the A/B/C pins. Using multiple instances of the BME280 class associated with each selected output will allow proper tracking of any internal state and data associated with the device connected to that output.

Or, and this is just throwing ideas out there, don't use the 74HC138 and tell your "lecturer" that it's a stupid idea to use 3 pins (4 including the chip select pin) to control a pair of devices that need a total of 2 pins.

---
Tags: esp8266, sensors, temperature-sensor
---


# Question
Title: Serial communication between python and arduino
I am working on object tracking robot. I am using python and OpenCV to detect the object and send the proper data to the arduino that controls two servo motors. The data which should be sent to the arduino are servo motors angles ranging between 0-180. I am using sample codes to understand how python and arduino communicate using serial bus.When I send a single digit, the arduino receives it and work as intended, but when I send more than one digit nothing happens. This is the arduino code:

```
#include <Servo.h>
int data;
Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0;    // variable to store the servo position

void setup() {
  Serial.begin(9600); //initialize serial COM at 9600 baudrate
  pinMode(LED_BUILTIN, OUTPUT); //make the LED pin (13) as output
  digitalWrite (LED_BUILTIN, LOW);
  myservo.attach(9);
  Serial.println("Hi!, I am Arduino");
}

void loop() {
while (Serial.available()){
 //to receive more than one character
 char buffer[] = {' ',' ',' ',' ',' ',' ',' '}; // Receive up to 7 bytes
 while (!Serial.available()); // Wait for characters
 Serial.readBytesUntil('n', buffer, 7);
 data = atoi(buffer);

}
myservo.write(data);
}

```

And here is the python code:

```
import serial
import time  # Required to use delay functions

arduinoSerialData = serial.Serial('com14', 9600)  # Create Serial port
object called arduinoSerialData
time.sleep(2)  # wait for 2 secounds for the communication to get
established

print arduinoSerialData.readline()  # read the serial data and print it as
line
print ("Enter 1 to turn ON LED and 0 to turn OFF LED")

while 1:  # Do this forever

    var = raw_input()  # get input from user
    print "you entered", var  # print the intput for confirmation

    arduinoSerialData.write(var)

```

# Answer
> 1 votes
If the python Serial write function sends byte, then you should read it in Arduino with Serial.read().

```
void loop() {
  if (Serial.available()){
    byte data = Serial.read();
    myservo.write(data);
  }
}

```

If python sends the number as text, then you can read it with `parseInt()`.

```
void loop() {
  if (Serial.available()){
    int data = Serial.parseInt();
    myservo.write(data);
  }
}

```

The `parseInt` is one of the blocking functions and will by default wait one second for next char after the last sent digit was received. But the number is sent at once from python so the delays between digits are small. Set in `setup()` `Serial.setTimeout(10);`

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


title: How to detect when intercom is ringing?

text:
# Question
Title: How to detect when intercom is ringing?
For my apartment, I need to check when intercom is ringing and call an API in that case. I was thinking about using an AC input / DC output relay, since the buzzer signal is an AC signal. Is there an equivalent pre-built component similar to this?

# Answer
> 2 votes
As it sounds like you do not own the buzzer (it is part of the appartment), someone may not like you directly connecting to it.

If this is a classic buzzer with an electromagnet, consider using a Hall Effect Sensor. The magnetic field generated by the buzzer may be able to activate the Hall Effect Sensor and inform the Arduino the buzzer has been activated. This article talks about Hall Effect sensors and an Arduino.

Image of Arduino and Hall Effect Sensor from linked to article:

Further, this is a much safer way connect to a buzzer. As a classic buzzer can generate very high voltages that can damage processors and other sensitive electronic devices when directly connected.

---
Tags: esp8266, relay, buzzer
---


# Question
Title: TinkerCAD switch seems to be not working (always closed)
I am using TinkerCAD to simulate the functionality of a slide switch. Please comment if you think this question is off-topic.

```
/*
  LiquidCrystal Library - Hello World

 Demonstrates the use a 16x2 LCD display.  The LiquidCrystal
 library works with all LCD displays that are compatible with the
 Hitachi HD44780 driver. There are many of them out there, and you
 can usually tell them by the 16-pin interface.

 This sketch prints "Hello World!" to the LCD
 and shows the time.

  The circuit:
 * LCD RS pin to digital pin 12
 * LCD Enable pin to digital pin 11
 * LCD D4 pin to digital pin 5
 * LCD D5 pin to digital pin 4
 * LCD D6 pin to digital pin 3
 * LCD D7 pin to digital pin 2
 * LCD R/W pin to ground
 * LCD VSS pin to ground
 * LCD VCC pin to 5V
 * 10K resistor:
 * ends to +5V and ground
 * wiper to LCD VO pin (pin 3)

 Library originally added 18 Apr 2008
 by David A. Mellis
 library modified 5 Jul 2009
 by Limor Fried (http://www.ladyada.net)
 example added 9 Jul 2009
 by Tom Igoe
 modified 22 Nov 2010
 by Tom Igoe

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/LiquidCrystal
 */
#include <LiquidCrystal.h>

const byte pin8 = 8;

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  Serial.begin(9600);      // open the serial port at 9600 bps:
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("Welcome.");
}

void loop() {
  byte val = digitalRead(pin8);
  Serial.println(val);
  if(val == HIGH)
  {
    lcd.setCursor(0, 1);
    lcd.print("Switch on right.");
  }
  else
  {
    lcd.setCursor(0, 1);
    lcd.print("Switch on left.");
  }
}

```

The serial monitor and the output of the LCD screen are showing the slide switch to always be on the right side (not creating an open circuit when the switch is on the left side).  As seen in the picture, the switch is on the left. And the code, I think, is correct. So it should display, "Switch on left." This is because `pin8` is low (not connected to 3.3V).

So I'm very confused. The switch appears to be shorting all three rails to which it's connected. When the switch is removed, that part becomes open; `pin8` is low.

# Answer
> -1 votes
As Sener said, "use a pull-down resistor (10K) from pin8 to GND."

And in case anyone notices, yes, I'm aware of `clear()`.

---

TinkerCAD must be assuming a floating input reads high instead of an intrinsically floating ground. The most simple solution is adding `pinMode(pin8, INPUT_PULLUP);` to the setup() function. Then, tie the opposite (than with a resistor) side of the switch to ground: Modified circuit TinkerCAD simulation.

---
Tags: switch, simulator
---


title: Connecting 2 arduino on same ground

text:
# Question
Title: Connecting 2 arduino on same ground
I'm working project which consist of 2 arduino running a 2 different sketch, However, can i make these 2 ic to run on same power +ve and same ground?

# Answer
> 2 votes
Yes, you can. Just be sure, that you connect both Arduinos in parallel to the power source (both power inputs together to the power output of the source and both grounds together to the ground of the source), so that the current for the second Arduino won't flow through the first Arduino. Also use a power source, that is capable oft providing enough current for your needs.

---
Tags: power
---


# Question
Title: Using serial.available to return number of bytes
My code:

```
char data;
int numOfBytes;
void setup() {
    Serial.begin(9600);
}
void loop()
{
    if (Serial.available() > 0)
    {
        int numOfBytes = Serial.available();
        Serial.print("numOfBytes: ");
        Serial.println(numOfBytes);

        data=Serial.read();
        Serial.print("data: ");
        Serial.print(data);
        Serial.print("\n-----------\n");

        delay(500);
    }
}

```

I expected that this code returns 5 and then 4,3,2,1.
But it returned: 1,4,3,2,1

Why?

# Answer
> 3 votes
This is because at the first execution only one byte was received. The Serial interface does not send the data in one big packet of 5 bytes, only because you typed five bytes and started the transmission of all with one press in enter. It is sending the bytes one by one, in other words serial (hence the name). The exact transmission time is dependend on many factors (especially, when other technologies are involved, like the USB interface, when you are transmitting over the Arduinos USB to serial converter).

In this case the first byte is sent, followed by a short break, then the other bytes. The Arduino is fast enough in checking the Serial interface to sense this at 9600 baud.

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


# Question
Title: Can I use a camera sensor from a not functioning smartphone in Arduino or Raspberry pi?
I want to use the OmniVision\_OV16860 camera sensor from a not functioning Moto G4 plus phone to capture pictures using Arduino or Raspberry Pi.

Is it possible to do that? If yes, explain the whole process.

# Answer
> 2 votes
> Is it possible to ... use the OmniVision\_OV16860 camera sensor (on an) Arduino?

It is doubtful as bare image sensors usually require specialized software drivers to be of any use. Also, a common Arduino does not have the power to do image processing. Only the few Arduino's built with unusually powerful processors could handle image processing. But, at this level, expect little support as most do not do image processing on the Arduino platform.

---
Tags: arduino-mega, camera
---


# Question
Title: RF24Mesh master-base node communication delay
I'm trying to build a mesh network using 4 nRF24L01 modules directly connected with Arduino Uno where 1 module is master node and the rest are base nodes.

The workflow is exactly as follows

I'm sending a command in the Arduino IDE serial monitor. The master node receives this command and send it to other base nodes. There's no problem receiving the command on the base node side (from master node) as well as sending the command on the master node side (to base nodes). Upon receiving the command from the master node, base nodes successfully able to read the command and send the response. No problem at all.

But when the master node receives the response status from the base node(s), there's the problem. Master node is not receiving the data immediately. I have to send the command from the Arduino serial monitor repeatedly and on the 10th time, the master node is able to read the response status from the base node(s). Exactly on the 10th times every time.

Here's the source.

**master node**

```
// global variables
int dat2;
String temp1 = "";
boolean actualDataSent = false;

// get input from arduino serial monitor

 while (Serial.available() > 0) {
      // my command
      String temp1 = Serial.readString();
}

// write block
if (actualDataSent == false && temp1 != "") {

    // send this data to the base node one by one char
    for (int j = 0; j < mesh.addrListTop; j++)
    {
      for (int k = 0; k < temp1.length(); k++) {
        char ch = (char)temp1.charAt(k);
        Serial.print("NodeID: ");
        Serial.print(mesh.addrList[j].nodeID);
        Serial.print(" RF24Network Address: 0");
        Serial.println(mesh.addrList[j].address, OCT);
        RF24NetworkHeader header(mesh.addrList[j].address, OCT);
        Serial.println( network.write(header, &ch, sizeof(ch)) == 1 ? F("Send OK") : F("Send Fail"));
      }
      actualDataSent = true;
    }
    temp1 = "";
  }

// read block
else if (network.available() && actualDataSent == true) {
    RF24NetworkHeader header;
    network.peek(header);

    switch (header.type) {
      case 'M':
        network.read(header, &dat2, sizeof(dat2));
        Serial.print("Got: ");
        Serial.print(dat2);
        Serial.print(" from RF24Network address 0");
        Serial.println(header.from_node, OCT);
        actualDataSent = false;
        break;
      default: network.read(header, 0, 0); Serial.print("Not M case"); Serial.println(header.type); actualDataSent = false; break;
    }
  }

```

**base node**:

```
//global variables

String mypayload = "";
int res1;

// receive command from master
while (network.available()) {
    RF24NetworkHeader header;
    network.read(header, &payload, sizeof(payload));
    mypayload.concat(payload);
  }
  if (mypayload != "")
  {
    Serial.print("Received data: ");
    Serial.println(mypayload);
    if ((mypayload == "100%"))
    {
      res1 = 1;
      Serial.println("Turn ON");
      if (!mesh.write(&res1, 'M', sizeof(res1))) {
      if ( ! mesh.checkConnection() ) {
        Serial.println("Renewing Address");
        mesh.renewAddress();
      } else {
        Serial.println("Send fail, Test OK");
      }
    } else {
      Serial.print("Send OK: "); Serial.println(res1);
    }
    }
    else if (mypayload == "0%")
    {
      res1 = '1';
      Serial.println("Turn OFF");
      if (!mesh.write(&res1, 'M', sizeof(res1))) {
      if ( ! mesh.checkConnection() ) {
        Serial.println("Renewing Address");
        mesh.renewAddress();
      } else {
        Serial.println("Send fail, Test OK");
      }
    } else {
      Serial.print("Send OK: "); Serial.println(res1);
    }
    }
    mypayload = "";
  }

```

# Answer
The nRF24L01 "ACK\_PAYLOAD" feature allows for two-way data transfer in a single radio transaction. This is more complicated to set up but plenty of tutorials can be found online, on arduino stackexchange and of course another very helpful source is the nRF24L01 data sheet. This should solve your problem by ensuring the master/slave radio messages are sent in the same, rather than independent, radio transactions.
> 1 votes

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