body: I am completely new to arduino. I have created a circuit using solderless breadboard. But obviously the connections are lose or not as good as a soldered solution. So I was wondering since I am new to circuits too, what is the easiest

title: Arduino Newbie: Solderless Breadboard Alternate

Answers: 8

body:
The next step up from breadboard is either matrix board or strip board.

Matrix board is a PCB with a grid (matrix) of holes in a 0.1" grid with copper annulars around them for soldering.

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

Strip board (also known as the brand name Veroboard) is like matrix board but the holes are linked together in long strips, a little like a breadboard. These strips run the length of the board and you have to break the strips (there is a special tool you can use, but most people just use a small drill bit) into the pattern you require for your circuit.

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

Yes, both of these require soldering - so now is the time to get to grips with how to solder. There's plenty of tutorials and videos online to help you get to grips with it (though don't grip the hot end...). Don't be afraid of making a mess of your first attempts, soldering takes practice to get it right - and having the right tools helps.

Get a semi-decent soldering iron - not a plumber's iron, but a proper electronic one. You can get basic ones quite cheap. I started out with one of these cheap Antex ones:

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

If you can afford it, though, go for a temperature controlled one instead. It makes soldering easier since you are less likely to lift pads from over-temperature.

And last you will want some decent solder. I use 0.7mm solder with a rosin flux core. Don't use solder that doesn't have a flux core, that is for plumbing.

Having a flux pen (electronic flux, not plumbing flux) will help get you out of some sticky situations with your soldering as well. The addition of flux makes the solder behave itself. Without extra flux it can me somewhat unruly. Also some desoldering braid and maybe a desoldering pump can be useful (I tend to use braid more than my pump these days).

[![enter image description here][4]][4]
[![enter image description here][5]][5]

  [1]: https://i.stack.imgur.com/H6G35.jpg
  [2]: https://i.stack.imgur.com/1eJxj.jpg
  [3]: https://i.stack.imgur.com/KYo6N.jpg
  [4]: https://i.stack.imgur.com/6onRH.jpg
  [5]: https://i.stack.imgur.com/tflHV.jpg

body:
To make it easy, you can buy so-called proto shields for Arduino like below.

The advantage is that you can stick it directly on your Arduino (Uno/Mega) and you can soldier the extra components on the proto space.

[![Proto shield][1]][1]

  [1]: https://i.stack.imgur.com/7zk2v.jpg

body:
Breadboards are for development and testing. When you are OK with your circuit, then you solder it.

Your alternatives:

**Point-to-Point**

Just solder directly component to component. You can arrange your component for minimal space and minimal wiring length. Can be very elegant (depends on your abilities) and doesn't require any board.

[![Point to point example][1]][1]

**Perforated board**

For personal projects, you can use a perforated board to put all your components. Requires some planning in components placement and wiring (you can paint yourself in a corner). Easy to do.

[![Arduino pro mini][2]][2]

**Expansion Shield**

It's a perforated board on a shield, so you just plug it over your Arduino Uno. Great if you need easy access to lots of Arduino pins. Cons: little space for components. There are versions with a mini-breadboard instead of a perforated board.

[![Expansion shield][3]][3]

**PCB**

You can make your how PCB, but it's hard and too much work. Use it only for high volume production. It require lots of preparation and dangerous chemicals.

[![PCB][4]][4]

**Useful links (YouTube)**

 - [Review of some prototype circuit building methods][5]
 - [Perfboard Prototyping][6]
 - [Breadboards & Perfboards][7]

  [1]: https://i.stack.imgur.com/nu07B.jpg
  [2]: https://i.stack.imgur.com/72Jf0.jpg
  [3]: https://i.stack.imgur.com/y1BOC.jpg
  [4]: https://i.stack.imgur.com/0p2Z9.jpg
  [5]: https://youtu.be/kH110yjYZ2g
  [6]: https://youtu.be/3N3ApzmyjzE
  [7]: https://youtu.be/w0c3t0fJhXU

body:
One alternative that I like is the "breadboard-like" copper boards from [Busboard Prototype Systems](http://www.busboard.com/pcbbreadboards).  Several of their models have layouts just like solderless breadboards, but are soldered, and so more durable and stable, while leveraging your breadboard design pin-for-pin:

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

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

I love these because like many folks, I prototype earliest versions on one or more breadboards and these have the same hole layout, even down to the parallel power and ground rails down the sides.  Very convenient and available in several sizes and other configurations.

body:
> what is the easiest

for most people, breadboard is the easiest.

I sometimes do point to point (deadbug, mostly RF or small things), or onto pcb adapters (ghetto-style).

body:
![enter image description here](https://i.stack.imgur.com/Zv3Q3.jpg)
Use wire wrap for quick and easy prototyping.

body:
I have not had much luck with breadboards either. I see, on internet, that others seem to make even quite complex circuits. I can only assume it means I need to take more care to insert the components better and perhaps spend a bit more on a better quality product? I see the replies all give alternatives but no suggestions as to why Saad has problems and how to improve I would be interested to know too! At the moment, I also solder components to breadboards but it is a pain if I have to de-solder. I also use one of those childrens kits for experimenting with electronics together with a solderless bread board. It has transistors and capacitors etc and so I can connect it to IC or other particular components fitted to the [![enter image description here][1]][1]solderless breadboard. The photo is just to give an idea. I have also tried soldering small female sockets to breadboards and plug the various components into those for testing.

I have been experimenting more and reading some articles on internet. In fact, I found it better to make small jumper wires, rather than use tje ready made ones. The ready made ones tend to move and the contact is not so secure. It is nit so easy to make the small jumpers though and needs patience! I also made a small switch power supply board.. I found on "instructables" https://www.instructables.com/id/Ultimate-DIY-Breadboard-Power-Supply/#CB1TV2QJ70QKF7I
It plugs into the bread board and I can select a required voltage

  [1]: https://i.stack.imgur.com/sXOmY.jpg![enter image description here](https://i.stack.imgur.com/04gr3.jpg)![enter image description here](https://i.stack.imgur.com/LMnMn.jpg)

body:
Make a PCB with a plotter
-------------------------

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

You can create a PCB using copper foil and a cutting plotter. The complexity of the circuits will be limited to the resolution and precision that you cutter can plot at but it's a great for prototypes or full projects.

If you already have a machine, the materials are cheap and circuits can be designed using any vector based editing software. [Fritzing][2] supports the export of vector files.

> [LudwigLabs] is creating PCBs using copper foil and a cutting plotter
> (vinyl cutter). In this approach, it’s an additive process where
> instead of removing copper from a copper-clad board, the traces are
> cut out of copper foil and transferred to a solid backing surface
> (cardboard, fiberglass, etc.).

[Hackaday: Making PCBs with a cutting plotter][3]

[Cricut copper PCB][4]

  [1]: https://i.stack.imgur.com/EBcYn.png
  [2]: https://fritzing.org/
  [3]: https://hackaday.com/2018/10/28/making-pcbs-with-a-cutting-plotter/
  [4]: https://www.reddit.com/r/electronics/comments/914oa4/singlesided_copper_pcb_cut_with_a_cricut_cutting/


body:
Is there a way to determine whether a variable is of an arithmetic type or not?

 - arithmetic: integer, floating point numbers, boolean values
 - not arithmetic: pointers, references; e.g. strings, and _probably_ all other implementation- and user-defined types. However if someone for some reason defines `typedef int myInt` `myInt` should be considered arithmetic as well (because it is!)

In a normal C++ program I could use `std::is_arithmetic<T>::value`, where `T` is the type I need to check, but this doesn't seem to work in the Arduino environment. (Am I wrong? If it works, could someone please tell me how to use it?)

I imagine I could make a list of allowed types, e.g. as described in [this][1] answer to a similar question (I'm referring to the second option, the Alternative). But given that I don't need to exactly know the type of `T` I was wondering whether there is a more elegant and flexible solution...

  [1]: https://arduino.stackexchange.com/a/3080/23991

title: Determine whether a variable is of an arithmetic type

Answers: 1

body:
> Is there a way to determine whether a variable is of an arithmetic type or not?

no. end of the day, those are just bit pieces and it only makes sense to the computer with the right context. Another way to put it, the same bit pieces can and will mean different things under different situations.


body:
I'm very new to Arduino and this is my first project, so I may misunderstand something simple.

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

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

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

    #include "LedControl.h"

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

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

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

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

Some high res photos: [1][2], [2][3], [3][4]

UPD: [scheme added][5].

  [1]: http://wayoda.github.io/LedControl/
  [2]: https://i.stack.imgur.com/y2AUV.jpg
  [3]: https://i.stack.imgur.com/yBsJV.jpg
  [4]: https://i.stack.imgur.com/6zbSh.jpg
  [5]: https://i.stack.imgur.com/3Z8Dl.jpg

title: MAX7219 with Arduino UNO - LED control doesn't work

Answers: 1

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


body:
I'm using FreeRTOs on Arduino for the first time. In my setup(), i would like to create my tasks but i have few more configuration to do after so i would like to create my tasks but don't start the scheduler immediately.
This is my code currently with xTaskCreate and vTaskScheduler, but my code start the task immediately when they are created :

       //Create Tasks
       s1 = xTaskCreate(TaskAcquisition, NULL, configMINIMAL_STACK_SIZE, NULL, 2, &Acquisition);
       s2 = xTaskCreate(TaskStockage,NULL,configMINIMAL_STACK_SIZE + 200, NULL, 1, &Stockage);

    .... Some more config

       Serial.println(F("Config finished"));

      //Check errors
      if(fifoData==NULL || fifoSpace == NULL || s1 != pdPASS || s2 != pdPASS){
      Serial.println(F("Creation error"));
      while(1);
      }
      Serial.println(F("Fifo and Tasks created"));

      //starting
      vTaskStartScheduler();

      //if the scheduler start the code don't came here
      Serial.println(F("Ram issue"));
      while(1);

Thanks for your help !

title: FreeRTOS : Create Tasks but don't start Scheduler

Answers: 1

body:
You need to `vTaskSuspend` the tasks immediately after creating them.

Then when you need a task to run you `vTaskResume` it.


body:
I'm working on a project that uses an LM35 temperature sensor to control a few LEDs. Above 97 degrees, one LED should switch on. Below 95 degrees, it should switch off and the other should switch on. In between those temperatures, the LED state should remain unchanged.

When the Arduino Micro is plugged into my Macbook USB port, everything functions as I expect, however when I plug the same USB cable into a different USB power supply (like a portable cell phone charger), the LEDs tend to blink back and forth at the frequency at which I tell the Arduino to check which state the LEDs should be in.

The only thing I can think of that is different between the laptop USB and battery is the lack of serial data being read by the battery. Unclear, though how I can fix this issue. Any suggestions would be appreciated.

title: Different behavior when Arduino Micro powered by laptop USB vs portable charger USB

Answers: 0


body:
Hej..I am building a project with four NTC 10k ohm temperature sensor with Arduino. It is easy to measure only one NTC temperature sensor. There  is many examples for NTC measurement for example code written with Steinhart-Hart Equation or reading  ADC Thermistor with Lookup Table.

I found one example with Steinhart-Hart Formula.  I am not so good at coding  with Arduino but I Manage and build to write code for only one NTC sensor and read it with Nokia LCD 5110.  The question is how to do code for Multiple NTC sensors?

    /* NTC temperature mesurment 13-08-2017
     *
     *  Using Nokia LCD 5110
     */

    #include "LCD5110_Graph.h"
    LCD5110 myGLCD(8, 9, 10, 12, 11);  // Setup Nokia 5110 Screen SCLK/CLK=5, DIN/MOSI/DATA=6, DC/CS=7, RST=8 Chip Select/CE/SCE=9,
    extern uint8_t SmallFont[];
    extern uint8_t MediumNumbers[];

    int tempPin = 0;   // A0 analog input
    int Vout, charTc ;
    float R1 = 10000; //otpornost na sobnoj temperaturi 10K ili 10000 oma
    float R2, Tk, Tc;
    float Ac = 1.009249522e-03, Bc = 2.378405444e-04, Cc = 2.019202697e-07;
    char charBuffer[10];

    void setup(){
    myGLCD.InitLCD(); //initialize LCD with default contrast of 70
    myGLCD.setContrast(68);
    myGLCD.setFont(SmallFont); // Set default font size. tinyFont 4x6, smallFont 6x8, mediumNumber 12x16, bigNumbers 14x24
    myGLCD.clrScr();

    myGLCD.print("Temp test",CENTER,0);
    myGLCD.print("Check",CENTER,12);
    myGLCD.print("Please Wait",CENTER,24);

    myGLCD.update();
    delay(5000);
    myGLCD.clrScr();
    }

    void loop() {
      Vout = analogRead(tempPin);
      R2 = R1 * (1023.0 / (float)Vout - 1.0); // konvertovanje iz analogne u digitalnu
      Tk = (1.0 / (Ac + Bc*log(R2) + Cc*log(R2)*log(R2)*log(R2))); // Temperature in Klven
      Tc = Tk - 273.15; //temperature converted to celcious

    charTc=dtostrf(Tc, 3, 2, charBuffer);

      myGLCD.clrScr();
      //myGLCD.print("Discharging",CENTER,0);
      //myGLCD.print("Temperature:",CENTER,0);
      myGLCD.print("Temp1:",0,0);
      //myGLCD.print( charTc,CENTER,20 );
      myGLCD.print( charTc,36,0 );
      myGLCD.print("Temp2:",0,10);
      myGLCD.print("Temp3:",0,20);
      myGLCD.print("Temp4:",0,30);
      myGLCD.update();
      delay(2000);
      myGLCD.clrScr();
    }

title: Reading multiple NTC temperature sensors with Arduino

Answers: 5

body:
The row `int tempPin = 0; // A0 analog input` specify which analog input that should be used as input for reading the NTC value.

Then you can expand the code with the analog inputs that is needed.

body:
1. Put in multiple analog input pins and read them sequentially;

2. Put in multiple analog input pins and scan them in the adc interrupts.

the first approach is quite simple and the 2nd approach requires a thorough read of the datasheet.

body:
----------
Arduino UNO has 6 Analog pins ..

Sequentially Read ADC every 2 seconds either by calling the Respective ADC functions inside a TIMER_INTERRRUPT_VECTOR() or if high Accuracy is not Required you can restrict your main loop() to be small and write all ADCs inside it.
Also make sure that you sample your ADC if writing inside loop to make sure that its accurate.

body:
As I understand, you have multiple analog sensors you want to read. So your code should look something like this:

    // assuming sensors are on A0, A1, A2, Ax

    sensorPins [] = {A0, A1, A2};
    int sensorNum = 3;

    for(int x = 0; x < sensorNum; x++){
      readSensor(x);
    }

Something like that should work for you.

body:
This is pretty simple. Create an array of uint_8 variables that contains your pin numbers.

Then write a function that takes a pin number as an input, reads the ADC, does the math, and returns a value.

    sensorPins [] = {A0, A1, A2, A3};

    float readTemp(int tempPin) {
      int Vout = analogRead(tempPin);
      float R2 = R1 * (1023.0 / (float)Vout - 1.0); // konvertovanje iz analogne u digitalnu
      float Tk = (1.0 / (Ac + Bc*log(R2) + Cc*log(R2)*log(R2)*log(R2))); // Temperature in Kelven
      Tc = Tk - 273.15; //temperature converted to Celsius
      return Tc;
    }

Then write a loop that loops through your array of pin numbers and calls the readTemp function.


body:
I'm trying to connect to an http server that uses HTTP 1.1, my problem is that even thought the request is in HTTP 1.1 format and the server does actually use HTTP 1.1(I tried it in a browser) it only responds with HTTP 1.0. I'm using this modified example of the web client, I updated the Ethernet library yesterday and for my server I'm using Node 8.4.0, I'm testing with google first even though I know the server can respond with HTTP 1.1.

Ethernet shield model: Han Run HR911105A 16/02

Arduino: Mega 2560

     This sketch connects to a website (http://www.google.com)
     using an Arduino Wiznet Ethernet shield.

     Circuit:
     * Ethernet shield attached to pins 10, 11, 12, 13

     created 18 Dec 2009
     by David A. Mellis
     modified 9 Apr 2012
     by Tom Igoe, based on work by Adrian McEwen

     */

    #include <SPI.h>
    #include <Ethernet.h>

    // Enter a MAC address for your controller below.
    // Newer Ethernet shields have a MAC address printed on a sticker on the shield
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    // if you don't want to use DNS (and reduce your sketch size)
    // use the numeric IP instead of the name for the server:
    //IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
    char server[] = "www.google.com";    // name address for Google (using DNS)

    // Set the static IP address to use if the DHCP fails to assign
    IPAddress ip(192, 168, 0, 177);

    // Initialize the Ethernet client library
    // with the IP address and port of the server
    // that you want to connect to (port 80 is default for HTTP):
    EthernetClient client;

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

      // start the Ethernet connection:
      if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
        // try to congifure using IP address instead of DHCP:
        Ethernet.begin(mac, ip);
      }
      // give the Ethernet shield a second to initialize:
      delay(1000);
      Serial.println("connecting...");

      // if you get a connection, report back via serial:
      if (client.connect(server, 80)) {
        Serial.println("connected");
        // Make a HTTP request:
      client.print("GET / HTTP/1.1\r\n");
      client.print("Host: www.google.com\r\n");
      client.print("Content-Type: application/x-www-form-urlencoded\r\n");
      client.print("Cache-Control: no-cache\r\n");
      client.print("\r\n");
      } else {
        // if you didn't get a connection to the server:
        Serial.println("connection failed");
      }
    }

    void loop() {
      // if there are incoming bytes available
      // from the server, read them and print them:
      while (client.available()) {
        char c = client.read();
        Serial.print(c);
      }

      // if the server's disconnected, stop the client:
      if (!client.connected()) {
        Serial.println();
        Serial.println("disconnecting.");
        client.stop();
      }
    }

With this I get the following response:
[![enter image description here][1]][1]

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

Thank you in advance

title: Arduino only sends HTTP 1.0 requests

Answers: 1

body:
The device sending the request has no bearing on if it is HTTP 1.0 or 1.1. Only the content has an effect.

That and what is in the path - and I suspect that may be your problem: your are going through a squid proxy - and an old version at that. It is most likely that the proxy is changing the request to be a 1.0 request instead of a 1.1 request.


body:
How can i know the angle of the vertical window blind by placing a small sensor on one of the blind slat

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

Tried so far:

 1. open and close based on time which it takes to open and close, but it keeps drifting over time

 2.  Cannot use light sensor to sense the ambient light, does not give correct information (day and night)

 3. Tried to put a potentiometer on top of one of the blind slat ( no enough room to place things there, potentiometers have more friction)

any suggestions for angle sensor ?

title: How to get the angle from vertical window blinds

Answers: 2

body:
> How to get the angle from vertical window blinds

vertical blinds have by definition a 90degree angle.

unless "angle" means something else to you.

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

Edit:
I had imagined something like:

[![Hall Effect Sensor placement on blind slat][1]][1]

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

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

Edit 2:

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

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


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

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

title: Can I set pin 13 to output 5v, then put arduino mini pro to sleep?

Answers: 2

body:
Given the absence of clarity on the driving state of pins during sleep, consider connecting Pin 13 to an [SR Latch][1] or the gate of a MOSFET.

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

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

  [1]: https://www.allaboutcircuits.com/textbook/digital/chpt-10/s-r-latch/

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

yes.


body:
i want to operate a relay with an ARDUINO UNO, but i want to use a separate power supply for the relay. Ive seen relays with VCC and jVCC (dont know what that is), but mine only has this pins: GND, IN1, IN2, VCC.
how should i connect it to the Arduino and the external power supply?
[![enter image description here][1]][1]

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

title: Arduino Uno - relay with separate power

Answers: 3

body: External psu to gnd and vcc, in1 and in2 to arduino pins which control each relay (on is LOW) and most importantly gnd also to arduino gnd.

body:
The Arduino and the external PSU should have the GND or - connected with each other.

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

body:
This relay is designed to operate on 5V.

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

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

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

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

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

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

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

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

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

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


body:
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?

title: Debouncing, or problem with my code?

Answers: 4

body:
Yes, it is bouncing of your button.

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

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

body:
your code works as coded - whether it works as expected is unknown.

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

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

not an effective debouncing strategy.

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

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

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");
            }
          }
        }


body:
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

title: Sim808: Is My GPS Module Broken?

Answers: 1

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.


body:
I am using an Arduino Mega connected with a motion sensor and **HC05 bluetooth chip** to transmit distance data to a larger computer, process it, and send a data back. Currently, **I am having trouble receiving/reading bluetooth output received from the program running on my PC** which is successfully receiving data from the HC05 chip. I am using the Serial Software library to process serial input/output to the Arduino Mega. Having probed the output of the HC05 chip that serves as return stream of decision data to the Mega, I see that the magnitude of the waveform is around 3V. **My guess is that for the Arduino and Software Serial library to process this input, it must be at 5 volts**, just like the output, for which I had to build a voltage divider so that I could provided the specified 3.3 V to the HC05 input. Clearly if the output at TXD from the HC05 is 3.3V then the Mega will receive 3.3 volts at PIN4, the receiving pin.

Here is a basic diagram without the sensors or motors. Exact resistances are not provided but should not affect the issue.
[![enter image description here][1]][1]

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

I have provided the code below for Arduino-side operation.

    /*
     This module uses the L293D chip to modulate and power
     two DC motors controlling the wheels of the FryeBot
    */

    #include <SoftwareSerial\SoftwareSerial.h>

    SoftwareSerial mySerial(4, 2); // RX, TX

    /*L293D INPUT 7*/
    const int YELLOW_GEAR_MOTOR_BACK = 8;

    /*L293D INPUT 2*/
    const int YELLOW_GEAR_MOTOR_FORWARD = 9;

    /*L293D INPUT 10*/
    const int RED_GEAR_MOTOR_BACK = 10;

    /*L293D INPUT 15*/
    const int RED_GEAR_MOTOR_FORWARD = 11;

    /*
     Establish ratio os the rate of the faster slower gear
     to the faster gear to scale the duty cycle of the
     faster gear
    */
    const float RED_GEAR_SPEED_TO_YELLOW = 0.97;

    /*Constant for full duty cycle for analogWrite*/
    const int FULL_ANALOG_MOTOR_SPEED = 255;

    const int pingPin = 7;

    long duration, cm;

    char buf[10];

    char current;
    String messageHolder;
    String message;

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

     /* add setup code here */
     pinMode(YELLOW_GEAR_MOTOR_FORWARD, OUTPUT);
     pinMode(YELLOW_GEAR_MOTOR_BACK, OUTPUT);
     pinMode(RED_GEAR_MOTOR_BACK, OUTPUT);
     pinMode(RED_GEAR_MOTOR_FORWARD, OUTPUT);

    }

    void loop() {

     pinMode(pingPin, OUTPUT);
     digitalWrite(pingPin, LOW);
     delayMicroseconds(2);
     digitalWrite(pingPin, HIGH);
     delayMicroseconds(5);
     digitalWrite(pingPin, LOW);

     pinMode(pingPin, INPUT);
     duration = pulseIn(pingPin, HIGH);

     cm = microsecondsToCentimeters(duration);

     Serial.print(cm);
     Serial.print("cm");
     Serial.println();

     /* Load the distance value into a buffer */
     String sendValue = String(cm);
     sendValue.toCharArray(buf, sizeof(buf));

     /* Write the buffer with a space after for parsing*/
     mySerial.write(buf);
     mySerial.write(' ');

     /* Stop if too close to an object */
     //Serial.print("current: ");
     //Serial.print((int)current);
     Serial.println();

     if (message != "STOP_MOTORS") {

      analogWrite(YELLOW_GEAR_MOTOR_FORWARD, (int)(RED_GEAR_SPEED_TO_YELLOW * (float)FULL_ANALOG_MOTOR_SPEED));
      digitalWrite(YELLOW_GEAR_MOTOR_BACK, LOW);

      digitalWrite(RED_GEAR_MOTOR_BACK, LOW);
      digitalWrite(RED_GEAR_MOTOR_FORWARD, HIGH);
     }
     else {
      digitalWrite(YELLOW_GEAR_MOTOR_FORWARD, 0);
      digitalWrite(YELLOW_GEAR_MOTOR_BACK, LOW);

      digitalWrite(RED_GEAR_MOTOR_BACK, LOW);
      digitalWrite(RED_GEAR_MOTOR_FORWARD, LOW);
     }

     current = mySerial.read();
     Serial.print((int)current);
     Serial.println();

     if (current == ' ') {
      message = messageHolder;
      messageHolder = "";
     }
     else {
      messageHolder += current;
     }

     delay(100);

    }

    long microsecondsToCentimeters(long microseconds) {
     // The speed of sound is 340 m/s or 29 microseconds per centimeter.
     // The ping travels out and back, so to find the distance of the
     // object we take half of the distance travelled.
     return microseconds / 29 / 2;
    }

title: Reading HC05 Output

Answers: 0


body:
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?

title: Using ESP8266-01 with Arduino uno R3

Answers: 3

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");
}

...
```


body: 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?

title: Connecting multiple boards to Arduino Uno r3

Answers: 1

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


body:
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

title: DHT11 returning incorrect values

Answers: 2

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.


body:
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!

title: Best way to store files on Arduino

Answers: 3

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


body:
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

title: Disabling Timer2

Answers: 3

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.


body:
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.

title: Dshot implementation on Arduino (ESC protocol)

Answers: 2

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


body:
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));
      }
    }

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

Answers: 1

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.


body:
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

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

Answers: 5

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


body:
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).

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

Answers: 2

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
    }


body:
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);
      }
    }

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

Answers: 3

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.


body:
I am working with an Arduino Uno, and have recently been given an assignment to use the servo motor.
The requirements are that I tune the pulse widths while comparing the 0 and 180 degrees. Secondly I must put in a protective clause to prevent it from going past the values. Any help at all is greatly appreciated. Thank you.
(Using the `servo.attach(pin, minpulse, maxpulse)` method, and `writeMicroseconds()` command.)

1. You may want to put in protective clauses in your code to prevent accidental driving of the servo beyond its intended range.
2. Write a simple program to tune up your servo’s min and max pulsewidths corresponding to 0° and 180°. Start by using 900 and 2100 in the `attach()` command, and perhaps sending the motor to 0°, 90°, and 180° delaying a couple seconds between moves for you to assess the quality of alignment.

My only ideas have been to manually fine tune it by checking when it does not turn any more.

title: How to tune up a servo and add protective clauses?

Answers: 0


body:
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?

title: Uploading Arduino bootloader to ATmega32U4 with another Arduino?

Answers: 1

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.


body:
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.`

title: Standalone 328p Programming with CH340G programmer

Answers: 2

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/)


body:
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

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

Answers: 3

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 have a number of questions:

use a transistor to turn on / off each leds. size the transistor based on the leds' voltage / current requirement.

make sure that your arduino has sufficient number of pins for the sensors + leds. if not, you can split the tasks among multiple arduinos.

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


body:
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)

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

Answers: 4

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.


body:
Serial Monitor get's flooded with "No Socket Available" message.  This seems to occur even before I Try to communicate with my Hue bridge through my hub port.  Does anyone see why this is occurring after my wireless connection is established?

Serial Output:

    Firmware needs upgrade
    Attempting to connect to WPA SSID: ifiw_ym
    connected to the networkSSID: ifiw_ym
    BSSID: 0:B2:8F:6A:C4:28
    signal strength (RSSI):-47
    Encryption Type:4

    IP Address: 192.168.1.7
    192.168.1.7
    MAC address: 78:C4:E:1:9F:B1
    in loopin loopin loopNo Socket available
    No Socket available
    in loopNo Socket available
    No Socket available
    in loopNo Socket available
    No Socket available
    in loopNo Socket available
    No Socket available
    ...

code:

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

    //  Hue constants
    const char hueHubIP[] = "192.168.1.6";
    const char hueUsername[] = "my_hue_app";
    const int hueHubPort = 80;

    boolean activated = false;

    //  Hue variables
    boolean hueOn;
    int hueBri;  // brightness value
    long hueHue;  // hue value
    String hueCmd;  // Hue command

    unsigned long buffer=0;  //buffer for received data storage
    unsigned long addr;

    // Wireless network
    char ssid[] = "**********";
    char pass[] = "**********";
    int status = WL_IDLE_STATUS;
    WiFiClient client;

    //0:B2:8F:6A:C4:28

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

      if (WiFi.status() == WL_NO_SHIELD) {
        Serial.println("WiFi shield not present");
        while (true);
      }

      String fv = WiFi.firmwareVersion();
      if (fv != "1.1.0") {
        Serial.println("Firmware needs upgrade");
      }

      while (status != WL_CONNECTED) {
        Serial.print("Attempting to connect to WPA SSID: ");
        Serial.println(ssid);
        status = WiFi.begin(ssid, pass);

        // wait 10 seconds for connection:
        delay(10000);
      }

      Serial.print("connected to the network");
      printCurrentNet();
      printWifiData();
    }

    void loop() {
      Serial.print("in loop");
      // printCurrentNet();
      alterHueColors();
    }

    void alterHueColors() {
      if(activated){
        client.println("Hue is activated");

         // A series of four sample commands, which colour fades two lights between red and pink. Read up on the Hue API
        // documentation for more details on the exact commands to be used, but note that quote marks must be escaped.
        String command = "{\"on\": true,\"hue\": 50100,\"sat\":255,\"bri\":255,\"transitiontime\":"+String(random(15,25))+"}";
        setHue(3,command);
        command = "{\"on\": true,\"hue\": 65280,\"sat\":255,\"bri\":255,\"transitiontime\":"+String(random(15,25))+"}";
        setHue(4,command);
        command = "{\"hue\": 65280,\"sat\":255,\"bri\":255,\"transitiontime\":"+String(random(15,25))+"}";
        setHue(3,command);
        command = "{\"hue\": 50100,\"sat\":255,\"bri\":255,\"transitiontime\":"+String(random(15,25))+"}";
        setHue(4,command);

        activated = true;
      }
      else{
          activated = false;
          client.println("deactivated");

          //was activated, so send a single off command
          String command = "{\"on\": false}";
          setHue(3,command);
          setHue(4,command);
      }
    }

It's also interesting to not that my print calls in alterHueColors()  aren't triggering.

[Full .ino file][2]

  [2]:https://github.com/EbenezerGH/hue_arduino_communication/blob/master/basic_hue_communication/basic_hue_communication.ino

title: No Socket Available message floods serial monitor

Answers: 0