# Question
Title: How to get the angle from vertical window blinds
How can i know the angle of the vertical window blind by placing a small sensor on one of the blind slat

i am trying to make a arduino/esp8266 controlled window blinds, the controlling can be easily achieved in horizontal blinds, but my apartment has a vertical blind which are not interconnected at the bottom

Tried so far:

1. open and close based on time which it takes to open and close, but it keeps drifting over time
2. Cannot use light sensor to sense the ambient light, does not give correct information (day and night)
3. Tried to put a potentiometer on top of one of the blind slat ( no enough room to place things there, potentiometers have more friction)

any suggestions for angle sensor ?

# Answer
> 2 votes
A hall-effect sensor, plus a small magnet attached (glue?) to the outside edge of one slat ought to be able to tell you the strength of the magnetic field, and thus the distance of the magnet from the sensor. From that, given that the rotation is with a fixed radius, you can deduce the angle while introducing zero additional friction.

Edit: I had imagined something like:

However, looking again, this introduces difficulty in detecting the 90deg position, where the magnetic flux lines are exactly parallel to the hall-effect sensor plane.

If you experiment with this enough, you may be able to get repeatable values from the sensor to know the angle of the blind slats.

Edit 2:

The timing measure you noted in your question could also be a possibility. If you could use a microswitch or photo-interrupt sensor on the extreme ends of travel (0deg and 180deg), so that any time those extreme ends are detected, you can eliminate drift.

# Answer
> 0 votes
> How to get the angle from vertical window blinds

vertical blinds have by definition a 90degree angle.

unless "angle" means something else to you.

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


title: ESP8266 disconnects after relay switch

text:
# Question
Title: ESP8266 disconnects after relay switch
the aim of the project I'm working on is to water my bonsai automatically, depending on numerous sensor inputs. So basically I have Arduino Nano with huminity and light sensor, a relay to switch the water pump and ESP8266 wifi module, which I use to check the data from the sensors in the Blynk app on my phone. I use two isolated circuits. The first one is used only by the DC motor (water pump) and is supplied by a 5V 600 mA power source. The second takes care of the rest (arduino, ESP, sensors, relay) while it's supplied by a 5V 1A power source. I'm using this with the ESP8266 board.

Once I run the program, it connects to the Blynk server and I can read data from the sensors on my phone. The problem comes when I want to switch the relay from the Blynk app. Than the ESP8266 disconnects (nearly immediately, or after few seconds). I tried a different DC motor (not a water pump) and it worked fine. I also tried to switch the pump without using EPS8266, that worked as well (so the code should be ok). I think this has something to do with the current draw caused by the water pump, but that makes no sense - I'm using two independent circuits, the pump draws maximally 300 mA from the 600 mA source, while the rest of the electronics draws no more than 200 mA from the 1 A power supply. Neither different power supplies, nor another relay worked.

Here's my code:

```
#define BLYNK_PRINT Serial
#define BLYNK_DEBUG

#include <ESP8266_Lib.h>
#include <BlynkSimpleShieldEsp8266.h>

#include <BH1750.h>
#include <Time.h>
#include <SoftwareSerial.h>

#define PUMP  10
#define SENSOR A0
#define BUTTON 2

char ssid[] = "XXXXX";
char pass[] = "XXXXXXXXXXXXXXXXXX";

SoftwareSerial EspSerial(11, 12);
ESP8266 wifi(&EspSerial);

BlynkTimer timer;
BH1750 lightMeter;
int humidity;
int light;
bool pressed = 0  ;
bool pump=1;
char auth[] = "XXXXXXXXXXXXXXXXXXXXXXXXXX";

void sendData(){
      humidity=analogRead(SENSOR);
      light=lightMeter.readLightLevel();
      Blynk.virtualWrite(V0,humidity);
      Blynk.virtualWrite(V1,light);
//      Serial.print("humidity: ");
//      Serial.println(humidity);
//      Serial.print("light: ");
//      Serial.println(light);
}
void checkConnection(){
  if(!Blynk.connected()){
    digitalWrite(PUMP,1);
    Blynk.begin(auth, wifi, ssid, pass);
  }
 }
void checkButton(){
  if(digitalRead(BUTTON) && pressed){
     Blynk.virtualWrite(V3,digitalRead(BUTTON));
     pump=!pump;
//      Serial.println("pump from button");
     }
  else if(digitalRead(BUTTON) && !pressed){
    pressed=1;
    }
  else{
    pressed=0;
    }
}
BLYNK_WRITE(V2)
{
    Serial.println("switching pump");
    pump=!param.asInt();
    digitalWrite(PUMP,pump);
}
void setup() {
  Serial.begin(9600);
  delay(10);
  EspSerial.begin(9600);
  delay(10);
  lightMeter.begin();
  pinMode(PUMP, OUTPUT);
  pinMode(BUTTON, INPUT);
  digitalWrite(PUMP, pump);
  Blynk.begin(auth, wifi, ssid, pass);
  timer.setInterval(5000L, sendData);
  //timer.setInterval(5L, checkButton);
//  timer.setInterval(2000L, checkConnection);
  }

void loop() {
  if (Blynk.connected()) {
      Blynk.run();
      timer.run();
    }
}

```

and the Blynk log:

```
[2631095] <[06|05|14|00|00]
[2631389] >[00|05|14|00|C8]
[2632112] <[14|05|15|00|08]vw[00]0[00]632
[2632280] <[14|05|16|00|07]vw[00]1[00]28
[2637109] <[14|05|17|00|08]vw[00]0[00]630
[2637214] <[14|05|18|00|07]vw[00]1[00]28
[2641393] <[06|05|19|00|00]
[2651445] Cmd error
[2656470] Cmd skipped:20
[2656471] Cmd skipped:20

```

\[EDIT\] and the circuit:

# Answer
> 2 votes
The problem was hidden in a wrong relay wiring. Once I'm using only COM and NO PIN as it is showed in this article, not only that the whole system is stable and the ESP8266 is not disconnecting any more, but I can also power the circuit using only one 5V 2A power supply.

Here's my updated schematics

---
Tags: esp8266, arduino-nano
---


# Question
Title: Can I set pin 13 to output 5v, then put arduino mini pro to sleep?
Can I set pin 13 to output 5v, then put arduino pro mini to sleep and it maintains 5v going through pin 13 while in sleep mode?

I know there are various "levels" of sleep - can a voltage be maintained on a pin for all/any of the sleep modes?

# Answer
> can a voltage be maintained on a pin for all/any of the sleep modes?

yes.
> 3 votes

# Answer
Given the absence of clarity on the driving state of pins during sleep, consider connecting Pin 13 to an SR Latch or the gate of a MOSFET.

An SR Latch will hold it's output high or low until a high is presented on the Set or Reset inputs, so connect Pin 13 to the Set input, with a pull-down resistor -- even if the MCU in sleep mode allows the voltage output to drain away to 0v, the SR Latch will maintain it's output.

A MOSFET gate has a non-trivial capacitance which can hold a charge if the gate's driver goes high-impedance, thus holding the gate open after the driver is disconnected.
> 3 votes

---
Tags: arduino-pro-mini, sleep
---


title: Arduino Uno - relay with separate power

text:
# Question
Title: Arduino Uno - relay with separate power
i want to operate a relay with an ARDUINO UNO, but i want to use a separate power supply for the relay. Ive seen relays with VCC and jVCC (dont know what that is), but mine only has this pins: GND, IN1, IN2, VCC. how should i connect it to the Arduino and the external power supply?

# Answer
> 3 votes
This relay is designed to operate on 5V.

Most commonly this will come from the Uno's `5v` pin.

## If you want to externally power the relay itself then make sure to connect the `+5` to the `Vcc` on the relay board and the `-` lead to the `GND` on the relay board.

**Uno's `GND` must also be connected to the `GND` on the relay so the Digital outputs from the Uno will properly control the `IN1` and `IN2` inputs to the relay board.**

---

The Uno has multiple `GND` connections so it makes the most sense to connect the `-` to one of them then another to the relay.

---

Note that the Uno's 9V Vcc external power comes in through the barrel connector on the Uno itself. The Uno will pass power through its internal regulator to provide `5v` at the appropriate connection.

---

If you are switching external devices that run on 120V it would be on the screw-terminal side of the board only.

---

> To prevent accidental activation of the relays, note that this particular board is `ACTIVE-LOW` which means that as you initialize the output pins you should first set them `HIGH` so setting the pinMode will not default to `LOW` which would trigger the relay.

In the `setup()` section, using pins D5 and D6 as an example:

```
digitalWrite(5,HIGH); pinMode(5,OUTPUT);
digitalWrite(6,HIGH); pinmode(6,OUTPUT);

```

# Answer
> 2 votes
The Arduino and the external PSU should have the GND or - connected with each other.

Then connect the external PSU + or Vcc to the relay boards Vcc.

# Answer
> 1 votes
External psu to gnd and vcc, in1 and in2 to arduino pins which control each relay (on is LOW) and most importantly gnd also to arduino gnd.

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


# Question
Title: Connecting multiple boards to Arduino Uno r3
How can I connect the Arduino RFID RC 522 and SD card adapter to one Arduino Uno R3? As each library takes specific pins in Arduino for MOSI, MISO, CLK. So I have conflict in the pins, how can this be solved?

# Answer
> 2 votes
Short answer: yes, you can. No pin conflict, but you will need an extra SS pin for the second SPI device. \[If you can, use the I2C version of your device.\]

Unlike the I2C, the SPI bus uses separate lines for sending and receiving data, and it employs an additonal line (SS, SS1, SS2, ...) for selecting which slave device you are talking to. This adds additonal wires, but also eliminates needing different slave device addressses. So what this means is instead of specifying the address of the slave device, we simply address that slave device by turning on its SS pin. It's a lot more simple.

So, if you have two devices (RFID reader and SD Card Adapter), the conections looks like this:

The thing is, you need to use two Arduino pins for selecting the devices you want to talk to: one pin select the RFID reader; the other, the SD card.

Arduino has a fixed pin assignment for SPI comunications:

Because all devices share the MOSI, MISO, and SCLK lines, all commands sent from the master arrive at each slave device. The SS pin tells the slave whether it should ignore this data or respond to it. Importantly, this means that you must make sure to only have one SS pin LOW.

So you can see now how it's a minimum of four data lines that must be present in any SPI system. The MISO, MOSI, and SCLK signals are shared common with all slave devices. However, the SS chip cannot; it must be separate, because each slave device needs its own unique connection so that it alone can be addressed when the master device wants to communicate with it. So for each additional slave device that you add, you must have an additional line available on the master device for that slave device. So, using the above diagram as an example, if we have added a third slave device, we would have to add another SS3 data line to the master device and then connect to the SS pin of that third slave device.

---
Tags: arduino-uno, sd-card, rfid
---


title: Disabling Timer2

text:
# Question
Title: Disabling Timer2
I am working on a Heart Rate Monitoring project, using this Sensor from sparkFun, plugged to Arduino pro mini and reading proper BPM, I have an LED connected to pin 13 of my Arduino that blinks when the pulse happen. The code given on SparkFun page works on Timer2

I have two more LEDs connected to pin12 and pin11, which indicates battery percentage - because i am powering my Arduino using a 2 cell lithium ion battery with Voltage regulator.. I also have a voltage divider circuit at the voltage regulator with 1K resistors and connected to analog pin A0 for monitoring battery voltage.

I have assigned LED connected on pin 13 as LED1, on 12 as LED2 and 11 as LED3

LED1 for low charge LED2 for half charge LED3 for full charge

Here is the problem :

When i connect charger ,Arduino reads data from voltage divider and outputs levels to LEDS

Here - LED1 is conflicting between the pulse sensor (which is working on Timer2) and also for indicating the low level charging, and LED1 is flickering.

how to overcome with this issue.? disabling Timer2 helps.? if'Yes' then how to do that.?

Note : I don't want to sample Heart Rate Pulse when charger is connected!

Thank you very much.

Best

```
void charging() {
TCCR2A = 0;
usbState = digitalRead(usb_detect);
while (usbState == HIGH) {
usbState = digitalRead(usb_detect);
// read the input on analog pin 0:
int sensorValue = analogRead(A1);
// Convert the analog reading (which goes from 0 - 512) to a voltage (0
- 3.3V):
float voltage = sensorValue * (3.3 / 512.0);
// print out the value you read:
if (voltage >= 2.5 && voltage <= 3.3)
{

  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }
    digitalWrite(gps_led, ledState);
    digitalWrite(blinkPin, LOW);
    digitalWrite(save_led, LOW);
  }
}

if (voltage >= 3.4 && voltage <= 3.7)
{
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(blinkPin, ledState);
    digitalWrite(gps_led, HIGH);
    digitalWrite(save_led, LOW);
  }
}

if (voltage >= 3.8 && voltage <= 4.1)
{
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(save_led, ledState);
    digitalWrite(blinkPin, HIGH);
    digitalWrite(gps_led, HIGH);
  }

}

Serial.println(voltage);

delay(1);        // delay in between reads for stability

}
}

```

# Answer
> 1 votes
Timer 2 is fundamental to that code. It is used to sample the heart rate sensor at a regular period. If you disable that timer you will never sample the sensor.

You cannot have two functions on one LED - it makes no sense. You should decide on one and only one function to use that LED for. If you want to use it for the battery status then remove the code from the timer interrupt that controls the LED. If you want to use it to display the hear beat then you will have to make do with just two LEDs for your battery status.

If the two operations are mutually exclusive then yes you can disable the timer. Just turn it off, then turn it on again when you want sampling to start again.

Off:

```
TCCR2B = 0;

```

On (assuming you are using this code):

```
TCCR2B = 0x06;

```

# Answer
> 1 votes
in the linked repo in the product page you linked there is a explanation page how to use the device without using timers buried at the bottom of a file:

https://github.com/WorldFamousElectronics/PulseSensor\_Amped\_Arduino/blob/master/PulseSensorAmped\_Arduino\_1.5.0/Timer\_Interrupt\_Notes.ino#L217

In essence instead of using the timer interrupt you put the sampling code in the `loop()` body triggered by a software timer and make sure that there are no `delay()` or busy loops happening in it.

# Answer
> 0 votes
you provide lots of information that has nothing to do with your question, and at the same time omitted critical information that can help other help you.

> how to overcome with this issue.?

the simplest would be to move the pins so they have their dedicated pins.

> disabling Timer2 helps.? if'Yes' then how to do that.?

if you want to reuse the pins -\> multiple functions on the same pin, you may have to code as such. For example, you disconnect the led briefly, read the pulse sensor, and then restore the led. if you do that sufficiently quick, you wouldn't notice that the led had been disconnected.

the feasibility of such approaches will depend on the sensors connected to that pin and your ability to code.

---
Tags: arduino-uno, timers
---


title: Best way to store files on Arduino

text:
# Question
Title: Best way to store files on Arduino
I was wondering what is the best way to store files on Arduino, I've seen that is possible using the SD Card module but I only want like 2/3 file texts so having a whole SD Card for that sounds a bit overkill, is there any other way to store files like that?

Cheers!

# Answer
If you want files, then you need a filesystem. The only simple to use and reliable things on an Arduino that have a filesystem are SD cards or USB memory sticks through the USB Host Shield.

However, most of what people think they want to store in "text files" is actually data that can better be stored in other ways. Using text to store numeric values that only the Arduino will ever see is pointless - store it as numeric values.

The most convenient place to store such values (if you don't have lots of them) is in the internal EEPROM.

If you have more than a few values you can use an external EEPROM or serial Flash chip to store larger amounts of data.

Anything more than that, though, and SD card rapidly becomes the most cost effective method.
> 2 votes

# Answer
> Best way to store files on Arduino

what's best (or not) depends on your criteria, which you didn't articulate.

The simplest (and dumbest) way is to use a sd card. generally a waste of space and pins for small files.

the 2nd best is to use flash or eeprom: limited space and potentially risky. this can be partially addressed via out-board storage devices.

the best is to not store files on arduino: transmit the content away and let more capable devices to handle that.
> 2 votes

# Answer
The Arduino Uno uses the ATmega328P microcontroller. That microcontroller is able to write the EEPROM 100,000 times. As far as I know, that is 100,000 times per EEPROM location.

Suppose you want to run it for 10 years, then 10 years / 100k is about 1 hour. That means you can write to EEPROM every hour. Storing settings is no problem. There is even a EEPROM.update function that only writes the data when the data has changed.

If you want to store the latest settings every second, then you need to look for something else.

Important note: When storing settings (in EEPROM or SD memory card) the Arduino could be powered off while it is busy writing. Those settings will not be valid. Therefor you might have to add a checksum, store a copy of the settings, and keep default settings in the code in case both the settings and its copy are not valid.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Wireless Shield Not being detected w/ Arduino Uno R3
Wireless Shield is not being detected by arduino, not MAC address is displaying. Not sure what to try next, there is nothing noticeably wrong with the shield at first glance.

Green LED under status is on.

```
Shield Type: CC3000 WiFi Shield
Board Model: UNO R3

```

No Mac Address is being detected (my output in Serial Monitor)

```
Initializing Wifi...
MAC: 0:0:0:0:0:0
Scanning available networks...
** Scan Networks **
number of available networks:0

```

My Script:

```
#include <SPI.h>
#include <WiFi.h>

void setup() {
  // initialize serial and wait for the port to open:
  Serial.begin(9600);
  while(!Serial) ;

  // attempt to connect using WEP encryption:
  Serial.println("Initializing Wifi...");
  printMacAddress();

  // scan for existing networks:
  Serial.println("Scanning available networks...");
  listNetworks();
}

void loop() {
  delay(10000);
  // scan for existing networks:
  Serial.println("Scanning available networks...");
  listNetworks();
}

void printMacAddress() {
  // the MAC address of your Wifi shield
  byte mac[6];

  // print your MAC address:
  WiFi.macAddress(mac);
  Serial.print("MAC: ");
  Serial.print(mac[5],HEX);
  Serial.print(":");
  Serial.print(mac[4],HEX);
  Serial.print(":");
  Serial.print(mac[3],HEX);
  Serial.print(":");
  Serial.print(mac[2],HEX);
  Serial.print(":");
  Serial.print(mac[1],HEX);
  Serial.print(":");
  Serial.println(mac[0],HEX);
}

void listNetworks() {
  // scan for nearby networks:
  Serial.println("** Scan Networks **");
  byte numSsid = WiFi.scanNetworks();

  // print the list of networks seen:
  Serial.print("number of available networks:");
  Serial.println(numSsid);

  // print the network number and name for each network found:
  for (int thisNet = 0; thisNet<numSsid; thisNet++) {
    Serial.print(thisNet);
    Serial.print(") ");
    Serial.print(WiFi.SSID(thisNet));
    Serial.print("\tSignal: ");
    Serial.print(WiFi.RSSI(thisNet));
    Serial.print(" dBm");
    Serial.print("\tEncryption: ");
    Serial.println(WiFi.encryptionType(thisNet));
  }
}

```

# Answer
Your problem:

* You have a CC3000 WiFi shield
* You are using the WiFi library for the Arduino WiFi Shield
* The Arduino WiFi Shield is a HDG204 based shield, not CC3000

Get the right library for your shield, install it, and try the examples and tutorials that come with it.
> 1 votes

---
Tags: arduino-uno, wifi, shields, library, wireless
---


title: Sim808: Is My GPS Module Broken?

text:
# Question
Title: Sim808: Is My GPS Module Broken?
Is my GPS module broken?

My GPS returns `$GPGGA,000250.262,,,,,210,,2,700,,*4C` as NMEA. Why there is no latitude longitude? the first value is the UTC time, but there are so many null values `,,,,,` Is my GPS module broken?

---

## Edited

My Sim808 model is SIM808 Module GPRS SMS Development Board IPX SMA with GSM GPS Antenna

What makes me think why is this broken is because the day before, the module keep giving me location for every second. The lock was almost instant. I use the module at the same place like before. It is weird because the module is so unstable, yesterday was fine but the next day it takes forever to lock location.

# Answer
> 1 votes
Many fields will empty until the unit can get a lock. $GPGSV messages will tell you how many satellites it currently sees, and how strong the transmissions are. The first lock can take several minutes, and it can be very difficult to get a lock indoors.

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


# Question
Title: Why did my pushbutton LED circuit work when my wiring was wrong?
I had a Coursera Arduino homewhere wherein you create a simple pushbutton-controlled LED circuit.

I used the example "button.ino" script that's builtin to the Arduino IDE, without modification. I'll reproduce it at the end of this question.

Here's what I did (wrong):

My circuit went from 5V Power to the top pin of a push button. The bottom of the pushbutton was (correctly) wired to Pin 2 on one side and a resistor was used to wire the other bottom pin to the anode of LED. The cathode of the LED was wired to ground.

The reason I think this is wrong is that I forgot that I was supposed to wire the LED to a pin corresponding to `ledPin` in the example script. The example script uses Pin 13, which has the builtin LED. I was using an external LED. Yet, the circuit worked perfectly.

Why did it work? Doesn't that mean the 5V power output was getting turned off (I'd guess you call that being set to LOW) when Pin 13 was set to LOW? Why would that be the case?

```
/*
  Button

 Turns on and off a light emitting diode(LED) connected to digital
 pin 13, when pressing a pushbutton attached to pin 2.

 The circuit:
 * LED attached from pin 13 to ground
 * pushbutton attached to pin 2 from +5V
 * 10K resistor attached to pin 2 from ground

 * Note: on most Arduinos there is already an LED on the board
 attached to pin 13.

 created 2005
 by DojoDave <http://www.0j0.org>
 modified 30 Aug 2011
 by Tom Igoe

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/Button
 */

// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

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

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
  }
  else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}

```

# Answer
The LED wired to the push button was turned ON by the push button closing the circuit, without any intervention from the micro controller. That's a pretty simple circuit: a voltage source, a switch, an LED and a resistor, all in series. When you close the circuit the LED turns on. Simple.

The code on your microcontroller is watching the state change on the button and turning ON/OFF the on board LED: it has nothing to do with the LED in your circuit/breadboard.
> 2 votes

# Answer
The circuit you are describing seems to just have the button control whether the LED got the supply or not. Unless pin2 was grounded, you effectively supplied 5V to the resistor-LED as well as pin2 through the button. This essentially gives you the standard LED circuit. Have a great day!
> 2 votes

# Answer
> Why did it work?

the button is shorting the led (turning it off) when it is closed. when the button is open, the led lights up from the resistor.

essentially your arduino is not involved with the led's operations.
> 2 votes

---
Tags: power, led, button
---


# Question
Title: How to use Multiple MPU9250 to Arduino Lilypad
Is it possible to connect more than one or to be specific 5 MPU9250 into 1 Arduino lilypad? How will I set the addresses, and where should I put the pins for SDA and SCL? I hope someone out there could help me on this project.

Cheers!

What if I have this working codes, how will I edit this to connect more than two MPU9250? Please guide me. Thanks.

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

 #define    MPU9250_ADDRESS            0x68

 #define    MAG_ADDRESS                0x0C

 #define    GYRO_FULL_SCALE_250_DPS    0x00
 #define    GYRO_FULL_SCALE_500_DPS    0x08
 #define    GYRO_FULL_SCALE_1000_DPS   0x10
 #define    GYRO_FULL_SCALE_2000_DPS   0x18

 #define    ACC_FULL_SCALE_2_G        0x00
 #define    ACC_FULL_SCALE_4_G        0x08
 #define    ACC_FULL_SCALE_8_G        0x10
 #define    ACC_FULL_SCALE_16_G       0x18

 // This function read Nbytes bytes from I2C device at address Address.
// Put read bytes starting at register Register in the Data array.
void I2Cread(uint8_t Address, uint8_t Register, uint8_t Nbytes, uint8_t*      Data)
{
// Set register address
Wire.beginTransmission(Address);
Wire.write(Register);
Wire.endTransmission();

// Read Nbytes
Wire.requestFrom(Address, Nbytes);
uint8_t index=0;
while (Wire.available())
Data[index++]=Wire.read();
}

// Write a byte (Data) in device (Address) at register (Register)
void I2CwriteByte(uint8_t Address, uint8_t Register, uint8_t Data)
{
// Set register address
Wire.beginTransmission(Address);
Wire.write(Register);
Wire.write(Data);
Wire.endTransmission();
}

// Initial time
long int ti;
volatile bool intFlag=false;

// Initializations
void setup()
{
// Arduino initializations
Wire.begin();
Serial.begin(115200);

// Set accelerometers low pass filter at 5Hz
I2CwriteByte(MPU9250_ADDRESS,29,0x06);
// Set gyroscope low pass filter at 5Hz
I2CwriteByte(MPU9250_ADDRESS,26,0x06);

// Configure gyroscope range
I2CwriteByte(MPU9250_ADDRESS,27,GYRO_FULL_SCALE_1000_DPS);
// Configure accelerometers range
 I2CwriteByte(MPU9250_ADDRESS,28,ACC_FULL_SCALE_4_G);
 // Set by pass mode for the magnetometers
 I2CwriteByte(MPU9250_ADDRESS,0x37,0x02);

 // Request continuous magnetometer measurements in 16 bits
 I2CwriteByte(MAG_ADDRESS,0x0A,0x16);

 pinMode(13, OUTPUT);
 Timer1.initialize(10000);         // initialize timer1, and set a 1/2   second period
 Timer1.attachInterrupt(callback);  // attaches callback() as a timer overflow interrupt

 // Store initial time
 ti=millis();
 }

 // Counter
 long int cpt=0;

 void callback()
  {
  intFlag=true;
  digitalWrite(13, digitalRead(13) ^ 1);
  }

  // Main loop, read and display data
  void loop()
  {
  while (!intFlag);
  intFlag=false;

  // Display time
  Serial.print (millis()-ti,DEC);
  Serial.print ("\t");

   // _______________
  // ::: Counter :::

   // Display data counter
  //  Serial.print (cpt++,DEC);
 //  Serial.print ("\t");

  // ____________________________________
  // :::  accelerometer and gyroscope :::

 // Read accelerometer and gyroscope
 uint8_t Buf[14];
 I2Cread(MPU9250_ADDRESS,0x3B,14,Buf);

 // Create 16 bits values from 8 bits data

// Accelerometer
int16_t ax=-(Buf[0]<<8 | Buf[1]);
int16_t ay=-(Buf[2]<<8 | Buf[3]);
int16_t az=Buf[4]<<8 | Buf[5];

// Gyroscope
int16_t gx=-(Buf[8]<<8 | Buf[9]);
int16_t gy=-(Buf[10]<<8 | Buf[11]);
int16_t gz=Buf[12]<<8 | Buf[13];

 // Display values

// Accelerometer
Serial.print (ax,DEC);
Serial.print ("\t");
Serial.print (ay,DEC);
Serial.print ("\t");
Serial.print (az,DEC);
Serial.print ("\t");

// Gyroscope
Serial.print (gx,DEC);
Serial.print ("\t");
Serial.print (gy,DEC);
Serial.print ("\t");
Serial.print (gz,DEC);
Serial.print ("\t");

// _____________________
// :::  Magnetometer :::

// Read register Status 1 and wait for the DRDY: Data Ready

uint8_t ST1;
do
{
 I2Cread(MAG_ADDRESS,0x02,1,&ST1);
}
while (!(ST1&0x01));

// Read magnetometer data
uint8_t Mag[7];
I2Cread(MAG_ADDRESS,0x03,7,Mag);

// Create 16 bits values from 8 bits data

// Magnetometer
int16_t mx=-(Mag[3]<<8 | Mag[2]);
int16_t my=-(Mag[1]<<8 | Mag[0]);
int16_t mz=-(Mag[5]<<8 | Mag[4]);

// Magnetometer
Serial.print (mx+200,DEC);
Serial.print ("\t");
Serial.print (my-70,DEC);
Serial.print ("\t");
Serial.print (mz-700,DEC);
Serial.print ("\t");

// End of line
Serial.println("");
//  delay(100);
 }

```

# Answer
> 1 votes
> Is it possible to connect more than one or to be specific 5 MPU9250 into 1 Arduino lilypad?

Yes, that is possible with both SPI and I2C. With SPI you will need MOSI(11), MISO(12), SCK(13), and CSn where CSn is CS0..CS4 are digital pins in output mode for chip select.

With I2C the following pins are needed SDA(A4), SCL(A5), and CSn. The chip select pin is connected to AD0 on the device. AD0 is used for the lowest bit in the I2C address. Addressing is achieved by connecting AD0 to CSn and keeping all high except the one that is addressed. The I2C address is the same for all access. The CSn pin defines which device will response.

The example code below uses the lower address and chip select is put low for the selected device.

```
// Chip select pin device#0
const int CS0 = 4;
...
void setup()
{
  ...
  // Initiate chip select pin for device#0
  pinMode(CS0, OUTPUT);
  digitalWrite(CS0, HIGH);
  ...
}
...
void loop()
{
   ...
   // Select device#0
   digitalWrite(CS0, LOW);
   MPU9250_someFunction();
   digitalWrite(CS0, HIGH);
   ...
}

```

> How will I set the addresses, and where should I put the pins for SDA and SCL?

SDA is connected to A4 and SCL to A5.

Using the above given example code (from the question) a rewrite of the I2Cread function could be:

```
// This function read Nbytes bytes from MPU9250 device with chip select pin.
// Put read bytes starting at register Register in the Data array.

void MPU9250_read(uint8_t CS, uint8_t Register, uint8_t Nbytes, uint8_t* Data)
{
  digitalWrite(CS, LOW);

  // Set register address
  Wire.beginTransmission(MPU9250_ADDRESS);
  Wire.write(Register);
  Wire.endTransmission();

  // Read Nbytes
  Wire.requestFrom(Address, Nbytes);
  uint8_t index = 0;
  while (Wire.available()) Data[index++] = Wire.read();

  digitalWrite(CS, HIGH);
}
...
// Read magnetometer data from device#3
uint8_t Mag[7];
MPU9250_read(CS3, 0x03, 7, Mag);

```

Cheers!

# Answer
> 3 votes
> where should I put the pins for SDA and SCL?

Same as on a Uno:

* SDA is on pin A4
* SCL is on pin A5

> Can you suggest me some links that can help me learn more about SPI?

I have an SPI page and also one about I2C.

There is also a page about SPI on this site: How do you use SPI on an Arduino?

If you want to use 5 devices, it sounds like Majenko's recommendation is good: Use SPI. You would share MOSI/MISO/SCK between all devices (D11/D12/D13), and give each one a separate SS (slave select) line.

# Answer
> 1 votes
According to the datasheet the MPU-9250 can work in either I2C or SPI mode.

When it is in SPI mode you can connect up as many MPU-9250s as you have spare IO pins. With SPI the clock and data lines are all shared, and each slave device has its own Slave Select line.

In I2C mode it is possible to only use 2 devices at once - the AD0 pin configures which is which device (connect it to GND or VCC to identify the two devices).

Interestingly the MPU-9250 does include an I2C master module for connecting other sensors to it. Theoretically it should be possible to connect the master port of an MPU-9250 to two other MPU-9250s, and each of those could connect to a further two MPU-9250s each, and so on and so forth in a huge tree. However the programming of such an environment would be an absolute nightmare and not something I would like to undertake.

So in summary: use SPI mode, it's simpler.

# Answer
> 0 votes
If you use I2C, you can use an I2C multiplex chip to handle the arbitration to handle lots of MPU-9250s. I had a setup with 6x of them going. I did find however, that the amount of CPU time that it takes for I2C communication is high, so once you get in to that many 9250s, you don't have much CPU time left over for other things. Using SPI is a bit trickier to get going, but it is wicked fast and also lets you take advantage of the FIFO buffer on the 9250s.

Majenko mentioned using the I2C master functionality on the 9250 to daisy chain - I had also tried that approach before I tried the I2C multiplexer. I have to say it was a horrible experience. When you use that I2C master function, you are actually programming the advanced functionality of the 9250 instead of using the Arduino coding in C. Once it all starts working (if it does), it acts quite flaky. That functionality on the chip was really designed to enable using an external magnetometer on the 6250 to get 9dof. Any more complex use than that gets hairy with the interchip timing, and initializing on startup is also rough.

Final answer - put in the time to learn how to use the SPI bus as mentioned in some of the other answers. Once you get through the learning curve, it can run at up to 20khz communication speed. SPI is designed for high speed communication. I2C is designed to be easier to use but for things with lower update rates.

---
Tags: arduino-mega, accelerometer, gyroscope, magnetometer
---


# Question
Title: Uploading Arduino bootloader to ATmega32U4 with another Arduino?
I am in a situation where it is useful if I can upload a bootloader into an ATmega32U4 using another Arduino like this, for ex:https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard. I have a different circuit though.

Is there a reason to believe that this can't be adapted to ATmega32U4?

Are there any important differences between the ATmega328P and ATmega32U4, that I have to take into account for this to work?

# Answer
The only difference you have to take into account is that if you're using an ATmega32U4 board such as Leonardo the SPI pins are not broken out to the pin headers along the edge of the board as is the case with the Uno shown in the tutorial you linked. Instead you should connect the programmer board to the ICSP header pins on your ATmega32U4 board, where the SPI pins are broken out:

* MISO: ICSP-1
* MOSI: ICSP-4
* SCK: ICSP-3

So this means you can't follow the wiring shown on the tutorial exactly but it should be very easy to adapt that tutorial to your needs.
> 1 votes

---
Tags: bootloader, isp
---


# Question
Title: Standalone 328p Programming with CH340G programmer
I have made a standalone arduino board with a Atmega328p w/ Uno bootloader taking inspiration from this video https://youtu.be/sNIMCdVOHOM However, when I try to program mine all I get is "Problem uploading to board". I have confirmed that everything on the board works and that I could upload Blink through my arduino Uno via ArduinoISP but I would like to use this adapter to program the board instead.

Other things that I have tried: Swapping Tx/Rx from adapter to board

Adding 100nF capacitor on DTR to RST

Trying without DTR

(The board also has a 10k pullup resistor on the RST line)

Burning a new bootloader after programming with Arduino as ISP

Any suggestions are greatly appreciated.

Thanks,

Verbose Upload Output

`Sketch uses 928 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
C:\Program Files\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM7 -b115200 -D -Uflash:w:C:\Users\Admin\AppData\Local\Temp\arduino_build_446007/Blink.ino.hex:i`

```
     Using Port                    : COM7
     Using Programmer              : arduino
     Overriding Baud Rate          : 115200

```

`avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xe8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe8`

`avrdude done. Thank you.
Problem uploading to board.`

# Answer
> I have confirmed that everything on the board works and that I could upload Blink through my arduino Uno via ArduinoISP but I would like to use this adapter.

Because the ATmega family does not support a partial flash erase via ISP, loading a sketch via ISP removes the bootloader.

Therefore you must (re)load a suitable bootloader using the ISP connection, before you can perform a serial upload of a sketch using that bootloader.
> 2 votes

# Answer
There are two stages to programming a chip. First is to get the firmware (the bootloader, for example) on there, which you have done.

Second is to configure the chip to operate in the way you have wired it up. Specifically to configure the oscillator and clock source.

The bootloader and your sketch all expect the chip to be running at 16MHz. It uses that constant value to calculate things like the baud rate for serial communications. If the chip isn't running at 16MHz then all those calculations will be meaningless.

You have connected a 16MHz crystal, which is good, but unless you tell the chip to use it you will still be using the internal oscillator for your clock source as set in the factory. This is an 8MHz oscillator with clock division down to 1MHz.

You need to configure the fuse bits on the chip using avrdude and your Arduino as an ISP.

This article details exactly how to do it and teaches you what the fuses are and what they mean.
> 2 votes

---
Tags: atmega328, uploading
---


# Question
Title: How to call more than 10 different functions based on serial input?
I'm looking to basically call functions based on the serial ID I assign to it. For example, if I want to call function A I would type on the serial A and if I want to call function B then I would type B.

Now I have taken a look at some arduino.cc ASCII and other lookup tables but I'm still not getting my results. YES I can indeed make up serial calls 1 through 9 using char datatype but as you can see I'm only limited to 9 function calls and so this is where I'm looking for tips. How can I expand this serial ID as I'm calling it?

```
char id;
int led = 6; // the PWM pin the LED is attached to

void setup() {
  Serial.begin(9600);
  pinMode(led, OUTPUT);
}

void loop() {
  id = Serial.read();
  /*
    will only read the 1st bit on the buffer so
    no 10s...90s because the whole char so we
    need to use Strings datatype somehow but
    the thing is that the Serial.Read func only
    reads the first byte. R&D?
  */
  if (id == '1') {
    digitalWrite(led, HIGH);
  } else if (id == '2') {
    digitalWrite(led, LOW);
  }
}

```

So in my above example I'm using `char` to communicate. I know there are other datatypes but not sure which is the best suited for the 100's of functions I would like to call via terminal.

I thought about using the alphabet A-Z as well as a-z to double the function calls but I would like to come up with something a bit more formal rather than single numbers or single letters (char).

# Answer
> 2 votes
First, you could use a string for the commands. You just need to ensure there is some special char to mark the end of a command - like the newline char. Read the input from the port one char at a time, building the string as you go:

```
char buffer[256];
uint16_t buffer_index = 0;
void loop() {
  while (Serial.available()) {
    int c = Serial.read();
    if ('\n' == c) {
      buffer[buffer_index] = 0;   // Append EOS
      // Complete message - do something
      buffer_index = 0;   // Reset, ready for next message
    }
    else {
      // Append char to end of buffer
      buffer[buffer_index++] = c;
    }
    // Check for overflow
    if (256 == buffer_index) {
        buffer_index = 0;
    }
  }
}

```

There are plenty of examples like this on this site.

Next, I don't recommend using an `if` statement with a hundred or more conditions. Instead, you can store pointers to each function in an array:

```
// Use a typedef to simplfy
typedef void (*function_type)(); // A function with no params and no return, change as needed
// Fixed array size
const int max_functions = 200;
// Create an array of 200 function pointers
function_type all_functions[max_functions] = {0};

```

So to call function #11:

```
all_functions[10]();

```

Now you just need a way to marry the function pointers to a name. A hash table could work here. A hash function converts a string to a number. There are lots of examples on the web. Here's one:

```
uint16_t djb2_hash(const char *str)
{
    unsigned long hash = 5381;
    int c;

    while (0 != (c = *str++)) {
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
    }

    // Note: we use the mod operator to make sure value
    // is less than array size
    return hash % max_functions;
}

```

Create two functions, one to add a function and one to retreive:

```
bool add_function(const char *name, function_type f)
{
  // Convert name to number
  uint16_t index = djb2_hash(name);  //  0 <= index <= max_functions
  if (NULL != all_functions[index]) {
    // There is already a function stored at this index
    Serial.print("Adding ");
    Serial.print(name);
    Serial.print("failed. index = ");
    Serial.println(index);
    return false;
  }
  else {
    // Store the function in the array
    all_functions[index] = f;
    return true;
  }
}
bool run_function(const char *name)
{
  uint16_t index = djb2_hash(name);
  if (NULL == all_functions[index]) {
    // Name not found
    return false;
  }
  else {
    // Call the function
    all_functions[index]();
    return true;
  }
}

```

Last, create some functions and add to hash table:

```
void f1() {Serial.println("F1");}
void f2() {Serial.println("F2");}
void f3() {Serial.println("F3");}

void setup() {
  Serial.begin(9600);
  add_function("F1", f1);
  add_function("F2", f2);
  add_function("F3", f3);
}

```

All that's left is to modify `loop()` to call the functions when a complete message is received.

```
void loop() {
  while (Serial.available()) {
    int c = Serial.read();
    if ('\n' == c) {
      buffer[buffer_index] = 0;
      run_function(buffer);
      buffer_index = 0;
    }
    else {
      buffer[buffer_index++] = c;
    }
    // Check for overflow
    if (256 == buffer_index) {
        buffer_index = 0;
    }
  }
}

```

If you enter "F1", "F2", or "F3" in the serial monitor, those functions should execute. Just make sure you change the serial monitor to append a newline.

Some notes: the hash function may not create a unique id for each string. You need to handle this situation. Also, the names are case sensitive. If you don't want that, convert everything to all upper case or all lower.

# Answer
> 0 votes
a state machine would be the most efficient approach here.

first, you need to process each valid input - making sure that it is between 0..9. then you need to form a 2-digit number with that. for that to work, you will need to be able to tell when the input ends - lots of ways to do that.

the heart of the code would be something like this:

```
current_input = valid_input();  //obtain valid input
input = cmd_2dig(current_input); //2-dig commands
switch (cmd_2dig) {
  case 0: do_cmd0(); break;
  case 1: do_cmd1(); break;
  case ....
  default: reset_cmd(); //invalid command, reset command buffer
}

```

---
Tags: serial-data
---


title: Connecting ESP8266 to Arduino Uno

text:
# Question
Title: Connecting ESP8266 to Arduino Uno
I want to get data from ESP to my Arduino. I added firmware v2 to my ESP and it works correctly in my serial USB to TTL and shows the JSON data that I send to it.

But when I connect to my Uno serial it shows some unknown chars.

```
#include <SoftwareSerial.h> //Including the software serial library
#define DEBUG true
SoftwareSerial esp8266(2, 3); // This will make the Arduino pin 2 as the RX pin and Arduino pin 3 as the TX. Software UART
/* So you have to connect the TX of the esp8266 to the pin 2 of the Arduino and the TX of the esp8266 to the pin 3 of the Arduino. This means that you need to connect the TX line from the esp to the Arduino's pin 2 */

void setup() {
  Serial.begin(115200); // Setting the baudrate to 9600
  esp8266.begin(115200); // Set it according to your esp’s baudrate. Different esp’s have different baud rates.
  pinMode(11, OUTPUT); // Setting the pin 11 as the output pin.
  digitalWrite(11, LOW); // Making it low.
  pinMode(12, OUTPUT); // Setting the pin 12 as the output pin..
  digitalWrite(12, LOW); // Making pin 12 low.
  pinMode(13, OUTPUT); // Setting the pin 13 as the output pin.
  digitalWrite(13, LOW); // Making pin 13 low.
  sendData("AT+RST\r\n", 2000, DEBUG); //This command will reset module to default
  sendData("AT+CWMODE=2\r\n", 1000, DEBUG); // This will configure the mode as access point
  sendData("AT+CIFSR\r\n", 1000, DEBUG); // This will get ip address and will show it
  sendData("AT+CIPMUX=1\r\n", 1000, DEBUG); // This will configure the ESP8266 for multiple connections
  sendData("AT+CIPSERVER=1,80\r\n", 1000, DEBUG); // This will set the server on port 80
}

void loop() {
  if (esp8266.available()) {
    // Checking that whether the esp8266 is sending a message or not (Software UART Data)
    while (esp8266.available()) {
      // Checking whether ESP8266 has received the data or not
      char c = esp8266.read(); // Read the next character.
      Serial.print(c);
      // Storing the response from the ESP8266
    }
  }
}

String sendData(String command, const int timeout, boolean debug) {
  // Function to send the data to the esp8266
  String response = "";
  esp8266.print(command); // Send the command to the ESP8266
  long int time = millis();
  while ((time + timeout) > millis()) {
    // ESP8266 will wait for some time for the data to receive
    while (esp8266.available()) {
      // Checking whether ESP8266 has received the data or not
      char c = esp8266.read(); // Read the next character.
      response += c; // Storing the response from the ESP8266
    }
  }
  if (debug) {
    Serial.print(response);
   // Printing the response of the ESP8266 on the serial monitor.
  }
  return response;
}

```

Prints this for me:

```
???AR)?WS?TZ?eO?C?AJ+CIFSR
+CIFSR:APHP,"192.168.4.1"
+CIFSQ:APMAC,"62:01:94:22:96:7e"

OK
AZ??R????jC?u?H?AT+CIPSERVDR=1,80

OK
0,CONNECT

+IPD,0,385:POST / HTTP/1.1
cache-control: no-cache
Postman-Token; 45494ff7-b3e1-400f-8afc-fcda26514705
Content,Type: application/jsonUser-Agent: PostmanRunthme/6.1.6
@ccept: */*Host: 192.178.4.1
accept-encoding: gzip, defl`te
content,length: 14Connection: keep-alive
{"name":"`li"}0,CLOSED

```

My correct JSON is: `{"name":"ali"}`. But it shows incorrectly. And I set the mt serial library to `#define _SS_MAX_RX_BUFF 1024`.

How can I fix this?

My connection is:

# Answer
i used AT+UART\_DEF=9600,8,1,0,0 and it works correctly now
> 3 votes

# Answer
Software serial doesn't work reliably at 115200. You need to use a lower baud rate:

1. Connect the ESP8266 back to your serial USB to TTL setup.
2. Send the following command to reconfigure the ESP8266 to do AT communication at 9600 baud: `AT+UART_DEF=9600,8,1,0,3`
3. Change line 9 of your sketch to `esp8266.begin(9600);`. This will cause the Uno to communicate with the ESP8266 at 9600 baud.
4. Upload the revised sketch to your Uno and connect it back up to the ESP8266.
> 2 votes

# Answer
Try connecting arduino's TX and RX pins (0 and 1) with esp8266's RX and TX and see if it works. Upload a blank sketch. Whatever you type in serial box will be sent to esp. Instead of using voltage divider you should use logic level converters with LM2596.
> 1 votes

---
Tags: esp8266
---


# Question
Title: What is the proper way to make library pin mappings configurable?
I am working with some libraries that provide APIs for interacting with specific hardware chips (that makes these drivers?). However, different custom boards or shields will have the chip mapped to different pins meaning the library needs to be modified for each case. Needing to modify the library does not work well with the Arduino IDE Library Manager.

Are there preferred/recommended patterns for exposing this configuration so that the library itself does not need to be modified every time?

Here is an example where it is documented which part needs to be changed to match the pin layout of your board.

# Answer
> 6 votes
The method I use is to provide the pins as parameters to the constructor. Those pin numbers are stored in variables to use later in the `.begin()` function and elsewhere.

Most of the time I use initialization lists to keep things simple. For example:

```
class Something {
    uint8_t _cs;
    uint8_t _dc;

    Something(uint8_t cs, uint8_t dc) : _cs(cs), _dc(dc) {}
    void begin();
};

void Something::begin() {
    pinMode(_cs, OUTPUT);
    pinMode(_dc, OUTPUT);
}

Something mySomething(10, 8);

```

# Answer
> 6 votes
I would use either of the following two possibilities:

**Use (class) variables and set them within the constructor.**

Advantages:

* Always initialized
* Easy to use (constructor and pin setup at once)

**Use a separate (e.g. Init) method.**

Advantages:

* Can be dynamically changed

**Remarks**

For pin settings, mostly static circuits are used so the first approach is probably better.

For settings, mostly the second method is better.

If many pins are involved (not likely), use a structure or separate pin settings class.

**Macros**

What I wouldn't advice is macros. When users need to change source code themselves, and new versions are installed, they either have to merge or redo the changes again. The advantages is a bit less (machine)code, a little bit faster probably and a bit less memory usage, but all three aspects are minimal.

# Answer
> 3 votes
In case you'd avoid the C++ constructor stuff that's quite commonly an overkill on Arduino, you could use `#define`'s (object-like macros).

Like so:

```
#define PIN_ONE 1
#define PIN_TWO 2

```

The preprocessor will seamlessly replace `PIN_ONE` with the number 1 and `PIN_TWO` with 2 assuming those definitions are in the library header `.h` file. This will most likely takes the least amount of resources compared to the other possible solutions.

### Alternative 1

If you have the opportunity to use modern-ish C++, you can use `constexpr` to define variables. Compared to macros you'll get type checking and it should be just as efficient.

# Answer
> 2 votes
depending on your approach.

1) if you just provide the binary + header files, you will have to make the pins variables.

2) if you provide the source code and expect the user to recompile the source code, use macros.

---
Tags: library, pins
---


# Question
Title: How can I move an arduino library into my project repo and use it from there?
I've got this project that that is using the LiquidCrystal.h library. My import looks like this...

```
#import <LiquidCrystal.h>

```

I've tried making a 'libraries' folder in my repo, and copying the LiquidCrystal directory from arduino's global libraries folder to my\_project/libraries and changing my import to...

```
#import "libraries/LiquidCrystal/LiquidCrystal.h"

```

and it explodes on me. I know the path is right, because it gives me a different error if I change the import path to be wrong... but even when it's right, I get this traceback...

```
Arduino: 1.8.1 (Mac OS X), TD: 1.36, Board: "Arduino/Genuino Uno"

/var/folders/sz/cdsmvqws6rq9839mhd802prm0000gp/T//cc4gIISN.ltrans0.ltrans.o: In function `__static_initialization_and_destruction_0':
/Users/chris/art/greenhouse/greenhouse/greenhouse.ino:36: undefined reference to `LiquidCrystal::LiquidCrystal(unsigned char, unsigned char, unsigned char, unsigned char, unsigned char, unsigned char)'
etc....

```

What's the deal? Aren't I supposed to be able to import libraries with an absolute path to the library? This is literally the same file.

What is the difference between `#import <foo.h>` and `#import "my_libraries/myfoo.h"` ?

# Answer
> What's the deal? Aren't I supposed to be able to import libraries with an absolute path to the library? This is literally the same file.

Yes you can use both absolute and relative paths, but "libraries/LiquidCrystal/LiquidCrystal.h" is a relative path because it doesn't start from `C:\\` or `/` basically. Also make sure you get the `LiquidCrystal.cpp` file which actually contains all the functions `LiquidCrystal.h` specifies.

> What is the difference between #import and #import "my\_libraries/myfoo.h" ?

`#include "my_libraries/myfoo.h"` specifies that `myfoo.h` is in a folder `my_libraries` first searched for in `current_folder/my_libraries/myfoo.h` then quote directories and rest of the search paths later, `#include <foo.h>` specifies that `foo.h` is a system header, it's only searched for in search paths.

Solution here would be saying inside your sketch that it is in a subfolder, that the folder is one folder below and then two folders deeper for ex. `#include "../libraries/LiquidCrystal/LiquidCrystal.h"` this here assumes your sketch is in `root_folder/Sketch/Sketch.ino` and library in `root_folder/libraries/LiquidCrystal/LiquidCrystal.h`.
> 2 votes

# Answer
Try it with this folder structure:

```
my_project
|_src
  |_LiquidCrystal

```

and change the import to:

```
#import "src/LiquidCrystal/LiquidCrystal.h"

```

Since Arduino IDE 1.6.10, recursive compilation of the sketch folder has been limited to the `src` subfolder (see Arduino/arduino-builder#148).

By the way, it's much more common to use `#include` instead of `#import`, which is deprecated and will cause a compiler warning. Any properly written library will not require the use of `#import`.
> 0 votes

---
Tags: arduino-uno
---


title: Debouncing, or problem with my code?

text:
# Question
Title: Debouncing, or problem with my code?
I'm using a simple microswitch on pin 2, to activate an external interrupt.

```
void pause()
{
  Serial.print("\n\nPause\n\n");
  delay(1000);
}

void setup()
{
  pinMode(2, INPUT_PULLUP);
  attachInterrupt(0, pause, RISING);
  Serial.begin(9600);
  delay(1000);
}

void loop()
{
  Serial.print("\nGoing");
  delay(100);
}

```

When I tap the micro switch, some reason, my serial monitor output looks like this:

Just to clarify, there is no delay between any of

Is this just some serious debouncing, causing my Arduino to find lots of rising instances? or is there some kind of problem in my code?

# Answer
> 1 votes
I have a page about using switches but since I don't want to give a link-only answer I'll summarize here.

---

## Detect switch changes

What is needed is to detect a *transition*. That is, either:

* It was closed and is now open.

Or:

* It was open and is now closed.

To do that you need to "remember" the previous state of the switch and detect a change, like this:

```
const byte switchPin = 8;
byte oldSwitchState = HIGH;  // assume switch open because of pull-up resistor

void setup ()
  {
  Serial.begin (115200);
  pinMode (switchPin, INPUT_PULLUP);
  }  // end of setup

void loop ()
  {
  // see if switch is open or closed
  byte switchState = digitalRead (switchPin);

  // has it changed since last time?
  if (switchState != oldSwitchState)
    {
    oldSwitchState =  switchState;  // remember for next time
    if (switchState == LOW)
       {
       Serial.println ("Switch closed.");
       }  // end if switchState is LOW
    else
       {
       Serial.println ("Switch opened.");
       }  // end if switchState is HIGH
    }  // end of state change

  // other code here ...

  }  // end of loop

```

This code looks for changes, and only displays something when the switch changes.

---

By the way, you should be doing neither `delay` nor `Serial.print` inside an interrupt, as both of the rely upon interrupts being active, and interrupts are not active inside an ISR.

---

## Debouncing

A simple technique is just to build in a short delay, for example 10 milliseconds (ms). For example:

```
const byte switchPin = 8;
byte oldSwitchState = HIGH;  // assume switch open because of pull-up resistor
const unsigned long debounceTime = 10;  // milliseconds

void setup ()
  {
  Serial.begin (115200);
  pinMode (switchPin, INPUT_PULLUP);
  }  // end of setup

void loop ()
  {
  // see if switch is open or closed
  byte switchState = digitalRead (switchPin);

  // has it changed since last time?
  if (switchState != oldSwitchState)
    {
    oldSwitchState =  switchState;  // remember for next time
    delay (debounceTime);   // debounce
    if (switchState == LOW)
       {
       Serial.println ("Switch closed.");
       }  // end if switchState is LOW
    else
       {
       Serial.println ("Switch opened.");
       }  // end if switchState is HIGH
    }  // end of state change

  // other code here ...

  }  // end of loop

```

In the above code the delay is inside `loop` (where it is OK to use it) and causes a short pause to allow the switch to stop bouncing.

---

## Debouncing without delay

The above code is fine in simple applications, and if you test it, you should find that the message "Switch closed." and "Switch opened." should only occur once per switch press. But, there's a problem. If you hang around the Arduino forums for a little while you will probably see people telling you "don't use `delay`". There are various reasons for this, not the least is which that using delay stops your code from doing anything else useful (like testing sensors, controlling motors, flashing LEDs, etc.).

The code below does not use `delay`, but rather checks for the time that has elapsed after you hit the switch, and sees if the "debounceTime" (in this case 10 ms) has elapsed. If not, it ignores the transition.

```
const byte switchPin = 8;
byte oldSwitchState = HIGH;  // assume switch open because of pull-up resistor
const unsigned long debounceTime = 10;  // milliseconds
unsigned long switchPressTime;  // when the switch last changed state

void setup ()
  {
  Serial.begin (115200);
  pinMode (switchPin, INPUT_PULLUP);
  }  // end of setup

void loop ()
  {
  // see if switch is open or closed
  byte switchState = digitalRead (switchPin);

  // has it changed since last time?
  if (switchState != oldSwitchState)
    {
    // debounce
    if (millis () - switchPressTime >= debounceTime)
       {
       switchPressTime = millis ();  // when we closed the switch
       oldSwitchState =  switchState;  // remember for next time
       if (switchState == LOW)
          {
          Serial.println ("Switch closed.");
          }  // end if switchState is LOW
       else
          {
          Serial.println ("Switch opened.");
          }  // end if switchState is HIGH

       }  // end if debounce time up

    }  // end of state change

  // other code here ...

  }  // end of loop

```

More information on the Arduino site: http://arduino.cc/en/Tutorial/Debounce

---

> It is essential for me to use an interrupt, because I need to be able to pause my entire program, at the push of a button, then resume it when the button is pushed again. I heard from other people that I cannot use any type of delay in the interrupt, is this true?

You don't really pause a program with `delay`, it is now just doing something else (waiting for a timer to reach a certain time). Timers depend on interrupts to update counters as the hardware timer will overflow (roll over) very rapidly.

I suggest a redesign. In your main loop, for example, you could detect the switch press, and then not do anything until it is pressed again. For example, where I had "other code here" in my example:

```
static bool switchWasPressed;

if (switchWasPressed)
  {
  // do nothing
  }
else
  {
  // do what you want to do continuously
  }

```

Now, in the code which detects switch presses you toggle `switchWasPressed`. So instead of:

```
Serial.println ("Switch closed.");

```

You put:

```
switchWasPressed = !switchWasPressed;  // toggle switch press state

```

# Answer
> 1 votes
Do you really need to use an interrupt to debounce a switch? If not, this library may work for you: https://playground.arduino.cc/uploads/Code/Debounce.zip. It is easy to use and assumes you are using a normally open switch with one connection to ground and the other connected to pin 4 on the Arduino.

```
    #include <Debounce.h>
    const byte SWITCH = 4;

    Debounce debouncer = Debounce(50, SWITCH);

    void setup(){
      Serial.begin(9600);
      pinMode(SWITCH, INPUT_PULLUP);
    }

    void loop(){
      if(debouncer.update()){
        if(debouncer.read() == 0){
          Serial.println("Button Pressed");
        }
        else if(debouncer.read() == 1){
          Serial.println("Button Released");
        }
      }
    }

```

# Answer
> 0 votes
Yes, it is bouncing of your button.

You are seeing it because `delay()` does not work, and cannot be used, in an interrupt.

Also delaying in an interrupt is completely opposite to the whole ethos of interrupt programming.

# Answer
> 0 votes
your code works as coded - whether it works as expected is unknown.

basically the isr is triggered on the first edge, and the execution loops around in the isr, and the execution returns one second later.

As a result, your code missed most of the "bouncing", actually it missed all bounces other than the very first one.

not an effective debouncing strategy.

yes, delays or while loops can be used in an isr, so long as you know what you are doing.

---
Tags: serial, debounce
---


# Question
Title: MAX7219 with Arduino UNO - LED control doesn't work
I'm very new to Arduino and this is my first project, so I may misunderstand something simple.

As a hardware I'm using 4 MAX7219 connected to Arduino UNO and a single diod for tests.

As a software I have Waoyda's LedControl 1.06 for MAX72XX.

It seems, I'm completely missing something, because with the code below, the diod is never lit, regardless on matrix position it is connected to.

```
#include "LedControl.h"

LedControl lc=LedControl(12,11,10,4);

void setup() {
  int devices=lc.getDeviceCount();
  for(int address=0;address<devices;address++) {
    lc.shutdown(address,false);
    lc.setIntensity(address,8)
    lc.clearDisplay(address);
  }
}

void loop() {
  int devices=lc.getDeviceCount();

  for(int row=0;row<8;row++) {
    for(int col=0;col<8;col++) {
      for(int address=0;address<devices;address++) {
        lc.setLed(address,row,col,true);
      }
    }
  }
}

```

Some high res photos: , ,

UPD: scheme added.

# Answer
> 1 votes
OMG, the only problem was a typo in `LedController` initialisation! I used `LedControl lc=LedControl(12,11,10,4);` instead for `LedControl lc=LedControl(11,12,10,4);`. It seems the library has no error detection if passed data pin isn't really a data pin. Now everything works fine.

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


title: Arduino Video player?

text:
# Question
Title: Arduino Video player?
I want to play video from SD card by using arduino mega 2560 and TFT 3.2" touch screen is it possible ?

if yes please tell me.

thanks in adavance

# Answer
> 1 votes
An ATMEGA2560 has no enough computational power to perform on-the-fly decoding, even at resolutions as low as 160x128 pixels and low frame rates.

The best you can hope for is a 20 fps, 16 bpp, 160x128 pixel video, directly streamed from the SD card, uncompressed (800kB/s), if the MCU runs at 16MHz. Even with such low specs, you'll have to use a trick, to implement a direct peripheral to peripheral transfer.

We made a guide here for the Arduino Uno (i.e. ATMEGA328P), but it should work also for ATMEGA2560 with little modifications: https://next-hack.com/index.php/2017/08/14/how-to-play-a-video-on-arduino-uno-46-playing-a-20-fps-animation-from-sd-card/

On the same link you'll find also the youtube links for a video guide.

---
Tags: arduino-mega, sd-card, tft
---


# Question
Title: someone can help please? am getting an error saying expected } at the end of input
```
    //set initial values
int x = 0; // set initail zero value for the counter
int preE = 512; // set initial value for light intensity in east direction
int preW = 512; // set initial value for light intensity in west direction
int predtime = 512; // set initial value for delay time
int pretol= 512; // set initial value for tolerance value
void setup() {
  Serial.begin(9600); // set the baud rate for the serial monitor

  // first set the relays off
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  digitalWrite(7,HIGH);
  digitalWrite(8,HIGH); // began the loop
}

  void loop()
  {
    // Read the first reading

    //read the east LDR
    int E1 = analogRead(5); //read the west LDR
    int W1 = analogRead(4); // read the delay time potentiometer
    int dtime1 = analogRead(1);
    //read the tolerance potentiometer
     int tol1 = analogRead(0); // Check if the readings reasonable, otherwise set them to previous ones.

if (E1 < 10 || E1 > 1000 )
{
  E1 = preE ;
  }
  if (W1 < 10 || W1 > 1000 )
  {
    W1 = preW ;
    }
    if (dtime1 < 10 || dtime1 > 1000 )
    {
      dtime1 = predtime ;
      }
      if (tol1 < 10 || tol1 > 1000)
      {
        tol1 = pretol ;
        }
        delay(100); // delay for one 0.1 second and take the next reading

        int E2= analogRead(5);
        int W2= analogRead(4);
        int dtime2= analogRead(1);
        int tol2= analogRead(0);
        if (E2 < 10 || E2 > 1000 )
        {
          E2= preE ;
        }

if (W2 < 10 || W2 > 1000 )
{
  W2= preW ;
  }
  if (dtime2 < 10 || dtime2 > 1000 )
  {
    dtime2= predtime ;
    }
    if (tol2 < 10 || tol2 > 1000 )
    {
      tol2= pretol ;
      }
      delay(100); // delay for one 0.1 second and take the third reading

      int E3= analogRead(5);
      int W3= analogRead(4);
      int dtime3= analogRead(1);
      int tol3= analogRead(0);
      if (E3 < 10 || E3 > 1000 )
      {
        E3= preE ;
        }
        if (W3 < 10 || W3 > 1000 )
        {
          W3= preW ;
          }
          if (dtime3 < 10 || dtime3 > 1000 )

{
  dtime3= predtime ;
  }
  if (tol3 < 10 || tol3 > 1000 )
  {
    tol3= pretol ;
    }
    int E4 = analogRead(5);
    int W4 = analogRead(4);
    int dtime4= analogRead(1);
    int tol4= analogRead(0);
    if (E4 < 10 || E4 > 1000 )
    {
      E4= preE ;
      }
      if (W4 < 10 || W4 > 1000 )
      {
        W4= preW ;
        }
        if (dtime4 < 10 || dtime4 > 1000 )
        {
          dtime4= predtime ;
          }
          if (tol4 < 10 || tol4 > 1000 )
          {
            tol4= pretol ;
            }

delay(100);
int E5 = analogRead(5);
int W5 = analogRead(4);
int dtime5= analogRead(1);
int tol5= analogRead(0);
if (E5 < 10 || E5 > 1000 )
{
  E5= preE ;
  }
  if (W5 < 10 || W5 > 1000 )
  {
    W5= preW ;
    }
    if (dtime5 < 10 || dtime5 > 1000 )
    {
      dtime5= predtime ;
      }
      if (tol5 < 10 || tol5 > 1000 )
      {
        tol5= pretol ;
      }
      delay(100);
      int E6 = analogRead(5);
      int W6 = analogRead(4);
      int dtime6= analogRead(1);
      int tol6= analogRead(0); if (E6 < 10 || E6 > 1000 )
      {
E6= preE ;
}
if (W6 < 10 || W6 > 1000 )
{
  W6= preW ;
  }
  if (dtime6 < 10 || dtime6 > 1000 )
  {
    dtime6= predtime ;
    }
    if (tol6 < 10 || tol6 > 1000 )
    {
      tol6= pretol ;
      }
      delay(100);
      int E7 = analogRead(5);
      int W7 = analogRead(4);
      int dtime7= analogRead(1);
      int tol7= analogRead(0);
      if (E7 < 10 || E7 > 1000 )
      {
        E7= preE ;
        }
        if (W7 < 10 || W7 > 1000 )
        {
          W7= preW ;
          }
          if (dtime7 < 10 || dtime7 > 1000 )

{
  dtime7= predtime ;
  }
  if (tol7 < 10 || tol7 > 1000 )
  {
    tol7= pretol ;
    }
    delay(100);
    int E8 = analogRead(5);
    int W8 = analogRead(4);
    int dtime8= analogRead(1);
    int tol8= analogRead(0);
    if (E8 < 10 || E8 > 1000 )
    {
      E8= preE ;
      }
      if (W8 < 10 || W8 > 1000 )
      {
        W8= preW ;
        }
        if (dtime8 < 10 || dtime8 > 1000 )
        {
          dtime8= predtime ;
          }
          if (tol8 < 10 || tol8 > 1000 )
          {
            tol8= pretol ;
            }

delay(100);
int E9 = analogRead(5);
int W9 = analogRead(4);
int dtime9= analogRead(1);
int tol9= analogRead(0);

{
if (E9 < 10 || E9 > 1000 )
{
  E9= preE ;
  }
{
  if (W9 < 10 || W9 > 1000 )
  {
    W9= preW ;
    }
{
    if (dtime9 < 10 || dtime9 > 1000 )
    {
      dtime9= predtime ;
      }
{
      if (tol9 < 10 || tol9 > 1000 )
      {
        tol9= pretol ;
        }
        delay(100);
        int E10 = analogRead(5);
        int W10 = analogRead(4);
        int dtime10= analogRead(1);
        int tol10= analogRead(0);

          if (E10 < 10 || E10 > 1000 )

        {
E10= preE ;
}
{
if (W10 < 10 || W10 > 1000 )
{
  W10= preW ;
  }
  {
  if (dtime10 < 10 || dtime10 > 1000 )
  {
    dtime10= predtime ;
    }
    {
    if (tol10 < 10 || tol10 > 1000 )
    {
      tol10= pretol ;
      }

      //Average the ten readings

   int E=(E1+E2+E3+E4+E5+E6+E7+E8+E9+E10)/10;

   //light intensityin east
   int W =(W1+W2+W3+W4+W5+W6+W7+W8+W9+W10)/10;

   // light intensity in west
   int dtime=(dtime1+dtime2+dtime3+dtime4+dtime5+dtime6+dtime7+dtime8+dtime9+dtime10)/10;

   int tol = (tol1+tol2+tol3+tol4+tol5+tol6+tol7+tol8+tol9+tol10)/10;// tolerance value
   int delaytime = (dtime *10);// increase the delay by magnitude of 10
   int tolerance = tol / 40;

   // display the readings through serial monitor
   Serial.println("Light intesity in the East");
   Serial.println(E);
   Serial.println(" ");
   Serial.println("Light intesity in the west");
   Serial.println(W);
   Serial.println(" ");
   Serial.println("delay time");
   Serial.println(delaytime);
   Serial.println(" ");
   Serial.println("tolerance");
   Serial.println(tolerance);

   //check the differenc and open the coresponding relays

   // check the diffirence of light intensity in east and west
   int diff = E - W;

   // check if the diffirence is in the tolerance else rotates the motor
   {
   if (-1*tolerance > diff || diff > tolerance)

   {
    if (E > W)// check if light intensity in east is greater than in west

    {
      if ( x <30)// check counter to ensure the motor does not run infinitely

    {
      Serial.println("Turn motors towards east");

   digitalWrite(7, LOW);// Turn ON Relay 1

   delay(2000);

   digitalWrite(7,HIGH); //Turn OFF Relay 1
   ++x;
   }
   }
   //check if light intensity in west is greater than in east
   else if (W > E) { if (x > -30)

   {
    }
    }
   }

Serial.println("Turn motor toward west");
digitalWrite(8, LOW);// Turn ON Relay 4
digitalWrite(9, LOW);
delay(2000);
digitalWrite(8, HIGH);//Turn OFF Relay 4
digitalWrite(9, HIGH);
--x;
// decrease counter
}
}
}
//store the values for the next loop

preE = 512;
preW = 512;
pretol= 512;
predtime = 512;
Serial.println(" ");
Serial.println("--------------------------------------------------------------------- ");
// delay the next loop
delay(1000);
}

```

# Answer
> 3 votes
You are missing five `}` at the end of your sketch.

As @Chris said, proper indentation will make your problem obvious. Use the menu Tools-AutoFormat (Ctrl-T) to format your sketch.

That's is looks like with the missing `}` added:

```
//store the values for the next loop

                        preE = 512;
                        preW = 512;
                        pretol= 512;
                        predtime = 512;
                        Serial.println(" ");
                        Serial.println("--------------------------------------------------------------------- ");
// delay the next loop
                        delay(1000);
                    }
//--- This } are missing in your sketch
                }
            }
        }
    }
}

```

# Answer
> 1 votes
I mean no offence by this but you have got in such a mess because you have written monolithic code. As a new developer you aren't expected to know this, I sure as hell didn't know it 30+ years ago. The fact that you have posted you code on here, shows that it is too big for a normal brain to manage. You loop function is over 300 lines long! A screen full is about all a normal person can manage.

What I think you should do is refactor your code, look at it and pick out common blocks and turn them into functions, this will reduce the number of lines, making in it easier to read and reduce the possibility of bugs. So firstly I notice you have this block repeated:

```
if (E1 < 10 || E1 > 1000)
{
    E1 = preE;
}

```

If you wrote that as a function:

```
int CheckLimits (const int& value, const int& lowerBound, const int& upperBound, const int& default)
{
  if (value < lowerBound || value > upperBound)
    return default;
  return value;
}
// This means those 4 lines collapse to this one line.
E1 = CheckLimits (E1, 10, 1000, preE);

```

Those 4 lines of code appear at least 39 times in loop, that's 120 lines that have just bee removed!

The `preE` value (and its pre friends) is never changed, so make it a constant and that will remove another 4 lines at the end.

Using literal numbers for your pins makes it harder to change them if you ever need to rewire. More importantly it makes the code harder to understand, so always `#define` them at the top of you code.

If you create two variables to hold the same sort of number you should be thinking about using an array instead. When you create E1 to E10 to hold ten readings, you should have done it in an array. The array size should be a constant, defined in a single place, so you can change it if necessary. And guess what, the averaging code should have been a function.

**ANYWAY** I rewrote you code and hopefully it will explain what I mean. Loop is down to about 90 lines now and it would be easy to make it smaller. Yes, get a decent editor, Notepad++ or Visual Studio or Visual Code are all free, but you have to learn to think in smaller blocks, if you ever copy and paste more than one line, it probably should be a function :)

I haven't compiled it, but it should work - Please don't copy it just look at it and make your code better than this.

```
//set initial values
int x = 0; // set initial zero value for the counter
static const int preE = 512; // set initial value for light intensity in east direction
static const int preW = 512; // set initial value for light intensity in west direction
static const int predtime = 512; // set initial value for delay time
static const int pretol = 512; // set initial value for tolerance value
// Define the PINS
#define APIN_E (5)
#define APIN_W (4)
#define APIN_DTIME (1)
#define APIN_TOL (0)
static const int MaxReadings(10);       // The number of readings used to form the average
int E_Reading[MaxReadings];             // Holds all the readings, not sure it is required any more, replaced by average variable.
int W_Reading[MaxReadings];
int dtime_Reading[MaxReadings];
int tol_Reading[MaxReadings];

void setup()
{
    Serial.begin(9600); // set the baud rate for the serial monitor

                        // first set the relays off
    pinMode(7, OUTPUT);
    pinMode(8, OUTPUT);
    digitalWrite(7, HIGH);
    digitalWrite(8, HIGH); // began the loop
}

/// Check that the given value is within the limits
/// value: The reading to check
/// lowerBound : The lowest acceptable value
/// upperBound : The highest acceptable value
/// defValue : The value to use if outside the range.
int CheckLimits(const int& value, const int& lowerBound, const int& upperBound, const int& defValue)
{
    if (value < lowerBound || value > upperBound)
        return defValue;
    return value;
}

/// Take a reading from the specified pi and check it is within the acceptable bounds.
/// pinNumber   : The Analog pin number
/// lowerBound : The lowest acceptable value
/// upperBound : The highest acceptable value
/// defValue : The value to use if outside the range.
int TakeReading(const int& pinNumber, const int& lowerBound, const int& upperBound, const int& defValue)
{
    return CheckLimits(analogRead(pinNumber), lowerBound, upperBound, defValue);
}

void loop()
{
    int Eaverage = 0;
    int Waverage = 0;
    int dtimeaverage = 0;
    int tolaverage = 0;

    // Read the first reading
    for (int index = 0; index < MaxReadings; ++index)
    {   // You don't actually need the values unless you want them, TakeReading could be assigned to the average variables.
        E_Reading[index] = TakeReading(APIN_E, 10, 1000, preE);         // read the east LDR
        W_Reading[index] = TakeReading(APIN_W, 10, 1000, preW);         // read the west LDR
        dtime_Reading[index] = TakeReading(APIN_DTIME, 10, 1000, predtme);  // read the delay time potentiometer
        tol_Reading[index] = TakeReading(APIN_TOL, 10, 1000, prepretol);    // read the tolerance potentiometer

        Eaverage += E_Reading[index];
        Waverage += W_Reading[index];
        dtimeaverage += dtime_Reading[index];
        tolaverage += tol_Reading[index];
        delay(100);
    }

    //Average the ten readings
    Eaverage /= MaxReadings;
    Waverage /= MaxReadings;
    dtimeaverage /= MaxReadings;
    tolaverage /= MaxReadings;

    const int delaytime = (dtime * 10);// increase the delay by magnitude of 10
    const int tolerance = tol / 40;

    // display the readings through serial monitor
    Serial.println("Light intensity in the East");
    Serial.println(E);
    Serial.println(" ");
    Serial.println("Light intensity in the west");
    Serial.println(W);
    Serial.println(" ");
    Serial.println("delay time");
    Serial.println(delaytime);
    Serial.println(" ");
    Serial.println("tolerance");
    Serial.println(tolerance);

    //check the difference and open the corresponding relays

    // check the difference of light intensity in east and west
    const int diff = E - W;

    // check if the difference is in the tolerance else rotates the motor
    if (-1 * tolerance > diff || diff > tolerance)
    {
        if (E > W)// check if light intensity in east is greater than in west
        {
            if (x < 30)// check counter to ensure the motor does not run infinitely

            {
                Serial.println("Turn motors towards east");
                digitalWrite(7, LOW);// Turn ON Relay 1
                delay(2000);
                digitalWrite(7, HIGH); //Turn OFF Relay 1
                ++x;
            }
        }
        //check if light intensity in west is greater than in east
        else if (W > E)
        {
            if (x > -30)
            {
                // MISSING CODE??
            }
        }
    }
    Serial.println("Turn motor toward west");
    digitalWrite(8, LOW);// Turn ON Relay 4
    digitalWrite(9, LOW);
    delay(2000);
    digitalWrite(8, HIGH);//Turn OFF Relay 4
    digitalWrite(9, HIGH);
    --x;
    // decrease counter

    //store the values for the next loop
    Serial.println(" ");
    Serial.println("--------------------------------------------------------------------- ");
    // delay the next loop
    delay(1000);
}

```

# Answer
> -1 votes
usually unmatched brackets.

run your code through astyle and it will be more clear to you.

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


# Question
Title: Is a solenoid piston strong enough to lock a water tubling?
My question is about hardware that i'll control with my arduino... Not Arduino itself (So I don't know if I'm in the right section ... :s)

My project is to create a cocktail machine at the cheapest price.

I was wondering if this kind of solenoid piston would be strong enough to seals a plastic pipe like this one ?

My idea from now is to use only 1 water pump (as this one) and connect all the pipes from the bottles with some Y and control which one is giving the liquid by controling pistons that are going to compress the tube.

I'm open to all advices you could give me and new ideas ... I saw that there's also solenoid valves ... But I only find it in 12V ... Does it exist in 5V ?

# Answer
The pump you are looking at is to powerful for you application: 350 liters/hour, or little less than 5 ltr/min. It will fill a 250 ml glass in about 3 seconds!

The solenoid cost you $5 a piece, but you still need a valve and a way to attach solenoid, valve and tubing.

Also, your idea means liquids will get mixed inside the tubes. And nobody wants a trace of whiskey in his Vodka Screwdriver.

You must visit The Inebriator, a cocktail mixing machine. His design have one tube for every bottle pouring liquid into the glass.

As they note, they have in version 2.0

> Switching mixers from a pressurised system with valves to using pumps – This slows the pouring, but vastly simplifies the machine as a whole. We have a capacity for 16 pumps

They don't use valves, but pumps. I recomend a peristaltic pump ($7 on Aliexpress), like this:

They don't touch the fluid, easy to mount, and are a very precise delivery mechanism, like in this video https://youtu.be/GdTUIwj5ros, showing an Arduino controlling a pump to 1ml precision:
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: connection for hall sensor 4 pin and arduino nano
I'm not from electronics background so I don't know what should be the connections. My Hall sensor has 4 pins(AO, GND, +, DO)

So, I have connected hall sensor pins to Arduino nano pins in this order(connection)

```
AO(Sensor) <-> A4(Arduino)   [Changed from A0 to A4]
DO(Sensor) <-> D4(Arduino)   [Changed from D0 to D4]
+(Sensor) <-> 5V(Arduino)
GND(Sensor) <-> GND (Arduino)

```

What should be pseudo code? So that if the magnet passes close to the sensor. Arduino should get the output & I'll blink the led on Arduino

This below is my code that I have written so far

```
int sensorPin = 4; // this is for sensor in analog pin 4
int buttonPin = 4; // we are looking for digital 4
int val;

bool flag = false;

void setup() {
  // put your setup code here, to run once:
  pinMode(buttonPin, INPUT); // defines digital pin 4 as input for LED
  Serial.begin(9600);
}

void loop() {
   int reading = analogRead(sensorPin);

   float voltage = reading * 5.0;
   voltage /= 1024.0;

  if(voltage > 3.0) {
   Serial.print(voltage); Serial.println("volts");
  }
   val = digitalRead(buttonPin);  // read data from digital Pin

   if(val == HIGH) // when the sensor detects a magnetic field
   {
      flag = !flag;
      if(flag){
         digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
      } else {                 // wait for a second
          digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
      }
      //delay(1000);                       // wait for a second
   }
   delay(100);
}

```

**Expected output:** It should turn On/Off the LED when voltage goes `HIGH`

**Known issues:** It works sometime. It doesn't work sometime. Also it works only when magnet is kept clone. Doesn't detect when I'm waving magnet close to the sensor

# Answer
The board you have has two outputs - AO and DO (note, those are the letter O not the number zero - for output).

You can connect AO to any of the analog inputs on your board if you want to read a discrete analog value from the sensor.

You can connect DO to any of the digital inputs (or analog ones since they are also digital inputs) if you just want a simple "Something is there" signal.

The sensitivity of the "something is there" is controlled by the trimmer on the board.

The simplest way of doing what you want is to use DO and adjust the trimmer to suit. Then the sensor looks, to all intents and purposes, like a switch or a button (but you don't need the pull up / pull down resistor). So you can leave AO disconnected.

Note that using D0 (zero) and D1 (one) on the Arduino is discouraged since they are connected to the USB interface and using them can affect your ability to upload sketches. It also means you cannot use any serial communication in your program.
> 2 votes

# Answer
Someone will probably post a comment saying this is not a code writing service, but I get the impression that you just need pointers, so here they are.

In the IDE you have an example on how to blink the LED, called **blink**, if you haven't already make yourself familiar with that.

I think there is an example on how to read from the analog pin, if not its **`int value = analogRead(A0);`**

Now **print** that value to the **Serial** monitor and see what happens when you start waving the magnet around. The value will change say for 400 odd to 800 odd.

Now write an **if** statement that turns on the LED when the value you read is greater than (**\>**) a certain value.

If you need any help on the code you need to write look in the Help-\>Reference section of the IDE, you might find the **Bold** words especially relevant :)

If you get stuck, post the code of how far you have got and people will help.
> 0 votes

---
Tags: arduino-nano
---


title: New to Arduino building

text:
# Question
Title: New to Arduino building
I am new to Arduino an working with the Uno. My dream is to activate servos in a perticular order once some type of sensor recognizes a live person near it. Is their a perticular easy to understand book out there I can read? There are lots and lots of books but they all get very complex rather quickly. I'd be curious as to fellow inventors in here telling me how they mastered the Arduino? Maybe it was not a book but rather a complete course. Will others please respond to help me. ps... I do have an electronics degree so I don't need soldering or component understanding. I know what Vcc is. I need please some type of course book which will take me now beyond the self blinking light into robotic control if that easy to understand book or course is out there. Thank you. Michael in Palm Beach, FL

# Answer
There are lots of examples on the official Arduino website.

My advice is you follow them, not only by reading, but buy the components you need (they are cheap) and practice and see how to handle them within the Arduino environment.

Do one component at a time (led, switch, Servo, Sensor), and focus on the servo/sensors you want to use.

Than try to combine multiple components, step by step until you have your dream project ready.

Also, try not to just copy sketches (programs), but understand them. And than adapt them a bit, make variations on the component 'tests'.

I have a whole folder where I test each component with Arduino (and for some complicated components multiple sketches). Save them, and add links etc, so you can easily reference back to it.

You can use books, but there is so much information for the Arduino that this forum, the official web site and google should be enough to get you going.

(note: for the Arduino I did not use books, since as above said, there is so much information. I'm now diving in to STM32 which is more complex and a book/PDF is more convenient).
> 1 votes

---
Tags: arduino-uno
---


title: Moving motion sensor?

text:
# Question
Title: Moving motion sensor?
Long story short, I'm trying to build some form of device that you can wear and it will detect when something moves behind you. I wanted to use PIR sensors for the motion detection, but I have no idea if they can detect objects if you're moving. Any ideas?

# Answer
OP didn't really specify the actual requirements other than detecting movement and wanting to use PIR while in motion.

PIR (Passive Infrared) implies looking for warm bodies. In general, PIR motion sensors look for the presence of thermal radiation that moves between the individual parts of the sensor. On TV it is shown that you can fool PIR detectors by carrying a large cold panel between you and the detector. ;-)

They also detect reflected thermal radiation that is moving. It does not need to be a direct view. So moving the sensor around outside would pick up a lot of reflected IR sunlight changes. And certainly incandescent lights would do the same since about 80% of their emitted energy is IR.

The way they are designed, (with lenses like a bee's eye) they are more likely to detect your own arms swinging back as you walk and generate false alarms that way. So you would need some kind of mounting arrangement that only allowed it to "see" directly behind. And even then only in a dark room.

PIR sounds like a lot of trouble for an application like this. (As in, probably not suitable)

Here is a decent instructable that explains how they work: http://www.instructables.com/id/PIR-Motion-Sensor-Tutorial/

If PIR is not a be-all requirement, here is an alternative to be considered, even though it would require some work to get it right:

## Radar

Here is a nice, inexpensive radar unit that will arrive eventually on the slow boat, and the price is right. It could work well in motion if you program it to detect changes that occur at speeds faster than your own motion. And you would want to program a pulse gate it so it only senses objects at more than a certain distance behind you.

Anyway, in the spirit of hacking, I offer this idea:

## LFS-DC04 2.7GHz Microwave Radar Module DC 5V

http://www.ebay.com/itm/262662221979

It is small enough to wear. But it is slow, so I wouldn't recommend using it to detect intruders with violent intent. I believe it would be good mounted on a bicycle-pulled trailer or something like that, to make sure you know if something is coming up on you too fast.

## Product Introduction:

```
1.Model:LFS-DC04
2.Frequency:2.7GHz
3.Size:40*22mm
4.Input Voltage:DC 5V
5.Output Type:level signal output
6.Connection Method:VCC,GND connect with positive negative input, OUT,GND signal connect with output
7.Installation Height:1-3.5m
8.Sensing Ditance:5-8m
9.Delay Time:30s(quick testing mode is 4s)
10.Sensing Angle:360 degree

```

It is low enough power that it shouldn't fry your kidneys. Probably very similar to sitting next to a high-power WiFi router all the time, or like having a cellphone in your pocket with WiFi and 4G turned on all the time.
> 4 votes

# Answer
PIR sensors detect the movement of a warm body *relative* to the location of the PIR sensor. Therefore if the PIR sensor moves then the location of a static object *relative to* that PIR sensor will change and motion will be detected.

So no, PIR is not really suitable for this.

TBH I can't, off the top of my head, think of a simple way of achieving what you want short of image processing with OpenCV on something considerably more powerful than an Arduino.
> 2 votes

# Answer
A PIR is entirely passive. The sensor has an enclosed vertical and horizontal IR receptor which reacts to the change of IR coming through a faceted lens, to accentuate the effects of movement, striking the surfaces through a small window on top. Having a passive system attached to a moving body would result in mostly false positives. It could be worth looking at active systems such as video, microwave, or even ultrasound
> 0 votes

---
Tags: arduino-uno, sensors, electronics, project
---


# Question
Title: Make Sure Digital pin is high before Serial.write()
I have the following code for a TTL to RS-485 Adapter Module

```
[...code]
digitalWrite(DE_PIN, HIGH); //directional control for adapter
Serial2.write(Message, Size);
Serial2.flush();
digitalWrite(DE_PIN, LOW);  // Set To Recieve
Serial2_reading_foo();
[code...]

```

I've noticed that `DE_PIN` does not seem to go `High` fast enough before `Serial2.write()` executes I confirmed this by adding a small `delay(ms)` which made the code function perfectly.

```
digitalWrite(DE_PIN, HIGH);
delay(100);
Serial2.write(Message, Size);
Serial2.flush();
digitalWrite(DE_PIN, LOW);  // Set To Recieve
delay(100);
Serial2_reading_foo();

```

Unfortunately, there's pretty much universal agreement that you shouldn't ever use `delay()` in programming. Plus doing any kind of wait function here seems to be insensitive to the real problem. Is there a better way to make sure that `DE_PIN==HIGH` before the Serial2.write() Function begins?

# Answer
The MAX485 requires 2V on the DE pin to register a HIGH. It takes no more than an absolute maximum of 50ns for the DE pin to switch the buffers. The Arduino takes 10.4ns for an IO pin to rise to 2V.

That's an absolute maximum of 60.4ns.

One clock cycle of a 16MHz Arduino is 63ns.

That is longer than it takes for the IO pin to tell the MAX485 to switch the buffers.

You can increase that rise time by taking in to account the input capacitance of the MAX485 and the resistance of the connection between the Arduino and the DE pin, but it will still be microscopically small compared to the time between the pin going HIGH and the serial transmission starting.

So there must be something fundamentally wrong with your setup. Two possibilities spring to mind:

1. You aren't controlling RE, only DE, so RE is floating and is being capacitively linked to DE through the parasitic capacitances of the board and circuitry, making it rise and fall very slowly.
2. You haven't set the IO pin on the Arduino to OUTPUT, so it switches between floating and HIGH through a very high resistance, causing slow rise to HIGH and maybe never getting to LOW at all.

Or a combination of the two.
> 1 votes

---
Tags: serial, arduino-mega, rs485
---