message:
Servo motor sweeps beyond 180

I'm trying to get my servo motor to sweep from 0 to 180 degrees then back to 0 degrees for infinite amount of times. I using the following code but my motor keeps resetting when it get backs to 0 degrees (meaning it goes 0-->180-->0 then completes a 360 and starts over). Also the 0-180 degree sweep appears to be more of a 0-270 degree sweep. Anyone running into these problems?

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

    int angle = 0;

    void setup() {
      myservo.attach(9);
      myservo.write(angle);
    }

    void loop()
    {
      for (angle = 0; angle < 180; angle += 1)
      {
        myservo.write(angle);
        delay (50);
      }

      for (angle = 180; angle > 0; angle -= 1)
      {
        myservo.write(angle);
        delay(50);
      }
    }

body:
Are you trying to have the servo sweep at a particular speed? Why not just use:

    void loop()
    {
      angle=180;
      myservo.write(angle);

      delay(500); //Allow 0.5 seconds for servo to complete it's move; adjust as necessary depending on servo's rotation speed.

      angle=0;
      myservo.write(angle);

      delay(500); //Allow 0.5 seconds for servo to complete it's move; adjust as necessary depending on servo's rotation speed.
    }


sender: user

sender: assistant

body: Is your servo the modified 360 degree type with no position feedback (meaning the internal feedback potentiometer has been disabled)?


body:
I had a bunch of SG90 mini servos so I tried your code. My servos turn 0 -> 180 -> 0 -> 180 -> 0 -> 180, over and over. No 360 spins at all.

 - Maybe your servo is defect? (can you check with another servo?)
 - Maybe it is not getting enough power? (how are you powering it?) It needs at least 4.8V and at least 220mA
 - Maybe it doesn't get a strong clean PWM signal? (You'll probably need an oscilloscope to check this)


message:
How to use ESP8266 wifi shield as a hotspot?

I have bought a ESP8266 wifi shield and I want to use it hotspot, I have tried the examples that have been provided in Arduino IDE, and the shield is getting connected to my network and giving me a wifi but without internet access (like I can connect my phone to the shield but I cannot browse the internet).
Any suggestion please?

Thanks......

body:
Connecting through the ESP8266 to the internet would require the ESP8266 to handle Network Address Traversal and/or routing, which is not officially supported.

However, if you are prepared to do a lot of work, it can be done. The performance and reliability is bad, but it can be done. See http://bbs.espressif.com/viewtopic.php?t=960 Note that this will require far more skills than running the examples in the Arduino IDE.


message:
NodeMCU keeps hanging after random time

I have tried almost everything but my NodeMCU keeps hanging after random intervals, it usually stops working after 2 days, but well... I will describe it's behaviour, what I mean by hanging is that the server stops responding to the assigned static ip, if I restart my modem or the node it works again, but this device is meant to be working endlessly and shouldn't stop working even if it has been connected during one week, I have tested it a lot, it has worked for 2 days, for 3 days, once it worked for 4 days without any problem, but after reconnecting it in another place, hanged again after almost 2 days. I started to think that probably the problem it's related to NodeMCU. So please I would really appreciate any helpful suggestion like assigning ip through the modem or something that can help. Thanks in advance.

The NodeMCU is connected to a usb power hub (A regular android phone wall charger), and it controls a relay.

Here is my code:

    #include <ESP8266WiFi.h>

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

    int ledPin = 13; // GPIO13
    int ledPin2 = 12; // GPIO13
    int desconectado = 5;
    int conectado = 4;
    WiFiServer server(80);
    WiFiClient client;

    int counter = 0;
    int count;

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

      WiFi.mode(WIFI_STA);

      pinMode(ledPin, OUTPUT);
      digitalWrite(ledPin, HIGH);

      pinMode(ledPin2, OUTPUT);
      digitalWrite(ledPin2, HIGH);

      pinMode(conectado, OUTPUT);
      pinMode(desconectado, OUTPUT);
      digitalWrite(desconectado, HIGH);

      connectWifi();

      Serial.print(F("Setting static ip to : "));
      Serial.println(WiFi.localIP());

      // Start the server
      server.begin();
      Serial.println("Server started");

    }

    void loop() {

      delay(200);

      if (WiFi.status() != WL_CONNECTED) {
        delay(100);
        digitalWrite(conectado, LOW);
        digitalWrite(desconectado, HIGH);
       connectWifi();
      }

      // Check if a client has connected
      client = server.available();
      if (!client) {
        return;
      }

      // Wait until the client sends some data
      Serial.println("new client");
      count = 0;
    while(!client.available()){
    delay(1);
    count++;
    if ( count > 1000 )
    {
    Serial.println("Abandoned Client");
    client.stop();
    return;
    }
    }

    //Serial.println("new client");
    //  int t = millis();
    //  while(!client.available()){
    //  delay(1);
    //  if (millis()-t>130) return;
    //  }

      // Read the first line of the request
      String request = client.readStringUntil('\r');
      Serial.println(request);
      client.flush();

      client.println("HTTP/1.1 200 OK");
      client.println("Access-Control-Allow-Origin: *");
      client.println("Content-Type: text/html");
      client.println(""); //  do not forget this one

      // Match the request
      if (request.indexOf("/switch") != -1)  {
        digitalWrite(ledPin, !digitalRead(ledPin));
        digitalWrite(ledPin2, !digitalRead(ledPin2));
        printSwitch();
      }else if (request.indexOf("/uno") != -1) {
        client.print("Canal 1 apagagado | Canal 2 encendido");
        digitalWrite(ledPin, HIGH);
        digitalWrite(ledPin2, LOW);
      }else if (request.indexOf("/dos") != -1){
        client.print("Canal 1 encendido | Canal 2 apagado");
        digitalWrite(ledPin, LOW);
        digitalWrite(ledPin2, HIGH);
      }else if (request.indexOf("/tres") != -1){
        client.print("Canal 1 apagado | Canal 2 apagado");
        digitalWrite(ledPin, HIGH);
        digitalWrite(ledPin2, HIGH);
      }else if (request.indexOf("/cuatro") != -1){
        client.print("Canal 1 encendido | Canal 2 encendido");
        digitalWrite(ledPin, LOW);
        digitalWrite(ledPin2, LOW);
      }else if (request.indexOf("/cinco") != -1){
        printIP();
      }else if (request.indexOf("/apagaruno") != -1){
        client.print("Canal 1 apagado");
        digitalWrite(ledPin, HIGH);
      }else if (request.indexOf("/apagardos") != -1){
        client.print("Canal 2 apagado");
        digitalWrite(ledPin2, HIGH);
      }else if (request.indexOf("/prenderuno") != -1){
        client.print("Canal 1 encendido");
        digitalWrite(ledPin, LOW);
      }else if (request.indexOf("/prenderdos") != -1){
        client.print("Canal 2 encendido");
        digitalWrite(ledPin2, LOW);
      }else if (request.indexOf("/canaluno") != -1){

        if(digitalRead(ledPin) == HIGH) {
          client.print("Off");
      } else {
        client.print("On");
      }

      }else if (request.indexOf("/canaldos") != -1){

        if(digitalRead(ledPin2) == HIGH) {
        client.print("Off");
      } else {
        client.print("On");
      }

      }

    // Set ledPin according to the request
    //digitalWrite(ledPin, value);

      // Return the response

      delay(1);
      Serial.println("Client disonnected");
      Serial.println("");
      client.stop();

    }

    void printSwitch(){

      if(digitalRead(ledPin) == LOW) {
        client.print("Canal 1 Encendido");
      } else {
        client.print("Canal 1 Apagado");
      }
      Serial.println("");
      if(digitalRead(ledPin2) == LOW) {
        client.print("Canal 2 Encendido");
      } else {
        client.print("Canal 2 Apagado");
      }
    }

    void printIP(){
      delay(100);
      client.print(WiFi.localIP());
    }

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

      // config static IP
      IPAddress ip(192, 168, 1, 66);
      IPAddress gateway(192, 168, 1, 1);
      IPAddress subnet(255, 255, 255, 0);
      WiFi.config(ip, gateway, subnet);
      digitalWrite(conectado, HIGH);
      digitalWrite(desconectado, LOW);
      Serial.println("");
      Serial.println("Connected");
      Serial.println("");

      // Print the IP address
      Serial.print("Use this URL to connect: ");
      Serial.print("http://");
      Serial.print(WiFi.localIP());
      Serial.println("/");
    }//end connect

body: Check the power source. If you're powering it via USB it is likely to malfunction over time, but if you use an external and stable power source you won't have that kind of problem.


message:
Very long range wireless communication between two arduinos(500-1000 KM)

I searched for very long range wireless communications between two Arduinos, but can't find solutions. I don't live in USA, In my country there are regions, where GSM does not work.
I want wireless communication approximately 500-1 000 KMs.
What are options without GSM for that distance wireless communication(500-1000 KM)?

body:
> What are options without GSM for that distance wireless communication(500-1000 KM)?

1) use the internet;

2) use narrow band transmission, like qrp;

3) use relays;

4) use satellite phones;

5) use a high-powered lw transceivers.

6) ...


body:
Back in the old days, we used things called modems to connect computers across POTS.

[![old modems][1]][1]

Your country may not have GMS, but I bet you still have old land lines. In that case, you can use a land line + modem to connect the arduinos directly , no Internet involved, no ISP needed, no overhead, no lag, nothing. It's just one Arduino at each end of a very long cable. No TCP/IP needed, but you need your own protocol to keep data in sync and filter out errors. There is lot of well proven ones from the golden era of BBS.

I search Aliexpress, I didn't find any modem suitable for direct conection with Arduino, but there is a lot of USB modem like this:

[![USB Modem][2]][2]

I don't know if they can work with Arduino. I'm afraid that they are *win-modem* only.

What it really works with anything is a traditional modem, like this [model][3] from Multitech (not an endorsing):

[![Multitech modem][4]][4]

You will need a RS-232 level converter however, because RS-232's voltages can go up to 25V. The converter avoids you to deal with the peculiarities of the RS-232 standard and DB-9 connector.

[![RS232-TTL level converter][5]][5]

And a cable, of course.

You can develop and test your project using a *null modem* cable, to connect both Arduinos, a few meters apart, without need of a land line.

  [1]: https://i.stack.imgur.com/HILmV.jpg
  [2]: https://i.stack.imgur.com/Q5LtI.jpg
  [3]: https://www.multitech.com/brands/multimodem-zba
  [4]: https://i.stack.imgur.com/twd2u.png
  [5]: https://i.stack.imgur.com/0ZDHQ.jpg


message:
Simulate V1838B IR LED output

I have a HDMI switcher which uses a TL1338 IR LED that's connected via a 3.5mm audio jack. It has its own remote for switching between the inputs, but I want to use my TV remote.

In order to do that I want to connect the IR led to an ATTiny85 to receive the input and send the 'translated'code to the switcher.

When analysed with an oscilloscope it seemed that Arduino Libraries output a PWM signal, while the TL1838 outputs a digital signal. Is there a way to simulate a TL1838 signal?

Original situation:
[![Original situation][1]][1]

Goal situation with ATTiny85.
[![Updated situation][2]][2]

  [1]: https://i.stack.imgur.com/hX47O.png
  [2]: https://i.stack.imgur.com/ihD6d.png

body:
What you want to do is send "unmodulated" IR Codes, but the library is trying to modulate them with a 38khz carrier. (The TL1838 device has a built-in demodulator.)

While your question is not a duplicate, [this answer][1] applies.

  [1]: https://arduino.stackexchange.com/questions/18582/how-to-send-unmodulated-ir-signal-via-cable


message:
How to send information from Arduino?

I plan to make an air quality monitoring system that uses Arduino uno, but I can't decide how I will be able to distribute the air condition and harmful gas concentration info and have it available to other people.

Aside from using a GSM module to text individual persons and making a new website to chart the data from the Arduino, what else can I use to receive information that my Arduino sensed to people's smartphones/computers wirelessly?

body:
There is a Wi-Fi module named "ESP-01" (which uses the ESP8266 microcontroller) and it comes ready to be used with Arduino. But better than that, I think, is that you can program it directly via Arduino's IDE if you flash it with [NodeMCU's firmware][1]. You can also use a NodeMCU instead of Arduino, but ESP-01 has the advantage of being much, much cheaper.

  [1]: http://randomnerdtutorials.com/flashing-nodemcu-firmware-on-the-esp8266-using-windows/


body:
You can use a pair of ESP8266 WiFi Transceiver modules (one as the client and the other as the server).

There are a few guides to [getting started with the ESP8266][1] out there, which generally contain some helpful tips.

I also found this fairly straightforward [ESP8266 – Wireless Weather Station with Data Logging to Excel][2] project which illustrates the principle of using a pair of ESP8266 modules as client and server.

  [1]: http://randomnerdtutorials.com/getting-started-with-esp8266-wifi-transceiver-review/
  [2]: http://randomnerdtutorials.com/esp8266-wireless-weather-station-with-data-logging-to-excel/


body:
Others suggest ESP8266, but I think it's now outdated, there's a new and improved version of it available named ESP32, it's better in basically every way (faster, more RAM, ROM etc.), not that much more expensive and can still be programmed using the Arduino IDE, that means programming it just as simple as programming an ESP8266.

Disclaimer: ESP32 Arduino core is still under development, some less frequently used features might be experimental or missing.


body:
> what else can I use to receive information that my Arduino sensed to people's smartphones/computers wirelessly?

take a different route. get the information to a pc (or to a server through a pc) and you have much more flexibility.

there are many ways to get that information to a pc, like serial, spi, i2c, acquisition cards, wired / wireless, ....


message:
ESP-01 adapter and logic level converter

I read that I'll need a logic level converter like [this][1] to run an ESP8266-01 from the Uno.

But I saw this ESP adapter:

http://www.ebay.com/itm/ESP-01-ESP8266-Serial-Wi-Fi-Wireless-Adapter-Module-3-3V-5V-Compatible-Arduino-/282524471281?hash=item41c7c54ff1:g:wp0AAOSwQ59ZaClP

Two questions:

1. The ESP-01 has 8 connections but this has only 4, how come? Will I get the same functionality?

2. If I'll use this adapter, then I won't need the logic level converter?

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

body:
The module has a 3.3V voltage regulator circuit and **5v-3.3v onboard level conversion circuit**.

Yes, the module can be used with Arduino UNO R3 or compatible board without needing an additional level converter, as it is integrated in the module.

The module has Vcc, GND, TX and RX, so it means it uses a serial protocol for Arduino communication (and you will need two pins in the Arduino). Other pins in the ESP-01 are not needed in this scenario, but you still have access to them via the 8-pins female connector on the module.

It's totally plug and play.

**Addendum: The old way**

This how you connect a standard ESP-01 with an Arduino. The module you are looking at include all the resistors and also connect the CH_PD pin to Vcc. You only need to connect four pins. It saves you time, money and space.

[![Tradicional ESP-01][1]][1]

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


body:
The ESP-01 is a microcontroller that works only with 3.3V. If you don't use a logic converter, it will not work correctly with 5V on TX and RX and you might even damage your module if you use it like that. So answering your second question, the important thing to keep in mind is that you need to power it with 3.3V and the logic level of the data you send must also be 3.3V.

As for the number of pins, the 4 pins are for VCC, GND, TX and RX. These are the only ones you'll need to connect with Arduino. The other pins on the ESP-01 are CH_PD, RST and two GPIOs.

(I'm not sure if you need to connect any of these while using it with Arduino, but in my experience using it standalone i know CH_PD must be connected to VCC in operation mode, and RST must be connected with GND on flashing mode.)


body: I used in one of my projects, instead of a logic level converter, some voltage dividers on the pins, Arduino inputs don't mind the 3.3v, it works just the same.


message:
Using multiple sensors on ESP8266 Wifi module

I have an ESP8266 ESP-01 WiFi module.
I have a project where I need to use the following and send their data to a firebase database.

2x Force Sensitive Resistors(Sensor)

1x GPS module

My question is what GPS module can I use to send GPS location thru the ESP8266 Wifi module. My ESP-01 has only 2 GPIO. What should I do so I can use 2 FSR and GPS module at the same time send all 3 data to firebase realtime database.

Thanks

body:
You really need something external to both provide the analog inputs for the force sensors and the serial communication for the GPS module.

The simplest "something" is another microcontroller.  Ideally one with two UART ports.

You can then:

* Communicate between the microcontroller and the GPS with one UART
* Sample the FSRs with the microcontroller
* Format and send the data to the ESP-01 through the other UART

Using `SoftwareSerial` you chould just about do it with an Arduino Uno (though you'd have to disconnect whatever was on the hardware UART every time you wanted to program it), but ideally something with more UARTs would be better, such as a Mega2560.

A halfway house between the two would be a board based around the ATMega32U2 which uses a direct USB connection for programming leaving the hardware UART free to be used permanently. However you'd still need to use `SoftwareSerial` to emulate the second UART (maybe best for the GPS since it's then only used for receiving).


body:
I would go for an i2c A/D converter, example ADS1015 (4 analog input, 12 bit) and connect that to the ESP-01.

Ref.:

https://en.wikipedia.org/wiki/I²C

https://www.youtube.com/watch?v=6IAkYpmA1DQ&t=32s


message:
How to switch on or off up to seven devices individually?

Is there a way to turn on or off the power supply of up to seven hard drives with the help of an Arduino? Or maybe there is another way to ultimately - but restorable - prevent read/write access to the disks.

body:
An Arduino have 13 digital I/O pins so theoretically you can control 13 devices without any additional additional circuits.

You will probably need some circuits for the devices you want to control.


body:
If you want to control them externally, I suggest buying e.g. an 8 channel relay. This way you can easily control them with the Arduino, and using external power for the devices to switch on/off.

If you want extra protection (especially with motors or expecting spikes on signals), use relays with opto-couplers.


body:
Switching power on and off to hard drives is not as simple as you may think.

First you have three voltages to control - 3.3V, 5V and 12V, and on top of that you have (ideally) pre-charging for the 5V and 12V pins. The power-on sequence would ideally be:

1. Power up 5V and 12V pre-charge
2. Power up 3.3V, 5V and 12V main power

That's 5 poles for one drive (although you can get away without the pre-charge).

So you would be switching at minimum 3 power signals per drive. For 7 drives that would be 21 power signals that need to be switched.

**HOWEVER**

**Switching off power to a hard drive using mechanisms that aren't directly under the control of the operating system can cause file-system corruption and data loss.**

The operating system caches data internally and writes it to the hard drive when able to. If the hard drive is turned off while there is still data cached that data will never get written to the hard drive. Worse still, if you turn it off *whilst it is writing* the file-system could become irrevocably corrupted (depending on the file-system in use and the resilience of it).

Most hard drives have the ability to power themselves down at a command from the operating system. I suggest you use this mechanism instead, since it is more reliable that blindly shutting off the power. Chances are your hard drives are already doing this, since most operating systems enable it by default.


message:
SIM900A A6 module Arduino +CME error 58

I've recently bought a SIM900A A6 GSM module. Whenever I send a command it gives an error: +CME error 58.

Does anybody know what this means and how to solve it?

body: Your sim card is probably protected by a PIN. Easiest way to get it working is to put the SIM into a normal phone and remove the PIN protection.


body: I had the same error.  My error was using the incorrect baud rate.  Set the baud rate to 115200.  Also, ensure that "Both NL & CR" option is selected for new line options.  After changing those settings, I had to reboot the A7, and wait for all the status messages to complete before I could send the AT command.


message:
Serial.print and char[] & null

I don't write a lot of C, so I'm always discovering things I only partly understand in the Arduino variety. One of these is how `Serial.print` handles `char[]`.

Does Serial.print always require a null terminator? In the case of (say) `Serial.print(88, DEC);` is a null implied?

What happens in the following cases?

    char buff[3] = "ABC"; // warned because no room for a null
    Serial.print(buff);   // will absence of a null cause overrun?

    char buff[4] = "ABC"; // now there's a null
    Serial.print(buff);   // will the null character be sent too?

Any references appreciated.

body:
When passing a char* you need to also pass some way of telling the function where it ends. In C that is usually the null terminator and that's all a null terminator is for. If that is missing then you get a buffer overrun.

The null terminator is not sent.


body:
The "Serial" is a object/class and that makes it possible to have more than one function for [`Serial.print()`][1]. According to the type of the parameter the proper `Serial.print()` is selected.

This is the include file for the `Serial.print()`: [Print.h][2]
And these are the possibilities:

 - `size_t print(const __FlashStringHelper *);`
 - `size_t print(const String &);`
 - `size_t print(const char[]);`
 - `size_t print(char);`
 - `size_t print(unsigned char, int = DEC);`
 - `size_t print(int, int = DEC);`
 - `size_t print(unsigned int, int = DEC);`
 - `size_t print(long, int = DEC);`
 - `size_t print(unsigned long, int = DEC);`
 - `size_t print(double, int = 2);`
 - `size_t print(const Printable&);`

The reference for [`Serial.print()`][1] is short, but it explains pretty well that those different parameters are possible.

Your `Serial.print(88, DEC);` does not use a string of text, it uses the integer number 88.

As soon as a string of text is used, it should be zero-terminated.
The line `char buff[3] = "ABC";` is indeed wrong, as you already wrote. That is one of the things of the 'c' language. The "ABC" gets a zero-terminater and that makes 4 bytes.

  [1]: https://www.arduino.cc/en/Serial/Print
  [2]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Print.h


message:
Powering Arduino with 12V AC-DC Adapter Jack

I have 12V,700mA AC-DC adapter power jack. Is it ok power on arduino board directly using this power jack?

Though Arduino webpage suggests that arduino can stand and upto 20V power supply, I ask this because somewhere it is written that supply 12v, 700mA will end up the board to smoke and need a converter to make it 5V.

Is this correct?

Thanks,
Jyoti Raj

body: You can use that to power the Arduino through the barrel jack or the VIN pin.  The only way you end up with smoke is if you try to pull too much current through that setup.  Don't power any motors or solenoids directly off of output pins for example.


body:
> Is it ok power on arduino board directly using this power jack?

it depends on the regulator used and the current you expect to draw from the regulator.

essentially, you want to make sure that the power dissipation over the regulator isn't too much. that power dissipation is proportional to the voltage drop over the regulator (Vin - Vcc) and the current draw (20ma + whatever you may draw from the arduino).

once you have that, check against the regulator datasheet to make sure that its temperature rise is within range.


message:
connecting multiple keypads

My project is to use an Arduino to control the lighting of a small apartment. My preferred option is to replace each wall light switch with a 4x4 membrane keypad (https://www.amazon.co.uk/Mirocle-Matrix-Membrane-Keyboard-Arduino/dp/B01LMU6OPG/ref=sr_1_19?s=electronics&ie=UTF8&qid=1504376458&sr=1-19&keywords=membrane+keypad). The UX would allow any keypad to control any light, eg. pressing 1-4 will set light 1 to brightness 4.

The problem I have is this will result require 4 x 8 = 32 pins, so I'm looking for alternatives.

So my questions:-

1/ Is there a simple pll to serial converter that I should be using to interface the keypads?

2/ Can I wire multiple keypads onto the same set of 8 pins? Only one keypad will ever be touched at one time.

3/ Are there simple serial versions of the classic membrane keypad.

body:
As far as I know, you can connect multiple keypads of this type to a single set of 8 pins.  However, it seems like a lot of wire needs to be strung to get this to work, for each switch, 8 wires for the keypad, and two, or more, for power control.

Were I to do this project.  I would likely handle each switch independently, embedding a Pro Mini in each switch box along with an HC-12, or some such.  This means no wires are needed, any pad could control any switch, and expansion is much easier.

Of course, this is only what I would do, and you understand your own requirements far better than I.


body:
Or the 8 pins 4 will be connected to output pins to be enabled one at a time and 4 will be connected to input pins that get shorted to the input pins when the button is pressed.

The way to get a keypress from this will be to pull a single output pin high and then check all of the inputs, if any of them are high then the corresponding button is pressed.

If you want to treat all keypads the same then you can simply put them in parallel. If you want to treat each of them differently then you can parallel either the inputs or the outputs. But the other set needs to have a S2P or P2S shift register to get the proper data or make the correct pin high.

Though it will probably be simpler if each got their own microcontroller to poll the keypad and use a different longer range protocol to communicate to the main controller.


message:
XBee s6b internet

For my project i need to send some data logged into a SD card to a remote server.
For this im using an XBee S6b wifi module connected to an arduino. ive had trouble connecting the xbee module to wifi. and also how can i set the ssid and other information through arduino?

body:
You configure the XBee with AT commands. However there is one important thing to know about the XBee: it loves to be in "data" mode and won't stay in command mode while you play with it.

You need to first get into command mode by sending `+++` with a delay each side of it:

    delay(1000);
    xBeeSerial.print(F("+++"));
    delay(1000);

Then you can send commands:

    // Set the SSID:
    xBeeSerial.println(F("ATIDThis Is My SSID"));
    // Set the wireless key:
    xBeeSerial.println(F("ATPKTh!sI5mYk3Y"));

Once you have set the details you need to write the settings to flash and reset the XBee for the changes to take effect:

    xBeeSerial.println(F("ATWR"));
    xBeeSerial.println(F("ATFR"));

After each command you should really be looking for the "OK" response.

If at any time you don't sent anything for more than a few seconds the XBee will exit command mode and go back to data mode - at which point you will have to go back to command mode with the delays and `+++`.

It's easiest to configure the XBee using your computer and an XBee Explorer.

All the AT commands are detailed [here](https://www.digi.com/resources/documentation/Digidocs/90002180/).


message:
Servos: attach() and write()

Arduino newbie here, so this question might sound too simple. I am trying to run a parallax continuous rotation servo using Arduino Uno. From the reference, I learned that the servo needs to be "attached" to one of digital pins with PWM capability, and the servo's speed can be controlled by `write(0~180, 90=stop)`.

But I am having a hard time understanding the role of the PWM digital pin. If the servo's speed and direction of rotation is determined by `write()`, what is the role of `attach(pin#)`?

Thanks in advance!

body:
`attach` tells the servo library which pin it should be writing to, this is stored somewhere in ram and `write` will look it up and communicate with the correct pin.

It's possible that you are using the other pwm capable pins for other purposes and suddenly having that library interfere with that is not a good thing.


message:
Is it possible to connect nodemcu to mobile internet and how?

Guys i have done project home automation over Android in which i have use NodeMCU and relay to control switching of lights but this is a offline project.

Now I want to connect it with internet please tell me if I can connect NodeMCU to mobile WiFi.

I don't have router at home  please tell me if it is possible and how?

body:
If you have a mobile wifi router, the nodemcu can connect to it just as it would connect to a fixed router.
If you want to connect the nodemcu to the internet without a mobile wifi router, you can use a gsm/gprs/3G/4G module, for example the SIM800L. (Provided the location has cell coverage.)


body:
You don't need an external router or LAN to connect nodeMCU with Android or any other TCP/IP device. nodeMCU is capable of works as a WiFi access point, among other things.

You use he function `wifi.setmode()` to configure the WiFi mode to use. NodeMCU can run in one of four WiFi modes:

 1. **Station mode**, where the NodeMCU device joins an existing network.
 2. **Access point** (AP) mode, where it creates its own network that others can join.
 3. **Station + AP mode**, where it both creates its own network while at the same time being joined to another existing network
 4. **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.

Now, to connect to Internet you will need something else. You can use a SIM800/SIM900 module, which let you conect your nodeMCU to Internet and send/receive SMS.

In this scenario, nodeMCU will connect directly to Internet for your remote connections, and will also works as WiFi router for local connections.

Keep in mind that nodeMCU is a lightweight router.


body:
I have a wifi library.This is how I connect the NodeMCU with that library.

    #include <ESP8266WiFi.h>

    #define WIFI_SSID "name_of_your_hotspot"
    #define WIFI_PASSWORD "password_of_hotspot"

    void setup() {
       Serial.begin(9600);
       WiFi.begin( WIFI_SSID,  WIFI_PASSWORD) ;

        Serial.print("connecting");

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

         Serial.println();
         Serial.print("connected");
         Serial.println(WiFi.localIP);
    }

    void loop () {
        // Your code
    }

I used this tested and working code. Comment if any issue.

Make sure you import the library.

Hope this fixed your issue.

***EDIT : 4th Jan 2018***

I know this topic is old and maybe the OP solved this problem but I saw many people struggling with this same situation how to connect nodeMCU to an internet connection.

So, I created a medium post with detailed information on how to Connect ESP8266 module to the internet? You can read the [story here][1] (I am not paid or sponsored by this post I made this story to help the newbies)

If you still have any problem comment down below or add a response in my medium story.

  [1]: https://medium.com/@raajnadar/connect-esp8266-module-to-internet-81cab724b8c3


message:
How to set Inquire Access Code (IAC) via AT commands on HC-05?

I am trying to set IAC of HC05 via AT Commands, but for some reason, the result is not as desired.

I need to set the IAC as '1234', for which I enter the command:

    AT+IAC=1234

The module responds OK, but when I ask `AT+IAC?`, it replies '01234'.

Now, it has been troubling me for the past few days. I've also tried adding '\r\n' to the end of command, but it sets the IAC as '1234444'

I would be thankful if you could help me with this! I tried searching the net but to no avail.

body:
You have to have `\r\n` in both the set and read command.

Example:

    AT+IAC=12345f\r\n
    OK

    AT+IAC?\r\n
    +IAC: 12345f
    OK


message:
I have built a battery level indicator and have tested with a 12V battery Would it harm my arduino board if I connect a 48V battery?

I am a newbie and have followed a tutorial to build a battery level indicator as below
[![the basic design ][1]][1]

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

Please suggest any changes I'll need to make to make the circuit useful with a 48V battery as the above circuit is tested with a 12V one.
Thank You.

body:
You have a voltage divider there, which would give (if the pre-set pot was set to the maximum):

    Vout = (Vin * R2) / (R1 + R2)
    Vout = (12 * 10000) / (100000 + 10000)
    Vout = 1.09

Thus a 12V battery would present 1.09V at the analog input.

This same wiring would seem to be in range for a 48V battery:

    Vout = (48 * 10000) / (100000 + 10000)
    Vout = 4.36

Since the analog input can handle up to 5V, then that should be OK. However I would test the voltage divider output first with a multimeter to make sure it doesn't exceed 5V - before connecting it to the Arduino.

---

You would probably need to change the code to test for different ranges of input voltages, other than what is used for the 12V battery.


body:
To get a smoother switch from one level to another you could introduce another resistor and use analogWrite() to dim one LED and make next brighter.

Ref.: https://www.arduino.cc/en/Tutorial/PWM

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

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


message:
Low power RGB LED for wearable device

I am trying to prototype a wearable device which will have about 120 RGB LEDs. I was considering the WS2812B but they seem to draw about 50mA and so may not be a good option since I will be powering them from a battery.

I would be glad to know of other options or ways to implement the LEDs in order to consume less power.

body:
You can reduce the current by simply reducing the duty cycle. For example, to display red, rather than sending 255 as the red component, send 42.

If you divide each of the R/G/B values by the same figure you get the same colour, just duller. In a quick test I found that a 24-pixel strip only used 67 mA if I sent red=0, green=0, blue=42 which made them look a dull blue. If you send a value of 8 (in a single channel) then it takes 25 mA for 24 pixels.

A bit more testing reveals a base consumption of 21 mA even if you are sending black. That is, the overhead is 21 mA, which works out at about 1.1 mA per neoPixel.

Based on that, you would consume 335 mA to make 120 NeoPixels show a moderately bright red.

I don't think there is going to be some "magic bullet" that lets you light up 120 LEDs brightly, but not use much power. However using the NeoPixels which lets you have fine control over the brightness of each of the R/G/B pixels is probably going to be about as close as you can get.

The figure of 50 mA which you quoted is to have "full brightness" on all three colours (ie. bright white).


message:
HC-05 module short circuit

I have bought a HC05 bluetooth module and I think I accidentally short circuited it. Is there any way to change the voltage regulator or methods to reuse it again?

body:
I suppose you're referring to the HC05 module, already soldered on a board, with the 6-pin header. The regulator is on that board.

Online you'll find several versions of that board, therefore you should check the schematics, to find which you need to mount. For instance, on some board, a R1114-33 is used.

Changing the regulator is not the hardest task on earth, however, other components are very close to it (capacitors).

Still there are 2 things to consider:

 - Is it worthy to change the regulator? That module will cost few
   bucks.
 - As you can see from the datasheet, the regulator is short-circuit protected (yes, it does not mean that it will be indestructible). I think, instead, you destroyed one of the two ICs of the bluetooth module soldered on board. And those one, beside of being quite difficult to find and expensive in small quantity, they are very hard do replace.

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

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


message:
Differences between Arduino IDE versions

I run Arduino IDE on both my Mac and under Raspbian on a Raspberry Pi, both running the latest version of OS.

The Raspberry Pi has `Arduino 2:1.0.5+dfsg2-4.1` and I am running the latest `1.8.4` on macOS.
Debian is always somewhat behind the latest software, and this has not concerned me before, as I have never had issues before. (I know I could download the latest ARM32 build or compile from source, but this would probably generate a lot of dependencies.)

I have recently run into a couple of problems.
Compiling a script which has `#include <SdFat.h>` generates an error, although the library is present in `~/sketchbook/libraries/SdFat/src/SdFat.h`. This does not seem to be an issue on macOS.

I was also trying to program an Atmega using a Uno as ISP as in "Using an Arduino as an AVR ISP". I have done this in the past, but the instructions and the Arduino program seem to have changed; there is no longer "Upload Using Programmer" menu, but suggests the "Burn Bootloader" command. Does this upload both the Bootloader and Sketch?

body:
> Debian is always somewhat behind the latest software

No, when it comes to the Arduino IDE Debian is *frozen* on an ancient version.

1.0.5 is considered to be too old to use. Many many things have changed since then - bug fixes, optimisations, new API components. And not least the implementation of the Board Manager for installing support for more boards, both by Arduino and other makers, and support for multi-arch libraries (which your SdFat library is with a `src` folder in it).

You should never install the Arduino IDE from the Debian repositories. Instead you should download the current version of the Arduino website (http://arduino.cc/download) as a tar.\z file and extract it into a folder and run it from there.


body:
Majenko answered why my sketch did not compile.

I decided to give it a try and downloaded `arduino-1.8.4-linux32.tar.xz`.
I was somewhat concerned that there seemed to be no indication whether the `Linux ARM` supported ARM6, or ARM7.

The download itself contained absolutely no information, not even a README. I ran `install.sh` as outlined in  https://www.arduino.cc/en/Guide/Linux and Arduino IDE installed alongside the existing Arduino IDE, and worked (at least on the PI3).

I also solved my issue using a Uno as ISP. The documentation on the Arduino site now describes "Use the Burn Bootloader command". I found the missing "Upload Using Programmer" menu under the Sketch menu.


message:
Can't upload the program to Arduino Uno

My Arduino Uno R3 is not detected by any laptop (I tried 3 laptops). Under devices there is no Arduino port or other devices option. It does not make sound on inserting USB cable. On plugging the USB LED 13 doesn't blink. I is just continuously on. Reset also didn't blink LED 13. Even on external power also it's not resetting.

I checked the USB cable but it's working for my friend's Arduino in my laptop too.

5V Pin giving voltage around 4.96 v, and 3.3 also giving voltage around 3.27 v.

Now I don't have access to any other Arduino for testing. Is there any way to figure out whether the ATmega chip is fried or whether it's a bootloader problem? And how to fix them? Thanks in advance.

body:
If you have access to a linux computer, what does `lsusb` say when it is plugged in over USB? Compare that output to lsusb with no Arduino plugged in. If you don't, does the arduino show up as a device to your OS at all?

[You could also use your friend's arduino to reflash your bootloader][1]. If that still doesn't work, or if your arduino doesn't show up as a device, [you can try reflashing the atmega16u4][2] ( the USB <-> serial chip ). It is the chip responsible for telling the computer that it is an arduino serial port, so if things are still getting power, but not showing up, I would check that chip.

If it is neither of those things, there may be something wrong with one of the passive USB components, maybe one of the varistors died and is now shorted to ground, for instance. I could give more help if you share the schematic for your specific board.. is it an official Arduino, or a clone?

  [1]: https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader
  [2]: https://www.arduino.cc/en/Hacking/DFUProgramming8U2


body:
> Can't upload the program to Arduino Uno

if your trouble is limited to just "the program", then the issues must be specific to that program.

if you cannot upload "any program", then the issues must be hardware or host related.


body:
While installing the Arduino software,

there are several **window pop ups** which occur to **install the  drivers** needed for the operating system to communicate with the device.

Click **install** to all of them.


body: It is probably not a problem with the Atmega328p chip or its bootloader; the Uno has a separate processor to handle USB - an Atmega 32U4, which is the flat, surface-mount chip right behind the USB connector on the board. If that or its firmware is damaged, your PC won't recognize the device when you plug it in. If that chip is up and running, your PC will see it.


message:
Known conflicts between use of HC-12 and Ethernet Shield on Mega2560?

I have two somewhat similar sketches that use both HC-12 [for data collection] and a W5100-type Ethernet Shield [for Email construction and transmit].
Both sketches run fine until the code for the Ethernet Shield is invoked, which creates a connection and successfully transmits an Email.
Once this happens, the HC-12 no longer receives transmits.  No exceptions are raised, and I am at a loss to determine the cause of the problem.
[The HC-12 is using pins 50-52.]

I have other sketches that use either the HC-12 or the Ethernet Shield, and they work fine.  Before I build a custom sketch to attempt problem isolation,
I thought I would simply ask the question of whether known conflicts exist.  I know that many questions are resolved by posting the sketch and someone other
than the author scanning it.  I think that impractical in this particular case.  The sketch comprises 6,000+ lines of code.

If no helpful responses are forthcoming, I will continue with problem isolation, and post again if no success is achieved.

body:
As suggested by Majenko, the problem results from using Software Serial for the HC-12, and unfortunately choosing the pin set 50-52, which conflicts with the pin usage specification for the Ethercard Library.
Hence, the HC-12 code works fine until usage of the Ethernet shield is finally activated.  From that point on, the Ethernet code functions properly,  whilst the HC-12 code does not.  The recommended solution, which does indeed solve the problem, is to abandon usage of SoftwareSerial for the HC-12, and use Serial1, or Serial2, or Serial3 instead.

I do not feel that the solution to the problem is truly mine, but post it only that the information may be of subsequent use to a user encountering a problem of similar nature.


message:
Midi Program not sending notes

I'm working on a midi device with a pro micro, it's reading as a midi device, but not outputting any notes, here's my program:
    const int button1 = 2;
    const int button2 = 3;
    const int button3 = 4;
    const int button4 = 5;
    const int button5 = 6;
    const int button6 = 7;

    int note = 0;

    const int c3 = 36;
    const int d3 = 38;
    const int e3 = 40;
    const int f3 = 41;
    const int g3 = 43;
    const int a3 = 45;

    void setup() {

      pinMode(button1,INPUT);
      pinMode(button2,INPUT);
      pinMode(button3,INPUT);
      pinMode(button4,INPUT);
      pinMode(button5,INPUT);
      pinMode(button6,INPUT);

      Serial.begin(31250);

    }

    void loop() {
      int button1State = digitalRead(button1);
      int button2State = digitalRead(button2);
      int button3State = digitalRead(button3);
      int button4State = digitalRead(button4);
      int button5State = digitalRead(button5);
      int button6State = digitalRead(button6);

      if (button1State == HIGH) {
        note = c3;
        noteOn(0x90, note, 0x64);
      }
      if (button1State == LOW) {
        note = c3;
        noteOn(0x90, note, 0x00);
      }

      if (button2State == HIGH) {
        note = d3;
        noteOn(0x90, note, 0x64);
      }
      if (button2State == LOW) {
        note = d3;
        noteOn(0x90, note, 0x00);
      }

      if (button3State == HIGH) {
        note = e3;
        noteOn(0x90, note, 0x64);
      }
      if (button3State == LOW ) {
        note = e3;
        noteOn(0x90, note, 0x00);
      }

      if (button4State == HIGH) {
        note = f3;
        noteOn(0x90, note, 0x64);
      }
      if (button4State == LOW) {
        note = f3;
        noteOn(0x90, note, 0x00);
      }

      if (button5State == HIGH) {
        note = g3;
        noteOn(0x90, note, 0x64);
      }
      if (button5State == LOW) {
        note = g3;
        noteOn(0x90, note, 0x00);
      }

      if (button6State == HIGH) {
        note = a3;
        noteOn(0x90, note, 0x64);
      }
      if (button6State == LOW ) {
        note = a3;
        noteOn(0x90, note, 0x00);
      }

    }

    void noteOn(int cmd, int pitch, int velocity) {
      Serial.write(cmd);
      Serial.write(pitch);
      Serial.write(velocity);
    }

body:
Check:

- If your serial properties are ok (baudrate 31250, 8 bits, 1 stop bit)
- Check if noteOn is really called (print out the values which are sent)
- Show your MIDI circuit, assuming you think no MIDI notes are send because you have a MIDI connector attached.
- Use a protocol analyzer if you have one to check the MIDI signals sent
- Check the components of your circuit, e.g. if you use an opto-coupler, what types is it? some are too slow for MIDI
- Do not use virtual serial ports, I tried with MIDI and they give bad results (checked on Uno).


body:
You are handling your buttons in completely the wrong way. You are basically saying:

> While I press this button send a constant stream of NOTE ON commands. Otherwise send a constant stream of NOTE OFF commands.
>
> At the same time, send more NOTE OFF commands because the other buttons aren't pressed.

So you can see it's going to be a bit of a mess.

Instead you need to detect *changes* in the state of a button.

For example:

    void loop() {
        static bool oldButton1 = LOW;

        bool button1State = digitalRead(button1);

        if (button1State != oldButton1) { // It changed from last time
            oldButton1 = button1State; // Remember it for next time
            if (button1State) { // Pressed
                noteOn(0x90, c3, 0x64);
            } else { // Released
                noteOn(0x80, c3, 0x00); // Note: 0x80 is NOTE OFF, not 0x90.
            }
        }

        ... etc for the other buttons ...
    }


message:
Wiring diagram for Arduino to prevent relay firing on reboot

I'm starting to explore using an Arduino to control a couple of switches programatically. I have read somewhere about relays firing during reboot due to floating inputs/outputs during the reboot phase.

What is the best way to ensure that a relay will not fire on a reboot?

Is there a simple wiring diagram to explain it? I am using an Arduino Uno and a [Relay Module][1].

Any assistance would be greatly appreciated.

  [1]: https://www.jaycar.com.au/medias/sys_master/images/8978832654366/XC4419-dataSheetMain.pdf

body: You can add a pull down/up resistor between the wire and ground/vcc so that when the arduino pin is set to high impedance during reboot the wire is pulled low/high as desired.


body:
Two things:

1. If that relay uses a FET input with no pulldown then you should add your own. If it uses an opto-isolator there is no floating problem to deal with.
2. Don't use pin 13 for a relay - that is connected to the LED which blinks during reset and will "flash" your relay.


body:
> What is the best way to ensure that a relay will not fire on a reboot?

put pull-up/down, as appropriate, on those pins.


message:
Avoiding false rising and falling edge when using demultiplexer

I have 8 sets of 8 push buttons. There is a Teensy and a demultiplexer. The demultiplexer has 8 outputs. When an output is selected it is pulled low. Each output is connected to a group of 8 push buttons. The 8 push buttons are then connected to 8 pullup inputs on the Teensy.

Each group of 8 push buttons is connected to a unique demultiplexer output, but all the push buttons are connected to the same 8 inputs on the Teensy. That is, push button #1 in group 1 shares a Teensy input with push button #1 in group 2. The push buttons are isolated from each other with diodes.

I'm using `bounce.h` for debouncing. It looks for rising and falling edges.

The problem is this:

- Push button #1 in group #1 is pressed, pulling that input low, causing a falling edge to be detected. This is good.
- The demultiplexer shifts to group #2, where the #1 button hasn't been pressed, and thus is high.
- Because both #1 buttons in group #1 and #2 share the same input line, the Teensy sees this change as a rising edge. This is undesired.

What is the better approach to this?

Thanks,

Dan

body:
To do multiplexing with bounce.h you will need one bounce object *per button*. That's 64 bounce objects for an 8x8 matrix.

Then you only want to update the bounce objects *for the group you currently have active*.

That is:

1. Switch to group 1.
2. Update objects 1-8
3. Switch to group 2
4. Update objects 9-16
5. ... etc ...

You need one object per button so that the internal data can track the state of that specific button, and you only update the 8 objects for the currently selected group otherwise the objects that aren't associated with that group will get confused by incorrect data.


body:
> What is the better approach to this?

write your code so it debounces each pin / group of pins separately.

looks like your code used global / static variables.


message:
Arduino MEGA2560 Standalone

I had an Arduino UNO (ATmega168) standalone working, but I need more pins, and I decided to use the ATmega2560, I was searching for some schematics, and none of them shown an ATmega2560 standalone, only the full Arduino, with the FTDI, power transformers... etc integrated. So taking parts from those designs, I made this, but I don't know if it's enough or I need Something more:
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/eQ5n1.png
Note: VCC2 is connected to 5V.

body:
You need more decoupling capacitors - one per VCC and AVCC pin, plus a larger (10µF) for the whole chip.

You need a pullup resistor (and maybe button) on RESET.


body:
1. check the datasheet;

2. I would put a pull-up on the reset pin, plus a small capacitor;

3. crystal + capacitors as optional;

4. AVCC to VCC with filtering, if you need good analog performance;

5. separate Vbat domain, if it has one.

...


message:
ESP needs a reboot after wifi OTA flash

I would like to use OTA in some of my less accessible esp's. I am using the examples/BasicOTA and BasicOTA_test. My esp is a -01 model with 1Mb of flash.

I upload the BasicOTA to my esp through the COM port, then upload the BasicOTA_test over WiFi.  Everything appears to go OK, but the test sketch doesn't run until I press reset on the esp.

If I upload BasicOTA over the com port then upload a simple blink sketch over WiFi without the OTA code, it uploads fine then runs without a reset.  But then, I can't upload over WiFi anymore.

If I have to hit reset every time I upload a new sketch that contains the OTA code, then why bother?

Tips would be appreciated.

body:
I've done some research and this appears to be a common problem while using OTA to update the ESP8266. In fact, this bug has been reported on their [GitHub][1] and it's due to the watchdog timer resetting after the ESP8266 is flashed via OTA.

It appears the problem can be solved by manually resetting (once) after you upload it via serial BEFORE you can upload it via OTA. After that, you shouldn't have any problems.

  [1]: https://github.com/esp8266/Arduino/issues/2478


body:
You can add `ESP.restart()` in the following line to make it restart.

    ArduinoOTA.onEnd([]() {
    Serial.println("\nEnd");
    ESP.restart();
    });

Now you can upload code each time without hitting reset.


message:
Particle Spark (Arduino) How to flash 2 LED sequences at the same time?

I can't find any information that relates to my problem. The few things I did find confused me (I'm quite new to this).

I'm trying to flash 2 sequences of 4 lights at the same time. I can get 1 set flashing but I don't know how to run other sequences at the same time. My probably laughable attempt at the code is below:

    int led1 = D0;
    int led2 = D1;
    int led3 = D2;
    int led4 = D3;
    int led5 = D4;
    int led6 = D5;
    int led7 = D6;
    int led8 = D7;

    void setup() {
      setupPart1();
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);
      pinMode(led4, OUTPUT);
      setupPart2();
      pinMode(led5, OUTPUT);
      pinMode(led6, OUTPUT);
      pinMode(led7, OUTPUT);
      pinMode(led8, OUTPUT);
    }

    void loop() {
      loopPart1();
      digitalWrite(led1, HIGH);
      delay(500); // delayed for half a second
      digitalWrite(led1, LOW);
      digitalWrite(led2, HIGH);
      delay(500); // delayed for half a second
      digitalWrite(led2, LOW);
      digitalWrite(led3, HIGH);
      delay(500); // delayed for half a second
      digitalWrite(led3, LOW);
      digitalWrite(led4, HIGH);
      delay(500); // delayed for half a second
      digitalWrite(led4, LOW);
      loopPart2();
      digitalWrite(led5, HIGH);
      delay(500); // delayed for half a second
      digitalWrite(led5, LOW);
      digitalWrite(led6, HIGH);
      delay(500); // delayed for half a second
      digitalWrite(led6, LOW);
      digitalWrite(led7, HIGH);
      delay(500); // delayed for half a second
      digitalWrite(led7, LOW);
      digitalWrite(led8, HIGH);
      delay(500); // delayed for half a second
      digitalWrite(led8, LOW);
    }

body:
I cover this exact question in my web page: <http://www.gammon.com.au/blink>

Example code that blinks two LEDs at different rates:

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

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


body:
This kind of problem (doing several things in parallel) is frequent enough to merit a more elegant solution. While projects like this are excellent ([Tasks: A Time-Triggered Scheduler for Arduino][1]), I can't get it working.

I wrote this minimal self-contained example of how to do two things simultaneously. It will blink the built-in LED and write "*" to the serial monitor:

    --- Task Scheduler ---
    Runtime in SS:MMMM
    10:9 **********
    110:64 **********
    210:89 ***

This is the sketch. Study it and adapt it to your own problem:

    /*
     * Task Scheduler for Arduino/ESP2866 by Look Alterno - 2017/8/9.0
     * Show how to execute tasks at regular intervals without using delay() or interrupts.
     * For educational purposes only; not production ready.
     *
     * This sketch have two example tasks running:
     * - Task 1 blinks the builtin led every second
     * - Task 2 write lines with run time and one "*" every ten seconds in the Serial Monitor.
     * Tasks are run in sequence, so keep them short.
     * No interrupts are used; you have to call runTasks() in each loop() pass.
     */

    // Definition: Every task must receive nothing and return nothing.
    typedef void (*fcnptr)();
    //  Here we must declare our task functions (required by C)
    void fcnBlink();      // Task 1
    void fcnSerial();     // Task 2
    //  Add more tasks here.

    //  The interval between fcnBlink execution. Adjustable between 25 to 250 ms.
    //  LED still will blink every second at the same freq (250ms on, 750ms off).
    #define BLINK_LEN 25

    //  The task list
    struct {
     uint8_t  runnable;  // The task is runnable (true/false).
     uint32_t start;     // Next start time for the task (ms).
     uint32_t interval;  // Execution interval in ms.
     fcnptr fcn;          // Function to execute.
    } taskList[] = {
     {true, 0, BLINK_LEN,fcnBlink}, // Execute fcnBlink every 25 ms, blink LED every second
     {true, 0, 10000,    fcnSerial} // Execute fcnSerial every 10 seconds.
     // Here you can add other tasks.
    };
    // The number of task in our task list.
    const uint8_t nTasks = sizeof(taskList) / sizeof(taskList[0]);

    void setup() {
      // Just a standard setup. Nothing is required for task execution.
      Serial.begin(9600);
      while(!Serial) {};
      randomSeed(analogRead(A0));
      Serial.println("");
      Serial.println("--- Task Scheduler ---");
      Serial.println("Runtime in SS:MMMM");
      pinMode(LED_BUILTIN, OUTPUT);
    }

    void loop() {
      // Here you write your processing code (without using delay())
      // --- Start of your code.
      // Some random delays to simulate work
      // Just a bit less than half fcnBlink interval length.
      // You can change BLINK_LEN to test other scenarios.

      delay(random(1, BLINK_LEN / 2));

      // --- End of your code
      runTasks();  // At the end of the loop(), but can be anywhere.
    }

    /*
     * Check the task list and execute them.
     * Sequence of execution guaranteed: tasks could be delayed,
     * but not omitted or executed of order.
     */
    void runTasks() {
      uint32_t now = millis();
      for(uint8_t i=0; i < nTasks; i++) {
        if(taskList[i].runnable) {
          uint32_t diff = now - taskList[i].start; // ms since last execution.
          if(diff >= taskList[i].interval) {
            taskList[i].start = now; // Have to be the same for all task, to keep sync.
            taskList[i].fcn();
          }
        }
      }
    }

    /*
     * Blink the led.
     */
    void fcnBlink() {
      // Called every 25 milliseconds. Turn on the led in the
      // 10 first passes and turn off in the next 30.
      static uint8_t count = 0;
      count++;
      if(count <= 250 / BLINK_LEN) {
        digitalWrite(LED_BUILTIN, HIGH);
      } else {
        digitalWrite(LED_BUILTIN, LOW);
        if(count == 1000 / BLINK_LEN) {
          count = 0;
        }
      }
    }

    /*
     * Print run time (s) and a row of ten "*"
     */
    void fcnSerial() {
      static uint8_t count = 0;
      count++;
      // Print run time in seconds:miliseconds at the start of each line
      if (count == 1) {
        uint32_t now = millis();
        Serial.print(now/1000);
        Serial.print(":");
        Serial.print(now00);
        Serial.print(" ");
      }
      Serial.print("*");
      if(count == 10) {
        Serial.println();
        count = 0;
      }
    }

  [1]: https://chrisbarlow.wordpress.com/2016/04/27/tasks-a-time-triggered-scheduler-for-arduino/


message:
Connecting Arduino to the ESP8266

I want to run more stepper motors and would like to know if there is a way to connect the Arduino and the ESP8266 NodeMCU together for more functioning.

body:
Absolutely. I'll use the Arduino UNO and the ESP8266-01 WiFi module as an example:

<hr>

![ESP8266 to Arduino Uno][1]

 1. The ESP8266 works with 3.3V and not 5V, so you need to connect the 3v3 pin on the Arduino to the VCC and CH_PD pins on the ESP8266.
 2. Connect the GND pin on the Uno to the GND pin on the ESP.
 3. Connect the RESET pin on the Uno to GND. Grounding the RESET pin
    effectively causes your Arduino to work as a dumb USB to serial
    connector (which is what we want to talk to the ESP8266).
 4. Connect the CH_PD pin on the ESP8266 to the 3.3V line
 5. Connect the RXD pin on the Arduino Uno to the RX pin of the ESP8266.
 6. Connect the TXD pin on your Arduino Uno to the TX pin of the
    ESP8266.

Normally, when you want two things to communicate over serial, you'd connect the TX pin of one to the RX of the other (send --> receive). In this case, however, the Arduino isn't talking to the ESP8266; the computer is talking to the ESP8266 via the Arduino.

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


message:
ESP8266 error: espcomm_upload_mem failed while uploading sketch

First of all, I would like to apologize for posting this error once again to this community. However, I have been studying articles for last many days to resolve this error. Unfortunately, I did not get any solution which could resolve my problem.

Below is the error which I get when uploading a sketch (even the example sketch):

warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

Here are the connections:
Vcc - 3.3V
RST - 3.3v
CH_PD - 3.3v
Tx - Rx
Rx - Tx
GPIO0 - GND
GND - GND

I tried various combinations like Tx to Tx, Rx to Rx, pulling off GPIO0. Pulling off reset and ch_pd. Supplying external power source, supplying power directly from Arduino using 3.3V. Supplying power from Arduino 5V using an LD33V regulator. I have even tried uploading the code using USB to TTL. But every time I get exactly the same error.

body:
Well, first of all you should make sure that the voltage on both Tx and Rx pins of the ESP8266 is 3.3V (the Tx and Rx voltage on Arduino is 5V). Personally, I've never succeded in using an Arduino to program the ESP (even though there are plenty of examples of this setup in the web). After a while, I just gave up and bought a converter to do the job for me (it's totally worth it).

Even so, I got this error a few times. You must keep two things in mind:

1. In operation mode, the CH_PD pin must be connected to 3.3V, but it won't do any harm to let it connected during the flashing, so I just soldered a wire between these two pins to make things easier.

2. In flashing mode, GPIO0 must be connected to GND. It won't work otherwise. I strongly recommend you using a usb converter for this, and only connect it to your computer once GPIO0 has been set to GND. This has solved this issue for me, in fact I even soldered a switch on my converter between GPIO0 and GND.

Hope this answers your question.

EDIT: Here are some photos of the setup

[![ESP-01 with the wire soldered between CH_PD and VCC][1]][1]

[![USB to Serial converter for the ESP-01 (and a switch poorly soldered on the back)][2]][2]

  [1]: https://i.stack.imgur.com/GClra.jpg
  [2]: https://i.stack.imgur.com/a3bnv.jpg


body: Please verify you're choosing the right board -Generic ESP for ESP-01.


message:
How to vibrate Adafruit Feather 32u4 Bluefruit LE device?

I have 11 Adafruit Feather 32u4 Bluefruit LE devices. I want to vibrate my devices using a signal through an app. Is there any signal (Code from app like 0x56-NeoPixel checking, 0x43-clear color) or any sketch? Please provide me.

body:
The Adafruit Feather you are talking about is a small format Arduino compatible with BlueTooth Low Energy, USB and battery connector. It doesn't have any way to vibrate without adding external hardware.

[![Adafruit Feather][1]][1]

Now, having Bluetooth in the package means that it can comunicate with an Android Phone, and can send/receive commands, post results, anything you need.

We don't provide sketchs for particular projects. You must learn how to program Arduino and Android. Follow the examples and tutorials widely available in the Web.

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


message:
Adafruit Motor Shield and Bridge Library for Yun Shield

I am using the Leonardo board with the Adafruit Motor Shield v2, 2 steppers and the Yun Shield. The yun shield and steppers all run harmoniously, however, as soon as I do Bridge.begin() and anything that accesses the Yun shield Bridge library to access the console, the steppers stop running. Is this to be expected and are there any solutions?

Thanks

body:
Looking at Bridge.begin() description [here](https://www.arduino.cc/en/Reference/YunBridgeBegin)
 you can see this is blocking function.

>begin() is a blocking function. Once you call Bridge.begin(), nothing else will happen in your sketch until it has completed. This process takes approximately three seconds.


message:
Data from RC522 to firebase real time database

#include<ESP8266WiFi.h>
    #include<SPI.h>
    #include "MFRC522.h"
    #define RST_PIN D3
    #define SS_PIN D4
    MFRC522 mfrc522(SS_PIN, RST_PIN);

    void setup() {
      Serial.begin(9600);
      SPI.begin();
      mfrc522.PCD_Init();
    }

    void loop() {
      if ( !mfrc522.PICC_IsNewCardPresent() ) {
        delay(50);
        return;
      }

      if ( !mfrc522.PICC_ReadCardSerial() ) {
        delay(50);
        return;
      }

      Serial.print(F("Card UID: "));
      dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
      Serial.println();
    }

    void dump_byte_array(byte *buffer, byte bufferSize) {
      for ( byte i = 0; i< bufferSize; i++ ) {
        Serial.print(buffer[i] < 0x10 ? " 0" : " ");
        Serial.print(buffer[i], HEX);
      }
    }

I am able to get the unique ID of the RFID tag & card. But now the problem is that how can I send the unique ID from ESP8266 to the firebase realtime database.

The hexadecimal values that are generated are they unique? or they are something else? Because in some youtube videos I saw people using only numbers as a unique ID from RFID to distinguish between 2 cards or tags.

The wifi connection and firebase auth all are set peoperly ony the unique id number is the problem.

body:
The "UID" of the card is supposed to be unique. Most RFID chips also have blocks of readable/writable space, but some systems do only use the UID from the chip as the complete identifier.

It may be that you come across RFID chips that have utilized random bytes as the UID, in which case there is a chance of duplication. Depending on the number of possible cards to be used in your system, this may or may not be a big worry for you. If it is a big worry, you may want to use the actual memory on the RFID chips to store your user's ID data.

Regarding HEX versus numbers -- Hexadecimal is just one way to represent numbers.
Your code:

    Serial.print(buffer[i], HEX);

tells the print command to take the byte at `buffer[i]` and print its value in Hexadecimal format. You could replace `HEX` by `DEC` to see the base-10 (decimal) value instead. The actual bits underneath would be the same -- it's just one way to display/represent the underlying number.

One byte (8 bits) of data can be represented in decimal as the numbers 0 through 255. The same byte can be represented in Hexadecimal as 0x00 through 0xFF. ('0x' is one way to denote that what follows are hexadecimal values.) Each 'digit' in hex represents 4 bits of data (0-15 in decimal), so 2 hex digits can represent 16^2 values (256 decimal), hence 0-255 as the 1-byte range of decimal values.

(That explanation assumes un-signed types.)


message:
Using Multiple identical sensors - Beginner

I'm trying to make an interactive installation where I have 6 pressure pads that each control an Air Fan. The pressure sensors ideally will be on chairs.

I would like the changes in pressure to change the speed of the Air Fans.

What is the easiest way for me to do this? Can I do it with just an Arduino?

I haven't bought anything yet as I'm assessing what the best route is.

body:
If you mean [this][1] kind of sensor:

The sensor is a simple microswitch with mechanical pressure switching point, which means your Arduino just needs to monitor 6 digital inputs. That is entirely possible.

The sensors would have one side connected to ground, and the other to a GPIO pin on the Arduino, with a pull-up resistor to 5V. Your code should just check each of the 6 GPIO inputs. If the pressure sensor is tripped, the input would be `LOW`, otherwise `HIGH`.

  [1]: https://www.aventics.com/de/en/pneumatics-shop/series-pm1-pgr.256289


body:
Yes one Arduino have enough in and out-put to make your project fly.

The sensor that would detect pressure sensor is called "Force Sensitive Resistor".

Example: http://www.ladyada.net/make/midisense/forcesensors.html

They need some amplifier circuitry that could adapt the sensors low output signal to an Arduino analog input.

And to make six digital output that uses PWM to control the FAN's is also quite straight forward. but may also be subject to some driver circuit.


message:
Breaking out of while loop using IR remote input

I'm trying to control a series of LEDs using an IR remote. I have a problem when I try to play a sequence with the LEDs where they all light up in a line and turn off accordingly. I loop through the sequence and I am trying to make it so the instant I press a button on the remote it breaks out of that sequence. The issue lies in the Flash(); function, I think. What can I do?

    #include <boarddefs.h>
    #include <IRremote.h>
    #include <IRremoteInt.h>
    #include <ir_Lego_PF_BitStreamEncoder.h>

    int recvPin = 11;
    IRrecv irrecv(recvPin);
    decode_results results;

    #define BUTTON_ON 0xF076C13B    // codes for different buttons on the remote
    #define BUTTON_OFF 0xFF9186B7
    #define BUTTON_R 0xE5CFBD7F
    #define BUTTON_G 0x8C22657B
    #define BUTTON_B 0x2A89195F
    #define BUTTON_FLASH 0x35A9425F

    int rLED = 5;
    int gLED = 4;
    int bLED = 3;
    int stR = LOW;  // intital state of red LED
    int stG = LOW;  // intital state of green LED
    int stB = LOW;  // initial state of blue LED
    int flash = false;

    void setup() {
      Serial.begin(9600);   // Status message will be sent to PC at 9600 baud
      pinMode(rLED, OUTPUT);
      pinMode(gLED, OUTPUT);
      pinMode(bLED, OUTPUT);

      irrecv.enableIRIn();
    }

    void Flash() {    // flashing function
      while (flash == false) {
        digitalWrite(rLED, LOW);
        digitalWrite(gLED, LOW);
        digitalWrite(bLED, LOW);
        digitalWrite(rLED, HIGH);
        delay(75);
        digitalWrite(gLED, HIGH);
        delay(75);
        digitalWrite(bLED, HIGH);
        delay(75);
        digitalWrite(rLED, LOW);
        delay(75);
        digitalWrite(gLED, LOW);
        delay(75);
        digitalWrite(bLED, LOW);
        delay(75);
        stR = LOW;
        stG = LOW;
        stB = LOW;
        if (results.value == BUTTON_OFF)    // attempting to make it so when i press the OFF button on the remote,
        {                                   // the loop breaks/stops and I can go back to pressing any button on
          break;                            // the remote
        }
      }
    }

    void loop() {
      if (irrecv.decode(&results))
      {
        if (results.value == BUTTON_ON)
        {
          digitalWrite(rLED, HIGH);
          digitalWrite(gLED, HIGH);
          digitalWrite(bLED, HIGH);
          stR = HIGH;
          stG = HIGH;
          stB = HIGH;
        }
        if (results.value == BUTTON_OFF)
        {
          digitalWrite(rLED, LOW);
          digitalWrite(gLED, LOW);
          digitalWrite(bLED, LOW);
          stR = LOW;
          stG = LOW;
          stB = LOW;
        }
        if (results.value == BUTTON_R)
        {
          digitalWrite(rLED, !stR);
          stR = !stR;
        }
        if (results.value == BUTTON_G)
        {
          digitalWrite(gLED, !stG);
          stG = !stG;
        }
        if (results.value == BUTTON_B)
        {
          digitalWrite(bLED, !stB);
          stB = !stB;
        }
        if (results.value == BUTTON_FLASH)
        {
          Flash();    // calling flash func
        }
        irrecv.resume();
      }
    }

body:
Replace delay with millis in `Flash()`.

You do this by making every delay it's own state and give each state a number. Then inside `flash` you check which state you are in to set the LEDs and how long you have been in it to trigger the next state.

    boolean flashing = false;
    int flashingState = -1;
    long nextFlashingState = 0;

    void Flash() {    // flashing function
      if(!flashing ){
        flashingState =-1;
        return;
      }

      long ms = millis();
      switch(flashingState ){
      case -1:
        flashingState =0;
        nextflashingState = ms+75; //init "timer"
        //fallthrough
      case 0:
        digitalWrite(rLED, LOW);
        digitalWrite(gLED, LOW);
        digitalWrite(bLED, LOW);
        digitalWrite(rLED, HIGH);
        if(nextflashingState < ms){
            flashingState =1;
            nextflashingState +=75;
        }
        break;
     case 1:
        digitalWrite(gLED, HIGH);
        if(nextflashingState < ms){
            flashingState = 2;
            nextflashingState +=75;
        }
        break;
     case 2:
        digitalWrite(bLED, HIGH);
        if(nextflashingState < ms){
            flashingState = 3;
            nextflashingState +=75;
        }
        break;
      case 3:
        digitalWrite(rLED, LOW);
        if(nextflashingState < ms){
            flashingState = 4;
            nextflashingState +=75;
        }
        break;
      case 4:
        digitalWrite(gLED, LOW);
        if(nextflashingState < ms){
            flashingState = 5;
            nextflashingState +=75;
        }
        break;
      case 5:
        digitalWrite(bLED, LOW);
        if(nextflashingState < ms){
            flashingState = 0;
            nextflashingState +=75;
        }
        break;
      }
    }

I used state `-1` as the init state to start the timer, the case block will fall through to the next case. The `millis()` function returns the number of milliseconds since the arduino booted up (it overflows every ~1.5 months). So when I start a timer I set the the `nextFlashingState` to the time when it should start the next state.

Then in loop you call it every time.

    void loop() {
      if (irrecv.decode(&results))
      {
        if (results.value == BUTTON_ON)
        {
          digitalWrite(rLED, HIGH);
          digitalWrite(gLED, HIGH);
          digitalWrite(bLED, HIGH);
          stR = HIGH;
          stG = HIGH;
          stB = HIGH;
        }
        if (results.value == BUTTON_OFF)
        {
            flashing =false;
          digitalWrite(rLED, LOW);
          digitalWrite(gLED, LOW);
          digitalWrite(bLED, LOW);
          stR = LOW;
          stG = LOW;
          stB = LOW;
        }
        if (results.value == BUTTON_R)
        {
          digitalWrite(rLED, !stR);
          stR = !stR;
        }
        if (results.value == BUTTON_G)
        {
          digitalWrite(gLED, !stG);
          stG = !stG;
        }
        if (results.value == BUTTON_B)
        {
          digitalWrite(bLED, !stB);
          stB = !stB;
        }
        if (results.value == BUTTON_FLASH)
        {
            flashing =true;
        }
        irrecv.resume();
      }

      Flash();
    }


message:
Midi Timecode Fails to Send

I have an ATMEGA 2560 platform running HIDUINO and a sketch based on the stock MIDI library. I'm intending to use it to convert Linear Timecode (LTC) to MTC. Got a long way through the project - LTC decoding working fine, timer configuration OK, and Midi output working fine. It's just that as soon as I try and generate MTC messages, they are being dropped before they land on the computer USB interface.

Equipment to hand: Macbook Pro running El Cap/Reaper and Protools., ATMEGA2560 MEGA R3 (With 16u2 for HIDUINO) and small audio interface circuit.

Using Timer 4 for LTC Decoding and Timer 5 for MTC generation (4 messages per LTC Frame).

Midi Monitor on the OSX box.

Sees Note on/Note off packets quite happily, but no MTC messages are registering.

I do note the TX LED is active during MTC Message generation, indicating that the sketch is actually generating messages and sending them to the 16u2 chip.

Specifically, my question is how do I get the MTC messages through HIDUINO into the computer?

https://pastebin.com/pAXyq04s

body:
The HIDUINO library supports only some MIDI message correctly; most System Common and System Real-Time message are buggy, and SysEx messages are not handled at all.

Try some other library, e.g., [mocoLUFA](https://github.com/kuwatay/mocolufa).


body:
If you clone my fork of the code, I have got this working.
https://github.com/mwr9uk/mocolufa

I have generated a pull request to merge it with mainline.


message:
Bluetooth HM-10 in central mode bonding with another bluetooth device

I have a bluetooth HM-10 configured in central mode. I have successfully connected it to another bluetooth device (a hexiwear bluetooth wearable). The problem now is that the hexiwear requires me to provide a 6 digit pin before it will bond with my HM-10.

Would anyone know the AT command that I could use to send the 6 digit pin from the HM-10 to the hexiwear?

Thank you.

body:
The manual for the HM-10 can be found [here](ftp://imall.iteadstudio.com/Modules/IM130614001_Serial_Port_BLE_Module_Master_Slave_HM-10/DS_IM130614001_Serial_Port_BLE_Module_Master_Slave_HM-10.pdf).

Page 11 has the AT command you are interested in: `AT+PIN`:

    AT+PIN123456
    OK+Set:123456

By default the PIN is `000000`.

(The manual is quite vague about the role of that command, so I assume since it is the only reference to PIN codes that it does what you require).


message:
Broadcasting parallel data from Arduino using router

I'm looking to read data from sensors using an ArduinoUNO in a greenhouse and then access the data wirelessly through a router. Hopefully through a webpage. No need for internet access, just local network access is good enough.

Preferably the only components involved would be the Arduino, the circuit, and a router with OpenWRT/DD-WRT to host the webpage and broadcast the network.

Pretty new to Arduinos in general, would this be possible? And how? The following 2 links from instructables.com seem to be the most relevant, can anyone give their input on how similar/different is this to my project?

http://www.instructables.com/id/PART-1-Send-Arduino-data-to-the-Web-PHP-MySQL-D3js/

http://www.instructables.com/id/Getting-Arduino-data-to-a-web-Page/

body:
Use a NodeMCU (ESP8266 based) because it have WiFi included. It can work as a light web server. You can serve HTML, but not large files (like many .js).

Instead of HTML you can use [websockets][1] to get only data from NodeMCU and all the other files (html, js, images) from another bigger server. Websockets is fast, but you still have to deal with .html, .css, .js and other files in your webserver.

If you want something even easier and lighter, take a look at [MQTT][2], which was developed with IoT in mind.

There is lot of MQTT client for Android/Iphone/PC/Mac. You use your client to send data and commands to your NodeMCU. No need to program anything here; you simply construct a visual interface by adding controls (buttons, meters) to a blank slate. No brains job.

You will need a *broker*, a server that acts as a relay, receiving commands/data from your Android and resending it to your NodeMCU. And your NodeMCU can publish temp, humidity, light levels and other data to your broker. You can use multiple client at once. There is no limit.

Your broker can be an public Internet broker (many) or a private one in your LAN. There is many brokers available for different platforms. You can run one in your smartphone or any old PC. [Mosquitto][3] is a free one.

Depending on your configuration, you will be even able to access your green house from Internet and look at your girls from far away.

[![IoT][4]][4]

  [1]: https://en.wikipedia.org/wiki/WebSocket
  [2]: https://en.wikipedia.org/wiki/MQTT
  [3]: https://mosquitto.org/
  [4]: https://i.stack.imgur.com/8NRpJ.png


message:
Advice on cabling, packaging and connectors for 12v light project

My project is to have a 12V solar LED strip lighting system throughout my apartment. This has 6 individual lights, with 5 white and 1 RGB = 8 channels.

I've got the whole setup working on my breadboard. Now it's time to transfer it to a "live" setup. Since it's my first such project, I'm looking for any and all recommendations on cabling and connectors to deal with reliability, isolation, modularity, aesthetics and of course safety.

Schematically, it all looks something like this

    solar panel------\
                      charge controller--5v regulator--arduino--mosfets x 8--\__lights
    12v battery_fuse_/                  \____________________________________/

So I have questions such as:-

 1. should I use a prototype shield, or a discrete pcb?
 1. do the MOSFETs (RFP30N06LE) need a heatsink, and any recommended unit?
 1. what connectors are recommended?
 1. any suggestions on box/packaging for the above?
 1. wire gauge? Maximum run is 4m to the furthest light.

And any other hints, tips and suggestions greatly appreciated. Bonus appreciation for amazon links to the parts :-)

update
The breadboard is simply the mosfets, each with a current limiting resistor on the gate. The lights range from 8W to 40W. I will generally have them dimmed using PWM.

body:
generic DC connector advice:

avoid the use of connectors which connect serially, like headphone jacks. you make strange combinations while plugging in

avoid connectors which do not latch, like headphone jacks

in a system like yours, with stages and signal processing in between, use different connectors for each phase, so you can not get it wrong

use connectors that can not be connected backwards for DC. I prefer:

Hopkins 47965 2-Pole Flat Extension for raw solar power.Not because    it's a great connector, but because it's common in low power solar

 - Anderson Power Poles for regulated DC power. you can secure them
   together with a tie wrap; you can't connect them backwards without
   doing things that are obviously counter intuitive.
 - Fuel injection    connectors from Autozone for signal wires. they got
   a million of    them, they are made for DC at useful current levels
 - Trailer    connectors for multiple lead serious power.
 - XLR connectors can be    found from 3 to 6 pins, and you can't jam a
   5 pin into a 6 pin, so    you can't cross connnect

keep things dummy proof.


message:
Arduino 101 accelerometer drift or calculation error?

I want to calculate the displacement of the Arduino 101 board compared to the starting point (only in the x direction so far).

In below data I'm swinging the board multiple times in circles around my laptop and then putting it back at the origin a few seconds later.

Regardless if 1ms-100ms between the loops, the numbers show no sign of the board returning to the origin. I've calibrated the accelerometer x-axis as closely as possible.

[![Results from swinging][1]][1]

Am I doing something wrong in deriving the acceleration/velocity/distance, or is this the level of compounding error to expect?

If so, can combining gyro data correct acceleration (thought it mainly worked the other way around)?

I have a GPS meant for correcting position but was hoping any drift wouldn't be this quick.

EDIT: I was incorrect re. use of gyro data; the attitude of the board, which was not consistent in my swings, will effect the acceleration output. Gyro data can be used to calculate and "cancel out" this gravitational impact, and get a more accurate (linear) acceleration (http://www.cl.cam.ac.uk/research/dtg/www/files/publications/public/abr28/ojw28_thesis.pdf). Will report back in a few days.

Code:

    #include "CurieIMU.h"

    float gravity = 9.80665; // to convert G forces (1 m/s2 = 0.101972 g; 1 g = 9.80665 m/s2)
    long t1; // create object for first time reference, set time just before the loop later on

    // Variables that are dependent on value from last loop
    float vx, vy, vz;
    float imu_x, imu_y, imu_z;

    void setup() {
      Serial.begin(9600);
      while (!Serial);  // wait for serial to open

      Serial.println("Initializing IMU device...");
      CurieIMU.begin(); // start accelerometer / gyro
      CurieIMU.setAccelerometerRange(2);  // accelerometer range to 2G - might need to be greater later on (18 m/s2 highest possible now)

      /*

      // Auto-calibration to ensure accelerometer doesn't drift
      CurieIMU.autoCalibrateAccelerometerOffset(X_AXIS, 0); // 89.69999 creates both positive and negative spikes
      delay(1000);
      CurieIMU.autoCalibrateAccelerometerOffset(Y_AXIS, 0);
      delay(1000);
      CurieIMU.autoCalibrateAccelerometerOffset(Z_AXIS, 1);
      delay(1000);

      */

      // Hardcoded accelerometer offsets after testing
      CurieIMU.setAccelerometerOffset(X_AXIS,89);

      // Fetch the offsets from the IMU
      float x_offset = CurieIMU.getAccelerometerOffset(X_AXIS);
      float y_offset = CurieIMU.getAccelerometerOffset(Y_AXIS);
      float z_offset = CurieIMU.getAccelerometerOffset(Z_AXIS);

      Serial.println("Current x_offset, y offset, z offset");
      Serial.print(x_offset, 6);
      Serial.print("\t");
      Serial.print(y_offset, 6);
      Serial.print("\t");
      Serial.println(z_offset, 6);
      delay(5000);

      t1 = millis(); // set the first time reference

      Serial.println("ax_g (g), ax (m/s2), t1 (ms), t2 (ms), td (ms), tds (s), vx (m/s), imu_posx (m)");

    }

    void loop() {

      // Fetch G forces
      float ax_g, ay_g, az_g;   //scaled accelerometer values
      CurieIMU.readAccelerometerScaled(ax_g, ay_g, az_g); // read accelerometer measurements from device, scaled to the configured range

      // Convert G force to m/s2
      float ax = ax_g / gravity;
      float ay = ay_g / gravity;
      float az = az_g / gravity;

      // Calculate time since last loop
      long t2 = millis();
      float td = t2 - t1; // time delta in ms
      float tds = td / 1000; // delta in seconds for easier logic

      // Calculate current velocity: velocity (m/s) = velocity (m/s) + acceleration (m/s2) * deltaTime (s)
      vx = vx + ax * tds;
      vy = vy + ay * tds;
      vz = vz + az * tds;

      // Calculate position: position (m) = position (m) + velocity (m/s) * deltaTime (s)
      imu_x = imu_x + vx * tds;
      imu_y = imu_y + vy * tds;
      imu_z = imu_z + vz * tds;

      // Print the values
      Serial.print(ax_g, 6);
      Serial.print("\t");
      Serial.print(ax, 6);
      Serial.print("\t");
      Serial.print(t1);
      Serial.print("\t");
      Serial.print(t2);
      Serial.print("\t");
      Serial.print(td, 6);
      Serial.print("\t");
      Serial.print(tds, 6);
      Serial.print("\t");
      Serial.print(vx, 6);
      Serial.print("\t");
      Serial.println(imu_x, 6);

      // Reset start values for next loop
      t1 = millis();

      delay(1);

    }

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

body:
The Arduino 101 contains the Intel® Curie™ Module, this module contains an Inertial Measurements Unit or IMU for short among other sensors and peripherals [![Intel® Curie™ Module Block Diagram][1]][1]

The IMU of this module is Bosch BMI160 which is a low cost MEMS IMU, this IMUs typically suffer from systematic errors and random/stochastic errors, the following diagram summarize them:
[![enter image description here][2]][2]

If we take the bias error as an example of those errors, an uncompensated accelerometer bias introduces an error proportional to time (t) in the velocity and proportional to t^2 in the position. For example, consider a case where accelerometer bias is 10 m/s^2. If this bias offset is not removed from the measurements, it can generate a 500 m error in position after 10 seconds and 12.5 km error after 50 seconds. Let us back to our IMU, if we read the data sheet the Zero-g error "or bias" is 40mg for the 8g sensing accelerometer and Ta = 25 Celsius with normal VDD and the IC has been assembled on board. If we just consider this 40mg bias error "dropping other error sources" it is 0.392266 m/s^2 so after 10 seconds the position offset will be 1.96133 meter even if you don't move the Arduino.
I suggest you read "MEMS-Based Integrated Navigation" book [here][3] it will give you a good vision about MEMS based inertial sensors and basic navigation concepts.

  [1]: https://i.stack.imgur.com/UqoaL.png
  [2]: https://i.stack.imgur.com/gV9W1.png
  [3]: https://www.amazon.com/MEMS-Based-Integrated-Navigation-Technology-Applications/dp/1608070433


message:
How to flash/blink I2C LCD backlight without delay function?

Since I am an using I2C LCD backpack, I'm unable to call in for pinmode to set variables like `#define BACKLIGHT_PIN 13`. I know `lcd.setBacklight(HIGH);` and `lcd.setBacklight(LOW);` controls the I2C LCD backlight, but if I use delay in the loop it slows down the whole loop.

How do I flicker the LCD backlight without using delay? I tried for example to blink without delay, but I don't know how to assign a global variable to `lcd.setbacklight` so as to control it.

I want to use an if statement to warn the user that so and so has happened, eg:

    #include <Ticker.h>
    #include <LiquidCrystal_I2C.h>
    LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

    //Ticker flashBacklight(toggleBacklight, 100);
    // when I use ticker here am getting not declared in scope
    const int buttonPin = 3;
    int buttonState = 0;
    // pls declare flashBacklight, long flashBacklight = 100; ??
    // pls declare toggleBacklight

    void toggleBacklight() {
      // lcd.setBacklight(!lcd.getBacklight());
      // !lcd.getbacklight() spelling mistake ? or it is setbacklight?
    }

    void setup() {
      lcd.begin(20, 4);
      lcd.setBacklight(HIGH);
      pinMode(buttonPin, INPUT);
     }

    void loop() {
      buttonState = digitalRead(buttonPin);
      if (buttonState == HIGH) {
        // if button goes high the back light must keep on flashing until it's released
        flashBacklight.start();
        //flash the lcd backlight
      } else {
        flashBacklight.stop(); // Stop flashing the backlight
      }
      flashBlacklight.update();
    }

But delay slows down the whole loop, so how do I flash the backlight without it? Thank you.

body:
Besides the standard 'compute a target `millis()` and compare' standard, which can get clunky when you have to handle more than 1 repeating or delayed event, there are also more than one decent library that abstract the concept, but also add features.

One example is the [Ticker][1] library.

With these methods, you create a **callback** function and pass that function name into the object constructor, along with the timing parameters.

So you might:

    [various #include, #define, etc.]

    Ticker flashBacklight(toggleBacklight, 100); //call toggleBacklight() every 100ms

    // Create the callback function, which just toggles the backlight each call.
    void toggleBacklight() {
      lcd.setBacklight( !lcd.getBacklight() );
    }

    setup() {
      [...]
    }

    loop() {
      // Start or stop the ticker based on your own situation. Once started, it will call your callback function at the specified interval until stopped.

      if (warningSituation) {
        flashBacklight.start();
      } else {
        flashBacklight.stop();
      }

      flashBlacklight.update();
    }

Another related library is [SimpleTimer][2]

**EDIT**

Your code example, updated:

    #include <Ticker.h>
    #include <LiquidCrystal_I2C.h>
    LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

    void toggleBacklight();

    Ticker flashBacklight(toggleBacklight, 100); //when i use ticker here am getting not declared in scope

    const int buttonPin = 3;
    int buttonState = 0;
                          // pls declare   flashBacklight   , long flashBacklight = 100;   ??
                          //   pls declare toggleBacklight

    void toggleBacklight() {
     // lcd.setBacklight( !lcd.getBacklight() );  // !lcd.getbacklight() spelling mistake ? or it is setbacklight?
    }
    void setup() {
       lcd.begin(20, 4);
     lcd.setBacklight(HIGH);
     pinMode(buttonPin, INPUT);
     }
    void loop() {
          buttonState = digitalRead(buttonPin);
       if (buttonState == HIGH)          // if button goes high the back light must keep on flashing untill its released
       {
        flashBacklight.start();          //flash the lcd backlight
      } else {
        flashBacklight.stop();           // Stop flashing the backligh
     }
       flashBacklight.update();
      }

  [1]: https://github.com/sstaub/Ticker
  [2]: https://playground.arduino.cc/Code/SimpleTimer


body:
You will need to alter the pin / bit tied to the backlight led.

To do that you will need to be able to read the state of all the pins on the i2c expander.

That can be done by reading back the pin state from the i2c expander or to hold the pin state in a buffer.

Once you know the pin state, you can OR or NEG it to clear or set the pin.