title: SdFat initialization blocks HC-SR04

text:
# Question
Title: SdFat initialization blocks HC-SR04
I appreciate the help of this forum very much and it\`s my first time to ask you experts befor driving crazy...

ArduinoUno and SDcard-BreakOutboard and DistanceSensor HC-SR04 are not working well together. The problem - as far as I found out - is in this statement:

```
if (!sd.begin(sdChipSelect) || !file.open("DATALOG.TXT", O_CREAT | O_WRITE | O_APPEND)) {
// Replace this with something for your app.
Serial.println(F("SD problem"));
//while(1);
}

```

When it is erased the distance sensor works perfectly, if it is in place it shows 0 cm (and that for days! ;-) ). I read something that SdFat ist doing something with Pin10 but also putting it on OUTPUT - HIGH or LOW didn't do the trick. Any ideas?

Kind regards

Rob

The "minimal" code:

```
/*
SD card datalogger

This example shows how to log data
to an SD card using the SdFat library.

The circuit:
* analog sensors on analog ins 0, 1, and 2
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 7 (for MKRZero SD: SDCARD_SS_PIN)
*/
#include <SdFat.h>
const uint8_t sdChipSelect = 7;
// SD file system.
SdFat sd;
// Log file.
SdFile file;

// Hook up HC-SR04 with Trig to Arduino Pin 9, Echo to Arduino pin 10
// Maximum Distance is 400 cm
unsigned long echo = 10;
int ultraSoundSignal = 9; // Ultrasound signal pin
unsigned long ultrasoundValue = 0;

void setup() {
// Serial Port
Serial.begin(9600);
// Pin 9 = TriggerPin
pinMode(ultraSoundSignal,OUTPUT);

// Initialize the SD and create or open the data file for append.
if (!sd.begin(sdChipSelect) || !file.open("DATALOG.TXT", O_CREAT | O_WRITE | O_APPEND)) {
// Replace this with somthing for your app.
Serial.println(F("SD problem"));
//while(1);
}
Serial.println("card initialized.");
delay(1000);
}

void loop() {
Serial.println("Beginn");
// Distanzmessung mit HC-SR04
int x = 0;
x = ping();
Serial.print(x); Serial.println(" cm");
delay(1000); //delay 1/4 seconds.
}

unsigned long ping()
{
  pinMode(ultraSoundSignal, OUTPUT); // Switch signalpin to output
  digitalWrite(ultraSoundSignal, LOW); // Send low pulse
  delayMicroseconds(2); // Wait for 2 microseconds
  digitalWrite(ultraSoundSignal, HIGH); // Send high pulse
  delayMicroseconds(5); // Wait for 5 microseconds
  digitalWrite(ultraSoundSignal, LOW); // Holdoff
  pinMode(ultraSoundSignal, INPUT); // Switch signalpin to input
  digitalWrite(ultraSoundSignal, HIGH); // Turn on pullup resistor
  // please note that pulseIn has a 1sec timeout, which may
  // not be desirable. Depending on your sensor specs, you
  // can likely bound the time like this -- marcmerlin
  // echo = pulseIn(ultraSoundSignal, HIGH, 38000)
  echo = pulseIn(ultraSoundSignal, HIGH,38000); //Listen for echo
  ultrasoundValue = (echo / 58.138);// * .39; //convert to CM then to         inches
  return ultrasoundValue;
}

```

# Answer
> 1 votes
Pin 10 is the SS pin for SPI. Since you are using SPI for the SD card pin 10 *must* be an output (for SPI to operate in master mode). Ideally you will use that pin as the SS (or CS, whatever you want to call it) for the SD card.

You can't use it as the echo input of an ultrasound range finder and use SPI.

---
Tags: sd-card, hc-sr04
---


# Question
Title: Is it possible to program/flash ESP8266MOD(07) With Arduino UNO
i am new to ESp and yesterday i received my **ESP8266MOD**, i don't have FTDi connector with me right now(it's on the way).

**Is it possible to flash ESP with Arduino UNO?**

Regards, Ben

# Answer
> 3 votes
Yes you can.

Take a look at this detailed guide.

The most important thing to keep in mind is that you have to connect from the ATmega16U2's perspective, so you have to swap RX and TX:

You'll probably want some buttons to facilitate the flashing process:

# Answer
> 1 votes
I think it is possible. You can use the Arduino Uno 's Rx and Tx lines, but maybe you will need to have a voltage divider resistor arrangement to step down the 5V UART lines from the Uno to the 3.3V needed by the ESP, otherwise you risk damaging the ESP.

The basic approach to flash a ESP is described by several web sources and instructables, such this one Getting started with the ESP8266 ESP-12 (there is also one section how to flash with an Arduino Uno).

---
Tags: esp8266
---


# Question
Title: Measuring the speed of an object moving fast through air
I am new to arduino and am confused about how I would go about doing this: I want to attach a device to a small ball, that will move through the air at speed. The purpose of this device would be to determine the speed of this object as it moves through the air. My ball will always move in the same path because it will be shot out of a tennis ball shooter. My initial intuition would be to use an accelerometer to determine the acceleration at quarter second intervals and then multiply those values by a quarter of a second to obtain the change in speed and then add it to the sum of all the previous change in speed values (starting at 0).

Would this work? Is my reasoning correct? Are there any better solutions?

Thank You!

# Answer
> 1 votes
You are proposing calculating velocity based on sampled acceleration. Essentially taking the integral of the acceleration. This is the first step in a process call dead reckoning. This is discussed in this arduino.stackexchange.com answer. In that answer there is a link to a web page which implements dead reckoning using an Arduino. You will find this equation on that web page:

```
velocity(i) = velocity(i-1) + acceleration (i)

```

---
Tags: accelerometer, speed
---


title: char array comparison

text:
# Question
Title: char array comparison
I'm having some issues dealing with strings in a small Arduino app. I wonder why **this code works**:

```
mqtt.setServer("192.168.1.42", port);

```

and this code doesn't:

```
IPAddress ip = MDNS.queryHost(...);
mqtt.setServer(ip.toString().c_str(), port);

```

Even when `strcmp` returns 0 when I compare both:

```
strcmp(ip.toString().c_str(), "192.168.1.42"); // output = 0 => equality

```

I've also tried other alternatives, such as creating a `char` array, with no luck:

```
String ipstr = ip.toString();
char ipchar[ipstr.length() + 1];
ipstr.toCharArray(ipchar, ipstr.length() + 1);

mqtt.setServer(ipchar, port);

```

All alternatives compile, but the mqtt connection is never established later on. I must be missing something obvious because it works when I hardcode the "192.168.1.42" string.

# Answer
> 6 votes
`PubSubClient::setServer(const char * domain, uint16_t port)` just saves the pointer, it doesn't copy the string (probably because it expects a static string literal). (Source)
In your case, when `ip` goes out of scope, the pointer is no longer valid, so it won't work.

Just use the `PubSubClient::setServer(IPAddress ip, uint16_t port)` function instead. (Source)

Always read the API documentation, most libraries have one, even though it can be hard to find. The ReadMe and GitHub Wiki pages are a good place to start.
If that's insufficient (not uncommon for open source projects), read the header files, which list all functions of the library.
If you still have doubts about what a function does, refer to the actual implementation files.

---
Tags: string
---


# Question
Title: MicroSD interfering with ISP programming
I have a microSD connected to an Arduino and I can't program it over ISP without removing the SD card. Does anybody know how to prevent the SD card from interfering with the ISP programming?

Details:

This is the microSD breakout: https://www.adafruit.com/products/254

I'm using an ATMEGA328P at 3.3V 8MHz.

I'm not using a bootloader and, for several reasons, I can't use the serial port for programming.

Thanks!

# Answer
> 3 votes
Because the SD card is an SPI device it shares the same pins as the ISP interface. The only way to not have the SD card interfere with the ISP is to not have the SD card connected.

As you have seen, that can be achieved by removing the card.

It can also be achieved by adding a tri-state buffer between the MCU and the card so the MCU only connects the card to the SPI bus when it is ready to use it - under default operation the card is disconnected.

# Answer
> 1 votes
I had the exact same problem, also using Arduino (Atmega 328P). I have an sd card module with a different layout, but also with a level shifter. My circuit is running at 5V (which is appropriate when using a level shifter).

To resolve the issue I just installed a pullup resistor (10k) on my own board to the chip select line of the sd module, which keeps the sd card unselected while programming the MCU. Now it works.

There seems to be no pullup integrated into the module. Hence the CS is low during programming (without the pullup), the sd card thinks it should answer the SPI commands, and so interferes with the communication to the MCU, which is why programming over an ISP fails.

---
Tags: isp, arduino-pro-micro
---


# Question
Title: One shift delay in receiving the response messages when using two nRF24L01 to communicate with each other
When I send "a" from the Serial Monitor of the slave, on the master slave window it will show "car1\_place\_2\_go = a" then it should show on the slave Serial Monitor "a" but it doesn't show up in the slave serial window until I send another new characters. So there is a 1 delay shift in the messages showed on the slave Serial Monitor.

Master:

```
#include <SPI.h>
#include <SoftwareSerial.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8); // CE, CSN
const byte addresses[][6] = {"00001", "00002"};

char car1_place_2_go;
char car2_place_2_go;
char temp_place = 0 ;

void setup()
{
  Serial.begin(9600);
  radio.begin();
  radio.openWritingPipe(addresses[1]); // mastr
  radio.openReadingPipe(1, addresses[0]); // carwl

  radio.setPALevel(RF24_PA_MIN);
}

void loop()
{
  delay(5);
  radio.startListening();

  if (radio.available())
  {
    radio.read(&car1_place_2_go, sizeof(car1_place_2_go));
    Serial.print("car1_place_2_go = ");
    Serial.println(car1_place_2_go);

    delay(5);
    radio.stopListening();

    radio.write(&car1_place_2_go, sizeof(car1_place_2_go));
  }
}

```

Slave:

```
#include <SPI.h>
#include <SoftwareSerial.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8); // CE, CSN
const byte addresses[][6] = {"00001", "00002"};

char car1_place_2_go;
char car2_place_2_go;

void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openWritingPipe(addresses[0]); // 00003
  radio.openReadingPipe(1, addresses[1]); // 00002

  radio.setPALevel(RF24_PA_MIN);
}

void loop()
{
  if (Serial.available() > 0)
  {
    car2_place_2_go = Serial.read();

    delay(5);
    radio.stopListening();

    radio.write(&car2_place_2_go, sizeof(car2_place_2_go));

    radio.startListening();

    if ( radio.available())
    {
      char text[32] = "";
      radio.read(&text, sizeof(text));
      Serial.println(text);
    }
  }
}

```

Library I use: https://github.com/nRF24/RF24

# Answer
> 0 votes
i found the problem is that the receiver in the slave doesn't see what send to it until the next loop and that mean it need a delay so it can see what transmit to it so i add this while loop in the slave so the slave doesn't exit the "void loop" function until it get the message from the master

slave

```
 radio.startListening();

    while(! radio.available())
    {

    }
    if ( radio.available())
    {
        char text[32] = "";
        radio.read(&text, sizeof(text));
        Serial.println(text);
     }

```

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


title: I want a code for 6 LDR/LED pair

text:
# Question
Title: I want a code for 6 LDR/LED pair
Each LDR is connected to one LED because I am doing a parking lot model. I have tried but with no luck. Help!

```
    int ledPin = 11;
int sensorInput = A0;

boolean ledIsOn = false;

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

void loop() {
  int lightLevel = analogRead(A0);

  if (ledIsOn) {
    if (lightLevel > 600) {
      ledIsOn = false;
    }
  } else {
    if (lightLevel < 400) {
      ledIsOn = true;
    }
  }

  digitalWrite(ledPin, ledIsOn);

  Serial.println(lightLevel);
}

```

\*this is the code for one LED to one LDR Sensor but I cannot make the 6 led to 6 ldr

and I did this code for 6 LDR

```
#define pin_size 6
const int pin[pin_size] = { A0, A1, A2, A3, A4, A5};

void setup() {

  Serial.begin(9600);

}

void loop() {
  for (int i = 0 ; i < pin_size; i++) {
    Serial.print(analogRead(pin[i]));
    Serial.print(" - ");
    Serial.print(i);
    Serial.print("  |  ");

  }
  Serial.print("\n");
  delay(1000);

}

```

# Answer
You need to convert all the regular variables to arrays. The loop through each index and run the the same as before for each index.

```
const int pin_size 6
int ledPins[] = {3, 4, 5, 6, 7, 8};
int sensorPins[] = {A0, A1, A2, A3, A4, A5};
boolean ledIsOn[] = {false, false, false, false, false, false};

void setup() {
  for (int i = 0 ; i < pin_size; i++) {
    pinMode(ledPins[i], OUTPUT);
  }
  Serial.begin(9600);
}

void loop() {
  for (int i = 0 ; i < pin_size; i++) {
    int lightLevel = analogRead(sensorPins[i]);

    if (ledIsOn[i]) {
      if (lightLevel > 600) {
        ledIsOn[i] = false;
      }
    } else {
      if (lightLevel < 400) {
        ledIsOn[i] = true;
      }
    }

    digitalWrite(ledPins[i], ledIsOn[i]);

    Serial.println(lightLevel);
  }
}

```
> 1 votes

---
Tags: arduino-uno, programming, sensors, led
---


# Question
Title: Digital selection for gain control not working instead showing 0
I am making a device which will have a button to measure the input and another button to reset and the inputs are variable analog values(0 to 5v) and output is a ratio of two analog input voltages. It also has a selection keys(two buttons) for four selections(like gain eg. if key1 == LOW key 2 == LOW then J = 1 and likewise) but the problem is when i am multiplying j with it the output shows zero if I multiply numbers like 1,2,3etc without using j then the ratio value gets multiplied.

here is the code

```
    void setup() // put your setup code here, to run once:
    {
      Serial.begin(9600);
      pinMode( K1, INPUT );
      pinMode( K2, INPUT );
      pinMode( MeasureButton, INPUT );
      pinMode( ResetButton, INPUT );
      dsp.begin(20, 4);
      current = millis();
    }

    void loop()
    {

      while(current < wait)
      {
      Serial.println("INITIALIZING");
      delay(1000);
      current = millis();
      }
      Serial.println("                   ");
      delay(1000);
      Serial.println(" READY TO MEASURE ");
      delay(2000);
      while (digitalRead(MeasureButton) == LOW)
      {
        if(K1 == LOW && K2 == LOW)
        {J = 1; // SOMETHING VALUE
        showMessage1();
        i = 0;
        delay(1000);
        }if(K1 == LOW && K2 == HIGH)
        J= 2; // SOMETHING VALUE
        showMessage1();
        i = 0;
        delay(1000);
        if(K1 == HIGH && K2 == LOW )
        J= 3; // SOMETHING VALUE
        showMessage1();
        i = 0;
        delay(1000);
        if(K1 == HIGH && K2 == HIGH )
        J= 4; // SOMETHING VALUE
        showMessage1();
        i = 0;
        delay(1000);

      }
      while (digitalRead(ResetButton) == HIGH)
      {
      dsp.setCursor(1,0);
      dsp.print("                   ");
      Serial.println("                   ");
      delay(1000);
      dsp.setCursor(1,0);
      dsp.print("RESETED");
      Serial.println("RESETED");
      delay(1000);
      }
while (digitalRead(ResetButton) == LOW)
      {
      dsp.setCursor(1,0);
      dsp.print("                   ");
      Serial.println("                   ");
      delay(1000);
      dsp.setCursor(1,0);
      dsp.print("PRESS MEASURE");
      Serial.println("PRESS MEASURE");
      delay(1000);
      }
    }

    void showMessage1()
    {
       while(i<5)
        {
        A = analogRead(A0);
        B = analogRead(A1);
        C = analogRead(A2);
        D = analogRead(A3);
        N = analogRead(A4);
        W1 = (A/N)*J;        // J is another variable whose value is dependent on K selection values
        W2 = (B/N)*J;        // J is another variable whose value is dependent on K selection values
        W3 = (C/N)*J;        // J is another variable whose value is dependent on K selection values
        W4 = (D/A)*J;        // J is another variable whose value is dependent on K selection values

        sumW1 = sumW1 + W1;
        sumW2 = sumW2 + W2;
        sumW3 = sumW3 + W3;
        sumW4 = sumW4 + W4;
        i++;
      }
        Serial.print("W1-");
        Serial.print(sumW1);
        Serial.print("W2-");
        Serial.println(sumW2);
        Serial.print("W3-");
        Serial.print(sumW2);
        Serial.print("W4-");
        Serial.println(sumW4);
        sumW1 = 0;
        sumW2 = 0;
        sumW3 = 0;
        sumW4 = 0;
    }

```

# Answer
> 4 votes
```
  pinMode( K1, INPUT );

```

with

```
    if(K1 == LOW && K2 == LOW)

```

makes no sense. `K1` is a pin number. `LOW` is a macro for `0` (`HIGH` for `1`). You are comparing a static pin number against a static number.

If `K1` is not equal to 0, the inner part of that if statement can never be reached.

What you meant to do was "if the voltage at the pin K1 is low". For that you need to read out the current value of the pin and check it.

For that you must replace your `if(K1 == LOW)` type statements to `if( digitalRead(K1) == LOW)`.

I'd also like to mention that you must have a pull-up on your buttons for this "LOW"/"HIGH" logic to work. Either externally, or use `INPUT_PULLUP` instead of `INPUT` in `pinMode`.

---
Tags: arduino-uno, digital, potentiometer
---


# Question
Title: Timer2 Compare Interrupt not working as expected
To get this out of the way first: I have already looked at "Timer2 does not work as it should" and "Timer2 “Clear OC2B on Compare Match” not working as expected in CTC mode" but have not found the answers there very useful.

Now on to my problem:

I'm trying to use the Timer2 in CTC mode to have an interrupt every 500us. For this, I have the following code:

```
#include "TimerTwo.h"

TimerTwo Timer2;

ISR(TIMER2_COMPA_vect) { //ISR on Compare Match A
  Timer2.isrCallback();
}

void TimerTwo::initialize() {
  cli();
  TCCR2A = 0;// set entire TCCR2A register to 0
  TCCR2B = 0;// same for TCCR2B
  TCNT2  = 0;//initialize counter value to 0

  // set compare match register for 2khz increments
  OCR2A = 124;// = (16*10^6) / (2000*64) - 1 (must be <256)

  // turn on CTC mode
  TCCR2A |= _BV(WGM21);

  // Set CS22 bit for 64 prescaler
  TCCR2B |=  _BV(CS22);

  // enable timer compare interrupt
  TIMSK2 |= _BV(OCIE2A);
  sei();
}

void TimerTwo::attachInterrupt(void (*isr)()) {
  TIMSK2 |= _BV(OCIE2A);
  isrCallback = isr;
}

void TimerTwo::detachInterrupt() {
  TIMSK2 &= ~_BV(OCIE2A);
  isrCallback = nullptr;
}

```

and

```
#ifndef TIMERTWO_H
#define TIMERTWO_H

#include <Arduino.h>

class TimerTwo
{
  public: //methods
    void initialize();
    void attachInterrupt(void (*isr)());
    void detachInterrupt();
    void (*isrCallback)();
};

extern TimerTwo Timer2;

#endif

```

It was inspired by the TimerOne library.

However, when I measure the period at the output pin (which I have attached inside some other code) I only get a period of 1ms. Even if I set `ORC2A` to 63, this fact doesn't change.

I have the constructor of this called inside my `setup()` so the registers should not be overwritten by the wiring.c.

I have also looked at the datasheet of the ATmega328p and checked that all registers are set correctly.

Thanks in advance for your help. If you need any further information, let me know.

# Answer
So you're right that CTC is acting weird. I've noticed this few years ago too on different board, but I've always suspected asychronous mode (I've added 32k RTC Xtal on Arduino Mega).

However Fast PWM mode with `OCR2A` as a `TOP` value seems to be working:

```
class TimerTwo
{
  public: //methods
    void initialize();
    void attachInterrupt(void (*isr)());
    void detachInterrupt();
    void (*isrCallback)() = nullptr;
};

TimerTwo Timer2;

ISR(TIMER2_COMPA_vect) { //ISR on Compare Match A
  Timer2.isrCallback();
}

void TimerTwo::initialize() {
  cli();

  OCR2A = 124;                        // = (16*10^6) / (2000*64) - 1 (must be <256)
  TCCR2A = _BV(WGM21) | _BV(WGM20);   // turn on fast PWM mode with top in OCR2A
  TCCR2B = _BV(WGM22) | _BV(CS22);    // Set CS22 bit for 64 prescaler
  TCNT2  = 0;                         // initialize counter value to 0

  sei();
}

void TimerTwo::attachInterrupt(void (*isr)()) {
  isrCallback = isr;
  TIMSK2 |= _BV(OCIE2A);
}

void TimerTwo::detachInterrupt() {
  TIMSK2 &= ~_BV(OCIE2A);
  isrCallback = nullptr;
}

volatile uint32_t counter = 0;
void isrHandler() {
  ++counter;
}

void setup() {
  Serial.begin(115200);
  Timer2.initialize();
  Timer2.attachInterrupt(&isrHandler);
}

void loop() {
    static uint32_t counter_old = 0;
    Serial.println(counter - counter_old);
    counter_old = counter;
    delay(500);
}

```

EDIT: Ok, so after some digging on this issue I've found that setting CTC mode might cause OCR2A corruption (I guess?) . It seems to be working if you reorder the settings to:

```
  TCCR2B = 0;          // stop the timer and reset WGM22
  TCCR2A = _BV(WGM21); // turn on CTC mode with top in OCR2A
  OCR2A  = 124;        // = (16*10^6) / (2000*64) - 1 (must be <256)
  TCNT2  = 0;          //initialize counter value to 0
  TCCR2B = _BV(CS22);  // Set CS22 bit for 64 prescaler (for starting the timer)

```
> 1 votes

---
Tags: arduino-uno, interrupt, atmega328, timers
---


# Question
Title: Why the LED freezes? when I am adding a delay?
I am new into arduino and stuff. So i was playing around with the pull up resistor. It worked fine but the problem rised when I used a delay to turn the led on for few seconds before it gets back to low state it stopped working when I pressed the switch multiple times it may work sometimes but maximum time it is not working

***here is the code***

```
const int buttonPin = 4;
const int ledPin =  12;
int buttonState = 0;

void setup() {
      pinMode(ledPin, OUTPUT);
      pinMode(buttonPin, INPUT_PULLUP);
}

void loop() {
        buttonState = digitalRead(buttonPin);
      if (buttonState == LOW)
  {
    digitalWrite(ledPin, HIGH);
    delay(5000);
  } else
  {
    digitalWrite(ledPin, LOW);
    delay(5000);
  }
}

```

# Answer
> 5 votes
Your Arduino does nothing during the delay(5000). So pressing the button during the 5000 mSec that the led is off won't do anything. Or you must be very lucky to press the button in the very small time between one loop and the next.

I learned a lot about timing and delays with this tutorial: Blink Without Delay

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


# Question
Title: Need Input: Wait for voltage input to begin script & when voltage maintains 0V for X amount of time Reset and wait for Voltage Input
So I'm currently working on an automotive set up.

I'm using a 555 timer to emulate a turn-signal alternating voltage pulse (12V to 0V and repeat) for debugging purposes which is output to turnPin/A1.

Here's the goal: When voltage is greater than 1V arduino is to supply constant power to output pin (pin 13) until input voltage is returned to constant 0 (or end of turn signal input) for x-time or as I'll refer to as Timeout.

It seems I've gotten the constant power to apply when input is applied and then turn off constant output when voltage is back to 0V. However I'm having difficulty getting the timeout function to work properly as the LED still remains HIGH.

## EDIT: I've reworked the code to use millis(); rather than purely using sensor inputs. I've also added comments to help walk you through what I believe is happened/what I want to happen.

```
// Constants won't change
const int ledPin = LED_BUILTIN; //using built in led + pin13
const int turnPin = A1;         // the input pin (turn signal alternating 5V/0V/5V/0V & so-forth)

// Variables will change
int ledState = LOW;             // the current state of the output pin
int prevLed = ledState;
int lastVoltage = 1;            // the previous reading from voltage source
int state = 1;                      // the current "state" (see below)
                                // State = 1++: LED OFF -- State = 0: LED ON

// The following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.

long previousMillis = 0;    //the last time the voltage reached 0
long waitTime = 100;    // the wait time

void setup()
{
  pinMode(ledState, OUTPUT);        //set output pin
  pinMode(turnPin, INPUT);          //set input pin NOTE: SIGNAL ALTERNATES
5V/0V/5V/0V & so forth to emulate a turn signal for this application
  Serial.begin(9600);               //begin serial
}

void loop()
{
  int sensorValue = analogRead(turnPin);        // Read voltage at input pin
  float voltage = sensorValue * (5.0/1023.0);   // Convert
  unsigned long currentMillis = millis();    // set currentMillis as current
 time

  if (voltage > 1)      //if Voltage greater than 1V
  {
    ledState = HIGH;    //turn led on
    state = 0;          //set state to 0
  }

  if (voltage < 1)      //if voltage less than 1V
  {
    currentMillis;      //set currentMillis as current time

    if ((millis() - currentMillis) > waitTime) // if (current time minus time voltage was less than 1) is greater than wait time
    {
        ledState = LOW;     //set LED to off
        Serial.print("OFF - TIMED OUT - WAITING FOR INPUT: ");  //output message for debug
        Serial.println(state);//current state
        state++;              //increment state (time passed)
    }
        else if ((millis() - currentMillis) < waitTime) // if (current time minus time voltage was less than 1) is less than wait time
        {
            ledState = HIGH;    //set LED to on
        }
  }
  digitalWrite(ledPin, ledState);   //send LED status to output
}

```

# Answer
> 1 votes
Thanks for everyone's input. I've come up with the solution.

Using the `while` function I was able to create two "states" for the code to be in. A timed-out state and *not* timed-out state, respectively. While in the timed-out state the output will be 0 and vice-versa for the latter and wait for the voltage to reach 0 for "X" amount of time.

I also integrated a "learn" feature to set the delay based on the alternating input voltage if necessary. Otherwise it will default to the value within the `timeoutWait` variable.

Code is below. Please let me know if you have any input/suggestions.

```
/*
  PURPOSE: This application was built for an automotive application. Client replaced OEM turn signal's with aftermarket multicolor
  LED strips controlled by an unknown controller. In order for the turn signal function of the LED strips to work the
  controller had to be powered on. It was undesired to run the LED's every time the vehicle was driven. Therefore, the
  controller needed to be supplied constant power when an input from the OEM turn signal wiring (which alternates 16V/0V/16V/0V...
  and so-forth was applied.

  OVERVIEW: In a nutshell: this application will supply constant output to any specified output (pin 13 in this case) when 5 Volts is
  applied to any specified Analog input (pin A1 in this case). When voltage to the input pin is discontinued after 250milliseconds
  the constant output will be terminated. The application will then wait for voltage to be resupplied to the input pin.

  This application will also support an alternating input source (turn signal in this case). The amount of time to wait before returning
  the output pin to an OFF state is determined one of two methods.

  METHOD 1: Setting a default by amending the timeoutWait variable.
  METHOD 2: Using the Learn Button to time voltage drops and adjust the time-out wait time accordingly (+ 50 milliseconds for any variations in timing)

  USING THE LEARN BUTTON: At any point in time, press and hold the push button for approximately 6-seconds (real time - non simulation). This will
  time the difference in time between Voltage > 1 and Voltage < 1 and set it as the timeoutWait time. NOTE: The variable timeoutWait is not updated!
  The variable blinkRate is updated with this data.

  CIRCUIT: For emulation purposes a circuit was built using a 5V Power Supply connected to an ATTINY microprocessor (to emulate the alternating
  turn signal of 5V/0V/5V/0V alternation every 250milliseconds) connected to pin A1 on an Arduino UNO R3. An LED with a 1kΩ resistor was connected to pin 13.
  The learn button is powered and grounded from the arduino board with a 10kΩ resistor and connected to Digital Pin 2 on the arduino board.*/

// Constants won't change
int output = 13;            // Pin to output voltage
int input = A1;             // Pin to receive voltage
int learnButton = 2;        // Pin to receive signal for learn mode
int waitTime = 500;         // Time to wait in milliseconds
int timeoutWait = 250;      // Time to wait in milliseconds

// These variables will change
int relayState = LOW;       // Track what state the relay is in
bool timeout = false;       // Track if we're timed-out or not
bool learnMode = false;     // Track if we're supposed to be in learn mode or not
int blinkRate = 0;          // Store blink interval in millis (obtained from learn mode)
int lastButtonState = 0;    // Track the last state of the learn button
int buttonState = 0;        // Track the current state of the learn button

// The following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long timerStart = 0;        // Track when timer started
long timerStop = 0;         // Track when timer stopped
long passedTime = 0;        // Track time elapsed =(timerStop - timerStart)
long blinkStart = 0;        // Track when blink HIGH (learn mode)
long blinkStop = 0;         // Track when blink LOW  (learn mode)

void setup()
{
  pinMode(relayState, OUTPUT); // Set output pin
  pinMode(input, INPUT);       // Set input pin
  pinMode(learnButton, INPUT); // Set input pin (learn mode)
}

void loop()
{
  int sensorValue = analogRead(input);          // Read voltage at input pin
  float voltage = sensorValue * (5.0 / 1023.0); // Convert
  buttonState = digitalRead(learnButton);       // Read the learnButton pin
  Serial.begin(9600);                           //  Begin serial communication

  if (buttonState == HIGH)  // If the learnButton is pressed
  {
    learnMode = true;   // Enter learnMode
  }
  delay(50);        // Debounce

      if (voltage > 1)    // If Voltage is Greater Than 1 Volt
  {
    timeout = false;  // Set timeout state to FALSE since there's no reason to timeout
    passedTime = 0;   // Reset passedTime variable
    timerStart = 0;   // Reset timerStart variable
    timerStop = 0;    // Reset timerStop variable
  }

  if (voltage < 1)  //If Voltage is Less Than 1 Volt
  {
    timerStart = millis();                 // Start the timeout timer
    delay(waitTime);                       // How long should we wait until it times out?
    timerStop = millis();                  // Stop the timeout timer
    passedTime = (timerStop - timerStart); // Calculate how much time we waited

    if (passedTime >= waitTime) //If the calculated time is greater than or equal to our wait time
    {
      sensorValue;      // Re-check the Voltage first

      if (voltage < 1)  // If the voltage is still Less Than 1 Volt
      {
        timeout = true; // Set timeout state to TRUE since the voltage has been less than 1 Volt for >= our Wait Time
        timerStart = 0; // Reseet timerStart variable
        timerStop = 0;  // Reset timerStop variable
        passedTime = 0; // Reset passedTime variable
      }
    }
  }

  while (timeout == true)                    // If TIMEOUT = TRUE
  {
    relayState = LOW;                        // Set the relay state to LOW/OFF
    sensorValue = analogRead(input);         // Read voltage at input pin
    voltage = sensorValue * (5.0 / 1023.0);  // Convert
    digitalWrite(output, relayState);        // Tell the relay to turn off

    if (voltage > 1)    // if the voltage is Greater Than 1 Volt
    {
      timeout = false;  // Set timeout state to FALSE since there's no reason to timeout
      timerStart = 0;   // Reseet timerStart variable
      timerStop = 0;    // Reset timerStop variable
      passedTime = 0;   // Reset passedTime variable

    }

    if (voltage < 1)
    {
      timeout = true; // Set timeout state to TRUE since the voltage has been less than 1 Volt
      timerStart = 0; // Reseet timerStart variable
      timerStop = 0;  // Reset timerStop variable
      passedTime = 0; // Reset passedTime variable
    }
  }

  while (timeout == false)  // If TIMEOUT = FALSE
  {
    sensorValue = analogRead(input);        // Read voltage at input pin
    voltage = sensorValue * (5.0 / 1023.0); // Convert
    relayState = HIGH;                      // Set the relay to ON/HIGH since we're not timed out
    digitalWrite(output, relayState);       // The the relay to turn on
    buttonState = digitalRead(learnButton); // Read the learnButton pin

    if (buttonState == HIGH)  // If the learnButton is pressed
    {
      learnMode = true; // Enter learnMode
    }
    delay(50);        // Debounce

    if (voltage < 1)  // If the voltage is Less Than 1 Volt
    {
      timerStart = millis();                // Start the timeout timer

      if (blinkRate > 100)          // If blinkRate is Greater Than 100
      {
        timeoutWait = blinkRate + 50; // Set timeoutWait to blinkRate value + 50 milliseconds for any variations in timing
      }
      else                // If blinkRate is not Greater Than 100
      {
        timeoutWait = timeoutWait; // Leave default value alone
      }

      delay(timeoutWait);                     // How long should we wait to timeout in this state?
      timerStop = millis();                   // Stop the timeout timer
      passedTime = (timerStop - timerStart);  // Calculate how much time we waited

      if (passedTime >= timeoutWait)  //If the calculated time is greater than or equal to our assigned wait time
      {
        sensorValue;        //Re-check the sensor first

        if (voltage < 1)    //If the sensor read less than 1 Volt
        {
          relayState = LOW; //Set the relay state to OFF/LOW.
          timeout = true;   //Keep us in the timed out state.
          timerStart = 0;   //Reset timerStart variable.
          timerStop = 0;    //Reset timerStop variable.
          passedTime = 0;   //Resed passedTime variable.
        }
      }
    }
  }
  while (learnMode == true)  // If LEARNMODE = TRUE
  {
    sensorValue = analogRead(input);        // Read voltage at input pin
    voltage = sensorValue * (5.0 / 1023.0); // Convert
    Serial.println("LEARN MODE ACTIVE");  // Print to Serial Monitor

    while (voltage > 1)
    {
      sensorValue = analogRead(input);        // Read voltage at input pin
      voltage = sensorValue * (5.0 / 1023.0); // Convert
      blinkStart = millis();          // Set blinkStart as running millis();
      Serial.print("Start: ");          // Print to Serial Monitor
      Serial.println(blinkStart);       // Print to Serial Monitor
      delay(50);                // Debounce
    }
    while (voltage < 1)
    {
      sensorValue = analogRead(input);        // Read voltage at input pin
      voltage = sensorValue * (5.0 / 1023.0); // Convert
      blinkStop = millis();           // Set blinkStop as running millis();
      Serial.print("Stop: ");         // Print to Serial Monitor
      Serial.println(blinkStop);        // Print to Serial Monitor
      delay(50);                // Debounce
    }

    blinkRate = (blinkStop - blinkStart);   // Calculate blinkRate
    Serial.print("Blink Interval: ");     // Print to Serial Monitor
    Serial.println(blinkRate);          // Print to Serial Monitor
    delay(50);                  // Debounce
    learnMode = false;              // Exit learnMode
  }
  digitalWrite(output, relayState);       // Send relayState
}

```

# Answer
> 1 votes
It's hard to know where to start here. :)

---

```
 if (currentMillis + 500)

```

OK, what is that doing? It is adding 500 to currentMillis so that will be true almost all the time.

---

```
if (status = 3)

```

That is assigning 3 to status and then checking if it is non-zero, which it will be (it will be 3).

---

```
int turnPin = A1;
...

  int sensorValue = analogRead(A1);

```

Why not write:

```
  int sensorValue = analogRead(turnPin);

```

---

```
float voltage = sensorValue * (5.0 / 1023.0);

```

You calculate `voltage` but never use it. Why bother?

---

> As for your question regarding if (currentMillis + 500) I wanted this statement to take the current time and add 500 to it and then check ...

OK, then this is the way to do that:

```
// see if 1/2 a second is up
if (currentMillis - previousMillis >= 500)
   {
   previousMillis = currentMillis;  // reset previousMillis
   ... do something ...
   }

```

BTW, `previousMillis` is also a variable you weren't using anywhere else.

---
Tags: time, voltage
---


title: What's wrong with this code?

text:
# Question
Title: What's wrong with this code?
```
//Error message Arduino: 1.8.5 (Windows 10), Placa:"Arduino/Genuino Uno"

Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':

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

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

collect2.exe: error: ld returned 1 exit status

exit status 1
Erro ao compilar para a placa Arduino/Genuino Uno.

Este relatório teria mais informação com a
opção «Mostrar mensagens detalhadas durante a
compilação» seleccionada nas Preferências.
//

```

Code

```
#include <IRremote.h>      //must copy IRremote library to arduino libraries
#include <Servo.h>
#define plus 0xFD10EF   //clockwise rotation button
#define minus 0xFD50AF  //counter clockwise rotation button

int RECV_PIN = 2;       //IR receiver pin
Servo servo;
int val;                //rotation angle
bool cwRotation, ccwRotation;  //the states of rotation

IRrecv irrecv(RECV_PIN);

decode_results results;

const int pinoledlar=10;
int portaled4 = 12;
int portaled3 = 8;
int portaled2 = 11;
#define pinopir 3
int acionamento;
const int sirene=7;
int portaLDR = A5; //Porta analógica utilizada pelo LDR

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
  servo.attach(9);     //servo pin
  pinMode(pinoledlar,OUTPUT);
  pinMode(portaled2, OUTPUT);
  pinMode(portaled3, OUTPUT);
  pinMode(portaled4, OUTPUT);
  pinMode(pinopir,INPUT);
  pinMode(sirene,OUTPUT);
}

void loop()
{
    acionamento=digitalRead(pinopir);
    if (irrecv.decode(&results))
    {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value

    if (results.value == plus)
    {
      cwRotation = !cwRotation;      //toggle the rotation value
      ccwRotation = false;         //no rotation in this direction
    }

    if (results.value == minus)
    {
      ccwRotation = !ccwRotation;   //toggle the rotation value
      cwRotation = false;            //no rotation in this direction
    }
    }
    if (cwRotation && (val != 175))
    {
    val++;                         //for colockwise button
    }
    if (ccwRotation && (val != 0))
    {
    val--;                         //for counter colockwise button
    }
    servo.write(val);
    delay(20);          //General speed

    if (acionamento==HIGH)//se detetar movimento
    {
    digitalWrite(pinoledlar,LOW);
    tone(sirene,440,1000);
    delay(1500);
    }
    else// senão detetar movimento
    {
    digitalWrite(pinoledlar,HIGH);
    noTone(sirene);
    delay(1500);

    int estado = analogRead(portaLDR);  //Lê o valor fornecido pelo LDR

    // Caso o valor lido na porta analógica seja maior do que
    // 800, acende o LED
    // Ajuste o valor abaixo de acordo com o seu circuito
    if (estado > 900)
    {
    digitalWrite(portaled2, HIGH);
    digitalWrite(portaled3, HIGH);
    digitalWrite(portaled4, HIGH);
    }
    else  //Caso contrário, apaga o led
    {
    digitalWrite(portaled2, LOW);
    digitalWrite(portaled3, LOW);
    digitalWrite(portaled4, LOW);
    }
}
}

```

# Answer
You have a very common problem that is documented all over. You have two libraries, Servo and IRremote, that are both trying to use the same hardware timer. Do a little Google searching for possible fixes. You will need to either find a different Servo library or a different IRremote library.
> 1 votes

---
Tags: arduino-uno
---


title: Using a channel relay

text:
# Question
Title: Using a channel relay
im using 4 channel relay to switch the motor pump. but when the arduino output is high and i check first with led. the led behavior were high too but when i attached to the relay input IN1, the relay were low. its like reversed action(the arduino is high, but relay was low then when arduino output is low, suddenly the relay was high. i try to edit the code hoping if i set arduino output is low then relay will be high but its still the same, its reversed. arduino output is low but the relay become high. is there any way to make the relay to become high when the digital output is high?

however.. i didnt have the the actual circuit act but im using the digital pin as the output and some switches. the project im work on is the automatic aquarium pump and water change which is the pump will automatically refill the water actuated by the float switch and will automatically drain the water and refill the new water in certain time.

im using pin 13 as the output.. and the pin 1 as the input which is a switch as in picture im using a led as a output. but as soon i change to the relay, it become what i just said at the above

# Answer
> 0 votes
First of all, you'll soon blow up that LED. (Or the Arduino if you're really unlucky.) You need a current limiting resistor.

Secondly, most relays have two switch contacts: normally closed (N.C.) and normally open (N.O.). If you want your device to be off, unless the Arduino turns on the relay, use the N.O. connection. If you want your device to be on, unless the Arduino turns on the relay, use the N.C. connection.
It looks like you need N.O.

N.b: 'closed' means on (i.e. the switch is closed and current is allowed to flow).

Finally, you seem to be using an external pull-up resistor for you switch, which is completely unnecessary: the Arduino has an internal pull-up resistor on every digital pin that you can enable using `pinMode(pin, INPUT_PULLUP)`.

**Edit**: you didn't connect the relay to the button pin instead of the LED pin, did you?

---
Tags: atmega328, relay
---


# Question
Title: Using Teensy 3.5 (Arduino) to produce USB and Hardware MIDI messages simultaneously. Help?
Currently trying to get a teensy 3.5 to spam a series of notes in a loop over USB and hardware serial, which I am pretty sure it can do.

I have a MIDI circuit set up as per the specifications here: https://www.pjrc.com/teensy/td\_libs\_MIDI.html And currently have it booping a looping grouping of notes through massive embedded in ableton over a 5 PIN DIN circuit feeding into a generic MIDI 5 Pin DIN -\> USB converter.

```
 #include <MIDI.h>

#define HWSerial Serial1
MIDI_CREATE_INSTANCE(HardwareSerial, Serial1, MIDI);
const int channel = 1;

void setup() {

  HWSerial.begin(9600);
  MIDI.begin();
}

void loop() {
  int note;
  for (note=10; note <= 127; note++) {
    MIDI.sendNoteOn(note, 100, channel);
    delay(200);
    MIDI.sendNoteOff(note, 100, channel);
  }
  delay(2000);
}

```

I am lead to believe that when working with the USB serial output on the teensy you simply refer to the port as 'Serial' and for the others it's 'Serial1', 'Serial2', and so on.

I have tried using serial in place of the arguments within MIDI\_CREATE\_INSTANCE and also tried using MIDI\_CREATE\_DEFAULT\_INSTANCE which should do this setup on the default serial port, which I assume is USB? (This worked fine on my arduino mega setup where I was using the 16u2 chip as a serial -\> USB midi converter as per this method: https://github.com/ddiakopoulos/hiduino)

I'm just a little stumped as I have managed to get the code to compile using default instance and it appears as a midi device in windows device manager and also in ableton when I set USB Type: Serial + MIDI from arduinos tools dropdown box but does not output any notes :(

Can anyone help me get this working?

I'm currently toying with:

```
    #include <MIDI.h>

const int channel = 1;

void setup()
{

}

void loop()
{
  int note;
  for (note=20; note <= 63; note++) // Range was changed from 10:127 to save eardrums.
  {
    usbMIDI.sendNoteOn(note, 100, channel);
    delay(200);
    usbMIDI.sendNoteOff(note, 100, channel);
  }
  delay(2000);
}

```

but get

```
    C:\Users\Jamie\AppData\Local\Temp\arduino_build_144363/..\arduino_cache_283435\core\core_teensy_avr_teensy35_usb_serialmidi,speed_120,opt_o2std,keys_en-us_4939f5412a75a8560acb0f9e98268f02.a(pins_teensy.c.o): In function `_init_Teensyduino_internal_':

C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3/pins_teensy.c:582: undefined reference to `analog_init'

collect2.exe: error: ld returned 1 exit status

Error compiling for board Teensy 3.5.

```

and if I try inluding 'usbMIDI' I get

```
F:\GigaTech\MMMM_Beta_Code\debug\TeensyUSBMIDILoopTest\TeensyUSBMIDILoopTest.ino:1:21: fatal error: usbMIDI.h: No such file or directory

compilation terminated.

Error compiling for board Teensy 3.5.

```

although midiUSB is definitely installed :S

---

## ------------------------------C O N T I N U E D ----------------------------

Ok so I now have a working sketch for both USB and Hardware MIDI comms but I can't seem to get them to work simultaneously. My code for the hardware is as shown above, and the USB method is below:

```
 #include <MIDI.h>

MIDI_CREATE_INSTANCE(HardwareSerial, Serial1, MIDI);
const int channel = 1;

void setup() {
  MIDI.begin();
}

void loop() {
  int note;
  for (note=10; note <= 127; note++)
  {
    usbMIDI.sendNoteOn(note, 100, channel);
    delay(200);
    usbMIDI.sendNoteOff(note, 100, channel);
  }
  delay(2000);
}

```

I sort of assumed it would be possible to do something like this:

```
 #include <MIDI.h>

#define HWSerial Serial1
MIDI_CREATE_INSTANCE(HardwareSerial, Serial, MIDI); // 5 Pin DIN Out
const int channel = 1;

void setup()
{
  HWSerial.begin(9600);
  MIDI.begin();
}

void loop() {
  int note;
  for (note=20; note <= 63; note++) // Range was changed from 10:127 to save eardrums.
  {
    usbMIDI.sendNoteOn(note, 100, channel);
    MIDI.sendNoteOn(note, 100, channel);
    delay(200);
    usbMIDI.sendNoteOff(note, 100, channel);
    MIDI.sendNoteOff(note, 100, channel);
  }
  delay(2000);
}

```

But It doesn't seem to work. The code compiles and uploads just fine, however, ableton only sees MIDI messages coming over the teensy usb port and not through my MIDI receiver. I wondered if this is because the two are both being routed to my PC via a usb port but this shouldn't be a problem surely. I have also tried assigning the USB and hardware MIDI sends to different channels but to no avail.

I would love to get these both working simultaneously.

# Answer
> 1 votes
Just use usbMidi.

```
#include <MIDI.h>

MIDI_CREATE_INSTANCE(HardwareSerial, Serial1, MIDI);
const int channel = 1;

void setup() {
  MIDI.begin();
}

void loop() {
  int note;
  for (note=10; note <= 127; note++) {
    MIDI.sendNoteOn(note, 100, channel);
    usbMIDI.sendNoteOn(note, 100, channel);
    delay(200);
    MIDI.sendNoteOff(note, 100, channel);
    usbMIDI.sendNoteOff(note, 100, channel);
  }
  delay(2000);
}

```

# Answer
> 0 votes
So I managed to get both working sumultaneously!

It seems that no declaration of a MIDI instance is necessary for teensy MIDI over USB, and I had a small error in my code, Said function declaration should read 'Serial1' not 'Serial'.

Working code is below! :)

```
#include <MIDI.h>

#define HWSerial Serial1
MIDI_CREATE_INSTANCE(HardwareSerial, Serial1, MIDI); // 5 Pin DIN Out
const int HWChannel = 2;
const int USBChannel = 1;

void setup()
{
  HWSerial.begin(9600);
  MIDI.begin();
}

void loop() {
  int note;
  for (note=20; note <= 63; note++) // Range was changed from 10:127 to save eardrums.
  {
    usbMIDI.sendNoteOn(note, 100, USBChannel);
    MIDI.sendNoteOn(note, 100, HWChannel);
    delay(200);
    usbMIDI.sendNoteOff(note, 100, USBChannel);
    MIDI.sendNoteOff(note, 100, HWChannel);
  }
  delay(2000);
}

```

---
Tags: usb, midi, teensy
---


# Question
Title: How to show one thing in the serial monitor?
I am trying to make a device which has two push buttons and one analog input. At first the serial monitor will show INITIALIZING, then it will show ready to begin if the measured pin is pressed. Then only it will start to measure if again pressed, then it will show \****************************** and if the reset pin is pressed, it will show reset. If again pressed then ------------------------ but the problem is, it is showing

## \*************

(analog value) at the same time.

This is my code.

```
int sensor = A0;
int A = 0;
int resetPin = 3;
int measurePin = 2;
int resetstatus = 0;
int measurestatus = 0;
boolean flag1 = true;
boolean flag2 = true;
long current = 0;

void setup() {
    Serial.begin (9600);
    pinMode (sensor, INPUT);
    pinMode (resetPin, INPUT_PULLUP);
    pinMode (measurePin, INPUT_PULLUP);
    current = millis ();
}

void loop() {
    while (current < 3000) {
        Serial.println ("INITIALIZING");
        current = millis ();
        delay (200);
    }
    Serial.println ("Ready to begin");
    delay (200);
    resetstatus = digitalRead (resetPin);
    measurestatus = digitalRead (measurePin);
    if (resetstatus == LOW) {
        flag1 = !flag1;
        delay (50);
    }
    if (flag1 == HIGH)  {
        delay (50);
        reset ();
    }
    if (flag1 == LOW) {
        Serial.println ("------------------------------------");
    }
    delay (100);
    if (measurestatus == LOW) {
        flag2 = !flag2;
        delay (50);
    }
    if (flag2 == HIGH) {
        delay (50);
        measure ();
    }
    if (flag2 == LOW) {
        Serial.println ("***********************************");
        digitalWrite (13, LOW);
    }
    delay (100);
}

void measure() {
    A = analogRead (sensor);
    Serial.println (A);
    digitalWrite (13, HIGH);
}

void reset() {
    Serial.println ("reset");
}

```

# Answer
You have declare flag1 and flag2 as Boolean values but then you are looking to see if they are HIGH or LOW. Bools are either true or false. However because of the quirks of C++ this will probably work, if High and low are 1 and 0, its just bad style.

When you have this bit of code:

```
if (flag2 == HIGH)
{
    delay (50);
    measure ();
}
if (flag2 == LOW)
{
    Serial.println ("***********************************");
    digitalWrite (13, LOW);
}

```

You could use an else statement instead, i.e.

```
if (flag2 == true) // Corrected to true
{
    delay (50);
    measure ();
}
else
{
    Serial.println ("***********************************");
    digitalWrite (13, LOW);
}

```
> 2 votes

---
Tags: arduino-uno
---


# Question
Title: Will analog servo work with Arduino servo library?
I ordered some cheap servos from Amazon before I noticed that there seemed to be two different kinds (digital & analog).

Mine are Tower Pro SG90 Analog (http://www.towerpro.com.tw/product/sg90-analog/)

I was trying to get mine to work with an extremely simple sample code (below) using the Arduino Servo library (using digital pin 3) and I was experiencing the jitters.

I read over the solutions at : https://electronics.stackexchange.com/questions/77502/is-there-a-way-to-stop-servos-from-shaking

While reading that I learned that there is also a *digital* flavor of the servo: http://www.towerpro.com.tw/product/sg90-7/

I'm wondering if that is part of the problem I'm seeing with the servo jittering. I haven't seen this addressed elsewhere.

**My questions are:**

1. Are those servos even different? Maybe that is just a marketing thing??
2. Do I need to switch to using an analog pin for the servo data connection?
3. Is it even possible to use the Arduino Servo library for this purpose or do I need to use some *manual* code (like analogWrite()) **and** move the servo to an analog pin?
4. Or, should it work completely fine and the jittering is just some unrelated problem?

Here's the simple code I'm using:

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

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(3);  // attaches the servo on pin 3 to the servo object
}

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

```

# Answer
> 1 votes
Jitter can be caused by a lack of power, in which case it will be an irregular pattern that leaves the servo in the wrong place or it can be caused by the increment commands not being sent to the servo smoothly enough.

Have you got enough power for the servo? Where is the power coming from, does this output match the datasheet?

This analog servo requires PWM, so is pin 3 of you board PWM capable?

How fast does you servo rotate? At the moment you are saying 1degree every 15ms, I suspect that is too slow and that's why the arm is coming to a stop and then rotating again which is making it jitter.

# Answer
> 1 votes
There's a discussion here about the difference. The short answer is they both are commanded by a PWM signal but differ in the internal control circuitry that responds to it.

---
Tags: servo, atmega328
---


# Question
Title: Arduino Wall Wart and Relay Board Power Supply
I am relatively new to Arduino, and have been doing a project to trigger an LED/alarm when movement is detected to be over a certain threshold value. I am using an Arduino Uno, an LED/buzzer (https://www.adafruit.com/product/2994), an MPU-6050 (https://playground.arduino.cc/Main/MPU-6050), and a 4 channel relay board (http://www.seeedstudio.com/blog/2013/02/28/shield-evolution-flexible-add-ons-for-arduino/relay-shield/ \- sorry it's not very descriptive).

The LED/buzzer needs a 12V DC power supply, and I am using a wall wart to supply it. I am wondering how I am supposed to hook everything up - everything online tells me that the LED needs to be connected not only to the relay board, but to a power supply as well. However, my power supply is to the Arduino itself.

Based on the following picture, I would think that I would need to take the ground wire of the LED to the power source itself, then connect the power source to the relay board Common input.

Here is the circuit without the external power, using a small LED:

And here is the current setup (note that the cables were initially shifted over by 1 on the analog input, but I have fixed that since):

Is there a way to use the wall wart as the power supply? Do I even need the relay board?

# Answer
You will need the relay board. The Arduino output 5V and so you can't use it to directly power the 12V half of the circuit.

If you can split the power from the wall wart so it powers the 12V circuit and the barrel connector on the Arduino then that should work. If you can, then you will need to ensure that the 0v of the Arduino and the 12v circuit are tied together, otherwise the two halves of the circuit will be using different versions of 0V and you will get interesting results.

If you want to use the setup in your second picture then no you don't need the relay board, but that's only because the whole circuit is 5V.

"How do you split the power?" I hear you say, "do I need any extra hardware?"

That depends, how attached are you to your wall wart's cable? The way I have done it is to ***UNPLUG*** the wall wart, cut the cable in "half", strip a cm of each wire and plug both ends of it into two empty rows on you bread board. Then use jumper wires to take an additional feed off to the 12V circuit.

**CAUTION** Ensure you get the polarity of the wires the right way around. You can test this with a volt metre. I suggest red electrical tape to mark the +ve wire.

**IF YOU ARE NOT CONFIDENT DON'T DO IT!**
> 0 votes

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


title: RGB LED strip inverted PWM

text:
# Question
Title: RGB LED strip inverted PWM
This bug/stupidity-of-myself/problem is killing me:
I'm have created an RGB strip controller that cycles through the additive-rgb-color spectrum while turning a potentiometer.

I have a pot hooked up to my Arduino Nano v3 (from AZ-Delivery, not official Arduino). Then I have an RGB amplifier hooked up to the Arduino with each phase (R, G, B, V+) and to an external power supply (12V by 2A max).

I shortened my program and removed all the value-to-colour-conversion because that has nothing to do with the problem:

```
void loop() {
    ColorVal = analogRead(pinPot); //read value of color poti
    ColorByte = map(ColorVal, 0, 1023, 0, 255); //Scales 0-1023 to 0-255

    // potvalue to color conversion
    // ...

    // write via PWM to LED
    analogWrite(pinR, R);
    analogWrite(pinG, G);
    analogWrite(pinB, B);
}

```

**My problem:** Theoretically you would expect the system to show white when all variables (R, G and B) are set to 255. However, it behaves the other way around. When all values are set to 255 it's off and vice versa. Another example: When R = 255 and G = 0 and B = 0 Green and Blue are lighting and Red is off.

I thought this has to do with polarity or something but I cannot seem to find it out.

# Answer
> 2 votes
The RGB LED strip has a common anode (V+). When you put 12 V on R, G or B, the LEDs have 12 V on both sides, so there is no voltage across it and no current.

And if you put 0 V, they have 12 V across it and light up.

To fix it, just invert the PWM value in your code:

```
analogWrite(255-pinR, R);
analogWrite(255-pinG, G);
analogWrite(255-pinB, B);

```

---
Tags: arduino-nano, rgb-led, led-strip
---


# Question
Title: Powering USB cable that powers Arduino with regulated 5V
I am having an issue with external loads causing the computer I have my Arduino connected to to momentarily drop out, which causes the Arduino to lose USB power momentarily and the port drops out and won't reconnect unless I physically remove and reconnect the USB cable. Since I need the USB connected in order to send and receive serial data to/from the Arduino, I was wondering if I could physically open the USB cable, cut the 5V line, and supply it via and external regulated 5V supply. I wouldn't cut the ground wire, but would tie it to the external 5V supply. I have read conflicting information on this (something about handshaking) but was wondering if that applied to Arduino's specifically.

# Answer
I solved this problem by using a laptop instead. It is immune to these power fluctuations
> 1 votes

# Answer
If you are drawing more than 500mA from your PC then that is why it is happening.

I suggest, rather than butchering a cable, you get yourself a "wallwart" (Mobile phone charger) and use that to power the board. You really should work out how much current you are pulling before deciding on what PSU to use.

A problem with wall warts is earthing, you need to make sure that your PC and wall wart are connected to the same earth connection, so that they share a common ground.

If the current being drawn us only for a very short time then it might be possible to provide additional power using a capacitor in the power line. But plugging a charger in is much easier.
> 0 votes

---
Tags: arduino-mega, power
---


title: Relay Board making Output Signal Weak

text:
# Question
Title: Relay Board making Output Signal Weak
I am using an Arduino Uno and Relay Shield (http://www.seeedstudio.com/blog/2013/02/28/shield-evolution-flexible-add-ons-for-arduino/relay-shield/), and using a code similar to the Teapot Demo, in which an LED blinks when movement is detected. When I connect the shield, the LED blinks at the normal brightness when uploading the code, but blinks extraordinarily dimly when indicating movement. This is both the external and internal LED display for the Arduino.

This is my current setup:

I think it must be a code issue because the LED clearly has the ability to blink on and off normally. Any suggestions as to what is wrong or what I should do?

Below is my code:

```
#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif
MPU6050 mpu;
// uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
// components with gravity removed. This acceleration reference frame is
// not compensated for orientation, so +X is always +X according to the
// sensor, just without the effects of gravity. If you want acceleration
// compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
#define OUTPUT_READABLE_REALACCEL

// uncomment "OUTPUT_TEAPOT" if you want output that matches the
// format used for the InvenSense teapot demo
#define OUTPUT_TEAPOT

//----------------------------------------------------------------------------------------------

const int LED_PIN = 13; // (Arduino is 13, Teensy is 11, Teensy++ is 6)
const int buzzerPin = 12;

bool blinkState = false;

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}

// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================

void setup() {
    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    // initialize serial communication
    // (115200 chosen because it is required for Teapot Demo output, but it's
    // really up to you depending on your project)
    Serial.begin(115200); // this is a "Baud" rate
    while (!Serial); // wait for Leonardo enumeration, others continue immediately

    // initialize device
    Serial.println(F("Initializing I2C devices..."));
    mpu.initialize();

    // verify connection
    Serial.println(F("Testing device connections..."));
    Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

    // wait for ready
    Serial.println(F("\nSend any character to begin DMP programming and demo: "));
    while (Serial.available() && Serial.read()); // empty buffer
    while (!Serial.available());                 // wait for data
    while (Serial.available() && Serial.read()); // empty buffer again

    // load and configure the DMP
    Serial.println(F("Initializing DMP..."));
    devStatus = mpu.dmpInitialize();

    // supply your own gyro offsets here, scaled for min sensitivity
    mpu.setXGyroOffset(220);
    mpu.setYGyroOffset(76);
    mpu.setZGyroOffset(-85);
    mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

    // make sure it worked (returns 0 if so)
    if (devStatus == 0) {
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();

        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }

    // configure LED for output
    pinMode(LED_PIN, INPUT);
    pinMode(buzzerPin, INPUT);
}

// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================

void loop() {
    // if programming failed, don't try to do anything
    if (!dmpReady) return;

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {
        // other program behavior stuff here
    }

    // reset interrupt flag and get INT_STATUS byte
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    // get current FIFO count
    fifoCount = mpu.getFIFOCount();

    // check for overflow (this should never happen unless our code is too inefficient)
    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
    } else if (mpuIntStatus & 0x02) {
        // wait for correct available data length, should be a VERY short wait
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);

        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;

        #ifdef OUTPUT_READABLE_REALACCEL
            // display real acceleration, adjusted to remove gravity
            int Mag;
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            Serial.print("areal\t");
            Serial.print(aaReal.x);
            Serial.print("\t");
            Serial.print(aaReal.y);
            Serial.print("\n");
            Mag = sqrt((aaReal.x*aaReal.x) + (aaReal.y*aaReal.y));
            Serial.print("Accel. Mag. is ");
            Serial.print(Mag);
//            Serial.print("\t");
//            Serial.println(aaReal.z);
        #endif

        #ifdef OUTPUT_TEAPOT
            // display quaternion values in InvenSense Teapot demo format:
            teapotPacket[2] = fifoBuffer[0];
            teapotPacket[3] = fifoBuffer[1];
            teapotPacket[4] = fifoBuffer[4];
            teapotPacket[5] = fifoBuffer[5];
            teapotPacket[6] = fifoBuffer[8];
            teapotPacket[7] = fifoBuffer[9];
            teapotPacket[8] = fifoBuffer[12];
            teapotPacket[9] = fifoBuffer[13];
            Serial.write(teapotPacket, 14);
            teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
        #endif

        // blink LED and sound buzzer to indicate activity
        if (Mag > 120) {
          blinkState = !blinkState;
          digitalWrite(LED_PIN, blinkState);
//          delay(1000);
          tone(buzzerPin, 100);
        }
        else if (Mag <= 120) {
          digitalWrite(LED_PIN, LOW);
          noTone(buzzerPin);
        }

    }
}

```

# Answer
Without seeing your code, it is hard to tell you directly what the problems is. If you can, please post your code.

Based on the information in your question, I can see two possible causes for this.

Firstly, it could be that there isn't enough power from your supply to power everything. So when the Arduino tries to turn on the relay, it doesn't have enough grunt and the voltage drops too low and the Arduino resets, de-energising the relay. This happens many times a second and shows up as a dull LED.

This can be proven by disconnecting the relay from the Arduino output. Run the sketch again, and if everything works at full brightness without the relay connected, then it is almost certainly not enough power.

My second theory is that it is a bug in your code. Some cycles it detects movement and so it turns the LED on. Others cycles it doesn't detect a change in movement so it turns the LED off. This happens many thousand times a second. It would be visible on an oscilloscope if you have one.

The simple thing you could do for this scenario is to add a delay (eg `delay(1000);`) straight after the LED is turned on when movement is detected. This should leave the LED on for at least a second after movement is detected.
> 1 votes

---
Tags: arduino-uno, led, relay
---


# Question
Title: How to drive SPI MAX7219 7-segment led module using MCP23S17 extender
I have used Nick Gammon's (MAX7219) and (bitBangedSPI) libraries to drive SPI 7-segment 8 digit led modules successfully from the Arduino Uno. I would like to extend the number of Slave Select (CS) choices by using the MCP23S17 chip. The Mcp23s17 libraries to use might be https://github.com/dreamcat4/Mcp23s17 or https://github.com/MajenkoLibraries/MCP23S17. I have found the stackExchange entry How do you use SPI on an Arduino? to be helpful and this entry to be helpful http://www.ermicro.com/blog/?p=1050, but all the examples just turn on LED lights, not digits of 7-segment led modules.

I realize I might have to modify the MAX7219 and bitBangedSPI libraries where the digitalWrite command is used. However, I'm not sure how to modify or drive these 7-segement modules using the MCP23S17 chip.

A skeleton script to display PI selected on pin 6 on the Uno and address 0x0 of the MCP23S17 is shown below. I would like to choose which pinout to utilize as well but am not sure how this would be coded.

```
#include <SPI.h>
#include <bitBangedSPI.h>
#include <MAX7219.h>
// Mcp23s17 library available from https://github.com/dreamcat4/Mcp23s17
#include <Mcp23s17.h>

// Wire up the SPI Interface common lines:
// #define SPI_MOSI             7 //arduino   <->   SPI Master Out Slave In   -> SI  (Pin 13 on MCP23S17 DIP)
// #define SPI_MISO   not used 12 //arduino   <->   SPI Master In Slave Out   -> SO  (Pin 14 on MCP23S17 DIP)
// #define SPI_CLOCK            8 //arduino   <->   SPI Slave Clock Input     -> SCK (Pin 12 on MCP23S17 DIP)

// Then choose any other free pin as the Slave Select (pin 10 if the default but doesn't have to be)
#define MCP23S17_SLAVE_SELECT_PIN  6 //arduino   <->   SPI Slave Select           -> CS  (Pin 11 on MCP23S17 DIP)
// MULTIPLE DEVICES
// Up to 8 MCP23S17 devices can share the same SPI bus and slave select pins.
// Assign each chip a unique 3-bit device address (by setting the A2,A1,A0 pins)
// Then below, device address is optional 2nd parameter to the constructor fn...
// MCP23S17 Mcp23s17_0 = MCP23S17(MCP23S17_SLAVE_SELECT_PIN,0x0);
// ...
// MCP23S17 Mcp23s17_7 = MCP23S17(MCP23S17_SLAVE_SELECT_PIN,0x7);

// SINGLE DEVICE
// Instantiate a single Mcp23s17 object
MCP23S17 Mcp23s17_0 = MCP23S17(MCP23S17_SLAVE_SELECT_PIN,0x0);
const byte chips = 1;
static char outputBuffer[20]; // outputBuffer[] likely 2x the size it needs to be.

 // 1 chip, bit banged SPI on pins 6, 7, 8

MAX7219 display(chips, 6, 7, 8);  // Chips / LOAD / DIN / CLK
void setup()
{
    // Set all pins to be outputs (by default they are all inputs)
    Mcp23s17_0.pinMode(OUTPUT);

    display.begin();
    display.setIntensity(1);
    float pi = PI;
    dtostrf(pi, 7, 7, outputBuffer);
    display.sendString(outputBuffer);

}  // end of setup

void loop() { }

```

An example of the 8-digit 7-segment display. They are available on Amazon, Ebay, AliExpress etc. This one has 0.33 inch digits; other modules are 0.56 inch digits.

# Answer
> 1 votes
I'm not 100% on what you want to do but I have used both the chips you seem to want to do it with.

The MAX7219 can control 8 7Segment displays. I don't remember it being an SPI device, you just set the pattern you want in the registers and off it goes. (It could be that is used such a high level abstraction that I didn't realise it was SPI)

The IOX chip you are referring to is quite similar in behaviour, you setup the registers and away it goes.

On the surface it appears you can do what you want, but I suspect you will hit timing issues unless you want very static displays (maybe \< 1FPS). The time it takes you to establish the correct settings on the IOX chips will be the limiting factor.

You might want to look at the I2C version of the IOX which will require just 2 pins to connect to up to 7 ICs.

Alternatively use a network of microprocessors to each drive the maximum number of MAX7219s that they can, such as Nanos, ESP8266-12/NodeMCU, etc.

# Answer
> 1 votes
The MAX7219 chip is designed to be daisy chained -- connect Dout to the Din of the next MAX7219 (see the No-op Register section in the data sheet). I'm not sure if there is a limit to the number that can be daisy chained.

In fact Nick Gammon's library appears to support this. The "chips" parameter is the number of daisy chained MAX7219s.

The MAX7219 is does not use SPI. As I understand it the SPI/bitBangedSPI libraries are used as a convenient way to send the data bits with a synchronized clock.

# Answer
> 0 votes
Just daisy chain the MAX7219s as already mentioned. I use SPI directly with the chip all time, it works great with the default modes - 4 MHz clock, Mode 0, MSBFIRST. Many libraries use software SPI to talk to it, which I think is just a waste of the SPI hardware in the '328P family of chips.

---
Tags: spi, max7219
---


# Question
Title: Limiting Data Output Frequency from ADXL345
I have a working ADXL345 connected to an Arduino UNO, I need to limit the rate at which the ADXL345 takes in readings. I am using the SparkFun library for this sensor. I have read about the delay function and it works in the loop function but I was wondering if there might be a better way that is much more efficient?

# Answer
> 0 votes
Everytime you get a value from the sensor (for example with `getX()` or others) the library communicates with the sensor over I2C or SPI. So you can limit the usage of these function in your sketch. One way is with using `delay()`, but this is considered unefficient in most cases, since you are basically busy waiting during execution of `delay()`. You will not be able to do anything else in the future during this time span (if you want to add functionality to your device).

It's better to use non-blocking code, that only checks, if it is time to do something and if not going further through the program. Image like you yourself would bake a pizza. You would not stare at the clock for 20 min, until the time is up. You would periodically check, if the time has come to take the pizza out.

You can achieve this on an Arduino with use of the `millis()` function, which returns the number of milliseconds since the last powerup/reset. (Note that it overflows after about 50 days). There are plenty of tutorials for that out there. You can start with the `BlinkWithoutDelay` example from the Arduino IDE, which perfectly shows, how this is to be coded.

Note: If you are using the sensor with a battery, then you might want to limit its power usage. For this the library can set the corresponding registers in the sensor to set the datarate in the sensor (The rate at which the data in the sensor is updated). A smaller rate will lower the power consumption. So you can set the rate at about the rate of the reading in your sketch.

---
Tags: arduino-uno, accelerometer
---


# Question
Title: Combining two different coding program into one sketch
Im working on project that uses a relay module,arduino atmega328 and a 2 motor 12vdc. based on coding i give, the first code is the motor 1 will run based on the input switch. and the second code the motor will run based on the delay time. what im doing is, im going to combine these two coding into one sketch hoping these two coding will run together. but im confused on how to combine.

```
`int motorPin = 10; // pin that turns on the motor
int blinkPin = 9; // pin that turns on the LED
int watertime = 5; // how long to water in seconds
int waittime = 60; // how long to wait between watering, in minutes

void setup()
{
  pinMode(motorPin, OUTPUT);
  pinMode(blinkPin, OUTPUT); // set pin 13 to an output so we can use it to turn on the LED
}

void loop()
{
  digitalWrite(motorPin, HIGH); // turn on the motor
  digitalWrite(blinkPin, HIGH); // turn on the LED
  delay(watertime*3000);        // multiply by 1000 to translate seconds to milliseconds

  digitalWrite(motorPin, LOW);  // turn off the motor
  digitalWrite(blinkPin, LOW);  // turn off the LED
  delay(waittime*6000);        // multiply by 60000 to translate minutes to milliseconds
}`

```

this is the coding to run the motor by using delay time

```
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 == LOW) {
    // turn LED on:
    digitalWrite(ledPin, LOW);
  } else {
    // turn LED off:
    digitalWrite(ledPin, HIGH);
  }
}

```

this is the code which the motor will run based on the switch

for now, i dont have idea on how to combine these two coding.

the idea of my project is when switch is LOW(pin 3) the Motor 1(pin 13) will HIGH until the switch is HIGH, the motor 1 will be LOW and stop. At the same time, there will be time delay for 10 second and the Motor 2 (pin 10)will active soon after switch is LOW and delaying time for 10 seconds and the Motor 2 will be active with time for 25 second and stop and the next active for another 60 minutes

# Answer
> 1 votes
The simplest way of combining two programs is this:

1. Copy the content of the two programs into a single new .ino (program) file
2. Rename the first setup function `setup_one`
3. Rename the first loop function `loop_one`
4. Rename the other setup and loop functions `setup_two` and `loop_two`
5. Add the following code to the bottom of that file.

Code:

```
void setup()
{
  setup_one();
  setupr_two();
}
void loop ()
{
  loop_one();
  loop_two();
}

```

This is a very simplistic approach and it won't work for all cases. It will work in this case, but you will find it will do program one then program two. It will work because your constants don't clash (at the top of the program) you aren't using the same pin in the different programs, etc.

You need to learn what the code does though to really merge the programs, you will see better ways of doing it. The best way to learn is to right down, in your native language, what each line of code does, so in the case of program one:

```
turn on the motor
turn on the LED
wait for 'watertime' seconds
turn off the motor
turn off the LED
wait for 'waittime' minutes

```

For program 2:

```
  read the state of the pushbutton value:
  If the button is in state low
    Turn off the LED -- Not sure  this might be on
  else
    Turn on the LED -- Not sure this might be off

```

Hopefully you should recognise those descriptions (they are the comments) and when you read through the descriptions you will realise why the code you put together using the above method "doesn't work". It does, you just need to wait for 'waittime' minutes before you get a few microseconds to press the button.

If you want the motor to respond to the button then rearrange the natural language description to do what you want and then replace the English with the code and you should have a program that is close to working. (Hopefully)

---
Tags: relay
---


# Question
Title: How to set up a long press with something other than a button?
I wrote a program for a night light. There are 4 modes:

* on,
* adjustable brightness,
* timer,
* off.

For input, instead of using a button, I am using a distance sensor. Once a certain distance is read (eg. when passing your hand over the distance sensor) it changes to the next mode.

For the adjustable brightness mode it reads the distance sensor and is mapped to a PWM. The output pin is connected to a MOSFET which is switching a 12 volt LED.

This seems a slow way to cycle thru the system. I would like instead, if the user waved their hand over the sensor, it would turn on or off. However, if the user waited for 3 seconds with their hand over the sensor it would enable a dimmable mode. I'm not concerned about the timer function anymore and will be removing it.

All the code is already there except I need help writing a function that will keep track of how long its been reading a certain distance. Let's say for instance if the sensor reads a distance between 1 inch to 3 inches for 3 seconds it will then go into the dimmable mode. If it's under that then it will only toggle on/off. If the hand remains longer then 3 seconds it will also trigger the dimmable mode.

```
//----------------------------------------------------------
// USING A DISTANCE SENSOR TO CYCLE THRU DIFFERENT MODE
// FOR AN LED NIGHT LIGHT
// vonderasche
//----------------------------------------------------------

// declares library for distance sensor
#include <NewPing.h>
// constants
#define TRIGGER_PIN  12
#define ECHO_PIN     13
#define MAX_DISTANCE 200
const unsigned long onTime = 5000;
const unsigned long onTimer = 1200000;

int state = 1;

// declares NewPing object
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

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

void loop() {
    delay(50);
    // take distances reading
    int distance = sonar.ping_in();
    static enum { ON, ADJUST, TIMER } state;

    // if distance range is between certain values switch the state
    if (distance > 1 && distance < 3) {
        switch(state) {
        case ON:
          {
            // turns LEDs on
            Serial.println("ON");
            analogWrite(3, 255);
            analogWrite(5, 255);
            state = ADJUST;
            delay(1000);
          }
          break;
        case ADJUST:
          {
            // allows user to set brightness based on hand distance to sensor
            Serial.println("Adjusting Brightness");
            int distance2 = 0;
            int mappedBrightness = 0;
            unsigned long previousMillis = millis();
            unsigned long currentMillis = millis();

            // timer for setting brightness
            while ((currentMillis - previousMillis) < onTime) {
                int distance2 = sonar.ping_in();
                if (distance2 >= 1 && distance2 <= 6) {
                    mappedBrightness = map(distance2, 0, 6, 13, 255);
                    analogWrite(3, mappedBrightness);
                    analogWrite(5, mappedBrightness);
                }
                currentMillis = millis();
            }
            Serial.print("Mapped Brightness = ");
            Serial.println(mappedBrightness);
            delay(1000);
            state = TIMER;
          }
          break;

        case TIMER:
          {
            Serial.println("TIMER - 20 MINS");
            // variable declaration
            unsigned long ontime = 50;
            unsigned long previousMillis = millis();
            unsigned long currentMillis = millis();

            // dims leds to 25 percent
            analogWrite(3, 64);
            analogWrite(5, 64);
            delay(1000);
            // timer for leds
            while ((currentMillis - previousMillis) < onTimer) {
                int distance2 = sonar.ping_in();
                //breaks timer if hand swipe
                if (distance2 >= 1 && distance2 <= 4) {
                    break;
                }
                currentMillis = millis();
            }
            // turn off leds - either hand swipe happened or timer is up
            Serial.println("Turn off LEDs.");
            analogWrite(3, 0);
            analogWrite(5, 0);
            delay(1000);
            state = ON;
          }
          break;
        }
    }
}

```

# Answer
This is not too different from the long press of a button. Lets consider the code to detect a long button press of greater than 3 seconds.

```
buttonState = digitalRead(PIN1);

if (buttonstate == HIGH)
{
    if ((currentMillis - previousMillis) > THREE_SECONDS)
    {
        // Put your code here
    }
}
else  // ie. buttonState == LOW
{
    previousMillis = currentMillis;
}

```

OK, so the code could be optimized. However, it shows the code for a long button press and hopefully its easy to understand for any newbies out there. The code above reads the button state and if it is HIGH (ie. pressed), it will then check to see if the timer has run for more than 3 seconds. However, if the button is released, the timer resets.

Now lets consider the code for a distance sensor:

```
int distance = sonar.ping_in();

if (distance >= 1 && distance <= 3)
{
    if ((currentMillis - previousMillis) > THREE_SECONDS)
    {
        // Put your code here
    }
}
else  // ie. outside of the range
{
    previousMillis = currentMillis;
}

```

You will notice that only the first two lines change. I hope this helps!!
> 1 votes

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


title: maintain state of a channel cd74hc4067

text:
# Question
Title: maintain state of a channel cd74hc4067
I have this code to change channels.

```
void setMuxChannel(byte channel) {
   digitalWrite(muxS0, bitRead(channel, 0));
   digitalWrite(muxS1, bitRead(channel, 1));
   digitalWrite(muxS2, bitRead(channel, 2));
   digitalWrite(muxS3, bitRead(channel, 3));
}

```

I have this code to write a value in a channels, but when I change to a new channel, the previous channel returns to LOW. I want to turn on LEDs using multiplexer, however the LEDs do not stay on since the channel they are connected to does not keep its value.

```
  setMuxChannel(1);
  digitalWrite (muxSIG,a);
  delay(5);
  setMuxChannel(2);
  digitalWrite (muxSIG,b);
  delay(5);
  setMuxChannel(3);
  digitalWrite (muxSIG,c);
  delay(5);
  setMuxChannel(4);
  digitalWrite (muxSIG,d);

```

# Answer
> 1 votes
The whole point of a multiplexer is to only connect ONE channel at a time to the input. It is designed to send many different signals through one wire by time sharing. Normally data in some form is send, and not the direct control current of a simple load. So you will not be able to drive more than one channel at a given time.

You can cycle very fast through the channels to let it seem, as if the LEDs were on simultaneously, but this will decrease their light intensity.

If you just want to drive some LEDs without using too mich of the IO pins, you should follow Majenkos comment and use a shift register instead. They can drive all outputs at the same time if wanted. Also often they can be daisy-chained to simply controlling multiple shift registers through a single output of the Arduino.

---
Tags: arduino-uno, multiplexer
---


title: RTC square wave

text:
# Question
Title: RTC square wave
I have a DS3231 Real Time Clock module and I'd like to use the Square Wave output.

I wonder how can I set the frequency of the pulse?

How long is the (time) length of the pulse?

**UPDATED QUESTION**

In order to use the DS3231 as an 1PPS interrupt, I want to use the Square Wave output. Here's how I connected it to an Arduino.

I connected to the SQW output a 10kΩ pull-up resistor and an LED. After that I tested the code which shows the time and worked fine.

```
#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 rtc;

void setup () {
   Serial.begin(9600);
   #ifdef AVR
      Wire.begin();
   #else
      Wire1.begin();
   #endif
   rtc.begin();

  if (! rtc.isrunning()) {
     Serial.println("RTC is NOT running!");
     rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    }
  }

void loop () {

   DateTime now = rtc.now();
   Serial.print(now.year(), DEC);
   // etc
   }

```

*(The DS3231 works fine with the DS1307 library)*

In this case the LED was just flickering, so I thought that the default frequency of the SQW should be grater than 1Hz. I googled a bit and realized that I had to change some registers. So I found this piece of code which I called from the setup() function, but with no success, the LED is still flickering.

```
void set1Hz() {
   // Frequency is stored in register 0x0e in bit 3 and 4
   Wire.beginTransmission(0x68);
   Wire.write(0x0e);
   Wire.endTransmission();
   Wire.requestFrom(0x68, 1);
   uint8_t register0E = Wire.read();

   // clear bits 3 and 4 for 1Hz
   register0E &= ~(1 << 3);
   register0E &= ~(1 << 4);

   // put the value of the register back
   Wire.beginTransmission(0x68);
   Wire.write(0x0e);
   Wire.write(register0E);
   Wire.endTransmission();
 }

```

Since I'm now qualified for low level programming, any suggestions on how to change the registers would be appreciated.

# Answer
Even though it is unusual for someone to answer his/her own question, I did some more digging and managed to solve the problem. So, I'd like to mention one or two items in order to help someone who may encounter the same problem.

* I used the Jack Christensen's library https://github.com/JChristensen/DS3232RTC, but I had to update the Time.h library.
* In the setup() I add this line in order to enable the SQW output and set it to 1PPS.

```
RTC.squareWave(SQWAVE_1_HZ);

```

Other options are SQWAVE\_1024\_Hz, SQWAVE\_4096\_Hz, SQWAVE\_8192\_Hz and SQWAVE\_NONE
* Using the LED and resistor (390Ω) as shown in the figure above, it works as a voltage divider. In that case the voltage between SQW output and Ground didn't exceed 2.0V. Thus someone should be careful if wants to have an LED indicator and wants to use SQW output as interrupt.
> 2 votes

# Answer
with DS1307 Tiny RTC library:

"**rtc.writeSqwPinMode(0x10);**" in the setup loop...

sets DS output to 1 Hertz, squarewave

Its not exactly 1PPS signal, which is typically a narrow pulse,

but this 50% duty cycle signal will do as a 1 second interrupt.
> 0 votes

# Answer
SQWV output only pulls low, it is an open drain output.

Wire up like this: 5V to LED anode, LED cathode to current limit resistor, other leg of resistor to SQWV pin.

Check the current capability of the pin. 10K will make very dim (if seen at all) LED. Try 1K.
> 0 votes

---
Tags: rtc
---


title: How to use tone in two pins?

text:
# Question
Title: How to use tone in two pins?
I have a buzzer and an IR led emitter so I have to use the tone function to sound the buzzer and to modulate the output of the LED. I have connected the led pin 5 of the arduino, the buzzer pin A0.

```
int tones[] = {261, 277, 294, 280, 230};
const int pinBuzzer = A0;
const int cr_pin = 5;

void setup(){
  Serial.begin(1200);
  tone(cr_pin, 38000);  /* For modulation at 38kHz */
  pinMode(pinBuzzer, OUTPUT);
}

void soundBuzzer() {
  for (int i = 0; i < sizeof tones; i ++) {
    tone(pinBuzzer, tones[i]);
  }
    noTone(pinBuzzer);
}

void irLED() {
  Serial.println("Hello");
}

```

This is my code but I can not make the led and the buzzer work at the same time, apparently the buzzer is affected by the tone line `(cr_pin, 38000); / * For modulation at 38kHz * /.`

I tried to remove `(cr_pin, 38000); / * For modulation at 38kHz * /.` of the setup and leave code in the following way.

```
int tones[] = {261, 277, 294, 280, 230};
const int pinBuzzer = A0;
const int cr_pin = 5;

void setup(){
  Serial.begin(1200);
  pinMode(pinBuzzer, OUTPUT);
}

void soundBuzzer() {
  for (int i = 0; i < sizeof tones; i ++) {
    tone(pinBuzzer, tones[i]);
  }
    noTone(pinBuzzer);
}

void irLED() {
tone(cr_pin, 38000);  /* For modulation at 38kHz */
      Serial.println("Hello");
noTone(cr_pin);
    }

```

In the first code the LED works but not the buzzer and in the second code the buzzer now works but not the LED.

# Answer
> 1 votes
Only one tone can be generated at a time. If a tone is already playing on a different pin, the call to `tone()` will have no effect. If the tone is playing on the same pin, the call will set its frequency. Source: arduino.cc - tone().

`noTone()` Stops the generation of a square wave triggered by `tone()`. Has no effect if no tone is being generated. Source: arduino.cc - noTone()

---
Tags: arduino-uno
---


title: Reduce speed on DC motor

text:
# Question
Title: Reduce speed on DC motor
The Arduino starter kit came with a DC motor. I want to have it rotate at a slow speed so it can be on a reel and automatically dispense and wind wire, however, I don't know how I can slow it down.

Giving it an analog value of 1 is still way too fast.

Is there any way to control or reduce the speed. Like a 360 degree turn in a second rather than milliseconds?

Thanks

# Answer
> 1 votes
Remember if you are using a UNO or similar there is no Analog Output, the output is PWM (Look that up). If its DC motor then it needs to work from a DC (constant voltage) and will spin at a fixed speed. Motors usually have a RPM (speed) specification. Speed can be reduced with gears and rotation detected with rotary encoders and or sensors like Infra Red Switches or Reed Switches. You can also get Motor Controllers like... https://howtomechatronics.com/tutorials/arduino/arduino-dc-motor-control-tutorial-l298n-pwm-h-bridge/ AC Motors can be speed controlled by changing drive frequency, this is usually called an inverter. NOTE reducing DC voltage will result in less torque and higher current. Hope this helps.

---
Tags: arduino-uno, motor, speed
---


# Question
Title: How to communicate with ESP8266 ESP01 by sending data through softwareserial on Arduino Uno?
I am able to send AT commands when connecting to the software through the TX/RX pins (1, 0) and the ESP01 communicates perfectly. However, as soon as I start doing that same thing with code I can't get the ESP01 to respond whatsoever. All I'm trying to do is get an OK back from the serial monitor. I changed the baudrate on the ESP01 as well as my serial monitor from 115200 to 9600, 19200 using this command:

`AT+UART_DEF=9600,8,1,0,0`

Troubleshooting steps taken:

1. Tried upping the voltage in case it wasn't getting enough current.
2. Tried different ESP01s.
3. Tried switching TX and RX pins.
4. Tried using different pins on the Uno (2 and 3, 10 and 11, 7 and 8).
5. tried changing `myESP.println("AT");` to `myESP.write("AT\n\r");`.

Nothing works. I've done a ton of research and I haven't found anything wrong with what I'm doing, do you guys have any ideas?

```
#define TX 3
#define RX 2
String ssid = "*****";
String password = "******";

#include "SoftwareSerial.h"

SoftwareSerial myESP(RX,TX);

void setup() {
  pinMode(RX, INPUT);
  pinMode(TX, OUTPUT);
  myESP.begin(19200);
  Serial.begin(19200);
}

void loop() {
  myESP.println("AT");
  delay(5000);
}

```

Schematic is as follows: TX -\> pin 3 RX -\> pin 2 Vcc -\> 3.3v GND -\> Ground CH\_PD -\> Vcc

# Answer
How about this:

```
void loop() {
  while(Serial.available() > 0) {
     myESP.write(Serial.read());
  }
  while(myESP.available() > 0) {
     Serial.write(myESP.read());
  }
}

```

That code will continue to load data to and from the software serial not just one byte. You can also use string concatenation:

```
String data = "";
while(Serial.available() > 0) {
   data += Serial.read();
}

```

Or arrays:

```
int data_max = 4096;
int data_size = 0;
char data[data_max];
while(Serial.available() > 0) {
   if(data_size < data_max) data[data_size++] = Serial.read();
}

```
> 1 votes

# Answer
Alright so I figured out my issue. Here's the answer for anyone with this problem in the future.

1. Remove `pinMode(RX, INPUT);` and `pinMode(TX, OUTPUT);`.
2. SoftwareSerial isn't going to relay the response back, so you have to program a response in, that's why sending "AT" by itself to the serial port is pointless.
> 0 votes

# Answer
RX from Arduino goes to TX on EXP, and TX from Arduino goes to RX on ESP, BUT

Why not just put ESP01 in program mode and upload adruino code directly to it doing away with the AT commands
> -1 votes

---
Tags: arduino-uno, serial, esp8266, c, softwareserial
---


title: FTDI and atmega328p-au

text:
# Question
Title: FTDI and atmega328p-au
I want to connect an Arduino Pro Mini with ATmega328P so as to drive a SI4463. But I don't know BLK, CTS, DTR should be connected to what pins of ATmega328P.

How do I connect this?

# Answer
BLK is ground.
CTS is generally not used. I leave it unconnected on my boards.
DTR goes to the auto-reset circuit.

Update:

> Can I let DTR directly connect with RESET ?

Auto-reset circuits use a .1uf capacitor between the DTR (or RTS, depends on which one your cable supplies) and the reset pin. (The exact value probably isn't too important). Without it, the reset circuit is likely pick up noise and randomly reset the Arduino.
> 4 votes

---
Tags: pins, atmega328
---