body:
I have [a page about using switches](http://www.gammon.com.au/switches) but since I don't want to give a link-only answer I'll summarize here.

---

## Detect switch changes

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

* It was closed and is now open.

Or:

* It was open and is now closed.

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

<!-- language: lang-c++ -->

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

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

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

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

      // other code here ...

      }  // end of loop

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

---

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

---

## Debouncing

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

<!-- language: lang-c++ -->

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

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

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

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

      // other code here ...

      }  // end of loop

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

---

## Debouncing without delay

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

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

<!-- language: lang-c++ -->

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

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

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

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

           }  // end if debounce time up

        }  // end of state change

      // other code here ...

      }  // end of loop

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

---

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

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

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

<!-- language: lang-c++ -->

    static bool switchWasPressed;

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

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

<!-- language: lang-c++ -->

    Serial.println ("Switch closed.");

You put:

<!-- language: lang-c++ -->

    switchWasPressed = !switchWasPressed;  // toggle switch press state


sender: user

message:
Debouncing, or problem with my code?

I'm using a simple microswitch on pin 2, to activate an external interrupt.

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

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

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

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

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/cwjiq.png
Just to clarify, there is no delay between any of

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

sender: assistant

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

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

        Debounce debouncer = Debounce(50, SWITCH);

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

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


message:
Sim808: Is My GPS Module Broken?

Is my GPS module broken?

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

------------
Edited
------------

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

[![enter image description here][2]][2]

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

  [1]: https://www.banggood.com/SIM808-Module-GSM-GPRS-GPS-SMS-Development-Board-IPX-SMA-with-Antenna-p-1062818.html
  [2]: https://i.stack.imgur.com/DMBR3.png

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


message:
Using ESP8266-01 with Arduino uno R3

I am trying to learn how to use ESP-01(AI-Cloud, Black Version) with arduino

Initially, I created an adapter for it that has 4 inputs: RX, TX, Vcc(3.3v), GND I checked it and the wiring seems fine then I attached TX of arduino to TX of ESP and same with RX but with a voltage divider (1k ohm,2kohm),I uploaded arduino with a blank sketch and tried to run commands like AT and AT+CWMODE? but I got no response on the serial monitor.I tried to look for a proper tutorial to do this but, all tutorials show how to upload a sketch to ESP rather than arduino. Then I searched and found this piece of code:

    #include <SoftwareSerial.h>

    #define DEBUG true

    SoftwareSerial esp8266(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                                // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                                // and the RX line from the esp to the Arduino's pin 3
    void setup()
    {
     Serial.begin(9600);
     esp8266.begin(115200); // your esp's baud rate might be different

     sendData("AT+RST\r\n",2000,DEBUG); // reset module
     sendData("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
     sendData("AT+CIFSR\r\n",1000,DEBUG); // get ip address
     sendData("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
     sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80
    }

    void loop()
    {
     if(esp8266.available()) // check if the esp is sending a message
     {
       /*
       while(esp8266.available())
       {
         // The esp has data so display its output to the serial window
         char c = esp8266.read(); // read the next character.
         Serial.write(c);
       } */

       if(esp8266.find("+IPD,"))
       {
        delay(1000);

        int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                              // the ASCII decimal value and 0 (the first decimal number) starts at 48

        String webpage = "
Hello
&lth2>World!
<button>LED1</button>";

        String cipSend = "AT+CIPSEND=";
        cipSend += connectionId;
        cipSend += ",";
        cipSend +=webpage.length();
        cipSend +="\r\n";

        sendData(cipSend,1000,DEBUG);
        sendData(webpage,1000,DEBUG);

        webpage="<button>LED2</button>";

        cipSend = "AT+CIPSEND=";
        cipSend += connectionId;
        cipSend += ",";
        cipSend +=webpage.length();
        cipSend +="\r\n";

        sendData(cipSend,1000,DEBUG);
        sendData(webpage,1000,DEBUG);

        String closeCommand = "AT+CIPCLOSE=";
        closeCommand+=connectionId; // append connection id
        closeCommand+="\r\n";

        sendData(closeCommand,3000,DEBUG);
       }
     }
    }

    String sendData(String command, const int timeout, boolean debug)
    {
       String response = "";

       esp8266.print(command); // send the read character to the esp8266

       long int time = millis();

       while( (time+timeout) > millis())
       {
         while(esp8266.available())
         {

           // The esp has data so display its output to the serial window
           char c = esp8266.read(); // read the next character.
           response+=c;
         }
       }

       if(debug)
       {
         Serial.print(response);
       }

       return response;
    }

I hooked pins according to the code and it worked serial monitor output some lines but with allot of garbage values, This also created a wifi hotspot 'AI-Thinker' which I connected to and opened Ip as shown on debugging. This made ESP try to send string 'webpage' but mostly was garbage.

so my question is, how to properly use esp with arduino to maybe just switch an led on or send data from sensors, super basics?

Is it better to use esp Library and upload sketches to esp and control arduino with it?

Can some one suggest the proper tutorial for this? because even after all this I am still confused that is RX of arduino connected to RX(which makes no sense but given in many of google images) or TX of ESP-01?

body:
To confirm that the serial communication is working, connect the ESP to the Arduino D10 and D11 that is used as SoftSerial pins.

    +----+
    | PC |
    +--/-+
       |       +---------+
       \-------| Arduino |
         USB   +--.------+
                  | SoftSerial
                  |
               +--\----+
               | ESP01 |
               +-------+

And then upload this code to the Arduino. The code is from https://www.arduino.cc/en/Tutorial/SoftwareSerialExample

    /*
     Receives from the hardware serial, sends to software serial.
     Receives from software serial, sends to hardware serial.

     The circuit:
     * RX is digital pin 10 (connect to TX of ESP01)
     * TX is digital pin 11 (connect to RX of ESP01)

     Created back in the mists of time
     modified 25 May 2012
     by Tom Igoe
     based on Mikal Hart's example

     This example code is in the public domain.
     */

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(10, 11); // RX, TX

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(115200);
      while (!Serial) {
        ;
      }

      Serial.println("Goodnight moon!");

      // Set the data rate for the SoftwareSerial port
      mySerial.begin(115200);
      mySerial.println("Hello, world?");
    }

    void loop() {

      if (mySerial.available()) {
        Serial.write(mySerial.read());
      }
      if (Serial.available()) {
        mySerial.write(Serial.read());
      }
    }


body:
The `TX` pin of the Arduino goes into the `RX` pin of the ESP and vice versa: that's the way serial communication works, apart for voltage level considerations.

Another factor you have to take into consideration is the two devices MUST operate at the same speed, once known as *Baud Rate*: I believe 115200 might be the ESP default speed, but that's programmable.
There are also other two additional parameters which play a role in [serial communication][1], *Parity* and *Data bits*, but the default values are more than likely fine and you shouldn't worry about those.

So, in essence, verify your wiring and set the right speed considering some ESP modules run a firmware using non standard speed for serial comm.

  [1]: https://en.m.wikipedia.org/wiki/Serial_port


body:
```
#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <SoftwareSerial.h>

...

SoftwareSerial wifiSerial(WIFI_RX, WIFI_TX);
WiFiEspClient WIFI_CLIENT;

...

void setup() {
  wifiSerial.begin(9600); // or 115200
  WiFi.init(&wifiSerial);
  if (WiFi.status() == WL_NO_SHIELD) {
    printLog("WiFi shield not present");
    // don't continue
    while (true);
  }
  printLog("Connecting to AP ...");
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  printLog("Connected to AP");
}

...
```


message:
Connecting multiple boards to Arduino Uno r3

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

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

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

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

[![A SPI Master plus slaves][1]][1]

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

Arduino has a fixed pin assignment for SPI comunications:

[![Arduino Uno SPI][2]][2]

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

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

  [1]: https://i.stack.imgur.com/ZUpIB.png
  [2]: https://i.stack.imgur.com/QJx5X.jpg


message:
DHT11 returning incorrect values

I am trying to use DHT11 sensor with Arduino. But unfortunately it is returning following values:

Temperature = 1.00
Humidity = 2.00

My code is as follows:

    #include <dht.h>
    dht DHT;
    #define DHT11_PIN 7

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

    void loop()
    {
        int chk = DHT.read11(DHT11_PIN);
        Serial.print("Temperature = ");
        Serial.println(DHT.temperature);
        Serial.print("Humidity = ");
        Serial.println(DHT.humidity);
        delay(1000);
    }

Link to the library I am using is [here][1]

I have connected +ve to 3.3 V
I have connected -ve to Ground
I have connected out to digital pin # 7

[![enter image description here][2]][2]
[![enter image description here][3]][3]
[![enter image description here][4]][4]

  [1]: https://drive.google.com/file/d/0B1paTI5fzcHodno5azFOSVVDT0E/view
  [2]: https://i.stack.imgur.com/29Geb.jpg
  [3]: https://i.stack.imgur.com/PRsvr.jpg
  [4]: https://i.stack.imgur.com/JlmVP.jpg

body:
You have to call the **functions**:

    #include <DHT.h>
    #define DHT11_PIN 7
    DHT dht(DHT11_PIN, DHT11);

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

    void loop() {

        float humidity = dht.readHumidity();
        float temperature = dht.readTemperature();

       if (isnan(humidity) || isnan(temperature)) {
          Serial.println("Failed to read from DHT sensor!");
          return;
        }

        Serial.print("Temperature = ");
        Serial.println(temperature);
        Serial.print("Humidity = ");
        Serial.println(humidity);

        delay(1000);
    }

**Edit**

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/iDuou.png


body:
This is not a DHT11, DHT11 is blue, DHT21 is black, and DHT 22 is white.
It must be a DHT22 hence the wrong values.

EDIT : on your pictures the white case says AM2302, it's definitely a DHT22 the code must be adapted accordingly.


message:
Best way to store files on Arduino

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

Cheers!

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

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

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

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

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


body:
> Best way to store files on Arduino

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

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

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

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


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

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

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

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

  [1]: https://www.arduino.cc/en/Reference/EEPROMUpdate


message:
Disabling Timer2

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

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

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

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

Here is the problem :

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

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

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

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

Thank you very much.

Best

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

      unsigned long currentMillis = millis();

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

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

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

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

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

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

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

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

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

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

    }

    Serial.println(voltage);

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

    }
    }

  [1]: https://www.sparkfun.com/products/11574

body:
you provide lots of information that has nothing to do with your question, and at the same time omitted critical information that can help other help you.

> how to overcome with this issue.?

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

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

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

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


body:
Timer 2 is fundamental to that code. It is used to sample the heart rate sensor at a regular period. If you disable that timer you will never sample the sensor.

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

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

Off:

    TCCR2B = 0;

On (assuming you are using [this
code](https://github.com/WorldFamousElectronics/PulseSensor_Amped_Arduino/blob/master/PulseSensorAmped_Arduino_1.5.0/Interrupt.ino)):

    TCCR2B = 0x06;


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

https://github.com/WorldFamousElectronics/PulseSensor_Amped_Arduino/blob/master/PulseSensorAmped_Arduino_1.5.0/Timer_Interrupt_Notes.ino#L217

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


message:
Dshot implementation on Arduino (ESC protocol)

Does anyone one know if it's possible to implement Dshot on Arduino? I want to interface the Arduino with ESCs (electric speed controllers). These ESCs use Dshot,
 (https://oscarliang.com/dshot/) a digital protocol. From what I read online, you can make PWM follow a duty cycle. However, I want to change the duty cycle after each pulse and not just repeat the same duty cycle. I understand this requires DMA (direct memory access) but it's a bit over my head.

body:
> you can make pwm follow a duty cycle.

single shot pwm would be difficult to do on an avr.

much better to use hardware spi. Looks like you can do use 3 spi bits for every dshot bit. So 6 bytes of spi transmission would enough for every dshot frame (16 dshot bits).

running hardware spi at 3*0.6Mhz = 1.8Mhz or where about on a 16MIPS avr would be quite doable.


body:
In short, I ended up creating a library capable to drive multiple DShot600 ESCs:
[DShot-Arduino][1]
It still need a lot more polish, but the bit-banging works really well.

----------------

**SPI method**

I tried the method @dannyf mentioned, which involved combining 3 SPI bytes to form 1 dShot bit and it actually works.

But there's a few problem with SPI:

- It takes up the valuable SPI port, in theory you can still connect other SPI devices, but;
- maximum 1 dShot ESC can be connected
- During transmission of the packet, the CPU need to wait for the whole task, assume we are sending DShot300, each packet is about 54us long so CPU is halt for that amount of time. If you are doing this in 1000Hz, that is 5% CPU time.
- The timing is not very accurate to the DShot protocol standard

e.g. for DShot300, each bit is
> 1.25us High - 1.25us H/L - 0.83 Low

> for a 16MHz Arduino, 1.25us will be 20 CPU cycles which is not accurate to transmit with a SPI byte

I end up with the following codes to send a bit:

    inline void dshot_0(){
      SPDR = 0xFF;
      NOP;
      while (!(SPSR & _BV(SPIF))) ;
      SPDR = 0x60;
      NOP;
      while (!(SPSR & _BV(SPIF))) ;
      SPDR = 0x00;
      NOP8;
      while (!(SPSR & _BV(SPIF))) ;
    }

    inline void dshot_1(){
      SPDR = 0xFF;
      NOP;
      while (!(SPSR & _BV(SPIF))) ;
      SPDR = 0xFF;
      NOP;
      while (!(SPSR & _BV(SPIF))) ;
      SPDR = 0xF0;
      NOP8;
      while (!(SPSR & _BV(SPIF))) ;
    }

Above code is for DShot150, the SPI was set to 4Mbps, to adhere to the correct timing, I cannot transmit a full DShot byte as all on or all off, here's how the calculation done:

> 4Mbit SPI, each bit 0.25us. Thus for 16M clock arduino:

> * DShot 0 sequence: 10 bits of 1, 14 bits of 0
> * DShot 1 sequence: 20 bits of 1, 4 bits of 0

Those NOPn are just macro for the number of NOPs. I avoided using SPI library code here since the overhead of making library call is quite a lot.

**Pure software bit-banging**

This is the method resulted in my [library][1], since using hardware SPI won't give me any advantages of releasing CPU time, and doing some Math gives me that a DShot600 require total 27 CPU cycle on 16MHz UNO. Which the pattern is the following:

> 10 Cycle High -> 10 Cycle H/L (depending on bit 1/0) -> 7 cycles low

Which gives total of 1.6875us per bit or 27us per packet. To allow the very tight timing those are coded in assembly.

Also by applying bit-masking the library is capable of driving at most 8 ESCs on the same hardware port (on UNO, Digital pin 0-7, PORTD).

**_Update cycle_**

One last note about DShot is during my test, I found it is quite strict on the update frequency. It must be updated at exact time interval and I found the slowest update frequency will be around 500Hz. To provide the correct timing for that, the library used Timer 1 and by default update in 1000Hz frequency.

  [1]: https://github.com/gueei/DShot-Arduino


message:
Wireless Shield Not being detected w/ Arduino Uno R3

Wireless Shield is not being detected by arduino, not MAC address is displaying.
 Not sure what to try next, there is nothing noticeably wrong with the shield at first glance.

Green LED under status is on.

    Shield Type: CC3000 WiFi Shield
    Board Model: UNO R3

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

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

My Script:

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

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

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

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

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

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

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

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

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

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

body:
Your problem:

* You have a CC3000 WiFi shield
* You are using the WiFi library for the Arduino WiFi Shield
* The [Arduino WiFi Shield](https://store.arduino.cc/usa/arduino-wifi-shield) is a HDG204 based shield, not CC3000

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


message:
CH34x board fails with avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00 Atemel Mega328P AU1640

I have been given a board(*Atmel ATmega328P-AU 1640*) to program. I googled and found category of board <strike>*Arduino Uno*/</strike> CH34x-based clone.

But when I program an empty program:

<!-- language: lang-cpp -->

    void setup() {
      // put your setup code here, to run once:

    }

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

    }

I get this error:

    Sketch uses 444 bytes (1%) of program storage space. Maximum is 32256 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

These are all the ports that are available to me. I have connected my Arduino with one of the USB ports on my Macbook running MacOS Sierra

[![enter image description here][1]][1]

[![enter image description here][2]][2]

[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/tmbEU.png
  [2]: https://i.stack.imgur.com/NaqcR.png
  [3]: https://i.stack.imgur.com/ABA3Y.jpg

body:
That looks like a clone of an Arduino Nano to me, with a CH340G chip as the USB interface chip.  You need to:

1. Install the CH340G drivers
2. Ensure that the ATMega328PU chip has a bootloader installed on it

The last Nano I bought from China didn't have a bootloader installed. There are many tutorials online for teaching you how to install the bootloader using another Arduino as the programmer.


body: You have an Arduino nano clone using a CH340G chip for serial communication. You to down load and install a driver for your computer to recognize it. I don't use OSX, so there's not one I can recommend.


body:
The board is an Arduino Nano clone, not an Uno.

1. Plug the Nano's USB cable into your computer.
1. Download and install the CH340 driver from here: http://www.wch.cn/download/CH341SER_MAC_ZIP.html
2. In the Arduino IDE, select the port of your Nano from the **Tools > Port** menu.
1. **Tools > Board > Arduino Nano**
1. **Sketch > Upload**

If the port of your Nano doesn't appear in the **Tools > Port** menu (and no, dev/cu.Bluetooth-Incoming-Port is not the correct port) then you may have a damaged or charge-only USB cable. Try using a known-good cable or verify that your cable works for data on another device. If you have it plugged into a USB 3.0 port on your computer then try a USB 2.0 port instead.


body:
Try this instructions from install driver. https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver

Installation with Homebrew-Cask.

Then try this, and all work fine  ;)
http://www.instructables.com/id/How-to-fix-bad-Chinese-Arduino-clones/


body:
Remove the old driver by issuing one of the following commands (depending on your installation):

 - sudo rm -rf /System/Library/Extensions/usb.kext
 - sudo rm -rf /Library/Extensions/usbserial.kext

Restart your Mac.

**Install with Homebrew-Cask**
Install the driver by the following commands

 - brew tap mengbo/ch340g-ch34g-ch34x-mac-os-x-driver https://github.com/mengbo/ch340g-ch34g-ch34x-mac-os-x-driver
 - brew cask install wch-ch34x-usb-serial-driver

Restart your Mac.

Try upload some code in your Arduino.
In some cases the board might still not work.

This is because there is no bootloader installed on the Atmel microcontroller ship. To solve this problem we need a working Arduino and the clone Arduino we want to fix.

[![Make an ISP Programmer From Your Working Arduino
][1]][1]

First we connect the working Arduino to our computer and open the Arduino IDE.

We go to File -> Examples and click ArduinoISP and upload this to the Arduino. Ones uploaded disconnect the Arduino.

**

Connecting the Wires
--------------------

**

[![Connecting the Wires][2]][2]

**Next we connect the wires from the working Arduino to the clone as follows.**

**Without 10 uF capacitor.**

Go to Tools -> Board and select the chinese board that is not working. in my case it's an Arduino Genius/Uno

Next we go to Tools again -> Programmer and select Arduino as ISP.

Go to Tools again and select "Burn Bootloader".

Go back to Tools -> Programmer and set back to ArduinoISP.

Your clone should work just fine now. ;)

  [1]: https://i.stack.imgur.com/RfbYV.jpg
  [2]: https://i.stack.imgur.com/X5Mac.jpg


message:
How to call more than 10 different functions based on serial input?

I'm looking to basically call functions based on the serial ID I assign to it. For example, if I want to call function A I would type on the serial A and if I want to call function B then I would type B.

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

<!-- language: lang-cpp -->

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

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

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

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

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

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

<!-- language: lang-c -->

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

There are plenty of examples like this on this site.

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

<!-- language: lang-c -->

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

So to call function #11:

<!-- language: lang-c -->

    all_functions[10]();

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

<!-- language: lang-c -->

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

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

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

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

<!-- language: lang-c -->

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

Last, create some functions and add to hash table:

<!-- language: lang-c -->

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

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

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

<!-- language: lang-c -->

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

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

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


body:
a state machine would be the most efficient approach here.

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

the heart of the code would be something like this:

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


message:
Why did my pushbutton LED circuit work when my wiring was wrong?

I had a Coursera Arduino homewhere wherein you create a simple pushbutton-controlled LED circuit.

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

Here's what I did (wrong):

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

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

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

    /*
      Button

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

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

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

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

     This example code is in the public domain.

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

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

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

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

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

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

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

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


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


body:
> Why did it work?

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

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


message:
Uploading Arduino bootloader to ATmega32U4 with another Arduino?

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

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

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

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

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

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


message:
Standalone 328p Programming with CH340G programmer

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

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

Adding 100nF capacitor on DTR to RST

Trying without DTR

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

Burning a new bootloader after programming with Arduino as ISP

Any suggestions are greatly appreciated.

Thanks,

[![Circuit picture][1]][1]

  [1]: https://i.stack.imgur.com/9E6Fx.jpg

Verbose Upload Output

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

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

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

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

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

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


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

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

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

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

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

[This article details exactly how to do it and teaches you what the fuses are and what they mean.](http://www.instructables.com/id/How-to-change-fuse-bits-of-AVR-Atmega328p-8bit-mic/)


message:
Controlling 10+x 5m led strips with 10+ individual analog floor switches

I am looking to control around 10 (exact number TBD) non-addressable 5m led strips with an Arduino. Each led strip will be activated when a corresponding DIY analog floor switch.

The idea is to have a hallway with a number of these led strips oriented vertically from the floor to the ceiling and when somebody walks on the corresponding floor switch under the strip, the strip will light up.

I have a number of questions:

1. How could I have a setup that is scalable from 10 led strips and floor switches to 20? (having enough analog and digital pins)

2. How should I best distribute power to all the strips and for each switch? This is how I understand to setup 1 of the switches:[![][1]][1]

3. How do I wire the one colored non-addressable LED strips to the Arduino?

Note: I have coded before and done some soldering and simple electronics but have never used Arduino.

Thank you!

  [1]: https://i.stack.imgur.com/N0Vwq.png

body:
Unless you want to do fancy things with the LED strips you really don't need an Arduino to accomplish this task.  You can just switch each strip with a powerful enough MOSFET and control the gate with the sensor:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/e58OC.png)

<!-- End schematic -->

If you really want the Arduino (for example to add effects like delays, fading, blinking patterns, etc) it would basically go into the circuit at point `A` in the circuit. The sensor into an input and the MOSFET into an output.

Since these are just presence sensors (not pressure sensors, they don't sense pressure, only presence) you don't need an analog input to read them - a digital one will suffice and also make your programming simpler.

You can use shift registers or IO expanders to increase the number of input and output pins you have, or you can use a larger Arduino with more pins.


body:
I think that the best solution for you, unless you want a simple on/off control (if you want it just go with Majenko's solution) is to use port expanders.

Maybe this can be slightly overkill, but you can think of using a MAX7313.

This IC is I2C controlled and has 16 I/O; you can configure each as input or output, and with automatic PWM generation too. This means that the uC just has to send it the value of light you want to output and it automatically keeps the LED strips at the correct duty cycle.

This way you can connect a sensor to P0, P2, P4, ... and configure them as input, then a pull-up resistor and a MOSFET to P1, P3, P5, ... and configure them as output with PWM. From the arduino, you will just have to connect two pins (SDA, SCL) and, of course, GND, then you will have the ability to control eight sensor/led pairs to one sensor. You want to extend it? Just solder another IC and assign it another address (pins AD0..2 serve for this purpose). You can set 64 different addresses, thus being able to drive 512 sensor/led pairs.

Want more? Use RGB led strips. Connect P0 to sensor, P1 to R, P2 to G, P3 to B, and with each IC you'll be able to drive four sensor/led pairs. You'll be able to drive only 256 sensor/led pairs, but they will be rainbow colored...

This solution has only one drawback: I could not find any pre-made board with the MAX7313 on ebay. So you'll have to design your own PCB and solder it. If you are not able to do this, alternatives exist.

Adafruit has a PCA9685 16-channels port expander board (and a lot of other manufacturers made this). This has also integrated PWM and a lot of addresses possible, but the PCA has only outputs (so no inputs). You will be able to arrange them in a matrix (so with the 18 pins remainig you will be able to control 81 switches).

Another alternative is the MCP23017; this has inputs and outputs, but no automatic PWM; this means that if you want turn them on and iff ok, but if you want a variable light you will have to "manually" pull the pin high or low (very heavy on the I2C network).

Other solutions using SPI may have better performances (SPI is faster than I2C), and a lot of other ICs with SPI, I2C or other serial connections exist. You just have to find out the most suitable for you


message:
What is the proper way to make library pin mappings configurable?

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

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

[Here is an example where it is documented which part needs to be changed to match the pin layout of your board.](https://github.com/JoaoDiogoFalcao/Arduino_Due_SD_HSCMI#arduino-wiring)

body:
depending on your approach.

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

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


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

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

    class Something {
        uint8_t _cs;
        uint8_t _dc;

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

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

    Something mySomething(10, 8);


body:
I would use either of the following two possibilities:

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

Advantages:

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

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

Advantages:

- Can be dynamically changed

**Remarks**

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

For settings, mostly the second method is better.

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

**Macros**

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


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

Like so:

    #define PIN_ONE 1
    #define PIN_TWO 2

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

### Alternative 1

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


message:
How can I move an arduino library into my project repo and use it from there?

I've got this project that that is using the LiquidCrystal.h library. My import looks like this...

    #import <LiquidCrystal.h>

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

    #import "libraries/LiquidCrystal/LiquidCrystal.h"

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

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

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

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

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

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

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

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

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

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


body:
Try it with this folder structure:

    my_project
    |_src
      |_LiquidCrystal

and change the import to:

    #import "src/LiquidCrystal/LiquidCrystal.h"

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

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


message:
someone can help please? am getting an error saying expected } at the end of input

//set initial values
    int x = 0; // set initail zero value for the counter
    int preE = 512; // set initial value for light intensity in east direction
    int preW = 512; // set initial value for light intensity in west direction
    int predtime = 512; // set initial value for delay time
    int pretol= 512; // set initial value for tolerance value
    void setup() {
      Serial.begin(9600); // set the baud rate for the serial monitor

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

      void loop()
      {
        // Read the first reading

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

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

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

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

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

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

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

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

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

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

              if (E10 < 10 || E10 > 1000 )

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

          //Average the ten readings

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

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

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

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

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

       //check the differenc and open the coresponding relays

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

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

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

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

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

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

       delay(2000);

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

       {
        }
        }
       }

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

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

body:
You are missing five `}` at the end of your sketch.

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

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

    //store the values for the next loop

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


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

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

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

If you wrote that as a function:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

     //check the difference and open the corresponding relays

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

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

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

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


message:
Can't move servo with my Nano

I'm new to this kind of thing. My code works on my Uno without problem with two separate servos. I've ensured that it's not any faulty leads, having tried a few other circuits with LEDs, buttons and potentiometers as well, simply switching between my Uno (which works fine) and the Nano.

I've chosen the correct port, chipset and board each time and the code uploads fine to the Nano. The Nano simply refuses to do anything I tell it.

- Digital PIN of servo goes to designated D5 pin.

- Ground goes to the GND near the Analog pins (shouldn't matter which I imagine).

- Power goes to 5V.

The code above simply tells the servo to go to a certain degree when uploaded. Could anybody tell me why the servo will not move at all with the Nano? I just bought it and I haven't hooked up any power to it other than the USB, surely it isn't fried. It lights up and flashes as well.

    #include <Servo.h>
    Servo my_servo;

    void setup() {
      my_servo.attach(5);
      // Pin definition
    }

    void loop() {
      my_servo.write(60);
      // No. of degrees
    }

body:
Connect a multi meter in series with the servo connection from the uno to the servo and see how much current it draws when working (probably less than 20ma, definitely less than 40ma). Then connect it in series with the nano and see what happens. If you get no current then you're activating the wrong pin.

If you see a current draw but the servo doesn't move then you need to use some sort of switch (transistor, FET, relay) to switch the servo. You could also compare the voltage and current read off the nano to the requirement in the datasheet for the servo. Again, this may lead you to needing a switch.

Edit based on comments above... Also try your 5v directly to the servo, then add a forward biased diode in series which should simulate the voltage drop to the level of your nano (0.4-0.6v). If the servo doesn't work with the diode and does without then you can be pretty sure the issue is insufficient volts (which is likely given the rating of 4.8v you mentioned in comments).


body: I has the same problem. Example: With Arduino Uno only conected to 5V from PC, the servos run perfectly, but with Nano no, maybe the servos try to move, but not. I charged the skecth on the arduino Nano and deesconect form pc, and then i supply Arduino Nano with baterry Li-ion 2s. In another words, for servos you must to supply over 6 volts. Be careful because the max voltage of servos,can be 6 volts, you can use the regulator of Arduino, severals servos produce overheating in this regulator. Yes my english is noob.


message:
Is a solenoid piston strong enough to lock a water tubling?

My question is about hardware that i'll control with my arduino... Not Arduino itself (So I don't know if I'm in the right section ... :s)

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

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

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

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

  [1]: https://www.sparkfun.com/products/11015
  [2]: https://www.gearbest.com/robot-vacuum/pp_47721.html
  [3]: https://www.banggood.com/12V-Mini-DC-Brushless-Garden-Fountain-Pump-Hydrological-Cycle-Submersible-Water-Pump-p-1009353.html?rmmds=buy
  [4]: https://www.banggood.com/12V-Electric-Solenoid-Valve-Magnetic-DC-NC-Water-Air-Inlet-Flow-Switch-12-p-1023361.html?rmmds=buy

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

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

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

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

[![Cocktail Mixing Machine][2]][2]

As they note, they have in version 2.0

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

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

[![Peristaltic pump][3]][3]

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

[![Arduino controlled pump][4]][4]

  [1]: https://www.theinebriator.com/
  [2]: https://i.stack.imgur.com/OR8FD.jpg
  [3]: https://i.stack.imgur.com/F0bTH.jpg
  [4]: https://i.stack.imgur.com/EWYcM.jpg


message:
connection for hall sensor 4 pin and arduino nano

I'm not from electronics background so I don't know what should be the connections. My Hall sensor has 4 pins(AO, GND, +, DO)

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

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

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

This below is my code that I have written so far

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

    bool flag = false;

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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


message:
Make Sure Digital pin is high before Serial.write()

I have the following code for a [TTL to RS-485 Adapter Module ](https://www.newegg.com/Product/Product.aspx?Item=9SIA4SR1T56020&ignorebbr=1&nm_mc=KNC-GoogleMKP-PC&cm_mmc=KNC-GoogleMKP-PC-_-pla-_-AT+-+Electronics-_-9SIA4SR1T56020&gclid=Cj0KCQjwierMBRCHARIsAHl9i4FHSB6Xl5JEhlYYHC-P1SXYl0Tb-_HCnV8KZf9hBH_MuPIc__QB3kEaAsEZEALw_wcB&gclsrc=aw.ds)

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

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

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

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

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

That's an absolute maximum of 60.4ns.

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

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

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

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

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

Or a combination of the two.


message:
New to Arduino building

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

body:
There are lots of examples on the official Arduino website.

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

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

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

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

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

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

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


message:
How to detect if LED is switched on in external circuit using Arduino NANO?

I want to detect when an LED is powered on using an Arduino NANO. The LED is part of an external circuit. The LED uses about 1.8V. Would the circuit below allow me to detect when the LED is switched on? Is this the correct method of doing it? (The LED in the diagram represents the external circuit).

[![Circuit][1]][1]

  [1]: https://i.stack.imgur.com/wyece.png

body:
The answer depends on your definition of "on".

An led is on if

1. There is voltage across I th or

2. There insufficient voltage across it, or

3. There is current through it, or

4. It generates light output, or

5. It generates sufficient light output.

...

Based on each of the above, there is an answer to your question.


body:
No, you will not detect the LED state at all, as your transistor base is connected to the target circuit's supply rail, not a switched node.

Additionally, your circuit risks burning out the LED as it lacks a current limiting resistor.

Speaking more generally, the only *safe* way to do this with a fully unknown circuit is to have an optical sensor looking at the LED.

If you can determine that it is safe to make an electrical connection to the circuit (ie, that the internal ground is not riding on mains voltage) and that the point of the circuit you want to measure is within an allowed voltage above that, then you can connect the grounds and measure the switched side of the LED / resistor.  **But until you have far more electrical engineering experience, you are probably not in a position to make this safety determination.**  Even battery powered devices can generate dangerous voltages internally.

It's important that you not connect *between* the LED and resistor, but rather to whichever side of that series unit is not connected to a supply rail, as the voltage drop on the LED itself may not be sufficient to register.

Certain fancier LED drivers may give you problems, for example if they regulator current internally.  Also, LEDs with PWM brightness control may require filtered polling, or even interrupts / hardware pulse-in.


body:
I'm afraid your circuit does not work.
In fact, the base of the transistor is always connected to the power, regardless the LED being ON or OFF. Therefore the BJT would be always in the ON-state. Also a current limiting resistor in series to the LED is missing (but I think that it was just for sake of simplicity).

Assuming that:

- you can mount in series something to the LED

- an additional 1.3-1.5V voltage drop will not cause too much issues (to be short: if the external circuit power supply is "large enough", and if you will not be too much upset if the LED luminosity will be smaller).

- You want to sense a signal LED, i.e. let's say with a current smaller than 20 mA.

Then, the safest way would be to use an optocoupler, such as 4N25-4N35. Put the LED of the optocoupler (transmitter side) in series to the LED you want to "sense", and use the phototransistor side to sense the LED status: it's emitter goes to the GND to your Arduino Nano, the collector to any input, with pull-up (The pull-up is mandatory!).

In this way, when current flows across the LED, it will also flow in the optocoupler LED, therefore the optocoupler phototransistor will be ON.

Also, using the optocoupler the two systems are electrically insulated each other (and you won't need to share the grounds).

Below you can find an example.

[![enter image description here][1]][1]

EDIT:
If you cannot wire the optocoupler LED in series (e.g. not enough voltage headroom because the power supply is too close to the LED Vf, or your LED is already on a PCB), you can connect the optocoupler in parallel.
Assuming the LED current is much larger than 1mA, you can use the following circuit. Choose RO so that the current flowing on the optocoupler will be 1mA (390-470 Ohm in your case). Usage of high current-transfer-ratio (CTR) optocoupler is suggested, but this might work also with a 4N25 or 4N35 (you'll be pretty close to the limit...)
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/cgGyH.png
  [2]: https://i.stack.imgur.com/8EuZ8.png