body:
The relevant tech specs for a MKR Zero are:
  32.768 kHz (RTC*), 48 MHz

*Real-Time Clock

What I'm curious about is how I might do an approximate calculation of cycles per second from operations.

I'm running the following (extremely simplified) code :

    int pin3 = 3;
    void setup() {
      //set digital pin pin3 as output

      pinMode(pin3,OUTPUT);
    }

    void loop(){
      digitalWrite(pin3,HIGH);//set pin pin3 to +5V
      delay(100);//wait 100ms
      digitalWrite(pin3,LOW);//set pin pin3 to 0V
      delay(100);//wait 100ms
    }

Now I'm curious how many cycles per second (approximately) that might account for.

**The Equation?**

What would the equation be to calculate that?

**Not Processor Op Codes**

Is this even possible to approximate?  I understand it will be difficult because those lines of code do not equal the actual op codes and don't exactly break down to specific cpu cycles or whatever.

Would it be something like:

    48,000,000 (48MHz) / 200 (millisecond pause) = 240KHz?

Or would I use the real-time clock speed?

    32768 / 200 = @163Hz

Or something completely different?
I'm trying to better understand how I might create a very simple frequency generator and I know that depending upon the chip speed the code will vary.

title: How can I calculate approximate cycles per second from pulsed pin on Arduino MKR Zero?

Answers: 2

body: It is unclear exactly what you are trying to do, however the frequency generated by the code would be ~5Hz - corresponding to a period of 200mS

body:
The dependency on the clock speed is hidden in the implementation of the delay() function. It works with 'human readable' milliseconds.

Hertz is count of repeating in one second. One second has 1000 ms. So with 200 ms delay, 5 repeating happen in a second. Then the frequency is 5 Hz.


body:
I have corrected my code for reading the optical encoder index but I am now getting a different calculation error.  At the index the encoder reset's to zero but now my readouts are as follows:
Index point - resets to zero.
- At the 90 degree rotation mark I have a readout of 180 degrees.
- At the 180 degree rotation mark I have a readout of 0 because the code has it reset to zero after 359 degrees.
- At the 270 degree rotation mark I have a readout of 180 degrees.
- At the 0 degree mark it is zero again and that's what I would expect from the index.  If I restart the Arduino Mega at the 270 degree mark, the index resets itself to zero like it should.  Being new to this, before I had the index working it was working correctly minus the index function, now it seems to be double counting.  Any ideas?

    // Wiring connections for my encoder:
    // Brown : VCC = 5V
    // Blue + Shield : 0V = GND
    // Black : ENCODER0PINA, Pin 20
    // White : ENCODER0PINB, Pin 17
    // Orange : ENCODER0PINI, Pin 19

    #define ENCODER0PINA         20      // this pin needs to support interrupts
    #define ENCODER0PINB         17      // no interrupt required
    #define ENCODER0PINI         19      // this pin needs to support interrupts

    // variables modified by interrupt handler must be declared as volatile
    volatile long encoder0Position = 0;
    volatile long interruptsReceived = 0;
    volatile byte INTFLAG1 = 0;

    // track last position so we know whether it's worth printing new output
    long previousPosition = 0;

    void setup()
    {

      // inputs
      pinMode(ENCODER0PINA, INPUT);
      digitalWrite(ENCODER0PINA, HIGH);  // turn on pullup resistor
      pinMode(ENCODER0PINB, INPUT);
      digitalWrite(ENCODER0PINB, HIGH);  // turn on pullup resistor
      pinMode(ENCODER0PINI, INPUT);
      digitalWrite(ENCODER0PINI, HIGH);  // turn on pullup resistor

      // interrupts
      attachInterrupt(3, onInterrupt, CHANGE);  // encoder track A on interrupt 3 - pin 20
      attachInterrupt(4, onReset, CHANGE);  // encoder Index track on interrupt 4 - pin 19

      // enable diagnostic output
      Serial.begin (115200);
      Serial.println("Ready.");
    }

    void loop()
    {
      // only display position info if has changed
      if (encoder0Position != previousPosition )
      {
        Serial.println(encoder0Position, DEC);

        previousPosition = encoder0Position;
      }
    }

    // interrupt function needs to do as little as possible

    void onReset()
    {
      // read Index input
      int i = digitalRead(ENCODER0PINI);
      if (i == 1)
      {
      encoder0Position = INTFLAG1;
      }
    }

    void onInterrupt()
    {
      // read both directional inputs
      int a = digitalRead(ENCODER0PINA);
      int b = digitalRead(ENCODER0PINB);

      if (a == b)
      {
        // b is leading a (counter-clockwise)
        encoder0Position--;
        if (encoder0Position < 0)
        {
          encoder0Position = (encoder0Position + 360);
        }
      }
      else
      {
        // a is leading b (clockwise)
        encoder0Position++;
        if (encoder0Position >= 360)
        {
          encoder0Position = (encoder0Position - 360);
        }
      }
    }

title: Calculation error with Optical Encoder

Answers: 1

body: I have figured out my issue, at least I am getting good results. With this code I had to change interrupts from CHANGE to RISING. I want to thank everyone that has made comments on this question. –


body:
I have a Nano+ENC28J60 and I'm using Pushingbox which I have setup to write data to a GoogleDrive spreadsheet which works *perfectly* at home. However when I take it to my workplace it no longer works.

At work, serial tells me that the

 - Ethernet connection is good;
 - I get a client connection OK too.

*However*, [edit] even with 5 attempts at a response client.read(); it reports nothing at all. Serial shows

    OK connected! Written. Checking response: + + + + +

I assume it is to do with some firewall or other restriction, but if I can get a connection that should be enough, no?

[edit] note: i have also tried connecting to port 443 instead of port 80 in case it was an HTTPS issue - same results, though]

**How I can write to GDrive on my work network?**

The code [edit#2 modified client.connect() to try 5 times and a response check via client.read() to try 5 times and Serial.print("+ "); each time] :

    #include "DHTesp.h"
    #include <SPI.h>
    #include <UIPEthernet.h>

    DHTesp dhtA; DHTesp dhtB;

    const int ledPin =  LED_BUILTIN;
    int ledState = LOW;
    int interval = 20; // this is the num seconds between reads (120=2mins) ***************************
    int numReads = 2;   // Amount of reads between posting to Gdocs.  ***************************

    byte mac[] = {0xAA, 0xF0, 0xDE, 0xDE, 0x06, 0xAF };  // Ethernet shield MAC addy
    byte ip[] = { 10, 10, xx, yy };
    char devid [] = "vXXXXXXXXXXXXXXXX";  //  device ID from Pushingbox

    char server[] = "http://api.pushingbox.com";
    EthernetClient client;

    int c = '\0';

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

      Serial.print(F("dB_CoSdataV3.  Establishing..."));
      if (Ethernet.begin(mac) == 0) {
        Serial.println(F("Failed to configure ethernet"));

        //while (true); // no point in carrying on, so do nothing forevermore
      }
      else {
        Serial.println(F("Ethernet OK."));
        // print the Ethernet board/shield's IP address:
        Serial.print(F("local IP addy: "));
        Serial.println(Ethernet.localIP());
      }

      // give the Ethernet shield a second to initialize:
      delay(3000);

      Serial.println("____________________________________________");  Serial.println();

      dhtA.setup(3); //  sensor A
      dhtB.setup(4); //  sensor B
      //dhtC.setup(7); dhtD.setup(7);

      pinMode(ledPin, OUTPUT);

    }

    void loop(){

      int Ahumidity = 0;   int Atemperature = 0 ;
      int Bhumidity = 0;   int Btemperature = 0;

      int j = 0;
      for (j = 1; j <= numReads ; j++ ) {
        int p = 0;
        for (p = 1; p <= interval ; p++) {
          delay (1000);
          // if the LED is off turn it on and vice-versa:
          if (ledState == LOW) {        ledState = HIGH;       }
          else {        ledState = LOW;      }
          Serial.print (F("."));
          digitalWrite(ledPin, ledState);
        }

        Serial.print (" reading: ");
        Ahumidity += 10 * dhtA.getHumidity();  Atemperature += 10 * dhtA.getTemperature();
        Bhumidity += 10 * dhtB.getHumidity();  Btemperature += 10 * dhtB.getTemperature();

        Serial.print (j);     Serial.print (F("/"));     Serial.print (numReads);
        Serial.println();
      }

      Serial.print (F("Show the averaged val.s : "));
      Serial.print(F("\t\tA:")); Serial.print(Atemperature/(numReads)); Serial.print(F("\t")); Serial.print(Ahumidity/(numReads));
      Serial.print  (F("\tB:")); Serial.print(Btemperature/(numReads)); Serial.print(F("\t")); Serial.print(Bhumidity/(numReads));

      // now connect + write to Gdrive....................
      boolean connected;
      int counter1 = 0;
      do {
          connected = client.connect(server, 80);
          if (connected) { break; }
          client.stop();
          delay(1000);
          Serial.println("retry");
          counter1++;
      } while (!connected && counter1 <5);

    //------------------
    //if (client.connect(server, 80)) {

    if (connected){
        Serial.println();
        Serial.print(F("OK connected! "));

          String buf;

          buf += F("GET /pushingbox?devid=");
          buf += String(devid);

          buf += F("&tempA=");  buf += String(Atemperature/numReads);
          buf += F("&tempB=");  buf += String(Btemperature/numReads);
          buf += F("&tempC=0&tempD=0&tempE=0&tempF=0&tempG=0&tempH=0"); // null data needed

          buf += F("&humidA=");  buf += String (Ahumidity/numReads);
          buf += F("&humidB=");  buf += String (Bhumidity/numReads);
          buf += F("&humidC=0&humidD=0&humidE=0&humidF=0&humidG=0&humidH=0"); //null data needed

          buf += F("&submit=Submit");
          buf += F(" HTTP/1.1");
          //client.println(F("Host: api.pushingbox.com"));
          buf += F("Host: http://api.pushingbox.com"); // trying the addition of http://...
          buf += F("Connection: close\r\n");
          //client.println();

          client.print(buf);
          Serial.print(F(" Written. "));
          delay(1000);
          int counter2 = 0;
          Serial.print ("Checking response: ");

          do {
              if (client.available()) {
                  Serial.print("Y ");
                  c = client.read();
                  Serial.print((char)c);
              }
              delay(2000);
              Serial.print("+ ");
              counter2++;
          } while (counter2 < 5);

          Serial.println ();       Serial.println ();
          //client.stop();
      }

    }

title: Nano & Ethernet will not write to PushingBox on a workplace network (but will at home)

Answers: 1

body:
Your code for HTTP request has multiple issues.

After you connect to an HTTP server, it doesn't send anything until it receives your request. Your check for available bytes should always fail. Remove the `if (client.available())` part, including the `else` part.

You make a POST request, but you put all parameters to URL and the request has no body. Change it to GET or put the parameters into request body and use "Content-type: application/x-www-form-urlencoded". Don't forget the Content-length parameter.

You send the request in very small parts. Every single print is send right away over network. Concatenate strings and print one or use buffered print.

And you should read the HTTP response and check the status.


body: I am making an air purifier which also increases o2 level as a school project but facing some difficulties. I plan to run the purifier whenever the co2 level is higher than usual or o2 level is lesser than usual but the sensor available in the market are quite expensive. So is there any cheaper alternative or any other method to detect a change in concentration?

title: What is a cheap way to measure co2 or o2 level in air?

Answers: 1

body:
Well, MQ 135 sensor is very cheap general air quality measurement device. It costs around 3$. There is another similar on AliExpress, not even worth mentioning. What is your budget? Gravity from Adafruit seems proper, yet it is at 56$. One that seems actually serious is K30 sensor, but that is around 100$. That 3$ stuff is general, and will work when temperature is constant, humidity is constant and Mars is aligned with Venus.

I think 56$ is ok if they want to have something proper. Remember that you get what you pay for.


body:
I would like to `Serial.print();` the multiplication tables, 1 - 10. This is my work so far. Is there an easier way to do this with array? Thanks

    // "MultiTable"

    //Define global array, is this needed? Makes no difference for my output in serial monitor.
    //int number[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    //Define variable
    int prod;

    void setup() {
      // Open serial connection at 9600Bd
      Serial.begin(9600);
    }

    void loop() {
      //Print the times table for 1

      for(int i = 0; i <=9; i=i+1) {
       prod = i*1+1;
       Serial.print(prod);
       Serial.print(",  ");
      }

      Serial.println();
      delay(3000);
      Serial.println();

    //Print the times table for 2

      for(int i = 0; i <= 9; i=i+1) {
      prod = i*2+2;
       Serial.print(prod);
       Serial.print(",  ");
      }

      Serial.println();
      delay(3000);
      Serial.println();

    //Print the times table for 3

      for(int i = 0; i <= 9; i=i+1) {
      prod = i*3+3;
       Serial.print(prod);
       Serial.print(",  ");
      }

      Serial.println();
      delay(3000);
      Serial.println();
    }

title: Print out times tables from 1 to 10 with array

Answers: 1

body:
    //Define global array, is this needed? Makes no difference for my output in serial monitor.
    //int number[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

This is not needed, you can use a for lop from 1 to 10.

The void loop will look like this (not checked, no IDE nearby):

    void loop()
    {
      for (int multiplier = 1; multiplier <= 3; multiplier++)
      {
          for(int i = 0; i <= 9; i++)
          {
             prod = i * multiplier + multiplier;
             // or: prod = (i + 1) * multiplier;
             Serial.print(prod);
             Serial.print(",  ");
          }

          Serial.println();
          Serial.println();
          delay(3000);
      }
    }

Some remarks:

- To go to the main for loop (with multiplier):
  - Identify the similar parts
  - Check the differences within each similar part (only the multiplier value, 1, 2 or 3)
  - Make this a for loop and instead of 1, 2, 3 use the multiplier variable
  - Instead if i = i + 1 you can use i++. It means exactly the same.
  - For clearity I put the Serial.println() together. You also can use Serial.print('\r\n\r\n') or Serial.println('\r\n') to achieve the same


body:
I am building a positioner and I store the current position to EEPROM _when the move is complete_. On start up, I want the positioner to return to the HOME position. I am running an UNO powered from the USB.
My problem is that if the Arduino is turned off, I would like to stop the move and store the current position before the Arduino dies.

Note that this would also be relevant to devices like thermostats which remember the set point through a power outage.

**POSSIBLE SOLUTIONS**

1. Store position in EEPROM at each step. No, that will wear out the EEPROM.

2. Connect a large capacitor from +5V to Gnd. When this falls below a set level, trigger an interrupt (ISR) that stops motion and stores current position in EEPROM.

**QUESTIONS**

1. Will #2 work, and how could I program it?
2. Any other ideas I am missing?

title: Save Data before Shutdown

Answers: 2

body:
Thermostats would save the set point to eeprom once when the set point it set by the user. On startup it would just read the set point.

The analogue pins measure relative to VCC. So if you short the analogue pint to VCC the result will remain at max even as the voltage drops.

Instead use a diode to separate the measurement point from the power supply.

<!-- 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/pY6tm.png)

<!-- End schematic -->

As long as power is supplied the gpio input will be high. As soon as the power is removed the gpio pin will be low and the capacitor will need hold enough charge to save the position.

However what would happen if the positioner is manipulated when the arduino is off? Most devices have a callibration routine using end-of-travel detection or something similar they run on startup to find the home position.

body:
Thanks for all the suggestions. At first I wanted a circuit like @ratchet freaks. I wanted to keep the mechanics and circuits very simple since the positioner is 3D printed and uses a standard M3 screw to move, so that rules out limit switches and encoders.
I also realized the typical move only takes a max of 10 seconds, so I could just store the commanded position like @CrossRoads suggested. When the `HOME` command is given it steps back to 0.

Here is my Answer:

 1. Store the EEPROM address of the persistent information at `EEPROM[0]`.
 2. At that Address store the persistent information:
 3. Item 1: `EEPROM[EEPROM[0]]` The number of writes to this address block as a two byte unsigned int.
 4. Item 2: `EEPROM[EEPROM[0]+2]` The commanded position as a two byte signed int.
 5. When the number of writes gets to about 5000, increment the address of the data in `EEPROM[0]`.

Working this way I'll gradually burn out the Arduino EEPROM, but it will take many years!


body: I am trying to use an Uno to detect if an LED is on or not. Sounds simple, but I am tearing my hair out on this one, here is why.... This is a model railway application and I want to detect an LED being lit on the control panel showing how a route (points/turnouts) is set. The LED is lit by a point position indicator (www.blocksignalling.co.uk/index.php/points-position-indicator-ppi4-dc) which works perfectly but the LEDs are not permanently on when lit, even though they appear so, they are pulsed at around 8khz. I tried using opto isolators triggering an digital input on the Uno. They all happily detect 'no light' and the pin goes HIGH, but when the led is lit, the pin flucuates between 0 and 1 so not a true or stable LOW. I also made my own opto using a TCRT5000 with the leds pointing at eachother encased in shrinkwrap, using standard breadboard set-up which worked perfectly when powering the transmitter from the Uno, but same result when powered from the LED. Anyone out there got any ideas please?

title: Detecting pulsed LED

Answers: 3

body: Why not connect a low pass filter to the LED, and measure the DC level coming out? Will certainly be higher when on than when off.  Resistor from anode to analog input pin, and capacitor to Gnd.

body: Count HIGH values read for example in 2 ms. It should be zero if the LED is not lit and more then zero if it is lit.

body:
Use a photoresistor (also called LDR).

Connect the photoresistor between Vcc and an analog input and place it physically next to the LED you want to monitor.

In your arduino code simply monitox the analog input value. When the LED will be on the photoresistor will have a lower resistance andyou will read a higher analog voltage.


body:
I have an Arduino Mega 2560 that I would like to connect to the internet using an ESP8266-12E.

Searching the internet for relevant keyphrases only yielded one type of result: The articles all explain how to **program** the ESP using the Arduino. Been there, done that.

Does anybody know of a way to use the ESP as a "wifi interface" for an Arduino, e.g. using a Serial interface from the Arduino?

Basically, I'd want to use the library ESP8266Wifi transparently on my Mega 2560, and maybe in conjunction with something like [WifiManager][1] - all of that running on the Mega.

The only thing I found was this: https://www.hackster.io/jeffpar0721/add-wifi-to-arduino-uno-663b9e. But this uses AT commands only.

Any hint is appreciated.

  [1]: https://github.com/tzapu/WiFiManager "WiFiManager"

title: ESP8266-12E as WiFi interface for Arduino Mega

Answers: 2

body:
ESP8266-01 usually come pre-programmed with the "AT" instructions interpreter for WiFi communication. If your -12 didn't, or if you've reprogrammed it, you'll need to find and download a copy of the AT interpreter to re-load.

Then you'll cross-connect one of the Mega's UARTs to the ESP (Tx > Rx and Rx > Tx), respecting the voltage level differences between the Mega and the ESP (5v vs. 3.3v). You'll need use a level-shifter or make a voltage divider for at least the Mega Tx > ESP Rx connection.

Then it's just a matter of using an existing Arduino ESP-WiFi library, or writing your own serial communications using the ESP's AT commands if you want the challenge.

I generally use the [Blynk][1] Internet of Things service and libraries as the quickest and a full-featured way to put a device online with access to/by your cellphone. It's not the only way but it's a good start.

  [1]: https://www.blynk.cc/

body:
If you know how to write code for the esp8266, then write the networking part in the esp8266 and exchange data and commands with the sketch in Mega over Serial.

Other option is to use AT firmware with the WiFiEsp library or WiFiLink firmware with WiFiLink library.

Or you can connect the ESP-12 to Mega over SPI and use the [WiFiSpiESP firmware][1] with WiFiEsp library.

All mentioned libraries are 'clones' of the WiFi library.

  [1]: https://github.com/JiriBilek/WiFiSpiESP


body:
I know I should post some code that maybe cleaner but really I am just in need of a answer to a problem I seem to run into a lot when using `mills()` in place of `delay()`, whilst making a Christmas light display.

Maybe it's me but I do not get contestant switching over of mechanical relays when I try to use `mills()` timing to switch relays . I seems like the code trips the relay then untrips the relay in milliseconds and not really latching the relay like I get with `delay()`. Is this the nature of the `mills()` choice where the output is triggered every cycle  but is not truly an output during the whole process cycle?  Now if this is true, then is there a good way to latch a relay with out using a `delay()`?

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>
    //

      unsigned long currentMillis = millis();
      unsigned long previousMillis = millis();
      int interval_on = 2000; //  Length of time On

      unsigned long currentMillis_off = millis();
      unsigned long previousMillis_off ;
      int interval_off = 2000; // length of time off

    //
    #define button 4
    int Lite_1=0;

    RF24 radio(7, 8); // CE, CSN

    const byte address[6] = "00001";
    boolean buttonState = 0;

    unsigned long time;

    void setup() {
      radio.begin();
      radio.openWritingPipe(address);
      radio.setPALevel(RF24_PA_MIN);
      radio.stopListening();
      Serial.begin(9600);
    }

    void loop() {
      unsigned long currentMillis = millis();        // must be in loop
       unsigned long currentMillis_off = millis();  // Must be in loop
      //                             const char text[] = "Hello World";
     //                       radio.write(&text, sizeof(text));
      //delay(1000);

       //                       delay(5); Removed to help in timing
       //                       radio.stopListening(); removeded to help in timing
       // Lite_1 = 1;
        radio.write(&Lite_1, sizeof(Lite_1));
      //    delay(1000);
     //   Lite_1 = 0 ;
     // radio.write(&Lite_1, sizeof(Lite_1));
      // delay(250);

      if (Lite_1 == 0 && currentMillis - previousMillis > interval_off)
        {
        previousMillis = currentMillis;
        previousMillis + 10;
        previousMillis_off = currentMillis_off  ;
        Lite_1 = 1;
        Serial.println(currentMillis);    //prints time since program started
          }
        //Debug
      // Serial.print("Time: ");
     // time = millis();

     // Serial.println(time);    //prints time since program started
    //  Serial.println(currentMillis);    //prints time since program started
    //  Serial.println(previousMillis);    //prints time since program started
    //  Serial.println(previousMillis_off);    //prints time since program started
     // Serial.println(currentMillis_off);    //prints time since program started
      //delay(250);

        if (Lite_1==1 && currentMillis_off - previousMillis_off > interval_on)
           {
        previousMillis_off = currentMillis_off;
        previousMillis = currentMillis;
        previousMillis + 10;
        Lite_1 = 0;
        Serial.print("OFF: ");
        Serial.println(previousMillis_off);    //prints time since program started
        }

      }

title: Using mills() in place of delay() on relays not getting solid switch over

Answers: 1

body:
Something like this works.

   unsigned long currentMillis;
   unsigned long previousMillis;
   unsigned long nextEventTime;

   unsigned long interval_on  = 2000;        // length of time On
   unsigned long interval_off = 2000;        // length of time off

   bool Lite_1;

   void setup() {

  previousMillis = millis();

  Lite_1 = false;                                     // start at the begining of the off cycle
  nextEventTime = previousMillis + interval_off;      // start at the begining of the off cycle

  Serial.begin(9600);
  Serial.print("starting in OFF cycle\t");
  Serial.println(previousMillis);
   }

   void loop() {

  if (millis() > nextEventTime) {                     // check the interval before doing any other checks

  currentMillis = millis();

  if (Lite_1) {

    nextEventTime = currentMillis + interval_off;     // do the calculation only once
    Serial.print("OFF:\t");

  } else {

    nextEventTime = currentMillis + interval_on;
    Serial.print("ON:\t");
  }

  Lite_1 = !Lite_1;                           // invert value
  Serial.println(currentMillis);              // prints time since program started
  }
   }


body:
I want to automate the chicken coop of my grandmother. To do so, I want to use Arduinos and NodeMCUs, respectively. I want to check if all chickens are in the coop at night and then close a little door. I was trying to use RFID technology and tag the chickens with a little RFID tag but the read range I got was too short to get it working properly. Now, I am trying to implement a light gate with two small lasers and two receivers. I want to detect the direction (in or out) of the chickens. I got the lasers working and I get a signal (1  and 0 = light gate interrupted). I have to know which of the two laser detectors first detected a 0 (zero). I have no idea how to implement this in code. I was trying to use timers to no avail. I also was trying to use interrupts (see small code fragment).

I hope I made clear what I am trying to achieve. Please tell me if and how I can improve this question. Any google fu was to no avail. Every hint/help is greatly appreciated.

    #include <Arduino.h>

    // Functions
    void pin_ISR();

    const int detectorPin = 3;     // the number of the detector pin
    const int ledPin =  13;      // the number of the LED pin
    const int Laser = 6;
    // variables will change:
    volatile int buttonState = 1;         // variable for reading the status

    void setup() {
    Serial.begin(9600);
    // initialize the LED pin as an output:
    pinMode(ledPin, OUTPUT);
    // initialize the pushbutton pin as an input:
    pinMode(detectorPin, INPUT);
    pinMode(Laser, OUTPUT);
    digitalWrite(Laser, HIGH);
    // Attach an interrupt to the ISR vector
    attachInterrupt(digitalPinToInterrupt(3), pin_ISR, CHANGE);
    }

    void loop() {
    Serial.print(buttonState);
    delay(100);
    }

    void pin_ISR() {
    Serial.println("There was an interrupt!");
    buttonState = digitalRead(detectorPin);
    digitalWrite(ledPin, buttonState);
    }

title: How to know which event fired first?

Answers: 1

body:
Consider using [quadrature encoding][1] to detect travel direction using two light beams. A [method used in older mechanical mouse pointer devices][2] and track balls. [Using an Arduino to decode quadrature encoding][3] is talked about in many places on the web.

Place beam A and beam B such that a chicken waling out of the coop will activate beam B first and beam A second.

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

Because the activation of beam B occurs first we know the chicken is walking out of the coop.  If beam A occurred first we know the chicken is walking into the coop.

The shape of a chicken is irregular and a chicken may change its mind half way out of the coop.  These and other unexpected anomalies may lead to unexpected results.  Consider supplementing the beams with a [PIR][5] sensor outside the coop to confirm there are no chickens left outside.

  [1]: https://en.wikipedia.org/wiki/Incremental_encoder#Quadrature_outputs
  [2]: https://www.explainthatstuff.com/computermouse.html
  [3]: https://playground.arduino.cc/Main/RotaryEncoders
  [4]: https://i.stack.imgur.com/BFfgJ.png
  [5]: https://playground.arduino.cc/Code/PIRsense


body:
Alright. This is what I wanted to do:

 Make a circuit and code the arduino such that there are 2 tactile switches, each with a predefined pwm value.
 Whenever any one button is pressed the led should run at that pwm value, until the button is released. There is
 also an ultrasonic sensor on the same arduino that triggers an interrupt at a threshold distance that
 stops the led. When no button is pressed or the ultrasonic isnt active, the led should run at another pwm value.

Here is the code:(updated)

    const int trig = 9;
    const int echo = 10;
    const int redswitch = 2;
    const int yellowswitch = 3;
    int redled = 6;
    int greenled = 5;
    volatile int pwm = 50;

    volatile bool rs = LOW;      //RS - RED SWITCH
    volatile bool ys = LOW;      //YS - YELLOWSWITCH
    bool last_rs = LOW;
    bool last_ys =  LOW;
    volatile long distance=0;
    long duration=0;
    long temp=0;

    void setup(){
      pinMode(trig,OUTPUT);
      pinMode(echo,INPUT);
      pinMode(redled,OUTPUT);
      pinMode(greenled,OUTPUT);
      pinMode(redswitch,INPUT);
      pinMode(yellowswitch,INPUT);
      Serial.begin(9600);

      attachInterrupt(digitalPinToInterrupt(redswitch), red,CHANGE);
      attachInterrupt(digitalPinToInterrupt(yellowswitch), green,CHANGE);

      digitalWrite(greenled,LOW);
      digitalWrite(redled,LOW);
    }

    boolean debounce(boolean temp,int switchPin)
    {
      boolean current = digitalRead(switchPin);
      if (temp != current)
      {
        delay(5);
        current = digitalRead(switchPin);
      }
      return current;
    }

    void loop(){

      //Ultrasonic sensor's distance calculation
      digitalWrite(trig,LOW);
      delayMicroseconds(5);

      digitalWrite(trig,HIGH);
      delayMicroseconds(10);
      digitalWrite(trig,LOW);

      duration = pulseIn(echo, HIGH);
      temp = duration * 0.0343 / 2;
      noInterrupts();
      distance = temp;
      rs = debounce(last_rs,redswitch);
      ys = debounce(last_ys,yellowswitch);
      last_rs = rs;
      last_ys = ys;
      if(distance>8)interrupts();

      Serial.println(distance);
      analogWrite(redled,pwm);
      analogWrite(greenled,pwm);
    }

    void red(){

      if(rs == HIGH) pwm = 150;
      else pwm = 0;

    }

    void green(){

      if(ys == HIGH) pwm = 250;
      else pwm = 0;

    }

Now, when the arduino is connected to my laptop, led runs at the a particular value. But whenever I press a button they go off. Can you help me find out what's wrong here?

title: Problem with interrupts

Answers: 1

body:
Look at these lines:

    distance = temp;
    duration = pulseIn(echo,HIGH);
    distance = duration * 0.0343 /2;

Here is what they do:

- The first line sets the variable `distance` to zero (that's the value
  of `temp`).
- The second line waits for the ultrasonic pulse to reach the target,
  bounce against it and come back, while at the same time timing the
  whole trip. This can take a long time (several milliseconds). Chances
  are your program spends _most_ of its time executing this line.
- The third line sets the variable `distance` to something sensible.

This means `distance` is zero most of the time (while the second line
executes). When the interrupt fires, there is a very high probability
for the interrupt handler to find a zero distance, and thus to set `pwm`
to zero.

Simple fix: never set `distance` to an unreasonable value. Leave it's
value alone until you have a new distance measurement ready, and only
then update that variable. In other words, just remove the first of
those three lines.

But there is a catch now. The variable is four bytes long, and updating
it takes four instructions. There is a small probability that the
interrupt fire _in between_ these instructions. When that happens, the
interrupt handler finds the `distance` variable half-updated, with a mix
of bytes from the previous and the current distance measurements. This
is called a “race condition”, and is one of the worst kind of bugs you
can meet, because it is very hard to systematically reproduce.

The fix to the race condition is to update the variable with interrupts
disabled. The wrong way to do it is:

    duration = pulseIn(echo, HIGH);
    noInterrupts();
    distance = duration * 0.0343 / 2;
    interrupts();

This is bad because interrupts are blocked during the distance
calculation, which is too much. The right way is this:

    duration = pulseIn(echo, HIGH);
    temp = duration * 0.0343 / 2;
    noInterrupts();
    distance = temp;
    interrupts();

Now interrupts are blocked only while writing the `distance` variable.

Personally I don't think it is such a great idea to read the buttons
with interrupts. Buttons are extremely slow peripherals. If you make
your code non-blocking, your `loop()` will always be fast enough to deal
with them. Handling the buttons in `loop()` means you don't have to
worry about all the bugs that can easily sneak into interrupt-driven
code, like the above mentioned race condition.

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

**Edit**: In the original version of your code, interrupts were used to
read the switches. In the edited version, you added a debouncer, and you
don't need interrupts anymore. In fact, the way this version uses
interrupts makes no sense at all. The most problematic bit is the fact
that this code can disable interrupts for arbitrarily long times. This
is not good, and you should be aware that the Arduino's timekeeping
functions rely on interrupts to perform their job.

I suggest you just remove from this code every single line where you see
the word “interrupt” (singular or plural), and you replace

    if(distance>8)interrupts();

by

    if (distance > 8) {
        red();
        green();
    }

or, to streamline things a little bit, by

    if (distance > 8) {
        if (ys == HIGH) pwm = 250;
        else if (rs == HIGH) pwm = 150;
        else pwm = 0;
    }


body:
I am working with two sets of IR beam, they are to be placed in X distance. My goal is to measure speed. I would like to measure time between the first IR beam to the second beam when the beam breaks.

I am not sure what's going on, I am not getting any time of the serial port but the LEDs are turning on and off the way I wanted.

Please help me with getting the time between two IR beam sensors.

This the sensor that I am using -  [Adafruit IR breakbeam sensors][1]
and I am working with a Mega2560.

    #define LEDPIN 13
    int startPin = 8, finishPin = 5;
    unsigned long starttime = 0, finishtime, time_interval;
    float distance = 1, Speed; // Speed calculated
    int trigger1 = 0; // Sensor 1
    int trigger2 = 0; // Sensor 2
    int sensor1State; // Sensor 1 status
    int sensor2State; // Sensor 2 status

    void setup() {
      pinMode(startPin, INPUT_PULLUP); // Sensor 1 as input
      digitalWrite(startPin, HIGH); // Turn on the pullup
      pinMode(finishPin, INPUT_PULLUP); // Sensor 2s input
      //digitalWrite(finishPin, HIGH); // Turn on the pullup

      pinMode(LEDPIN, OUTPUT);
      time_interval = ((finishtime - starttime) / 1000000);
      Serial.println(time_interval);
    }

    void loop() {
      sensor1State = digitalRead(startPin); // Read the state of the IR sensor 1:
      if (sensor1State == LOW) // See if IR beam of sensor 1 has been broken
      {
        if (trigger1 == 0 && trigger2 == 0) // Check to make sure both sensors have not triggered
        {
          starttime = micros(); // Save time when sensor 1 was triggered
          digitalWrite(LEDPIN, HIGH);
          trigger1 = 1; // Prevent sensor 1 from triggering again
        }
      }
      if (trigger1 == 1) {
        sensor2State = digitalRead(finishPin); // See if IR beam of sensor 2 has been broken
        if (sensor2State == LOW) {
          // Check to make sure sensor 1 has triggered but not sensor2
          if (trigger2 == 0) {
            // Run speed function
            trigger2 = 1;
            finishtime = micros(); // Save time when sensor 2 was triggered
            digitalWrite(LEDPIN, LOW);
            // time takes to travel between 2 IR Beam  // divide by 1000000 to convert microsecond to second
            Serial.println(time_interval);
          }
          // Reset both sensors
          trigger1 = 0;
          trigger2 = 0;
        }
      }
    }

  [1]: https://learn.adafruit.com/ir-breakbeam-sensors/overview

title: Time between two IR beam sensors

Answers: 2

body:
You never calculate the time_interval that you print. Add that after the finishtime line

      if (trigger2 == 0) {
        // Run speed function
        trigger2 = 1;
        finishtime = micros(); // Save time when sensor 2 was triggered
        digitalWrite(LEDPIN, LOW);
        // time takes to travel between 2 IR Beam  // divide by 1000000 to convert microsecond to second
        Serial.println(time_interval);
      }

body:
You've tried to print an interval at the bottom of the setup() function, using finishtime before you have ever used it. Fortunately, finishtime will have been initialized to zero before the program runs so the the arithmetic result will be zero, though meaningless.

In loop(), you've never completed the interval calculation before you try to print it.

If nothing at all is being printed, check your wiring and be sure your code is getting the triggers. You haven't showed your wiring, so we can't help you debug that, in case there is a problem with that also.


body:
I have a strange behavior, using ESP32 devkit v.1 boards.
Everything works, I can upload blink sketch, serial works, led blinks.
However, once I upload any sketch which is using the wifi.h (and utilizing it for example calling WiFi.mode(WIFI_STA);), upon upload, the board keeps resetting the serial connection, stays up for not more then 1 second, resets again, and so on.
I could not debug the issue, since serial is unusable. Any ideas what is wrong? I did a fresh ArduinoIDE, ESP32 board manager install, etc. and normal sketches work flawlessly.

title: ESP32 reset loop when using wifi.h

Answers: 1

body:
The USB cable was too long, and hence power loss.

Sorry, I figured it out a day after I asked this question.


body:
I currently have a push solenoid connected to my standard Arduino board. The Arduino is powered via its USB cable, while the solenoid is powered using a 12V Huawei adapter (in conjunction with a MOSFET driver module).

How can I switch out the push solenoid for a servo motor? The operational voltage of the servo is 4.8 to 7.2V (with a stall torque of 13 kg-cm) to give you an idea of its size. I have been told to buy a DC-DC step-down module (to adjust the Huawei supply from 12V down to 5V) but I think it could be easier to power the servo using some sort of USB?

Or other suggestions are welcome. I want the easiest solution (since I am NOT tech savvy) and I can't buy parts until I am for certain the solution will work (that's research for you). Thanks!

title: Connecting a servo motor to an Arduino

Answers: 3

body: I don't know if i understand your question properly, but if you want to connect the servo to the Arduino try connecting it to the 5v Output of your board.

body:
You will have to check in the servos datasheet for the maximal current, that it draws (motors draw more current, when inhibited by mechanical force, so be sure to get the maximal current from the datasheet). From the data, that you gave us, I think it will draw rather much current. So you should not power it over the USB port of your PC (which gives 500mA at maximum). Also you should not use the 5V pin of your Arduino, or you may fry components like the diode, that lies in the current path from USB to 5V pin.

For your step down module, you will also have to check, if it can provide the current, that the servo needs, or you may kill it. If you want to use USB, you can use a standard USB charger or powerbank. Often these can provide more than 1A (depending on the actual product). Most USB wallwart chargers have a current specification on them. But (as said earlier) don't provide the power through the Arduino. Provide it directly from the source, so that the possibly high current for the servo does not have to pass trough the Arduino. You can also power the Arduino with the same source in parallel to the servo, so that you don't need two sources or a converter.

For more info, you will have to provide more information about the servo

body: Getting a DC-DC step down converter would definitely work and would be a good way to do it. However,realistically you will be fine if you connect the servo to +5V from USB, since you said it only draws absolute max of 1.2A. Almost all USB ports can handle that.


body:
I am making an Arduino mod-bus device and I want to make a webpage as well that will allow me to reset the unit if there is any issues remotely. To do this I would need the mod-bus to operate on port 502 and the webpage to operate on port 80. is it possible for the Arduino to support two ports? I am using an Uno with a Ethernet shield and the standard ehternet.h file with a [Modbus library][1]. Any suggestions or ideas?

     #include SPI.h
     #include VL53L0X.h
     #include Ethernet.h
     #include Modbus.h
     #include ModbusIP.h
     #include VL53L0X.h
     #include Wire.h

    VL53L0X sensor;
    EthernetServer server(80);

    //Modbus Registers Offsets (0-9999)
    const int SENSOR_Hreg0 = 100;

    //ModbusIP object
    ModbusIP mb;

    short ts;

    void setup() {
      byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
      byte ip[] = { 192, 168, 1, 177 };

      Wire.begin();
      mb.config(mac, ip);

      // Add SENSOR_Ireg register - Use addIreg() for analog Inputs
      mb.addHreg(SENSOR_Hreg0);

      ts = millis();

      //Sensor setup
      sensor.init();
      sensor.setTimeout(500);
      sensor.startContinuous();

      //remote reset
        pinMode(13, INPUT);
        digitalWrite(13, LOW);

       // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }
      Serial.println("Ethernet WebServer Example");

      // start the Ethernet connection and the server:
      Ethernet.begin(mac, ip);

      // Check for Ethernet hardware present
      if (Ethernet.hardwareStatus() == EthernetNoHardware) {
        Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
        while (true) {
          delay(1); // do nothing, no point running without Ethernet hardware
        }
      }
      if (Ethernet.linkStatus() == LinkOFF) {
        Serial.println("Ethernet cable is not connected.");
      }

      // start the server
      server.begin();
      Serial.print("server is at ");
      Serial.println(Ethernet.localIP());

    }

    void loop() {

      mb.task();

        //Webpage
        // listen for incoming clients
      EthernetClient client = server.available();
      if (client) {
        Serial.println("new client");
        // an http request ends with a blank line
        bool currentLineIsBlank = true;
        while (client.connected()) {
          if (client.available()) {
            char c = client.read();
            Serial.write(c);
            // if you've gotten to the end of the line (received a newline
            // character) and the line is blank, the http request has ended,
            // so you can send a reply
            if (c == '\n' && currentLineIsBlank) {
              // send a standard http response header
              client.println("HTTP/1.1 200 OK");
              client.println("Content-Type: text/html");
              client.println("Connection: close");  // the connection will be closed after completion of the response
              client.println("Refresh: 5");  // refresh the page automatically every 5 sec
              client.println();
              client.println("<!DOCTYPE HTML>");
              client.println("");
              // output the value of each analog input pin

                client.print("Distance Measures ");
                client.print(sensor.readRangeContinuousMillimeters());
                client.print("mm");
                client.println("
");
                client.print("Filter Count:");
                client.print(-2.2*sensor.readRangeContinuousMillimeters()+404);
                client.println("
");
              }
              client.println("");
              break;
            }

          }

      //Modbus
      if (millis() > ts + 100) {
        ts = millis();

         mb.Hreg(SENSOR_Hreg0, sensor.readRangeContinuousMillimeters() );

         }
    }}

Edit:
Note: The issue seems to lie somewhere in with the sensor, because when I run it with out have the sensor code in there is no problem but when I add it the issue starts again.

  [1]: https://github.com/andresarmento/modbus-arduino

title: Two ports on Uno with ethernet shield

Answers: 1

body:
 - **move the modbus refresh out of the `if (client)` condition**

 - `mb.begin()` calls `Ethernet.begin()`. Do not repeat it in setup()
 - move `client.println("</html>"); break;` inside the `if` block before it
 - copy the rest of the detection of empty line from the WebServer example

 - `stop()` the client after response

 - change type of `ts` to `unsigned long`

  [1]: https://github.com/jandrassy/Regulator/blob/master/Regulator/WebServer.ino
  [2]: https://github.com/jandrassy/Regulator/blob/master/Regulator/Telnet.ino
  [3]: https://github.com/jandrassy/Regulator/blob/master/Regulator/Regulator.ino


body:
I'm trying to make an iot device that connects to my wifi, establishes a socket connection with my golang backend and then starts to send sensor data from the ardunio.

I've got an ardunio uno board and this ESP8266:

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

I found [this websockets library][2] but I don't know if I can import the .h files if I have "arduino uno" selected in the IDE

**My question:**
Is it possible to establish a WebSocket connection with my go backend using the esp model that I have? If so, how can I import the required libraries in the arduno IDE? I would be happy if you could give me some directions.

  [1]: https://i.stack.imgur.com/QPVbD.png
  [2]: https://github.com/Links2004/arduinoWebSockets

title: Websockets with the ESP8266 using arduino uno board

Answers: 1

body:
The library you linked is not for Uno with esp8266 module.

It is possible to use the ESP-01 with Uno for WebSockets client for example with ArduinoHttpClient library over the WiFiEsp library.

Better option is to use only an esp8266 development board programmed with Arduino IDE without the Uno.


body:
I'm fairly inexperienced with Arduino and entirely new to networking, so bear with me.

I've programmed a couple of NodeMCU devices to communicate the use of an instrument via activation of an LED. I have one set up as an access point and another as a client. I roughly followed the [second answer from this question](https://arduino.stackexchange.com/questions/18176/peer-to-peer-communication) to set mine  up. I'll eventually shift this particular project to `mqtt` but I'd like to understand how to get the direct peer-to-peer working for other projects as well.

While it _is_ partially working, I am having a couple issues that I assume are related to networking.
1. After plugging in the client ESP8266, the server only recognizes it for two loops (taking ~5 seconds each), then I have to restart the client, which is discovered instantaneously by the server.
2.  After the client connects, if I press the pushbutton on the client - while recognized - only once, the "toggle" command is repeatedly sent, resulting in the LED blinking for a handful of loops until it stops and the client has to be restarted again.
2.1. If I comment out the button debounce on the client, this happens more reliably. With debounce on, if I click the button immediately upon the first "client found!" message, the LED will _typically_ toggle on the second (final) loop. Subsequent presses changing nothing.

Server sketch:

    // Particle counter use server
    // Place outside with LED

    // load libraries
    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>

    // Set up variables
    #define use_LED   D2

    const char* ssid = "esp_server";
    const char* password = "password";

    WiFiServer server(80); // set port to 80

    int toggle = 0;
    String request = "";

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

      WiFi.mode(WIFI_AP);
      WiFi.softAP(ssid, password);
      digitalWrite(use_LED, HIGH);
      delay(1000);
      Serial.println(WiFi.softAPIP());

      digitalWrite(use_LED, LOW);

      server.begin();
    }

    void loop() {
      // Check for a client
      WiFiClient client = server.available();
      if (client) {
      // Wait until client is connected
    //  while(!client.available()) { delay(1); }/
      Serial.println("client found!");

      // Parse commands
      String request = client.readString();
      Serial.println(request);

      // After pressing client switch once, this dances between on and off with every loop
      if (request == "toggle") {
        toggle = 1 - toggle; // switches to opposite on request reception
        digitalWrite(use_LED, toggle);
        delay(2000);
      }

      client.flush();
      }

    }

Client sketch

    // Particle counter use client
    // Place in analysis room with button

    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>

    #define toggle_button D1 // make sure to use a pulldown resistor

    int toggled = 0;

    // Set up connection to server ESP
    const char* ssid = "esp_server";    // ssid of server
    const char* password = "password";  // password of server
    const int port = 80;                // port of server

    byte ip[] = {192,168,4,1};

    WiFiClient client;

    void setup() {
      Serial.begin(9600);
      pinMode(toggle_button, INPUT);
      Serial.println("active");

      WiFi.mode(WIFI_STA); // Setup as client
      WiFi.begin(ssid, password); // Connect to server ESP
    }

    void loop() {
      toggled = digitalRead(toggle_button);

      if (client.connect(ip, port)) { Serial.println("CONNECTED"); }

      if (toggled == HIGH) {
        // send command to toggle LED when button is pressed
        Serial.println("triggered");
        client.print("toggle");
      }

      client.flush();
    }

Strangely, the slow recognition is only on the server side, the client spams its serial output with "CONNECTED", until stopping (I assume when the second loop completes on the server side, I can only monitor the serial of one at a time). But once found the following [lines suggesting a WiFi or memory error](https://github.com/esp8266/Arduino/issues/1648) in the output nestled among all the lines of "CONNECTED":

    Exception (29):
    epc1=0x40202a8f epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000000 depc=0x00000000

    ctx: cont
    sp: 3ffefa30 end: 3ffefc40 offset: 01a0

    >>>stack>>>
    3ffefbd0:  3ffe8b70 3ffee9b0 3ffeebe4 40202a8d
    3ffefbe0:  0104a8c0 00000000 3ffeebe4 4020328c
    3ffefbf0:  00000000 3ffee9b4 3ffeebe4 3ffeec10
    3ffefc00:  3fffdad0 3ffee9b0 3ffee998 40202107
    3ffefc10:  401070a0 0104a8c0 00000001 40203519
    3ffefc20:  3fffdad0 00000000 3ffeec08 40203544
    3ffefc30:  feefeffe feefeffe 3ffeec20 40100710
    <<<stack<<<

I have pulldown resistors on both the client switch and the server LED, I'm guessing that `client.flush()` does not clear the command? I'm baffled as to why the loop on the server only runs twice before I have to reset the client, and why upon resetting the client is instantly recognized, but takes so long to see it again. Does anyone have any advice?

title: ESP8266 Peer to Peer with AP and STA - Cache AP Clients, Flush Their Requests?

Answers: 1

body:
You `connect()` and do not `stop()` the client. You get out of the 5 connections limit.

Use client in `if (client.connect(...))`, print and then do `client.stop()`.

And also `stop()` the server's client object.

`readString` has one second timeout. you should send a delimiter and use [readStringUntil][1]

Edit: For permanent connection of multiple clients on server side see the WiFiTelnetToSerial example. At client side you can use one global client object. But check if it is connected and if not, call stop and then connect again.

    void loop() {

        if (!client.connected()) {
          client.stop();
          if (!client.connect(ip, port)) {
            delay(1000);
            return;
          }
        }

        int toggled = digitalRead(toggle_button);

        if (toggled == HIGH) {
          // send command to toggle LED when button is pressed
          Serial.println("triggered");
          client.print("toggle.");
        }
    }

  [1]: https://www.arduino.cc/reference/en/language/functions/communication/stream/streamreadstringuntil/


body:
i have resistor based sensor, when i test it using arduino connect to PC using serial monitor  without sharing ground to other circuit it has a nice value between 300-650 in adc range and the error/ accuracy reading just have about 5 value (ex: 607-612) if there is no condition change in the sensor.

But the problem comes when i sharing the ground to the other circuit. The accuracy is messed up bigger than 60 adc value (570-660) with the same condition without sharing ground.

My circuit is powered by PSU 24V and 24V driver to produce input signal for electric pressure regulator. The arduino ground is sharing because to control the input of the 24V driver. Here my circuit in the attachment.

So there is two ground from PC (i need it to use serial monitor) and the PSU 24V

How to eliminate the noise? Is there any way to control the 24v driver and read the sensor at the same time without sharing ground? Maybe using two controller with master/slave? Or there is any advice?[![my circuit][1]][1]

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

title: ADC noise when sharing ground from external supplies

Answers: 1

body:
You've created what's known as a "Ground Loop".  You have 2 grounds in your circuit, your 24v PS has a ground and the PC supplying 5V to your Arduino has a ground.  They are not likely to be equivalent and will cause many unwanted side effects.

You can reduce some noise using RC or RLC circuits on your power supply pins.  It's probably best to use only a single power supply (and ground).


body:
I am having an issue that I can't seem to get my head wrapped around.  What I am trying to accomplish is to have a minutes worth of sensor data in an array (reading every 5 seconds) so I'll have 12 values in this after one minute.

I want to keep the array to 12 values so I need to keep moving all the values in it down one index per new value hitting index [0] to make sure that each reading has a lifetime of 60 seconds on the array.  Here is my code so far:

    void add_readings_to_averages() {
      // At this point, I am moving values down the array to make room at the beginning.
      for (int a = 11; a >= 0; a--) {
        Serial.print("The value at temperature_c_minute_avg[");
        Serial.print(a);
        Serial.print("] is ");
        Serial.print(temperature_c_minute_avg[a]);
        Serial.println();
        if (a == 11) {
          Serial.println("At 12 so need to overwrite this value");
        }

        if (a <= 10) {
          Serial.print("a is ");
          Serial.println(a);
          temperature_c_minute_avg[a] = temperature_c_minute_avg[a + 1];  // This moves each entry down one index in the array creating an empty space at index[0]
        }

        if (a == 0) {
          temperature_c_minute_avg[a] = temperature_c;
        }
      }

I've loaded my array at the time of initialization with some dummy data so I could see what was going on.  First run displays as you would expect.

<!-- language: lang-none -->

    The value at temperature_c_minute_avg[11] is 120.00
    At 12 so need to overwrite this value
    The value at temperature_c_minute_avg[10] is 110.00
    a is 10
    The value at temperature_c_minute_avg[9] is 100.00
    a is 9
    The value at temperature_c_minute_avg[8] is 90.00
    a is 8
    The value at temperature_c_minute_avg[7] is 80.00
    a is 7
    The value at temperature_c_minute_avg[6] is 70.00
    a is 6
    The value at temperature_c_minute_avg[5] is 60.00
    a is 5
    The value at temperature_c_minute_avg[4] is 50.00
    a is 4
    The value at temperature_c_minute_avg[3] is 40.00
    a is 3
    The value at temperature_c_minute_avg[2] is 30.00
    a is 2
    The value at temperature_c_minute_avg[1] is 20.00
    a is 1
    The value at temperature_c_minute_avg[0] is 10.00
    a is 0
    2018/11/2 11:4:39  -  Running for a total of 0 hours 0 minutes and 7         seconds

But the second time through the `loop()` my array is trashed.

<!-- language: lang-none -->

    The value at temperature_c_minute_avg[11] is 120.00
    At 12 so need to overwrite this value
    The value at temperature_c_minute_avg[10] is 120.00
    a is 10
    The value at temperature_c_minute_avg[9] is 120.00
    a is 9
    The value at temperature_c_minute_avg[8] is 120.00
    a is 8
    The value at temperature_c_minute_avg[7] is 120.00
    a is 7
    The value at temperature_c_minute_avg[6] is 120.00
    a is 6
    The value at temperature_c_minute_avg[5] is 120.00
    a is 5
    The value at temperature_c_minute_avg[4] is 120.00
    a is 4
    The value at temperature_c_minute_avg[3] is 120.00
    a is 3
    The value at temperature_c_minute_avg[2] is 120.00
    a is 2
    The value at temperature_c_minute_avg[1] is 120.00
    a is 1
    The value at temperature_c_minute_avg[0] is 0.00
    a is 0
    2018/11/2 11:4:44  -  Running for a total of 0 hours 0 minutes and 12     seconds

The entire array was overwritten with the last value and the new value was not added.  The array itself is setup as a global variable.  The initialization at the top.

    float temperature_c_minute_avg[12] = {10.0,20.0,30.0,40.0,50.0,60.0,70.0,80.0,90.0,100.0,110.0,120.0};

What am I missing here?  Been staring at this for some time, but this is the first time I've tried to use an Arduino array so I can totally believe the issue is PBKAC! :)

title: Having some issues with an array

Answers: 2

body:
In your if (a <= 10) block, you are inside a for loop that is decreasing and replacing each value with the value inside index+1. This means that as you are going down the indices, you are carrying the 11th index value with you. Here is how it is without variables (allow me to shorten the variable name to t):

    t[10] = t[11];
    t[9] = t[10];
    t[8] = t[9];

And so forth. Whatever was in a[11] is being dragged through each of the variables of lower indices.

I strongly suggest going the other way around with either your loop or which way you are pushing the data. For instance (continuing with array name t):

    for (int i = 11; i >=0; i--) {
        if (i > 0)
            t[i] = t[i-1]; // shift data from index 10->11, 9->10, etc.
    }
    t[0] = arbitrary_data; // fill in new 'empty' space

Or, alternatively if you still want to put new data in index 11:

    for (int i = 0; i <= 11; i++) {
        if (i < 11)
            t[i] = t[i+1]; // shift data from index 1->0, 2->1, etc.
    }
    t[i] = arbitrary_data; // fill in new 'empty' space

This is my solution for your current data management method. Another answer suggested a circular buffer where you simply keep track of which datum is being changed at a time and is far more efficient.

body: Your issue is a C programming issue and has nothing to do with the Arduino specifically.  You should research how to implement a circular buffer.  You don't want to move around the values within the array, but rather just increment array index values.  Keep two index values, one of the current index position (the place where the next recorded value will be placed) and another of the number of values recorded.  Eventually the number of values recorded will be equal to your maximum array size and only the index position will increment.  When the array index exceeds the maximum array size it wraps back to 0.


body:
I have the strange pb.
My esp8266 was working fine with my DHT22 and then failed every time.
I loaded an example sketch in a other ESP8266 and I have the same pb.... until I shut down -> up the DHT22 when the ESP8266 is working.
To check more, I added this at the setup before `dht.begin()` :

          digitalWrite(0, LOW); // turn the LED on (HIGH is the voltage level)
      delay(1000); // wait for a second
      digitalWrite(0, HIGH);

And it works. But I don't know why I need to do this "pull up".
PS : I already tried with or without the 10K resistor, same pb.
PS2 : I already tried with 3.3v or 5V for DHT22. Same pb.

Any idea ?

title: DHT22 need pull down/up ESP8266

Answers: 1

body:
I answer my own question in case someone has the same issue.
**The ADAFRUIT_DHT lib DOESN'T WORK WITH ESP8266.** It keep saying `Failed to read from DHT sensor!` until you unplug/plug the VCC on the DHT.

But the **DHTesp** ([link][1]) works very well at first try !

Thx @Juraj and @Jot for their support.

  [1]: https://github.com/beegee-tokyo/DHTesp


body:
I am running into an issue with a loop call on an Arduino MKR1000. I have tried the solutions suggested in [this question][1] and it usually works for 5 minutes and then collapses.  I am trying to make two calls to different APIs every 10 seconds and update something on the Arduino accordingly, but the loops seem to be getting out of sync after a few minutes. Here is the code - I tried to shorten it...
<!-- language-all: lang-cpp -->

    #include <Time.h>
    #include <SPI.h>
    #include <WiFi101.h>
    #include "arduino_secrets.h"

    // put your local wifi info here
    const char* ssid     = SECRET_SSID;
    const char* password = SECRET_PASS;

    const char* host = "bustime.mta.info";

    void setup() {
      Serial.begin(9600);
      delay(10);
     // connecting to a WiFi network
      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(300);
        Serial.print(". ");
      }
    }

    void loop() {
      Serial.println("START THE LOOP");
      // Use WiFiclient class to create TCP connections
      WiFiClient client;
      WiFiClient client2;
      char * serviceDeliveryString = new char[40]();
      strcpy(serviceDeliveryString, "/ServiceDelivery");
      char * responseTimestampString = new char[40]();
      strcpy(responseTimestampString, "<ResponseTimestamp>");
      char * TString = new char[40]();
      strcpy(TString, "T");

      if (!client.connect(host, 80)) {
        lcd.clear();
        lcd.gotoXY(0, 0);
        lcd.string(connectionFailed);
        delay(2000);
        return;
      }

      //connect to schedule data
      if (!client2.connect(host, 80)) {
        lcd.clear();
        lcd.gotoXY(0, 0);
        lcd.string(connectionFailed);
        delay(2000);
        return;
      }

      char * req1full = new char [100]();
      strcat(req1full, "GET /api/siri/stop-monitoring.xml?key=KEY&OperatorRef=MTA");
      strcat(req1full, " HTTP/1.1");
      client.println(req1full);
      client.println("Host: bustime.mta.info");
      client.println("Connection: close\r\n");

      char * req2full = new char [100]();
      strcat(req2full, "GET /api/where/schedule-for-stop/MTA_");
      strcat(req2full, stopNum);
      strcat(req2full, ".xml?");
      strcat(req2full, "key=KEY HTTP/1.1");
      Serial.println(req2full);
      client2.println(req2full);
      client2.println("Host: bustime.mta.info");
      client2.println("Connection: close\r\n");

      //Pause long enough for the connection to happen. Make this longer if you have issues.
      delay(1000);

      while(client.available()){
        if (client.findUntil(responseTimestampString, serviceDeliveryString)){
          Serial.println("inside client...");
          client.findUntil(TString, serviceDeliveryString);
          String mtaTime = client.readStringUntil('.');
          Serial.println(mtaTime);
        }
        delay(10);
      }

      while(client2.available()){
        if (client2.findUntil("<currentTime>", "/data")){
          Serial.println("inside client2...");
          String mtaTime2 = client2.readStringUntil('<');
          Serial.println(mtaTime2);
        }
        delay(10);
      }

      client.stop();
      client2.stop();
      delay(9000);

    }

The output starts out looking good:

    START THE LOOP
    GET /api/where/schedule-for-stop/MTA_306762.xml?key=KEY HTTP/1.1
    inside client...
    22:13:38
    inside client...
    22:13:38
    inside client2...
    1541211218146
    START THE LOOP
    GET /api/where/schedule-for-stop/MTA_306762.xml?key=KEY HTTP/1.1
    inside client...
    22:13:51
    inside client...
    22:13:51
    inside client2...
    1541211231815
    START THE LOOP
    GET /api/where/schedule-for-stop/MTA_306762.xml?key=KEY HTTP/1.1
    inside client...
    22:14:04
    inside client...
    22:14:04
    inside client2...
    1541211244465

But eventually something seems to happen with the loops and this is the final output, when it should keep running:

    inside client...
    22:19:02
    inside client...
    22:19:02
    START THE LOOP
    GET /api/where/schedule-for-stop/MTA_306762.xml?key=KEY HTTP/1.1
    START THE LOOP
    GET /api/where/schedule-for-stop/MTA_306762.xml?key=KEY HTTP/1.1
    START THE LOOP

Any suggestions for how to fix this?

  [1]: https://arduino.stackexchange.com/questions/33120/how-can-i-make-this-code-read-a-page-every-10-seconds

title: Loops fail after ~5 minutes when making two API calls every 10 seconds using WiFi client

Answers: 1

body: You keep calling new to allocate memory but you never free it.  This is a memory leak and eventually you run out.  Instead of constantly creating new arrays, why don't you make those global or static.  Or even just local arrays if you don't need them to be persistent.  On a microcontroller you really don't want to be using new unless absolutely necessary.


body: Has anyone had success using the keyboard functionality of any arduino in single user mode of mac computers? I would like to inject keystrokes in single user mode, and have been unsuccessful with the atmega32u4.

title: Is Arduino Keyboard in Single User Mode Possible?

Answers: 2

body:
OS X requires a "Boot Interface" compatible HID profile for a keyboard to work in single user mode (it has only loaded very rudimentary drivers by that point).  The Arduino doesn't provide that interface, so can only work with the more advanced drivers the OS provides once booted.

You can *try* setting the "boot interface" flag to 1 in the interface subclass ([here](https://github.com/arduino/ArduinoCore-avr/blob/2663be17272e19f00c55f3f2d8f1ebfac47158d6/libraries/HID/src/HID.cpp#L33), I think, changing `HID_SUBCLASS_NONE` to `HID_SUBCLASS_BOOT_INTERFACE`) though I have no clue what the actual effect of that will be given that it's a composite device that may or may not conform to the boot interface standard.

body:
I have found the solution to my problem. The issue is that the presence of both the usb device and serial port causes issue in single user mode. For the keyboard to work properly, the serial port must be disabled. This means that reflashing the micro requires pulling the reset pin low twice quickly for the port to show up again. Here is an example of how to remove the serial port:
https://github.com/gdsports/usb-metamorph/tree/master/USBSerPassThruLine


body:
I have a string to be splitted into define chunks.

For example `new_str="abcdefghjklmnopqrstuvwxyz`, and my goal is to split it to chunks of `split_size=5`, so the result should be :`abcde`,`fghij` and so o.

`new_str` gets every time a different string.

`split_size` can be any size.

I have 2 questions:

1) Attached code does the job, but looks a BIT not elegant for a newbie like me. is there another way doing it ?

2)In code attached, output is `Serial.println(tmp)` and should be replaced with an output function to post each chunk to as a MQTT message. Ive rather that each chunk would be stored into a global array, to be sent later on in code out side `msgSplitter`.

So I wrote the following code:

    int split_size=5;
    char new_str[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    void setup() {

            Serial.begin(9600);
            Serial.print("String length: ");
            Serial.println(strlen(new_str));
            Serial.print("Split Size: ");
            Serial.println(strlen(split_size));

            msgSplitter(new_str, split_size, "Split #");

    }
    void msgSplitter( const char* msg_in, int chop_size, char *prefix){
            num=ceil((float)strlen(msg_in)/chop_size);
            char tmp[50];
            int pre_len;

            if (num > 1) {
                    for (int k=0; k<num; k++) {
                      pre_len=0;
                            sprintf(tmp,"%s %d: ",prefix,k);
                            pre_len = strlen(tmp);
                            for (int i=0; i<chop_size; i++) {
                                    tmp[i+pre_len]=(char)msg_in[i+k*chop_size];
                                    tmp[i+1+pre_len]='\0';
                            }
                            Serial.println(tmp);
                    }
            }
            else {
                    Serial.println(msg_in);
            }
    }

title: Splitting a message

Answers: 1

body:
    // concat version
    void msgSplitter(const char* msg_in, int chop_size, char *prefix) {
      char tmp[50];
      int size = strlen(msg_in);
      for (int pos = 0, k = 0; pos < size; pos += chop_size) {
        int l = sprintf(tmp, "%s %d: ", prefix, k++);
        strncat(tmp + l, msg_in + pos, chop_size);
        Serial.println(tmp);
      }
    }

    // only value version
    void msgSplitter(const char* msg_in, int chop_size, char *prefix) {
      char tmp[chop_size + 1];
      tmp[chop_size] = 0;
      int size = strlen(msg_in);
      for (int pos = 0; pos < size; pos += chop_size) {
        strncpy(tmp, msg_in + pos, chop_size);
        Serial.println(tmp);
      }
    }


body:
I recently got into arduino and I want to set up something big. My project will need the arduino to be able to get into a specific directory of a windows (later may change to linux but for now windows) computer which will have some files with values required for the arduino to run.

Is it possible to set it to go to a fixed path and open a file with a specific name and get it's contents?

Ideally I would want those values to be stored to my micro sd so I do not load too many things on memory as my board is a Leonardo and the code is quite extensive already. (The board can be changed if needed)

Any help/ideas are appreciated!

title: Is there a way to traverse a filesystem and read files with an arduino?

Answers: 2

body: The Arduino has no access to the file system on a PC.  All it has is a serial connection with which it can communicate with some program running on the PC. The code that is handling the PC's file system would have to run on the PC itself.

body:
This could get complicated.

You'll need to develop a USB interface on your Arduino to "talk" to the PC.  Then you'll need to write an application (*use whatever language you feel comfortable with - that's an entire religious discussion for another place and time*) that "listens" for the Arduino's USB connection and does most of the legwork.  Think of the PC application as sort of a "script server", allowing the Arduino to make cryptic requests ("**FCNT**" requests a 'File Count' on your target PC folder, that sort of thing) which the PC application will then return data from, as needed.  (In the previous example "**FCNT**" gets a file count of a predetermined folder - which would return a four-byte [*integer*] value revealing the results of the file count.)  From this point you could add additional scripts and functionality, allowing your Arduino to make abbreviated (sometimes wonky-seeming) calls to the PC, and have the PC do what is necessary to fulfill those requests.

In the example I hastily described above, your Arduino sends "**FCNT**" and then "listens" to the USB interface, eagerly awaiting the return value that it knows will be a four-byte response.  If the PC application were properly programmed, you could get slick with your command calls, sending "**XFR #**" which asks the PC application to "**transfer file [#] to me**" at which time the Arduino goes into "paddle board" mode, where it receives data from USB and immediately transfers it to the MicroSD until <EOF> is "seen" in the data stream, at which point the Arduino returns to normal code operations mode.

Of course, your PC application will need to be extremely fault-tolerant in order to prevent sending your Arduino bad data or worse, sending it into a state that can't be easily recovered, such as if the Arduino "thinks" it's expecting a file and goes into "wait for transfer" state, but the file it requested doesn't exist because it got deleted sometime between the file count request and the transfer request.  The Arduino would appear to be "hung up" because it would be in "File Transfer" or "paddle board" mode, and not looking for other messages or awaiting other operator stimulus.

Due to the different architectures, there really is no *simple* way to interface an Arduino to a PC.  Sorry about that.


body:
I'm trying to connect my nodeMCU to my WiFi network but it keeps printing **`........`** which means is not connecting to the network. Here is my code used to connect to WiFi. Any reason why it isn't connecting to WiFi network?.

    #include <ESP8266WiFi.h>

            // Replace these with your WiFi network settings
            const char* ssid = "******"; //replace this with your WiFi network name
            const char* password = "******"; //replace this with your WiFi network password

            void setup()
            {
              delay(1000);
              Serial.begin(57600);

              WiFi.begin(ssid, password);

              Serial.println();
              Serial.print("Connecting");
              while (WiFi.status() != WL_CONNECTED)
              {
                delay(500);
                Serial.print(".");
              }

              Serial.println("success!");
              Serial.print("IP Address is: ");
              Serial.println(WiFi.localIP());
            }

            void loop() {
            }

title: NodeMCU does not connect to wifi

Answers: 2

body:
If your WiFi network doesn't have DHCP, then you must set the IP addresses

example:

      IPAddress ip(192, 168, 1, 8);
      IPAddress gw(192, 168, 1, 1);
      IPAddress sn(255, 255, 255, 0);
      WiFi.config(ip, gw, sn, gw);

gw is gateway. the last parmeter is dns server's IP. sn is subnet mask.

body:
If your powering the device via a computer USB port there is a good chance it’s not providing enough power for the wifi.
Try powering fron an external source.


body:
I followed an example link for WDT. Code was copied as is, and uploaded to Nano successfully.

Now- when I wish to upload another code, I get an error message saying `avrdude: stk500_recv(): programmer is not responding`.

Is it possible to undo it ?

[code][1]:

    #include <avr/wdt.h>

    #define led 13 // pin 13 is connected to a led on Arduino Uno

    void setup()
    {
      pinMode(led, OUTPUT);      // set pin mode
      digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(100);                // wait for a tenth of a second
      digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
      delay(100);                // wait for a tenth of a second
    }

    void loop(){
      wdt_enable(WDTO_15MS);     // enable the watchdog
                                 // will fire after 15 ms without reset

      while(1)
      {
    //     wdt_reset();          // uncomment to avoid reboot
      }
    }

  [1]: https://folk.uio.no/jeanra/Microelectronics/ArduinoWatchdog.html

title: Arduino Nano- Programer not responding after upload WDT

Answers: 2

body:
If the WDT program is running when you try to upload a new one, it may be blocking the bootloader. Try holding the reset button while you click the the IDE's upload button, releasing the reset once you see avrdude launch. It may take a few tries to get the button-dance just right.

Update:

> what is avrdude ?

It is the program on your PC that uploads the compiled image to the Arduino. You'll see it running in the lower pane of the Arduino IDE.

body:
One of the things with the watchdog is that after a watchdog reset it remains active. It has to specifically be turned off - and the bootloader doesn't (IIRC) normally turn it off.

If the timeout is too short (shorter than the time taken to upload new code) the watchdog will reset the chip while you're uploading.

The only way to turn it off is to physically remove power from the chip, and make sure that the loaded sketch never runs.

1. Select the board / port etc ready to upload
2. Unplug the board
3. Hold the reset button in
4. Plug in the board
5. Press upload on the IDE
6 Just as `avrdude` is about to run (that's the program that does the actual uploading) - just as the compiling has finished, release the reset button

If you did it right you should be able to upload properly.  If not, you will have to try again from step 1.


body:
Is it possible to burn the bootloader of an arduino redboard using an esp8266 feather? whenever i connect my redboard to my pc the ports list on the ide would just be greyed out. I've looked around online and tried everything I found except burning the bootloader since I didnt have a spare arduino, atmega or a programmer. I have an [EPS8266][1] feather though.

If anyone know whether or not this is possible to do and could walk me through on how to do it if it was.

  [1]: https://www.adafruit.com/product/2821

title: using esp8266 feather to burn bootloader on redboard

Answers: 1

body:
The RedBoard has an FT232 chip for the USB interface.  Flashing the bootloader on the main MCU will have no effect at all on your problem.

While, yes, it is technically possible to use the ESP8266, it's not easy and, since it won't cure your problem of a greyed out port option, isn't worth the effort to try and do it.

Instead, you should be looking at things like your USB ports, USB cables, FT232 drivers, etc on your computer.


body:
In this code i am taking the TID data(20bytes of 160bits) in the form of array according documentation and and its working correctly and getting the output of RFID tags.

Now I just need your guidance that how can i convert the array of 20 Bytes into a single variable or into a double long datatype? or another. Because I have to push it on to my MySQL database server for further processing.

I had tried the following code which works fine

    byte x[10] = "450210921";
    long result = atol(x);
    Serial.print("long value of the byte is: ");
    Serial.println(result);

but when i put the above code into my main code, getting not any error and I am not getting the required output.!

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

    void loop()
    {
      byte response;
      byte myTID[20]; //TIDs are 20 bytes
      byte tidLength = sizeof(myTID);

      //Read unique ID of tag
      response = nano.readTID(myTID, tidLength);
      if (response == RESPONSE_SUCCESS)
      {
        for(byte x = 0 ; x < tidLength ; x++)
        {
          if(myTID[x] < 0x10) Serial.print("0");
          /*temp[x]=(myTID[x], HEX);*/
          //Swapping values into temp variable
          temp[x]=myTID[x];
          Serial.print(temp[x]);
        }
        /*byte x[10] = "450210921";*/
        //Convert a whole array into a single long variable
        long result = atol(temp);
        Serial.print("long value of the byte is: ");
        Serial.println(result);
      }
      else
        Serial.println("Failed read");
    }

title: How to convert byte array into a single variable

Answers: 1

body:
You can't convert 20 bytes to long. Send it as string of hex values. A byte takes two characters in hex, so you will send a 40 characters string, which can be simply decoded back to bytes.

    char str[sizeof(myTID) * 2 + 1];
    const char* hex = "0123456789ABCDEF";
    for (int i = 0; i < sizeof(myTID); i++) {
      str[i * 2] = hex[(myTID[i] >> 4)];
      str[i * 2 + 1] = hex[(myTID[i] & 0x0F)];
    }
    str[sizeof(str)] = 0;
    Serial.println(str);


body:
Here is the schematic I followed:

[![Schematic][1]][1]

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

Here also the link: https://www.circuito.io/app?components=10167,11021,12083,13678,13959

    #include "DHT.h"
    #include "NewPing.h"
    #include <SoftwareSerial.h>
    #define DEBUG true

    SoftwareSerial esp8266(11,10);

    #define DHTPIN 2       // DHT-11 Output Pin connection
    #define DHTTYPE DHT11   // DHT Type is DHT 11 (AM2302)
    #define TRIGGER_PIN 4
    #define ECHO_PIN 3
    #define MAX_DISTANCE 400

    NewPing sonar(TRIGGER_PIN,ECHO_PIN,MAX_DISTANCE);

    float hum;
    float temp;

    DHT dht(DHTPIN, DHTTYPE);

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

      pinMode(TRIGGER_PIN, OUTPUT);
      pinMode(ECHO_PIN, INPUT);

      sendData("AT+RST\r\n",2000,DEBUG);
      sendData("AT+CWMODE=2\r\n",1000,DEBUG);
      sendData("AT+CIFSR\r\n",1000,DEBUG);
      sendData("AT+CIPMUX=1\r\n",1000,DEBUG);
      sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG);
    }

    void loop()
    {
      delay(2000);  // Delay so DHT-11 sensor can stabalize

      hum = dht.readHumidity();  // Get Humidity value
      temp= dht.readTemperature();  // Get Temperature value

      digitalWrite(TRIGGER_PIN, LOW);
      delayMicroseconds(2);
      digitalWrite(TRIGGER_PIN, HIGH);
      delayMicroseconds(10);
      digitalWrite(TRIGGER_PIN, LOW);

      long duration,distance;
      duration = pulseIn(ECHO_PIN,HIGH);

      distance = duration/58.2;

      Serial.print("Humid: ");
      Serial.print(hum);
      Serial.print(" %, Temp: ");
      Serial.print(temp);
      Serial.print(" C, ");
      Serial.print("Distance: ");
      Serial.print(distance);
      Serial.println(" cm");
      delay(50);

      if(esp8266.available())
      is sending a message
      {
        if(esp8266.find("+IPD,"))
        {
          delay(1000);
          int connectionId = esp8266.read()-48;
          /* We are subtracting 48 from the
             output because the read() function returns
             the ASCII decimal value and the
             first decimal number which is 0 starts at 48 */
          String webpage = "
IOT Garbage Monitoring System
";
          webpage += "

";
          if (distance<5)
          {
            webpage+= " Trash can is Full";
          }
          else{
            webpage+= " Trash can is Empty";
          }
          webpage += "

";
          String 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;
          closeCommand+="\r\n";
          sendData(closeCommand,3000,DEBUG);
        }
      }
    }

    String sendData(String command, const int timeout, boolean debug)
    {
      String response = "";
      esp8266.print(command);
      long int time = millis();
      while( (time+timeout) > millis())
      {
        while(esp8266.available())
        {
          char c = esp8266.read();
          response+=c;
        }
      }
      if(debug)
      {
        Serial.print(response);
      }
      return response;
    }

I've been trying to solve this problem for almost a week.

title: Arduino Uno with ESP8266-01 with AT

Answers: 1

body:
If you want to use esp-01 over SoftwareSerial, you must set the AT firmware's default baud rate to 9600 baud. The default baud rate of AT firmware is 115200 baud. SoftwareSerial can't work at this speed.

To change the baud rate you must have a way to communicate with AT firmware at the default baud rate of 115200 baud. You can use the USB adapter of the Uno. Upload BareMinimal sketch from Examples to Uno to make it silent and connect the esp-01 to RX and TX pins of the Uno.

Connect RX to RX and TX to TX to have the cross connection to USB of the Uno. Then connect from Serial Monitor to esp-01 at 115200 with "Both line end characters" set. Try some basic AT commands and then still at 115200 baud send the command to change the default baud rate AT+UART_DEF=9600,8,1,0,0

----------

In setup() in sketch `begin` for SoftwareSerial is missing. Add  `esp8266.begin(9600);`

----------

Uno pin 11 is RX of software serial, pin 10 is TX. The RX pin 11 must connect to TX pin of esp-01. Same applies for TX pin 10. It must connect to RX pin of the esp-01.

On the Fritzing schema on Uno pin 11 is green wire and on esp-01 TX is green wire. But the green wire is on sides of the level converter not on the same position. The conclusion is that you have RX connected to RX not to TX. Switch wires on best at level converter.

----------

The 3.3 V pin of some Uno clones can't supply enough current for WiFi operations of the esp8266. You need to convert to 3.3 V from Uno 5 V pin or use a separate 3.3 V power source for the esp-01.


body:
I am trying to write some code, which I barely grasp - but it's coming along! But I think I've hit a wall that I could using some help getting  over...

I'm not asking for you to fix my code - I know that's not how I am going to learn, maybe explain why my code isn't doing what I want it to, and/or some resources I can using to learn about it.

I think it has something to do with me trying to use the same pins in the initialization part since the error is about a conflicting declaration..

Here's my breadboard layout if this helps too:

[![My breadboard][1]][1]

    //ABOUT - This programs goal is to make a button cycle through three    different 'modes'
    //Mode 1 - make a RGB LED cycle through its colors
    //Mode 2 - make the same RGB LED fade-cycle through its colors
    //Mode 3 - make the same RGB LED blink on-off all three colors at once
    //Additional modes may follow but this is the beginning.

    //currently all my initialization code is from three different programs and I think that's why parts are not working.. I think
    //I can share the mode initialization code for each mode....?  But the face code uses the uint8_t vs just int so maybe not?

    //Button Cycle - this is the first part of my code, designed to teacah me how to make a button cycle through to different parts of the code

    int counter = 0;
    int switchPin = 13;
    int LEDB = 11;
    int LEDG = 10;
    int LEDR = 9;

    //RGB LED Cycle Circuit - mode 1
    const int redLED=3; //red LED connects to digital pin 8
    const int blueLED=5; //blue LED connected to digital pin 7
    const int greenLED=6; //green LED connected to dogotal pin 6

    //RGB LED Fade Circuit - mode 2
    const uint8_t redLED = 3;  // pin connected to the red LED - I don't understand why this code says const uint8_t  -
    const uint8_t blueLED = 5;  // pin connected to the green LED
    const uint8_t greenLED = 6; // pin connected to the yellow LED

    void setup()
    {
      Serial.begin(9600); //I added this to help learn what the counter was doing
      pinMode(switchPin, INPUT);
      pinMode(LEDR, OUTPUT);
      pinMode(LEDG, OUTPUT);
      pinMode(LEDB, OUTPUT);
    }

    void loop() {
      //Handle input
      int switchVal = digitalRead(switchPin);
      if(switchVal == LOW) //changed from HIGH which was making the modes appear to change randomly - may come in useful later but not what I want initially
      {
        delay(500);
        counter ++;
        Serial.println(counter); //prints value of counter to serial monitor so I can see why it appeared to be random
        //I learned that when the switchVal == HIGH was in place the counter would cycle continuously. Making each button
        //press appear random. Changing this to LOW made the counter wait for a LOW event before counting. Increasing the
        //delay to half a sec gives time to release the button before the counter continues.

        //Reset count if over max mode number
        if(counter > 3)
        {
          counter = 1; //in serial monitor you will see that the counter goes to 4 but this code tells the program that 4 = 1 so it runs the right mode
        }
      }
      else
        //Change mode 1
        switch (counter) {
        case 1:
          analogWrite(LEDB, 000);
          analogWrite(LEDG, 000);
          analogWrite(LEDR, 255);

          //start LED Cycle - this is simply pasted in from the LED cycle program - seems to work fine

          digitalWrite(redLED,HIGH);//turns the LED on
          delay(100);//waits 3 seconds
          digitalWrite(redLED,LOW);//turns the LED off
          digitalWrite(greenLED,HIGH);//turns the LED on
          delay(100);//waits 3 seconds
          digitalWrite(greenLED,LOW);//turns the LED off
          digitalWrite(blueLED,HIGH);//turns the LED on
          delay(100);//waits 3 seconds
          digitalWrite(blueLED,LOW);//turns the LED off
          break;

        //mode 2 code
        case 2:
          analogWrite(LEDR, 000);
          analogWrite(LEDB, 000);
          analogWrite(LEDG, 255);

          //LED Fade Cycle
          // Fade an analog pin up and down.
          void fade(uint8_t pin);
          {
            for (int i = 1; i <= 255; i=i+5) {
              delay(10);
            }
            for (int i = 254; i >= 0; i=i-5) {
              delay(10);
            }
          }
          //void loop(); - think I can only have one void loop so I'm commenting this out for now..
          {
            //Serial.println(F("Fading GREEN."));
            fade(redLED);
            //Serial.println(F("Fading BLUE."));
            fade(blueLED);
            //Serial.println(F("Fading YELLOW."));
            fade(greenLED);
          }
          break;

        //mode 3 not coded yet - waiting to make mode 2 work
        case 3:
          analogWrite(LEDG, 000);
          analogWrite(LEDR, 000);
          analogWrite(LEDB, 255);
          break;
        }
    }

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

title: Trying to understand how to make a program do three things with a button press

Answers: 3

body:
There are two immediate things I can see wrong:

1. You have two sets of the same pin definitions. You only want one set. Both sets are identical - once it's defined its defined - you can't define it again as the same thing.
2. You seem to have a function defined in the middle of your loop() function.  That can't work - functions have to be separate things. (also you don't want a `;` in your function definition...)

body:
You've used the blue lower rail for Ground but used the red lower rail (usually used for +5v) as a simple connection point. It's not wrong but it's unusual enough to be confusing to readers. The choice of red  button-signal wire on the red rail also strongly suggest a connection to +5v even though that is not the case here.

The buttons, "tact" switches, are confusing by design (see picture below). Each pair of pins curved toward each other (I marked one with a red arrow) are the physically *same* pin and always connected to each other. The *pairs* are connected to each other only when the button is pressed. It's really easy to miss that and insert the button 90deg either way from what you intended. Fritzing's button icon doesn't show the orientation either. Yours may well be correct - it's just a pitfall to be aware of.

 [![Typical "Tact" switch][1]][1]

`void fade(uint8_t pin);` doesn't define a function - it declares that one exists somewhere else. I think you meant `void fade(uint8_t pin){ ... }` (note no semi-colon), which would define the function, if that were a proper location to do so. But in C and C++, functions may not be defined within other functions (loop(), in this case). Fix the definition of 'fade' and move it to above 'setup()'. That will properly define it and make it usable from within the loop() function.

The braces, {}, where you tried to define a second loop function are unnecessary (and, you're correct, you can't define more than one function with the same name and signature (parameter count & types, and return type). But you don't need another `loop()`; the code contained in the {} - three calls to the fade function - remain part of `case 2:`.

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

body:
I think what you are missing is a pulldown resistor for the button. Simply put, a pulldown resistor is a resistor pulls down the input reading to 0 when the button is not pressed. Without the pulldown resistor, the value read in the `digitalRead` will float around giving inaccurate results.

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

Above is a circuit showing how the pulldown resistor should be wired with a button.

If you would like to learn more about pulldown resistors, please refer to [this page describing buttons in the Arduino Website][2].

This is just a hardware issue I noticed; hopefully, this will help you out in addition to the other recommendations given.

As a side note, a pull-up resistor can also be used, and in this case, the value will be 1 when the button is not pressed.

  [1]: https://i.stack.imgur.com/eUrjX.png
  [2]: https://www.arduino.cc/en/Tutorial/Button


body:
I have purchased an MG995 servo (4.8-7.2V operating voltage, 170MA no load operating current draw) and will power this using a 5V, 2A mains plug pack. Do I need a breadboard to connect this with my Arduino (which will itself be powered through its usb port)? Or is it possible to connect the servo with the Arduino directly?

If it's possible to connect it directly, which pins should I be using on the Arduino? Will it look something like this:
[![Servo to a RedBoard][1]][1]

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

except the red wire (and black wire?) connects to the external power supply?

Any answers (or links to relevant tutorials which have all three of these components) would be welcome. Thanks!

title: Connecting an Arduino to a servo with an external power supply

Answers: 2

body:
You did not indicate how you plan to connect the 5V, 2A mains plug pack to the Arduino board. If you want to use the barrel jack on the left, please note the listed input voltage. 5 volts is too low if you plan on powering the Uno board with the external power source. There is a voltage comparator circuit that will switch over to the barrel jack power if the voltage is high enough.

But since you are not really asking about powering the Uno, just the servo, then it gets interesting. The Sparkfun schematic shows a diode in line with the barrel connector and the Vin connection point on the board. This could provide a power path for the servo. The problem is that the servo voltage range 4.8 volts on the low end. With a 5 volt output of your external power supply, a voltage drop from the diode would give the servo almost enough voltage to meet the 4.8 volt minimum but not quite.

You are better off to not connect the servo power through the Uno board. If you had a somewhat higher voltage supply, at least 6 volts, then it would be ok. But if it is only 5 volts then it really is at a very marginal level.

body:
Your question is not very concise, but I'll try to hit the main points.

I'm going with the assumption that your "Arduino" is the Sparkfun Redboard. The Redboard has a current limit of <800mA (heat management on the Redboard probably lowers this number even more), as per the [LM1117 voltage regulator][1] listed in the provided [RedBoard schematic][2], and a minimum input voltage of 7V. You won't be able to power your Arduino with the 5V2A powerbrick. If you are powering the RedBoard through the standard USB, then it will typically be limited to 500mA.

Are you sure your servo has a no-load draw of 170mA? That's really high for a servo. If it does, then I'm assuming it's a large servo that likely has a high stall current draw, so 800mA from the Redboard's on-board regulator won't cut it, nor a USB port.

To power your servo externally, wire the servo and Redboard according to the schematic below. The power supply is indicative of your 5V 2A "wall wart". It's important to note that you need to connect the ground of the the power supply to the ground of the Arduino. For controlling the servo, check out [Adafruit's servo tutorial][3]. You will also need to provide power to your Arduino via USB or a DC barrel jack with a power brick that outputs >= 7v.

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

  [1]: http://www.ti.com/lit/ds/symlink/lm1117.pdf
  [2]: https://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/RedBoard-V22.pdf
  [3]: https://learn.adafruit.com/adafruit-arduino-lesson-14-servo-motors/overview
  [4]: https://i.stack.imgur.com/3QHEv.png