message:
Semantics of local PROGMEM

I want to create a class to better use strings in flash. At its core is the following

    template<size_t N>
    struct progstr
    {
        constexpr progstr(const char (&str)[N])
            : progstr(str, make_index_sequence<N> {}) {}

        template<size_t... Is>
        constexpr progstr(const char (&str)[N], index_sequence<Is...>)
            : _str{str[Is]...} {}

        constexpr operator const char*() const {
            return _str;
        }

        const char _str[N] PROGMEM;
    };

Where `make_index_sequence` and `index_sequence` are [the same][1] as those from `<utility>`.

The problem arises when I try to emulate `PSTR`

    template<size_t N>
    constexpr const char* pstr(const char (&str)[N])
    {
        return progstr<N>{str};  // huh?
    }

It even compiles. However

+ The returned pointer is "dangling", but it is pointing into flash memory. Will this work?

+ A `constexpr` function may be called with an array with runtime values, and that cannot possibly create the string in flash can it?

[1]: https://godbolt.org/g/41bkiQ

body:
I tested with 100 chars string

const char*

    Sketch uses 1566 bytes
    Global variables use 288 bytes

with F macro

    Sketch uses 1594 bytes
    Global variables use 188 bytes

progstr <101> ps(...

    Sketch uses 1618 bytes
    Global variables use 288 bytes

const char* ps = pstr("...

    Sketch uses 1502 bytes
    Global variables use 188 bytes

the pstr version string has errors at the end, when printed.

**sorry, the pstr function works only if previous sketch version put the string into flash memory. it is not in hex file.**


sender: user

message:
How to set the sampling frequency in Arduino without using a delay

I am reading an ECG signal using a [single lead heart rate monitor][1]. What I know is that when I use `delay(15)` it means that I am getting 66.67 readings in a second which corresponds to the sampling frequency. I want to set the sampling frequency to 250. This can be done by introducing `delay(4)`.

What I really need is to set the sampling frequency to 250 Hz without introducing a delay in the code because I am acquiring ECG data in real time. Also, I am sending the data to python for processing and the delay will affect the sampling frequency in the time domain analysis.

any detailed solution or code ??

PS. I am using Arduino UNO

Code:

    #define SERIAL_BUFFER_SIZE 8192
    #include <SoftwareSerial.h>
    unsigned long Time;
    void setup() {

      // initialize the serial communication:

      pinMode(10, INPUT); // Setup for leads off detection LO +
      pinMode(11, INPUT); // Setup for leads off detection LO -
      Serial.println("CLEARDATA"); //clears up

      Serial.println("RESETTIMER"); //resets timer to 0

      Serial.begin(115200);

    }

    void loop() {
      if((digitalRead(10) == 1)||(digitalRead(11) == 1)){
       Serial.println('!');
      //  continue;
      }
      else{
       /*
         // send the value of analog input 0:
         int idata = analogRead(A0);
      //  float data = (idata*3.3)/1023;
          Serial.println(idata);
    */
      int sensorValue = analogRead(A0);
      float voltage = sensorValue * (3.3/1023.0);
      Serial.println(voltage);
      }
      //Wait for a bit
        delay(4);
    }

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

sender: assistant

body:
Use the concept of blink without delay.

Instead of using delay() to set the timeout you use a timestamp and check `micros()` against that to see whether your interval has passed:

    const unsigned long READ_PERIOD = 4000;  // 4000 us: 250 Hz

    void loop() {
        static unsigned long lastRead;
        if (micros() - lastRead >= READ_PERIOD) {
            lastRead += READ_PERIOD;
            if (digitalRead(10) == 1 || digitalRead(11) == 1)
                Serial.println('!');
            else
                Serial.println(analogRead(A0) * (3.3/1024));
        }
    }


message:
Arduino UNO SPI Serial Clock (Pin 13 SCK) gives no output, but Blink Example (Pin 13 LED) works

I was attempting to use an SPI library and DAC device (Library AD57X4) for the first time, when I realized that the Arduino UNO Pin 13 was not outputting a clock signal (something I expected it to do).

Using a serial analyzer I can sample at 16MHz, yet nothing comes out of UNO Pin 13 except maybe a very occasional noise blip.  After no luck with the AD57X4 library, I wrote this simple program to try to get SPI clock signal on UNO Pin 13.  Setting UNO Pin 13 to OUTPUT makes no difference.

    #include <SPI.h>

    void setup() {
      //pinMode(13, OUTPUT);
      SPI.begin();

    }

    void loop() {
      SPI.transfer(0x00);
    }

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

I do get a signal on UNO Pin 11 (MOSI), frequency 381 kHz.  This signal is due to `SPI.transfer(0x00);` , as it disappears when the line is removed.  Although likely irrelevant to the question, I noticed some periodic 6us gaps every ~1ms on this UNO Pin 11 (MOSI) signal.

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

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

The Blink Example Works:

        // the setup function runs once when you press reset or power the board
    void setup() {
      // initialize digital pin LED_BUILTIN as an output.
      pinMode(LED_BUILTIN, OUTPUT);
    }

    // the loop function runs over and over again forever
    void loop() {
      digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);                       // wait for a second
      digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);                       // wait for a second
    }

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

I tried monitoring UNO ICSP header pin 3 (SCK), however there is no signal for either the SPI or Blink programs.

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

**UPDATE:**
I switched over to an Arduino NANO that I had around and was able to get this output.  I expected the clock to be high frequency and continuous for SPI.  The MOSI output is the same 381 kHz that I observed earlier.

[![enter image description here][6]][6]

[![enter image description here][7]][7]

    #include <SPI.h>

    void setup() {
      pinMode(13, OUTPUT);
      SPI.begin();

    }

    void loop() {
      SPI.transfer(0x00);
    }

**EDIT:**
Here is a schematic of my circuit.  I am using an [EVAL-AD5754R Evaluation Board][8] from Analog Devices.  Here is a link to the AD5754 [chip data sheet][9].  I'm providing 5V power through the J7 terminal (via the UNO), and supplying the SPI connections through the J8 header. The EVAL-AD5754R board works perfectly via USB and their software, but now I am transitioning to controlling it through Arduino/SPI.  As you can see I'm temporarily using a 12V battery for the analog voltage supply - this is until I build a regulated circuit.  J8 DGND pins are shown unconnected on the schematic below, but I've tried connecting one of them to the UNO's GND to no effect.

[![enter image description here][10]][10]

This is the configuration of the linkers which act to configure the eval board:
[![enter image description here][11]][11]

This is an annotated table describing J8 header connections (UNO <-> EVAL-AD5754R):
[![enter image description here][12]][12]

  [1]: https://i.stack.imgur.com/qt0To.png
  [2]: https://i.stack.imgur.com/7c46R.png
  [3]: https://i.stack.imgur.com/sUZxC.png
  [4]: https://i.stack.imgur.com/8dFNY.png
  [5]: https://i.stack.imgur.com/jl9TT.jpg
  [6]: https://i.stack.imgur.com/koDHo.png
  [7]: https://i.stack.imgur.com/rgt5P.jpg
  [8]: http://www.analog.com/media/en/technical-documentation/user-guides/EVAL-AD5754R.pdf
  [9]: http://www.analog.com/media/en/technical-documentation/data-sheets/AD5724R_5734R_5754R.pdf
  [10]: https://i.stack.imgur.com/9748j.png
  [11]: https://i.stack.imgur.com/G0wRL.png
  [12]: https://i.stack.imgur.com/NZDAI.png

body:
I can't reproduce that. Using your first test code:

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

    #include <SPI.h>

    void setup() {
      //pinMode(13, OUTPUT);
      SPI.begin();

    }

    void loop() {
      SPI.transfer(0x00);
    }

I get this on the logic analyzer:

[![Logic analyzer - SPI][1]][1]

Also on my scope on pin 13:

[![Scope capture - SPI][2]][2]

As expected, a 4 MHz signal with gaps between the bytes.

---

> I expected the clock to be high frequency and continuous for SPI.

No, you get the clock when data is being transmitted and not at other times.

>  Although likely irrelevant to the question, I noticed some periodic 6us gaps every ~1ms on this UNO Pin 10 (MOSI) signal.

That would be the Timer 0 interrupt kicking in (roughly every 1 ms) and thus interrupting your looping code for a few microseconds.

---

## Possible solution

Try enabling slave select (write LOW to pin 10). I think some versions of the logic analyzer ignore incoming data if the slave isn't selected.

In fact, pin 10 should be an output, otherwise the SPI hardware goes into slave mode. Some versions of the library might not set it to output.

  [1]: https://i.stack.imgur.com/J57zq.png
  [2]: https://i.stack.imgur.com/emGfN.png


message:
Control/Interacting with Android OS using Arduino board

I am new to arduino, and based on my search, it is possible to connect Android devices and Arduino board thru bluetooth module. But most solutions i found are either for controlling Arduino board using an Android app, or controlling Android app using Arduino board.

My question is, is there a way to control/interact with the Android OS on the phone using Arduino, thru whatever connection?

I am asking this because I am thinking of building a portable keyboard or touchscreen device for Android devices, and want to see if Arduino is a good platform for prototype.

body:
What you've seen is most usually a bluetooth module which has a "virtual COM port" service -- you connect to the bluetooth module and you can then send a data stream up and down through this COM port, just like you are able to do with a normal `Serial` port.

**If you want a bluetooth keyboard**:

What you *want* for seamless integration is a bluetooth module which natively exposes a "HID" (Human Interface Device) profile. Keyboard, mice and gamepads are examples of an HID.

There is a multitude of projects which use Arduino + Bluetooth HID module:

 * http://www.kobakant.at/DIY/?p=3310 uses an Arduino Pro Mini and and BlueSMiRF HID (from Sparkfun)
 * Evan Kale's video: https://www.youtube.com/watch?v=BBqsVKMYz1I (uses HC05 bluetooth module with altered firmware)
 * https://mitxela.com/projects/bluetooth_hid_gamepad
 * Bluefruit EZ-Key: https://www.adafruit.com/product/1535

When you are a beginner you should buy the more expensive modules which don't require you to do any firmware hacking. Adafruit's product might work for you. As the description page says, you can connect a microcontroller's UART TX to the modules RX pin to send arbitrary keystrokes. You can then add a keyboard matrix, or lots of buttons, or whatever you desire to that microcontroller to make it trigger the keypresses you want.

This should get you started on your own research.


message:
Need assistance with serial data between PC and Arduino Mega 2560

With help from a friend I have written a sketch for my Mega2560 that talks to a PC application via serial at 9600 baud.  The PC application send an S which instructs the mega to send variable values without any delimiters.  The PC application then creates a string from the data which is split to fill text boxes.  Some elements of these text boxes can then be changed and clicking a button makes the PC application build a string, prefixed by R# and using <> as delimiters.  It then tags an S on the end.  This string is then sent to the Mega, which as it detects the R and # reads the delimited data into a 43 element array. Once it reads the S it then runs the send function again to confirm the changes.

As a stand alone program this works -

I then added in functions for reading four Ds18B20's, four DHT11's an RTC and displaying this on a TFT.  These routines were added as separate contained voids and called in order from the main loop.  When testing the serial it nolonger works.  I either have to click on the get data button multiple times for it to read and display the info.  Sending updated information back gets lost in transit (I've used a com port sniffer and it shows data passing out to the mega).  Lastly, it's no longer accepting the updates when it does work - and having sent data back a second time it still reads the same as before the values were changed.  When the coms fails the mega seems to have locked up, so it's stuck in the comms section, presumably as one of the IF/Then conditions hasn't been met because it's run out of data.  But the routine wasn't changed from the standalone code which worked fine.

Hopefully this is as concise as you need but still has enough information to help diagnose the possible issue.  I've tried extending delays in the PC application to see if it was that which was the cause, but even setting them to 5 seconds it still errors as described

Thanks
Malcolm

Main loop from working standalone code

    void loop ()
     {

    loopcount = 0;

    // Serial.println ("in main loop ");   // to show then program is looping the main code
    // delay(3000);

     // your other 5seconds of code etc

     if(Serial.available()){             // test is S or R on comms

     int tbyte = Serial.read();

     if (tbyte == 'S'){
    //  Serial.println ("send data");      // S received so Send data
      transmit ();
    //   sendarray ();
       }

      if (tbyte == 'R'){                 // R received  so readstream of data
    //    Serial.println ("recive data");
       readstream ();
        }
      }
     // sendarray ();
     }

     // end of main loop

 Subroutines from the standalone code

    // Subroutines --------------------------------------------------

     void readstream ()  {

      while (loopcount < 2000){
        if(Serial.available() > 0){

    if  (serialFlag == 0) {

       inByte = Serial.read();

      if (inByte == 0X23 ){
        serialFlag = 1;
    //    Serial.println ("# receieved so delimited data follows  ");
      }
    }

      if  (serialFlag == 1) {
       processInput ();
        }
       }
      }
     }

    // ProcessNumber-----------------

    void processNumber (const long n)
     {
    // Serial.println (n);

     dataIn[i]  = n;

     //Serial.println (i);
    // Serial.print (dataIn[i]);

     i++;

    // Serial.println (i);

     if ( i >= 43) {
    //  Serial.println (" end of data....... return to main loop");
      serialFlag = 0;     // set flag back to zero
      i = 0;

     loopcount = 2222;   // stops the Serial While Loop, though better replaced by a timer
     }
     sendarray ();
     }

     // End of ProcessNumber-----------

     // ProcessInput--------------------

    void processInput ()
     {
     static long receivedNumber = 0;
     static boolean negative = false;

     byte c = Serial.read ();

     switch (c)
       {

       case endOfNumberDelimiter:
         if (negative)
           processNumber (- receivedNumber);
         else
           processNumber (receivedNumber);

       // fall through to start a new number
       case startOfNumberDelimiter:
         receivedNumber = 0;
         negative = false;
         break;

       case '0' ... '9':
         receivedNumber *= 10;
         receivedNumber += c - '0';
         break;

       case '-':
         negative = true;
         break;

       } // end of switch
     }

     // End of ProcessInput------------------

And the input to array

    void sendarray ()
    {
    daytemp1 = (dataIn[0]);
    daytemp1=daytemp1/10;
    daytemp2 = (dataIn[1]);
    daytemp2=daytemp2/10;
    daytemp3 = (dataIn[2]);
    daytemp3=daytemp3/10;
    daytemp4 = (dataIn[3]);
    daytemp4=daytemp4/10;

    <snip>

body:
I'm sorry, I know you are new, but this is not a very easy to understand question, please keep reading though, I am trying to help.  Your description of what you want your code to do is like trying to eat a dinner plate.  Remember no one reading this has the knowledge of the problem that you do and a diagram or three speak a million words.

If it is failing to compile you need to post the source code and the compilation error.  Without that information there is no point posting the question.  The information on what is wrong is there, unfortunately you haven't used Google's Klingon to English translator.  Seriously paste the compile errors into Google and you will get a stack of results, some of which will tell you what you have done wrong.

Your friend's code is not great.  If that really is the code (rather than a space enforced edit), then I suspect it won't compile either, because its not valid C++.  Also there are logic errors in it, you can make a number negative, but once you have you can't go positive.

**So, what can you do about it?**

Rule 1: You have to learn how to walk before running around the globe.  Part of your requirement is to read Q or S from the serial line.  So write a program of YOU OWN that does just that (I mean don't copy one of a web site/friend).

 - Write a program that reads the serial line.
 - When you press Q it prints "You pressed Q!"
 - When you press S it prints "You pressed S!"
 - When you press any other key it prints "You pressed something else"
 - What happens when you press s or q?

Then build up step by step, keep back ups of everything, because you will break it at some point.

Other rules, which will contradict rule 1, will be available once you have mastered number one :)

Good luck and if you get stuck again, please post here again

     (small example code + error messages + output + expectations) = good post


message:
ESP8266 MQTT client error

#include <PubSubClient.h>
    #include <ESP8266WiFi.h>

    //EDIT THESE LINES TO MATCH YOUR SETUP
    #define MQTT_SERVER "YOUR.MQTT.SERVER.IP"
    const char* ssid = "YOUR_SSID";
    const char* password = "YOUR_PASSWORD";

    //LED on ESP8266 GPIO2
    const int lightPin = 2;

    char* lightTopic = "/test/light1";

    WiFiClient wifiClient;
    PubSubClient client(MQTT_SERVER, 1883, callback, wifiClient);

    void setup() {
     //initialize the light as an output and set to LOW (off)
     pinMode(lightPin, OUTPUT);
     digitalWrite(lightPin, LOW);

     //start the serial line for debugging
     Serial.begin(115200);
     delay(100);

     //start wifi subsystem
     WiFi.begin(ssid, password);
     //attempt to connect to the WIFI network and then connect to the MQTT server
     reconnect();

     //wait a bit before starting the main loop
         delay(2000);
    }

    void loop(){

     //reconnect if connection is lost
     if (!client.connected() && WiFi.status() == 3) {reconnect();}

     //maintain MQTT connection
     client.loop();

     //MUST delay to allow ESP8266 WIFI functions to run
     delay(10);
    }

    void callback(char* topic, byte* payload, unsigned int length) {

     //convert topic to string to make it easier to work with
     String topicStr = topic;

     //Print out some debugging info
     Serial.println("Callback update.");
     Serial.print("Topic: ");
     Serial.println(topicStr);

     //turn the light on if the payload is '1' and publish to the MQTT server a confirmation message
     if(payload[0] == '1'){
      digitalWrite(lightPin, HIGH);
      client.publish("/test/confirm", "Light On");

     }

     //turn the light off if the payload is '0' and publish to the MQTT server a confirmation message
     else if (payload[0] == '0'){
      digitalWrite(lightPin, LOW);
      client.publish("/test/confirm", "Light Off");
     }

    }

    void reconnect() {

     //attempt to connect to the wifi if connection is lost
     if(WiFi.status() != WL_CONNECTED){
      //debug printing
      Serial.print("Connecting to ");
      Serial.println(ssid);

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

      //print out some more debug once connected
      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
     }

     //make sure we are connected to WIFI before attemping to reconnect to MQTT
     if(WiFi.status() == WL_CONNECTED){
     // Loop until we're reconnected to the MQTT server
      while (!client.connected()) {
       Serial.print("Attempting MQTT connection...");

       // Generate client name based on MAC address and last 8 bits of microsecond counter
       String clientName;
       clientName += "esp8266-";
       uint8_t mac[6];
       WiFi.macAddress(mac);
       clientName += macToStr(mac);

       //if connected, subscribe to the topic(s) we want to be notified about
       if (client.connect((char*) clientName.c_str())) {
        Serial.print("\tMTQQ Connected");
        client.subscribe(lightTopic);
       }

       //otherwise print failed for debugging
       else{Serial.println("\tFailed."); abort();}
      }
     }
    }

    //generate unique name from MAC addr
    String macToStr(const uint8_t* mac){

      String result;

      for (int i = 0; i < 6; ++i) {
        result += String(mac[i], 16);

        if (i < 5){
          result += ':';
        }
      }

      return result;
    }

The error is 'callback' was not declared in this scope

body:
In C++, you can't use or reference a function before it is declared, that's not Arduino specific, it's how C++ "works"

Moving the `callback` function above the `client` declaration won't help, because the `callback` function references `client`

The only solution is to declare the `callback` function before it is referenced in `client` initialisation, but have the definition of `callback` after

i.e. add one line

    WiFiClient wifiClient;
    void callback(char* topic, byte* payload, unsigned int length); // add this in your code
    PubSubClient client(MQTT_SERVER, 1883, callback, wifiClient);

Nothing else needs to be changed

Please excuse some terminology mistakes above - it's been a long time since I learned C/C++, while I know how to use it, I don't always know how to describe it :p

> apprently there's some bug in the toolchain - see the comments in the question. However, this is still a valid solution, I guess it works around the bug


message:
Can you make it so, when your phone connects to the Hc-05 on a Arduino, a variable changes?

So whenever my phone gets close, and it connects to the Hc-05, the Arduino changes a variable? I want to avoid the use of apps, where the user has to do anything after first time connecting. The project is an automatic door opener, wherein the user for whatever reason can't use their hands, like if they have groceries in their hands.

Thank you for your time

body:
Detecting successful connection with HC-05
------------------------------------------

The HC-05 can be configured to do what you are after.

Search for "POLAR" in the [AT set documentation][1].

    AT+POLAR=0,1
should be what you need as per their examples.
Hook up **PI09** to your arduino and wait for it to go HIGH.
You may even want to wake up your arduino with an hardware interrupt using that signal.

Depending on your package, this may require soldering to the HC-05 module.
The [datasheet][2] features a pinout in that case. Be sure to checkout the manual of your breakout board first.

  [1]: http://elecfreaks.com/store/download/datasheet/Bluetooth/HC-0305 serail module AT commamd set 201104 revised.pdf
  [2]: https://cdn.makezine.com/uploads/2014/03/hc_hc-05-user-instructions-bluetooth.pdf


message:
Difference between Ciao REST server and Ciao REST connector and when to use each or the other

I'm reading the [Ciao library][1] and can't make out the difference between [Ciao REST server][2] and [Ciao REST connector][3].

When is the connector suitable and at what point do I need the server?

This is a graphic of what im thinking to do:

[![my aduino ciao setup][4]][4]

  [1]: https://www.arduino.cc/en/Reference/Ciao
  [2]: https://www.arduino.cc/en/Reference/CiaoRestServer
  [3]: https://www.arduino.cc/en/Reference/CiaoRestConnector
  [4]: https://i.stack.imgur.com/NZn90.png

body:
I don't know about "Ciao" but generally a rest server answers requests from a client that is connecting via a rest connector.
You client will use POST, GET, PUT, etc. to ask the server to provide a service.  This could be as simple as "GET .\index.htm" or more likely posting information to be stored in a database.

The server will sit waiting for these requests and will have handling routines for each specific request and might supply a response.


message:
Can someone help me with my arduino and relay and switch?

This is my code. What i want to do is activate the relay when switchInNcPin is activate. I am using a switch (micro switch). It has COM NC and NO pins. Can you tell me what is wrong with my code?
PROBLEM:
The relay keeps clicking ON and OFF even though it is meant to wait 5000ms, activate, wait 3000ms, deactivate only once. Can you look at my code and help me?

[![ARDUINO CODE][1]][1]

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

body:
Maybe it's not the only problem, but at least:

    int val = ...

and

    if (val == "FLUSH")

do not match.

I assume you mean a digit here (0 or 9 to flush)?

Also, you should put your circuit in your question. A reason because of the 'flipping' is that your switch is not pulled down, and it results in undefined behavior.

Another thing you could add is debouncing, when a switch is clicked, it results in multiple 0/1 and 1/0 transitions (although your delay might help too).


message:
GSM library_ all examples ar working except GPRS?

i am using arduino uno and sim808. i connected the sim808 to pins 2,3 on arduino uno and used GSM library. i tested all examples: make and receive a call or messages. the part of GPRS initialization is not working after many tries in changing APN and pin number.
i want to use the arduino as a webserver exactly as the example includded in the library.
any one can help?
thanks,
https://www.arduino.cc/en/Reference/GSM

body: I had the same problem I solved it by moving the jumper wires on the shield(if you are using one) to SW serial. if that doesn't work try testing it with AT commands


message:
Problems encountered when trying to program Arduino UNO via esp8266 with ESP-Link

Basically my project requires to program Arduino Board wirelessly and I have found ESP-link which seems to match my purpose.

I tried to follow the instructions in documentations on the github page https://github.com/jeelabs/esp-link I am using Arduino UNO and ESP8266-01 by the way.

Flashing ESP-link into ESP8266 was successful. I followed the configuration page and successfully connect the ESP8266 to an MQTT Server. I connect my Arduino UNO to computer via USB Serial. Connected UNO to ESP8266 using the default settings (TX - TX, RX - RX, GPIO0 - RST). When I checked the Microcontroller Console page, I could send and received messages to/from UNO as well as resetting the UNO (I programmed blink sketch into my UNO, so I can see every time I reset it, it works)

However, the next step is not that successful. I tried to program UNO via ESP8266 but it does not work out quite well. There are several methods posted on the documentation https://github.com/jeelabs/esp-link/blob/master/UC-FLASHING.md and I have tried them to some extent.

1.Use Avrdude to program. Basically I copied the command when Arduino IDE programmed UNO using avrdude, and change the port to net:{localIP_of_ESP8266}:23
By the way I tested the code by set the port to local Serial port and it works
I get the error and below is what cmd shows:

    avrdude.exe: Version 6.3, compiled on Feb 17 2016 at 09:25:53
                 Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
                 Copyright (c) 2007-2014 Joerg Wunsch

                 System wide configuration file is "C:\Users\ktz001\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf"

                 Using Port                    : net:192.168.10.97:23
                 Using Programmer              : arduino
                 Overriding Baud Rate          : 115200
    avrdude.exe: ser_drain(): read error: The parameter is incorrect

    avrdude.exe: ser_drain(): read error: The parameter is incorrect

    avrdude.exe: ser_drain(): read error: The parameter is incorrect

    avrdude.exe: stk500_recv(): programmer is not responding
    avrdude.exe: stk500_getsync() attempt 1 of 10: not in sync: resp=0xa4
    avrdude.exe: stk500_recv(): programmer is not responding
    avrdude.exe: stk500_getsync() attempt 2 of 10: not in sync: resp=0xa4
    avrdude.exe: stk500_recv(): programmer is not responding
    avrdude.exe: stk500_getsync() attempt 3 of 10: not in sync: resp=0xa4
    avrdude.exe: stk500_recv(): programmer is not responding
    avrdude.exe: stk500_getsync() attempt 4 of 10: not in sync: resp=0xa4
    avrdude.exe: stk500_recv(): programmer is not responding
    avrdude.exe: stk500_getsync() attempt 5 of 10: not in sync: resp=0xa4
    avrdude.exe: stk500_recv(): programmer is not responding
    avrdude.exe: stk500_getsync() attempt 6 of 10: not in sync: resp=0xa4
    avrdude.exe: stk500_recv(): programmer is not responding
    avrdude.exe: stk500_getsync() attempt 7 of 10: not in sync: resp=0xa4
    avrdude.exe: stk500_recv(): programmer is not responding
    avrdude.exe: stk500_getsync() attempt 8 of 10: not in sync: resp=0xa4
    avrdude.exe: stk500_recv(): programmer is not responding
    avrdude.exe: stk500_getsync() attempt 9 of 10: not in sync: resp=0xa4
    avrdude.exe: stk500_recv(): programmer is not responding
    avrdude.exe: stk500_getsync() attempt 10 of 10: not in sync: resp=0xa4
    avrdude.exe: ser_drain(): read error: The parameter is incorrect

    avrdude.exe done.  Thank you.

2. Then I tried the post http method. Basically I sent a post request to http://{IP_of_ESP8266}/pgm/sync     in my case:

POST http://192.168.10.97/pgm/sync

I get 204 OK as response
Then I tried:

GET http://192.168.10.97/pgm/sync

It returns "sync abandoned after 8 attempts"
So I am stuck again

3. I tried also a small tool called avr-link https://gitlab.com/bc547-playground/avr-link
Someone used it to program a pro mini via esp8266-01 which I think is close enough to my situation. I ran it on the powershell (I am using Windos 10 btw)
The result is

>     PS C:\> .\avr-link.exe flash --esp 192.168.10.97 --file C:/Blink.ino.hex
>     AVR reset initiated...waiting for SYNC status
>     .
>     .
>     .
>     .
>     .
>     .
>     .
>     .
>     .
>     .
>     .
>     .
>     .
>     .
>     .
>     FATAL ERROR: Unexpected response:
>     00000000  73 79 6e 63 20 61 62 61  6e 64 6f 6e 65 64 20 61  |sync abandoned a|
>     00000010  66 74 65 72 20 38 20 61  74 74 65 6d 70 74 73     |fter 8 attempts|

4. using avrflash script. I am not sure how to run it in Windows OS so I did not use the script. If anyone could tell me about this, I appreciate it as well.

So to conclude, the problem seems to happen in getting sync after resetting the UNO (Although I am not 100% sure what does it mean - I am not familiar with the hardware process when flashing a UNO)
There is a paragraph actually in documentation suggesting the problem. Here is the quote:

> If you are having trouble with the built-in programmer and see something like this:
>
>  ./avrflash 192.168.3.104 blink.hex Error checking sync: FAILED to SYNC: abandoned after timeout, got:
> :\xF/\x00\xCj\xCz\xCJ\xCZ\xC\xAÜ\xC\xAä\xC\xAÜ\xC\xAä\xC\xBì\xC\xBô\xC\xBì\xC\xBô\xC\xAÜ\xC\xAä\xC
>
> the most likely cause is a baud rate mismatch and/or a bad connection
> from the esp8266 to the AVRs reset line. The baud rate used by
> esp-link is set on the uC Console web page and, as mentioned above, it
> will automatically try 9600, 57600, and 115200 as well. The above
> garbage characters are most likely due to optiboot timing out and
> starting the sketch and then the sketch sending data at a different
> baud rate than configured into esp-link. Note that sketches don't
> necessarily use the same baud rate as optiboot, so you may have the
> correct baud rate configured but reset isn't functioning, or reset may
> be functioning but the baud rate may be incorrect.

I tried to change the baud rate (both in command and microController Console page) but it still does not work. And in Arduino IDE it programs the board in 115200 so I should be okay with this baud rate imo, but anyway it did not work even when I change it.
As for the reset connection, I could reset the UNO by pressing reset in the Microcrontroller Console page so It shouldn't be the problem (and I don't know how to change it anyway).

Thank you for your patience reading through all this crap..
So what do you think the problem is? Any suggestion would help :D

body:
I tested it some weeks ago again after a year. The default upload from IDE should work, but mDNS in esp-link has now a bug and propagates the service only in AP mode so in STA mode the IDE doesn't show the network port.

from command line you can upload OTA with arduinoOTA tool used by IDE

example:

> /home/duro/.arduino15/packages/arduino/tools/arduinoOTA/1.1.1/bin/arduinoOTA
> -address 192.168.1.104 -port 80 -sketch /tmp/arduino_build_89762/Blink.ino.hex -upload /pgm/upload -sync
> /pgm/sync -reset /log/reset -sync_exp 204:SYNC

If the mdns bug was fixed, for upload from IDE some settings must be added to board.txt

    uno.upload.network.endpoint_upload=/pgm/upload
    uno.upload.network.endpoint_sync=/pgm/sync
    uno.upload.network.sync_return=204:SYNC
    uno.upload.network.endpoint_reset=/log/reset
    uno.upload.network.port=80

Uno WiFi uses an old version of esp-link so the settings and [tutorial][1] apply

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

  [1]: https://www.arduino.cc/en/Guide/ArduinoUnoWiFi#toc7
  [2]: https://i.stack.imgur.com/O9G4e.png


body:
I didn't test the avrdude network upload with esp-link. I used it with esp8266 AVRISP library. I configured the Arduino toolchain for network upload in platform.txt.

> tools.avrdude.upload.network_pattern="{cmd.path}" "-C{config.path}"
> -p{build.mcu} -c{upload.protocol} "-Pnet:{serial.port}:328" "-Uflash:w:{build.path}/{build.project_name}.hex:i"

Warning: the use case in my other answer uses the original setting of tools.avrdude.upload.network_pattern


message:
How do I turn lights on & off manually along with home automation?

Need some help regarding HomeAutomation

I was doing my room automate via Arduino with the help of relay , but a little problem I am facing,that when I switched on the light via relay then I cannot turn it off via switch board manually ,the switch is now useless & I have tried two way switch but it's not a better solution.
So please can anyone tell me how to solve this problem so that I can turn lights on manually & automatic too
Thanks

body:
You would need to create something like in the picture, one switch will be the relay.
[![hotel switch][1]][1]

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


message:
Does the StringObject.reserve() function prevent memory fragmentation/leaks?

I'm currently writing and testing a professional Arduino application, I'm aware of the dangers of using the String class, so I began to implement C-style strings in some places, but it's just way harder using them to receive data from a Software Serial port that's variable in size and needs some manipulation.

I've upgraded from an Arduino Uno to a Leonardo so my current minimum SRAM usage is 1325 bytes (51%)

Here's the relevant part of my code:

    String serialContents;
    char emailChar[SIZEOF_ARRAY][SIZEOF_CHAR];

    void setup(){
      serialContents.reserve(70);
      SerialOne.begin(9600);
    }

    void loop{

      if (SerialOne.available() > 0) //something is there to be read
      {
        serialContents = SerialOne.readStringUntil('\n'); //make a string of the characters coming on serial
      }

      if (serialContents.length() >= 60)
      {
       serialContents = ""; //ignore serial data
      }
     else{
      serialContents = cutString(serialContents); //some String manipulation, no adding only cutting
      serialContents.replace("@", "@");
      serialContents.toCharArray(emailChar[count], 31);
      serialContents = ""; //String reset
    }

So my question is, does something like this make my code unstable? Does the
*reserve()* function help at all?

Edit: Here's the cutString() function

    String cutString(String request) {

      int points = request.indexOf(':');

      if (request.substring(0, points) == "CHECKOUT")
      {
        modoPedido[count] = 'o'; //char array
      }
      else if (request.substring(0, points) == "CHECKIN")
      {
        modoPedido[count] = 'i';
      }

      request = request.substring(points + 1);

      return request;
    }

body:
Reserving space will *help* reduce memory fragmentation, but much of what else you are doing is swamping that small improvement you have made.

The biggest area of concern is your `cutString` function, which you have omitted from your code above.  Passing a `String` as a parameter, modifying it, and then returning it again, ends up in new `String` objects being created and destroyed multiple times, which will make a mess of your heap.

Instead you should pass a String object by reference, and modify that object in-place. No need to return anything.

    void cutString(String &theString) {
        // Modify theString here.
    }

Of course, what you do in `cutString` could cause more problems - you should include that function in your code above so we can check it out.


message:
Wemos mini pro switch power from servo with mosfet bs170

I got a servo connected to a wemos/arduino with a capacitor(470uf). Before I didn`t use a cap.

Now with the cap the device use to much power while sleeping(capacitor on the servo). I want to switch off the power to the servo with a MOSFET. I tried this with a BS170 N channel MOSFET. There is a youtube movie with the same settings except for the mainboard. They use an Arduino uno instead a wemos.

When I test the circuit with a led everything is working. When I use a servo instead a led, nothing happen. There is a little sound from the servo(I think not enough voltage).

When I check the voltage without anything hooked on the drain of the mosfet the output is perfect(5V). If I connect a led or a servo the voltage will drop to 3v.

Wemos mini pro has 3.3v output on the gpio pins.

Can someone explain me what I doing wrong? I saw and read some articles about Mosfet. I think it`s not clear enough for me.

[![Wemos with servo and mosfet][1]][1]

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

body:
My supposition:

The MOSFET's R(DSON) is too high and causing a large voltage drop.

A servo uses more current than a little LED.  That current passing through the MOSFET, with an R(DSON) of potentially up to 5Ω, reduces the voltage available to the servo, causing it to not work. Further more, ground for the servo is raised up above the real ground level adding an offset into the logic levels that could cause communication issues.

Suggestion: Pick a MOSFET with a lower R(DSON) (ideally measured in the milli-ohms), and a lower V(GS) threshold (something around 1-2V max would be good).


message:
Why do we need a transistor with a dc motor while we don't need one with a servo motor?

I was wondering why do we need to attach a transistor as we don't need one while we connect the Arduino with the servo motors. I am using mini servos.

body: Because a servo contains a driver circuit that controls the motor portion, whereas a motor doesn't. The transistor is the (simplistic) driver circuit for the motor.


body:
A servo typically has 3 wires: Power, Ground, and Signal

Inside the servo are a bit of electronics that read the input signal duty cycle, the absolute position of the horn, and power the motor in forward or reverse accordingly. There are transistors inside the servo housing to handle the high current of the motor.

A standalone motor doesn't have any other control electronics that separate power from control inputs.

**EDIT:**

Just to clarify: the signal wire for the Servo doesn't carry any significant power. The IO pins on the Arduino should not be asked to provide more than 40mA of current, and the PWM signal to the servo falls under that current limit.

But to operate a motor, or other device which draws significant operating power, it (the motor) asks for much more than 40mA of current, which can burn out the IO pin and damage it forever. This is why a transistor or other "switch" is necessary: the device which switches the high-current on and off can itself be operated by a very low current.


message:
Using digital pins 0/1 on Arduino Due when writing/reading over serialUSB port

I am aware that you cannot use pins 0 and 1 as digital pinouts when communicating over serial via serial.print(), but what if you are using the native port on the due with serialUSB.write()?

Thanks

body: Yes, you can use 0/1 while using the native USB. The two are completely separate.


message:
Does millis() work inside a function?

So I know that millis() doesn't work how it's suppose to if you use it in an interrupt but lets say we have a code that looks like below, will millis() work properly or how it behaves in an interrupt? Do I need to use the delay() instead of millis() when I'm outside of void loop() ?

To clarify, I understand how millis() behaves in an interrupt and why delay() doesn't work in an interrupt.

    const int ledPin =  LED_BUILTIN;// the number of the LED pin

    // Variables will change:
    int ledState = LOW;             // ledState used to set the LED

    // Generally, you should use "unsigned long" for variables that hold time
    // The value will quickly become too large for an int to store
    unsigned long previousMillis = 0;        // will store last time LED was updated

    // constants won't change:
    const long interval = 1000;

    void setup() {
     pinMode(ledPin, OUTPUT);
    }
    void loop(){
    blink();
    }
    void blink(){
      unsigned long currentMillis = millis();

      if (currentMillis - previousMillis >= interval) {
        // save the last time you blinked the LED
        previousMillis = currentMillis;

        // if the LED is off turn it on and vice-versa:
        if (ledState == LOW) {
          ledState = HIGH;
        } else {
          ledState = LOW;
        }

        // set the LED with the ledState of the variable:
        digitalWrite(ledPin, ledState);
      }
    }

body:
Millis is driven by an interrupt. The reason it doesn't "work" from inside an interrupt is that you can't have two interrupts running at the same time. So when your interrupt is running the interrupt that makes millis count can't run.

Millis does work in an interrupt as long as all you want is to record a single point in time. If you do anything that relies on millis changing within the lifetime of the interrupt it will break. That is why delay is bad in interrupts.

So from that you can see that it's only when in an interrupt that things can go awry. Everywhere else, as long as interrupts are enabled, both millis and delay work fine.

After all, loop is just a function called by main, and main is just a function called by _startup... Etc...


message:
ESP8266 + DHT11 AWS IOT Thing not updating thing shadow - was working before

I was able to get this working - https://www.youtube.com/watch?v=8hpro1olRK0 - send an SMS and email of temperature and humidity data from AWS IOT using esp8266 + dht11 but all of a sudden it stopped updating the shadow.

Here is the code
<!-- language-all: lang-cpp -->

    #include <ESP8266WiFi.h>
    #include <DHT11.h>
    #include <AmazonIOTClient.h>
    #include <ESP8266AWSImplementations.h>

    Esp8266HttpClient httpClient;
    Esp8266DateTimeProvider dateTimeProvider;

    AmazonIOTClient iotClient;
    ActionError actionError;

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

    // Pin 2 will be used to read sensor data
    int pin = 2;

    // Initializing the sensor
    DHT11 dht11(pin);

    //Function to convert Celsius to Fahrenheit
    double Fahrenheit(double celsius) {
      return ((celsius * 9 / 5) + 32);
    }

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

      // Connecting to Wi-Fi
      WiFi.mode(WIFI_STA);
      Serial.println();
      Serial.println();
      Serial.println("Connecting to ");
      Serial.println(ssid);

      WiFi.begin(ssid, password);

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

      iotClient.setAWSRegion("us-west-2");
      iotClient.setAWSEndpoint("amazonaws.com");
      iotClient.setAWSDomain("al1x5kb4rzh0x.iot.us-west-2.amazonaws.com");
      iotClient.setAWSPath("$aws/things/esp8266/shadow/update/accepted");
      iotClient.setAWSKeyID("AKIAJJQ6ASLIDIPBE4PQ");
      iotClient.setAWSSecretKey("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");
      iotClient.setHttpClient(&httpClient);
      iotClient.setDateTimeProvider(&dateTimeProvider);
    }

    void loop() {
      int err;
      float temp, humi;

    //Reading the sensor data
      if ((err = dht11.read(humi, temp)) == 0) {
        Serial.print(" temperature:");
        Serial.print(temp);
        Serial.print(" humidity:");
        Serial.print(humi);
        Serial.println();
      } else {
        Serial.println();
        Serial.print(" Error No :");
        Serial.print(err);
        Serial.println();

      }
    // Converting the float data to char arrays
      char sTemp[10], sHumi[10];
      dtostrf(humi, 6, 2, sHumi);
      dtostrf(temp, 6, 2, sTemp);

    // Creating the thing shadow to be sent to aws iot
      char shadow[100];
      strcpy(shadow, "{\"state\":{\"reported\": {\"Humidity\":");
      strcat(shadow, sHumi);
      strcat(shadow, ", \"Temperature\":");
      strcat(shadow, sTemp);
      strcat(shadow, "}}}");
      Serial.print(shadow);

      char* result = iotClient.update_shadow(shadow, actionError);
      Serial.print(result);

      delay(60000);
    }

Output as expected

    Connecting to
    NETGEAR53
    .........
    WiFi connected
     temperature:31.00 humidity:32.00
    {"state":{"reported": {"Humidity": 32.00, "Temperature": 31.00}}}al1x5kb4rzh0x.iot.us-west-2.amazonaws.com
    443
    POST $aws/things/esp8266/shadow/update/accepted HTTP/1.1
    Content-Type: application/json
    Connection: close
    Content-Length: 65
    Host: al1x5kb4rzh0x.iot.us-west-2.amazonaws.com
    x-amz-content-sha256: 923ed1ae613a9e14b45e4d080b092daf5cf61118041dc5225956299d5b0f8d49
    x-amz-date: 20180323T034259Z
    Authorization: AWS4-HMAC-SHA256 Credential=AKIAJJQ6ASLIDIPBE4PQ/20180323/us-west-2/iotdata/aws4_request,SignedHeaders=content-type;host;x-amz-content-sha256;x-amz-date,Signature=a10f0969043e609743412478567c10290b8c000185f2824e4a9cf07bb96cf279

    {"state":{"reported": {"Humidity": 32.00, "Temperature": 31.00}}}

body:
I was facing a similar problem: trying to update a thing's shadow on AWS IoT with no success. After some research, I found out that I was using an **outdated library**. In [this question][1] they advise to use *heskew*'s `aws-sdk-arduino`, on `iot-get-shadow-and-cleanup` branch:

https://github.com/heskew/aws-sdk-arduino/tree/iot-get-shadow-and-cleanup.

Additionally, I think you have a little error on your code. As far as I know, `AWSPath`, it should look like:

    iotClient.setAWSPath("/things/esp8266/shadow");

At least that works for me, and they use it this way on [this video][2].

That's all I can tell... I am learning at this moment as well.
Hope it helps!!

  [1]: https://stackoverflow.com/questions/40378582/connecting-esp8266-to-aws-iot#40519144
  [2]: https://www.youtube.com/watch?v=WJuXv5usXcY


body:
Just Change the Aws topic :
it should be  $aws/things/esp8266/shadow/update

and you have to add the certificate path also


message:
Sleep power down mode with change interrupt

I want to use to use an IR sensor as an interrupt to wake up my Arduino Uno R3 from the deep sleep power mode and then go back to sleep after changing the state of the relay.

Lets say if I press a button on the remote and the relay is on LOW mode, the relay is turned to HIGH mode and vice versa.

    #include <avr/interrupt.h>
    #include <avr/sleep.h>
    #include <IRremote.h>

    /* Sleep Demo
    ------------

    int relayPin = 8;            // LED connected to digital pin 13
    int irPin = 2;            // active LOW, ground this pin momentary to wake up
    int sleepStatus = 0;        // variable to store a request for sleep
    volatile byte state = LOW;

    IRrecv irrecv(irPin);
    decode_results results;

    void setup()
    {
      pinMode(relayPin, OUTPUT);         // sets the digital pin as output
      pinMode(irPin, INPUT);
      irrecv.enableIRIn(); // Start the receiver

      /* Now is time to enable a interrupt. In the function call
         attachInterrupt(A, B, C)
         A   can be either 0 or 1 for interrupts on pin 2 or 3.

         B   Name of a function you want to execute while in interrupt A.

         C   Trigger mode of the interrupt pin. can be:
                     LOW        a low level trigger
                     CHANGE     a change in level trigger
                     RISING     a rising edge of a level trigger
                     FALLING    a falling edge of a level trigger

         In all but the IDLE sleep modes only LOW can be used.
      */

      attachInterrupt(0, wakeUpNow, CHANGE); // use interrupt 0 (pin 2) and run function
      // wakeUpNow when pin 2 gets LOW
    }

    void sleepNow()         // here we put the arduino to sleep
    {
      /* Now is the time to set the sleep mode. In the Atmega8 datasheet
         http://www.atmel.com/dyn/resources/prod_documents/doc2486.pdf on page 35
         there is a list of sleep modes which explains which clocks and
         wake up sources are available in which sleep modus.

         In the avr/sleep.h file, the call names of these sleep modus are to be found:

         The 5 different modes are:
             SLEEP_MODE_IDLE         -the least power savings
             SLEEP_MODE_ADC
             SLEEP_MODE_PWR_SAVE
             SLEEP_MODE_STANDBY
             SLEEP_MODE_PWR_DOWN     -the most power savings

         For now, we want as much power savings as possible,
         so we choose the according sleep modus: SLEEP_MODE_PWR_DOWN

      */
      set_sleep_mode(SLEEP_MODE_IDLE);   // sleep mode is set here

      sleep_enable();              // enables the sleep bit in the mcucr register
      // so sleep is possible. just a safety pin

      /* Now is time to enable a interrupt. we do it here so an
         accidentally pushed interrupt button doesn't interrupt
         our running program. if you want to be able to run
         interrupt code besides the sleep function, place it in
         setup() for example.

         In the function call attachInterrupt(A, B, C)
         A   can be either 0 or 1 for interrupts on pin 2 or 3.

         B   Name of a function you want to execute at interrupt for A.

         C   Trigger mode of the interrupt pin. can be:
                     LOW        a low level triggers
                     CHANGE     a change in level triggers
                     RISING     a rising edge of a level triggers
                     FALLING    a falling edge of a level triggers

         In all but the IDLE sleep modes only LOW can be used.
      */

      attachInterrupt(0, wakeUpNow, CHANGE); // use interrupt 0 (pin 2) and run function
      // wakeUpNow when pin 2 gets LOW

      sleep_mode();                // here the device is actually put to sleep!!
      //

      sleep_disable();             // first thing after waking from sleep:
      // disable sleep...
      detachInterrupt(0);          // disables interrupt 0 on pin 2 so the
      // wakeUpNow code will not be executed
      // during normal running time.
      delay(1000);                 // wat 2 sec. so humans can notice the
      // interrupt.
      // LED to show the interrupt is handled
    }

    void wakeUpNow()        // here the interrupt is handled after wakeup
    {
      //execute code here after wake-up before returning to the loop() function
      // timers and code using timers (serial.print and more...) will not work here.
      if (irrecv.decode(&results)) {
        if (results.value == 0xff629d) {
          state = !state;
          digitalWrite(relayPin, state);
        }
      }
    }

    void loop()
    {

      sleepNow();                      // sleep function called here
    }

The Arduino never seems to wake up from sleep when I use the CHANGE interrupt. But if I use with the IDLE sleep mode, it is working.

Can somebody please help me how to fix this ?
Also will this code work with an Arduino Pro Mini or an ATTiny45?

body:
> The Arduino never seems to wake up from sleep when I use the CHANGE interrupt.

>       attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function

That's not a CHANGE interrupt, it's a LOW interrupt. Please post code that supports what you say in the question.

---

>     void wakeUpNow()        // here the interrupt is handled after wakeup
    {
      //execute code here after wake-up before returning to the loop() function
      // timers and code using timers (serial.print and more...) will not work here.
      if (irrecv.decode(&results)) {
        if (results.value == 0xff629d) {
          Serial.println("UP");
          state = !state;
          digitalWrite(relayPin, state);
        }
      }
    }

**Don't** do serial prints inside an ISR. In particular, a LOW interrupt keeps being called continuously while the interrupt pin is low.

> // timers and code using timers (serial.print and more...) will not work here

You *even have a comment* saying that the code won't work, yet you posted it in your question.


body:
You actually don't need to to worry about interrupts _at all_ for this
project. The IRremote library is itself based on a timer interrupt. As
soon as you `irrecv.enableIRIn()`, you start receiving a continuous
stream of interrupts... in addition to the timer interrupt initially set
up by the Arduino core.

If you want to save some power, you can call `sleep_mode()` once in your
loop. That's it. No need to `sleep_enable()` or `sleep_disable()`, as
these are already taken care of by `sleep_mode()`. No need to
`set_sleep_mode()` either, as the default sleep mode (IDLE) is the only
one that is appropriate for you. No need to `attachInterrupt()`, as you
will be waken up by these timer interrupts anyway.

Removing all the cruft, your posted code would become:

    #include <avr/sleep.h>
    #include <IRremote.h>

    const int relayPin = 8;
    const int irPin = 2;
    IRrecv irrecv(irPin);

    void setup()
    {
        pinMode(relayPin, OUTPUT);
        pinMode(irPin, INPUT);
        irrecv.enableIRIn();
    }

    void loop()
    {
        decode_results results;
        if (irrecv.decode(&results)) {
            if (results.value == 0xff629d) {
                static byte state = LOW;
                state = !state;
                digitalWrite(relayPin, state);
            }
            irrecv.resume();
        }

        // Sleep until next interrupt.
        sleep_mode();
    }


message:
Problem converting character array into integer in arduino using atoi function

I'm receiving a character string from a radio signal on my arduino.  This character string consists of four character digits, which I want to convert into an integer.  The four digit sequence may contain zeros padded in front of the integer, such as '0025' to represent the integer 25.

So, I saved this character string onto a character array of length 5:

    char left[5];

The first four characters in this array have the four character digits received in the radio signal.  I have a fifth character which I set to the character '\0' to signify a termination character.

The message received is any number ranging from 0 to 1023, but I need to use values between -255 and +255.  To convert the character into an integer, I use the atoi function as follows:

    int leftpower = (atoi(left)-512)/2;

When I print out the variable "leftpower", it seems to give the correct value.  I'm even able to use "leftpower" in an if then statement as follows:

    if (myvalue<0){
      Serial.println("inside the if-then statement");
      digitalWrite(in1,HIGH);
      digitalWrite(in2,LOW);
      //analogWrite(enableA,myvalue);
    }

So, as far as I can tell, everything is working fine.  I want to use "myvalue" as a command to an analogWrite function call as follows:

    //analogWrite(enablePinA,myvalue);

However, something strange happens when I uncomment this line.  WHen I uncomment it, the program seems to hang at the if statement, as if it paused at that point and neither crashes nor gives any error.  The program no longer prints out "inside the if-then statement" at all, but no other errors seem to be detected.  No other compilation or runtime errors.

The strange thing about this is that if I change "leftpower" to a number like 223 as follows:

    analogWrite(enablePinA,223);

the program works as I expected it to, producing a motor command.  So, I know the problem is not with my wiring.  The problem seems to be associated with the variable "leftpower", which was converted from a character array to an integer using the atoi function.

What exactly is going on?  What problem is actually occurring and how can I fix it?  Any help would be greatly appreciated!

For reference, my code is posted below:

    #include <RH_ASK.h> //radiohead library to read RF signals
    #include <SPI.h> //just because radiohead library depends on it
    RH_ASK driver; //default: transmitter data pin goes to arduino pin 11
    int in1=4;
    int in2=5;
    int in3=6;
    int in4=7;

    int enableA = 9;
    int enableB = 10;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      if (!driver.init()){
        Serial.println("receiver init failed");
      }
      pinMode(enableA,OUTPUT);
      pinMode(enableB,OUTPUT);
      pinMode(in1,OUTPUT);
      pinMode(in2,OUTPUT);
      pinMode(in3,OUTPUT);
      pinMode(in4,OUTPUT);
    }
    int leftpower,rightpower;
    void loop() {
      // put your main code here, to run repeatedly:
      uint8_t buf[8];
      uint8_t buflen = sizeof(buf);
      if (driver.recv(buf, &buflen)){ //non-blocking
        //Convert buf (unsigned integer) to a character array
        char temp[8]="";
        sprintf(temp,"%s",(char*) buf);
        //Four characters for first integer, four for the second integer
        //So, we have to split them into two parts (left and right)
        char left[5]="";
        for (int i=0; i<4; i++){
          left[i]=temp[i];
        }
        //Put a terminating character at the end
        left[4]='\0';
        char right[5]="";
        for (int i=0; i<4; i++){
          right[i]=temp[4+i];
        }
        //Put a terminating character at the end
        right[4]='\0';
        leftpower=(int) (atoi(left)-512)/2;
        rightpower=(int) (atoi(right)-512)/2;
        constrain(leftpower,-255,255);
        constrain(rightpower,-255,255);
        Serial.println(leftpower);
        Serial.println(rightpower);
        if (leftpower<0) {
          //switch H-bridge to forward direction
          Serial.println("inside the if-then statement");
          digitalWrite(in1,HIGH);
          digitalWrite(in2,LOW);
          analogWrite(enableA,255);
          Serial.println("got this far");
        }
        else {
          digitalWrite(in1,LOW);
          digitalWrite(in2,HIGH);
          analogWrite(enableA,255);
        }
    //    if (rightpower<0) {
    //      //switch H-bridge to forward direction
    //      digitalWrite(in3,LOW);
    //      digitalWrite(in4,HIGH);
    //      analogWrite(enableA,abs(rightpower));
    //    }
    //    else {
    //      digitalWrite(in4,LOW);
    //      digitalWrite(in3,HIGH);
    //      analogWrite(enableA,abs(rightpower));
    //    }

      }
    }

body:
You have a few issues here.

> `if (driver.recv(buf, &buflen)) { ... }`

You don't check the value of `buflen` after calling the `recv()` method.
<s>I didn't read the doc of the RH\_ASK library you are using. Are you sure
it does preserve message boundaries? I let you check. If it only
transports bytes (rather than full messages), then you will have to
repeatedly `recv()` until you have a full message.</s>

**Edit**: Looked at the doc. The communication is indeed packetized, so
you don't need to collect the message chunk by chunk. It is, however,
still a good idea to check whether the received size is what you expect:

    if (driver.recv(buf, &buflen) && buflen == 8) { ... }

> `sprintf(temp,"%s",(char*) buf);`

This is a serious bug, and most probably the reason your program behaves
inconsistently. Here `buf` is **not** a NUL-terminated string. The
`sprintf()` function will copy bytes from `buf` into `temp` until it
finds a NUL. It can potentially overwrite the receiving buffer and start
clobbering whatever happens to be past `temp` in your memory. This is
called “memory corruption” and can lead to any kind of unpredictable
behaviors.

Note that the whole copying you do here serves no useful purpose. You
can work from the initial buffer to start with:

    char left[5];
    memcpy(left, buf, 4);
    left[4] = '\0';
    char right[5];
    memcpy(right, buf+4, 4);
    right[4] = '\0';

> `constrain(leftpower,-255,255);`

You are implicitly discarding the value computed by `constrain()`. You
probably mean

    leftpower = constrain(leftpower, -255, 255);


message:
Why do people complain when I call my functions voids?

I have posted questions about "my void loop" or "my void setup" and people complain that they aren't really voids. But they are! See this example code:

    void setup() {
      pinMode(13, OUTPUT);
    }

    void loop() {
      digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);              // wait for a second
      digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);              // wait for a second
    }

Clearly `setup` and `loop` are voids because they have the word `void` right before them!

---

*Note: this is a reference question.*

body:
This is an easy mistake for a beginner to C++ to make. Let's look at other languages, like PHP:

<!-- language: lang-php -->

    function add ($a, $b)
      {
      return $a + $b;
      }

Or Lua:

<!-- language: lang-lua -->

    function add (a, b)
      return a + b
    end

Or JavaScript:

<!-- language: lang-js -->

    function add (a, b)
      {
      return a + b;
      }

Or VBscript:

<!-- language: lang-vbscript -->

    Function add (a, b)
      add = a + b
    End Function

All those languages have the word "function" there to indicate that you are declaring a function.

---

So what does C++ look like:

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

    int add (int a, int b)
      {
      return a + b;
      }

So this must be an "int" right? Or what if it doesn't return a value?

    void loop ()
      {
      }

Now it's a "void"? Kind of a weird name for a function!

Actually `int` and `void` in these examples are not weird names for functions. They are the **return types** of those functions. `int add (int a, int b)` is a **function** that returns an int. And `void loop ()` is a **function** that returns nothing.

The C++ compiler can deduce when it is seeing a function declaration from some clues:

* A return type (eg. int, float, long)
* A name (the function name)
* Some parentheses (for the function arguments)

Think of the word `function` as being there in spirit:

    int [function] add (int a, int b)
        ^^^^^^^^^^   <-- don't actually type this!
        {
        return a + b;
        }


body:
I think if you use a phrase like " my int a or my CustomType a " people would interpret those phrases to mean that you have a variable `a` that is an instance of an `int` or a `CustomType`.

According to [http://en.cppreference.com/w/cpp/language/types][1] you can't have an object or reference of type `void`.

If you have a phrase like "my void setup", I think most people would try to read that as implying you have a variable `setup` of type `void`, which I don't think makes sense, to most people.

What you actually have is this:

    void setup() {
    ...
    }

I think most people would phrase this as "my function setup, which takes no arguments are returns nothing".

  [1]: http://en.cppreference.com/w/cpp/language/types


message:
Proto Threading 2 functions

I would like to proto thread two functions to run pseudo-simultaneously. One function takes the input of a force sensor and moves a servo accordingly, and the other takes the input of a gyroscope (MPU650) and moves a different sensor accordingly. Below is my code where I attempt to use timers to handle this.

    #include <Wire.h>
    #include <Servo.h>
    #include "I2Cdev.h"
    #include "MPU6050.h"
    #include "Servo.h"

    int FSR_Pin = A0;
    bool isClosed = false;
    unsigned long lastMillis = 0;
    unsigned long lastMillis2 = 0;

    MPU6050 mpu;

    int16_t ax, ay, az;
    int16_t gx, gy, gz;

    Servo handServo;

    Servo wristServo;

    int pos = 0;
    int val;
    int prevVal;

    void setup(){
      Serial.begin(9600);
      handServo.attach(9);

      Wire.begin();
      Serial.begin(38400);

      Serial.println("Initialize MPU");
      mpu.initialize();
      Serial.println(mpu.testConnection() ? "Connected" : "Connection failed");
      wristServo.attach(8);
    }

    void handleFingers () {
      int FSRReading = analogRead(FSR_Pin);
      Serial.println(FSRReading);

    if (FSRReading > 9) {
     if (pos < 90) {
         handServo.write(pos);
          pos ++;
     }
      isClosed = true;

    } else if (isClosed == true && FSRReading < 10) {
      pos = 0;
      handServo.write(pos);
      isClosed = false;
    }
    }

    void handleWrist() {
      mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

        val = map(ay, -17000, 17000, 0, 179);
        if (val != prevVal)
        {
            wristServo.write(val);
            prevVal = val;
        }

    }

    void loop(){
      if (millis() - lastMillis > 1000) {
        handleFingers ();
      }
       lastMillis = millis();

     if (millis() - lastMillis2 > 1000) {
        handleWrist();
      }
       lastMillis2 = millis();

    }

When I run the code above, the servos move a few degrees each and then do nothing at all. It appears that none of the servos are responsive to the sensor feedback. Something is wrong with my timing or my method of proto threading. I would really appreciate your help, thanks.

body:
Jot provided the answer in a comment: you are updating `lastMillis` in
the wrong place. The correct way is:

    if (millis() - lastMillis >= 1000) {
        handleFingers();
        lastMillis = millis();
    }

Optionally, you can use `lastMillis += 1000` instead of
`lastMillis = millis()` if you want to precisely control the _average_
(rather than _minimum_) update period.

Just to elaborate a bit, the idiom I like for doing this kind of stuff
is as follows:

    const unsigned long FINGER_UPDATE_PERIOD = 1000;
    const unsigned long WRIST_UPDATE_PERIOD  = 1000;

    void loop() {
        unsigned long now = millis();

        // Handle the fingers.
        static unsigned long last_finger_update;
        if (now - last_finger_update >= FINGER_UPDATE_PERIOD) {
            last_finger_update = now;
            handleFingers();
        }

        // Handle the wrist.
        static unsigned long last_wrist_update;
        if (now - last_wrist_update >= WRIST_UPDATE_PERIOD) {
            last_wrist_update = now;
            handleWrist();
        }
    }

Note that:

 - The update periods are constants defined at the top of the
   program.
 - `millis()` only needs to be called once per loop iteration: if the
   loop takes many milliseconds to run you would be doing something
   wrong anyway.
 - `last_finger_update` and `last_wrist_update` stand for `lastMillis`
   and `lastMillis2`, which are very poor naming choices.
 - These two variables are local to `loop()`, as they are not needed
   anywhere else.
 - These variables are also declared `static`, which means they are
   implicitly initialized to 0 and they preserve their values from call
   to call.
 - I update the timing variables before doing the actual work. This
   helps keeping all the timing code together, which makes the code
   clearer, especially if the actual work takes many lines of code (e.g.
   you do the work inline instead of having it in separate functions).

Some people prefer using libraries for this kind of proto-threading. If
you use the [ArduinoThread][] library, the same could be written as:

    const unsigned long FINGER_UPDATE_PERIOD = 1000;
    const unsigned long WRIST_UPDATE_PERIOD  = 1000;

    Thread updateFingers(handleFingers, FINGER_UPDATE_PERIOD);
    Thread updateWrist(handleWrist, WRIST_UPDATE_PERIOD);
    StaticThreadController<2> scheduler(&updateFingers, &updateWrist);

    void loop() {
        scheduler.run();
    }

[ArduinoThread]: https://github.com/ivanseidel/ArduinoThread


message:
handling array from post data on espwebserver

I think I have a supplement question. If irrelevant , then sorry in advance.

I have nested array in post like:  from apache web server page index.php

$_POST['colorsarray'][0] = '#ff0000';

$_POST['colorsarray'][1] = '#2d67ea';

$_POST['colorsarray'][3] = '#7cf325';

$_POST['mode'] = 'none';

$_POST['singlecolour'] = '#ff0000';

Can you suggest me how to assign this array (coloursarray) directly to another array in espwebserver. In other use cases , only the list (length) of array will increase and is not know until the variable arrives from client.

Thanks in advance.

body:
The ability for PHP to do this is special to PHP. The PHP program parses the field names as PHP arrays if they are named thus:

    <form ....>
    <input name="[colorsarray][0]" value="#ff0000" />
    <input name="[colorsarray][1]" value="#2d67ea" />
    <input name="[colorsarray][2]" value="#000000" />
    <input name="[colorsarray][3]" value="#7cf325" />
    [...]
    </form>

But since the ESP8266's core doesn't use PHP or understand PHP arrays, you will have to use the literal field name `[colorsarray][3]`, parse it yourself, and determine at run-time the length of the array and how much memory is needed, etc.


message:
Can't read JSON data from client (webpage) with Arduino Leonardo ETH

I'm reading a digital pin and count how many times that pin is enable, after that the data is sent in JSON format. All is working well till here. But I want to introduce a value from webpage to arduino, so the arduino will know from what number it should count. I modified the webpage, I'm converting the value in JSON format, everything. But I can't get it on arduino. I see the value on Serial Monitor right before client disconnect. But I just cannot figure what I'm doing wrong, maybe you guys have a suggestion ?

Here is my Arduino code ( is a bit messy, and I haven't did the part were I tell to arduino the number where it should start to count, I will do that after i can get my numbers from webpage ). If needed i can also add the webpage code.

    #include <SD.h>
    #include <SPI.h>
    #include <Ethernet2.h>
    #include <ArduinoJson.h>

    int pin = 3;
    int state = 0;
    //==========================
    int push = 0;
    //==========================
    int laststate = 0;
    const int chipS = 4;

    byte mac[] = {0x00, 0x08, 0xDC, 0x1C, 0xB8, 0x4C}; // Enter the MAC address that is on your Ethernet shield (sticker) - eg. 00-08-DC-1C-B8-4C  (but use hexidecimal format eg. 0x00)
    IPAddress ip(192, 168, 0, 88);                     // The IP address that you will give the Server - will depend on your local network range
    EthernetServer server(8880);                       // The port to listen for Web Browsers - the default is 80, but some routers will block this port.. so change to 8081.

    //*************************************************************************************************
    // setup function
    //=================================================================================================
    void setup()
    {
        Serial.begin(9600); // Begin Serial communication (baud rate = 9600).
        while (!Serial)
        {
            ; // wait for serial port to connect. Needed for Leonardo only
        }

        Ethernet.begin(mac, ip); // Initialise the ethernet library and network settings: https://www.arduino.cc/en/Reference/EthernetBegin
        server.begin();          // Tell the server to begin listening for incoming connections (on port 8081 in this example)
        Serial.print("Server IP address : ");
        Serial.println(Ethernet.localIP()); // If you see the IP address within the Serial monitor - you know that the server started successfully
        Serial.println(" ");

        // cardlaif  -  SD CARD INITALIZATION
        Serial.println("Initializare card...");
        if (!SD.begin(chipS))
        {
            Serial.println(" Initializarea cardului a esuat sau cardul lipseste ");
            while (1)
                ;
        }
        Serial.println(" Card initializat ");
        Serial.println(" ");
        pinMode(3, INPUT);
    }

    //*************************************************************************************************
    // loop function
    //=================================================================================================
    void loop()
    {
        //=====================================================================================================
        // contor  PIN 3 COUNTER
        //======================================================================================================
        state = digitalRead(pin);

        if (state != laststate)
        {
            if (state == HIGH)
            {
                push++;
            }
            delay(50);
        }
        laststate = state;

        Serial.print(" nr. citiri: ");
        Serial.println(push);
        //====================================================================================================
        // card SD CARD WRITE CODE
        //====================================================================================================
        String dataString = " ";
        dataString += String("nr. citiri: ");
        dataString += String(push);

        File dataFile = SD.open("datalog.txt", FILE_WRITE);
        if (dataFile)
        {
            dataFile.println(dataString);
            dataFile.close();
        }
        else
        {
            Serial.println("error opening datalog.txt");
        }
        //========================================================================================================
        //    net
        //========================================================================================================
        EthernetClient client = server.available(); // assign any newly connected Web Browsers to the "client" variable.

        if (client.connected())
        {
            Serial.println("Client Connected");
            // char c = client.read();
            // Serial.print(c);
            while (client.available())
            {
                Serial.write(client.read()); // Uncomment if you want to write the request from the Browser (CLIENT) to the SERIAL MONITOR (and comment out the next line)
                // client.read();                               // This line will clear the communication buffer between the client and the server.
            }

            // Send the Server response header back to the browser.
            client.println(F("HTTP/1.1 200 OK"));                                                                                // This tells the browser that the request to provide data was accepted
                                                                                //    client.println("GET");
            client.println(F("Access-Control-Allow-Origin: *"));                                                                            // Tells the browser it has accepted its request for data from a different domain (origin).
            client.println(F("Access-Control-Allow-Methods:  GET,POST,PUT,DELETE,OPTIONS"));                                                // The arduino will accept JSON format data using this
            client.println(F("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")); // The arduino will accept JSON format data using this
            client.println(F("Content-Type: application/json;charset=utf-8"));                                                              // Lets the browser know that the data will be in a JSON format
            client.println(F("Server: Arduino"));                                                                                // The data is coming from an Arduino Web Server (this line can be omitted)
            client.println(F("Connection: close"));                                                                                // Will close the connection at the end of data transmission.
            client.println();                                                                                // You need to include this blank line - it tells the browser that it has reached the end of the Server reponse header.

            // Example Transmission: [{"key":0, "value":300},{"key":1, "value":320},{"key":2, "value":143},{"key":3, "value":24},{"key":4, "value":760},{"key":5, "value":470}]
            client.print("[");            // This is tha starting bracket of the JSON data
            client.print("{\"value\": "); // The value I read on pin 3 and send in JSON format to webpage
            client.print(push);           //  The value I read on pin 3 and send in JSON format to webpage
            client.print("}");            //  JSON things
            client.println("]");          // This is the final bracket of the JSON data
        }

        //=================================================================================================
        // trying to print on serial json data
        //=================================================================================================
        char json[] = "{\"index\" }";
        StaticJsonBuffer<300> jsonBuffer;
        JsonObject &root = jsonBuffer.createObject();
        if (!root.success())
        {
            Serial.println("Parsing failed");
        }
        int index = root["index"];
        Serial.print(" index: ");
        Serial.print(index);
        Serial.println(" ");

        client.stop();                       // This method terminates the connection to the client
        Serial.println("Client has closed"); // Print the message to the Serial monitor to indicate that the client connection has closed.
    } // VOID LOOP END

And this is what I get on serial monitor:

    Client Connected
    POST / HTTP/1.1
    Host: 192.168.0.88:8880
    Connection: keep-alive
    Content-Length: 1
    Accept: application/json, text/javascript, */*; q=0.01
    Origin: null
    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)     AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36
    Content-Type: application/json; charset=UTF-8
    Accept-Encoding: gzip, deflate
    Accept-Language: en-US,en;q=0.9,ro;q=0.8,es;q=0.7

    5 index: 0

At the end, that 5 before the " index " word should be where the 0 is.
The 5 it's my JSON data. The reason why I see it it's because I enabled to see the reqest from the browser.

Someone have any idea ?

P.S Sorry for my bad english ^_^

body:
Below, you create a static string, which is never used again.

    char json[] = "{\"index\" }";

Here you create a buffer and instantiate an empty JsonObject.

    StaticJsonBuffer jsonBuffer;
    JsonObject& root = jsonBuffer.createObject();

Here you check if `root` (your newly created JsonObject) is valid. Because it's empty and fresh, it is valid.

    if (!root.success())
    {
      Serial.println("Parsing failed");
    }

Here, you try to ask for the value of `index` from your empty object.

    int index = root["index"];
    Serial.print(" index: ");
    Serial.print(index);

If you never provide the `JsonObject` with any structure or content to parse, how can it give you anything back besides nothing?

The examples from the ArduinoJSON library prove to be helpful:

[Documentation on `parseObject`](https://arduinojson.org/api/jsonbuffer/parseobject/)

>     char json[] = "{\"hello\":\"world\"}";
>     StaticJsonBuffer<200> jsonBuffer;
>     JsonObject& object = jsonBuffer.parseObject(json);
>     const char* world = object["hello"];

Note the differences from what you are doing:

 1. The initial JSON string to parse has both a key and a value.
 2. The `StaticJsonBuffer` declaration includes a buffer size
 3. The `JsonObject` declaration uses `parseObject` and passes in the `json` string, instead of creating a blank/empty object.


message:
Arduino reduces the laser power

Its important to mention that I'm noob.
I bought 500mw 405nm TTL module laser(5-12 volt) driver circuit. When I supplied laser with 12 volt, it turns on with max power. but when i connects laser TTL module to arduino (pin 11) in order to control turning on & off of laser through GRBL(CNC machine language) command with full power, the output of laser reduces.

"M05 S0" turns off the laser while
"M03 S255" should turns on the laser with full power as it is turning on with direct 12 volt supply, but its not happening.

so how can I make laser turn on with full power with arduino control?

Laser I,m using
https://www.amazon.in/gp/product/B071J2W7V8/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1

Laser driver circuit
[![enter image description here][1]][1]

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

body:
The first thing I would recommend is to log into your Amazon account and contact the seller. Ask them to send you product documentation.

If the seller is not able to provide any, then you could return the product for a refund or try to figure it out how it works.

According to this document: [TTL Laser][1]

  [1]: http://www.onset-eo.com/img/product/PDT50c58f8c6404e/6701205675126ca3ce7bdc.pdf
TTL modulators emit 100% of their power when a TTL "0" (0 VDC) is input and less than 5% of their power when a TTL "1" (5 VDC) is input.

gre_gor's comment about trying a simple PWM sketch sounds like an excellent place to start.


message:
Code compatibility with Arduino Due

I am currently working on a quadcopter project that involves an MPU6050 accelerometer+gyroscope module, an ultrasonic sensor and control of electronic speed controllers. I have used existing examples and modified them to get raw values of acceleration, yaw pitch and roll angles, and the distance from the ultrasonic. Here is the _long code_.

    #include "I2Cdev.h"

    #include "MPU6050_6Axis_MotionApps20.h"
    //#include "MPU6050.h" // not necessary if using MotionApps include file

    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
    #endif

    MPU6050 mpu;
    //MPU6050 mpu(0x69); // <-- use for AD0 high

    const int trigPin = 9;
    const int echoPin = 10;

    #define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards
    #define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
    bool blinkState = false;

    // MPU control/status vars
    bool dmpReady = false;  // set true if DMP init was successful
    uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
    uint8_t devStatus;
    uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
    uint16_t fifoCount;     // count of all bytes currently in FIFO
    uint8_t fifoBuffer[64]; // FIFO storage buffer

    // orientation/motion vars
    Quaternion q;           // [w, x, y, z]         quaternion container
    VectorInt16 aa;         // [x, y, z]            accel sensor measurements
    VectorInt16 aaReal;     // [x, y, z]gravity-free accel sensor measurements
    VectorInt16 aaWorld;    // [x, y, z] world-frame accel sensor measurements
    VectorFloat gravity;    // [x, y, z]            gravity vector
    float euler[3];         // [psi, theta, phi]    Euler angle container
    float ypr[3], yprd[3] = {0, 0, 0};

    // packet structure for InvenSense teapot demo
    uint8_t teapotPacket[14] = {'$', 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x00, '\r', '\n' };

    // ================================================================
    // ===               INTERRUPT DETECTION ROUTINE                ===
    // ================================================================
    volatile bool mpuInterrupt = false;
    void dmpDataReady() {
      mpuInterrupt = true;
    }

    // ================================================================
    // ===                      INITIAL SETUP                       ===
    // ================================================================
    int16_t yo = 0, po = 0, ro = 0;
    int lv = 1, flag = 0;
    const int MPU_addr = 0x68; // I2C address of the MPU-6050
    int16_t AcX, AcY, AcZ, Tmp, GyX, GyY, GyZ;
    int32_t AcXo = 0, AcYo = 0, AcZo = 0, prev, curr;
    int32_t AcXd = 0, AcYd = 0, AcZd = 0;
    int i = 1, flaggl = 0;
    int  glc = 0, lv2 = 1;
    long duration;
    int distance, distanced;
    void setup() {

    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
      Wire.begin();
      Wire.setClock(400000);
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
      Fastwire::setup(400, true);
    #endif
      Serial.begin(115200);
      // initialize device
      Serial.println(F("Initializing I2C devices..."));
      mpu.initialize();
      pinMode(INTERRUPT_PIN, INPUT);
      // verify connection
      Serial.println(F("Testing device connections..."));
      Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
      // wait for ready
      Serial.println(F("\nSend any character to begin DMP programming and demo:
                       "));
      while (Serial.available() && Serial.read()); // empty buffer
      while (!Serial.available());                 // wait for data
      while (Serial.available() && Serial.read()); // empty buffer again
      // load and configure the DMP
      Serial.println(F("Initializing DMP..."));
      devStatus = mpu.dmpInitialize();
      // supply your own gyro offsets here, scaled for min sensitivity
      mpu.setXGyroOffset(220);
      mpu.setYGyroOffset(76);
      mpu.setZGyroOffset(-85);
      mpu.setZAccelOffset(1788); // 1688 factory default for my test chip
      // make sure it worked (returns 0 if so)
      if (devStatus == 0) {
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external
                         interrupt 0)..."));
        attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();

        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
      } else {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
      }

      // configure LED for output
      pinMode(LED_PIN, OUTPUT);
      glc = 0;
      distance = distanced = 0;
    }

    // ================================================================
    // ===                    MAIN PROGRAM LOOP                     ===
    // ================================================================
    void loop() {
      // if programming failed, don't try to do anything
      if (!dmpReady) return;

      // wait for MPU interrupt or extra packet(s) available
      while (!mpuInterrupt && fifoCount < packetSize) {
      }
      mpuInterrupt = false;
      mpuIntStatus = mpu.getIntStatus();
      // get current FIFO count
      fifoCount = mpu.getFIFOCount();
      // check for overflow (this should never happen unless our code is too inefficient)
      if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        Serial.println(F("FIFO overflow!"));
        // otherwise, check for DMP data ready interrupt (this should happen frequently)
      } else if (mpuIntStatus & 0x02) {
        // wait for correct available data length, should be a VERY short wait
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);
        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;
        //#ifdef OUTPUT_READABLE_YAWPITCHROLL
        // display Euler angles in degrees
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
        if (millis() > 30000 && flag == 0) {
          if ( flag == 0 && lv  < 21) {
            yo += ypr[0] * 180 / M_PI;
            po += ypr[1] * 180 / M_PI;
            ro += ypr[2] * 180 / M_PI;
            ++lv;
          } else if (flag == 0) {
            flag = 1;
            yo /= 20;
            po /= 20;
            ro /= 20;
          }
        }
        //#endif
        // blink LED to indicate activity
        blinkState = !blinkState;
        digitalWrite(LED_PIN, blinkState);
        Wire.beginTransmission(MPU_addr);
        Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
        Wire.endTransmission(false);
        Wire.requestFrom(MPU_addr, 14, true); // request a total of 14 registers
        AcX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C     (ACCEL_XOUT_L)
        AcY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
        AcZ = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
        Tmp = Wire.read() << 8 | Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
        GyX = Wire.read() << 8 | Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
        GyY = Wire.read() << 8 | Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
        GyZ = Wire.read() << 8 | Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
        mpu.resetFIFO();
        if (i < 21 && !flaggl) {
          AcXo += AcX;
          AcYo += AcY;
          AcZo += AcZ;
          ++i;
          Serial.println();
          Serial.println("***************************************************************************");
        } else if (!flaggl) {
          flaggl = 1;
          AcXo  = AcXo / 20;
          AcYo = AcYo / 20;
          AcZo = AcZo / 20;
        }
        curr = (AcZ - AcZo / 100);
        if (prev == curr )
          ++glc;
        else {
          glc = 0;
          prev = curr;
        }
        if (glc == 10) {
          Serial.println("lock broken!!!");
          glc = 0;
          loop();
        }
        if (flag == 1 && flaggl == 1) {
          if (lv2 < 21) {
            delayMicroseconds(2);
            digitalWrite(trigPin, HIGH);
            delayMicroseconds(10);
            digitalWrite(trigPin, LOW);
            duration = pulseIn(echoPin, HIGH);
            distance = duration * 0.034 / 2;
            AcXd += (AcX - AcXo) / 100;
            AcYd += (AcY - AcYo) / 100;
            AcZd += (AcZ - AcZo) / 100;
            yprd[0] += ypr[0] * 180 / M_PI - yo;
            yprd[1] += ypr[1] * 180 / M_PI - po;
            yprd[2] += ypr[2] * 180 / M_PI - ro;
            distanced += distance;
            ++lv2;
          } else {
            AcXd /= 20;
            AcYd /= 20;
            AcZd /= 20;
            yprd[0] /= 20;
            yprd[1] /= 20;
            yprd[2] /= 20;
            distanced /= 20;
            lv2 = 1;
            Serial.print("AcX = ");
            Serial.print(AcXd);
            Serial.print(" | AcY = ");
            Serial.print(AcYd);
            Serial.print(" | AcZ = ");
            Serial.print(AcZd);
            Serial.print(" | yaw = ");
            Serial.print(yprd[0]);
            Serial.print(" | pitch = ");
            Serial.print(yprd[1]);
            Serial.print(" | roll = ");
            Serial.print(yprd[2]);
            Serial.print(" | distance = ");
            Serial.println(distanced);
            AcXd  = 0;
            AcYd = 0;
            AcZd = 0;
            yprd[0] = 0;
            yprd[1] = 0;
            yprd[2] = 0;
            distanced = 0;
          }
        }
      }
    }

The code involves offset calculation and displays the averaged instantaneous values. After overcoming the problems of FIFO buffer overflow and some other typical issues, I've managed to get the code running but the the Arduino hangs after sometime (code tested on both Uno and Nano).

Therefore, it _seems_ that maybe I need a higher clock speed. So, I had a look through other Arduino boards and Due seemed to be the solution, as it has a clock speed of 84MHz, compared to Uno's 16 MHz. Therefore, my question is that will the libraries and functions used in this code be compatible with the Due? Also, can the 3.3V operation of the Due, compared to  Uno's 5V, present any problem in interfacing it with other sensors mentioned?

body:
> Therefore, my question is that will be the libraries and functions used in this code be compatiable with Due?

The I2Cdev library is made for abstracting the hardware I2C functions to a more user friendly interface for each chip. Since the Arduino Due has hardware TWI (which is basically I2C) the normal `Wire` library from the Arduino IDE should work with it.

> Also, can the 3.3V operation of Due, compared to Uno's 5V present any problem in interfacing it with other sensors mentioned?

You cannot put 5V from your sensor on a 3.3V pin on the Arduino Due, since this would destroy the pins hardware. I don't know how exactly you are using the MPU6050, but [this one from Adafruit][1] runs on 3.3V, which would be perfect. If your MPU6050 board only works with 5V maybe you can level shift the lines (but note that I2C would need 2-way level shifting, because SDA is used as output and input).

Also [this Article][2] may help you, where they are porting MultiWii to an Arduino Due.

  [1]: https://www.sparkfun.com/products/11028#documents-tab
  [2]: https://technicaladventure.blogspot.de/2014/05/porting-multiwii-to-arduino-due.html


body:
I am working with the ArduinoDue and ArduinoMega2560 boards and I have found that programs that compile with the Mega2560 board don't necessary compile with the Due board.
This is because there is a limited amount of available libraries that are compatible with the Due board.
Try compiling (verifying) your code with the Due options set, you don't need to buy one to try verifying it.


message:
tinkercad arduino simulator integers being outputted as larger numbers than they are?

I am using an Arduino simulator on [www.tinkercad.com][1] (a seemingly nice free product from Autodesk).  Working on conversion of an integer to a 16 bit binary string for output to a DAC, but unfortunately even at the first step I am getting unexpected behavior.

    void setup()
    {
      pinMode(13, OUTPUT);
      Serial.begin(9600);
      Serial.print("Sanity Check\n");
      uint16_t num = 12000;
      Serial.print("\nNumber: " + String(num) + "\n");
      delay(3000);
    }
Surprisingly the above code gave the following output:

    Sanity Check

    Number: 12222

Is there something I am doing wrong, or something wrong with the simulator?   The error seems to crop up with any value over 10000.  10001, 10002, 10003 all print as 10000.  11000, 11001, 11002, 11003 all print as 11111.  etc, etc.  What could be going on?
  [1]: http://www.tinkercad.com

body:
Bug. No other explanation. Real hardware (Arduino Uno) prints 12000.

Even the debugger tells me that the value of that variable is 12000.

[![debug][1]][1]

Outputs:

    Number: 12222
    12000
    12222 something

Most interestingly if you `Serial.println()` the number, it is outputted correctly. The bug must be in the constructor of the `String` object, as demonstrated by the "test" `String`. This bug also occurs on other data types, e.g. `int`.

If you only use direct `Serial.print[ln]` calls you should be able to workaround that bug.

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


body:
Tinkercad is (was) a very good simulator but it has stopped updates.
Here is the output from the free Arduino simulator from [here][1]

This [project][2] is used for the below screenshot

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

Here is an [article][4] pointing some more features of the simulator

  [1]: https://wokwi.com
  [2]: https://wokwi.com/arduino/projects/295390167781343757
  [3]: https://i.stack.imgur.com/RhmHv.png
  [4]: https://www.hackster.io/write2puneeth/tinkercad-versus-wokwi-arduino-simulator-5ab08d


message:
On a motor after a continuous input of a certain amount of time

I would like to produce an output after a constant input is detected for a certain amount of time. Below is a simple code of what I am trying to do minus the time factor. Can someone help me on how to code out the duration of an input occurrence?  i.e.

    if (sensorValue > threshold);
        //if this occurs for more than 4 hours, then
        digitalWrite (3, HIGH);

body:
You must store the state of the last readings and do something like this:

        //Off-loop:
        bool state_changed = false;
        unsigned long time_in_state = 0;
        unsigned long last_reading = 0;

        //On-loop:
        if (sensorValue > treshold && !state_changed) {
            time_in_state += millis() - last_reading;
            last_reading = millis();
        }
        else {
            state_changed = true;
            time_in_state = 0;
        }

        if (time_in_state > TIME_REQUIRED) {
          digitalWrite (3, HIGH);
        }