message:
Distance Readings Getting Manipulated When Calling Unrelated Function

I'm using a Lidar Lite v3 to measure the distance from one object to another. I pass the results to the serial monitor to see what that distance is. It appears that when I call an unrelated function, the distance that's being printed seems to be roughly subtracted by 512.

To describe exactly what I mean, this is my function:

    int pulseWidth = pulseIn(monitorPin, HIGH); //begin measurement of time
    int distanceConverted = (pulseWidth / 10); // 10usec = 1 cm of distance
    Serial.println(distanceConverted); // Print the distance

and it gives me an output of this (which is correct):

    780 cm
    787 cm
    790 cm
    794 cm
    782 cm
    787 cm
    790 cm
    786 cm
    790 cm
    780 cm
    788 cm
    784 cm

I'm using these distances to control LED lights and a speaker, and call this function to do so:

    void lights(int distanceConverted)
    {
        if (distanceConverted < 1000 && distanceConverted > 500)
        {
          digitalWrite(yellowLEDPin, HIGH);
          delay(20);
          tone(8, 35000, 250);
        }

        else if (distanceConverted <= 500)
        {
          digitalWrite(redLEDPin, HIGH);
          delay(20);
          tone(8, 40000, 250);
        }
    }

However, when this is called (and I call the function after I print the distance values), these are the results I get:

    268 cm
    267 cm
    266 cm
    267 cm
    269 cm
    267 cm
    265 cm
    267 cm
    266 cm
    266 cm
    267 cm
    264 cm
    269 cm

When I try to account for this and multiply by three, my values become even more off and seem to be multiplied by ten:

    int distanceConverted = (pulseWidth / 10)*3; // 10usec = 1 cm of distance

    New Values:
    2640 cm
    2673 cm
    2634 cm
    2649 cm
    2592 cm
    2619 cm
    2631 cm
    2628 cm
    2631 cm
    2673 cm
    2634 cm

At first I thought it might have been the delays within the lights() function manipulating the readings, but even after commenting them out I still get the same results. I don't know how the function could be throwing my values off.

Edit: I noticed at when the program is first looping, the 512 gets subtracted after the first time I run through the lights() function.

    761 cm <- first value from sensor, correct
    312 cm
    308 cm
    308 cm
    309 cm
    308 cm
    307 cm
    307 cm
    309 cm
    308 cm
    308 cm

When I comment out the tone() function, that seems to fix my problem. Could that function be overwriting a bit in the memory register causing it to subtract 512 from my distanceConverted variable?

body:
The tone function uses timer interrupts to toggle a GPIO pin to make noise. That's quite intense from a CPU point of view and is most likely skewing the timing of the pulseIn function.

I would suggest not using tone if you can help it. Maybe change the frequency of a PWM output to something suitable and use analowWrite to create a 50% duty square wave.

Also learning how to use the Input Capture peripheral of the MCU (read the datasheet) will enable you to perform asynchronous sampling of your pulses and obtain much more accurate results.


sender: user

message:
Nested for loop errors

Ok, I am trying to make 2 LEDs run at two different speeds.

Here is the code I am using:

    void setup() {

      pinMode(13, OUTPUT);
      pinMode(12, OUTPUT);
    }

    for ( ; ; ) {
      for ( ; ; ) {
       digitalWrite(12, HIGH);
       delay(250);
       digitalWrite(12, LOW);
       delay(250);
      }
      digitalWrite(13, HIGH);
      delay(500);
      digitalWrite(13, LOW);
      delay(500);
    }

This code unfortunately returns this error:

    error: expected unqualified-id before 'for'
     for ( ; ; ) {

Thanks for the help!

sender: assistant

body:
As Majenko's comments are suggesting you're missing the `loop` function here - which is not just eye candy but essential. It is the basic structure of the [sketches](https://www.arduino.cc/en/Tutorial/BareMinimum) to have two methods on the highest (user accessible) level: `void setup()` and `void loop()`. `setup` is run exactly once at the beginning of your program. Following that `loop` is looped (hence the name) forever.

This is what it should look like:

    void setup() {
      // doing the setup
    }

    void loop() {
        for ( ; ; ) {
            for ( ; ; ) {
                // something
            }
            // something else
        }
    }

However (and again Majenko's comment hints it) `something else` is never going to be executed as the inner loop is never exited. This [tutorial](https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay) (per Majenko's comment) should get you started. See also: [www.arduino.cc](https://www.arduino.cc/en/Tutorial/BuiltInExamples) with many more tutorials worth studying.


body:
First of all your question is so basic it means you didn't spend any time to look any example out there, not even after Majenko has clearly pointed out you can find the answer to your question in the many examples out there.

Once that is clear here follow the code you are looking for, but using it as it is without knowing what you are doing is not going to help you. Not to mention not many will be willing to help somebody with the attitude you are demonstrating.

    #define LED_1 5
    #define LED_2 6

    void setup() {
      pinMode(LED_1, OUTPUT);
      pinMode(LED_2, OUTPUT);
    }

    long one, two;
    bool led_1, led_2;

    void loop() {
      if (millis() - one >= 250) {
        digitalWrite(LED_1, led_1++);
        one = millis();
      }

      if (millis() - two >= 500) {
        digitalWrite(LED_2, led_2++);
        two = millis();
      }
    }


body:
You have a compiler error because you have executable code outside a function. In particular your first "for" loop.

Second, an infinite loop inside an infinite loop is not particularly useful.

> so how do I make it run both at the same time?

Ah yes, well unless you have multiple CPUs you don't run multiple things "at the same time". You do one thing, and then another thing.

I have an article about this general idea here:

http://www.gammon.com.au/blink

To save having to necessarily go to that link, here is an example from that page which blinks two LEDs at different rates:

    // Which pins are connected to which LED
    const byte greenLED = 12;
    const byte redLED = 13;

    // Time periods of blinks in milliseconds (1000 to a second).
    const unsigned long greenLEDinterval = 500;
    const unsigned long redLEDinterval = 1000;

    // Variable holding the timer value so far. One for each "Timer"
    unsigned long greenLEDtimer;
    unsigned long redLEDtimer;

    void setup ()
      {
      pinMode (greenLED, OUTPUT);
      pinMode (redLED, OUTPUT);
      greenLEDtimer = millis ();
      redLEDtimer = millis ();
      }  // end of setup

    void toggleGreenLED ()
      {
       if (digitalRead (greenLED) == LOW)
          digitalWrite (greenLED, HIGH);
       else
          digitalWrite (greenLED, LOW);

      // remember when we toggled it
      greenLEDtimer = millis ();
      }  // end of toggleGreenLED

    void toggleRedLED ()
      {
       if (digitalRead (redLED) == LOW)
          digitalWrite (redLED, HIGH);
       else
          digitalWrite (redLED, LOW);

      // remember when we toggled it
      redLEDtimer = millis ();
      }  // end of toggleRedLED

    void loop ()
      {

      // Handling the blink of one LED.
      if ( (millis () - greenLEDtimer) >= greenLEDinterval)
         toggleGreenLED ();

      // The other LED is controlled the same way. Repeat for more LEDs
      if ( (millis () - redLEDtimer) >= redLEDinterval)
        toggleRedLED ();

    /* Other code that needs to execute goes here.
       It will be called many thousand times per second because the above code
       does not wait for the LED blink interval to finish. */

    }  // end of loop

In that code, in the main loop, the code uses `millis()` to find the current time, and if sufficient time has elapsed it does something useful. As an analogy, when you are cooking dinner you look at the clock from time to time, and if sufficient time has elapsed since you started cooking, you take the roast from the oven and eat it.


message:
Arduino MotorShield code running but not motors

I have a motor shield V2 on my Arduino, i compile the codes just fine and i'm trying to just run the example dc motor test. The code compiles the serial is printing out the "tick tock ...." but the motors are not running. They ran once before on my mac though.

Using a 9v battery to power a basic Dc motor.

I'm using the right ports on pc. Same exact port for motor as the code tells. I'm not sure where i am wrong. TYIA

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

  [1]: https://i.stack.imgur.com/KCAAL.jpg
  [2]: https://i.stack.imgur.com/rQ08I.jpg

body: Turns out the pins connecting the shield to the Arduino are quite loose and didn't "touch" the Arduino.


body:
>Using a 9v battery to power a basic Dc motor.

Don't do that.  These were designed for early transistorized radios, which needed a moderately high voltage but very low current.

There are very few motors with suitable low-current coil characteristics to be driven by such a battery.  Others might work at best briefly before killing the battery.

If you need around 9 volts for a motor project, you should probably use 6 or so AA cells.


message:
Fingerprint sensor code won't work correctly with LCD 16x2

I am doing a fingerprint sensor that works with a 16x2 LCD. The code works correctly for the fingerprint sensor, but when I enter LCD code, the LCD works but the fingerprint stops working.

I am using an Arduino Uno and an Adafruit fingerprint sensor. Both the fingerprint and LCD are wired correctly and work separately. I have enrolled and tested fingerprints and it worked perfectly until I added LCD code.

    #include <Adafruit_Fingerprint.h>
    #include <SoftwareSerial.h>
    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    int getFingerprintIDez();
    // pin #2 is IN from sensor (GREEN wire)
    // pin #3 is OUT from arduino  (WHITE wire)
    SoftwareSerial mySerial(2, 3);

    Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

    void setup() {
     // set up the LCD's number of columns and rows:
      lcd.begin(16, 2);
      // Print a message to the LCD.
      lcd.print("hello, world!");
      Serial.begin(9600);
      Serial.println("fingertest");
      // set the data rate for the sensor serial port
      finger.begin(57600);
      if (finger.verifyPassword()) {
        Serial.println("Found fingerprint sensor!");
      } else {
        Serial.println("Did not find fingerprint sensor :(");
        while (1);
      }
      Serial.println("Waiting for valid finger...");
    }

    void loop() {
      getFingerprintIDez();
    }

    uint8_t getFingerprintID() {
      uint8_t p = finger.getImage();
      switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image taken");
          break;
        case FINGERPRINT_NOFINGER:
          Serial.println("No finger detected");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          return p;
        case FINGERPRINT_IMAGEFAIL:
          Serial.println("Imaging error");
          return p;
        default:
          Serial.println("Unknown error");
          return p;
      }

      // OK success!
      p = finger.image2Tz();
      switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image converted");
          break;
        case FINGERPRINT_IMAGEMESS:
          Serial.println("Image too messy");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          return p;
        case FINGERPRINT_FEATUREFAIL:
          Serial.println("Could not find fingerprint features");
          return p;
        case FINGERPRINT_INVALIDIMAGE:
          Serial.println("Could not find fingerprint features");
          return p;
        default:
          Serial.println("Unknown error");
          return p;
      }

      // OK converted!
      p = finger.fingerFastSearch();
      if (p == FINGERPRINT_OK) {
        Serial.println("Found a print match!");
      } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
        Serial.println("Communication error");
        return p;
      } else if (p == FINGERPRINT_NOTFOUND) {
        Serial.println("Did not find a match");
        return p;
      } else {
       Serial.println("Unknown error");
        return p;
      }

      // found a match!
      Serial.print("Found ID #");
      Serial.print(finger.fingerID);
      Serial.print(" with confidence of ");
      Serial.println(finger.confidence);
    }

    // returns -1 if failed, otherwise returns ID #
    int getFingerprintIDez() {
      uint8_t p = finger.getImage();
      if (p != FINGERPRINT_OK)  return -1;
      p = finger.image2Tz();
      if (p != FINGERPRINT_OK)  return -1;
      p = finger.fingerFastSearch();
      if (p != FINGERPRINT_OK)  return -1;
      // found a match!
      Serial.print("Found ID #");
      Serial.println(finger.fingerID);
      Serial.print("This Finger print related to : ");
      switch(finger.fingerID){
       case 0:
         Serial.println("Subhy Mesmar");
         break;
       case 1 :
         Serial.println("Amjad Mesmar");
         break;
      }
      return finger.fingerID;
    }

In this image the fingerprint sensor works without LCD code:

[![Fingerprint sensor works without lcd code][1]][1]

And in this one the LCD works after adding code but the fingerprint sensor stopped working:

[![lcd works after adding code but fingerprint sensors stopped working][2]][2]

  [1]: https://i.stack.imgur.com/bNRo5.jpg
  [2]: https://i.stack.imgur.com/GcKIu.jpg

body:
You have pins 2 and 3 used by both the LCD and the SoftwareSerial used for the fingerprint sensor.

Use different pins for one or the other.

Worth looking at [the Software Serial reference][1] to understand more about how it works.

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


message:
Auto Reset during programming Arduino

I know this that when you try to program a pro mini without a DTR pin it will give you a error as the atmega needs to be reset during programming. So I had a doubt why does the microcontroller needs to be reset and clearly at which time you know at which moment does it reset ?

body: A Reset is necessary to activate the Bootloader and allow programming. Without the DTR signal the Reset button has to be pressed just before starting the upload from the Arduino IDE.


message:
Can I power up my Arduino and MotorShield with four AA batteries?

can I power up my Arduino UNO with four AA batteries? It's about 6V, will my arduino burn? And, if I power my Arduino, I have to power my Motor Shield too or not?

I want to make line follower. I have to know what I have to power up. I dont know, how many battery holders I need. I have: Arduino UNO, motor shield, two 6V DC motors

body:
You won't damage the Arduino if you remove the power to the motors as even though you're using the same power supply to power the motots and Arduino (4 x 1.5 - 6V batteries) you're not powering it from the Arduino pins itself.

What exactly are you trying to accomplish here?  Post some more info.


body:
> can I power up my Arduino UNO with four AA batteries?

6v is about the max if it is directly applied to the chip;

6v is just shy of the minimum if it is applied to a regulator and then to the chip.


body:
It won't cause damage to connect 4xAA to the input of the Arduino's regulator, however it also won't result in specified operation, as even with fairly new cells the voltage will below that which the typically used 5v regulators require to deliver 5v at the output.

Additionally, the common L293D and L298 based bipolar motor shields are horribly lossy.  Feed them about 6v input, and you'll get just over 4v to your motor, which is likely to be disappointing.

To build an Arduino-based battery-powered motor project, you typically need to do one of two things

- Use 6, 7, 8 or more cells, and higher-voltage, lower current motors

- Use a 3.3v Arduino and a more efficient FET-based H-bridge motor driver/shield, for example the TB6612FNG.   This supports 4 cell operation quite well, and may to a more limited degree work on 3 *alkaline* cells.


message:
How to create jumping wire using fritzing tool

I am tying to design my circuit diagram with the help of http://fritzing.org/home/ I designed like below circuit where wires are simply straight.

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

I want some kinda jumping wires with this tool. Does anyone know how to create these jumping wires ?

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

  [1]: https://i.stack.imgur.com/Nk1RT.png
  [2]: https://i.stack.imgur.com/KYbW1.png

body:
1. Draw the wires
2. press and hold control button (mouse pointer will appear with a curve symbol)
3. drag the wire using mouse

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

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

  [1]: https://i.stack.imgur.com/veD8K.png
  [2]: https://i.stack.imgur.com/AtNhI.png


message:
Building Custom Bootloaders

Recently I was checking out the Atmel's AVR series and I found the Atmega328PB. I am really familiar with Arduino's environment. So I thought if somehow we could bootloader it with Arduino bootloader. My doubt is how can I make a Arduino bootloader for it.

body:
Here are a couple sources of ATmega328PB bootloaders based on optiboot:

- https://github.com/watterott/ATmega328PB-Testing
- https://github.com/ElektorLabs/Arduino

I haven't used either.
If you are set on making your own at least they can provide you with a reference.


message:
Using ATiny102 as HID device(emulating mouse)

I am trying to make my own mouse/keyboard from an attiny (it doesn't have to be attiny102 as the title suggests). I have read many articles on this subject: some are using v-usb library.But I understand this is for arduino uno/leonardo.I want to use an attiny with the least amount of electronic parts attached to it(no external oscillator-only the internal one..etc.). All the articles I read said that arduino can't be used as a host usb device but this applies only for it's built-in micro-usb. Can't I just emulate the HID device using digital pins on my attiny? If this is possible where can you provide some well-documented source for the protocol used when communicating with the pc?

body:
I have build a HID midi keyboard with the hiduino lib which is base on LUFA.
http://code.google.com/p/hiduino/w/list

I know LUFA is also capable to build a HID mouse device. But you need to switch to a bigger controller (i think). I used a 8u2 from atmel.

I used AVR Studio 6 to compile hiduino.
Currently i have no link to the LUFA because the git page is gone. Maybe you find a mirror or a other webpage.


body:
the only USB option for AVR microcontrollers without embedded USB, is VUSB which is somehow rare in Arduino; despite some aged libraries around :

https://blog.petrockblock.com/2012/05/19/usb-keyboard-with-arduino-and-v-usb-library-an-example/
https://github.com/gloob/vusb-for-arduino

but if you can rely on atmel studio, the very rich examples of VUSB itself are enough. I made a HID presenter (just two keys to go back and forth on powerpoint slides) using only an attiny24 which is super cheap. the codeandlife blog is a good start for VUSB. it also has a HID mouse example explained :

http://codeandlife.com/2012/02/11/v-usb-tutorial-continued-hid-mouse/


message:
Sending value from Arduino to MySQL using ESP8266

I am trying to send a value from Arduino to a remote MySQL. I am following [this tutorial][1].

I have tried but no data is received on the server. What is the issue? I am new to Arduino. My code is:

    int led1=8;
    int count=1;
    void setup() {
      pinMode(led1, OUTPUT);
      delay(3000);
      // initialize serial communication at 9600 bits per second:
      Serial.begin(115200);
      Serial.println("AT+CWMODE=1");
      delay(1000);
      Serial.println("AT+CWJAP=\"mhboys\",\"mhboys123\"");
      delay(1000);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      digitalWrite(led1,HIGH);
      // turn the LED on (HIGH is the voltage level)
      delay(1000);  // wait for a second
      if(digitalRead(led1)==LOW) {}
      if(digitalRead(led1)==HIGH) {
        count++;
        //code for sending updated count to mysql
      }
      digitalWrite(led1, LOW);
      // turn the LED off by making the voltage LOW
      delay(1000); // wait for a second
      int adjustedValue = count;
      // print out the value you read:
      Serial.println("AT+CIPSTART=\"TCP\",\"www.onemediagroup.in\",80");
      delay(1000);
      Serial.println("AT+CIPSEND=66");
      delay(1000);
      Serial.print("GET /energy/getUsage.php?currentValue=");
      Serial.print(adjustedValue);
      delay(1000);
      Serial.println("AT+CIPCLOSE");
      digitalWrite(13, HIGH);
      delay(100000); // delay in between reads for stability
    }

  [1]: http://bryceautomation.com/index.php/2016/12/24/logging-data-to-web-page-using-arduino-and-esp8266-01-at-command-set/

body:
You're sending commands blindly without checking if they actually succeeded. If you're not ready to correctly handle the responses, you're better off using a library like [this][1]. The 'HTTP GET' example should help.

  [1]: https://github.com/itead/ITEADLIB_Arduino_WeeESP8266


message:
Using RFID and fingerprint sensor together

I am using both an RFID and a fingerprint sensor in my project. When running the program, the RFID is detected but the fingerprint sensor is not detected and hence my code is not going forward.

Here is my code

    #include <Adafruit_Fingerprint.h>
    #include <SoftwareSerial.h>
    #include <MFRC522.h>
    #include <SPI.h>

    #define SAD 10
    #define RST 5
    MFRC522 nfc(SAD, RST);

    uint8_t id;
    uint8_t getFingerprintEnroll();
    int getFingerprintIDez();

    // pin #2 is IN from sensor (GREEN wire)
    // pin #3 is OUT from arduino  (WHITE wire)
    SoftwareSerial mySerial(2, 3);
    Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

    void setup() {
       SPI.begin();
       Serial.begin(115200);
        Serial.println("Looking for MFRC522.");
       nfc.begin();
       byte version = nfc.getFirmwareVersion();
      if (! version) {
        Serial.print("Didn't find MFRC522 board.");
        while (1); //halt
      }

      Serial.print("Found chip MFRC522 ");
      Serial.print("Firmware ver. 0x");
      Serial.print(version, HEX);
      Serial.println(".");
      Serial.begin(9600);

      Serial.println("Fingerprint and RFID Test");

      finger.begin(57600);
      if (finger.verifyPassword()) {
       Serial.println("Found fingerprint sensor!");
      } else {
        Serial.println("Did not find fingerprint sensor :(");
        while (1);
      }
    }

    char abc;
    void loop() {
        abc = Serial.read();
        switch (abc) {
          case '1': {
                 //Enroll method
          }
          break ;
          case '2': {
            //verify method
          }break;
          case '3': {
           //rfid method
          }
       }
    }

body: Get rid of the `Serial.begin(9600)`. You're accidentally changing the `Serial` baud rate without doing the same in the serial monitor so you'll probably see gibberish, if anything.


message:
ESP8266 TCP connection WiFiClient issue

I am using ESP8266 01 board to send some data via TCP to server on local network. My code is:

    #include <ESP8266WiFi.h>

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

    const char* host = "192.168.1.103";

    void setup() {
      Serial.begin(115200);
      delay(10);

      // Wifi connection

      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.begin(ssid, password);

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

      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());

       delay(5000);

      Serial.print("connecting to ");
      Serial.println(host);

      // Use WiFiClient class to create TCP connections
      WiFiClient client;
      const int port = 8888;
      if (!client.connect(host, port))
      {
        Serial.println("connection failed");
        return;
      }

    }

    void loop() {

      while(Serial.available() == 0)
      {
        //wait for arduino serial data
      }

       while(Serial.available())
      {
        // send data to server
        client.print(Serial.read());
      }
    }

After chacking code in Arduino IDE I am getting error message:

    In function 'void loop()':
    espwifitcp1:57: error: 'client' was not declared in this scope
         client.print(Serial.read());
         ^
    exit status 1
    'client' was not declared in this scope

It appears that if I declare `WiFiClient client;` inside `setup()` function it can't be accessed outside it. Do I correctly understand the problem? I have tried to declare object outside `setup()` and `loop()` functions but it got even more errors. Any suggestions?

body: You have declared `WiFiClient client;` in the scope of setup() only. Move it's declaration to the global scope by placing it above the declaration of `void setup()`


message:
State Machine with If/Else?

I am trying to make a state machine with if/else. But some of the code does not seem to be executing. I have information being displayed on an LCD screen so I know where it is, and it stays on **Todo=1** and does not go to the next state. I have tried using switch/case and it works. But I think it might be better for my project if I use if/else. Can I do this using if/else?

    Void loop{
      if (state == PLAY) {
        Todo = 1;
        Mastermachine(Todo);
      } else if (state == TRYAGIN) {

      }
    }

    void Mastermachine(int Todo) {
      if (Todo == 1) {
        lcd.setCursor(16, 2);
        lcd.print(String(Todo));
        SongSeq[largestindex];
        for (int index = 0; index < largestindex; index++) {
          SongSeq[index]();
        }
        Todo = 2;
      } else if (Todo == 2) {
        for (learnindex = 0; learnindex < largestindex;) {
          MIDI.read();
          if (learnindex >= largestindex) {
            Todo = 3;
          }
          lcd.setCursor(16, 2);
          lcd.print(String(Todo));
        }
      } else  if (Todo == 3) {
        if (array_cmp(learn, note, largestindex, largestindex) == true) {
          largestindex++;
          delay(2000);
          Todo = 1;
        } else {
          delay(2000);
          Todo = 1;
        }
        lcd.setCursor(16, 2);
        lcd.print(String(Todo));
      }
    }

body:
Your loop executes continually, always setting the state to 1.....

The called state machine supposedly changes the state, but it get set back to 1 every time the loop executes.

The loop program needs to do the state changes, not the masternachine function.


body:
Inside Mastermachine(), Todo is *a copy* whatever is passed as its paramter. Even if you make a global named Todo, it will be 'hidden' by the parameter of the same name. That parameter goes out of scope - disappears - when Mastermachine() exits, including any changes made to it within the function.

There are a few choices to accomplish what you want to do, but the easiest is probably to make a global Todo and get rid of the parameter Todo in Mastermachine(); i.e., make it `void Mastermachine(void)`. Then the name Todo inside the function will refer to the global by that name.


message:
Measuring the capacitance of 2 capacitors at a time

I need help with my project. In my project, I have two homemade capacitors made from 2 aluminum foil strips separated by a water bottle. I need to detect which bottle is going to become empty as people drink from it. So I plan to use the change in capacitance to detect the empty bottle. I know how to measure capacitance of 1 bottle and detect the change, but I don't know how to do it to 2 bottles at a time. Any ideas how to do this?
Here is the following code, I have been working on.

    // Initialize Pins
    int analogPin = 0;
    int analogPin1=1;
    int chargePin = 13;
    int chargePin1=12;
    int dischargePin = 11;
    int dischargePin1 = 10;

    // Initialize Resistor
    int resistorValue = 10000;

    // Initialize Timer
    unsigned long startTime;
    unsigned long elapsedTime;

    // Initialize Capacitance Variables
    float microFarads;
    float microFaradr;
    float nanoFarads;
    float nanoFaradr;

    void setup()
    {
      pinMode(chargePin, OUTPUT);
      pinMode(chargePin1,OUTPUT);
      digitalWrite(chargePin1,LOW);
      digitalWrite(chargePin, LOW);
      Serial.begin(9600); // Necessary to print data to serial monitor over USB
    }

    void loop()
    {
      digitalWrite(chargePin, HIGH); // Begins charging the capacitor
      digitalWrite(chargePin1,HIGH);
      startTime = millis(); // Begins the timer

      If(analogRead(analogPin)>648){
        elapsedTime= millis() - startTime;
        microFarads = ((float)elapsedTime / resistorValue) * 1000;

        if (microFarads == X) // X is an arbitrary capacitance when the bottle is empty and X is not a variable
        {
          Serial.println(" Bottle A is empty");
        }

        digitalWrite(chargePin, LOW); // Stops charging capacitor
        pinMode(dischargePin, OUTPUT);
        digitalWrite(dischargePin, LOW); // Allows capacitor to discharge
        while(analogRead(analogPin) > 0)
        {
          // Do nothing until capacitor is discharged
        }
        pinMode(dischargePin, INPUT); // Prevents capacitor from discharging
      }

      If(analogRead(analogPin1)>648){
        elapsedTime= millis() - startTime;
        microFaradr = ((float)elapsedTime / resistorValue) * 1000;

        if (microFaradr == Y) // Y is an arbitrary capacitance when the bottle is empty and Y is not a variable
        {
          Serial.println(" Bottle B is empty");
        }

        digitalWrite(chargePin1, LOW); // Stops charging capacitor
        pinMode(dischargePin1, OUTPUT);
        digitalWrite(dischargePin1, LOW); // Allows capacitor to discharge
        while(analogRead(analogPin1) > 0)
        {
          // Do nothing until capacitor is discharged
        }
        pinMode(dischargePin1, INPUT); // Prevents capacitor from discharging
      }
    }

body:
Before we get started, there are a few problems with your code.

First, I wouldn't check for `==648` or `==0`: what if you miss it by a moment and it jumps to 649, or it doesn't quite discharge to 0v?  I'd use `>=648` and `<=2` (or some other similarly low number - experimentation required).

How is your circuit connected?  I can't quite get my head around the charge and discharge pins, but I'll stick with what you have, assuming it works.

You say you want measurements every 30s, but don't say how long they take. (I have no idea of the capacitance of your bottle.)  My code assumes it takes much less than 30s to measure one bottle.  If it takes near to 30s to do one, this won't work.

I'll also assume your code works.  This is a bad assumption, since it won't even compile (capital `I` in `if`) but regardless, that's what I'll assume.

All that being said, here's the code:

    // Pins connections
    int analogPinA = 0;
    int analogPinB = 1;
    int chargePinA = 13;
    int chargePinB = 12;
    int dischargePinA = 11;
    int dischargePinB = 10;

    // Resistor being used
    int resistorValue = 10000;

    void setup()
    {
      pinMode(chargePinA, OUTPUT);
      pinMode(chargePinB, OUTPUT);
      digitalWrite(chargePinA, LOW);
      digitalWrite(chargePinB, LOW);
      pinMode(dischargePinA, OUTPUT);
      pinMode(dischargePinB, OUTPUT);
      digitalWrite(dischargePinA, LOW);
      digitalWrite(dischargePinB, LOW);
      Serial.begin(9600);
    }

    // Measure the capacitance of specified capacitor
    float measureCapacitance(int analogPin, int chargePin, int dischargePin)
    {
        // Ensure the capacitor is discharged
        digitalWrite(dischargePin, LOW);
        while (analogRead(analogPin)>2) { /* Do nothing */ }
        pinMode(dischargePin, INPUT);

        // Start charging
        unsigned long startTime = millis();
        digitalWrite(chargePin, HIGH);

        // Wait for the capacitor to charge
        while (analogRead(analogPin)<=648) { /* Do nothing */ }
        unsigned long endTime = millis();

        // Start it discharging again, ready for next time
        pinMode(dischargePin, OUTPUT);
        digitalWrite(dischargePin, LOW);

        // Calculate measured capacitance
        unsigned long elapsedTime = endTime - startTime;
        float microFarads = ((float)elapsedTime / resistorValue) * 1000;
        return microFarads;
    }

    void loop()
    {
        // Measure capacitance of first bottle
        float microFarads = measureCapacitance(analogPinA, chargePinA, dischargePinA);
        if (microFarads <= X) // X is an arbitrary capacitance when the bottle is empty
        {
          Serial.println("Bottle A is empty");
        }

        // Measure capacitance of second bottle
        float microFarads = measureCapacitance(analogPinB, chargePinB, dischargePinB);
        if (microFarads <= X) // X is an arbitrary capacitance when the bottle is empty
        {
          Serial.println("Bottle B is empty");
        }
    }


message:
Calculate absolute time based on cycles and RTC

I'm developing a low power data logging device. It samples sensors at the frequency of 20Hz, and also has a real time clock for absolute time (the logged time need to be exact down to ms).

I think that querying time for every samples would be wasteful of energy. One solution is calculate time based on number of cycles, and after a fixed duration (10 minutes) query RTC to update the time.

Here is my attempt:

    #define INTERVAL 12000 //10 minutes: 10*60*20 samples

    int count = 0;
    int checkPointMillis;
    int checkPointRTC;

    // timer interrupt at 20Hz
    ISR() {
     int a = analogRead(A0);
     int time = millis() - checkPointMillis + checkPointRTC;

     // write data to a buffer

     if (count > INTERVAL) {
      count = 0;
      checkPointMillis = millis();
      checkPointRTC = getRTCTime();
     }
    }

Is this a correct approach?

body:
In general, the idea is sound.  But there are problems with some of the details and tuning.

The most important detail:  Use the correct data type for storing and computing with time variables (like `time`, `checkPointMillis` and `checkPointRTC`).  The correct data type is `unsigned long` (or, equivalently, `unsigned long int` or `uint32_t`).

A second detail:  Rather than storing your calibration correction in two variables which you always use as a difference (in effect, `checkPointRTC-checkPointMillis`) just compute and store the difference.  For example:

    ...
    unsigned long clockCorrection;
    ...
    unsigned long time = millis() - clockCorrection;
    ...
    clockCorrection = getRTCTime() - checkPointMillis;

This will save a few bytes of RAM and a few cycles of computation.

A third detail:  If outside of the ISR you will need to access any of the values computed in the ISR, declared their variables `volatile`.  Example:

    volatile unsigned long time;

Fourth: If `getRTCTime()` or any of your sensor-reading code use interrupts, you will need to move such code out of the “timer interrupt at 20Hz” section, into (for example) `loop()`, triggered by a volatile variable going true.  [That's the model under which the balance of this answer was conceived; I overlooked, at first, the “timer interrupt at 20Hz” label.]  Note that `millis()` itself does not use interrupts.  But if your 20-Hz ISR runs longer than a millisecond, the `millis()` total will drop one millisecond per millisecond of additional ISR time.

By tuning, I refer to the number of measurement intervals to wait between recomputing the clock correction.  Under reasonable assumptions, the number of compute cycles is so closely the same with a one second interval versus a ten minute interval, that one probably should use only a second (or at the outside, a minute) interval between clock correction computes.

For example, suppose the total number of cycles awake per second is given by the following equation:

>a = 20*s + 1000*t + k * r

where *s* is the number of cycles used per sensor-set reading and recording; *t*  is the number of cycles used per clock interrupt; *k* is the number of clock correction computes per second; and *r* is the number of cycles used per clock correction compute.

For example, if *s* is 2000, *t* is 100, and *r* is 200, the equation becomes

>a = 20*2000 + 1000*100 + k * 200 = 140000 + k * 200

Now consider three cases: *k* equal to 20, or 1, or 1/600, corresponding to a clock correction compute 20 times per second, or once a second, or every 10 minutes:

       k           a
      20        144000
       1        144200
    1/600       144000.3

As you can see, under the assumptions *s* is 2000, *t* is 100, and *r* is 200, there is no compelling reason to prefer 1/600 corrections per second to one  correction per second.

If your RTC can be read reliably and quickly, reading it either every time (ie 20 per second) or every second has other advantages:  you compensate more quickly for MCU clock drift (ie, every second, rather than every 10 minutes) and strongly decrease the risk of out-of-order times.

For example, if your MCU clock drifts 2 seconds fast per 10 minutes, readings taken during the first two seconds of each new 10-minute interval would show smaller times than those taken during the last two seconds of the previous interval.  With secondly corrections, no such non-monotonic readings will occur.

Here is a slightly more correct analysis of the 2 seconds fast per 10 minutes case:  2 seconds error in 600 seconds is 3.33 milliseconds per second.  With sensor readings 50 milliseconds apart, and corrected clock readings not more than 3.33 milliseconds out of whack, non-monotonicity won't occur.  However, this does not meet the “logged time needs to be exact down to ms” criterion.  To meet that, drift of more than a half millisecond must be prevented.  That requires drift correction at least 6.67 times per second.  You could accomplish that by making a  clock correction compute at every third sensor cycle.

It should be clear from the example calculations of awake cycles that the major contributor to the count is ISR cycles, here taken as 100*1000, or 100000 cycles per second.  You could set up timer 1 to interrupt 20 times per second and turn timer 0 off (which would disable `millis()` and require a different `time = ...` formula).  If each timer 1 interrupt took 1000 cycles, that would contribute 20000 cycles instead of 100000 per second.

*Edit 4:* As I noted in a comment to Edgar Bonet's answer, one can change the TOP value used for timer interrupts, to control interrupt rate with better resolution than can be obtained by merely subtracting base values.

According to Gerben's comment, “`getRTCTime` only has 1sec resolution”.  As I haven't seen any code for your `getRTCTime()` I don't know if that is true or not; but if so, here is another approach for time-rate correction:

>• At some beginning point coincident with an RTC seconds-change, record `millis()` and an RTC reading, in eg `millibase` and `RTCbase`.
>• At some interval (eg, 10 seconds or a minute, in each case coincident with an RTC seconds-change) measure `millis()` and an RTC reading, in eg `millinow` and `RTCnow`.  Compute `RTCdeltaK` as the number of milliseconds from `RTCbase` to `RTCnow`.  Compute `millidelta` as `millinow-millibase`.
>• Whenever elapsed time in milliseconds is needed, compute `elapsedms = ((millis()-millibase)*RTCdeltaK)/millidelta`.

The above is an algorithm, and may need some adjustment before use as an implementation.  First, the `elapsedms` calculation can be arranged to avoid division, using a scaled multiplicative factor based on `millidelta`, `RTCdeltaK`, and some powers of 2.  Secondly, relatively constant clock drift is assumed.  If that assumption is incorrect, an average ratio with exponential decay could be used, instead of just a factor equivalent to `RTCdeltaK/millidelta`.


body:
If you are using a RTC a far better solution to use alarms.

I use `TimeAlarms` for this purpose

    #include <Time.h>        //http://www.arduino.cc/playground/Code/Time
    #include <Timezone.h>    //https://github.com/JChristensen/Timezone
    #include <TimeAlarms.h> //  Time alarms for use with Time library
    #include <DS1307RTC.h>   //http://www.arduino.cc/playground/Code/Time returns time as a time_t

then include code to do something. The following waits for the Minutes to rollover, then calls function `Repeats` every 30 seconds etc

    const int SampleRate = 30; // seconds >1

      Alarm.waitMinuteRollover();
      Alarm.timerRepeat(SampleRate, Repeats);   // timer for every SampleRate seconds
      Alarm.alarmRepeat(alarmTime, rolloverLogFile); // alarm to rollover LogFile (daily)


body:
Yours is a classical problem of _clock synchronization_. You have a
software clock (your program's idea of the current time) which you want
to keep in sync with a reference hardware clock (the RTC). This is
typically achieved by using a [phase-locked
loop](https://en.wikipedia.org/wiki/Phase-locked_loop), or PLL. It works
as follows:

* you measure the difference between your software clock's time and the
  reference time
* you adjust your software clock based on this measurement.

This is essentially what you are already doing, except that you are
fixing your clock by stepping it abruptly, whereas a PLL would usually
slew the clock to get it in sync progressively.

Stepping the clock has some undesirable effects: it makes the time
discontinuous and, more annoyingly, it can make it non-monotonic. I
would thus recommend you try to slew your clock instead.

Here is the approach I would try if I were in your shoes. I am assuming
you are using an Arduino Uno, or a similar AVR-based board with a 16-bit
Timer 1:

* configure Timer 1 in mode 4: CTC mode with TOP = OCR1A
* set the prescaler to 64 and OCR1A = 12499 in order to get a period of
  50 ms; TIMER1\_COMPA\_vect will be your data gathering interrupt
* configure your RTC to generate a 1 Hz output, and route this
  signal to the input capture pin ICP1 (pin 8 on the Uno)
* run the PLL logic inside TIMER1\_CAPT\_vect.

Since the RTC's 1 Hz period is a multiple of the timer period, you
would expect the timer's input capture unit to always capture the same
value. The difference between two consecutive captured values is thus a
direct measure of your clock's drift in units of 4 ppm
(4 µs/s). The ISR would be basically along these lines:

    ISR(TIMER1_CAPT_vect)
    {
        static uint16_t last_capture;
        uint16_t this_capture = ICR1;
        int16_t drift = this_capture - last_capture;
        last_capture = this_capture;

        // Reduce the drift modulo 12500 into [-6250, +6250).
        if (drift >= 6250) drift -= 12500;
        if (drift < -6250) drift += 12500;

        tune_clock(drift);
    }

where `tune_clock()` is your PLL algorithm responsible for slewing the
software clock.

Pay attention to the signedness of the variables. The subtraction of the
captured values should be done with unsigned numbers, _then_ the result
should be made signed.

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

**Edit**: as suggested by James Waldby, I'll give here some suggestions
on the implementation of the PLL. It turns out it is not so simple:
_measuring_ a clock drift is easy, _predicting_ it is harder.

Let me restate the problem. You have a “good” clock: the RTC 1 Hz
signal, assumed to be perfect, but with a limited resolution of one
second. And you have a “bad” clock: Timer 1, which has a 4 µs resolution
but suffers from [frequency inaccuracy, instability and sensitivity to
temperature and supply voltage][arduino-frequency]. You want to combine
both clocks into a software clock which tracks the good clock yet has
the superior resolution of the bad clock.

I will use the following notations:

* t is the time from the reference clock (the RTC), assumed to be also
  the physical time
* n = ⌊t⌋ is the integer part of t, which is also the time when we last
  got an update from the RTC (a timer capture event)
* t′ is the time from the local clock (the Arduino timers)
* x = t′ − t is the local clock offset, measured by the ISR above at
  integer values of t; the physical time is given by t = t′ − x
* y = dx/dt is the local clock drift rate; it's a dimensionless quantity
  and typically less than 10−3 (i.e. less than 1 ms/s)
* xe(t) is the estimate, made by the software, of the offset x(t)
* ye(t) = dxe/dt is the estimate of the drift rate y(t)
* te = t′ − xe(te) is our software
  clock: a self-consistent estimate of t

The simplest solution, which is equivalent to the one you have in your
question, is to assume x stays constant until it is updated. Thus

xe(t) = x(n)
te = t′ − x(n)

In other words, we are just correcting for the last known offset. The
problem is, as stated before, that this gives a discontinuous time
scale.

A better solution is to try to _predict_ x(n+1), and linearly
interpolate between our previous and our current prediction, thus
building a continuous piecewise linear estimate of x:

xe(t) = xe(n) + (t−n)ye(n+½),
where ye(n+½) = xe(n+1) − xe(n)

From this, the estimated time can be solved for as:

te = n + (t′−xe(n)−n)/(1+ye(n+½))
≈ n + (t′−xe(n)−n)⋅(1−ye(n+½))

The factor 1/(1+ye(n+½)) ≈ (1−ye(n+½)) accounts
for the fact that the clock has drifted since the last update at t = n.

Now we are left with the problem of predicting x(n+1). There are
many possible approaches, and I will try to describe only a few.

## Simple PLL

One simple approach is to simulate an analog PLL with a first order
low-pass filter. Here is the first illustration of the Wikipedia article
on [phase-locked loop][]:

![Schematic of a PLL][]

Some translation is needed between this analog picture and the digital
domain: The phase comparator takes the difference between the measured
offset x(n) and our previous prediction xe(n). The low pass
filter is implemented as an exponentially weighted moving average. The
output of the filter is our estimate of the drift rate: ye.
The VCO is the formula for estimating te, which has the
built-in drift rate −ye. This could be translated to C++
roughly along these lines:

    struct {
        uint32_t n;  // time of last update
        float xe;    // estimate of offset at time n
        float ye;    // estimate of drift rate for t in [n ,n+1]
    } clock;

    const float tau = 60;  // low-pass filter time constant, in seconds
    const float K = 1;     // DC gain of the filter
    const float alpha = 1/(1+tau);

    // Called by the ISR.
    // y is (x[now] - x[1 second ago]) in units of 4 us.
    void tune_clock(int16_t y)
    {
        static float x;   // last known offset
        x += y * 4e-6;    // update known offset
        float xe = clock.xe + clock.ye;  // estimate of current offset

        // Update time.
        clock.n++;

        // Update our estimate of the drift rate.
        clock.ye += alpha*(K*(x-xe) - clock.ye);

        // Update or estimate of the offset.
        clock.xe = xe;
    }

    // Estimate the current time.
    float time()
    {
        float t_local = micros() * 1e-6;
        return clock.n + (t_local - clock.xe - clock.n) * (1 - clock.ye);
    }

Note that the code above is only meant as a guide. A good implementation
should use fixed-point instead of floats and should also be
rollover-safe.

The time constant of the filter should be chosen large enough to smooth
out the jitter caused by the 4 µs resolution, yet short enough to
closely track the frequency variations of the local clock. Ideally, it
should be close to the [Allan intercept][] of the x(n) time series.

This kind of PLL normally does a good job at tracking the reference
clock, but it has one drawback: it tends to carry a systematic offset.
Let's assume, for simplicity, that the drift rate is constant. Then it
can be easily seen that the steady state of the PLL carries an offset
error:

te − t = x − xe = y/K

where K is the DC gain of the filter. A large gain minimizes this error,
but it does so at the expense of stability. Too large a DC gain and the
PLL will spontaneously go into large oscillations.

I assume it should be possible to get rid of this systematic bias by
using more sophisticated filters, maybe something like a [PID][], but I
do not want to dive into the complexities of such filters.

## Simple linear extrapolation

Another way of estimating x(n+1), which does not suffer from systematic
bias, is to linearly extrapolate from the two last known values:

xe(n+1) = 2 x(n) − x(n−1)

This means we assume that the drift rate is constant on this
short time scale. The problem with this method is that it tends to
amplify the fluctuations due to the jitter. Assuming for example an
(overoptimistic) drift rate of 2 ppm, the measured offset will
alternate between having zero and 4 µs increments. The
extrapolation will predict every zero increment to be followed by
another zero increment, and every 4 µs increment to be followed by
another 4 µs increment, and thus it will always be wrong. The time
evolution would look as follows:

    t[s]    0   1   2   3   4   5   6   7   8   9  10
    x[µs]   0   0   4   4   8   8  12  12  16  16  20
    xₑ[µs]  0   0   0   8   4  12   8  16  12  20  16

## Brown's linear exponential smoothing

[Brown's method][Brown] is one of many linear extrapolation methods
meant to smooth-out noise in the data. It is based on running _twice_
the same low-pass filter on the input data:

    s1 = low_pass(x)   // first smoothing
    s2 = low_pass(s1)  // second smoothing

If τ is the time constant of the filter, then s1 is an
average of data which has, _on average_ the age τ, whereas s2
has the age 2τ. When can then, at time t, do a linear extrapolation by
running a straight line through the points (t−τ, s1) and
(t−2τ, s2). This gives the following algorithm for updating
the estimates of the offset and the drift rate:

    static float s1, s2;      // x smoothed once and twice
    s1 += alpha * (x - s1);   // update s1
    s2 += alpha * (s1 - s2);  // update s2

    // Update or estimate of the offset.
    clock.xe = xe;

    // Extrapolate to estimate next offset.
    xe = s1 + (s1-s2)*(tau+1)/tau;

    // Update our estimate of the drift rate.
    clock.ye = xe - clock.xe;

Here again, the optimal time constant should be of the order of the
Allan intercept. Note that the limit τ → 0 gives the simple
extrapolation of the previous section.

The figure below shows the performance of this algorithm on simulated
data. The simulated clock has a drift rate oscillating between 1.7 and
2.3 ppm, and its measured offset is rounded to the closest multiple of
4 µs. The line labeled “predicted (τ = 0)” is the simple
extrapolation of the previous section:

![Clock offset extrapolation](https://i.stack.imgur.com/g2mkJ.png)

Here, the large jitter of the simple extrapolation method is quite
obvious. On this simulated data, Brown's method works well with a time
constant on the order of 5 s. The frequency of a real clock would
change much more slowly, and a longer time constant would work better.

Now, all this is probably too general for your particular use case. I
didn't know when I started this edit it would lead me so far... If you
can tolerate more than, say, 10 µs of jitter, then the simple
extrapolation should be good enough. And if you only need the time at
t′-periodic intervals, this may enable some optimizations.

[arduino-frequency]: http://jorisvr.nl/article/arduino-frequency
[phase-locked loop]: https://en.wikipedia.org/wiki/Phase-locked_loop
[Schematic of a PLL]: https://upload.wikimedia.org/wikipedia/commons/thumb/d/db/Phase_locked_loop.svg/320px-Phase_locked_loop.svg.png
[Allan intercept]: http://www.slac.stanford.edu/comp/unix/package/rtems/src/ssrlApps/ntpNanoclock/theory.htm##allan

[PID]: https://en.wikipedia.org/wiki/PID_controller
[Brown]: https://en.wikipedia.org/wiki/Exponential_smoothing#Double_exponential_smoothing


message:
WeMOS creating soft access point from old code even when new code doesn't have it

In the past I uploaded the code below:

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

    #define DHTTYPE DHT22     // DHT 11
    #define DHTPIN D5
    DHT dht(DHTPIN, DHTTYPE);

    const char *ssid = " Hello_IOT";
    const char *pass = "12345678";
    String command;
    ESP8266WebServer server(8080);

    void respond(){
      int h = dht.readHumidity();
      int t = dht.readTemperature();
      server.send(200, "text/html", "
Hello from Wemos R1 Mini
");
    }

    void outputJson(){
      char temp[400];
      int h = dht.readHumidity();
      int t = dht.readTemperature();
      int tf = dht.readTemperature(true);
      snprintf(temp, 400, "{\"wittyCloud\" : [{\"location\" : \"any\" ,\
        \"temperatureInC\" :%d ,\
        \"temperatureInF\" :%d ,\
        \"humidity\":%d,\
        \"ldr\":%d\
        }]}",
      t, tf, h, analogRead(A0));
      server.send(200, "text/json", temp);
    }

    void setup(){
      Serial.begin(115200);
      pinMode(BUILTIN_LED, OUTPUT);
      Serial.println("Connect to access Point");
      WiFi.softAP(ssid, pass);
      IPAddress IPserver = WiFi.softAPIP();
      Serial.println(" IP address server : ");
      Serial.println(IPserver);
      server.on("/", respond);
      server.on("/json", outputJson);
      server.begin();
      server.onNotFound([](){
        command = server.uri();
        server.send(200, "text/plain", command);
      });
    }

    void loop(){
      server.handleClient();
      if(command.equals("/mati")){
        digitalWrite(BUILTIN_LED, HIGH); //turn off BUILTIN LED
      }
      if(command.equals("/hidup")){
        digitalWrite(BUILTIN_LED, LOW); //turn on BUILTIN LED
      }
    }

For learning purpose it worked, however when I modified it to the code below for WeMOS, to connect to my home wifi router, it creates instead an access point, and on opening the URL after connecting to the WeMOS access point it displays the web page of the updated code.

    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266mDNS.h>
    #include <ESP8266WebServer.h>
    #include "control.h"
    #include "webpage.h"
    #include <DHT.h>

    ESP8266WebServer server(80);
    const char* sid = "router+ssid";
    const char* passwd = "ssid_password";

    #define DHTTYPE DHT22     // DHT 22
    #define DHTPIN D5
    DHT dht(DHTPIN, DHTTYPE);
    const char* host = "nodemcu";

    void outputJson(){
      char temp[400];
      int h = dht.readHumidity();
      int t = dht.readTemperature();
      int tf = dht.readTemperature(true);
      snprintf(temp, 400, "{\"wemos\" : [{\"location\" : \"bangalore\" ,\
        \"temperatureInC\" :- ,\
        \"temperatureInF\" :- ,\
        \"humidity\":-\
        }]}",
      t, tf, h);
      server.send(200, "text/json", temp);
    }

    void handleRoot(){
      const int nsize = 2300;
      char temp[nsize];
      delay(200);
      int h = dht.readHumidity();
      int t = dht.readTemperature();
      snprintf(temp, nsize,
        "%s\n</\div>\n\
        ",webpage::html);
      server.send(200, "text/html", temp);
    }

    void handleNotFound(){
      String message = "File Not Found\n\n";
      message += "URI: ";
      message += server.uri();
      message += "\nMethod: ";
      message +=(server.method()== HTTP_GET)? "GET" : "POST";
      message += "\nArguments: ";
      message += server.args();
      message += "\n";
      for(uint8_t i = 0; i < server.args(); i++){
        message += " " + server.argName(i)+ ": " + server.arg(i)+ "\n";
      }
      server.send(404, "text/plain", message);
    }

    void setup(void) {
      Serial.begin(9600);
      // config static IP
      IPAddress ip(192, 168, 1, 88);
      IPAddress gateway(192, 168, 1, 1);
      IPAddress subnet(255, 255, 255, 0);
      IPAddress dns(192, 168, 1, 1);
      WiFi.config(ip, dns, gateway, subnet);
      WiFi.begin(sid, passwd);
      Serial.println("");
      EEPROM.begin(512);

      // Wait for connection
      while(WiFi.status()!= WL_CONNECTED){
        delay(500);
        Serial.print(".");
      }

      Serial.println("");
      Serial.print("Connected to ");
      Serial.println(sid);
      Serial.print("IP address: ");
      Serial.println(WiFi.localIP());
      if(MDNS.begin(host)){
        Serial.println("MDNS responder started");
      }
      MDNS.addService("http", "tcp", 80);
      server.on("/", handleRoot);
      server.on("/json", outputJson);
      server.on("/control", control::toggleRelay);
      server.onNotFound(handleNotFound);
      server.begin();
      Serial.println(F("HTTP server started"));
    }

    void loop(void){
      server.handleClient();
    }

body: I had this issue with one of my chips. I eventually fixed it by using the SPIFFS uploader tool and uploading a blank "data" folder.


body:
> it creates instead an access point

Did you use setmode() to put it in station mode?

**wifi.setmode()**

Configures the WiFi mode to use. NodeMCU can run in one of four WiFi modes:

 - Station mode, where the NodeMCU device joins an existing network.
 - Access point (AP) mode, where it creates its own network that others can join.
 - Station + AP mode, where it both creates its own network while at the same time being joined to another existing network.
 - WiFi off.

When using the combined Station + AP mode, the same channel will be used for both networks as the radio can only listen on a single channel.

NOTE: WiFi Mode configuration will be retained until changed even if device is turned off.

**Syntax**

    wifi.setmode(mode)

**Parameters**

mode value should be one of

 - wifi.STATION for when the device is connected to a WiFi router. This is often done to give the device access to the Internet.
 - wifi.SOFTAP for when the device is acting only as an access point. This will allow you to see the device in the list of WiFi networks (unless you hide the SSID, of course). In this mode your computer can connect to the device, creating a local area network. Unless you change the value, the NodeMCU device will be given a local IP address of 192.168.4.1 and assign your computer the next available IP address, such as 192.168.4.2.
 - wifi.STATIONAP is the combination of wifi.STATION and wifi.SOFTAP. It allows you to create a local WiFi connection and connect to another WiFi router.
 - wifi.NULLMODE to switch off WiFi

**Returns**

current mode after setup

> WeMOS access point it displays the web page of the updated code

I think @Ciasto answered that part.


message:
Getting RFID tag data using C#

I am trying to get an RFID tag number using a WinForms application. But whenever I click the Button the application stops responding. Please help regarding this.

Arduino code

    void setup() {
      Serial.begin(9600);
      SPI.begin();
      rfid.init();
    }

    void loop() {
      if(rfid.isCard()) {
  if(rfid.readCardSerial()) {
          Serial.print(rfid.serNum[0], HEX);
          Serial.print(" ");
          Serial.print(rfid.serNum[1], HEX);
          Serial.print(" ");
          Serial.print(rfid.serNum[2], HEX);
          Serial.print(" ");
          Serial.print(rfid.serNum[3], HEX);
          Serial.print(" ");
          Serial.print(rfid.serNum[4], HEX);
          Serial.println("");
          delay(1000);
        }
      }
      rfid.halt();
    }

C# code

    private void button1_Click(object sender, EventArgs e) {
      try {
        serialPort1.Open();
        serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
        textBox2.Text = "connected";
        serialPort1.Close();
      }
      catch(Exception ex) {
        textBox2.Text = "Com port disconnected";
      }
    }

    private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) {
      SerialPort sp = (SerialPort)sender;
      string indata = sp.ReadExisting();
      textBox1.Text = indata;
    }

body:
You are closing the port immediately after you open it. You need to keep it open while you are expecting data. Remove the line

    serialPort1.Close();

Then, in the callback you try to access the GUI from the callback thread. That's not allowed. Use [`Invoke()`][1].

    private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
         SerialPort sp = (SerialPort)sender;
         //string indata = sp.ReadExisting();
         string indata = sp.ReadLine();
         //textBox1.Text = indata;
         Invoke(new Action<string>(
             (s) =>
             {
                 textBox1.Text = s;
             }
         ), indata);
    }

  [1]: https://msdn.microsoft.com/en-us/library/zyzhdc6b(v=vs.110).aspx


message:
Data transmission Serial to TCP

I am trying to send numeric data using ESP8266 to local network python server. Before that I am collecting data from sensors using Arduino UNO and then send it to ESP using hardware serial.

ESP8266 code:

    #include <ESP8266WiFi.h>

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

    const char* host = "192.168.1.103";

    String serial_data;

    WiFiClient client;

    void setup() {
      Serial.begin(115200);
      delay(5000);

      // We start by connecting to a WiFi network

      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.begin(ssid, password);

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

      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());

       delay(5000);

      Serial.print("connecting to ");
      Serial.println(host);

      // Use WiFiClient class to create TCP connections

      const int port = 8888;
      if (!client.connect(host, port))
      {
        Serial.println("connection failed");
        return;
      }

    }

    void loop() {

      delay(200);

      while(Serial.available() <= 0)
      {
        //wait for arduino serial data
      }

      if(Serial.available()>0)
      {
        // This will send data to client via TCP
        Serial.println("Sent..");
        serial_data = String(Serial.read());
        client.print(serial_data);
      }
    }

Python Server code:

    import socket
    import sys
    from thread import *
    from peewee import *

    db = SqliteDatabase("data.db")

    class post(Model):
        timestamp = DateTimeField()
        current = TextField()

        class Meta:
            database = db

    #connecting to database
    def initialize_db():
        db.connect()
        db.create_tables([post], safe = True)

    initialize_db()

    HOST = '192.168.1.103'
    PORT = 8888 # Arbitrary non-privileged port

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print 'Socket created'

    try:
        s.bind((HOST, PORT))
    except socket.error , msg:
        print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
        sys.exit()

    print 'Socket bind complete'

    s.listen(10)
    print 'Socket now listening'

    #keep talking with the client
    #Function for handling connections. This will be used to create threads
    def clientthread(conn):
        #Sending message to connected client
        conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string

        #infinite loop so that function do not terminate and thread do not end.
        while True:

            #Receiving from client
            data = conn.recv(1024)
            print data

            #send data to database
            post.create(
                current = data
            )

            reply = 'OK ->' + data
            if not data:
                break

            conn.sendall(reply)

        #came out of loop
        conn.close()

    #keep talking with the client
    while 1:
        #wait to accept a connection - blocking call
        conn, addr = s.accept()
        print 'Connected with ' + addr[0] + ':' + str(addr[1])

        start_new_thread(clientthread ,(conn,))

    s.close()

 After powering up ESP it successfully connects to server and then simulating arduino esp serial communication I am using serial monitor to send some numbers. Before I send anything server outputs number 240:

    Connected with 192.168.1.100:26137
    240

Then I am sending number 1 but on server terminal I get numbers 49 and 13. Sending numbers some 2 - 3 times and no more data are outputted to server terminal. Should I parse data received from serial to some form I can transmit it via TCP or data should be processed on server side?

body:
The numbers are ASCII Codes (here is [a chart](https://www.arduino.cc/en/Reference/ASCIIchart) from the Arduino website). 49 is the number 1, and 13 is a carriage return ('\n'). There should be a setting in the bottom right corner of Serial Monitor to change line ending, this should be set to "no line ending." If it is, than `client.print()` must be adding the carriage return, so you will need to remove it in Python. If you are only sending integers, replace

    serial_data = String(Serial.read());

with:

    serial_data = String(Serial.parseInt());

In the Python code I suggest adding a print statement to check if the connection is closed after

    #came out of loop
        conn.close()


message:
Problems with installing MIDI library in UECIDE

I installed UECIDE from Majenko but I couldn't register nor email him so I try it here.

When trying in install the MIDI library from 47 effects (https://github.com/FortySevenEffects/arduino_midi_library/releases/tag/4.3.1) I get the following error:

    Compiling Failed
    Analyzing Arduino_MIDI_Library_v4.3.1.zip ...
    Unable to detect any valid libraries in the archive.
    You may need to manually install it or re-package it properly.

How to solve this?

I tried install manually by copying files but that didn't result in anything.

body:
The auto-install method only (currently) works with old single-arch style libraries. This one is a new multi-arch style library (though it doesn't use the multi-arch facilities).

You need to install it manually.  Simply that means extracting the zip file into "libraries" within your "UECIDE" folder in your documents (My Documents/UECIDE/libraries on Windows, or ~/Documents/UECIDE/libraries on Linux / OS X).

If UECIDE is open at the time you can use "Help -> Debug -> Rebuild internal structures" to re-scan the available libraries, or just close it and re-open it.


message:
Where is Arduino on Fedora?

I am trying to install the Teensy loader software but I need to know where Arduino is installed. Does anyone know where in Fedora the Arduino files are?

body:
It depends how you installed it.

If you downloaded the tarball and extracted it then it's wherever you extracted it.

If you used a package manager to install it then they could be anywhere - you should look at the package manager software fedora uses (yum? it's been a while) to see how to find what files a package installs.

If you are running a modern version of Arduino (I know Debian based packages are from the stone age) then the board manager installs will be in `~/.arduino15`


body:
Assuming you have installed the tool from the Fedora repositories (that is, using yum/dnf or from the Software tool), the command to run the IDE will be installed at `/usr/bin/arduino` and you can run it from the command line just by typing `arduino` — or do the same in the search box in GNOME Shell.

Most of the package itself, including examples and libraries, will be installed under `/usr/share/arduino`.

And, once you run that program, it will create a new "sketchbook location" at `~/Arduino` — that is, a folder named "Arduino" in your home directory. If you've run the IDE already, that folder will already exist.


message:
Set array to array passed as parameter in constructor

I have a constructor which looks like this:

    Preset::Preset(char* presetName, MIDICommand* MIDICommands[])
      _presetName = presetName;
      _MIDICommands = MIDICommands;
    }

`_MIDICommnads` is declared like this: `MIDICommand* _MIDICommands[];`.

When run, this throws the error below on the second line in the constructor:

`incompatible types in assignment of 'MIDICommand**' to 'MIDICommand* [0]'`

Why do I need to declare `_MIDICommands` as `MIDICommands**`, and not `MIDICommand* _MIDICommands[]`?

The array I pass is declared like this:

    MIDICommand* one =  new MIDICommand(1, 2);
    MIDICommand* two =  new MIDICommand(2, 2);

    MIDICommand* MIDICommandsA[] = { one, two };

EDIT:
When I pass in an array, should I just use `MIDICommand* MIDICommands`, or do I need the `[]` at the end?
Now I've taken them off, but then I get trouble with passing the array.

It doesn't find a matching function to call. Basically, this `MIDICommand* MIDICommandsA[] = { one, two };` doesn't match this `MIDICommand* MIDICommands` parameter.

EDIT 2:
So, I've solved the problem of passing the array. I changed the parameter in the constructor to `MIDICommand** MIDICommands`, and I just pass a pointer to the array.

Now the constructor looks like this:

    Preset::Preset(char* presetName, MIDICommand** MIDICommands)
    {
      Serial.println(MIDICommands[0]->getProgramChange());

      _presetName = presetName;
      _MIDICommands = *MIDICommands;

      Serial.println(_MIDICommands[0]->getProgramChange());
    }

I'm getting an error on the second `Serial.println`, telling me it is a non-pointer type. I'd like it to be a pointer, so that's what I am looking at now.

`_MIDICommands` is now declared like this: `MIDICommand* _MIDICommands`.

EDIT 3: When I try to loop through the array now, it seems I have lost the second element, and have only the first.

body:
> _MIDICommnads is declared like this: MIDICommand* _MIDICommands[];.

This is the major error. That is an incomplete array type. The number of elements (and storage) is unknown.

To solve this you have decide on how the elements should be stored. Should the class allocate storage and copy the values given to the constructor or should a pointer to the vector be used.

One alternative is to use a template class and provide the max element size as a template class parameter.

Cheers!


message:
How to arrange my code block to make it work smooth and correct

I currently working on my system that automatically water the plant based on the water requirement of the plant for one day . I have a java application that let the user input the water requirement of the plant and then the java application send it to arduino the arduino will receive the data and put it inside the variable and it will be use .. I use the following sensor/module ..

 - SOIL MOISTURE 2 PCS.
 - WATER FLOW SENSOR 2 PCS.
 - SOLENOID VALVE 2PS
 - WATER LEVEL SENSOR 1 PCS.
 - HUMIDITY SENSOR 1 PCS.
 - REAL TIME CLOCK DS3231

The data that the java app will send is the water requirements for 1 day for example 400ml , the 400ml will be used by the water flow sensor if the sensor reads that its already 400ml has pass in the tube the solenoid will close the pipe . And my system has a water tank the water sensor is attach to it and will check if the water in the tank is not low if low the arduino will send that data into the java app .. All the sensors reading will be save into database using the java application ..

Here is My Whole code for arduino , its not finish yet because i'm stuck thinking on how to arrange my code blocks . Sorry for my English please bear with me ..

    #include <DS3231.h>

    //PINS
    #define MOISTURE1 A15
    #define MOISTURE2 A14
    #define WATERFLOW1 A13
    #define WATERFLOW2 A12
    #define HUMIDITY A11
    #define RELAY1 9
    #define RELAY2 8
    #define ALARM 2

    DS3231  rtc(SDA, SCL);
    int DELAYNI = 1000;
    void setup() {
      // put your setup code here, to run once:
    pinMode(MOISTURE1, INPUT);
    pinMode(MOISTURE2, INPUT);
    pinMode(WATERFLOW1, INPUT);
    pinMode(WATERFLOW2, INPUT);
    pinMode(HUMIDITY, INPUT);
    pinMode(RELAY1, OUTPUT);
    pinMode(RELAY2, OUTPUT);

    rtc.begin();

    Serial.begin(9600);
    }

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

      //Some Code here to get the data send by java app and then assign it to each variable

      readMoistureStatus();
      readWaterLevel();
    }
    void readWaterLevel(){
      ///Some code here
    }

    void readMoistureStatus(){

     int  moistureOneSensorValue = analogRead(MOISTURE1);
     int  moistureTwoSensorValue = analogRead(MOISTURE2);

       // checking the moisture range for the first soil moisture
      if(moistureOneSensorValue >= 700){
        // in case of dry soil:
        RelayOne();

         delay(DELAYNI);
      }
      if((moistureOneSensorValue < 700) && (moistureOneSensorValue >= 300)){
        // in case of moist soil:

        delay(DELAYNI);
      }
      if(moistureOneSensorValue < 300){
        // in case of soggy soil:

        delay(DELAYNI);
      }
       //
       //
       // Checking the moisture range for the second soil moisture

      if(moistureTwoSensorValue >= 700){
        // in case of dry soil:
        RelayTwo();

         delay(DELAYNI);
      }
      if((moistureTwoSensorValue < 700) && (moistureTwoSensorValue >= 300)){
        // in case of moist soil:

        delay(DELAYNI);
      }
      if(moistureTwoSensorValue < 300){
        // in case of soggy soil:

        delay(DELAYNI);
      }

    }

    void RelayOne(){
      //Close or Open the Solenoid

      //Read the water flow if the set point is reach it will close the solenoid using the relay
    }

    void RelayTwo(){
      //Close or Open the Solenoid

     //Read the water flow if the set point is reach it will close the solenoid using the relay
    }

body:
I think that overall your code looks good but I don't understand why you need to log data every 1 seconds (DELAYNI = 1000; is approx 1 sec).
Although there's nothing wrong in placing the

    if(moistureOneSensorValue >= ...)
    ...
    ...
codeblock in your readstatus(), it's best to separate this out into a dosomething function. Alternatively, you can read the moisture status in the `void loop()` itself and then place a `switch` case in the `doSomething()` function.

You can also use the data from the RTC to check moisture and do something:

    void setup(){
    ...
    time = DS3231.time(); //Time at the beginning
    }

    void loop(){

    timeElapsed = now() - DS3231.time();//seconds elapsed

    if (timeElapsed >= DELAYNI){
        moisture1 = analogRead(MOISTURE1); // Read ADC value
        moisture2 = analogRead(MOISTURE2); // Read ADC value
        updateDatabase(time, moisture1, moisture2, relay1, relay2); //update the moisture values and statuses of the relays to the database
        switchRelays(moisture1,moisture2); // switch relay1 and relay2 depending on vals
    time = DS3231.time(); // Update the time

        }

    }


message:
Multiplying the voltage output

I'm working on a project where my arduino is receiving a voltage 0-5V, I need the output to be 10V always. Is there a way to do that?

body:
Assuming the 0-5 Volts is supposed to switch the output, in which case you want a program to control your output, then you will want to use a digital output pin to either switch a relay or a transistor that controls the 10 Volts put out to whatever it is that you are controlling.

Perhaps you want PWM which indicates a transistor circuit.  Hard to tell what you want from the way this is worded.

Taking your words literaly, "I need the output to be 10V always" then that simply means hard-wiring to a 10V power supply.   ;-)


message:
Arduino Mega vs servo shield

I am currently designing a hexapod with a total of 18 servos. I come from a computer science background and know little about electronics, so there is one thing which puzzles me.
Adafruit is selling this [servo shield][1]. It can power up to 16 servos while only using two pins. But it's quite expensive as it would cost me ~30€. Add the cost of an Arduino Uno and you are at >50€. At the same time I could just buy an Arduino Mega and power all Servos for a lower price.

I like to think that Adafruit wouldn't sell a uselessly overpriced product, so would there be any advantage to using this shield?

Bonus question: If I'd end up buying the shield, could I just power 16 Servos with the shield and 2 via the Arduino? Would there be any problems with that? Like a delay in the 16 motors or similar issues which could through my kinematics over bord? Would I have to buy two shields (which is not really an option at that price)? Any other suggestions I have not heard of are also very welcome!

If it is of any relevance, I am planning to buy [these servos][2] as they are pretty strong and come super cheap in bulk.

  [1]: https://learn.adafruit.com/adafruit-16-channel-pwm-slash-servo-shield/overview
  [2]: https://www.amazon.de/gp/product/B01KNWN8LW/ref=ox_sc_act_title_3?smid=AVYNBB3B5GFFF&psc=1

body:
The idea of that particular servo shield is that it provides 16 PWM (pulse width modulation) channels. These are all operated simultaneously with no additional processing overhead on the Arduino.

The Arduino Uno itself does not offer 16 (or 18) hardware PWM channels but only 6 (see [here](https://www.arduino.cc/en/Main/arduinoBoardUno)). So driving 18 servos without an additional shield would require software PWM which requires some of the Arduino's ressources to be devoted doing the calculations. This may or may not interfere with the rest of your program.

Furthermore the Uno does only provide 14 dedicated digital GPIO pins in total (+6 multiplexed digital/analog pins, as [ZS6JMB's answer](https://arduino.stackexchange.com/a/37827/17196) points out), so additional hardware would* be required either way - or using an Arduino with more pins (such as the suggested Mega). The Mega however offers only 15 hardware PWM channels, leaving you with soft PWM again. (* assuming some pins will be needed for sensors or user interfacing).

An alternative is this [board](https://www.adafruit.com/product/815) or, uhm, well, cheaper clones if you like. It features the same chip as the shield but with a PCB half the size and thus skipping the "free use area". I expect it to behave the same way like the shield and operate with the same libraries as the both the shield and this board communicate only via I2C. Both can be chained (or stacked for the shield if you will) for up to 992 PWM outputs (62 boards).


body:
Most of those pen controllers or shields are o.o expanded or own generators. In this case, the resolution maxes out to be just shy of 8 bits.

There are better ways to do it. I can post the link later but I explored quite a few ways to drive multiple servos off of a timer on a pic or avr. The number of servos it can drive is determined by the length of off-duration a servo can tolerate, and number of gpio pins on a mcu.

here is the link: https://dannyelectronics.wordpress.com/2017/02/18/driving-multiple-servos-off-a-pic-timer2-ranged-extended/

it provides a few examples for its implementation on PIC and AVR. But the basic concept is the same.

No shield used and it runs in the background so it is full transparent to the user code.


body:
I need to correct an earlier poster: the number of PWM pins is irrelevant, since the servo library can control servos on any pins, even analog. That said, the servo library can only control 12 servos, but that has nothing to do with servo pins being PWM or not.

Same poster is also wrong on the number of pins, since the analog pins are fully capable of digital io just like the so-called digital pins. So an Uno has the 14 pins mentioned (0-13, although personally I never include 0 and 1 in that count since life's easier if they are left for serial) and 6 analog pins for a total of 20 (or 18 if you discount the serial Tx and Rx pins).


message:
Should I use motor driver or Motor driver shield?

I want to run 4 microgear motor for an RC car with Arduino. Should I use L293d motor driver/L298n motor driver/L293d motor driver shield?? I am using N20 microgear motor with following rating: 6 V, 200 RPM and 120 mA with no load, 40 oz-in (2.9 kg-cm) and 1.6 A at stall.

body:
The key differences between the [L293D](http://www.ti.com/lit/ds/symlink/l293.pdf) and the [L298](http://www.st.com/en/motor-drivers/l298.html) are these:

 - the L298 supports higher currents (up to 4 A with proper heat sink), the L293D is limited to 600 mA
 - the L298 has a higher operating voltage (up to 46 V), the L293D is limited to 36 V
 - the L298 is a dual full bridge driver whereas the L293D is a quadruple half bridge driver

Ok, what's the difference of two full bridges vs. four half bridges - it somehow sounds to be equal? In fact, when driving a DC motor that requires to reverse the polarity to reverse rotation a full bridge is required. This full bridge could now be provided by either of the L293D (two half bridges) or the L298 (one full bridge). If you on the other hand want to drive a four winding stepper motor (two phase bipolar) the L293D would be more helpful as it could drive two such steppers (using two separate half bridges) whereas the L298 would need to use both its full bridges and could therefore only operate one such stepper.

But since steppers are not part of this question this difference does not really matter and you could pick either chip with respect to the required current rating. A stall current of 1.6 A would be a serious problem for the L293D:

> Peak output current, I_O (nonrepetitive, t ≤ 100 μs): 1.2 A

Whether to use the chip or a driver board or a shield, to be honest, is mainly personal preference. Shields and driver boards come ready-to-use on a pretty printed circuit board which is probably their main benefit.


body:
The right driver module or shield depends on the motor. Do you know the voltage and the stall current of the motors ?

The L293D uses bipolar transistors for the output stage inside the chip and can only drive 600mA. It has a large voltage drop: the motor gets less voltage than the power voltage applied to the driver. Therefor it can be used with small 12V motors, but it does not work very well with 6V.
The L298N also uses bipolar transistors and also has a large voltage drop.
A mosfet driver like the DRV8833 works better with 6V, because it has a low voltage drop.

In small RC toys with four AA batteries, sometimes a H-bridge is made is transistors instead of using a special driver chip.

The very cheap motor shield with two L293D chips (originally designed by Adafruit) can drive four motors, but it uses many pins.

Bottom line: Everything depends on your motors. I suggest to use a mosfet driver.


message:
incompatible types in assignment of 'int*' to 'int [0]'

I was coding a class for "a kind of gun". I have this code for the classes:<br>
*Gun.h:*

    #ifndef Gun_h
    #define Gun_h

    #include "Arduino.h"

    class Gun
    {
      public:
        Gun(String identifier, String name, int teamIRCodes[]);
        String getIdentifier();
        String getName();
        int getIRCode();
      private:
        String _identifier;
        String _name;
        int _teamIRCodes[];
    };

    #endif
*Gun.cpp:*

    #include "Arduino.h"
    #include "Gun.h"

    Gun::Gun(String identifier, String name, int teamIRCodes[])
    {
      _identifier = identifier;
      _name = name;
      _teamIRCodes = teamIRCodes;
    }

    String Gun::getIdentifier(){
      return _identifier;
    }
    String Gun::getName(){
      return _name;
    }
    int Gun::getIRCode(){
      return _teamIRCodes[1];
    }
It returns me this error while compiling:

    sketch\Gun.cpp: In constructor 'Gun::Gun(String, String, int*)':

    Gun.cpp:8: error: incompatible types in assignment of 'int*' to 'int [0]'

       _teamIRCodes = teamIRCodes;

                    ^

    exit status 1
    incompatible types in assignment of 'int*' to 'int [0]'

body:
Ok, using this worked:<br>
Replace

    _teamIRCodes = teamIRCodes;
For

    for(int i = 0; i < (sizeof(teamIRCodes)/sizeof(int)) ;i++)
        _teamIRCodes[i] = teamIRCodes[i];
Needed to iterate through array, cannot copy full array.


body:
The issue is with flexible array `int _teamIRCodes[];` This is an old technique which I don't recommend. But if you want to use it, you need you use `malloc` to create a class object, adding on enough space for the array:

    // Allocate space for the class AND the array
    Gun *gun = (Gun *)malloc(sizeof(Gun) + sizeof(teamIRCodes));

However, this does not call the ctor, and you still have to manually copy the data:

    for(int i = 0; i < (sizeof(teamIRCodes) / sizeof(teamIRCodes[0])); i++) {
        gun->_teamIRCodes[i] = teamIRCodes[i];
    }

I think it's much simpler to use a pointer:

    int* _teamIRCodes;

Then you can make your ctor:

    Gun(String identifier, String name, int teamIRCodes[], int numberOfCodes) {
        _teamIRCodes = new int[numberOfCodes];
        // memcpy does the same thing as the for loop - copies the array
        memcpy(_teamIRCodes, teamIRCodes, sizeof(teamIRCodes[0]) * numberOfCodes);
    }

And don' forget to add a dtor:

    ~Gun() {
        delete [] _teamIRCodes;
    }

Or, if `teamIRCodes` is persistent throughout the lifetime of the object, you can just use a pointer to it:

     class Gun {
         public:
         int *_teamIRCodes;
         int _numberOfCodes;
         Gun(String identifier, String name, int teamIRCodes[], int numberOfCodes) {
             _teamIRCodes = teamIRCodes;
             _numberOfCodes = numberOfCodes;
       };

(Maybe this is an Arduino thing as this is the 2nd flexible array question I've seen today).


message:
Powering the attiny85 with a separate power source

I have an LED project for which i'm using a 9v power supply. For part of the project I'm using an off the shelf LED driver that is compatible with 9v however I have one LED component that I want to drive with the attiny85 (random blinking pattern), which is not compatible with 9v.

Does it make any sense to power the attiny85 separately with say a 3v coin cell, while allowing my LEDs to draw from 9v? The attiny85 would only be tripping transistors. I assume the attiny85 itself doesn't consume much power so hopefully I wouldn't be changing out the coin cell too often.

I have a couple 5v buck converters on hand but they take up more space than a coin cell would.

P.S. It's a Guy Manuel Daft Punk Helmet.

body:
> Does it make any sense...

Well, actually it does make sense and you already rationalize it in your question: less space consumed, expected life time of the coin cell is ok for your intended use case (though you could/should confirm the assumption about power consumption with the AVR's data sheet).

There is nothing wrong in powering the microcontroller with a different voltage than the "power" circuitry, assuming the ground lines are connected and the transistors mentioned are operated in a suitable mode, e.g. [open collector/open drain](https://en.wikipedia.org/wiki/Open_collector) type.


message:
Utilizing Array with RGB

I am trying to create a sketch that utilizes two arrays, one array to hold five buttons as input, assigned to pins, and another array to hold five musical notes.  I have attached a RGB LEDs with pull-down resistors and attached a 8 ohms resistor speaker.

The code is as followed:

     //Pentatonic Piano
     // C D E G A

     #define NOTE_C   262 //HZ
     #define NOTE_D   294 //HZ
     #define NOTE_E   330 //HZ
     #define NOTE_G   392 //HZ
     #define NOTE_A   440 //HZ

     const int SPEAKER = 9;   //speaker on pin 10
     const int BLED = 10;      //Blue LED on pin 9
     const int GLED = 6;      //Green LED on pin 6
     const int RLED = 5;      //Red LED on pin 3

     int buttonState = 0;

     //Button Array
     int Buttons[]= {11, 8, 7, 4, 3};

     //Tone Note Array
     int Notes[] = {NOTE_C, NOTE_D, NOTE_E, NOTE_G, NOTE_A};

     void setup()
     {
     pinMode(BLED, OUTPUT);
     pinMode(GLED, OUTPUT);
     pinMode(RLED, OUTPUT);
     pinMode(Buttons, INPUT);
     }

     void loop()
     {

       buttonState = digitalRead(Buttons);

       if (buttonState = Buttons[0])
       { tone(SPEAKER, Notes[0]);
        digitalWrite(BLED, LOW);
        digitalWrite(GLED, LOW);
        digitalWrite(RLED, HIGH);

       }
       else if (buttonState = Buttons[1])
       {tone(SPEAKER, Notes[1]);
        digitalWrite(BLED, LOW);
        digitalWrite(GLED, HIGH);
        digitalWrite(RLED, LOW);
       }
       else if (buttonState = Buttons[2])
       {tone(SPEAKER, Notes[2]);
        digitalWrite(BLED, HIGH);
        digitalWrite(GLED, LOW);
        digitalWrite(RLED, LOW);

       }
       else if (buttonState = Buttons[3])
       {tone(SPEAKER, Notes[3]);
        analogWrite(BLED, 127);
        analogWrite(GLED, 0);
        analogWrite(RLED, 127);

       }
       else if (buttonState = Buttons[4])
       {tone(SPEAKER, Notes[4]);
        analogWrite(BLED, 0);
        analogWrite(GLED, 127);
        analogWrite(RLED, 127);

       }

       else
       {
        digitalWrite(BLED, LOW);
        digitalWrite(GLED, LOW);
        digitalWrite(RLED, LOW);
        noTone(SPEAKER);
       }
     }

The problem is no matter what button I press, the RGB only emits a green light and there is absolutely no sound coming from the speaker.  I am truly stumped.

body:
First, these statements:

    if (buttonState = Buttons[0])

are doing an assignment, not a test for equality. You want:

    if (buttonState == Buttons[0])
    //               ^Notice

Next, `pinMode` takes two integers, but you are passing an array. You can use a loop to call `pinMode` multiple times:

    for (int i = 0; i < sizeof(Buttons) / sizeof(Buttons[0]); i++) {
         pinMode(Buttons[i], INPUT);
    }

Same goes for `digitalRead()`. You need to read the state for each button:

    buttonState = digitalRead(Buttons[0]);
    if (buttonState == HIGH) {
       ....
    }
    buttonState = digitalRead(Buttons[1]);
    if (buttonState == HIGH) {
       ....
    }
    //etc


message:
How do you balance an Arduino quadcopter using calculated gyro values?

I was working on an Arduino quadcopter project. I setup all my hardware and was having balancing problems with my software end. I am using an MPU-6050 gyro and accelerometer. I have calculated the angle of the quad in relation to the ground and was trying to implement these values by adjusting the output values to each of the four motors.

Here is some of my code:

        x=(-computedGyroAngleX-3.5)*10;
        y=(-computedGyroAngleY-2)*10;
        esc1.writeMicroseconds(rc_values[RC_CH1]+x-y);
        esc2.writeMicroseconds(rc_values[RC_CH1]+x+y);
        esc3.writeMicroseconds(rc_values[RC_CH1]-x-y);
        esc4.writeMicroseconds(rc_values[RC_CH1]-x+y);

If the quad is leaning forward I increase the power at the front of the quad and reduce it at the back. I do the same for the y axis. But I run into problems when I test out the quad. It flips over to the side or forward. How would I fix this?

body:
That was happening with me too. Check if the weight distribution of the drone is perfect. Lets say if the battery is placed a little more to one side of the frame than the other side, your drone will try to hover from the other side.
The center of gravity should be taken care of when the drone is not balancing properly.


message:
Voltage transfer

I'm trying to read the battery voltage using Arduino, using a 9V battery. I keep getting the same voltage (4.99). I connected my Arduino to Matlab so I'm only using the command `voltage=readVoltage(a,'pin')`. I'm very new to this, so any help would be appreciated.

 [![thats my circuit][1]][1]

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

body: Analog inputs on the arduino will measure 5v maximum. If you want to mesure higher voltage you will have to use a voltage divisor circuit (resistors).