message:
ESP8266 ASyncTCP class example

I am new to ESP programming on Arduino, as before I was developing on eLua. There were some memory problems in Lua, so I decided to move to Arduino.

After looking at some examples, I found a library called AsyncTCP and I was very glad because it provides callbacks for events just like Lua. But I was very disappointed when I found no example of an async TCP server. Instead there is an AsyncWeb Server but I don't want to use an HTTP server: I want a simple telnet server. Does someone have a working example?

body:
If there are no examples provided with the library then you will have to make do with the example you have :(

If you think about what a web server does it is really just a glorified Telnet server without proper security.  When the web server comes up it creates a waiting socket on port 80, you want port ?? (too long ago).  It sits there waiting for text messages from clients, which is what you want to do.  Every time it receives a message it sends it to a handler.

I don't know how experienced a programmer you are, but you should be able to pick up enough from the webserver code to write your own telnet server.  However with you being new to Arduino you may be much better doing it as a synchronous application to start with.

Another approach is to find a the source for a telnet server and see if you can port that to the ESP.


sender: user

sender: assistant

body:
There are examples in the ESP8266 library

https://github.com/me-no-dev/ESPAsyncTCP/tree/master/examples


message:
Sublime as external editor, error on Arduino compile dropdown: "avr-g++ is not recognized...", from Stino

The error message, generated from Sublime, in its entirety...

 Compiling KCT_Swimv4l...

 Creating C:\Users\ken\Documents\Arduino_Build\KCT_Swimv4l\KCT_Swimv4l.ino.cpp.o...

 '"avr-g++"' is not recognized as an internal or external command,
operable program or batch file.

 [Stino - Error 1]
__________
This is initial install of "Arduino-like IDE".

I used the following installation procedure:

   - Install Sublime Text 3
   - From Sublime, View --> Show Console
   - From a web browser, open  https://sublime.wbond.net/installation and choose Sublime Text 3 version.
   - Copy the code there to the Sublime-Console and press enter.
   - From Sublime, CTRL + Shift + P --> Type "Install" and choose "Install package"
   - Enter "Arduino" and choose "Arduino-like IDE"
   - from Arduino --> Preferences --> Select Arduino Application Folder.

Same problem with any sketch.

System Configuration:

-Windows 10 x64, current level
-Sublime Text 3 x64, build 3126
-Arduino IDE 1.8.0

github info on Stino was not helpful.
Has anyone encountered this problem and found a solution for it?
If not, I can open an issue there.
___________________________________________

I have now done the following:
Uninstalled Sublime
Searched System drive and removed any remaining Sublime content
Searched System drive and removed any Stino content
Download WinAVR from http://winavr.sourceforge.net/download.html, selecting PATH option
Reinstalled Sublime Text 3 x64
Close & Reopen Sublime
From Sublime, View --> Show Console
From web browser, open https://sublime.wbond.net/installation and choose Sublime Text 3 version.
Copy the code there to the Sublime-Console and press enter
Close & Reopen Sublime
From Sublime, CTRL + Shift + P --> Type "Install" and choose "Install package"
Enter "Arduino" and choose "Arduino-like IDE"
Close & Reopen Sublime
From Arduino --> Preferences --> Select Arduino Application Folder

On Compile, error msg is now different:
  Compiling KCT_Swimv4l...
  Creating C:\Users\kct\Documents\Arduino_Build\KCT_Swimv4l\KCT_Swimv4l.ino.cpp.o...
  cc1plus.exe: error: unrecognized command line option "-std=gnu++11"
  cc1plus.exe: error: unrecognized command line option "-flto"
  [Stino - Error 1]

body:
Download WinAVR from http://winavr.sourceforge.net/download.html, install it, add(in my case, its: C:\WinAVR-20100110\bin) to PATH variable of your system(If it was left unchecked while installing), And then try to build. I hope your problem will be solved.

**Update**

I have installed the latest version and found no board selection option. If you want to use it, you can download an older version. from here: https://drive.google.com/file/d/0B4zy7eqONHnuajk2aXlzOTJtaDQ/view it works on older version of arduino(probably 1.5 series)


message:
Using a MOSFET module to control DC LED PWM

I've seen some similar questions here for using MOSFET to control 12V LEDs
But apparently the only MOSFET currently available to us is a 2-MOSFET high power trigger module, details in the link below.

https://www.elecrow.com/high-power-mosfet-trigger-switch-drive-module.html

How do we connect this to the Arduino to send the PWM trigger (I get confused by the three holes) and how do we connect the DC power to this??? I get confused with the power connections.

body:
it seems to be a typical low-side switch (dual switches). the load goes into DC+ and DC- --> ask the manufactuer to be sure.

whether it works for you will depend on the load, driving signal and the mosfet used -> you should ask the seller for a schematic, or buy one and reverse engineer it.


body:
The three TRIG/PWM pins are connected to the same electrical point. The same goes for the three GND pins.

You can either solder:

1. A **2-pin 0.2 inch screw terminal** (the very same kind of those blue connectors already in the board) to the pair of big holes closer to the edge, or
2. A **2-pin 0.1 inch header** to the 2 holes in the centre of the 4-hole row (the smaller ones).
[![2-pin header][1]][1]

These will be the control input you should be connecting your Arduino to.

The DC power supply for the load that will be switched by the MOSFETS has to be connected between the VIN+ and VIN- terminals. Note that VIN- is connected internally to GND.

Your load has to be connected between the OUT+ and OUT- terminals.

That's all you need to know. In case you're in doubt, I've drawn this schematic for you (see below)

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/J7Otl.png)

<!-- End schematic -->

**IMPORTANT ADDITIONAL NOTES:**

 1. **No flyback diodes are present in the board**. If you try to switch an inductive load (a motor, a solenoid, etc.) with this board you have a high risk of damaging the MOSFETs and rend it useless.

 2. **You need at least a 5V control signal** for switching high current loads with this board. Although a 3.3V control may seem able to switch the MOSFET, its internal RdsON at 3.3V could easily be high enough to produce excessive power dissipation and blow up the MOSFET. See these curves from the [AOD4184 datasheet][2]:

[![ON-region characteristics][4]][4]
[![ON-resistance vs. Vgs][5]][5]

  [1]: https://i.stack.imgur.com/dmKu0m.jpg
  [2]: http://www.aosmd.com/pdfs/datasheet/AOI4184.pdf
  [4]: https://i.stack.imgur.com/3L1SOm.png
  [5]: https://i.stack.imgur.com/j4Zl0m.png


message:
OVF in serial monitor instead of data

I am currently working with two Arduinos and I'm trying to synchronize them. I want to get data from four LIS3DH accelerometers. The LIS3DH accelerometers are connected to the Arduino using I2C interface. I have managed to get the Arduinos to synchronize using SPI but when I get the third set of data it keeps on showing OVF rather than the values. My code is below can someone please help me out?

Thanks

    // SPI Master
    #include <Wire.h>
    #include <SPI.h>
    #include "SPI_anything.h"
    #include <Adafruit_LIS3DH.h>
    #include <Adafruit_Sensor.h>

    //#define LIS3DH_CLK 13
    //#define LIS3DH_MISO 12
    //#define LIS3DH_MOSI 11
    //#define LIS3DH_CS  10

    // I2C
    Adafruit_LIS3DH lisch1 = Adafruit_LIS3DH();
    Adafruit_LIS3DH lisch2 = Adafruit_LIS3DH();
    // Adafruit_LIS3DH lisch3 = Adafruit_LIS3DH();
    struct event3;

    #if defined(ARDUINO_ARCH_SAMD)
    // for Zero, output on USB Serial console, remove line below if using
    // programming port to program the Zero!
    #define Serial SerialUSB
    #endif

    void setup() {
    #ifndef ESP8266
      while (!Serial)
        ; // will pause Zero, Leonardo, etc until serial console opens
    #endif

      Serial.begin(9600);

      // have to send on master in, *slave out*
      pinMode(MISO, OUTPUT);

      // turn on SPI in slave mode
      SPCR |= _BV(SPE);

      Serial.println("LIS3DH test!");

      if (!lisch1.begin(0x19)) { // change this to 0x19 for alternative i2c address
                                 // - Voltage SDO

        Serial.println("Couldnt start");
        while (1)
          ;
      }
      Serial.println("LIS3DH1 found!");
      if (!lisch2.begin(0x18)) { // change this to 0x18 for alternative i2c address
                                 // - Ground SDO
        Serial.println("Couldnt start");
        while (1)
          ;
      }
      Serial.println("LIS3DH2 found!");

      lisch1.setRange(LIS3DH_RANGE_16_G); // 2, 4, 8 or 16 G!
      lisch2.setRange(LIS3DH_RANGE_16_G); // 2, 4, 8 or 16 G!

      Serial.print("Range = ");
      Serial.print(2 << lisch1.getRange());
      Serial.print("Range = ");
      Serial.print(2 << lisch2.getRange());
      Serial.println("G");
    }

    void loop() {

      lisch1.read(); // get X Y and Z data at once

      /* Or....get a new sensor event, normalized */
      sensors_event_t event;

      lisch1.getEvent(&event);

      /* Display the results (acceleration is measured in m/s^2) */
      Serial.print(" \t ");
      Serial.print(event.acceleration.x);
      Serial.print(" \t ");
      Serial.print(event.acceleration.y);
      Serial.print(" \t ");
      Serial.print(event.acceleration.z);

      lisch2.read(); // get X Y and Z data at once
      lisch2.getEvent(&event);

      /* Display the results (acceleration is measured in m/s^2) */
      Serial.print(" \t ");
      Serial.print(event.acceleration.x);
      Serial.print(" \t ");
      Serial.print(event.acceleration.y);
      Serial.print(" \t ");
      Serial.print(event.acceleration.z);

      struct event;

      SPI_readAnything(event);
      //  sensors_event_t event;

      //  lisch3.getEvent(&event);
      Serial.print(" \t "); Serial.print(float2s(event.acceleration.x,6);
      Serial.print(" \t "); Serial.print(event.acceleration.y);
      Serial.print(" \t "); Serial.print(event.acceleration.z);
      Serial.println ();

      delay(500);
    }

    / SPI Slave

    #include <Wire.h>
    #include <SPI.h>
    #include "SPI_anything.h"
    #include <Adafruit_LIS3DH.h>
    #include <Adafruit_Sensor.h>

    #define LIS3DH_CLK 13
    #define LIS3DH_MISO 12
    #define LIS3DH_MOSI 11
    #define LIS3DH_CS 10

        // I2C
        Adafruit_LIS3DH lisch3 = Adafruit_LIS3DH();

    #if defined(ARDUINO_ARCH_SAMD)
    // for Zero, output on USB Serial console, remove line below if using
    // programming port to program the Zero!
    #define Serial SerialUSB
    #endif

    void setup() {
    #ifndef ESP8266
      while (!Serial)
        ; // will pause Zero, Leonardo, etc until serial console opens
    #endif

      Serial.begin(9600); // start serial for output

      SPI.begin();

      // Slow down the master a bit
      SPI.setClockDivider(SPI_CLOCK_DIV8);

      Serial.println("LIS3DH3 test!");

      if (!lisch3.begin(0x19)) { // change this to 0x19 for alternative i2c address
                                 // - Voltage SDO

        Serial.println("Couldnt start");
        while (1)
          ;
      }
      Serial.println("LIS3DH3 found!");

      lisch3.setRange(LIS3DH_RANGE_16_G); // 2, 4, 8 or 16 G!

      Serial.print("Range = ");
      Serial.print(2 << lisch3.getRange());

      Serial.println("G");
    }

    void loop() {

      lisch3.read(); // get X Y and Z data at once

      /* Or....get a new sensor event, normalized */
      sensors_event_t event;

      lisch3.getEvent(&event);

      /* Display the results (acceleration is measured in m/s^2) */
      Serial.print(" \t ");
      Serial.print(event.acceleration.x);
      Serial.print(" \t ");
      Serial.print(event.acceleration.y);
      Serial.print(" \t ");
      Serial.print(event.acceleration.z);
      Serial.println();

      digitalWrite(SS, LOW); // SS is pin 10
      SPI_writeAnything(event);
      digitalWrite(SS, HIGH);
      //  delay (1000);  // for testing

      delay(100);
    }

body: OVF means overflow, you probably exceeded the range of the data type you're using. Try /1000; /10000000000 etc to your variable until you don't get the OVF or use a datatype with a bigger range.


message:
How to get response of issued AT command for ES266 on Arduino programatically?

I'm successfully running AT commands via the Serial Monitor. But now I'm issuing AT commands via Arduino code and facing problems getting the correct response.

**Goal:** After issuing AT commands programatically, knowing whether these run successfully or not.

**Microcontroller:** Arduino Uno

    #include<string.h>
    #include<SoftwareSerial.h>

    #define OK "OK"
    #define SERVER_PORT 1234
    #define RX_PIN 2
    #define TX_PIN 3

    SoftwareSerial ESP(RX_PIN, TX_PIN);

    void setup() {
      Serial.begin(115200);
      Serial.println("First serial");
      while(!Serial);
      ESP.begin(115200);
      Serial.println("Second serial");
      while(!ESP);
      //Enabling multiple connections
      ESP.println("AT+CIPMUX=1\r\n");
      while (!ESP.available());
      String muxResponse = ESP.readString();
      Serial.print("muxR:");
      Serial.println(muxResponse);
    }

    void loop() {
      if (ESP.available()) {
        String val = ESP.readString();
        Serial.println(val);
      }
    }

After running the above code I get the response in the Serial Monitor like:

    muxR:AT+CIPMUX=1

    busy p../

    OK

I'm getting special characters too.

body:
change

    AT+CIPMUX=1\r\n

to

    AT+CIPMUX=1


message:
fatal error ESP8266WiFi.h: No such file or directory

I want to turn my ESP8266 into an access point so that I can connect directly to it.

I use the following sketch, but when I select
GENERIC module ESP8266 from menu, the libraries `ESP8266WiFi.h` and `ESP8266WebServer.h` become available but I was unable to upload the sketch.

Also when I select board as Arduino Uno (Which i have really) and then what to upload then the above two files becomes unavailable and says fatal error no such file... no idea what to do next.

    #include <ESP8266wifi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>
    #include<WiFi.h>
    #include<SoftwareSerial.h>
    SoftwareSerial esp(2,3);
    IPAddress local_IP(192,168,4,22);
    IPAddress gateway(192,168,4,9);
    IPAddress subnet(255,255,255,0);
     String ssid="Wisal";
     String pass="12345678";
     ESP8266WebServer server(80);
     boolean isAccessPointCreated=false;
    void setup(){
      esp.begin(115200);
      Serial.begin(115200);

      WiFi.mode(WIFI_AP);
      Serial.print("Setting soft-AP configuration ... ");
      Serial.println(WiFi.softAPConfig(local_IP, gateway, subnet) ? "Ready" : "Failed!");

      Serial.print("Setting soft-AP ... ");
      Serial.println(WiFi.softAP("ESPsoftAP_01") ? "Ready" : "Failed!");
      Serial.print("Soft-AP IP address = ");
      Serial.println(WiFi.softAPIP());

    }

    void loop(){
      while(esp.available()>0){
        char a = esp.read();
          if(a == '\0')
            continue;
          if(a != '\r' && a != '\n' && (a < 32))
            continue;
          Serial.print(a);
       }
    }

body:
The [ESP8266 core for Arduino](https://github.com/esp8266/Arduino) that you're trying to use is for programming ESP8266 directly. You are trying to program an Uno with an ESP8266 connected to it for use as a WiFi module. For that application the ESP8266 core is of no use. For your application it's most common to run the AT firmware on the ESP8266 and communicate via serial. If you're doing that I recommend the WiFiEsp library:

https://github.com/bportaluri/WiFiEsp

Since you're uploading to the Uno you should have Arduino/Genuino Uno selected in the **Tools > Board** menu.


body:
There are two ways to use an ESP8266.

Method 1

You seem to say you are using it as a slave to your UNO.  You program you Uno from the IDE.  The program will have code in it to send 'AT' commands to the ESP and this will make the ESP handle all the WIFI stuff.

Method 2

You remove you Uno and use the ESP as the main processor.  This means you get to program the ESP with C++ like code through the IDE, just as if it was an UNO.  HOWEVER you will need to install the ESP package from the board manager and there are certain limitations.  You also have access to less IO ports, but you can connect the Uno (over serial or I2C) and use it as a slave (which you program through the IDE separately).


body: You have imported `ESP8266wifi.h` and not `ESP8266WiFi.h`


message:
Any resources you know with regards to remotely reading data from arduino?

I am trying to implement arduino101 and my application needs to read data from the Arduino without a USB connection to my laptop. I appreciate you if you know any beginner-level tutorial for this.

Please let me know if you can't understand my question.

body:
You can use the Bluetooth on the board, a Bluetooth dongle for your laptop if the laptop does not have bluetooth or you can buy a wifi shield.

The 101 has Bluetooth LE on the board.

You will find there is a Bluetooth -> Serial USB software, so the application on the laptop can still work the same way as when using the usb.

Here are the Bluetooth examples for the 101 on arduino.cc

https://www.arduino.cc/en/Reference/CurieBLE

and the user guide for the 101

https://www.arduino.cc/en/Guide/Arduino101


message:
Max current of Vin and 5V pin on Arduino Nano

What is the max current of the Arduino Nano's Vin (30) and 5V (27) pins?

body:
It's hard to say. The maximum [the on-board regulator](http://www.ti.com/lit/ds/symlink/lm1117.pdf) can provide is 800mA. However the actual amount it can provide at any time depends on other external factors - most notably:

* The voltage of your supply
* The ambient temperature around the board
* The thermal mass of the copper the tab is soldered to

The higher your input voltage the more excess voltage has to be converted to heat. When it gets too hot it overheats and (theoretically) shuts down.

Also the board itself will take some of the maximum 800mA quota, say 50mA (guestimate), so that leaves 750mA theoretical maximum for the 5V pin - but only when powered from not much more than 6.2V (5V + 1.2V regulator dropout voltage).

However, if you are powering from the USB port then it is limited to whatever the USB port can provide (100mA for a passive hub, 500mA for a normal USB port, 2A for a CDP).

The VIN current will be the same as the 5V pin current + the board current.


body:
> What is the max current of the Arduino Nano's Vin (30) and 5V (27) pins?

it depends on the power dissipation limits (and to a less extent the current limit) on the regulator. the power dissipation is determined by the load your arduino and its loads draw, and the voltage dropout on the regulator.

the other part of the thermal limit is the thermal resistance of the package and ambient temperature.

Most of them use el cheapo 1117 regulators in sot223 that has a limit of 1amp + a thermal limit of 100c/w. so max power dissipation should be less than 1w. That means a practical limit of 0.5amp under the most aggressive conditions (2v dropout, or 7v input).

at 9v input, max of 0.25amp.
at 12v input, a max of 0.15amp.
...


message:
Radio Issues with RF69HW

I am working through [this tutorial](https://www.allaboutcircuits.com/projects/introduction-to-the-rfm69hw-transceiver/) on using the RF69HW. The RF69HW datasheet can be found [here](http://www.hoperf.com/upload/rf/RFM69W-V1.3.pdf). I am using an Eegoo Uno R3 and yes I am aware that the Arduino is a 5v and the RF69HW is a 3.3v board. I am using some voltage dividers to get the voltage to 3.3v [via the circuit shown below, at end of question](https://i.stack.imgur.com/sreQq.png).

I would use a level shifter but I only realized this mistake today and I am trying to get this working ASAP. The radio does not appear to be working. In fact the program seems to get caught on it. I introduced:

    radio.sendACK();
    Serial.print(" - ACK sent");

After the button has been pressed. This is the output I get:

    Listening at 915 Mhz...
    Button pressed!

So it gets to the line before it where the button is pressed but then gets stuck attempting to sendACK. I don't know what to make of this. Any help getting these two to communicate is appreciated. Code and pictures below.

 Here is the code I am using as the sender:

    #include <SPIFlash.h>
    #include <SPI.h>
    #include <LowPower.h>
    #include <RFM69.h>
    #include <RFM69_ATC.h>
    #include <RFM69_OTA.h>
    #include <RFM69registers.h>

    //*********************************************************************************************
    // *********** IMPORTANT SETTINGS - YOU MUST CHANGE/CONFIGURE TO FIT YOUR HARDWARE *************
    //*********************************************************
    //This part of the code simply sets up the parameters we want the chip to use
    // these parameters allow you to have multiple networks, channels, and encryption keys
    #define NETWORKID     100  //the same on all nodes that talk to each other
    #define RECEIVER      1    //unique ID of the gateway/receiver
    #define SENDER        2    // you could for example, have multiple senders
    #define NODEID        SENDER  //change to "SENDER" if this is the sender node (the one with the button)
    //Select your frequency by uncommenting
    #define FREQUENCY     RF69_915MHZ
    #define ENCRYPTKEY    "sampleEncryptKey" //exactly the same 16 characters/bytes on all nodes!
    #define IS_RFM69HW    //uncomment only for RFM69HW! Remove/comment if you have RFM69W!
    //*********************************************************************************************
    #define SERIAL_BAUD   9600

    //This part defines the LED pin and button pin
    #define LED             9 //LED on D9
    #define BUTTON_INT      1 //user button on interrupt 1 (D3)
    #define BUTTON_PIN      3 //user button on interrupt 1 (D3)
    #define RX_TOGGLE_PIN   7 //GPIO to toggle on the RECEIVER

    RFM69 radio;

    // the setup contains the start-up procedure and some useful serial data
    void setup() {
      Serial.begin(SERIAL_BAUD);
      radio.initialize(FREQUENCY,NODEID,NETWORKID);
    #ifdef IS_RFM69HW
      radio.setHighPower(); //only for RFM69HW!
    #endif
      radio.encrypt(ENCRYPTKEY);
      char buff[50];
      sprintf(buff, "\nListening at %d Mhz...", FREQUENCY==RF69_433MHZ ? 433 : FREQUENCY==RF69_868MHZ ? 868 : 915);
      Serial.println(buff);
      Serial.flush();
      pinMode(BUTTON_PIN, INPUT_PULLUP);
      pinMode(LED, OUTPUT);
      attachInterrupt(BUTTON_INT, handleButton, FALLING);
      pinMode(RX_TOGGLE_PIN, OUTPUT);
    }

    //******** THIS IS INTERRUPT BASED DEBOUNCING FOR BUTTON ATTACHED TO D3 (INTERRUPT 1)
    #define FLAG_INTERRUPT 0x01
    volatile int mainEventFlags = 0;
    boolean buttonPressed = false;
    void handleButton() {
      mainEventFlags |= FLAG_INTERRUPT;
    }

    byte LEDSTATE=LOW; //LOW=0

    void loop() {
      //******** THIS IS INTERRUPT BASED DEBOUNCING FOR BUTTON ATTACHED TO D3 (INTERRUPT 1)
      if (mainEventFlags & FLAG_INTERRUPT) {
        LowPower.powerDown(SLEEP_120MS, ADC_OFF, BOD_ON);
        mainEventFlags &= ~FLAG_INTERRUPT;
        if (!digitalRead(BUTTON_PIN)) {
          buttonPressed=true;
        }
      }
      if (buttonPressed) {
        Serial.println("Button pressed!");
        buttonPressed = false;
        radio.sendACK();
        Serial.print(" - ACK sent");
        if (radio.sendWithRetry(RECEIVER, "All About Circuits", 18)) //target node Id, message as string or byte array, message length
          delay(100);
      }
      //check if something was received (could be an interrupt from the radio)
      if (radio.receiveDone()) {
        //print message received to serial
        Serial.print('[');Serial.print(radio.SENDERID);Serial.print("] ");
        Serial.print((char*)radio.DATA);
        Serial.print("   [RX_RSSI:");Serial.print(radio.RSSI);Serial.print("]");
        Serial.println();
        if(LEDSTATE==LOW) LEDSTATE=HIGH;
        else LEDSTATE=LOW;
        digitalWrite(LED, LEDSTATE);
        digitalWrite(RX_TOGGLE_PIN, LEDSTATE);
        //check if sender wanted an ACK
        if (radio.ACKRequested()) {
          radio.sendACK();
          Serial.print(" - ACK sent");
        }
      }
      radio.receiveDone(); //put radio in RX mode
      Serial.flush(); //make sure all serial data is clocked out before sleeping the MCU
      LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_ON); //sleep Arduino in low power mode (to save battery)
    }

And the receiver:

    #include <SPIFlash.h>
    #include <SPI.h>
    #include <LowPower.h>
    #include <RFM69.h>
    #include <RFM69_ATC.h>
    #include <RFM69_OTA.h>
    #include <RFM69registers.h>

    //*********************************************************************************************
    // *********** IMPORTANT SETTINGS - YOU MUST CHANGE/CONFIGURE TO FIT YOUR HARDWARE *************
    //*********************************************************
    //This part of the code simply sets up the parameters we want the chip to use
    // these parameters allow you to have multiple networks, channels, and encryption keys
    #define NETWORKID     100  //the same on all nodes that talk to each other
    #define RECEIVER      1    //unique ID of the gateway/receiver
    #define SENDER        2    // you could for example, have multiple senders
    #define NODEID        SENDER  //change to "SENDER" if this is the sender node (the one with the button)
    //Select your frequency by uncommenting
    #define FREQUENCY     RF69_915MHZ
    #define ENCRYPTKEY    "sampleEncryptKey" //exactly the same 16 characters/bytes on all nodes!
    #define IS_RFM69HW    //uncomment only for RFM69HW! Remove/comment if you have RFM69W!
    //*********************************************************************************************
    #define SERIAL_BAUD   9600

    //This part defines the LED pin and button pin
    #define LED             9 //LED on D9
    #define BUTTON_INT      1 //user button on interrupt 1 (D3)
    #define BUTTON_PIN      3 //user button on interrupt 1 (D3)
    #define RX_TOGGLE_PIN   7 //GPIO to toggle on the RECEIVER

    RFM69 radio;

    // the setup contains the start-up procedure and some useful serial data
    void setup() {
      Serial.begin(SERIAL_BAUD);
      radio.initialize(FREQUENCY, NODEID, NETWORKID);
    #ifdef IS_RFM69HW
      radio.setHighPower(); //only for RFM69HW!
    #endif
      radio.encrypt(ENCRYPTKEY);
      char buff[50];
      sprintf(buff, "\nListening at %d Mhz...", FREQUENCY == RF69_433MHZ ? 433 : FREQUENCY == RF69_868MHZ ? 868 : 915);
      Serial.println(buff);
      Serial.flush();
      pinMode(BUTTON_PIN, INPUT_PULLUP);
      pinMode(LED, OUTPUT);
      attachInterrupt(BUTTON_INT, handleButton, FALLING);
      pinMode(RX_TOGGLE_PIN, OUTPUT);
    }

    //******** THIS IS INTERRUPT BASED DEBOUNCING FOR BUTTON ATTACHED TO D3 (INTERRUPT 1)
    #define FLAG_INTERRUPT 0x01
    volatile int mainEventFlags = 0;
    boolean buttonPressed = false;

    void handleButton() {
      mainEventFlags |= FLAG_INTERRUPT;
    }

    byte LEDSTATE = LOW; //LOW=0

    void loop() {
      //******** THIS IS INTERRUPT BASED DEBOUNCING FOR BUTTON ATTACHED TO D3 (INTERRUPT 1)
      if (mainEventFlags & FLAG_INTERRUPT) {
        LowPower.powerDown(SLEEP_120MS, ADC_OFF, BOD_ON);
        mainEventFlags &= ~FLAG_INTERRUPT;
        if (!digitalRead(BUTTON_PIN)) {
          buttonPressed = true;
        }
      }
      if (buttonPressed) {
        Serial.println("Button pressed!");
        buttonPressed = false;
        radio.sendACK();
        Serial.print(" - ACK sent");
        if (radio.sendWithRetry(RECEIVER, "All About Circuits", 18)) //target node Id, message as string or byte array, message length
          delay(100);
      }
      //check if something was received (could be an interrupt from the radio)
      if (radio.receiveDone()) {
        //print message received to serial
        Serial.print('['); Serial.print(radio.SENDERID); Serial.print("] ");
        Serial.print((char*)radio.DATA);
        Serial.print("   [RX_RSSI:"); Serial.print(radio.RSSI); Serial.print("]");
        Serial.println();
        if (LEDSTATE == LOW) LEDSTATE = HIGH;
        else LEDSTATE = LOW;
        digitalWrite(LED, LEDSTATE);
        digitalWrite(RX_TOGGLE_PIN, LEDSTATE);
        //check if sender wanted an ACK
        if (radio.ACKRequested()) {
          radio.sendACK();
          Serial.print(" - ACK sent");
        }
      }
      radio.receiveDone(); //put radio in RX mode
      Serial.flush(); //make sure all serial data is clocked out before sleeping the MCU
      LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_ON); //sleep Arduino in low power mode (to save battery)
    }

Here is a link to project pictures: [imgur.com/a/sFW88](https://i.stack.imgur.com/Dc0Z9.jpg)

Here is [my circuit diagram](https://i.stack.imgur.com/sreQq.png): ![circuit diagram](https://i.stack.imgur.com/sreQq.png)

body:
The circuit diagram shows several resistive voltage divider circuits, each made up of a 1KΩ in series with 2KΩ.

When 5 V goes into the top of such a divider, about 3.3 V appears at the resistor junction.  (And 0 V in gives 0 V out.) This is suitable for a 5 V output pin connected to a 3.3 V input pin.

For connecting RF69HW 3.3 outputs (eg MISO) to 5 V Uno inputs, ideally one would step up 3.3 V to 5 V.  Instead, MISO goes to the resistor junction of what *resembles* a resistive voltage divider but in fact is not.

Consider a low output on MISO; then the 1K-2K junction goes to zero; so the Uno reads 0 on D12, as it should.

Now consider a high output on MISO.  The 1K-2K junction goes to 3.3 V, driving about 1.65 mA to ground through the 2KΩ resistor.  Presumably the SPI library uses pin 12, MISO, as an input, so current through the 1KΩ resistor is specified to be at most 10 μA (per Table 29-14 in ATmega328 datasheet) and is quite likely to be at most a few nanoAmps.  In any case, the voltage at pin 12 will be quite close to 3.3 V, which will register as a high input.  (Figure 31-72 in ATmega328 datasheet shows a 2.6 V threshold when Vcc is 5 V.)

This is more of a long comment than an answer, because although the MISO circuitry is problematic, it appears that it should work anyway.


message:
Encoders for precise robot turns

So I recently purchased:

DFRobot Wheel Encoders

DFRobot 3PA and 4WD Rovers (2pk)

Romeo V2 Arduino Controller

I was doing a bit of research online and I'm trying to figure out how to use the encoders to control the PWM applied to the motors which will make precise turns. This seems like a popular method to use. Here is some of my code. I have nothing for the encoders yet. I only have the sensors working the PWM control for the motors. All my code does is stop the motors when the front sensor detects a wall. My next step is to implement the encoders to give the robot a 90 degree turn. Does anyone have some sample code or tips on how to do this? Thanks in advanced!
<!-- language-all: lang-cpp -->

      void stop(void)
        {
          digitalWrite(5,LOW);
          digitalWrite(6,LOW);

        }
        void forward(char a,char b)
        {
          analogWrite(5,a);
          digitalWrite(4,HIGH);
          analogWrite(6,b);
          digitalWrite(7,HIGH);

        }
        void back(char a,char b)
        {
          analogWrite(5,a);
          digitalWrite(4,LOW);
          analogWrite(6,b);
          digitalWrite(7,LOW);

        }
        void Left(char a,char b)
        {
          analogWrite (5,a);
          digitalWrite(4,LOW);
          analogWrite (6,b);
          digitalWrite(7,HIGH);

        }
        void Right(char a,char b)
        {
          analogWrite (5,a);
          digitalWrite(4,HIGH);
          analogWrite (6,b);
          digitalWrite(7,LOW);

        }
        void setup(void)
        {

          pinMode(buttonPin2, INPUT);
          pinMode(buttonPin3, INPUT);
          for(int i =4;i<=7;i++)
            pinMode(i, OUTPUT);
          pinMode(LED_BUILTIN, OUTPUT);
         forward(100,100);

          Serial.begin(9600);

        }
    void GetSensor()
    {

      Sen_Val_B = SenAvg(Sensor_Back);
      Sen_Val_F = SenAvg(Sensor_Front);
      Sen_Val_R = SenAvg(Sensor_Right);
      Sen_Val_L = SenAvg(Sensor_Left);

    }

    int SenAvg(int SensorNumber)
    {

      Arr[100]= 0;
      avg = 0;

      for(int i = 0; i<100; i++)
      {
        Arr[i] = analogRead(SensorNumber);
        avg = avg + Arr[i];
      }
        avg = avg/100;
        return avg;
    }
    void loop(void)
    {

       GetSensor();
      if(Sen_Val_F > 200)
      {
       stop();
      }

    }

body:
> All my code does is stop the motors when the front sensor detects a wall. My next step is to implement the encoders to give the robot a 90 degree turn.

would this work?

      if (wall_sensed()) turn_90right(); //if wall is sensed, turn 90 degrees to the right

You may also consider change

      digitalWrite(5,LOW);
      digitalWrite(6,LOW);

to:

      digitalWrite(MOTOR_LF,STOP);   //stop left front motor
      digitalWrite(MOTOR_LR,STOP);   //stop left right motor

so that

1. it is a lot more readable; and
2. if you were to change pin assignment, it is done consistently throughout your code.


body:
What encoders do is give you clocked feedback on motor rotation, which you can count to get an idea of position and speed. So in order to turn by a specified amount, you will need to know how much your wheel has to turn for the given angle. You can then turn the wheel precisely by dividing your wheel circumference with the maximum encoder ticks per revolution.

Say we get 600 ticks per revolution and our wheel has a circumference of 10cm.
We would then turn the wheel by `100mm / 600 = 0,16mm` per encoder tick!

You could even write a function taking more parameters into account (robot diameter/distance between wheels) that calculates these values.
A faster/more empirical approach than gathering all these values is to just drive your robot for x (i.e. 100) ticks and measure the angle it drove to get a direct relation between encoder ticks and robot angle.

Another, much more precise solution would be to utilize a compass or gyroscope to measure the robot's orientation and rely on that instead of the encoders.


message:
Led and button simulation of a blink

My circuit:
[![enter image description here][1]][1]

My code:

    // Pin 13 has a LED connected on most Arduino boards.
    // give it a name:
    int led = 13;
    const int buttonPin = 2; // pushbutton connected to pin 2.

    // the setup routine runs once when you press reset:
    void setup() {
      // initialize the digital pin as an output.
      pinMode(led, OUTPUT);
      pinMode(buttonPin, INPUT);
    }

    // the loop routine runs over and over again forever:
    void loop()
    {
      bool buttonState = digitalRead(buttonPin);
      while (buttonState == HIGH) // check while the button is pressed
      {
       digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
       delay(1000);               // wait for a second
       digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
       delay(1000);               // wait for a second
      }
    }

What I wish to do is that when I press the button, the Led's start flashing and when I press them again, they stop blinking (like a fire alarm). Right now they do nothing and I dont know why. Is it something with the circuit or the code?
  [1]: https://i.stack.imgur.com/OAODo.jpg

body:
The volatage level on the IO pin needs to change (from low to high and vice versa), only then can the microcontroller detect a button press. Without another connection to the button, IO2 is simply floating (unconnected).

There are two methods to implement this: external pull-up or external pull-down resistors and internal pull-up resistors (both methods are described for example in [this tutorial](https://electrosome.com/switch-arduino-uno)).

I prefer the internal pull-up resitor method. You need to connect the second pin of the button to GND. Then change your setup code to

    pinMode(buttonPin, INPUT_PULLUP);

If the button is not pressed, the internal pull up resistor inside the microcontroller pulls IO2 to +5V and a `digitalRead(buttonPin)` returns `HIGH`. When you press the button, IO2 is pulled to GND and `digitalRead(buttonPin)` returns `LOW`.

So in your case you need to check for a `LOW` reading, because you want the LEDs to blink when the button is pressed.

(Btw. you can replace the while loop with an if, since the `loop()` function is already executed in an infinite loop.)


message:
Does int array[100] = {0} construct work on Arduino?

I'm compiling my code in Arduino IDE. I have an array that I want to 0-initialize. I know `memset` works on Arduino, but I'm used to this way from my desktop C++ programming practice:

    int array[100] = {0};

I couldn't find any info on whether or not this construct works on Arduino. I think it should since it uses GCC compiler. Even though it may be modified, I still expect it to remain C and C++-compliant. Still, can you confirm for me that this standard-compliant C/C++ construct works on Arduino?

body:
> I'm used to this way from my desktop C++ programming practice:
>
>     int array[100] = {0};
>
> I couldn't find any info on whether or not this construct works on Arduino.

The `= {0}` has no actual effect. It is the same as:

    int array[100];

Uninitialized static / global variables, and variables explicitly initialized to 0, are placed in the [.bss](https://en.wikipedia.org/wiki/.bss) section of memory.

This section is initialized to 0 by the CRT ([C Runtime]()) code (the startup code for the system).

The compiler is responsible for placing these variables in the .bss, but it is the job of the startup (CRT) code to initialize it to zero.

This is standard C operation and is not likely to ever change since it would break all sorts of things.

Note: this does NOT apply to local variables allocated on the stack. These *must* be initialized to 0 if you want them to start as 0.


body:
The GNU cross compilers for Arduino use C/C++ front-ends and meet some version the language specs. (Although that is a moving target, you can expect a recent IDE version will be compliant with a reasonably recent language spec.)

"Arduino language" is a misnomer. The Arduino IDE will try to assist new programmers by, for example, automagically discovering library references and inserting the required #includes for you, but the resulting code is C++ and will be presented to a C++ compiler. The IDE provides a `main()` function that calls `setup()` and `loop()` (and `serialEventRun()` if you provide one) thereby reminding the programmer to initialize whatever needs to be initialized before expecting things to work right. However you can write proper C++ and get what you've come to expect. You'd have to go 'behind the IDE's back' as it were, to suppress the automatically-supplied `main()` function, but the toolchain doesn't care, as long as there is one and only one, `main()`.

I tested this this trivial program:
```
    int array[100];

    void setup() {
      // put your setup code here, to run once:
       for(uint8_t i = 0; i < sizeof(array); ++i)
          array[i] = i;
    }

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

    }
```

with both the Arduino IDE and Sloeber - Eclipse with the EclipseArduino plugin, which routinely provides a basic memory map after compilation - and with and without the initialization expression `= {0}`. I found no difference in the size of the output in either environment, with or without the initialization. In all four cases, the .bss was 209 bytes, 200 bytes larger than without the global array.


body:
This construct does work in Arduino IDE. In fact, `= { 0 }` is one of the iconic idioms of C language. It can be used to zero-initialize an object of *any* type in C. In C++ things are a bit more complicated. It will work for an `int [100]` array, but in general case you might be better off with `= {}` initializer to achieve the same effect where applicable.

It is not clear why the accepted answer claims that this construct "has no actual effect" though. This is, of course, incorrect. More precisely, this initializer is *redundant* ("has no effect") on variables with static storage duration, since such variables are default-initialized anyway (zero-initialized for `int [100]`), even if you don't request it explicitly. But for a *local* variable declaration the effect of `= { 0 }` is undeniable and obvious: it will zero-initialize the array (which wouldn't've been initialized without it).

Note that even though the `0` in the `= { 0 }` initializes the first element of the array, this initializer ultimately triggers zero-initialization if the *entire* array.


message:
BLE Shield v2.1

I have an Arduino Mega 2560 and a BLE Shield v 2.1 from RedBearLab. When I try to connect it through Bluetooth from my laptop to 'BLE Shield', it says 'Connected!'. When I try from a Windows phone, it also says 'Connected'.

But when I try to connect from an Android device, it gives me an error: 'pairing rejected by BLE shield' or 'couldn't pair with BLE Shield because of an incorrect PIN or passkey'.

What seems to be the problem?

body:
I would guess that the problem is an incorrect PIN or passkey.

I've read from manuals for some gadgets that some devices/phones automatically try the PIN 0000 and some don't.  I have never seen my Windows phone ask for a PIN when the device hasn't got one set, so I'm guessing that Windows automatically tries 0000 and Android doesn't.  Is there a  setting on Android that will let you enter the pin (which is probably 0000) ?


message:
MIDI connectors / Diodes

Does anybody know if the following MIDI DIN connectors will fit in a breadboard?

(or in general with 'generic' electrical components?)

[MIDI DIN][1]

And the same for:

[Diodes][3] to be used for MIDI in.

  [1]: https://www.aliexpress.com/item/10Pcs-PCB-Panel-Mount-MIDI-Female-DIN5-DIN-5-Pin-Jack-D501/32791217703.html?spm=2114.01020208.3.1.t95Qxz&ws_ab_test=searchweb0_0,searchweb201602_1_10000073_10065_10068_10000074_10000132_10000033_10000030_119_10000167_10000026_10000175_10000126_10000129_10000023_10000123_432_10000069_10000068_10060_10062_10056_10055_10054_10000063_301_10059_10000120_10099_10000020_10000156_10000158_10000013_10000117_10103_10102_10000016_10000114_10096_10000111_10052_10053_10050_10107_10051_10106_10000097_10000094_10000090_10000147_10000091_10000144_10084_10000150_10000101_10083_10000100_10080_10000153_10000104_10082_10000045_10081_10110_10000108_10111_10000191_10112_10113_10000197_10114_10000089_10000086_10037_10000179_10000083_10000042_10000135_10000080_10078_10079_10077_10000039_10073_10000140_10070_10000036_10122_10123_10126_10124_10000187,searchweb201603_9,afswitch_1,ppcSwitch_5_ppcChannel,single_sort_1_price_asc&btsid=0146bbcb-0e04-4366-8430-cef31841f51c&algo_expid=0023200f-8a8b-4111-894e-cfac21bf8947-0&algo_pvid=0023200f-8a8b-4111-894e-cfac21bf8947
  [2]: https://nl.aliexpress.com/item/6-pcs-5-Pin-DIN-PCB-Mounting-Female-Sockets-Audio-ADAPTER-CONNECTOR-for-PC-Keyboard/32667718184.html?spm=2114.010208.3.64.IprWw0&ws_ab_test=searchweb0_0,searchweb201602_1_10000073_10065_10068_10000074_10000132_10000033_10000030_119_10000167_10000026_10000175_10000126_10000129_10000023_10000123_432_10000069_10000068_10060_10062_10056_10055_10054_10000063_301_10059_10000120_10099_10000020_10000156_10000158_10000013_10000117_10103_10102_10000016_10000114_10096_10000111_10052_10053_10050_10107_10051_10106_10000097_10000094_10000090_10000147_10000091_10000144_10084_10000150_10000101_10083_10000100_10080_10000153_10000104_10082_10000045_10081_10110_10000108_10111_10000191_10112_10113_10000197_10114_10000089_10000086_10037_10000179_10000083_10000042_10000135_10000080_10078_10079_10077_10000039_10073_10000140_10070_10000036_10122_10123_10126_10124_10000187-normal#cfs,searchweb201603_9,afswitch_1,ppcSwitch_5,single_sort_1_default&btsid=1f53af6f-43b3-40cd-9eb1-9d99a6817a4c&algo_expid=2b87c29d-a3b7-4676-91e0-3d1743e326fd-6&algo_pvid=2b87c29d-a3b7-4676-91e0-3d1743e326fd
  [3]: https://nl.aliexpress.com/item/50-Stks-1N914-DO-35-Hoge-Conductance-Fast-Diode/32678059771.html?spm=2114.010208.3.46.AwZwQl&ws_ab_test=searchweb0_0,searchweb201602_1_10000073_10065_10068_10000074_10000132_10000033_10000030_119_10000167_10000026_10000175_10000126_10000129_10000023_10000123_432_10000069_10000068_10060_10062_10056_10055_10054_10000063_301_10059_10000120_10099_10000020_10000156_10000158_10000013_10000117_10103_10102_10000016_10000114_10096_10000111_10052_10053_10050_10107_10051_10106_10000097_10000094_10000090_10000147_10000091_10000144_10084_10000150_10000101_10083_10000100_10080_10000153_10000104_10082_10000045_10081_10110_10000108_10111_10000191_10112_10113_10000197_10114_10000089_10000086_10037_10000179_10033_10000083_10000042_10000135_10000080_10078_10079_10077_10000039_10073_10000140_10070_10000036_10122_10123_10126_10124_10000187,searchweb201603_9,afswitch_1,ppcSwitch_5,single_sort_1_price_asc&btsid=a0290d56-802c-4022-b235-4d24ee48ea5f&algo_expid=062424e5-c965-4a5c-9520-0b488feafecd-5&algo_pvid=062424e5-c965-4a5c-9520-0b488feafecd

body:
Breadboards use a 2.54 mm (0.1") grid. The PCB footprint on that link uses a nominal 2.5 mm grid, which is essentially the same:
![MIDI jack PCB footprint](https://i.stack.imgur.com/P6C0F.png)

However, those pins are rather large; it's possible that you need to rotate some pins by 90° (with pliers and brute force) to make them fit into your breaboard's holes, or that they do not fit at all. And even if they fit, they can ruin your breadboard.
You might need to file them off.

Consider using a panel-mount MIDI jack instead (which would require soldering, or leads with test clips):

![panel-mount MIDI jack](https://i.stack.imgur.com/pO8DM.jpg)
(search for "5 pin DIN female jack")

---

The MIDI specification recommends a 1N914 diode, but that is only because it was written over thirty years ago. The 1N4148 is much more common now, and has the same characteristics. But this diode is used only as reverse voltage protection for the optocoupler's LED, so you can use any random fast switching diode.

---

As for the optocopler (which you didn't mention, but I'll throw in my two cents worth anyway): the PC900 was discontinued, and the 6N138 is slow. Use either the H11L1 (of which the PC900 was a clone) or the 6N137; both work best with a 1 kΩ pull-up resistor.


message:
ESP01 unsuccessful code execution

I am trying to upload the Blink example from the Arduino IDE to a ESP8266-01 module using an Arduino Uno as serial programmer.
Now, the upload is successful but, upon restart (and disconnecting GPIO0 from GND), nothing happens. <br>I have tried with different example sketches but it seems code was not uploaded.

My Board manager configuration

- Board: Generic ESP8266 Module
- Flash mode: QIO
- Flash frequency: 40 MHz
- CPU frequency: 80 MHz
- Flash size: 1M (128K SPIFFS)
- Debug port: Serial
- Debug level: none
- Reset method: ck (tried nodemcu too without success)
- Upload speed: 115200
- USB port

As an addition, here's what I get from the ESP01 through the Arduino IDE Serial monitor:

    load 0x4010f000, len 1384, room 16
    tail 8
    chksum 0x2d
    csum 0x2d
    v09f0c112
    ~ld
    e:
     ets Jan  8 2013,rst cause:3, boot mode:(3,7)

    ets_main.c

and here's the IDE console window output:

    sptool.py v1.3
    Connecting..........
    Auto-detected Flash size: 8m
    Running Cesanta flasher stub...
    Flash params set to 0x0020
    Writing 229376 @ 0x0... 0 (0 %)1024 [...]
    Wrote 229376 bytes at 0x0 in 39.0 seconds (47.0 kbit/s)...
    Writing 229376 @ 0x10000... 0 (0 %)1024 [...]
    Wrote 229376 bytes at 0x10000 in 39.0 seconds (47.0 kbit/s)...
    Leaving...

The sketch I am using

    void setup() {
      pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
    }

    // the loop function runs over and over again forever
    void loop() {
      digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                        // but actually the LED is on; this is because
                                        // it is acive low on the ESP-01)
      delay(1000);                      // Wait for a second
      digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
      delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
    }

body:
If you are using an ESP01 I don't think you should be using GPIO1 as the output pin, its my understanding that they don't have GPIO1.

I think they have GPIO0 and GPIO2, so you should have attached the LED to GPIO2 and use `digitalWrite(2, HIGH);` in you code.

Have a look at this page and see if what its on about is what you are trying to do.

http://iot-playground.com/blog/2-uncategorised/38-esp8266-and-arduino-ide-blink-example


message:
Post-split, where do I download the Arduino IDE?

I've been out of the loop with Arduino for several years.  I [heard][1] about [the split][2] (another [link][3]), but didn't really understand, nor keep up with it, nor the details of the fallout.

Today, I decided to jump back in and make something, and a [DDG search][4] led me to [Arduino.cc][5] to get the software.  But is that what I need?

How do I know if that's the right software IDE?  Is there another location?  Does it matter?  Does it depend on more variables?  Is this [split][6] akin to the [OpenOffice][7] and [LibreOffice][8] split, where one is more better (technical term!) supported than the other?

I'm working on an Arduino Uno I got from [Microcenter][9].

  [1]: http://makezine.com/2015/03/06/arduino-vs-arduino/
  [2]: https://news.slashdot.org/story/16/10/01/1926242/the-arduino-split-is-over-new-non-profit-formed
  [3]: https://olimex.wordpress.com/2015/03/20/arduino-split-in-court-revail-how-the-project-started-and-developed/
  [4]: https://duckduckgo.com/
  [5]: https://www.arduino.cc/en/Main/Software
  [6]: https://www.howtogeek.com/187663/openoffice-vs.-libreoffice-whats-the-difference-and-which-should-you-use/
  [7]: https://www.reddit.com/r/software/comments/2tmu4l/openoffice_vs_libreoffice/
  [8]: http://www.techrepublic.com/article/whats-the-difference-between-libreoffice-and-openoffice/
  [9]: http://www.microcenter.com/product/431997/Uno_R3_MainBoard

body:
The split is already over. They are working on merging everything that happened during the split, if they haven't already.

I'd go with the arduino.cc version, as that was the website before the split (where the other party used arduino.org).


body:
Both sites contain the same version of the IDE. .Org dropped their 1.7.x branch (actually 1.0.x renumbered) and both now have the 1.6.x branch version-bumped up to 1.8.x.

As Gerben noted, the split is over, https://arduino.meta.stackexchange.com/q/2380/4143.


message:
How I can make alarm on off?

I want to do is BEEP! to show that the program is running.

    #define SPKR 4 //this is the digital pin that you plugged the red       wire into

    void setup()
    {
       pinMode(SPKR, OUTPUT); //set the speaker as output
    }

    void loop() //do this over and over
    {
       digitalWrite(SPKR, HIGH); //turn the speaker on
       delay(500);                     //wait for half a second
       digitalWrite(SPKR, LOW); //turn the speaker off
       delay(500);                    //wait for half a second
    }

With out this any other way
I mean without repeating the code HIGH / LOW
during this beep I want do same things else

body:
The code you show will toggle the `SPKR` pin at a 1 Hz rate.  If you have an ordinary speaker attached, you will hear it click twice a second, but it won't generate an audible tone.

To generate a tone, use [`tone(pin, frequency)`](https://www.arduino.cc/en/Reference/Tone) calls, or `tone(pin, frequency, duration)` calls.

For example:

    void loop() {
       tone(SPKR, 400, 500); // 400 Hz tone for half second
       delay(500);           // no tone for half second
    }

Note, ordinary speakers are low-impedance devices, eg 4 Ω, 8 Ω, etc.  You can use an audio transformer for impedance matching – this helps produce an adequate output volume – but lacking that, should put a resistor (eg 220 Ω) in series with the speaker to avoid over-current conditions.  AVR pins can deliver 25 mA without too much stress, and typically are rated at an absolute max of 40 mA.


message:
How can an Arduino-Quadcopter be stabilized?

I have built an arduino quad-copter and I am using an MPU6050 to read the rotational position and velocity of the aircraft. The problem is that I cannot get the thing to stabilize. Watch this video [here][1] to get an idea of what I mean.

So as you can see from the footage (and you did watch it, right?), I'm not even getting steady oscillations, it's just random. What I don't understand is how people get their quad-copters to oscillate very quickly (maybe 10 times per second) and then trim up their PID gains to smooth it out, whereas if I raise my p-gain high enough for it to adjust that quickly, the quad-copter just goes berserk and tries to kill me.

And, speaking of p-gains, here's the PID I wrote:

    float KrP = 0.002000;
    float KrI = 0.000001;
    float KrD = 0.200000;

    void adjustRoll(float currentRoll, int newRoll) {
      if (thrust <= 1200){
        inAutoRoll = false;
        NWPower = thrust;
        NEPower = thrust;        //PID not ready to turn on yet? Just set motor powers
        SWPower = thrust;        //equal to the throttle.
        SEPower = thrust;

        I_roll = 0;              // Reset the integral.
        return;                  // Don't do anything else
      }

      float newRate = 2 * (newRoll - currentRoll); // How fast should the drone try to
                                                                           // adjust, based on the error.

      if (newRate > 50)newRate = 50;        // Don't adjust too fast!
      else if (newRate < -50)newRate = -50;

      float offset = newRate - rollRate;

      I_roll += KrI * offset;

      if(!inAutoRoll) {        // Is the PID just now turning on? (Throttle requirement met).
        lastRollRateOffset = offset;  //Smooth transition.
        inAutoRoll = true;
      }

      float adjust = (KrP * offset) + (KrI * I_roll) + (KrD * (offset - lastRollRateOffset));

      NWPower += adjust;
      NEPower -= adjust;
      SWPower += adjust;
      SEPower -= adjust;

      if (NWPower > maxOut) NWPower = maxOut;
       else if (NWPower < minOut) NWPower = minOut;

      if (NEPower > maxOut) NEPower = maxOut;
       else if (NEPower < minOut) NEPower = minOut;

      if (SWPower > maxOut) SWPower = maxOut;
       else if (SWPower < minOut) SWPower = minOut;

      if (SEPower > maxOut) SEPower = maxOut;
       else if (SEPower < minOut) SEPower = minOut;

      lastRollRateOffset = offset;
    }

And in case you were wondering... yes, I do know about integral windup. The reason I have not dealt with that in my code is because the quadcopter is no where near stable, so I'm not worrying about perfection just yet. Also, I have my I-gain set to 0.000001, so it doesn't matter. The reason I have done this is because (as far as I know) a quadcopter can fly with only P and D, and with the way mine is behaving, I think a larger I-gain would only make things worse.

More detail about my PID: The PID corrects for the rotational velocity of the quad-copter, which, as I understand it, is the best way to control a quadcopter. The correction-rotation-rate is determined by multiplying the error (in degrees) by two. Why two? I dunno. I experimented with some other multipliers and two seems to be okay. Its also a prime number, so, yeah...

So anyways! **What do I need to do to make the quad-copter stable?** I have seen amazingly perfect quad-copters using the same arduino and the same MPU6050, but mine just tilts all over the place.

Some possible problems off the top of my head:

 1. Bad algorithm for calculating the needed rotational velocity based on error.
 2. Bad PID algorithm.
 3. Bad PID gains.
 4. I didn't balance my props, but seriously, would a couple of pieces of electrical tape stuck to the props really fix this? It doesn't seem like it would.

Thanks for any help you have to offer!

  [1]: https://youtu.be/0zaPF644_Io

body:
For stability and tuning you need to make the adjustment cycle time compatible with the physical system.  How fast does this adjustment code get called relative to how fast the physical system oscillates?  Without that under control, tuning the gains will be difficult, particularly for krI and krD.

For instance, if you are updating every millisecond, and it takes a 1/10th of a second to physically flop over from -90 to 0 at the current roll_thrust setting, there's only enough kP to adjust the roll_thrust `kP*(RollDelta/2)*DT/dt=0.002*(90/2)*0.1/0.001=9`  Is that a sane adjustment for a thrust/motorPower of 1200+?  If you sample fast enough to make it capable of a full-throttle (+/-800?) adjustment with this particular kP, you might need to sample 88x faster (1ms/(800/9)=0.01125ms).  From the other direction, I'd figure out how fast you can sample, then choose a krP that could get you a full-bias adjustment in reasonable time.

Maybe think of `adjust` as `roll_thrust` state variable measured in units of ESC_microseconds, and krP is the conversion factor from whatever error you are measuring.  Is it roll angle error? roll rate error? Absolute roll rate error?  It looks like this bit:

    float newRate = 2 * (newRoll - currentRoll); // How fast should the drone try to
    if (newRoll - currentRoll < 0) {             // adjust, based on the error.
       newRate = 0 - newRate;
    }

is essentially:

    float newRate = 2 * abs(newRoll - currentRoll);

which might make control discontinuous.  If currentRoll is a positional roll angle setpoint, it won't be able to tell if it is on one side or the other.

If you want a roll angle of -90deg to make full throttle one way and 90deg to full throttle the other, then krP should be on the order of 900us/90deg=10us/degree.   And krI=krD=0 to start with.

I'd code up separate PIDs for `thrust`, `roll_thrust`, `pitch_thrust`, `yaw_thrust` control variables and then sum them together to get the  `{NE,NW,SE,SW}Power` outputs.  Then you could monitor and control in {thrust,roll_angle,pitch_angle,yaw_rate} space and the coding will be more straightforward and interpretable.


body:
To help solve this problem, I wrote a program in *Processing* that graphs all the data from the quadcopter, including roll rate, roll angle, thrust, etc... After doing so I realized that the problem was not in the PID, but in how I handled the data coming out of MPU6050. You can read all about it in this question I posted [here][1] before I had discovered the full solution.

The quadcopter is now capable of taking off, though sadly it is not very stable. This could be from bad PID gains, but I suspect it is from vibration in the roll-rate values from the MPU6050. The reason I think this is because I don't see steady oscillations, but rather random movement. Anyway, If I find a more complete solution I will update this answer.

  [1]: https://arduino.stackexchange.com/questions/35440/mpu6050-sending-bad-values-for-angular-velocity


body:
To be sure the receiver gets the right signal from the emitter it is mandatory to scrutinize the signal on the receiver for a while.
Once the signal on the receiver is checked good it is possible to go ahead step by step.
The first step is to drive the 4 ESC/motors with the same signal coming from the throttle.
Once the behavior of the 4 motors complies with changes on the throttle coming from the emitter it is time to go to the next step.
The next step stems from a mix with pitch/roll/yaw coming from the emitter.
The mix is added/removed to/from the throttle addressing each motor.
The behavior of the 4 motors must show exactly the mix that comes from the emitter.
An "acceptable" mix is something like (in the same unit, degres or microseconds):

Something like this:

```c++
int throttle_gaz;
int roll_length, pitch_length, yaw_length;

throttle_gaz=pulse_duration[throttle_chanel];
if ( abs(throttle_gaz-1500) <= 50 )
{
 throttle_gaz=1500;
}
roll_length=pulse_duration[roll_chanel]-1500;            //ROLL
if (abs (roll_length) <=100 )
{
roll_length=0;
}
roll_length/=3;

pitch_length=pulse_duration[pitch_chanel]-1500;           //PITCH
if (abs (pitch_length) <= 100 )
{
  pitch_length=0;
}
pitch_length/=3;

yaw_length=pulse_duration[yaw_chanel]-1500;             //YAW
if (abs (yaw_length) <=100 )
{
  yaw_length=0;
}
yaw_length/=3;

//add/soustract from THROTTLE (pulse_duration[throttle_chanel])
//change the sign (+ / -) acc
pulse_length_esc1=throttle_gaz + roll_length + pitch_length - yaw_length;
pulse_length_esc2=throttle_gaz - roll_length +  pitch_length +  yaw_length;
pulse_length_esc3=throttle_gaz + roll_length - pitch_length  + yaw_length;
pulse_length_esc4=throttle_gaz - roll_length -  pitch_length  -  yaw_length;
```


message:
Cheat Sheet for interruption

Just read a post about timers and there was a timers cheat sheet posted there. It has been very helpful and I wonder if there is one for interrupts as well?

The post with the nice timer cheatsheet was this one https://arduino.stackexchange.com/questions/16698/arduino-constant-clock-output

body:
Perhaps something like this (for the Arduino Uno based MPU): [![enter image description here][1]][1]

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


message:
Why does the serial monitor output show some unidentified symbols?

#define LED 13
    #define BAUDRATE 9600
    #define DEBUGOUTPUT 0
    #define LED 13
    #define powercontrol 10

    // checksum variables
    byte generatedChecksum = 0;
    byte checksum = 0;
    int payloadLength = 0;
    byte payloadData[64] = {0};
    byte poorQuality = 0;
    byte attention = 0;
    byte meditation = 0;

    // system variables
    long lastReceivedPacket = 0;
    boolean bigPacket = false;

    //////////////////////////
    // Microprocessor Setup //
    //////////////////////////
    void setup() {
      pinMode(LED, OUTPUT);
      Serial.begin(BAUDRATE); // USB
    }

    ////////////////////////////////
    // Read data from Serial UART //
    ////////////////////////////////
    byte ReadOneByte() {
      int ByteRead;
      while(!Serial.available());
      ByteRead = Serial.read();
      #if DEBUGOUTPUT
      Serial.print((char)ByteRead);
      // echo the same byte out the USB serial (for debug purposes)
      #endif
      return ByteRead;
    }

    /////////////
    //MAIN LOOP//
    /////////////
    void loop() {
      // Look for sync bytes
      if(ReadOneByte() == 170) {
        if(ReadOneByte() == 170) {
          payloadLength = ReadOneByte();
          if(payloadLength > 169)
          //Payload length can not be greater than 169
            return;
          generatedChecksum = 0;
          for(int i = 0; i < payloadLength; i++) {
            payloadData[i] = ReadOneByte();
            //Read payload into memory
            generatedChecksum += payloadData[i];
          }
          checksum = ReadOneByte();
          //Read checksum byte from stream
          generatedChecksum = 255 - generatedChecksum;
          //Take one's complement of generated checksum
          if(checksum == generatedChecksum) {
            poorQuality = 200;
            attention = 0;
            meditation = 0;
            for(int i = 0; i < payloadLength; i++) {
              // Parse the payload
              switch (payloadData[i]) {
                case 2:
                  i++;
                  poorQuality = payloadData[i];
                  bigPacket = true;
                  break;
                case 4:
                  i++;
                  attention = payloadData[i];
                  break;
                case 5:
                  i++;
                  meditation = payloadData[i];
                  break;
                case 0x80:
                  i = i + 3;
                  break;
                case 0x83:
                  i = i + 25;
                  break;
                default:
                  break;
              } // switch
            } // for loop

            #if !DEBUGOUTPUT
            // *** Add your code here ***
            if(bigPacket) {
              if(poorQuality == 0) digitalWrite(LED, HIGH);
              else digitalWrite(LED, LOW);
              Serial.print("PoorQuality: ");
              Serial.print(poorQuality, DEC);
              Serial.print(" Attention: ");
              Serial.print(attention, DEC);
              Serial.print(" Time since last packet: ");
              Serial.print(millis() - lastReceivedPacket, DEC);
              lastReceivedPacket = millis();
              Serial.print("\n");
              switch(attention / 10) {
                digitalWrite(LED, HIGH);
                digitalWrite(LED, LOW);
              }
            }
            #endif
            bigPacket = false;
          } else {
            // Checksum Error
          } // end if else for checksum
        } // end if read 0xAA byte
      } // end if read 0xAA byte
    }

body:
It time to start stroking our crystal balls, what symbols?

Actually it doesn't really matter, `ReadOneByte()` is the cause, you are printing `ByteRead` without checking that it is printable.  Character greater than 127 will look strange when you print them out, only 32-126 are printable (127 is backspace) see http://www.asciitable.com/ for more details.  In this case I would print the value as a hex number, `Serial.println(ByteRead, HEX);`

If you are still getting symbols after changing that there may be other prints that have the same problem


body: select the same serial **Baudrate** in the select which is in the bellow of the serial monitor window as you have put in the code.


message:
5V usb surge protection for circuit board?

I want to use a mini usb jack to power my device off board, but I want to make sure that the usb power coming in is not any higher than the 5V. I've read a bit about polyfuses but I am unsure if they would be useful for this scenario. Thanks!

body:
A polyfuse will limit **current** not voltage.

There are transient protection diodes which switch on if voltage exceeds a given level, which are often used in conjunction with a polyfuse. The diodes cause excessive current to flow, effectively turning on the polyfuse for extended overload, or just absorbing shorter transients. The Raspberry Pi uses a SMBJ5.0A device to suppress transients.

You should NOT need any of this if you use a reasonable power supply.


body:
I second Milliways answer:

> You should NOT need any of this if you use a reasonable power supply.

Anyway, if you really have a crappy power supply you can use one of the modules you find on ebay (for instance [this](http://www.ebay.com/itm/142230430507) is the first result I came across). Be sure to look for "buck boost" modules (step up/down), because they can both raise and lower the voltage.

This will do the job your power supply is not able to do, so to give you a stable voltage. You can then also vary the voltage without worrying (they usually are able to handle 4V (e.g. lithium batteries), 7.2V (e.g. 2 lithium batteries), 12V, ...

If you want also reverse protection, I suggest you to simply put a diode in series with THE INPUT (anode on the positive of your power supply, cathode on the IN+ terminal of this regulator). This way the voltage drop will be absorbed by the regulator. You can use a cheap 1N4007 or even a Schottky diode (which have less drop -> better power consumption).

I discourage you from using a full wave rectifier, since the diodes on the ground will change the ground reference (and so if you connect something else you may experience problems).

You can find a lot of "buck/boost" modules out there, just check that the input and output voltages and currents are suitable for your project.

But again, unless your power supply is really crappy you won't need this. If you just need an inversion protection, you can also use a circuit I found on a PC : put a fuse (they used a real fuse, you can use a polyfuse) between the power positive input and the circuit positive, then add a diode with the anode to ground and the cathode to the circuit positive. If you attach it correctly the diode will be reverse polarized and the circuit will work correctly, if you attach it in reverse the diode will conduct and so will create a large current which will trip the fuse.


message:
Stop Led's from blinking

My code:

    // Pin 13 has a LED connected on most Arduino boards.
    // give it a name:
    int led = 13;
    const int buttonPin = 2;

    // the setup routine runs once when you press reset:
    void setup() {
      // initialize the digital pin as an output.
      pinMode(led, OUTPUT);
      pinMode(buttonPin, INPUT_PULLUP);
    }

    // the loop routine runs over and over again forever:
    void loop()
    {
      bool buttonState = digitalRead(buttonPin);
      while (buttonState == LOW)
      {
       digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
       delay(1000);               // wait for a second
       digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
       delay(1000);               // wait for a second
       }
     if (buttonState == HIGH){
       digitalWrite(led, LOW);}
      }

The last line of code:

    if (buttonState == HIGH){
       digitalWrite(led, LOW);}
Is what I tried using to turn the led off from its continuous blinking state. So the point of this project is to make the led's blink with a button, then turn them off with the same button. This has been bugging me for hours and I've done all the work but can't seem to get this last part done. What is being done wrong here?

**EDITED for clarification:**

The intention is that with each push of the button the LED is toggled between a blinking and a no-blinking state. The state of the LED is not driven by the level (pushed/unpushed) of the button itself, but by the pushing action itself.

body:
while (buttonState == LOW)
gets you trapped in an endless loop, once `buttonState == LOW`.

You have to poll `buttonState` **inside** this loop if you ever want to get out of it.

However this is not enough for your purpose. What you really need is a (boolean) variable - let's name it `blinking`, for instance - which changes its value each time you see a falling edge on buttonState.

Then check this variable's value in an if/else clause like this:

    if (blinking == true)
    {
       digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
       delay(1000);               // wait for a second
       digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
       delay(1000);               // wait for a second
    }
    else
    {
       digitalWrite(led, LOW);}
    }

But with this you will soon face the next problem: The polling speed for your button is very low, because of the very long delays, which keep you about 2 seconds inside the `if` clause.

Try setting up the blink cycle using a PWM, as described [here][1]

Then use the `if` clause above to set the PWM duty to 50%, and the `else` clause to set it to 0%.

  [1]: http://playground.arduino.cc/Code/Timer1


body:
**EDITED**

The Arduino `loop()` function makes the use of a `while` loop redundant in this case. Even worse: the way you've implemented that `while` loop prevents `buttonState` from being updated, thus getting stuck in the loop.

What you actually need is to use timers to blink the LED, and a 2-state machine driven by HIGH to LOW button transitions.

Try this instead:

    #include "Timer.h"

    // Pin 13 has a LED connected on most Arduino boards.
    // give it a name:
    const int led = 13;
    const int buttonPin = 2;

    // declare state variables as global
    bool buttonState = LOW;
    bool buttonState_prev = LOW;
    bool toggleBlinking;
    bool blinkState;

    // declare a Timer object so blinking can be done without loosing button presses
    Timer timer_b;
    int blink_id;

    // the setup routine runs once when you press reset:
    void setup() {
      // initialize the digital pin as an output.
      pinMode(led, OUTPUT);
      pinMode(buttonPin, INPUT_PULLUP);

      // initial state: toggle led each 1000 ms
      blink_id = timer_b.oscillate(led, 1000, HIGH);
      blinkState = true;
      toggleBlinking = false;
    }

    // the loop routine runs over and over again forever:
    void loop() {
      // Update the timer (required)
      timer_b.update();

      // check if button has been pressed (HIGH to LOW),
      // then debounce it and raise toggle flag
      buttonState = digitalRead(buttonPin);
      if ((buttonState != buttonState_prev) && (buttonState_prev == HIGH)) {
        // simple button debounce (confirm press after some ms)
        delay (50);
        buttonState = digitalRead(buttonPin);
        if (buttonState != buttonState_prev) toggleBlinking = true;
      }

      // keep current LED state unless the button has been pushed
      switch (blinkState) {
        case true:
          // if button has been pushed, stop blinking and change LED state
          if (toggleBlinking == true) {
            timer_b.stop (blink_id);
            blinkState = false;
          }
          break;
        case false:
          digitalWrite(led, LOW);
          // if button has been pushed, start blinking and change LED state
          if (toggleBlinking == true) {
            blink_id = timer_b.oscillate(led, 1000, HIGH);
            blinkState = true;
          }
          break;
      }

      buttonState_prev = buttonState;
      toggleBlinking = false;
    }

**NOTE:** You'll need to install the [Timer.h library][1]. I'VE TESTED MY CODE AND IT WORKS.

  [1]: https://github.com/JChristensen/Timer


body:
As the OP explained in a comment, what he is trying to achieve is to have a button alternate between blink and off, not having the button to be pressed to shut down the led.

This can be done in this way:

    bool prevButtonState;
    bool ledBlinking;

    void loop()
    {
     bool buttonState = digitalRead(buttonPin);

     if (prevButtonState && !buttonState)
     { // Pressing edge: there is a transition between high and low
      ledBlinking = !ledBlinking;
     }
     prevButtonState = buttonState;

     if (ledBlinking)
     {
      digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);               // wait for a second
      digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);               // wait for a second
     }
     else
     {
      digitalWrite(led, LOW);
     }
    }

This, however, leads to a very long time between successive checks of the button (since there is a 2s delay between cycles). You can solve this using the millis function:

    bool prevButtonState;
    bool ledBlinking;
    unsigned long prevMillis;

    void loop()
    {
     bool buttonState = digitalRead(buttonPin);

     if (prevButtonState && !buttonState)
     { // Pressing edge: there is a transition between high and low
      ledBlinking = !ledBlinking;

      prevMillis = millis() - 1000; // Force a check
     }
     prevButtonState = buttonState;

     if (ledBlinking)
     {
      if ((millis() - prevMillis) >= 1000)
      {
       prevMillis += 1000;
       digitalWrite(led, !digitalRead(led));
      }
     }
     else
     {
      digitalWrite(led, LOW);
     }
    }

Next there is the debounce problem, but this becomes OT. Suggestion: use the Bounce2 library to manage the button if you experience bounces


body:
It makes sense to make switch-testing fairly independent of blink-control.  That's done in the following code, which turns blinking on or off each time a button is pressed.  With this code, between button presses the LED either is off or it blinks at about a 2 Hz rate.

    enum { LED=13, ButtonPin=2, BounceMS=50, BlinkMS=256 };
    unsigned long buttonAt;
    bool blinky, bouncy, buttonState;

    void setup() {
      pinMode(LED, OUTPUT);
      pinMode(ButtonPin, INPUT_PULLUP);
      blinky = bouncy = buttonState = false;
      buttonAt = millis();
    }

    void loop() {
      // Detect button changes
      if (bouncy) {
        if (millis() - buttonAt > BounceMS)
          bouncy = false;  // End of debounce period
      } else {
        if (digitalRead(ButtonPin) != buttonState) {
          buttonState = digitalRead(ButtonPin);
          buttonAt = millis();
          bouncy = true;  // Start debounce period
          if (buttonState) { // Was button just pressed?
            blinky = !blinky; // Toggle blink-state
          }
        }
      }
      // Control light-blinking
      if (blinky) {
        // Turn LED on for BlinkMS ms, then off for same
        digitalWrite(LED, (millis() - buttonAt)%(2*BlinkMS) < BlinkMS);
      } else {
        digitalWrite(LED, LOW);
      }
    }


body:
try this:

    if (key_pressed()) digitalWrite(LED_PIN, (digitalRead(LED_PIN)==ON)?OFF:ON);
    else digitalWrite(LED_PIN, OFF);

define ON/OFF based on your led connection.

Edit.

If you want the button too change the mode of led blinking, try this.

  if (btn_pressed())      //if btn falling edge detected
   btn_status ^= 1;    //flip the last bit. btn_status += 1; works as well
  if (btn_status & 0x01) led1_flp(); //flip led1
  else led1_off();     //otherwise, turn off led1

  //flip led2
  IO_FLP(LED_PORT, LED2);

the logic is fairly simple: if the button is pressed (active low), toggle btn_status. if btn_status is 1, blink the led1.

basically, press the button, led starts to blink; press the button the 2nd time, led stops to blink;

led2 is always blinking, to show concurrency of the code.

here it goes in action.

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

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

the code is written for a pic but basically runs on any mcu.


message:
Increase IR transmitter directivity and range

I am working on a project to control different devices with arduino and IR LED so I am testing with this circuit:
[![IR transmitter and receiver][1]][1]
So, everything is working fine but I want to increase range of my transmitter. For now its barely giving response at 1 meter distance. **I want to increase this to at least 5 meters**. I tried to increase receiver sensitivity by giving 5V to TSOP, when I do this the range is satisfactory but the directivity is too much its even responding when I point IR LED in opposite direction(inside a room, maybe the radiaton is bouncing off walls - this is not happening with 3.3V). I Know the transmitter range can be increased by increasing the current flowing through LED like this (please correct me if I am wrong): [![Range increase with 2N222 transistor][2]][2]
The problem is with directivity of emitter, I do not want all the devices in my room to turn on when I try to turn on my TV. **The devices are placed  up to 1 meter apart and the transmitting range should be at least 5 meters.**<br/>

 - Also it would be helpful if someone clarifies which part is actually sensitive (the part which looks like LED or the flat backside part - image below) for TSOP i.e. which part receives the pulses, so that I can cover it with tape (so that it receives signal from only one direction) if nothing else works.

 [![TSOP 1738][3]][3]
Any help is appreciated, thank you.

  [1]: https://i.stack.imgur.com/jeoEh.jpg
  [2]: https://i.stack.imgur.com/R4qTa.jpg
  [3]: https://i.stack.imgur.com/83DTi.jpg

body:
The IR sensors are usually build that way, that they get signal from as wide range as possible, also using walls, ceiling etc. to reflect the signal to receiver - the bussiness logic is simple - user want press buttton and have TV reacting - no trying to hit some particular spot on TV wiht invisible light - it is not shooting game, it is meant as remote switch and if it works regardless actual direction, then the best. To select different devices the transmiter sends different codes - every device in room ideally gets the same input, just the TV "knows" it should react say to range 0xFF0000..0xFF00FF and the radio knows it should react to 0xFF1100..0xFF11FF instead (it is more conplicated and the ranges are not continuous and possibly ovelaps, but it is the principle).

So the best way to difference between your devices is using longer numbers and let the device react just to some selected (specific to that device) and ignore all others.

But if you insist on "shooting it directly to head", then the way is putting both the transmitter diode and the receiver to some kind of tubes (like bore of riffle), so the data could be only send to /get from some small cone of space and communication occures only when those cones are aligned. Anyway it would probabelly react on the reflection from the wall on your back (shooting cone opposite way) as then the cone will get way larger by distance (and so hit more receivers) and also from difraction from particles in the wall (so the wall would light to all directions, not just reflect the cone, as mirror would). And there is nearly nothing to prevent this. (Yes, you can cover the wall with some nonreflective black textile or so, but would you do it?)

---

As for active part of the receiver, the datasheet say the center of sensiteve area is in the centre of the "diode-like" part, with angle around 80 of sensitivity to both sides vercically and horisontally (with the best sensitivity vaguely straight forward) http://html.alldatasheet.com/html-pdf/26589/VISHAY/TSOP1738/1117/6/TSOP1738.html - but basically it can  somehow receive nearly from anywhere on the "diode-like" side.

The back side (flat one) should not be sensitive.

---

Also you can (and should) use resistor between the pin and transistor base, to limit current from the pin. (transistors have gain like 100 or more, so you need a little current to fully open it).

---

LEDs are current consumers, not voltage consumers, so you restrict current (not voltage) thru your LED to not burn it and to make it shine more or less. LEDS should use current sources (like providing 20mA, no more or less for normal LED), not voltage sources (which would provide something like 9V, 5V, 3.3V or any other value, no more or less).

But as there are much more easily obtained voltage sources, the resistors are use to limit current thru the LEDs as easy "cheat".

You take the voltage of source (say 9V), substract all known voltages around the path (typically 0.7V for transistors, 1.2V for LEDS and so) and suppose the rest is wasted on the resistor. Knowing maximum alloved current for your LED (typically 20mA for "normal one") you compute value of resistor by dividing voltage (in V) by current (in A) to get resitance (in Ohm).

In your picture: 9V-0.7V-1.2V=7.1V on resistor, 7.1V/0.02A=355 Ohm. You take any resistor equal or larger than that and it would be safe to shine for infinity.

First cheap IR LED I found have typical continuous current 20mA, Absolute Maximum Ratings at Ta=25℃ (room temperature) is current 100mA and  Peak Forward Current (1/10 Duty Cycle, 0.1ms Pulse Width) 1A. But those Absolute values are values, where you probabelly will destroy the LED soon, as any temperatue higher (as in summer) moves them down fast. You should read "Absolute Maximum Ratings Values"  as "values, which can destroy it randomly any moment, if I get near to them" rather than "manufacturer recomed it for extreme usage". (you cannot make perfect laboratory conditions for any device in normal use).

But if you want to make extra power on the risk of destroying the LED, you can set the resistor as low as 7.1V/0.1A = 71 Ohm or even for short pulses 7.1V/1A=7.1 Ohm, but I would bet, that the LED will burn soon anyway. I myself would risk like 80 Ohm in short pulses, but it does not get as much more light as it get in heat. Consult you datasheet and try only on your own risk.

---

**TLDR:** I suggest using unique codes by your Arduino sender for diferent receivers, because you cannot reach you goal other way with good certainlity.

Use your receiver to scan all usual remote controllers you have, then select something totally different for your Arduino receivers.


message:
PCF8563 does not remember time when restarting Arduino Uno?

I'm trying to use the following RTC module (PCF8563) with Arduino Uno.[![enter image description here][1]][1]

I am using [this library][2] to set/get time and date from PCF8563. However, whenever I shut down the Arduino, the time/date is lost! Even though, as you can see in the picture, the module is equipped with a 3V battery to keep running when Arduino is unplugged.

Any help would be highly appreciated!

  [1]: https://i.stack.imgur.com/ZaU66.jpg
  [2]: http://playground.arduino.cc/Main/RTC-PCF8563

body:
[SOLVED]

The solution is simply to put a jumper between BAT and VCC positions in the module itself. Many thanks to [Edgar Bonet][1]

  [1]: https://arduino.stackexchange.com/users/7508/edgar-bonet


message:
FFT library for Arduino 101?

I am currently trying to get a real-time FFT working for a project on an Arduino 101 which uses the Intel Curie chip. All the FFT libraries (if any) seem to be for the Arduino Uno and architecture dependent (most of them have assembly stuff for optimization).

I was wondering if there is any robust, up do date and most importantly working (with the latest Arduino 101) library. I have tried the PlainFFT library which I read might be compatible with the Arduino 101 (https://forum.arduino.cc/index.php?topic=409791.0).

However this library seems to be out of date, using old extensions of sketch files and old library names in its code (I could not get it to work). Alternatively I wanted to try and tailor a pure C code such as https://github.com/jtfell/c-fft, which seems to have its own Makefile for compilation (this one uses a C99 compiler). I could compile and use this code on a Linux terminal but I am not sure how to go on about making it run inside an Arduino sketch.

body: I used lightweighted **KissFFT** (Mark Borgerding) at Arduino Mega and seems it is pure C code so should be running anywhere.


message:
Advice needed, commercializing an Arduino Due project

We have a project using an Arduino Due, and we are looking to commercialize the project. How would one typically proceed? Would you use the Arduino Due inside the project? This seems very amateur.
Using another Arduino is not an option due to the number of interrupts, number of pins, and processing power required.
Thanks!

body:
There's two routes you can take.

First route:

1. Get the Due schematics.
2. Remove the parts you don't need.
3. Add to it the new components for your product.
4. Lay out the PCB design.
5. Get the PCB manufactured.
6. Solder all the components on.
7. Test it and go back to step 2/3 as required.

Second route:

1. Hire a contractor that knows the SAM3X and can do it all for you.


body:
Depends on the kind of project you are doing. If the Due is just minor part (say you are producind 3D printer) and you plan to do like tens of the devices, I would consider using it, but probably would solder it in for good contact reliability. Maybe put it inside a box too, so nothing can short anything on the board. (And then the Due is not in plain sight).

If it is mainly Due with some sensors around and you want to sell thousands of them, then I would make extra PCB for it, containing everything what is possible on one board. (Like @Majenko suggested.)

Anyway I made a lot of PCB in my kitchen (yes, literally) for my "Arduino" projects, even when I made only 1 or 2 devices just for me. Every of them worked just fine. It is not so dificult to do if you are not pushing some limits too hard. Even Due small chip can be soldered by hands and with some basic tools on your eating table.

But if you lack the skills, hiring contractor (or found company, which does that) may be cheaper in terms of your time and number of devices destroyed before getting the skill and customers complaining about devices broken after short time use.


message:
CAN-Bus shield, SD-card module & LED_BUILTIN use D13; possible collision?

To my knowledge the SeeedStudio CAN-Bus shield utilizes D13, and so does the [SD-card module][1] I use. And also Arduino Uno's LED_BUILTIN is 13. **Am I in danger of some sort of collision here?**

I have read [this question][2], but that one describes situation where both modules are on *a single shield.*

Why I am alerted: I can perform following sequence: turn the LED on, open file, write, close file, turn the LED off, no apparent problem here. But when I connect my CAN-Bus shield to merely read messages (i.e. no sending data to the shield, not on purpose) my car behaves funny as if I still somehow managed to send some rogue bytes to the shield. (Right side windows and mirror are dead, infotainment display shows dead splash screen, dashboard complains about "engine malfunction" and airbags...)

I wonder if by writing to the SD-card and possibly turning the LED on I didn't send some bytes to the shield. Do I need to somehow Select Slave?

  [1]: http://ebay.to/2lqdrsL
  [2]: https://electronics.stackexchange.com/questions/67212/how-to-avoid-sd-card-and-w1500-spi-mixup-on-the-ethernet-shield/67214#67214

body:
Yes you are in danger of a collision, how much danger I can't say, but the potential is there.

 1. You could stop using the LED on D13?
 2. Could you move the pins of your SD card reader, or get a different one that allows I2C or SPI interfacing?

I guess there is nothing that can be done to the CAN bus device, but if there is it might be a good idea to move its pins.


message:
I2C Wire.write function doesn't seem to work

Using the simplest code possible to test the library:

    #include <Wire.h>

    void setup()
    {

      Wire.begin(); // join i2c bus

      Wire.beginTransmission(44); // transmit to device #44 (0x2c)
                                  // device address is specified in datasheet

      Wire.write(0xA);             // sends value byte
      Wire.write(0xA);             // sends value byte
      Wire.write(0xA);             // sends value byte

      Wire.endTransmission();     // stop transmitting
    }

But my data (three test byte of 0xA) is not getting sent. See image. As you can see, I get start bit, address, and then the stop bit. No data. Where am I going wrong?

[![Scope Trace][1]][1]

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

body:
According to the captured communication `NACK` was received (confirmed in comments) and according to the `Wire` library `twi_stop` will be called (and sent) in this fault scenario.

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

    case TW_MT_SLA_NACK:  // address sent, nack received
      twi_error = TW_MT_SLA_NACK;
      twi_stop();
      break;


body:
It looks like you have code for an I2C master. Sending to a slave involves sending the slave address, and waiting for an ACK from the slave (that is, the addressed slave pulls the data bus low).

You can see that in a graphic from [my page about I2C](http://www.gammon.com.au/i2c):

[![I2C protocol][1]][1]

At the 100 µs mark you can see that the slave pulls SDA low, which is an ACK. Thus the master knows that the addressed slave exists. Without that, the slave is not there, and there is no point in sending any further data.

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


body:
OK, I figured out what was going on...

An example program that I downloaded to test the hardware was sending a "self address" command to the chip, which was causing the address to get set to 0x03 and I didn't notice this. This new address stays in memory. So, when I went back to test the library code, I was sending 0x00 (default from factory) instead of the new address (0x03). The NACK after the address byte should have been a clue, but hey, live and learn.

Thanks for all the responses. Hopefully my pain will help someone else.


message:
Open video file if sensor reaches certain threshold value

I am an ABSOLUTE beginner at Arduino and my first project I've proposed to my teacher is as follows: an Mq-2 smoke sensor will sense smoke and if the level of smoke reaches a certain value (only because I want the smoke to accumulate for aesthetics purposes) then a video file in whatever directory opens and plays. It seemed plausible at first, but as I search for pertinent info., I am faced with content and hobbyists whose instructions and "knowledge" are way out of my depth. Can anyone help me with this? If anyone knows a good website/tutorial videos/documents/books that a beginner like me should take to improve his programming and physical computing(?) skills, please let me know!

body:
What I'm thinking is that you could make a conditional statement. Below is a little a bit of pseudo code on how to possibly open said video from an SD card because there's no way Arduino would be able to store a video on it's own, let alone play good quality videos:

    int dangerLevel = 500 (or however the shield reads the smoke level)

    int smokeDetectorPin = A0

    setup:

    smokeDetected = analogRead(smokeDetectorPin)

    loop:

    if smokeDetected >= dangerLevel:

    open video from SD card directory or computer.

So in order to get a "video" from the SD card, you should check this [website](http://www.instructables.com/id/Streaming-video-from-SD-card-to-Nokia-LCD-with-Ard/step6/Playback-program-sketch-for-the-Arduino/). Like I mentioned before, this is really primitive and it's probably not what you're looking for.

I found something very interest about the Arduino that I never knew you could do before and using composite display from a TV. Interesting and you can find that info [here](http://playground.arduino.cc/Main/TVout).

And lastly, to get a video from your computer or laptop, there's really no easy way. However, I did find two solutions that might be able to do this. First of all, and this may sound ironic since we're on an Arduino Stackexchange, you could use a Raspberry Pi (and this is the easily solution I can think of) though I believe your instructor prefers if you use the Arduino instead. Second, and this took me forever to find on the internet, you could use a third party software called "Gobetwino" and you can check out what that does [here](http://www.mikmo.dk/gobetwino.html). I saw on [YouTube video](https://www.youtube.com/watch?v=zHCnCrifyyY) of a quick little demonstration of what it does. When the button is pressed, the video is played. That's conditional and you can do the same thing but for the smoke detector.


message:
Change conditioning in real time

I am currently writing a program that reads an output voltage from a capacitive moisture sensor and depending on the moisture content, it will water some plants accordingly. I would like to make it so that a user can change the condition in real time because different plants will require different amounts of water. This will give a little more freedom on how much water the user would prefer for their plant. This is the code I have so far:

    int solenoidPin = 4; //connected to Digital 4
    int moisturePin = A0; //connected to Analog A0

    void setup() {
      Serial.begin(9600);
      pinMode(solenoidPin, OUTPUT);
    }
    void loop() {
      int val;
      moisture = analogRead(moisturePin); //connect sensor to Analog A0
      Serial.println(val); //print the value to serial port
      delay(1000); //wait 1 second for next reading

      if (moisture <= 350) //if moisture is less than reading 350 {
      digitalWrite(solenoidPin, HIGH); //switch solenoid ON
      delay(600000) //water for ten minutes
      digitalWrite(solenoidPin, LOW); //switch solenoid OFF
      }
      else {
      digitalWrite(solenoidPin, LOW); //switch solenoid OFF
      }
    }

I am aware that there is a touch screen shield for the Arduino and I could possibly allow the user to interact what is going on. However, I'm just asking if it's possible to change the ``if (moisture <= 350)`` while the code is running and perhaps allowing the user to change that value. If so, then how? Could I use a touch screen shield or another shield that allows a user to change the condition?

body:
>       if (moisture <= 350) //if moisture is less than reading 350 {

That is wrong, because you have the brace `{` **after** the comment. You need it **before** the comment, eg.

     if (moisture <= 350) { //if moisture is less than reading 350

Or preferably in my opinion:

    if (moisture <= 350) //if moisture is less than reading 350
      {

---

> I'm just asking if it's possible to change the `if (moisture <= 350)`

Yes, of course. That's what variables are for. You could read a potentiometer, and the value from that could replace `350` in the code. You could use a simple LCD or LED display to show what the current reading is.

---

>    delay(600000) //water for ten minutes

Your problem here is that the sketch will be totally unresponsive (it would not react to your changing the moisture level) during the time you are watering. You might want to read [How to do multiple things at once](http://www.gammon.cm.au/blink) which shows how you can keep doing other things, while waiting for time to elapse.


message:
My Digispark board won't show up in Ports tab in Arduino IDE (OSX)

I bought a Digistump/Digispark board online and when i received it, I plugged it into my iMac to see if it works. I went to the apple in the top left corner and clicked "About this Mac". Then I clicked "System Report" and I went to the USB tab and it showed something connected as:

    "Vendor-Specific Device:"

I was glad that it showed up but when I went to the Arduino IDE it didn't show up in the ports tab. I downloaded the AVR pack and the driver (i'm pretty sure the driver should work, if there is a specific driver that will work could someone send me to it) I am really frustrated and mad because it seems like this always happens. If someone could help me that would be greatly appreciated! Thank You.

    Atmel 1624 tiny85

body:
I don't think it is supposed to. The Digispark briefly connects in "bootloader" mode, which you spotted as "Vendor-Specific Device:".

Then after 5 seconds it runs the loaded sketch. If your sketch doesn't create a USB port (eg. a keyboard) then it will disappear from the USB list.

See:

http://digistump.com/wiki/digispark/tutorials/connecting

You don't select the port, the core files automatically find the Digispark and program it. You have to plug in the Digispark when instructed, to activate the bootloader.