message:
How to calculate actual Baud Rate and its percent error?

I am using an Arduino Uno, and I need to create a program that calculates the actual baud rate and the percent error for all standard baud rate in Arduino monitor program.

body:
First, look at the code used by the Arduino core library to configure
the USART baud rate register: it's in
[`HardwareSerial::begin()`][serial begin]. The general formula is

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

    uint16_t baud_setting = (F_CPU / 4 / baud - 1) / 2;

but beware of the hard-coded exception. You can replicate that part of
the code in your own.

Then, look at the ATmega328P datasheet. More specifically, at section
[24.4.1. Internal Clock Generation – The Baud Rate
Generator][datasheet]. Here you find the formula

    BAUD = F_CPU / (8*(UBRR0 + 1))

assuming the `U2X0` bit has been set (again, beware of the hard-coded
exception). Combine both formulas and you get the actual baud rate.

[serial begin]: https://github.com/arduino/Arduino/blob/1.8.5/hardware/arduino/avr/cores/arduino/HardwareSerial.cpp#L103

[datasheet]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf#page=227


sender: user

message:
LED blinking count with LDR sensor

How to count +1 all the time if LED blinks with LDR sensor

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

If i turn on led it must count into serial monitor 1 and if i turn off led and turn on again then it counts 2.

To turn on led I must put my hand into LDR sensor.

It also looping text in serial monitor "First LDR sensor is Dark".

    int ledPin1 = 7;
    int ledPin2 = 8;
    int ledPin3 = 9;
    int ldrPin1 = A0;
    int ldrPin2 = A1;
    int ledTest = 200;
    int ldrStatus1 = 0;
    int ldrStatus2 = 0;
    int ledCheck1 = 0;
    int ledCheck2 = 0;
    int Count = 0;

    void setup() {

      Serial.begin(9600);
      pinMode(ledPin1, OUTPUT);
      pinMode(ledPin2, OUTPUT);
      pinMode(ledPin3, OUTPUT);

      pinMode(ldrPin1, INPUT);
      pinMode(ldrPin2, INPUT);
    }

    void loop() {

      ldrStatus1 = analogRead(ldrPin1);
      ldrStatus2 = analogRead(ldrPin2);

       if (ldrStatus1 <= ledTest) {
        digitalWrite(ledPin1, HIGH);
        Serial.println("First LDR is Dark");
        ledCheck1 = 1;
        Count++;
        Serial.println(Count);
       } else {
        digitalWrite(ledPin1, LOW);
        ledCheck1 = 0;
       }

       if (ldrStatus2 <= ledTest) {
        digitalWrite(ledPin3, HIGH);
        Serial.println("Second LDR is Dark");
        ledCheck2 = 1;
        Count++;
        Serial.println(Count);
       } else {
        digitalWrite(ledPin3, LOW);
        ledCheck2 = 0;
       }

       if ((ledCheck1 == 1) && (ledCheck2 == 1)) {
        digitalWrite(ledPin2, HIGH);
       Count++;
        Serial.println(Count);
       } else {
        digitalWrite(ledPin2, LOW);
       }

    }

At the moment it counts when it is turned on, like seconds..
How to fix or make it work correctly?

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

sender: assistant

body:
Use state change detection and hysteresis for counting pulses in an analog signal.

    const int lowerThreshold = 150;
    const int upperThreshold = 200;

    const uint8_t analogPin = A0;
    const uint8_t ledPin = LED_BUILTIN;

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

    void loop() {
      static bool state = LOW;
      static unsigned int counter = 0;

      int analogValue = analogRead(analogPin);
      if (state == HIGH) {
        if (analogValue < lowerThreshold) {
          state = LOW;
          counter++;
          Serial.println(counter);
          digitalWrite(ledPin, LOW);
        }
      } else { // state == LOW
        if (analogValue > upperThreshold) {
          state = HIGH;
          digitalWrite(ledPin, HIGH);
        }
      }
    }

This sketch basically applies a software Schmitt trigger to the analog input signal, and increments the counter on each falling edge. (Rising edge of light intensity, because your LDR configuration inverts the signal.)
[![Schmitt Trigger Waveforms][1]][1]

The red waveform is the analog input from the LDR. The gray rectangular wave is the `state` (and the state of the LED). The counter is incremented at each black, vertical dashed line.

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


message:
Can I use atmega328P without capacitors?

I need to use atmega328P without arduino board, so far I know that I will need `16MHZ Quartz Resonator` and two `22nf capacitors`. However, I have seen that other people are using atmega328P without capacitors.

What is the role of those capacitors? Can I use atmega328P without capacitors?

body:
Those specific capacitors form part of the resonant clock oscillator circuit. If you are using a quartz crystal then they are required. You can't do without them.

If you use a 16MHz *ceramic resonator*, however, they don't need the capacitors (they're built into the resonator).

Also, if you have your ATMega328P on a breadboard the capacitance of the board itself is sometimes enough to "get it working", though as soon as you transfer your circuit to a permanent PCB it will suddenly stop working for no apparent reason.


message:
Connect Arduino to Socket IO Webserver via Esp8266

As part of a project I want to receive data on my arduino uno via a sensor, which is working fine. This data should be sent to a webserver where a node js with socket io is running. Therefore i bought a esp8266 and the corresponding adapter (https://www.amazon.de/gp/product/B01LZLVEJ4/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1).

In the IDE I have the following code:

        #include <SoftwareSerial.h>

        SoftwareSerial esp8266(2, 3);

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

          Serial.println("Started");

          // set the data rate for the SoftwareSerial port
          esp8266.begin(115200);
        }

        void loop() {
          if (esp8266.available()) {
            Serial.write(esp8266.read());
          }
          if (Serial.available()) {
            esp8266.write(Serial.read());
          }

        }

I use the serial monitor to perform my AT Commands and it seems to work some times, however there seems to be a problem with the output, for example if I type the command AT+CWLAP to display the Access Points. If I do so, it outputs something like:

        +CWLAP:(3,"WLAN-32CC39",-73,"10:c6:0f:2c:32:cc",1,65,0)
        +CWLAP:(3,"F1e:,:oMc:0(x8:1LN⸮⸮⸮:b),k7:,(-,36Ao-2,
        (e0e,C".66,Cwe8:"+L,:"+27:6L W79",944,Ab,::0(ot230( -5,CTO940PBc,63+3y8:")3,dc3
        "P4-ze6P!"80,3716

I should also note, that even if I input the same, the response differs, and sometimes it is just single characters that are wrong, e.g. "wigi" instead of "wifi". I tried different baud's for the esp8266 but the current one produces the least problems. So my questions here are:

1: Is there anything I am currently doing wrong while connecting to my local wifi network?

2: If there is a connection made, is there any way to connect to a socket io server as a client? Most Tutorials I have found have the arduino as a server. However, I want to have it as a client which communicates to a server. Therefore it should both be able to send and receive messages to/from the server.

Thanks in advance!

body:
### Using the ESP8266 in general
The easiest, most flexible, and most efficient way is to [program the ESP8266 directly](https://tttapa.github.io/ESP8266/Chap01 - ESP8266.html).
If it is possible, have it replace the Arduino entirely. To do this, it is best to get an ESP8266 development board that breaks out all IO pins and has a USB interface for easy programming. Programming these development boards is just like programming an Arduino: plug in the USB connection and hit upload in the Arduino IDE. One of my favourites is the WeMos D1 mini (around $3.50 from China).
The ESP8266 is a very powerful microcontroller on its own: it has a 32-bit processor that runs 10 times faster than an Arduino Uno, it has up to 4MB of flash memory (vs 32KB on the Uno), 160KB of RAM (vs 2KB on the Uno). It has 11 digital IO pins, an analog input, support for I²C, SPI, PWM, etc., just like an Arduino. If you use AT commands, you don't use its full potential.

### Your specific situation
Given that you already bought an ESP-01 + adapter that only gives you access to the UART, connecting the sensor to the ESP directly is probably not possible.
In this case, you can do one of three things:

1) Program the ESP8266 directly:
Write a program that just reads a number from the serial port, and sends it to the server over WiFi.
This is the easiest, because you can use all features of the ESP8266, and you don't have to change the program that you wrote for the Arduino (it should just measure the sensor value, and send it to the ESP8266 over the serial port, this is exactly the same as sending it to the serial monitor on your computer).

2) Don't program the ESP8266, but use an AT commands library on the Arduino. (For example WiFiEsp)
The downside is that you have to make significant changes to your Arduino sketch, and that you cannot use all of the functions and resources of the ESP.

3) Control the ESP8266 using AT commands yourself, without any libraries.
This is very cumbersome, and is a complete waste of time, IMHO.

### Practical
*Programming the ESP8266 directly*
To program the ESP8266 directly (both with an Arduino and stand-alone), you need a USB-to-Serial converter. You can either use something like an FT232 (3.3V) or an Arduino. How to program it is covered [here][1]. If you use an Arduino as USB-to-Serial adapter, the right connections are TX-TX, RX-RX.

*Using AT commands or an AT commands library*
If your Arduino has a hardware UART that is not used for programming the Arduino (e.g. Arduino Mega, Arduino Leonardo, Arduino Due, ...), you can use this UART for communicating with the ESP8266. The right connections are TX-RX, RX-TX. You can use any baud rate that's supported by both devices (9600 - 921600).
If your Arduino doesn't have an extra hardware UART, you'll have to use the UART on pins 0 and 1, that's used for programming, and you'll have to disconnect the ESP8266 every time you upload new firmware to the Arduino.
Alternatively, you can use SoftwareSerial. Keep in mind that this is far from an optimal solution, as it uses a lot of resources, it is very slow, and data might get corrupted if you spend a lot of time in interrupts on the Arduino.
To use the ESP8266 with SoftwareSerial, you need to lower the baud rate to 9600 baud. To do this, first upload an empty sketch (bare minimum) to the Arduino to make sure that the hardware UART is not used. Then connect the ESP8266 to pins 0 and 1: TX-TX, RX-RX.
Open the Serial Monitor from the Arduino IDE, and select the baud rate that the ESP8266 is currently operating at. (This is probably 115200, but it could be something else.) Select "Both NL + CR" as the line ending, and send "AT" (without the quotes) to verify that it is working. If everything works, it should answer with "OK". If it doesn't, check your hardware, or try a different baud rate. Finally, send "AT+UART_DEF=9600,8,1,0,0" to set the baud rate to 9600 baud. Then change the baud rate of the serial monitor to 9600 as well. Send "AT" again to verify that it is working.
Now you can connect the ESP8266 to the SoftwareSerial pins, using a baud rate of 9600 baud.

_Edit_: The WebSocket protocol is not supported using AT commands, so you have no other choice but to program the ESP8266 directly.

  [1]: https://tttapa.github.io/ESP8266/Chap02 - Hardware.html


message:
Blink without delay for 5 times every 20 seconds

I'm trying to write a blink without delay code that will wait 20 seconds, then blink 5 times, then wait another 20 seconds - rinse and repeat.

Here's the minimal code I wrote:

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

    if (currentTime % 20000 == 0) {
      for (int x = 0; x <= 5; x++) {
        if (currentTime % 500 == 0) {
          if (solenoid == LOW) {
            solenoid = HIGH;
          }   else {
            solenoid = LOW;
          }
          digitalWrite(solenoidpin, solenoid);
        }
      }
    }
    }

All this seems to do is set solenoid to HIGH and keep it there. If I get rid of the for loop and the second if statement, I can get it to switch between low and high every 20 seconds, but adding the if and for loops seems to kill it. Any thoughts on how to make this work?

body:
Here is a solution:

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

    #define INTERVAL 20000L
    #define BLINK_TIMES 5
    void loop()
    {
     static unsigned long lastBlink = 0;
     static int count = 0;

     unsigned long now = millis();

     if(count > 0) {
      count -= blink();
      lastBlink = now;
     } else {
      if(now - lastBlink >= INTERVAL) {
       count = BLINK_TIMES;
      }
     }
    }

    /*
     * Do one blink.
     * Return 1 when blink is done.
     */
    int blink()
    {
      static unsigned long lastFlip = 0;
      static int count = 0;
      bool last = false;

      unsigned long now = millis();

      if(now - lastFlip >= 500) {
     digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
        Serial.print(now / 1000); Serial.print(". "); Serial.println("blink");
     lastFlip = now;
        count++;
        if (count == 2) {
          count = 0;
          last = true;
          }
       }

       return (last) ? 1 : 0 ;
    }

The `count` variable controls when to blink and how many times. While it's zero, no blinking.

When not blinking, it keeps comparing actual time with the last time it blinked. When the time exceed 20s, it puts `count` to five, and in the next loop, the blinking start.

Variables are declared `static` so they keep their values between `loop` executions.


body:
    // assuming blinking is 500ms ON, 500ms OFF, so 4500ms for 5 blinks.

    int tick = (currentTime/500) % 49;
    // if one tick is 500ms, that means,
    //    1 tick ON, 1 tick OFF, 1 tick ON, ... , 1 tick ON, 40 ticks OFF (for a total of 49 ticks)
    if( ( tick < 5*2 ) && ( tick%2==0 ) )// only turn ON the led on the first 10 ticks (5 ON; 5 OFF)
                                         //  and only if the number of ticks is ODD
        digitalWrite(solenoidpin, HIGH);
    else
        digitalWrite(solenoidpin, LOW);

What I did was convert the milliseconds in to `ticks` of 500 ms. Then based on the `tick` value, update the led.

PS I tested it on a Arduino Pro Mini


message:
Controlling multiple solenoids with arduino

I was wondering how I could connect multiple 12v solenoids (more than the 53 allowed on mega because of the pins) on the Arduino Mega 2560 to get it to control the keys on a piano/keyboard/organ. Would 74HC595 shift register work for it with the 12v? (Many of them) Because there are so many high voltage solenoids is it possible to control a few of them at a time? I was wondering if someone has a link to somewhere that I could refer to. Thanks

body:
Arduino I/O pins, and the output pins of 74HC595 shift registers are logic-level outputs, and are not intended to drive power-hungry items like solenoids. In either case (direct I/O or shift registers) you need to use the logic signal from the output pin to drive *something else* that switches the 12V source.

That *something else* can be a MOSFET or a relay, though often even relay coils are themselves driven by a MOSFET or other transistor that is switched by a microcontroller output pin.

One of the many search results that describe this is at http://hades.mech.northwestern.edu/index.php/Driving_using_a_single_MOSFET


body:
the shift register has 2 features that will help you:

1. a latch pin. When a the storage register pin is kept low the outputs won't change this allows you to shift in a new value without perturbing the outputs.

2. a Qh' output this is the output from the last bit that bypasses the normal output. If you connect that to the next shift register you can daisy chain several registers.

The outputs of the chip are not meant to driver significant currents. Instead use them to drive a mosfet that in turn drives the relay. There are boards that contain all the support circuitry needed to drive relays using low power signals.


message:
Getting better results from DHT22

I am working on a dew point sensor, and I am using the Arduino Uno board with the DHT22 sensor. I have it taking a reading once ever 2 seconds and I am using the DHT.h library.
The problem I am having is when I compare the values to our standard here the Humidity reads high and the Temp reads low. Is there anyway to get the values to read closer to what the standard is?

body: Using a RH and Temp Calibrator I had access to I was able to get better results by all lines to adjust the RH and Temp to a better value. Basically a correction equation.


message:
Using different ADC channels

How could the same code be used with different ADC channels?

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

    const byte adcPin = 0;  // A0

    const int MAX_RESULTS = 100;

    volatile int resultsV [MAX_RESULTS];
    volatile int resultsI [MAX_RESULTS];

    volatile int resultNumber;

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

      // reset Timer 1
      TCCR1A = 0;
      TCCR1B = 0;
      TCNT1 = 0;
      TCCR1B = bit (CS11) | bit (WGM12);  // CTC, prescaler of 8
      TIMSK1 = bit (OCIE1B);
      OCR1A = 338;
      OCR1B = 338;   // 39 = 20 uS - sampling frequency 50 kHz

      ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF);   // turn ADC on, want interrupt on completion
      ADCSRA |= bit (ADPS2);  // Prescaler of 16
      //  ADCSRA |= (1 << ADPS1) | (1 << ADPS0);    // 8 prescaler for 153.8 KHz
      ADMUX = bit (REFS0) | (adcPin & 7);
      ADCSRB = bit (ADTS0) | bit (ADTS2);  // Timer/Counter1 Compare Match B
      ADCSRA |= bit (ADATE);   // turn on automatic triggering
    }

    // ADC complete ISR
    ISR (ADC_vect)
    {
      resultsV[resultNumber++] = ADC;

      //resultsI[resultNumber++] = ADC;

      if (resultNumber == MAX_RESULTS)
      {
        ADCSRA = 0;  // turn off ADC
      }
    }

    EMPTY_INTERRUPT (TIMER1_COMPB_vect);

    void loop () {

      while (resultNumber < MAX_RESULTS)
      { }

      for (int i = 0; i < MAX_RESULTS; i++)
      {
        Serial.print( resultsV);
        Serial.print("   ");
        Serial.print( resultsI);
        Serial.println();
      }
      resultNumber = 0;
      ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF) | bit (ADPS2) | bit (ADATE);
      // turn ADC back on
    }

body:
From what I understand, you want to read _two_ ADC channels
simultaneously. First, you have to understand that you cannot read them
exactly at the same time, as you have a single ADC. What you can do,
however, is read them one after the other: you read the V channel, then
the I channel, then the V channel again, etc. This means you will have
to change the multiplexer setting (the `ADMUX` register) in between the
readings. The most convenient place to do this is within the ADC ISR,
the logic of which becomes:

1. Save the value that has just been read
2. switch the multiplexer to the other channel
3. turn off the ADC if you are done.

Example code (not tested):

    const byte PIN_V = 0;  // A0
    const byte PIN_I = 1;  // A1

    // ADC complete ISR.
    ISR(ADC_vect)
    {
        if (ADMUX & 7 == PIN_V) {
            // We have just read the V channel.
            // Save the value and switch to the I channel.
            resultsV[resultNumber] = ADC;
            ADMUX = bit(REFS0) | PIN_I;
        } else {
            // Otherwise we completed a (V, I) pair, we can increment
            // resultNumber.
            resultsI[resultNumber++] = ADC;
            ADMUX = bit(REFS0) | PIN_V;
        }

        // Turn off the ADC when done.
        if (resultNumber == MAX_RESULTS)
            ADCSRA = 0;
    }

Note that this example assumes you do the readings in the (V, I) order.
Thus, within `setup()`, you have to initialize the multiplexer for the V
channel, as in

    ADMUX = bit(REFS0) | PIN_V;


message:
Communication between Arduino Uno and Mega

I am working on a project which uses a set of sensors (HC-SR04). These sensors use pins 2 to 13 of the Arduino Uno. Here you can find the board:

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

I also want to add an MP3 shield ([VS1053B][2]) to it and it fills all the pins on Arduino. So I decided to add an Arduino Mega and add the sensors to it and use the Arduino Uno and MP3 shield. The problem is with connecting these two Arduinos. As I said the MP3 shield fills A4 and A5 pins too, so I can not use them to communicate with the Mega. What other options do I have?

  [1]: https://i.stack.imgur.com/Q6ynm.jpg
  [2]: https://www.waveshare.com/music-shield.htm

body: You can multiplex the trigger line. With 3 pins you can address up to 8 sensors. If you multiplex the reply line as well (so you can abstract out the latency) you only need 2 additional pins for the actual trigger and reply.


body:
Salam, you could somewhat multiplex the HC-SR04 Ultrasonic Sensor by using I2C(IIC) instruction on how to convert those into I2C and by using OctoSonar library can be [found here][1] so that only the SDA(pin16) and SCL(pin17) pins on your Arduino UNO will be used.
https://hackaday.io/project/19950-hc-sr04-i2c-octopus-octosonar

  [1]: https://hackaday.io/project/19950-hc-sr04-i2c-octopus-octosonar


message:
client.connect() problem

I'm using XAMPP(version-7.2.1) server in my PC to publish my arduino sensor data in a webpage. I have tried the code above and it shows an error like:

> Ethernet configured via DHCP
>
Connecting...
>
-->connection failed

I have also followed the steps given in this https://forum.arduino.cc/index.php?topic=40448.0 but it doesn't work.
The code runs till client.connect() after that it doesn't get inside the if(client.connect(server,80)) loop.

The arduino's ethernet shield is assigned an IP by the PC via ICS.
I believe that the problem is in connecting the arduino to the localhost but I don't know how to resolve it. The XAMPP server seems to run properly. I have checked it logs.

I have also posted at https://forum.arduino.cc/index.php?topic=525947.0.

Hope someone can help me

Thanks in advance
<!-- language: lang-cpp -->

    #include <SPI.h>
    #include <Ethernet.h>
    #include "DHT.h"
    DHT dht;
    const int sensor_pin = A1;
    unsigned int ldr;
    byte mac[] = {  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    IPAddress ip(192, 168, 1, 33);
    char server[] = "192.168.1.7"; // IMPORTANT: If you are using XAMPP you will have to find out the IP address of your computer and put it here (it is explained in previous article). If you have a web page, enter its address (ie. "www.yourwebpage.com")
    EthernetClient client;

    void setup() {
      Serial.begin(9600); // Serial.begin starts the serial connection between
      computer and Arduino
      Ethernet.begin(mac, ip);
      Serial.println("Ethernet configured via DHCP");
      delay(1000);
      dht.setup(2);
    }

    void loop() {
      delay(dht.getMinimumSamplingPeriod());  /* Delay of amount equal to sampling period */
      float soilmoisture;
      int sensor_analog;
      sensor_analog = analogRead(sensor_pin);
      soilmoisture = ( 100 - ( (sensor_analog / 1023.00) * 100 ) );
      float temperature = dht.getTemperature();
      float humidity = dht.getHumidity();
      ldr = analogRead(A0);

      Serial.println("Connecting...");
      // Connect to the server (your computer or web page)
      if (client.connect(server, 80)) {
        Serial.println("--> Connected");
        client.print("GET /write_data.php?"); // This
        client.print("temperature="); // This
        client.print(temperature); // And this is what we did in the testing section above. We are making a GET request just like we would from our browser but now with live data from the sensor
        client.print("&humidity="); // This
        client.print(humidity); // And this is what we did in the testing section above. We are making a GET request just like we would from our browser but now with live data from the sensor
        client.print("&soilmoisture="); // This
        client.print(soilmoisture); // And this is what we did in the testing section above. We are making a GET request just like we would from our browser but now with live data from the sensor
        client.println(" HTTP/1.1"); // Part of the GET request
        client.println("Host: 192.168.1.7"); // IMPORTANT: If you are using XAMPP you will have to find out the IP address of your computer and put it here (it is explained in previous article). If you have a web page, enter its address (ie.Host: "www.yourwebpage.com")
        client.println( "Content-Type: application/x-www-form-urlencoded" );
        client.println("Connection: close"); // Part of the GET request telling the server that we are over transmitting the message
        client.println(); // Empty line
        client.println(); // Empty line
      }
      else {
        // If Arduino can't connect to the server (your computer or web page)
        Serial.println("--> connection failed\n");
      }
      client.flush();
      client.stop();
      // Give the server some time to recieve the data and store it. I used 10 seconds here. Be advised when delaying. If u use a short delay, the server might not capture data because of Arduino transmitting new data too soon.
      delay(10000);
    }
My PHP code is as follows:

    <?php
    // Prepare variables for database connection
    $dbusername = "x";  // enter database username, I used "arduino" in step 2.2
    $dbpassword = "y";  // enter database password, I used "arduinotest" in step 2.2
    $server = "localhost"; // IMPORTANT: if you are using XAMPP enter "localhost", but if you have an online website enter its address, ie."www.yourwebsite.com"
    $dbname = "arduinotest1";
    // Connect to your database
    $dbconnect = mysqli_connect($server, $dbusername, $dbpassword,$dbname);
    if (!$dbconnect) {
        die("Database connection failed: " . mysqli_connect_error());
    }
    $dbselect = mysqli_select_db($dbconnect, "arduinotest1");
    if (!$dbselect) {
        die("Database selection failed: " . mysqli_connect_error());
    }
    // Prepare the SQL statement
    $sql = "INSERT INTO arduinotest1.tabletest2 (temperature,humidity,soilmoisture) VALUES ('".$_GET["temperature"]."','".$_GET["humidity"]."','".$_GET["soilmoisture"]."')";
    // Execute SQL statement
    mysqli_query($dbconnect,$sql);
    ?>

body:
Check the server ip is correct and server is running. Then check the return value of client.connect() function. If it's a 0 then most likely your server is behind a firewall. If so, unblock the apache server to pass through it. I had this similar issue with wamp.

Although 0 is not a valid return code for client.connect() according to http://www.arduino.cc/en/Reference/ClientConnect , it weirdly returns a 0. Oherwise it will give you a clue.

Also use IPAddress class for assigning the server address instead of using char [].


body:
As far as I can see, when you call `client.connect(server, 80)`, you call it with char[] variable that holds `char server[] = "192.168.1.7"`. And from library code it seems that it will call function with those parameters which will try to resolve dns but can't do it and returns `0`.

It calls: `int EthernetClient::connect(const char * host, uint16_t port)`
,
when it should call: `int EthernetClient::connect(IPAddress ip, uint16_t port)`

Source code: [https://github.com/arduino-libraries/Ethernet/blob/master/src/EthernetClient.cpp][1]

So you need to change `char server[] = "192.168.1.7";` to `IPAddress server(192,168,1,7);`
That way it will call the right connection -function and wont get stuck with dns.

*Edit: added details*

  [1]: https://github.com/arduino-libraries/Ethernet/blob/master/src/EthernetClient.cpp


message:
Confusion over Transistors for a switching circuit with an Arduino Mega 2560

Apologies if this is a stupid question asked by a noob, but I've looked around to try and find the answer and just can't work it out.

Basically, I'm making a project on thingiverse (Glitch's MK2 Stargate), and I've tried all sorts of different transistors with my circuit, I just can't get it to work properly.
Could you please advise which Transistor would work for the following circuit:

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

It's a basic thing, but the plan I was originally working from on thingiverse called for BC548BU transistors, however, the LEDs they were using were surface mount, and I am trying the same thing with 3mm standard LEDs. The BC548BU didn't work right on the normal LEDs.

I'm a total noob with this, but I've been trying to match the **Base** pin on the Transistor voltage output of my Arduino, but not sure if I'm doing the right thing. Can anybody help?

Thanks
-Dave

p.s. I have a load of transistors already (listed below), if any of these work, that would be great, if not, I will order the correct ones. The only one that seemed to match Data with the BC548 is the S9014, but it didn't seem to work at all, unless my understanding of the wiring of Transistors needs adjustment.

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

  [1]: https://i.stack.imgur.com/8WnQ4.png
  [2]: https://i.stack.imgur.com/OlNjb.png

body:
A transistor amplifies current, not voltage.

The first thing to check is the current of your LEDs. In your current configuration, it is between 25 and 30 mA. This is too high for most LEDs. Check the datasheet of your LEDs for the actual forward voltage, and current rating.
To calculate the value for the resistor in your circuit, use Kirchhoff's and Ohm's laws. According to Kirchhoff: VResistor + 3 VLED = 12 V. Let's assume that the LED's forward voltage drop VLED = 1.8 V. This means that VResistor = 12 V - 3 VLED = 6.6 V. Ohm's law will then tell you the relationship between the voltage across the resistor and the current through it: R = VResistor / I. The current through the resistor is the same as the current through the LEDs. Let's assume that this is 20 mA. Therefore: R = VResistor / I = 6.6 V / 0.020 A = 330 Ω.

The next thing to calculate is the resistor between the Arduino and the base of the transistor. As mentioned before: the voltage on the base does not matter, the current does. You want to use the transistor as a switch, so you have to drive it into saturation. As a general rule of thumb, you want the base current to be a tenth of the collector current in that case: IBase = ICollector / 10. The current through the collector is the same as the current through the LEDs, so IBase = 20 mA / 10 = 2 mA.

In a similar way as before, we can calculate the base resistor: VResistor + VBase-Emitter = VArduino. The voltage of the Arduino pin is most likely 5 V, and the Base-Emitter voltage of a silicon transistor is around 700 mV (look it up in the datasheet): VResistor = 5 V - 0.7 V = 4.3 V. Then use Ohm's law again to calculate the resistor value: RBase = VResistor / IBase = 4.3 V / 0.002 A = 2150 Ω ≈ 2.2 kΩ.

The current has to flow _through_ the base to the emitter. For current to flow, you need at least two connections: current flows from the Arduino pin, through the transistor, to ground. You have to connect the emitter of the transistor to the Arduino's ground.

You can use pretty much any normal transistor that has a maximum collector current that is larger than the LED current, and a maximum collector-emitter voltage greater than your power supply.


message:
Can I remove soldered atmega328P from arduino board, using hot air gun, without damaging it?

I need to remove atmega328P from arduino board and the best tool what comes up to my mind is a hot air gun. What is the maximum temperature that atmega328P can withstand?

body:
web search reveals the peak reflow temperature is 260°C

the chip will withstand that for 15 seconds or so

here is an example graph of a reflow oven temperature during the reflow process

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

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


body:
The idea of using a simple "heat gun" (such as [this](https://www.screwfix.com/p/energer-enb467htg-2000w-heat-gun-240v/59740)) will fail on two fronts:

1. You can't control the temperature. It will get too hot and you will damage the chip.
2. You can't control the hot air. It will melt all the plastic items on  the board (the connectors, etc) and you'll just end up with a big blob of bubbling plastic.

You need a proper reflow station. These are to a heat gun what a soldering iron is to a blow torch. They are temperature controlled, so you can select a specific temperature (with reference to the datasheet of the component you want to (de)solder), and have interchangeable nozzles to allow you to accurately direct the heat where it is needed.

I use the (cheap) Atten 858D+.


body:
The ATMega328P comes in 2 packages. DIP(Dual Inline Package) and SMD(Surface Mount Device)

The Hot Air Gun method is only best applicable to the SMD version. I would recommend you to not focus on what temperature the board can withstand, but try to practice on the hot air soldering techniques.

First try to practice removing SMD components on a separate PCB so you can be familiar with the hand movements and the techniques in safely removing SMD components. When you are familiar enough with the hand movements and techniques, then that is the best time to work on your Arduino Board.

After doing this you should be able to remove and SMD components from any type of circuit boards.

PS. Be sure to use a lot of soldering paste when using hotair reflow ;)


message:
Call by reference

I am trying to learn 'call by reference'. I want to call a function `fcn1` from the main loop and pass a reference of the local variable `var` to the function `fcn1`. Next step is to call a second function `fcn2` from the function `fcn1` and pass again the reference of the local loop variable `var`. I always get this error massage:

    invalid conversion from 'int' to 'int*' [-fpermissive]

Here a small example code:

    void fcn1(int *variable)
    {
      fcn2(&variable);
    }

    void fcn2(int *variable)
    {
      //do something with the variable
    }

    void setup()
    {

    }

    void loop()
    {
      int var = 1000;
      fcn1(&var);
    }

I tried to solve that issue by using:

    void fcn1(int *variable)
    {
      fcn2(*variable);
    }

But it's the same error.

By deleting the `*` respectively `&` it works fine, but is it still a reference?

body:
    void fcn1(int *variable)
    {
      fcn2(*variable);
    }

This function takes a pointer to an integer as parameter, and then passes the value of the integer to the second function.

To do it by reference, use an ampersand (`&`, not to be confused with the address-of operator).

    void fcn1(int &variable) {
      // Do something to variable
    }

For example:

    void increment(int &variable) { // Reference to an integer
      variable++;
    }
    void setup() {
      Serial.begin(115200);
      int a = 1;
      Serial.println(a); // 1
      increment(a);
      Serial.println(a); // 2
    }
    void loop() {}

***
You could achieve the same thing using pointers, but using references is much cleaner and easier to read.

    void increment(int *variable) { // Pointer to an integer
      ++*variable; // dereference first, then increment value
    }
    void setup() {
      Serial.begin(115200);
      int a = 1;
      Serial.println(a); // 1
      increment(&a); // address of a
      Serial.println(a); // 2
    }
    void loop() {}

Please note: this question is not specific to Arduino, it is just C++. For questions like this, it is best to google for 'C++ pass by reference' instead of 'Arduino pass by reference'.


message:
Is it common that Uno clones misbehave when connected to 12v on VIN?

**Edit**: this was completely my mistake. See end.

My official Uno worked fine when powered by 12v on VIN, but my Uno clone acted really funny--it read random noise from an input when a simple wire was attached, but not with no wire. It was solved with a pulldown resistor. The worse problem was that the PWM didn't turn off when I called `analogWrite(pin, 0)`. More worrying, it seemed to be outputting by power rather than duty cycle, since my small LED strip seemed to be doing higher duty than my big LED strip (both powered by transistors), though both were being set with `analogWrite(pin, 0)`. I measured the 5v pin at 5.9v. The input voltage may have actually been up to 12.5 v, but clean. I disconnected VIN and hooked back up to USB, and everything worked fine.

I assume the solution is to either use a linear regulator wired to VIN, or a battery?

---------
I did get the linear regulator, which didn't help. I finally checked all my voltages, and found there was a 0.8 volt difference between different grounds!  It turned out my breadboard was wired to the Arduino pin next to ground, instead of ground itself. I feel very lucky not to have ruined the board, and my only complaint is that the pins aren't labeled clearly as they are on my official Arduino. On the other hand, I wouldn't have been able to debug this as easily on the official Arduino, since the clone has lovely solder holes at each pin which are a great spot to stick a voltmeter probe.

body:
> Is it common that Uno clones misbehave when connected to 12v on VIN

Whether it is "common" is probably unanswerable unless you do some sort of survey.

However bear in mind that clones or "knock off" boards (some of which pretend to be official ones) are built to a price. The original Arduino was already designed to be cheap. To make them even cheaper the manufacturers may well make a number of compromises. For example, some use a cheaper USB interface chip. It wouldn't surprise me if the components like the voltage regulator, capacitors, etc. are under-specified.

I see from eBay that clones are already quite cheap, possibly around $US 4.50. To compete with that, some manufacturers may be cutting back even further on the quality of components.

---

> I assume the solution is to either use a linear regulator wired to VIN, or a battery?

You are probably better off bypassing the on-board regulator entirely. Get a wall-wart that outputs 5V **regulated**. The sort of thing that might power a USB-based device. Then plug that into the 5V pin of the Uno (not VIN). In fact, virtually any mobile phone charger wall-wart will output exactly what you want. Just run a USB cable from that to the USB port on the Arduino, and there you have it! Regulated 5V power.

---

The other thing that could work would be to give the voltage regulator a break. Don't put 12V into it, put in 9V. Then it doesn't have to work so hard (that is, dissipate the extra voltage as heat).


message:
How to create custom bootloader with accompanying program loader for ATMega2560

Just for some context, I have created a custom board based on the ATMega2560. I currently have the original Arduino Bootloader for the ATMega2560 and have no problems uploading code via the USB Port on TX0 and RX0.

What I am hoping to achieve is creating a custom Bootloader that allows me to upload my .hex binaries to flash but in a proprietary way, so that any program cannot be uploaded to it with the standard **Wiring** Protocol used by Arduino IDE. In addition, I will need a custom PC based program that can upload the code via the USB port.

The reason why I need this is that I will have this device out in areas where I would not want someone taking the device and uploading their own program to it and screw it up. I know it sounds paranoid, however, it would be preferred to have this feature so I can update the firmware via the USB Port without using the **Wiring** protocol.

Has anyone accomplished this before?

TL;DR
===============
Want to upload custom Bootloader to Arduino Mega so that I can upload my firmware with a proprietary programmer via the USB Port on TX0 and RX0 because I am paranoid.

body:
The source of the bootloaders is publicly available, so a simple thing would be to make a minor modification, for example XOR each incoming byte with 0xEE. That would mean the bootloader wouldn't work with normal uploading programs (the IDE) but with a modified uploader.

However even simpler would be to upload your code using ICSP and **not include a bootloader at all**. Or, leave the bootloader there but turn off the BOOTRST fuse so that the processor ignores it.

That way, it takes some effort for people to replace your code.


message:
Connecting Load combinator to HX711 then to Arduino

i'm currently a student and my project is to create a weighing scale using 50kg load sensors (x4) with HX711 amplifiers, load combinator and Arduino UNO. I've connected the load combinator and HX711 based on the picture below:

[![connection of load combinator to hx711][1]][1]

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

I'm wondering after this connection, how do i connect it to the pins of Arduino UNO and does anyone know the codes to make the load sensors work? Because currently i keep getting 0kg as the final value as well as the offset value.

body:
To be able to wire load sensors up you first need to understand how they work and what the wires on them actually mean. There are no standards as regards colour coding of the wires.

So step one is to find out the colour coding of your load cells. Assuming they are "normal" cheap 3-wire ones, internally they look like:

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

<!-- End schematic -->

You need to identify those wires on your cells.  We'll call them +, C and - (in that order) from now on.

The idea is that you provide power between + and - and a varying voltage comes out of C depending on the load applied. More load means a lower voltage, since R1 and R2 form a simple potential divider.

However that's not enough to get good results - the voltage differences are too small. So they are usually used as part of a [Wheatstone Bridge](https://en.wikipedia.org/wiki/Wheatstone_bridge). This allows a much smaller voltage variance to be detected.

The Wheatstone Bridge is created by the combinator board. It does it by combining the individual parts of separate cells together to form just two load cells along with the static resistances.  This is the form the Wheatstone Bridge create takes:

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

<!-- End schematic -->

I have boxed in each load cell so you can see how two "variable" legs combine into a single variable resistance, and two "static" legs combine into a single static resistance.

Now you can see how you could test the combinator to make sure it's giving proper results. Apply a voltage between E+ and E- (say 5V) and measure the voltage between A+ and A-. Apply pressure to the load cells (all of them at once) and observe a change in the voltage between A+ and A-.

Assuming that is showing good results (the voltage change will be quite small, so set your DMM to its most sensitive setting), your next point of call is the connection to the Arduino itself.

The HX711 uses a digital serial protocol. Sparkfun has software that bit-bangs that protocol over any pair of IO pins you choose. There is nothing special about which pins are chosen - any two can be used. So as long as you have +5V, GND and the two data pins connected up to the Arduino there's not much that can go wrong.

So that then leaves the software.  The biggest mistake people often make is to not tell the software which pins are being used for the serial communication. Or telling it the wrong pins - getting the clock and data pins mixed up, for instance.  This would be the first port of call for checking the software. Make sure you have the right pins specified.  Quite how you do that without seeing your software I can't say, but [Sparkfun have some example software](https://learn.sparkfun.com/tutorials/load-cell-amplifier-hx711-breakout-hookup-guide) (scroll down to the bottom of the page) which just uses a pair of `#define` macros to specify the pins.


body:
thank you for your help to my question and sorry i was not being specific enough.

Initially the connection of the weighing scale was based on this:
[![Connection of Arduino to Load cells][1]][1]

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

However, after much research, i've decided to give the load combinator a try and use it to connect all the 4 load sensors to form a Wheatstone Bridge that will then connect to the Arduino. So basically, the load combinator is just another add on component.

As for my codes, this is how it looks like:

    #include <hx711.h>
    #define DOUT 3
    #define CLK 2

    Hx711 scale(3,2);

    int count=0;

    float sum=0;
    float value;
    float avg=0;
    float offset;
    float toffset;

    int count2;

    float V;
    float VT;
    float total;
    int t;
    float foffset;

    void setup()
    {
      Serial.begin(9600);
      Serial.println("HX711 Test");
    }

    void loop()
    {
      for(count=0;count<10;count++)
      {
        value = (scale.getGram()*0.07);
        sum = sum + value;
      }
            toffset = +(sum / 10);
             Serial.print("Offset: ");
            Serial.print(toffset, 1);
            Serial.println(" kg");

            Serial.println("Please stand on the plate and do not remove both of your legs.");
            delay(4000);

      for(count2=0;count2<10;count2++)
      {
        V= (scale.getGram()*0.07);
        total=total+ V;
      }

      VT=(total/10);
      Serial.print("Average Weight: ");
      Serial.print(VT, 1);
      Serial.println(" kg");

       if(foffset= -toffset)
       {
        Serial.print("Final Weight: ");
        Serial.print(((VT+foffset)*-1), 1);
        Serial.println(" kg");
       }
     else
      {
        if(foffset=toffset)
       {
        Serial.print("Final Weight: ");
        Serial.print((VT-foffset), 1);
        Serial.println(" kg");
       }
     }
     Serial.end();
    }


message:
ino.hex vs ino.with_bootloader.hex

I'm working on a Android App able to update the content of my Arduinos. Start to work (reset the Arduino, communicate with STK500 protocol, get id of ATmega and so on).
But I face a question about the two hex files produced by the compiler.
Some FAQ, forum... give replies about the two, explaining: "*the ino.hex file has only the code and the other as the code + the code of the bootloader*".
After having a look at the hex files, that's true: you can find in the "with_bootloader" the code of the bootloader.

The "why" gives the following answer: "*that's because when the bootloader receive the code, it erases the flash so the installed bootloader destroy itself. So if you send without bootloader, you will not have a bootloader any more in the Arduino*".

Problems:

1) In that case, in order to change the bootloader why use an ISP? Just add the HEX code of your new bootloader in the main HEX file, send it with AVRDUDE and that's all...
2) When you use the Arduino IDE with AVRDUDE in Verbose mode you'll see AVRDUDE send the file....
**without** the bootloader!

So the question is: when you want to update the content of the flash, sending "manually" the data using STK500 protocol, do you need to send the "ino.hex" or the "ino.with_bootloader.hex" file? **And why?**

body:
If flashing with AVR In System Programing (ISP) the bootloader is not needed. Only the flashing over Serial needs a bootloader.

The ISP erases the flash including the bootloader. To be able to use the serial flashing after ISP, the hex with_bootloader can be used.

I flash AVR over WiFi with esp8266's core AVRISP library and I use the hex with_bootloader to have the option of flashing later over USB.

Your Android app will use the serial flashing utilizing the bootloader. The bootloader doesn't delete itself. So you should use the hex WITHOUT bootloader.


body: While flashing the Arduino over USB (UART) you use the bootloader in that case the bootloader doesn't delete itself that's why the Arduino IDE sends the file without the bootloader. You need to use the file with a bootloader only when you are programming using an ISCP programmer and want to keep the ability to flash through USB.


message:
State machine sketch to drive a DC motor with limit switches

I have a DC motor that will need to use two limit switches to detect end of travel in two directions.

I've read that coding a state machine to do this task is the best method, however I have no idea where to even begin.

Below you'll find a fritzing sketch of my experimental configuration for the code once implemented, and a flow chart.

![Valid XHTML](https://i.stack.imgur.com/BHa44.png)
![Valid XHTML](https://i.stack.imgur.com/4Fks0.png)

body:
You have created a flow chart.  When discussing [state machines][1] it is better to use a [state diagram][2].

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

In this state diagram of a turnstile (from the state machine wikipedia page linked to above) it is observed that the nodes (bubbles) contain the state of the turnstile and on the edges (arrows) is written the condition required to travel in the direction of the arrow to a new state.

For the question asked here, at least 2 nodes are needed to state the direction of the motor.  The edges likely will state which arrow is to be used to travel to a new state based on which switch is open or closed.  Later, consider adding a new state to stop the motor once an end switch is closed. (Hint: Likely, you will need 2 stop nodes.  One for each end-stop switch.  The reason being you will need to know which direction the motor is to turn when restarted.)

For certain cases, adding a momentary contact switch is complex due to the need to mitigate the [contact bounce][4].  This is true when the meaning of activating the switch changes.  The end-stop switch meaning does not change so there is no need to mitigate the contact bounce or "debounce" the end-stop switches.  However, it is assumed the "Cycle Switch" can start the motor spinning in different directions depending on the history of the motor movement.  Therefor the "Cycle Switch" can benefit from a 4 node state machine where there is clearly nodes which output switch-closed and switch-open.  But to get to either of these 2 nodes there needs to be 2 other nodes where the switch "debouncing" is handled.

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

When handling multiple state machines in one program it is important not to block the flow.  All state machines need to be continuously checked for state chances (testing the edge conditions for traveling from the current node to a new node).

When writing for an Arduino (in C / C++), the code pattern most often used is a "case" statement (switch / case) where a variable is assigned numbers associated with different nodes.  In such a code pattern, each "case" is a node which contains the edge test(s) and can assign a new value to the variable to switch to a new node ("case") if any of the edge tests are true.

Simplifying the design:  If you do not plan on stopping the motor then you do not need to "debounce" the "Cycle Switch".

Here is why: The meaning of the "Cycle Switch" changes from push-to-start to push-to-stop should you want to stop the motor between the 2 stop-switches.  If all you need is to start the motor after either of the stop-switches are closed, then the number of times the "Cycle Switch" bounces is irrelevant as long as the bounces do not continue for longer then it takes for the motor to reach the opposite stop-switch.

  [1]: https://en.wikipedia.org/wiki/Finite-state_machine
  [2]: https://en.wikipedia.org/wiki/State_diagram
  [3]: https://i.stack.imgur.com/hY3S0h.png
  [4]: https://en.wikipedia.org/wiki/Switch#Contact_bounce
  [5]: https://i.stack.imgur.com/KtUkch.png


body:
Each state in the state machine should be a state in which the arduino will be for a time. Anywhere you would use a delay() or a blocking function or a busy loop will be a state.

You can also use multiple orthogonal statemachines and mix them. For example 1 to control whether the motor needs to be driven at all and one to control which direction it is driven in. That way the motor control part will look like:

    if(motorDriven) {
        if(motorDirection = TOP) {
            driveMotorCW();
        } else {
            driveMotorCCW();
        }
    } else {
        stopMotor();
    }

Then the control of the state machine is straightforward. If limit switch is pressed change motorDirection to the opposite (and maybe stop the motor).

For timing you should keep a timestamp of the start of the interval and then test if `millis() - timestamp > interval`. For intervals less than a month this will work decently enough (barring drift). For intervals greater than that you should invest in a external clock.


message:
Need to read/send both values of a button push

I'm trying to use a float switch to receive alerts via Blynk when a water level drops, and when it rises again. The code I have been using has been working for when the float drops (button pressed) and I could get it to work when the water comes back up, but it gets stuck in a loop. I'm new to Arduino programming and I'm sure it's some simple error in the way I'm writing/modifying this code...

    #define BLYNK_PRINT Serial
    #include <ESP8266WiFi.h>
    #include <BlynkSimpleEsp8266.h>
    BlynkTimer timer;

    char auth[] = "710a4af9b1d82412fa477705bf642c634";
    char ssid[] = "SSID";
    char pass[] = "PWD";
    int flag=0;
    void notifyOnButtonPress()
    {
      int isButtonPressed = digitalRead(D1); //assignment here for pin
      if (isButtonPressed==1 && flag==0) {

        Blynk.notify("Alert : Water Level has dropped");
        flag=1;
      }
      else if (isButtonPressed==0 && flag==0)
       Blynk.notify("Alert : Water level has risen");
      {
        flag=0;
      }

    }
    void setup()
    {
      // Debug console
      Serial.begin(9600);
    Blynk.begin(auth, ssid, pass);
      // Setup notification button on pin D1
      pinMode(D1,INPUT_PULLUP);
     timer.setInterval(16000L,notifyOnButtonPress);

    }
    void loop()
    {
      Blynk.run();
      timer.run(); // Initiates BlynkTimer
    }

I believe the problem is in function notifyOnButtonPress.

body:
Change

    else if (isButtonPressed==0 && flag==0)
        Blynk.notify("Alert : Water level has risen");

to

    else if ((isButtonPressed==0) && (flag==1))
    {
        Blynk.notify("Alert : Water level has risen");
    }

Otherwise, when flag == 1, it will never revert back to 0.
Also it's best to add brackets, and use parenthesis.

Also, change the variable name flag to something more meaningfull.


body:
It seems to me that the saved float level state needs to be initialized to what it's actual current level is rather than just starting it off as 0. That way conditions such as a power outage during which the float level has changed could be detected.

I also changed the text of your notifications, which may or may not be allowed, to more accurately describe the state of the system.

I haven't actually tested this so I would like feedback as to whether it works or not.

    int floatSavedState = -1;      // initial float low state indicates not yet known

    void notifyOnButtonPress()
    {
      // pin D1 will be 1 if float has dropped due to low water level
      // pin D1 will be 0 if water level is high enough
      int floatLevelLow = digitalRead(D1);  // read the float low indicator pin

      if (floatLevelLow && floatLevelLow != floatSavedState) {
           // send notification if this is first time or if the float level has
           // changed since the last notification.
           Blynk.notify("Alert : Water Level low.");
           floatSavedState = floatLevelLow;
      } else if (floatLevelLow != floatSavedState)
         // send notification if this is first time or if the float level has
         // changed since the last notification.
         Blynk.notify("Alert : Water level high");
         floatSavedState = floatLevelLow;
      }
    }

Or I suppose even simpler would be:

    int floatSavedState = -1;      // initial float low state indicates not yet known

    void notifyOnButtonPress()
    {
      // pin D1 will be 1 if float has dropped due to low water level
      // pin D1 will be 0 if water level is high enough
      int floatLevelLow = digitalRead(D1);  // read the float low indicator pin

      if (floatLevelLow != floatSavedState) {
           // send notification if this is first time or if the float level has
           // changed since the last notification.
           if (floatLevelLow) {
               Blynk.notify("Alert : Water Level low.");
           } else {
               Blynk.notify("Alert : Water level high");
           }
           floatSavedState = floatLevelLow;
      }
    }


message:
ESP8266 not connecting to WiFi

I am trying to send the temperatures from an DS18B20 to ThingSpeak, using an ESP8266. You can see the code I am using for that.

When I run the code I do not get any errors. In serial monitor it just shows that it is not connected to WiFi. If I change the WiFi name in code to something not even existing I still do not get any errors. I do not think that the ESP even finds the WiFi.

I think that the only problem to get everything work is just to get the WiFi connection to work properly. I have also checked the ESP with another simple code just to check that it is not broken and it actually get the code from my computer.

Here is the code I am using. (I have removed my password etc... )

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

    //nodeMCU v1.0 (black) with Arduino IDE
    //stream temperature data DS18B20 with 1wire on ESP8266 ESP12-E (nodeMCU v1.0)
    //shin-ajaran.blogspot.com
    //nodemcu pinout https://github.com/esp8266/Arduino/issues/584
    #include <ESP8266WiFi.h>
    #include <DallasTemperature.h>
    #include <OneWire.h>

    //Def
    #define myPeriodic 15 //in sec | Thingspeak pub is 15sec
    #define ONE_WIRE_BUS D4  // DS18B20 on arduino pin2 corresponds to D4 on physical board
    //#define mySSR 0  // Solid State Relay on pin 0

    OneWire oneWire(ONE_WIRE_BUS);
    DallasTemperature DS18B20(&oneWire);
    float prevTemp = 0;
    const char* server = "api.thingspeak.com";
    String apiKey ="******";
    const char* MY_SSID = "******";
    const char* MY_PWD = "******";
    int sent = 0;

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

 void loop() {
  float temp;
  //char buffer[10];
  //DS18B20.requestTemperatures();
  //temp = DS18B20.getTempCByIndex(0);
  temp=1111;
  //String tempC = dtostrf(temp, 4, 1, buffer);//handled in sendTemp()
  Serial.print(String(sent)+" Temperature: ");
  Serial.println(temp);

  //if (temp != prevTemp)
  //{
  //  sendTeperatureTS(temp);
  //  prevTemp = temp;
  //}

  sendTeperatureTS(temp);
  int count = myPeriodic;
  while(count--)
  delay(1000);
 }

 void connectWifi()
 {
  Serial.print("Connecting to "+*MY_SSID);
  WiFi.begin(MY_SSID, MY_PWD);
  while (WiFi.status() != WL_CONNECTED) {
   delay(1000);
   Serial.print(".");
  }

  Serial.println("");
  Serial.println("Connected");
  Serial.println("");
 }//end connect

 void sendTeperatureTS(float temp)
 {
  WiFiClient client;

  if (client.connect(server, 80)) { // use ip 184.106.153.149 or api.thingspeak.com
   Serial.println("WiFi Client connected ");

   String postStr = apiKey;
   postStr += "&field1=";
   postStr += String(temp);
   postStr += "\r\n\r\n";

   client.print("POST /update HTTP/1.1\n");
   client.print("Host: api.thingspeak.com\n");
   client.print("Connection: close\n");
   client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
   client.print("Content-Type: application/x-www-form-urlencoded\n");
   client.print("Content-Length: ");
   client.print(postStr.length());
   client.print("\n\n");
   client.print(postStr);
   delay(1000);

  }//end if
  sent++;
  client.stop();
 }//end send

body: Maybe you have a space in your WIFI SSID so you should check this in your router. Also maybe your WIFI is on 5Ghz and the ESP can't see it because it is only for 2.4 Ghz. Also if your WIFI AP is on a channel from 13 - 14 it also couldn't be seen by the ESP. And to test your ESP you can run the scan example and if it works you should try the web server example to connect to your network. If that all will work ok than the problem is in your code.


body:
I had the same problem, when i tried to connect to my home wifi i got stuck with just printing dots and never could connected. First of all i though that my ssid or password had a typo, but it hadn't. Then i changed the nodemcu and the problem persisted. But when i tried to connect to other wifi it worked. So the problem was in my modem/router.So i changed my modem/router configuration to:
Operation mode: 802.11g+n to Automatic
Channel: 11 to Automatic
Channel Bandwich: 20 to Automatic

then the problem was solved.


body: Try to add `WiFi.hostname("ESP-host");` before  `WiFi.begin(ssid, password);` - it works in my case.


body:
In order to connect to Wifi from ESP32 and other boards, the WiFi connection needs to be 2.4GHz, wireless mode must be legacy. It cannot be set to Auto or N only. Go to your router box web page, and change this setting under Advanced Settings > Wireless.

The only code required to connect is.

    void setup() {
      ...
      WiFi.begin(MY_SSID, MY_PWD);
    }

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


message:
Connecting TCD1304 with Arduino

I'm working on a project, where I will have 2 red light beams, where one will be constantly turned on while the other will be turned on and off continuously with frequency about 100 hz.
I need to detect, on which side is the blinking beam and show it on the output (something such as if the blinking beam is on the left, turn green LED on; if it's on the right side, turn on the red LED). Each beam is big as 3mm circle.

I bought 3pcs (in case if I burn 2 of them :D) of [Toshiba TCD1304 sensors(datasheet)][1], which have 3684 elements in a row. I want to connect the sensor with Arduino, but I really don't know how I would even start this project. I've found some schematics, but it's either for [some other model][2] or is for [different kind of a project][3](reading different colors over the field). Either way, none of them is useful for me.

It will look something like that at the end (the blue circle will be also red, but it's striped to show, it's the blinking one).
[![enter image description here][4]][4]

  [1]: http://pdf1.alldatasheet.com/datasheet-pdf/view/32197/TOSHIBA/TCD1304AP.html
  [2]: https://forum.arduino.cc/index.php?topic=138585.0
  [3]: https://hackaday.io/project/18126-dav5-v301-raman-spectrometer/log/53099-using-an-arduino-r3-to-power-the-tcd1304ap-ccd-chip
  [4]: https://i.stack.imgur.com/2VPFO.png

body:
The TCD1304's minimum OS-datarate is 200 kHz. Quite a lot more than what the arduino is capable of. You should look to faster processors or to a different sensor. The TSL1401 seems to be popular with the arduino-community.

If you /need/ the TCD1304, then an arduino due will probably be able to do it, but I'm guessing you'll have to drop the arduino-IDE to achieve the full speed of the ADC.

Here's how I've done it with a STM32F4 processor:
https://tcd1304.wordpress.com/


message:
When I turn on the servo it spins on its own before going to the right position and start the sketch

I can't get my head around this: when I turn the servo on it just spins on its own as if it's setting up, it goes to an angle superior to the one I want it to go. (Don't mind if it has to set up but it can't spin more than 20 degrees which is currently doing).

    #include <Servo.h>

    Servo myservo;  // create servo object to control a servo
    // twelve servo objects can be created on most boards
    int pos = 0;    // variable to store the servo position

    int degrees_of_motion = 20;
    int servo_speed = 88;

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

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

![enter image description here][1]

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

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

  [2]: https://i.stack.imgur.com/iKcSU.jpg

body:
What happens if you have a sketch such as the following? This uses the `loop()` function of the Arduino sketch to do one movement each time the `loop()` function is triggered.

    #include <Servo.h>

    Servo myservo;  // create servo object to control a servo
                    // twelve servo objects can be created on most boards

    int pos = 0;   // variable to store the servo position
    int direc = 1; // direction and amount of position iteration, + to increment, - to decrement

    int degrees_of_motion = 20;
    int servo_speed = 88;

    void setup() {
      myservo.attach(3);  // attaches the servo on pin 3 to the servo object
      pos = 0;            // start off with zero degrees.
      direc = 1;          // start off incrementing the angle by 1
    }

    void loop() {
      if (direc > 0 && pos > degrees_of_motion) {
        direc *= -1;       // change the direction of iteration, keep amount
        pos = degrees_of_motion;
      }
      if (direc < 0 && pos < - degrees_of_motion) {
        direc *= -1;       // change the direction of iteration, keep amount
        pos = - degrees_of_motion;
      }

      myservo.write(pos);    // tell servo to go to position in variable 'pos'
      pos += direc;          // increment/decrement the position
      delay(servo_speed);    // waits 15ms for the servo to reach the position
    }


message:
Arduino Vending Machine to monitor coin slot input while waiting for user input

I have this project called Onionskin Vending machine.
The function should be: when a coin is inserted, the pulses from the coin acceptor (which is not accurate sometimes so i didn't use attachInterrupt) is recorded by the Arduino and is shown to the user as Credits.
then while still waiting for coin input, it will ask the user to select a product.

EX. Scenario 1:
The user drops a 1cent coin, then the machine will show the user its credit as 1cents and will ask to press a button. the user will press a button then the machine will turn on a motor for (X) seconds to dispense product and say thank you then resets again.

EX. Scenario 2:
The user drops a 5cent coin, then the machine will show the user its credit as 5cents and will ask to press a button. then the user will drop again a 1cent coin so the machine will show its credit as 6cents and will again ask to press a button. the user will press a button then the machine will turn on a motor for (6X) seconds to dispense product and say thank you then resets again.

Here is the code I wrote so far, but the problem is when activated, it only records the first cent/pulse then goes on waiting for user input to press a button, even if I drop more coins, it will not count the new coins inserted, only always the 1cent / 1 Credit is displayed.

**EDIT:** There is no target credit, 1cents would do. but if user drop 2cents, then 2 Sets of product should be dispensed upon user selection of product. ***So target is the arduino should wait for coin slot input while waiting for user input at same time.***

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

    #include <Wire.h>  // Comes with Arduino IDE, Required for I2C
    #include <LiquidCrystal_I2C.h>  //Call LCD I2C Library

    LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);   // Set the LCD I2C address Set up data transmission from microcontroller to LCD

    int coinPin = 2;            //Defined as the receiving pin from the coin machine.
    int coinState = 0;          //Determine the status of coinPin
    int credits = 0;            //Define a variable to display the credit.
    int delayTime = 0;          //Define delay variable for number of onionskin sheet feed duration
    int resetPin = 12;          //Define reset pin for resetting after complete function
    int sensorPin = A0; // select the input pin for LDR
    int sensorValue = 0; // variable to store the value coming from the sensor
    const int laserPin = 6;
    const int shortSizeFeedTime = 5000;  //Duration for 2pc onionskin to pass feeder
    const int longSizeFeedTime = 7500;   //Duration for 3pc onionskin to pass feeder
    const int ledpin = 13;      //define LED Pin at pin13
    const int ButtonS = 8;      //Define button for short onionskin
    const int ButtonL = 7;      //Define button for long onionskin
    const int shortSize = 9;    //Define pin for motor pin shortSize
    const int longSize = 10;    //Define pin for motor pin longSize

    void setup()
    {
      digitalWrite(resetPin, HIGH);
      delay(200);
      pinMode(coinPin, INPUT);     //Determine the function of the buttton pin to the input pin.
      pinMode(resetPin, OUTPUT);  //Set Reset PIN as OUTPUT
      pinMode(shortSize, OUTPUT);
      pinMode(longSize, OUTPUT);
      pinMode(laserPin, OUTPUT);         //Laser PIN
      /*
        lcd.begin(16, 2);         //Schedule your columns and rows. LCD
        lcd.setCursor(4,0);         //Set the cursor's starting position at position(4,0)
        lcd.print("WELCOME");      //Display screen text LCD
        lcd.setCursor(0,1);         //Set the cursor's starting position at position(0,1)
        lcd.print("PLZ  INSERT COIN");      //Display screen text LCD
      */
      Serial.begin(9600);  // Begin Serial Connection to PC

      lcd.begin(16, 2);  // initialize the lcd for 16 chars 2 lines, turn on backlight
      pinMode(ButtonS, INPUT_PULLUP);
      pinMode(ButtonL, INPUT_PULLUP);
      digitalWrite(laserPin, HIGH);// used as a laser trip wire sensor
      start(); //GOTO Start FUNCTION
      //delay(8000);
      // Wait and then tell user they can start the Serial Monitor and type in characters to
      // Display. (Set Serial Monitor option to "No Line Ending")
      //lcd.clear();
      //lcd.setCursor(0,0); //Start at character 0 on line 0
    }

    void start()
    {
      //-------- Write characters on the display ------------------
      // NOTE: Cursor Position: (CHAR, LINE) start at 0
      lcd.clear();
      lcd.setCursor(4, 0); //Start at character 4 on line 0
      lcd.print("WELCOME!");
      delay(1000);
      lcd.setCursor(0, 1);
      lcd.print(" ->Insert Coin<-");
      loop();
    }

    void loop()
    {
      sensorValue = analogRead(sensorPin);//read the status of the LDR attached to the analog pin for laser trip wire
      coinState = digitalRead(coinPin);   //coinPin value In the coinState
      lcd.setCursor(0, 0);        //Set the cursor's starting position at position(0,0)
      while (analogRead(sensorPin) < 1000)
      {
        lcd.clear();
        lcd.print("PLS. REMOVE ANY");
        lcd.setCursor(0, 1);
        lcd.print("OBJECT FRM TRAY!");
        delay(2000);
        start();
      }
      if (coinState == LOW)         //Condition
      {
        credits += 1;          //Calculate the value of the variable. It will increase each time. 5
        delay(500);                        //Delay schedule 500ms.
        lcd.clear();            //Clear command all LCD screen
        lcd.print("CREDIT:");         //Display LCD Display Message
        lcd.setCursor(8, 0);        //Set the cursor's starting position at position(8,0)
        lcd.print(credits);            //Displays the value of variable "credit" on the LCD screen.
        lcd.setCursor(12, 0);        //Set the cursor's starting position at position(8,0)
        lcd.print("PHP");          //Display screen text LCD
        lcd.setCursor(0, 1);
        lcd.print("PRESS TO PROCEED");

        //Wait for button input from user
        while (digitalRead(ButtonS) == HIGH || digitalRead(ButtonL) == HIGH) {

          //---------Servo A----------------
          if (digitalRead(ButtonS) == LOW && sensorValue > 1000)  {
            lcd.clear();
            lcd.setCursor(4, 0);
            lcd.print("VENDING:");
            lcd.setCursor(0, 1);
            lcd.print("LONG ONIONSKIN");
            delayTime = credits * longSizeFeedTime;
            digitalWrite(longSize, HIGH);//Turn on the feeder motor
            delay(delayTime); //calculation time for 2pc of onionskin
            digitalWrite(longSize, LOW);//Turn off the feeder motor
            lcd.clear();
            lcd.setCursor(3, 0);
            lcd.print("THANK YOU!");
            lcd.setCursor(0, 1);
            lcd.print("PLS. COME AGAIN!");
            credits = 0;//set the credits back to zero
            delay(3000);
            digitalWrite(resetPin, LOW);//optional for activation harware reset pin
            start();//GO to start function, kind of reset
            break;//this never actually happens :)
          } // when item is dispensed exit loop and return to wait for coin

          //---------Servo B-------------
          else if (digitalRead(ButtonL) == LOW && sensorValue > 1000) {
            lcd.clear();
            lcd.setCursor(4, 0);
            lcd.print("VENDING:");
            lcd.setCursor(0, 1);
            lcd.print("SHORT ONIONSKIN");
            delayTime = credits * shortSizeFeedTime;//calculation time for 2pc of onionskin
            digitalWrite(shortSize, HIGH);//Turn on the feeder motor
            delay(delayTime);
            digitalWrite(shortSize, LOW);//Turn off the feeder motor
            lcd.clear();
            lcd.setCursor(3, 0);
            lcd.print("THANK YOU!");
            lcd.setCursor(0, 1);
            lcd.print("PLS. COME AGAIN!");
            credits = 0;
            delay(3000);
            digitalWrite(resetPin, LOW);//optional for activation harware reset pin
            start();//GO to start function, kind of reset
            break;//Again, this never happens :)
          }
        }//End While Loop
      }//End If coin detect loop
    }//End void loop()

PS: I have read somewhere that using millis could help solve the dual running problem or by using the correct while or switch-case loop. I'm not familiar much about how while, do-while, for, switch loops work.

body:
Make it a state machine:

Initial state is idle, nothing on the tray, no credit

If a coin is entered then it counts the credits and displays it. (Should always be true)

If a button is pushed then only if credit is sufficient and tray is empty will something be vended (and credit is subtracted), otherwise show error for a few seconds.

Showing an error can be done by setting a global and a start time and duration:

    long credit;
    enum{noError, insufficientCredit, trayError, thankyou};
    int error;
    unsigned long messageTimestamp;
    unsigned long messageDuration;

    void updateLCD(){
        if(millis() - messageTimestamp > messageDuration)
            error=noError;
        switch(error){
        case noError: break;

        case insufficientCredit:

            //show insufficient credit error
            break;
        case trayError:

            //show tray error
            break;
        case thankyou:

            //show thankyou message
            break;
        }

        if(credit == 0){
            //show attract mode
        }else{
            //show credit
        }
    }

You can do something similar for the motor:

    bool motorOn;
    unsigned long motorTimestamp;
    unsigned long motorDuration;

    if(motorOn && millis() - motorTimestamp> motorDuration){
        motorOn = false;
        digitalWrite(shortSize, LOW);//Turn off the feeder motor
    }

this way you can also prevent the vending from starting again while the motor is still running by making an extra check on `motorOn`.


body:
After several research here is the final working code and solution to the problem.

    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    // Constants

    bool userSelect = false;
    const int coinPin = 2;      // Defined as the receiving pin from the coin machine.
    int coinState = 0;          // Determine the status of coinPin
    volatile int credits = 0;   // Define a variable to display the credit.
    int delayTime = 0;          // Define delay variable for number of onionskin feed duration
    int resetPin = 12;          // Define reset pin for resetting after complete function
    int sensorPin = A0;         // select the input pin for LDR
    int sensorValue = 0;        // variable to store the value coming from the sensor
    const int laserPin = 6;
    const int shortSizeFeedTime = 5000;  // Duration for 2pc OnionSkin to pass feeder
    const int longSizeFeedTime = 7500;   // Duration for 3pc OnionSkin to pass feeder
    const int ledpin = 13;      // Define LED Pin at pin13
    const int ButtonS = 4;      // Define button for short Size OnionSkin
    const int ButtonL = 5;      // Define button for long Size OnionSkin
    const int shortSize = 6;    // Define pin for motor pin shortSize
    const int longSize = 7;    // Define pin for motor pin longSize

    //I2C pins declaration for LCD
    LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

    //CoinInterrupt counter function
    void coinInterrupt() {

      // Each time a pulse is sent from the coin acceptor, interrupt main loop to add 1 cent and flip on the LED
      credits += 1;
      digitalWrite(ledpin, HIGH);
      digitalWrite(ledpin, LOW);
    }

    //Long OnionSkin Feeder function
    void longSkinServe() {
      lcd.clear();
      lcd.setCursor(4, 0);
      lcd.print("VENDING:");
      lcd.setCursor(0, 1);
      lcd.print("LONG ONION SKIN");
      delayTime = credits * longSizeFeedTime;
      digitalWrite(longSize, HIGH);
      delay(delayTime);
      digitalWrite(longSize, LOW);
      lcd.clear();
      lcd.setCursor(3, 0);
      lcd.print("THANK YOU!");
      lcd.setCursor(0, 1);
      lcd.print("PLS. COME AGAIN!");
      delay(3000);
      digitalWrite(resetPin, LOW);
      credits = 0;
      userSelect = false;
    }

    //Short OnionSkin Feeder function
    void shortSkinServe() {
      lcd.clear();
      lcd.setCursor(4, 0);
      lcd.print("VENDING:");
      lcd.setCursor(0, 1);
      lcd.print("SHORT ONION SKIN");
      delayTime = credits * shortSizeFeedTime;
      digitalWrite(shortSize, HIGH);
      delay(delayTime);
      digitalWrite(shortSize, LOW);
      lcd.clear();
      lcd.setCursor(3, 0);
      lcd.print("THANK YOU!");
      lcd.setCursor(0, 1);
      lcd.print("PLS. COME AGAIN!");
      delay(3000);
      digitalWrite(resetPin, LOW);
      credits = 0;
      userSelect = false;
    }

    void setup() {
      Serial.begin(9600);  // Begin Serial Connection to PC
      // set up the LCD's number of columns and rows:
      lcd.begin(16, 2);  // initialize the lcd for 16 chars 2 lines, turn on backlight
      lcd.print("STARTING UP...");
      attachInterrupt(digitalPinToInterrupt(coinPin), coinInterrupt, RISING);
      pinMode(ledpin, OUTPUT);
      pinMode(resetPin, OUTPUT);  //Set Reset PIN as OUTPUT
      pinMode(shortSize, OUTPUT);
      pinMode(longSize, OUTPUT);
      //  pinMode(laserPin, OUTPUT);         //Laser PIN
      pinMode(ButtonS, INPUT_PULLUP);
      pinMode(ButtonL, INPUT_PULLUP);
      delay(2000);

    }

    // Main loop
    void loop() {
      if (credits == 0) {//not yet running, there is no credit yet
        lcd.clear();
        lcd.print("ONION SKIN VENDO");
        lcd.setCursor(0, 1);
        lcd.write("-[INSERT COINS]-");
        delay(3000);
        lcd.clear();
        lcd.print("-[INSERT COINS]-");
        lcd.setCursor(1, 1);
        lcd.write("P1 or P5 ONLY");
        Serial.println("No Coin Inserted Yet...Waiting");
        delay (3000);

        //---Wait for Coin/Credit-----------
        while (credits > 0 && userSelect == false) { //if coin inserted stay in servo enable loop

          lcd.clear();            //Clear command all LCD screen
          lcd.print("CREDITS:");         //Display LCD Display Message
          lcd.setCursor(9, 0);        //Set the cursor's starting position at position(8,0)
          lcd.print(credits);            //Displays the value of variable "credit" on the LCD screen.
          lcd.setCursor(12, 0);        //Set the cursor's starting position at position(8,0)
          lcd.print("PHP");          //Display screen text LCD
          lcd.setCursor(0, 1);
          lcd.print("PRESS TO PROCEED");
          Serial.println("Credits:");
          Serial.print(credits);
          if (digitalRead(ButtonS) == HIGH || digitalRead(ButtonL) == HIGH) {

            if (digitalRead(ButtonS) == LOW)  {
              //execute short size motor
              userSelect = true;
              shortSkinServe();
            }
            else if (digitalRead(ButtonL) == LOW)
            {
              userSelect = true;
              longSkinServe();
            }
          }
          delay (80); // for while loop LCD refresh speed control
        }

      }

    }

Also here is a circuit diagram.

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

Some may say that the coding is not efficient as using several if else..if statements, but hey, this solves the problem. Cheers!

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


message:
Power Arduino Due and 6 servo motor with Battery

I would like to create a project contains 6 servo motors and Arduino Due board, but I have no idea how to operate should I use only a 9V battery only or in addition to 4 AAA battery?

body:
There is no best way in general. With your setup you may use a 9V battery as input for the Due (over the power jack, which wants voltage between 7V and 12V) and using a voltage regulator to get maybe 6V from your 9V battery voltage for your servos. Make sure, you get a regulator that can give you enough current for the 6 servos (You can find this info in the datasheet of the servo motors).

Of course you can also drive your project with 2 different battery packages, like you have described it in your question. Note, that you have to connect both grounds to make this work.


message:
2 Motor Robot Control with RC Radio

I am making a robot for a local robotics competition.  One main function I need to do is move it forward, backward, right, left.  Just like an RC car.  I have programmed it to do that but it seems like the motors are not going the same speed as each other.  When I move the stick just a little bit only one motor starts moving then when I go a bit further the only starts as well. I use an L293D and an Arduino UNO to control the 2 12v motors. I use a 6 channel receiver and transmitter for radio control.  I think it might be something with the motor, but I might be missing something.  Hopefully, someone can help me out. Thanks!

    int motor1_in1 = 3; //H bridge direction pins
    int motor1_in2 = 2; //H bridge direction pins
    int motor2_in3 = 7; //H bridge direction pins
    int motor2_in4 = 6; //H bridge direction pins

    //the following are all ~PWM capable ports
    int motor1_enable1 = 4; //H bridge motor 1 PWM PIN
    int motor2_enable1 = 5; //H bridge motor 2 PWM PIN
    int rc_channel2 = 10;
    int rc_channel4 = 8;

    void setup() {
      pinMode(rc_channel2, INPUT);
      pinMode(rc_channel4, INPUT);
      pinMode(motor1_in1, OUTPUT);
      pinMode(motor1_in2, OUTPUT);
      pinMode(motor1_enable1, OUTPUT);

      pinMode(motor2_in3, OUTPUT);
      pinMode(motor2_in4, OUTPUT);
      pinMode(motor2_enable1, OUTPUT);
      Serial.begin(9600);
    }

    void loop() {
      motorMoveForward();
      motorMoveSide();
      // delay(100);
    }

    void motorMoveForward()  {
      int pwm = 0;
      int rc2 = pulseIn(rc_channel2, HIGH, 25000);

      if (rc2 == 0) {
        digitalWrite(motor1_in1, LOW);
        digitalWrite(motor1_in2, LOW);
        digitalWrite(motor2_in3, LOW);
        digitalWrite(motor2_in4, LOW);

        analogWrite(motor1_enable1, 0);
        analogWrite(motor2_enable1, 0);
      }
      else if (rc2 > 1520) { //Backwards
        pwm = map(rc2, 1520, 1910, 0, 255); //map our speed to 0-255 range
        digitalWrite(motor1_in1, LOW);
        digitalWrite(motor1_in2, HIGH);
        digitalWrite(motor2_in3, HIGH);
        digitalWrite(motor2_in4, LOW);

        analogWrite(motor1_enable1, pwm);
        analogWrite(motor2_enable1, pwm);

        Serial.print(" DOWN    : ");
        Serial.print(pwm);
        Serial.print("\t");
        Serial.print(rc2);

      }
      else if (rc2 < 1480) { //Forwards
        pwm = map(rc2, 1480, 1090, 0, 255); //map our speed to 0-255 range
        digitalWrite(motor1_in1, HIGH);
        digitalWrite(motor1_in2, LOW);
        digitalWrite(motor2_in3, LOW);
        digitalWrite(motor2_in4, HIGH);

        analogWrite(motor1_enable1, pwm);
        analogWrite(motor2_enable1, pwm);

        Serial.print(" UP     : ");
        Serial.print(pwm);
        Serial.print("\t");
        Serial.print(rc2);
      }
      else {
        digitalWrite(motor1_in1, LOW);
        digitalWrite(motor1_in2, LOW);
        digitalWrite(motor2_in3, LOW);
        digitalWrite(motor2_in4, LOW);

        analogWrite(motor1_enable1, 0);
        analogWrite(motor2_enable1, 0);

        Serial.print(" CENTER  : ");
        Serial.print(pwm);
        Serial.print("\t");
        Serial.print(rc2);
      }

    }

    void motorMoveSide()  {
      int pwm1 = 0;
      int rc4 = pulseIn(rc_channel4, HIGH, 25000);

      if (rc4 > 1520) { //RIGHT
        pwm1 = map(rc4, 1520, 1905, 0, 255); //map our speed to 0-255 range
        //digitalWrite(motor1_in1, LOW);
        // digitalWrite(motor1_in2, HIGH);
        digitalWrite(motor2_in3, LOW);
        digitalWrite(motor2_in4, HIGH);

        analogWrite(motor1_enable1, pwm1);
        analogWrite(motor2_enable1, pwm1);

        Serial.print(" RIGHT   : ");
        Serial.print(pwm1);
        Serial.print("\t");
        Serial.println(rc4);

      }
      else if (rc4 < 1480) { //LEFT
        pwm1 = map(rc4, 1480, 1090, 0, 255); //map our speed to 0-255 range
        digitalWrite(motor1_in1, HIGH);
        digitalWrite(motor1_in2, LOW);
        //digitalWrite(motor2_in3, HIGH);
        //digitalWrite(motor2_in4, LOW);

        analogWrite(motor1_enable1, pwm1);
        analogWrite(motor2_enable1, pwm1);

        Serial.print(" LEFT    : ");
        Serial.print(pwm1);
        Serial.print("\t");
        Serial.println(rc4);
      }
      else {
        digitalWrite(motor1_in1, LOW);
        digitalWrite(motor1_in2, LOW);
        digitalWrite(motor2_in3, LOW);
        digitalWrite(motor2_in4, LOW);

        analogWrite(motor1_enable1, 0);
        analogWrite(motor2_enable1, 0);

        Serial.print(" CENTER  : ");
        Serial.print(pwm1);
        Serial.print("\t");
        Serial.println(rc4);
      }

    }

body:
From your code I would say, the problem lies within your loop function. The functions `motorMoveForward()` and `motorMoveSide()` are both over very quickly. But to actually move your motors need some time, before you change directions. Currently the motors rapidly change between driving forward and sidewards. Since in your `motorMoveSide()` function you only change direction for one of the motors, this one will rapidly being told to move forward and backwards. That results in the motor to move slowly or to not move at all. You simply cannot move forward and sidewards at the same time.

If you just want to controll the movement of your robot via RC, it may be better to use one channel just for speed value (for example 0 --> stop, 255 --> full power) and one for the direction (for example 0 --> full power left, 127 --> just forward, 255 --> full power right). A normal RC car works the same way. Or you can take one channel for one motor (and mapping speed and direction of the specific motor like you did with both motors). Which way to go depends also on your remote (e.g. what is best for controlling it with the remote).


message:
Write a condition to execute 2 switch-case functions?

I'm new to programming and using Arduino products, and was wondering if someone wouldn't mind assisting me with a project I'm trying to tackle?

If you review my code below, I have 3 conditions within my "idle" case, and the program is constantly looking for any of those 3 conditions. If the first condition is met, then case 1 is called; if the second condition is met, then case 2 is called; if the third condition is met, then case 3 is called. All 3 cases return to the "idle" case once done running.

What I would like to do is find some way to insert the "warning" case if any of the conditions are met, BEFORE going to case 1, case 2 or case 3, without writing the functions of the "warning" case over each time for each of the other 3 cases. Essentially, the flow would be like this:

condition 1 --> warning --> case 1 --> case idle;

condition 2 --> warning --> case 2 --> case idle;

condition 3 --> warning --> case 3 --> case idle:

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

    void loop() {
      static byte theState = idle;
      switch (theState)
      {
        case idle:
          if (voltageA0 > 1.0) {
            theState = case1;
          }

          if (voltageA1 < 2.0) {
            theState = case2;
          }

          if (voltageA2 > 3.5) {
            theState = case3;
          }
          break;
        case warning:
          digitalWrite(7, HIGH);
          delay(5000);
          digitalWrite(7, LOW);
          delay(0);
          break;
        case 1:
          digitalWrite(8, HIGH);
          delay(2000);
          digitalWrite(8, LOW);
          delay(0);
          theState = idle;
          break;
        case 2:
          digitalWrite(9, HIGH);
          delay(2000);
          digitalWrite(9, LOW);
          delay(0);
          theState = idle;
          break;
        case 3:
          digitalWrite(10, HIGH);
          delay(2000);
          digitalWrite(10, LOW);
          delay(0);
          theState = idle;
          break;
      }
    }
Also, if there is a more efficient way to do this, code-wise, I'm all ears!

body:
    case idle:
      if (voltageA0 > 1.0 || voltageA1 < 2.0 || voltageA2 > 3.5) {
         digitalWrite(7, HIGH);
         delay(5000);
         digitalWrite(7, LOW);
         delay(0);

         if (voltageA0 > 1.0) {
            theState = case1;
            }

        if (voltageA1 < 2.0) {
           theState = case2;
           }

        if (voltageA2 > 3.5) {
           theState = case3;
           }
       }

EDIT:
To clarify original answer, I inlined the "warning" code and deleted the "case warning", as obviously this state is not longer needed.


body:
There is something incoherent in your code. It is structured as a finite
state machine, and yet you are using `delay()` within it. In this kind of
scenario, the whole purpose of a state machine is to avoid using
`delay()`, so that your program never blocks. If your program happens to
not have anything better to do than delaying, then you can forgo the
state machine and write much simpler code. For example:

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

    void warn_and_flash(byte pin)
    {
        // Flash the "warning" LED.
        digitalWrite(7, HIGH);
        delay(5000);
        digitalWrite(7, LOW);

        // Flash the requested LED.
        digitalWrite(pin, HIGH);
        delay(2000);
        digitalWrite(pin, LOW);
    }

    void loop()
    {
        if (voltageA0 > 1.0) warn_and_flash(8);
        if (voltageA1 < 2.0) warn_and_flash(9);
        if (voltageA2 > 3.5) warn_and_flash(10);
    }


message:
Notifications in constant loop (Blynk) trying to trigger along with serial function

This is an extension from a previous thread that was getting lengthy and off the original topic. I have the following code which monitors the state of a float switch (high or low). I upload the sketch, turn on the serial monitor and manually move the float switch up and down. The serial monitor output represents what I'm doing with the switch. The issue is that I get a constant loop of blynk notifications, every 15 seconds or so. Furthermore, if i move the switch to it's low position, the first blynk notification i get is correct reading "low", the following notifications are "high" thereafter. When the switch is moved to the high position, blynk just loops stating it's "high". I know it's weird and took quite a while to even establish what is going on here. but the biggest issue is the loop of notifications every 15 seconds.

    #define BLYNK_PRINT Serial
    #include <ESP8266WiFi.h>
    #include <BlynkSimpleEsp8266.h>
    BlynkTimer timer;

    char auth[] = "710a4af9b1d82412fa477705bf642c634";
    char ssid[] = "ssid";
    char pass[] = "pwd";
    int flag=0;
    int floatSavedState = -1;      // initial float low state indicates not yet known

    void notifyOnButtonPress()
    {
      // pin D1 will be 1 if float has dropped due to low water level
      // pin D1 will be 0 if water level is high enough
      int floatLevelLow = digitalRead(D1);  // read the float low indicator pin

      if (floatLevelLow && floatLevelLow != floatSavedState) {
           // send notification if this is first time or if the float level has
           // changed since the last notification.
           Serial.println("Resevoir Water is Low!");
           Blynk.notify("Alert : Water Level low.");
           floatSavedState = floatLevelLow;
      } else if (floatLevelLow != floatSavedState)
         // send notification if this is first time or if the float level has
         // changed since the last notification.
         Serial.println("Resevoir Water is High!");
         Blynk.notify("Alert : Water level high");
         floatSavedState = floatLevelLow;

    }
    void setup()
    {
      // Debug console
      Serial.begin(9600);
    Blynk.begin(auth, ssid, pass);
      // Setup notification button on pin D1
      pinMode(D1,INPUT_PULLUP);
     timer.setInterval(16000L,notifyOnButtonPress);

    }
    void loop()
    {
      Blynk.run();
      timer.run(); // Initiates BlynkTimer
    }

body:
Your code:

    timer.setInterval(16000L,notifyOnButtonPress);

Is calling this function every 16s.

This code:

    if (floatLevelLow && floatLevelLow != floatSavedState) {

needs some parentheses to force your desired order-of-operations. As it stands now, you are asking the result of `floatLevelLow && floatLevelLow` and comparing if that is not equal to `floatSavedState`. That's likely not what you want.

Did you mean:

    if (floatLevelLow && (floatLevelLow != floatSavedState)) {

**EDIT:**

Also, your if/else is missing brackets around the 2nd clause and should be:

    } else if (floatLevelLow != floatSavedState) {
         // send notification if this is first time or if the float level has
         // changed since the last notification.
         Serial.println("Resevoir Water is High!");
         Blynk.notify("Alert : Water level high");
         floatSavedState = floatLevelLow;
    }


message:
I keep getting an error message and I don't know how to fix it

I am using an Arduino Genuino, this is what comes up

    Multiple libraries were found for "LiquidCrystal.h"
     Used: /home/user/Arduino/libraries/LiquidCrystal
     Not used: /opt/ArduinoIDE/libraries/LiquidCrystal
    In file included from /home/user/Arduino/libraries/dht/DHT_U.cpp:22:0:
    /home/user/Arduino/libraries/dht/DHT_U.h:25:29: fatal error: Adafruit_Sensor.h: No such file or directory
     #include <Adafruit_Sensor.h>

                                 ^
    compilation terminated.
    exit status 1

body:
The first notice about multiple libraries is not stopping you. The DHU library relies on the [Adafruit Unified Sensor Library][1]

You should have the following libraries (installed and) included:

    #include <Adafruit_Sensor.h>
    #include <DHT.h>
    #include <DHT_U.h>

  [1]: https://github.com/adafruit/Adafruit_DHT_Unified


message:
What's a good alternative to an Arduino Nano that can be used with Neopixels?

I'm doing an arduino project in school which requires neopixels, but the Arduino's too big. Is there an arduino I can use that's compatible with neopixels? Thanks!

body:
There are Arduino ProMinis (they have the same specs as the nano) also there's an arduino digispark tiny 85 (they have lower specs than the nano) and at the end there are just microcontrollers that can be soldered on a PCB that is enough small for you (they have a big range of specs)
Here is a comparison to the nano [![enter image description here][1]][1]

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


body:
It's not really an Arduino, however there is an STM32 which you can program almost identical to an Arduino (using the Arduino IDE). It's the STM32F103C8T6.

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

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


body: **ESP8266** mini is the best and cheaper alternative 2$5 on [Ali express](https://www.aliexpress.com/item/ESP8266-ESP-12-USB-WeMos-D1-Mini-WIFI-Development-Board-D1-Mini-NodeMCU-Lua-IOT-Board/32788532951.html?spm=2114.search0204.3.34.73c15e69VXCTQ6&ws_ab_test=searchweb0_0,searchweb201602_2_10152_10065_10151_10344_10068_5722815_10342_10343_10340_5722915_10341_5722615_10697_10696_10084_10083_10618_10305_10304_10307_10306_10302_5722715_10059_10184_10534_308_100031_10103_441_10624_10623_10622_5722515_10621_10620,searchweb201603_25,ppcSwitch_5_ppcChannel&algo_expid=56ee0025-711a-4836-b371-13b4603c10fb-5&algo_pvid=56ee0025-711a-4836-b371-13b4603c10fb&priceBeautifyAB=0). Then 100% compatible with arduino toolchain/IDE + very impressive community/github library!