message:
SIM800L and Arduino Sleep - getting whimsy Serial output after 5 calls

i'm working on project where i'm trying to achieve that arduino parse caller ID so i can use it later to send SMS with sensor reading data.

Somehow i made that code (with much googling) and it works great... But when i include arduino sleep part, it does work at beginning, but after i call SIM800 4-5 times with distinct of 30 seconds, i get unusable data on Serial, so i can't no longer parse correct number.

I tried many things, dropping baud rate to 1200, changing delay, but still i get strange characters after few calls.

Can anyone help me?

P.S. ATMEGA328P ic MCU

Thank you,
Matija

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

    SoftwareSerial SIM800(8, 7);

    String buffer1;
    unsigned int current_millis = 0;
    String phone;

    void setup() {
         buffer1.reserve(200);
         phone.reserve(20);

         Serial.begin(19200); //
         SIM800.begin(9600);
         delay(1000);
         SIM800.write("AT\r");  // because of SIM800L autobounding mode
         delay(1000);
         SIM800.write("AT+IPR=9600\r");  // set baud at 9600, i tried with 1200
         and  other, and with autobauding but still got same problem
         delay(1000);
         SIM800.write("AT+CMGF=1\r");  // set SMS mode to text
         delay(1000);
         SIM800.write("AT+CNMI=2,2,0,0,0\r");
         delay(1000);
         Serial.print(SIM800.readString());
         SIM800.write("AT+CLIP=1\r\n");
         delay(1000);
         SIM800.write("AT+SGPIO=0,7,1,0\r");
         delay(1000);
         SIM800.write("AT+CSCLK=2\r"); //power saving mode of SIM800L
         delay(1000);
         current_millis = millis();
    }

    void loop() {
       // put your main code here, to run repeatedly:
       if (SIM800.available() > 0) {
          buffer1 = SIM800.readStringUntil('\n'); //Saving string then parsing
               caller number from it
          Serial.println(buffer1);
          parse();
          current_millis = millis();
          }

        if ((millis() - current_millis) > 10000) { //Putting atmega tu sleep
           sleepNow();
           delay(1000);// tried many delays
           current_millis = millis();
         }

     }

    void parse() {
        if (buffer1.indexOf("CLIP:") > 0) {
            phone = buffer1.substring(buffer1.indexOf("+CLIP: ") + 8,
            buffer1.indexOf("+CLIP: ") + 21); //parsing caller number
            Serial.println(phone);
            SIM800.write("ATH\r"); //hang out phone call
            delay(500);
            SIM800.write("ATH\r");
            delay(500);
      }

    }

    void sleepNow() { //PIN CHANGE INTERRUPT ON PIN 7,8 BECAUSE SOFTWARE SERIAL
                       LIBRARY USE IT AND IT WILL WAKE UP ATMEGA
        set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set herethe
                                              sleep bit in the mcucr register
        sleep_mode();            // here the device is actually put to sleep!!
                             // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
        sleep_disable();         // first thing after waking from sleep: disable
                                    sleep...
        }

[![Serial OUTPUT][1]][1]

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

body:
Give [AltSoftSerial][1] a try, it's hands down superior.

Reset might work but it does not actually solve your problem, it just swipes it under the mattress. Also, have you considered ditching that String? It is the source of many problems regarding memory. You could relatively easily substitute it for an array of chars instead. Something like this, taken from [example#2][2]:

    void recvWithEndMarker() {
        static byte ndx = 0;
        char endMarker = '\n';
        char rc;

        while (Serial.available() > 0 && newData == false) {
            rc = Serial.read();

            if (rc != endMarker) {
                receivedChars[ndx] = rc;
                ndx++;
                if (ndx >= numChars) {
                    ndx = numChars - 1;
                }
            }
            else {
                receivedChars[ndx] = '\0'; // terminate the string
                ndx = 0;
                newData = true;
            }
        }
    }

  [1]: https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html
  [2]: http://forum.arduino.cc/index.php?topic=396450


sender: user

sender: assistant

body:
When you use sleep mode SLEEP_MODE_PWR_DOWN you're turning off all of the microcontroller's timers, Including the timer SoftSerial is using.  I expect that turning off and then when wake from sleep turning back on the timers is affecting the timing of your serial communications.

Try using SLEEP_MODE_IDLE instead of SLEEP_MODE_PWR_DOWN and see if it corrects the problem.


message:
Wifi with ESP8266 and Arduino sketches

I have a NodeMcu Lua ESP8266 ESP-12E which i want to use to control to a relais via Wifi network.

The first step was to write an Arduino Sketch which scans networks and connects to the network. However, even the standard example from the examples menu didn't work (c.f.,https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino) .

To rule out hardware problems I tried the LUA version from the list API doc (see below), which worked.

     -- print ap list
    function listap(t)
          for k,v in pairs(t) do
            print(k.." : "..v)
          end
    end

    wifi.sta.getap(listap)

Using a firmware build from http://nodemcu.com/index_en.html

I gave the INO version another try and it seemed to work as well. However, it turned out it only works if the previous firmware has been the firmware from http://nodemcu.com/index_en.html

To I need to include a library or something ?

Thanks in advance,
Cafebabe

body:
(By googling) I figured out the problem and a work-around. **But not an executable solution.** The problem seems to be that the RF module is not properly initialised when the device is powered on or awakes from reset.

Sadly there seems to be no manual mode to switch on the RF module.

However, I found a workaround. First I made the connection to enable deep sleep, for that, we need to tie the `RST` pin to `D0`/`GPIO 16` on the ESP8266.

Then I added the following code to setup

    extern "C" {
      #include "user_interface.h"
    }

    void setup(){
      if (resetInfo->reason != REASON_DEEP_SLEEP_AWAKE) {

          ESP.deepSleep(10, WAKE_RF_DEFAULT)
      }

Basically whenever the system comes into setup from something else than deep sleep, the system goes to deep sleep and when powering back on the RF module is enabled.


message:
User configuration file does not exist or is not a regular file, skipping

I am facing issues while uploading sketch to **Adafruit Feature 32u4 Bluefruit LE** devices. When i try to upload **Blink** demo it was working fine and my device also blinking, But bellow error i am getting every time when i upload sketch.

       System wide configuration file is "/Applications/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/Users/myMacmnin/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

I am using **Adafruit Feature 32u4 Bluefruit Le device,Arduion 1.8.3 version, MacMini with macOs Sierra(10.12.3).**

body:
Finally i found answer for my question, It happen because of uploading sketch in selected pin.

    // Neopixel
    //#define PIN            6   /* Pin used to drive the NeoPixels */
    #define PIN            13   /* Pin used to drive the NeoPixels */

I Changed Pin 6 to 13 , it's worked for me.


message:
Flashing ESP8266 over WiFi whith samrtphone?

I'm working on a project in which an ESP8266 is the brain of the device. I want to add new features to the device controller later but this requires that the user open the controller and reprogram the ESP8266.

I want the user to be able to update the firmware with his smartphone (maybe through an application). How can I do that? Is this possible with this chip?

body:
ESP8266 OTA can be performed through a web browser as detailed [in the ESP8266 OTA information page](http://esp8266.github.io/Arduino/versions/2.0.0/doc/ota_updates/ota_updates.html).

Since a smartphone has a web browser I can see no reason why you can't use that.


message:
Arithmetic types in Arduino

I'm looking for a complete list of the arithmetic types in the Arduino framework.
On the Internet I found various incomplete lists: sometimes there is `short`, sometimes `word`, but other types are missing.

Could someone please provide an exhaustive list of the arithmetic data types in Arduino, including the C/C++ types and the Arduino-defined types (or aliases, e.g. the one created among others in Arduino.h with `typedef uint8_t byte;`) with a short description? If two types are identical please include both names in the list but making clear that they are the same.

body:
The Arduino "language" is actually C/C++. GNU GCC and tool chain are used. The Arduino IDE uses a preprocessor to make it easier for beginners by removing some of the C/C++ requirements such as forward declaration of functions.

The GNU AVR GCC data types and representation, and the answer to your question can be found on the project Wiki page; https://gcc.gnu.org/wiki/avr-gcc

For C/C++ there are build-in data types but also a set of standards. One of the standard header files with data types is `stdint.h`. http://www.nongnu.org/avr-libc/user-manual/group__avr__stdint.html

`Arduino.h` and additional header files within the Arduino core libary contains the extensions or redefinitions made. The complete reference list; https://www.arduino.cc/en/Reference/HomePage

Cheers!


body:
You have integers in 8, 16, 32 and 64 bits, both signed and unsigned. You have float and double, which can be the same thing on some systems.

There are many names given to those variable types, some standard or ubiquitous, some vague or unique, or change depending on which type of CPU you are working with.

The names aren't important, since they only exist in the source code. All that matters is the underlying size. Names of the same underlying size and signedness are interchangeable at will.

For example:

* uint8_t = unsigned char
* int32_t = long = int on 32 but systems
* uint16_t = unsigned short = int on 8 bit systems

As you can see `int` changes depending on the system you are on. So it is best to stick to specifically named types. I always use the `[u]int[N]_t` types.

So you have:

* uint8_t
* int8_t
* uint16_t
* int16_t
* uint32_t
* int32_t
* uint64_t
* int64_t

And:

* float
* double (if the compiler supports double on the platform you are compiling for, otherwise it is just float).

Arduino itself provides some more unique variable names that are completely nonstandard, such as `byte` for `unsigned char`.

In `short` (pun intended), stick to variables that specifically define their type if you are worried about how big they all are, and avoid all the rest.

For overloading the compiler will automatically "upscale" the variables to the best fitting available function (known as *type promotion*) unless functions are flagged as `explicit`, so you can have a function with a `long` parameter and pass any integer variable up to and including a `long` in size. The same with `float` / `double` types - if your function takes a `double` you can pass it a `float`. Useful when you don't know if the target provides a real `double` or not - just use `double` and it will work regardless with either `double` or `float`.


message:
Programming Leonardo with TTL to USB cable

I have wired my Arduino as seen in the picture, with the RX of the cable plugged into the TX (D1) of the Leonardo and the TX of the cable plugged into the RX(D0) of the Leonardo. I then have the ground plugged into GND and the power into 5V. The driver is installed correctly and the IDE recognizes the port, however, whenever I try and upload any sketch, I get the error:

Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding

I can upload sketches fine via usb, is it just unable to do so via a USB to TTL cable?

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

Thanks in advance

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

body:
The bootloader on the Leonardo operates through the native USB port of the ATMega32U2 chip, not the UART.

You cannot treat it like an Uno because it isn't an Uno.

You can only program it through the USB port or through the ICSP connector.

If you want to use UART to upload you will need to replace the bootloader with a suitable UART based alternative. (Before you ask, no I don't know if one even exists or where to get it if it does).


message:
Using Raspberry Pi to Receive Float from Arduino using NRF24L01

Good day. I've been learning on how to transfer data from Arduino to Raspberry Pi wirelessly using NRF24L01 based on the following reference:
[Raspberry Pi 3 Tutorial 14 – Wireless Pi to Arduino Communication with NRF24L01+][1].

The reason why I want to do this is to log temperature and humidity data wirelessly using DHT22 sensors.

The Arduino code is shown below:

    //SendReceive.ino

    #include<SPI.h>
    #include<RF24.h>

    // CE, CSN pins
    RF24 radio(9, 10);

    void setup(void){
     while(!Serial);
     Serial.begin(9600);

     radio.begin();
     radio.setPALevel(RF24_PA_MAX);
     radio.setChannel(0x76);
     radio.openWritingPipe(0xF0F0F0F0E1LL);
     const uint64_t pipe = (0xE8E8F0F0E1LL);
     radio.openReadingPipe(1, pipe);

     radio.enableDynamicPayloads();
     radio.powerUp();

    }

    void loop(void){
     radio.startListening();
     Serial.println("Starting loop. Radio on.");
     char receivedMessage[32] = {0};
     if(radio.available()){
      radio.read(receivedMessage, sizeof(receivedMessage));
      Serial.println(receivedMessage);
      Serial.println("Turning off the radio.");
      radio.stopListening();

      String stringMessage(receivedMessage);

      if(stringMessage == "GETSTRING"){
       Serial.println("Looks like they want a string!");
       const char text[] = "Yo wassup, haha";
       radio.write(text, sizeof(text));
       Serial.println("We sent our message.");
      }
     }
     delay(100);

    }

Meanwhile, the Raspberry Pi code is shown below:

    import RPi.GPIO as GPIO
    from lib_nrf24 import NRF24
    import time
    import spidev

    GPIO.setmode(GPIO.BCM)

    pipes = [[0xE8, 0xE8, 0xF0, 0xF0, 0xE1], [0xF0, 0xF0, 0xF0, 0xF0, 0xE1]]

    radio = NRF24(GPIO, spidev.SpiDev())
    radio.begin(0, 17)

    radio.setPayloadSize(32)
    radio.setChannel(0x76)
    radio.setDataRate(NRF24.BR_1MBPS)
    radio.setPALevel(NRF24.PA_MIN)

    radio.setAutoAck(True)
    radio.enableDynamicPayloads()
    radio.enableAckPayload()

    radio.openWritingPipe(pipes[0])
    radio.openReadingPipe(1, pipes[1])
    radio.printDetails()
    # radio.startListening()

    message = list("GETSTRING")
    while len(message) < 32:
        message.append(0)

    while(1):
        start = time.time()
        radio.write(message)
        print("Sent the message: {}".format(message))
        radio.startListening()

        while not radio.available(0):
            time.sleep(1 / 100)
            if time.time() - start > 2:
                print("Timed out.")
                break

        receivedMessage = []
        radio.read(receivedMessage, radio.getDynamicPayloadSize())
        print("Received: {}".format(receivedMessage))

        print("Translating the receivedMessage into unicode characters")
        string = ""
        for n in receivedMessage:
            # Decode into standard unicode set
            if (n >= 32 and n <= 126):
                string += chr(n)
        print("Out received message decodes to: {}".format(string))

        radio.stopListening()
        time.sleep(1)

Based on the Arduino code above, the code that shows the data that is transmitted is shown below:

    const char text[] = "Yo wassup, haha";

Based on the Raspberry code above, the codes that decode the received data from Arduino are shown below:

    for n in receivedMessage:
        # Decode into standard unicode set
        if (n >= 32 and n <= 126):
            string += chr(n)

However, these decoding code only works if I transmit string or integer from Arduino to Raspberry Pi. It doesn't work if I transmit float. Since DHT22 records temperature and humidity up until 1 decimal point, it is required for me to transmit float. Can anyone here please teach me how to decode the float values?

Thank you very much.

  [1]: http://invent.module143.com/daskal_tutorial/raspberry-pi-3-wireless-pi-to-arduino-communication-with-nrf24l01/

body:
If you say you only need one digit, why not multiplying your value with 10 (with rounding), transmit it as a 4 byte (unsigned?) integer, and divide by 10 after receiving.

You only need to check if you have little or big endian conversion needed (swapping MSB/LSB 2 byte or single byte). But you see this very fast if you print the values in hex format.


message:
Getting BPM from the given code

I have found code that can blink an LED on Arduino according to Heart Beat. I am using AD8232 as a sensor for Heart Rate.

Code for it is:

    //  Variables
    int PulseSensorPurplePin = 0; // Pulse Sensor PURPLE WIRE connected to ANALOG PIN 0
    int LED13 = 13; // The on-board Arduino LED
    int Signal; // holds the incoming raw data. Signal value can range from 0-1024
    int Threshold = 550; // Determine which Signal to "count as a beat", and which to ingore.

    void setup() {
      pinMode(LED13, OUTPUT); // pin that will blink to your heartbeat
      Serial.begin(9600); // Sets up Serial Communication at certain speed.
    }

    void loop() {
      Signal = analogRead(PulseSensorPurplePin); // Read the PulseSensor's value.
      // Assign this value to the "Signal" variable.
      Serial.println(Signal); // Send the Signal value to Serial Plotter.
      if(Signal > Threshold) {
        // If the signal is above "550", then "turn-on" Arduino's on-Board LED.
        digitalWrite(LED13, HIGH);
      } else {
        digitalWrite(LED13, LOW); //  Else, the signal must be below "550", so "turn-off" this LED.
      }
      delay(10);
    }

My question is: How can I get BPM?

Edited below:

Is this code for BPM correct?

    int x = 0;
    int LastTime = 0;
    bool BPMTiming = false;
    bool BeatComplete = false;
    int BPM = 0;
    #define UpperThreshold 518
    #define LowerThreshold 490
    int LED13 = 44; // The on-board Arduino LED
    int Signal; // holds the incoming raw data. Signal value can range from 0-1024

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

    void loop() {
      int value = analogRead(0);
      if (value > UpperThreshold) {
        if (BeatComplete) {
          BPM = millis() - LastTime;
          BPM = int(60 / (float(BPM) / 1000));
          BPMTiming = false;
          BeatComplete = false;
        }
        if (BPMTiming == false) {
          LastTime = millis();
          BPMTiming = true;
        }
      }
      if ((value < LowerThreshold) & (BPMTiming))
        BeatComplete = true;
        // display bpm
      Serial.print(BPM);
      Serial.println(" BPM");
      x++;
      Signal = analogRead(0); // Read the PulseSensor's value.
      // Assign this value to the "Signal" variable.
      if (Signal > UpperThreshold) {
        // If the signal is above "550", then "turn-on" Arduino's on-Board LED.
        digitalWrite(LED13, HIGH);
      } else {
        digitalWrite(LED13, LOW); //  Else, the signal must be below "550", so "turn-off" this LED.
      }
    }

body:
If you know the interval between heart beats, you can calculate the frequency using the formula: frequency = 1 / time. Now if you take the frequency and multiply it by 60, you should get BPM.

I don't have one of the sensors you are using so I connected a potentiometer to pin A0 to test this code.

        int UpperThreshold = 518;
        int LowerThreshold = 490;
        int reading = 0;
        float BPM = 0.0;
        bool IgnoreReading = false;
        bool FirstPulseDetected = false;
        unsigned long FirstPulseTime = 0;
        unsigned long SecondPulseTime = 0;
        unsigned long PulseInterval = 0;

        void setup(){
          Serial.begin(9600);
        }

        void loop(){

          reading = analogRead(0);

          // Heart beat leading edge detected.
          if(reading > UpperThreshold && IgnoreReading == false){
            if(FirstPulseDetected == false){
              FirstPulseTime = millis();
              FirstPulseDetected = true;
            }
            else{
              SecondPulseTime = millis();
              PulseInterval = SecondPulseTime - FirstPulseTime;
              FirstPulseTime = SecondPulseTime;
            }
            IgnoreReading = true;
          }

          // Heart beat trailing edge detected.
          if(reading < LowerThreshold){
            IgnoreReading = false;
          }

          BPM = (1.0/PulseInterval) * 60.0 * 1000;

          Serial.print(reading);
          Serial.print("\t");
          Serial.print(PulseInterval);
          Serial.print("\t");
          Serial.print(BPM);
          Serial.println(" BPM");
          Serial.flush();

          // Please don't use delay() - this is just for testing purposes.
          delay(50);
        }

Updated answer in response to your comments below:

The sketch is reading the data and sending the data to the serial monitor every 50ms because of the delay(50). What if we changed that to 1000 ms? The serial monitor would update once per second which would be more "human readable". The problem with that idea is for heart rates faster than 60 BPM, the reading would be inaccurate. I don't have a sensor to test with but I'm guessing a 1 second delay would make the code inoperable.

Before we add more complexity to this sketch we really should get rid of that delay. It would be nice to have one "timer" that we could use to update the BPM calculation and a second "timer" to update the serial monitor every second, or half second, or what ever you want it to be.

We can do that without any libraries using millis(). Here is an updated sketch using millis() for timers. This sketch has the blinking of the on board LED added to it. I'm using an Uno so you'll have to change LED_BUILTIN to what ever pin number you are using.

    int UpperThreshold = 518;
    int LowerThreshold = 490;
    int reading = 0;
    float BPM = 0.0;
    bool IgnoreReading = false;
    bool FirstPulseDetected = false;
    unsigned long FirstPulseTime = 0;
    unsigned long SecondPulseTime = 0;
    unsigned long PulseInterval = 0;
    const unsigned long delayTime = 10;
    const unsigned long delayTime2 = 1000;
    const unsigned long baudRate = 9600;
    unsigned long previousMillis = 0;
    unsigned long previousMillis2 = 0;

    void setup(){
      Serial.begin(baudRate);
      pinMode(LED_BUILTIN, OUTPUT);
      digitalWrite(LED_BUILTIN, LOW);
    }

    void loop(){

      // Get current time
      unsigned long currentMillis = millis();

      // First event
      if(myTimer1(delayTime, currentMillis) == 1){

        reading = analogRead(0);

        // Heart beat leading edge detected.
        if(reading > UpperThreshold && IgnoreReading == false){
          if(FirstPulseDetected == false){
            FirstPulseTime = millis();
            FirstPulseDetected = true;
          }
          else{
            SecondPulseTime = millis();
            PulseInterval = SecondPulseTime - FirstPulseTime;
            FirstPulseTime = SecondPulseTime;
          }
          IgnoreReading = true;
          digitalWrite(LED_BUILTIN, HIGH);
        }

        // Heart beat trailing edge detected.
        if(reading < LowerThreshold && IgnoreReading == true){
          IgnoreReading = false;
          digitalWrite(LED_BUILTIN, LOW);
        }

        // Calculate Beats Per Minute.
        BPM = (1.0/PulseInterval) * 60.0 * 1000;
      }

      // Second event
      if(myTimer2(delayTime2, currentMillis) == 1){
        Serial.print(reading);
        Serial.print("\t");
        Serial.print(PulseInterval);
        Serial.print("\t");
        Serial.print(BPM);
        Serial.println(" BPM");
        Serial.flush();
      }
    }

    // First event timer
    int myTimer1(long delayTime, long currentMillis){
      if(currentMillis - previousMillis >= delayTime){previousMillis = currentMillis;return 1;}
      else{return 0;}
    }

    // Second event timer
    int myTimer2(long delayTime2, long currentMillis){
      if(currentMillis - previousMillis2 >= delayTime2){previousMillis2 = currentMillis;return 1;}
      else{return 0;}
    }

The code compile size with delay is 4,732 vs the millis timers at 4,682 (with the LED code removed). Two timers for less than the price of one delay :)

The LED will remain on for the duration of the heart beat reading above the LowerThreshold. If you want to have it on longer or decide how long it should be on for, I won't write the code for you but I will give you a hint. You can copy myTimer1() again and make a third timer.


message:
How can I have the user instantiate an object?

So I'm building a MIDI controller. It has a 16-positions selector that lets the user select a "program": a playlist of commands to send to a MIDI instrument.

A push-switch allows the user to scroll through that playlist, running each command in sequence, one at a time.

The way I'm trying to implement this is as follows:
Playlist is a pure abstract class and each Program is derived from it. Each Program would have their own methods for each step, an array of pointers to these functions and a public playNext() method that loop() could call whenever the push-button is pressed with program.playNext()

I'm stuck at the selection of a program stage. I guess I could have an array of pointers to each program and call *arrayOfPrograms[currentProgram]->playNext()
but that would mean I would have to instantiate all the programs in setup() and keep them alive at all times...

Is there a way I could only instantiate the selected program and still call its playNext() method easily?

Sorry for the noob question. I'm fairly new to this and it gets confusing very quickly ;-) Thanks for your help.

Max

body:
I'm not fully understanding the way your sketch should work.

However, I think what you need is some kind of Controller object.
The controller object instantiates one program. The controller also keeps a Boolean to play the next one (playNext). Once the program finishes, the controller can delete the just played program, checks if the Boolean is set to play the next, instantiate the next program to play and play it.

This results that programs are not depending on each other.


body:
You seem like you are almost there. Allocate the objects using `new` and free with `delete`.

    // Abstract parent
    class Playlist {
        public:
        virtual void playNext() = 0;
        // etc.
    };
    // Derived classes
    class Something : public Playlist
        public:
        void playNext() {
            // your code here
        }
    };
    class SomethingElse : public Playlist
        public:
        void playNext() {
            // your code here
        }
    };
    // More derived classes......

    // A pointer of the current program
    Playlist *play_list = nullptr;

    // A factory function to create a Playlist while also freeing previous
    Playlist * create_playlist(int which_program) {
        // Important - delete old
        delete play_list;
        play_list = nullptr;
        // There are only 16 types, use a switch or if
        switch (which_program) {
            case 1:
                // Create a new one and save in global ptr
                play_list = new Something;
                break;
            case 2:
                play_list = new SomethingElse;
                break;
            // More cases here.....
        }
        return play_list;
    }

[edit]--------------------------

Ok. The issue is that C++ does not have a lot of reflection options. So you can't create a class only by its name (as a string). Here's another solution I came up with. It's not completely automatic as it involves registering each class in `setup`. But I think it's close to what you want:

    class Playlist;  //Forward declaration

    // Each class will have a function to create itself
    typedef Playlist * (*CreateFunc)();

    // The parent class. It also holds a list of all child classes
    // Could probably refactor into 2 separate classes
    class Playlist{
      public:
      // Need virtual dtor
      virtual ~Playlist() {
        delete last_created;
      }

      // Put all the overridable function declarations here
      virtual void playNext() = 0;

      // This has to be called for each child. (See macro below)
      static void register_class(int id, CreateFunc f) {
        all_maps[num_maps].id = id;
        all_maps[num_maps++].f = f;
      }

      // Factory method to instantiate an object
      static Playlist * create_playlist(int id) {
          // Delete old pointer
          if (nullptr != last_created) {
              delete last_created;
              last_created = nullptr;
          }
          for (int i = 0; i < num_maps; i++) {
              // Search the list for name match
              if (id == all_maps[i].id) {
                  // Call the creation func
                  return all_maps[i].f();
              }
          }
          return nullptr;
      }
      protected:
      // A struct to hold the class name and a pointer to the creation function
      struct Map {
        int id;
        CreateFunc f;
      };
      static Map all_maps[32];
      static int num_maps;
      static Playlist* last_created;
    };
    // Static declarations
    Playlist::Map Playlist::all_maps[32] = {{0, nullptr}};
    int Playlist::num_maps = 0;
    Playlist* Playlist::last_created = nullptr;

    // Example child class
    class Child1 : public Playlist{
      public:
      void playNext() {Serial.println("Child1");}

      // Must have this function and it must be static
      static Playlist * create() {return new Child1;}
    };
    // Another example
    class Child2 : public Playlist{
      public:
      void playNext() {Serial.println("Child2");}
      static Playlist * create() {return new Child2;}
    };

    // Helper macro to simplify registering
    #define REGISTER_PLAYLIST(id, name) Playlist::register_class(id, &name::create)

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

      // This must be done for all classes
      REGISTER_PLAYLIST(0, Child1);
      REGISTER_PLAYLIST(1, Child2);

      // Example usage
      Playlist*p = Playlist::create_playlist(0);
      p->playNext();
      p = Playlist::create_playlist(1);
      p->playNext();
    }

    void loop() {

    }

I just whipped this up. Probably room for improvement....


message:
strcat appending multiple times when called in loop

The strcat function is working fine when called for the first time but when the broker goes down and it's attempting to reconnect it is appending the value twice. I am not able to figure out the problem as i am writing C code for the first time.

    void reconnect() {

      while (!client.connected()) {
        const char* cid = clientID.c_str();
        if (client.connect(cid)) {
           const char* sTopic = strcat("clm/",cid);
           client.publish(outTopic, sTopic);
           client.subscribe(sTopic);
        } else {
        // Wait 5 seconds before retrying
        for(int i = 0; i<5000; i++){
          delay(1);
        }
      }
    }
  }

It is called in the loop method

    void loop() {
      if (!client.connected()) {
        reconnect();
      }
    }

The value of sTopic for the first time is `clm/5C:CF:7F:3D:5B:F6` but when the broker restarts and the client connects again it is `clm/5C:CF:7F:3D:5B:F65C:CF:7F:3D:5B:F6`

What could be the reason for the same ?

body:
You have to cat only one string per time. Your assumption is that it performs

    dest = strcat(string_1, string_2)

However, it is:

    dest = strcat(dest, string_1)

So you should use

    char sTopic[256]; // Max possible length

    ...

    strcpy(dest, "clm/");
    strcat(dest, cid);

This will first copy "clm/" to dest, than cid will be concatenated.

(code not tested)

See reference: [reference][1]

  [1]: http://www.tutorialspoint.com/c_standard_library/c_function_strcat.htm


body:
> Appends a copy of the *source* string to the *destination* string.

source

Congratulations, you've broken your string literal. Either stick to using `String` or make sure you allocate a string properly and then concatenate into that.


body:
strcat won't allocate any memory for the new string. So what really happens is that the location where the string constant `"clm/"` is stored gets the id appended.

In other words the second time around it's as if you passed `"clm/5C:CF:7F:3D:5B:F6"` as first parameter.

To fix that you need to supply a proper buffer for strcat to do its work:

    if (client.connect(cid)) {
       char[64] sTopic ={0};
       strcat(sTopic , "clm/");
       strcat(sTopic , cid);


message:
Can I read two PWM signals and output two square waves on an UNO?

My system requires that I read two independent PWM signals (60hz) and output two corresponding square waves. These output square waves vary in frequency according to their corresponding input duty cycle. The output frequencies will vary between 1-60Hz. (outside of tone() range)

I'm planning out the best way to approach this project.
My initial thought is to use the two available external interrupts set to CHANGE to measure the inputs. I believe I'll also need to reference a timer in this routine, to determine the time since the last change.

Unless I'm mistaken, it looks like I will also need a timer interrupt for each output, to control the frequency properly.

The Arduino UNO has 3 timers. timer0: 8bit (used internally), timer1: 16bit, and timer2: 8bit. In short, can I run all of these interrupts in the same code? Will I run out of timers, or can I multitask the timers between my requirements?

Thanks!

body:
Your signals are slow enough that you may not need any timer. You can
just use the Arduino `micros()` function to handle all your timings. Of
course, `micros()` itself relies on Timer 0, but you don't need to
access any timer directly.

I would use the external interrupts in `CHANGE` mode to measure the duty
cycle. For example:

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

    const uint8_t INPUT_0_PIN  = 2;  // digital 2 is also INT0
    const uint8_t OUTPUT_0_PIN = 4;

    // Measured duration of the HIGH level of input 0.
    static volatile uint32_t input_0_high_time;

    // Interrupt handler invoked when input 0 toggles.
    static void on_input_0_change()
    {
        static uint32_t time_rise;             // last time the signal rose
        uint32_t now = micros();
        if (digitalRead(INPUT_0_PIN) == HIGH)  // detected rising edge
            time_rise = now;
        else                                   // detected falling edge
            input_0_high_time = now - time_rise;
    }

    void setup()
    {
        pinMode(INPUT_0_PIN, INPUT);
        pinMode(OUTPUT_0_PIN, OUTPUT);
        attachInterrupt(0, on_input_0_change, CHANGE);
    }

For handling two inputs, you can duplicate everything that has a `0` in
its name and name it with a `1`. If your signal is no slower than
60 Hz, you can also replace all `uint32_t` by `uint16_t` to make
the code slightly faster.

For generating the outputs, do something similar to the Blink Without
Delay example:

    void loop()
    {
        uint32_t now = micros();

        // Determine suitable period for output 0.
        uint32_t input_0_high_time_copy;
        noInterrupts();  // avoid race condition while reading
        input_0_high_time_copy = input_0_high_time;
        interrupts();
        uint32_t output_0_half_period =
                map(input_0_high_time_copy, 0, 16666, 8333, 500e3);

        // Toggle output 0 when needed.
        static uint32_t time_output_0_toggle;
        static uint8_t output_0_state;
        if (now - time_output_0_toggle >= output_0_half_period) {
            time_output_0_toggle += output_0_half_period;
            output_0_state = !output_0_state;  // toggle state
            digitalWrite(OUTPUT_0_PIN, output_0_state);
        }
    }

Again, you can handle two outputs by duplicating the code and replacing
`0` with `1`. Note that you _cannot_ replace `uint32_t` by `uint16_t`,
as it would not work for the slowest frequencies.

**Edit**: Now we may ask the question whether it is possible to use some
timers to make all this more accurate. The answer is yes, you could
achieve maximum accuracy by using four 16-bit timers:

* You could use the input capture function of a 16-bit timer, with the
  prescaler set to 8, to measure the transitions of one of your
  inputs with a resolution of 0.5 µs.
* You could use a 16-bit timer in CTC mode, with the prescaler set
  to 256, to toggle one of your outputs at the desired frequency, with a
  16 µs resolution.

For reference, `micros()` has a resolution of 4 µs. The 16 µs
resolution of the timer-generated output seems poor in comparison, but
the timer has the advantage of having zero jitter.

Now, for doing that that, you would need an Arduino Mega 2560. The Uno
has only one 16-bit timer, so it could help with only one of your two
channels.

There is still something you can do with a single 16-bit timer. Set it
to normal counting mode, with the prescaler at 8, and use it
instead of `micros()` for timing your inputs: in `setup()`

    // Configure Timer 1.
    TCCR1A = 0;          // normal counting mode
    TCCR1B = _BV(CS11);  // clock at F_CPU/8

and in the interrupt handler, you replace `uint32_t now = micros();` by

    uint16_t now = TCNT1;

And now you have `input_0_high_time` (which should also be `uint16_t`)
in units of 0.5 µs.


body:
Your approach is generally sound.

Depending on the square waves you are generating, one timer can generate two pulse train with independent duty cycles but dependent phases.

That leaves two times for measuring the duty cycles of the input pulse train.

But replicating the input pulse trains makes zero practical sense.


message:
Urgent need of help splitting a JSON formatted string received by UDP

I guess that my problems are because I'm new to C, but after spending three evenings without success I thought I'd give it a try to ask here!

I receive a JSON-formatted string in a UDP message. It contains several values that I would like to catch and convert to variables. The string format is like this:

    {
      "U1": 224,
      "U2": 227,
      "U3": 224,
      "I1": 0,
      "I2": 0,
      "I3": 0,
      "P": 0,
      "PF": 0,
      "E pres": 639,
      "E total": 69901578,
      "Serial": "16889379",
      "Sec": 393833
    }

Actually I really only need to get values U1, U2, U3 and I1, I2, I3. I'm grateful for all the help I can get solving this!

Best regards
Per

body:
Two possible approaches:

 1. Tokenize the string using [`strtok()`][1], probably a few levels deep.
This may require you learning quite a bit more about C++, pointers, and character arrays as strings.
 2. An excellent opportunity to use an existing library, such as [ArduinoJSON][2], which abstracts out the difficulties you may encounter if the fields in your JSON string arrive in a different order, etc.

An example of using ArduinoJSON for your case is shown in the documentation (excerpted/adapted from [Decoding JSON][3])

    #include <ArduinoJson.h>

    // [...] other code

    char json[] = "{ \"U1\": 224, \"U2\": 227, \"U3\": 224, \"I1\": 0, \"I2\": 0, \"I3\": 0, \"P\": 0, \"PF\": 0, \"E pres\": 639, \"E total\": 69901578, \"Serial\": "16889379", \"Sec\": 393833 }";

    //
    // Step 1: Reserve memory space
    //
    StaticJsonBuffer<200> jsonBuffer;

    //
    // Step 2: Deserialize the JSON string
    //
    JsonObject& root = jsonBuffer.parseObject(json);

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

    //
    // Step 3: Retrieve the values
    //
    uint16_t    u1 = root["U1"];
    uint16_t    u2 = root["U2"];
    uint16_t    u3 = root["U3"];
    uint16_t    i1 = root["I1"];
    uint16_t    i2 = root["I2"];
    uint16_t    i3 = root["I3"];

  [1]: http://www.cplusplus.com/reference/cstring/strtok/
  [2]: https://bblanchon.github.io/ArduinoJson/
  [3]: https://bblanchon.github.io/ArduinoJson/doc/decoding/


message:
Using Serial as boolean function argument

The following program compiles in the Arduino IDE.

    void doSomething(bool) {}

    void setup() {
      doSomething(Serial);
    }

    void loop() {}

But, as expected, this one doesn't:

    class MyClass {};

    void doSomething(bool) {}

    void setup() {
      MyClass myClass;
      doSomething(myClass);
    }

    void loop() {}
The compiler returns the error `cannot convert 'MyClass' to 'bool' for argument '1' to 'void doSomething(bool)'`

---

Why is it possible to compile the former? Isn't Serial a normal class instance (of `HardwareSerial`)? Does it makes any sense to interpret `Serial` as a bool?

body: `HardwareSerial` defines `operator bool()`, which allows it to be used in a boolean context.


message:
Send HTTP get request from GSM SIM800c and Arduino

I am trying to send Get request from my GSM Module but after connecting to server it is not responding any thing

    #include <SoftwareSerial.h>
    SoftwareSerial myGsm(2,3);
    void setup()
    {
    myGsm.begin(9600);
    Serial.begin(9600);
    delay(500);
    myGsm.println("AT+CGATT=1");
    delay(200);
    printSerialData();
    myGsm.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");//setting the SAPBR,connection type is GPRS
    delay(1000);
    printSerialData();
    myGsm.println("AT+SAPBR=3,1,\"APN\",\"wap.mobilinkworld.com\"");//setting the APN,2nd parameter empty works for all networks
    delay(5000);
    printSerialData();
    myGsm.println();
    myGsm.println("AT+SAPBR=1,1");
    delay(10000);
    printSerialData();
    myGsm.println();
    myGsm.println("AT+SAPBR=2,1");
    delay(10000);
    printSerialData();
    myGsm.println("AT+HTTPINIT");
    delay(2000);
    printSerialData();
    myGsm.println("AT+HTTPPARA=\"URL\",\"http://sensor.somee.com/api/Data/GetData?SensorID=1\"");// setting the httppara,
    delay(1000);
    printSerialData();
    myGsm.println();
    delay(10000);//the delay is important if the return datas are very large, the time required longer.
    printSerialData();
    delay(9000);
    printSerialData();
    delay(1000);
    Serial.println("done ");
    printSerialData();
    }
    void loop()
    {
    }
    void printSerialData()
    {
    while(myGsm.available()!=0)
    Serial.write(myGsm.read());
    }

and the Out put is

    AT+CGATT=1

    OK
    AT+SAPBR=3,1,"CONTYPE","GPRS"

    OK
    AT+SAPBR=3,1,"APN","wap.mobilinkworld.com"

    OK

    AT+SAPBR=1,1

    OK

    AT+SAPBR=2,1

    +SAPBR: 1,1,"10.209.122.68"

    OK
    AT+HTTPINIT

    OK
    AT+HTTPPARA="URL","http://sensor.somee.com/api/Data/GetData?Sen
    done

body:
You haven't instructed the module to make a request yet.
With the AT+HTTPPARA command, you are just configuring the request you want to make. In your case, you just specified the URL you want to call.
Next, you have to send

    AT+HTTPACTION=1

to make the actual request using the HTTP GET method, and then you can read the HTTP response using

    AT+HTTPREAD

Keep in mind that after AT+HTTPACTION you will receive an unsolicited result code in the format

    +HTTPACTION: <Method>,<StatusCode>,<DataLen>

 this will happen after the module will actually do the request and will have the response.


message:
Arduino crashing during serial print for no obvious reason

I've written some Arduino Code which kept crashing and i couldn't find out why. Then i reduced the code as much as i could in order to see the problem.
The reduced code currently doesn't do anything extraordinary except printing some strings over the serial line.

**This is the reduced code:**

    void setup()
    {
      Serial.begin(9600);
      Serial.print("Begin\r\n");
      send_wifi_beacon();
    }
    void loop()
    {
      delay(1000);
    }
    void send_wifi_beacon()
    {
      send_wlan_chip_command("AT+CIFSR");
      Serial.print("notreached"); // this part is never reached
      send_data_over_network(); // can't remove this line otherwise the crash won't happen which is weird since this is never called
    }
    void read_response_from_serial()
    {
      delay(2000);
      Serial.print("==-1\r\n"); // crashes here
    }
    void send_wlan_chip_command(char* command)
    {
      Serial.print("Sending command to wifi module: ");
      Serial.print(command);
      read_response_from_serial();
      Serial.print("Command response: ");
    }
    // this function is never called, since the crash happens before the call, but it can't be removed otherwise the crash won't happen
    // also it can't  be altered then, the crash also will not happen.
    void send_data_over_network()
    {
      char number[3] = "12";
      //char number[3] = "";
      char length_of_payload[20] = "0123456789012345678"; // 20 digits if assuming 64 bit integer is the maximum this code will ever run on
    //  char length_of_payload[20] = "";
      char *command;

      command = malloc(26);
      command = "AT+CIPSSEND";
      strcat(command, number);
      strcat(command, ",");
      strcat(command, length_of_payload);
      send_wlan_chip_command(command);
      free(command);
    }

**This is the according output:**

> Begin Sending command to wifi module: AT+CIFSR==Begin
> Sending command to wifi module: AT+CIFSR==Begin
> Sending command to wifi module: AT+CIFSR==Begin
> Sending command to wifi module: AT+CIFSR==Begin

Which means that the arduino keeps crashing and resetting. This goes on forever.

The weird thing is, if I change the following two lines to: (in the"send_data_over_network" function as in example above)

    char number[3] = "1"; // changed from => char number[3] = "";
    char length_of_payload[20] = "123"; // changed from => char length_of_payload[20] = "0123456789012345678";

**The output now changes to :**

[![exact output][1]][1]

I call this behaviour weird since it shouldn't have any influence on the result because this function(send_data_over_network) is never called in the crash example from before.

**Troubleshooting options i already tried:**

 - Reinstalling Arduino IDE , i tried with mutliple versions 1.8 , 1.6, 1.4. 1.0
 - Different Arduino Boards (Arduino Uno and Arduino Mega)
 - Different Laptops (since i thought maybe it's related to power issues of my laptop)

Maybe it's something obvious and i just can't see it, but i already spent +16h debugging, so help would be really appreciated.

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

body:
This code looks wrong:

      command = malloc(26);
      command = "AT+CIPSSEND";
      strcat(command, number);
      strcat(command, ",");
      strcat(command, length_of_payload);
      send_wlan_chip_command(command);

First you allocate 26 bytes, then a new string is created, which you strcat to it. This happens in memory that is not allocated (or overwrites other data).

Instead of

      command = "AT+CIPSSEND";

use

      strcpy(command, "AT+CIPSSEND");

Also check that 26 bytes is enough, change it to 128 bytes to be sure (check the correct amount you need later).


body:
You are almost certainly running out of memory and have a stack collision with the heap. Dynamic memory allocation and de-allocation is not a good idea when you have less than 2K RAM to work with. If you use malloc() use it only to allocate buffer space and then reuse the buffers. Put your test code entirely in setup and see what happens. Also check the amount of RAM allocated at compile time it may be more than you think.

    char *buf1;
    char *buf2;

    void setup() {
       buf1 = (char *) malloc(10);
       buf2 = (char *) malloc(10);
       .
       .
       // test code here
    }


message:
Reason for warning "avr:build doesn't define a 'build.board' preference" when build.board is explicitly set in boards.txt?

I am trying to set up a custom board under the Arduino IDE, but I can not figure out why I am getting the warning...

    Warning: Board Move38:avr:build doesn't define a 'build.board' preference. Auto-set to: AVR_BUILD

I think am following the recommendations and template in the official spec here...
https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification#boardstxt

My "vendor/maintainer" is `move38` and my platform is `avr`, so the path to the `boards.txt` is...

    Arduino\hardware\Move38\avr\boards.txt

Here is my `boards.txt` that defines the `blink` board...

    blink.name=Blinks Tile
    blink.upload.tool=avrdude
    blink.upload.protocol=avrisp
    blink.upload.maximum_size=15872
    blink.upload.maximum_data_size=1024

    blink.build.core=blinks
    blink.build.board=AVR_Blink

    blink.build.mcu=atmega168pb

    blink.c.extra_flags=-Wextra -flto
    blink.c.elf.extra_flags=-w -flto
    blink.cpp.extra_flags=-Wextra -flto
    blink.ltoarcmd=avr-gcc-ar

    # set F_CPU to 1Mhz for all boards on this platform
    build.f_cpu=1000000L

...which would seem to define `build.board` as `AVR_BLINKS`.

I think am following the recommendations and template in the official spec here...
https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification#boardstxt

...but nonetheless the warning persists.

I am using Arduino IDE version 1.8.3 on Windows.

What am I missing here? Is there something special about the value, format, or position of the `build.board` key that I am missing here?

Thanks!

## More notes

Adding the following lines to a working `boards.txt` file...

    build.name=testname
    build.f_cpu=4000000L
    build.core=blinks
    build.board=AVR_BOARD

Will create a menu entry for a new phantom board called `testname`, but this is not a real board with usable keys. If you compile while that board is selected, you get the warning...

    Using board 'build' from platform in folder: C:\Users\passp\Documents\Arduino\hardware\Move38\avr
    Using core 'arduino' from platform in folder: C:\Users\passp\Documents\Arduino\hardware\Move38\avr
    Warning: Board Move38:avr:build doesn't define a 'build.board' preference. Auto-set to: AVR_BUILD

...despite the fact that the key `build.board` is explicitly defined.

body:
It appears that you can no longer set a global property in the `boards.txt` file. You must set every property individually inside each board ID, even if they are the same for every board in the file. This seems to contradict the documentation that states that...

> The other properties will override the corresponding global properties
> of the IDE when the user selects the board.

Further, if any global key is set directly, then *both* the board specific keys  *and* the global keys are ignored.

So in my above `boards.txt`, setting the the global key `build.f_cpu` at the end of the file seems to cover the `blink.build.board` key and prevent it from being copied to `build.board` when the board is selected. Even if you set the global key `build.board` directly, this setting is ignored.


body:
The line in your boards.txt:

    build.f_cpu=1000000L

created a separate board entry with the board ID `build`, thus the error message:

    Warning: Board Move38:avr:build doesn't define a 'build.board' preference. Auto-set to: AVR_BUILD

From your comment:

    # set F_CPU to 1Mhz for all boards on this platform

and your answer I see that you expected that line to define a global value for the `build.f_cpu` property but the Arduino IDE has no mechanism for doing this in boards.txt and I don't believe it ever has. You need to define the properties for each board individually in boards.txt, where they will override previously defined properties of the same name. However, you can define default property values for the hardware package in your platform.txt just as you attempted to do in boards.txt.


body:
In my case: I erase the board configurations that was with problem in the file boards.txt.
These configurations appears between #### ... board configurations... #####.


message:
Specifying port in Ciao.write

As far as I know, Ciao uses port 80 as the default and I haven't found a way of changing the port it attempts to connect to.

I tried using `"192.168.0.23:8080"` but the `Ciao.write()` seems to timeout after a while. Is there a way to specify the port to use?

P.S I'm using an Arduino Uno WiFi DevEd

body:
You can't. The factory firmware of Uno Wifi is discontinued.

[Uno WiFi and WiFi Link doc][1]

  [1]: https://github.com/jandrassy/arduino-firmware-wifilink/blob/ota/UNOWIFI_DEV_ED.md


message:
Problem with 16x2 LCD using Arduino

I've connected the circuit as shown in
https://www.arduino.cc/en/Tutorial/HelloWorld?from=Tutorial.LiquidCrystal
and I ran the program, but I can't fix this problem:

the LCD seems not to respond correctly: the first row is black and for what concerns the elements of the second, they all have three top lines of pixel high and the others low..

I checked over and over if I made some mistake connecting wires but I haven't found any error..

Is the LCD broken according to you? How can I fix?

Here the photos of the circuit:
https://drive.google.com/open?id=0B2h2zzEgtaqydElrRDVUNGVuWDA

body:
I looked the images you have on Google Drive. On the image called IMG_20170822_233722.jpg, I see you are using a 50k ohm potentiometer to control the display contrast. Normally you would use a 10k ohm potentiometer. Using the 50k will make the adjustment very sensitive and hard to adjust. If you are careful and adjust it slowly, it might work for you.

The other image, IMG_20170822_234242.jpg, clearly shows "poor solder joint" connections on the display. D4 - D6 (especially D5 to D6) look like they could be "shorted" together. I think you could fix them by using Desoldering braid or if you don't have any, you could heat up each connection with your soldering iron then quickly "flick" the display to remove the solder. After you have removed the excess solder from each connection, I strongly recommend applying soldering paste to the connections next. The soldering paste really helps the solder to flow into the connection. Now try re-soldering each connection. I'm not sure what kind of solder or iron you are using but I can tell you what works for me. 25 watt pencil tip soldering iron with 22 gauge / 0.71mm rosin core solder.

I can't tell for sure from the pictures if any of the display pins are shorted together and I don't know if shorting them together will damage the display, Arduino or both.


body: Black first row suggests that the LCD is incorrectly initiated. That's often caused by wrong code or wrong hardware / connection.


message:
Is there a way to power off external devices during deep sleep

I am looking to work with deep sleeping, particularly with the ESP8266 but this question applies to most all micros. I am interested in running the device off of battery power for as long as possible. My solution would be something like a weather station where you know you only want to take a measurement every x minutes. So, I would like to sleep as much as possible in between measurements to extend battery life as much as possible. However, sleeping the microcontroller is one thing. How about when you have some sensors that piggyback off of the battery too. No need for those to be powered while the micro is sleeping and not taking a measurement.

Similar to this, I was thinking about reading the battery level. There are plenty of examples on how to do this online using a voltage divider (if necessary) and running the battery into analog input. This also draws from the battery while sleeping.

So, is there a way I can run all of these external sensors/devices through a transistor or something with low power draw when off and turn it all one when the device wakes up from sleep?

Thanks!

body:
I made a [temperature and humidity sensor](http://www.gammon.com.au/forum/?id=12106) which runs off 3 x AA batteries. It lasts a couple of years without changing the batteries, and writes to an SD card.

The power-control part of the circuit is here:

[![Power management][1]][1]

The general idea is that Q1 is used to turn on/off a "switched 5V" rail (5V_SW) to which are attached most of the peripherals. This is done in conjunction with power-down sleep mode on the processor. A watchdog timer wakes the processor every 8 seconds to check to see if it is time to take another reading.

---

The full schematic is:

[![Full schematic][2]][2]

---

I think I've changed the batteries once since making it in 2013.

  [1]: https://i.stack.imgur.com/IkEbk.png
  [2]: https://i.stack.imgur.com/v8SCY.png


message:
How to read data from an NI DAQ?

I'm using an Arduino to control an experimental setup and read analogue signals from some sensors. But there are [other sensors][1] for which I need a DAQ for. I have a National Instrument USB-6259. On my PC I use LabView or NI SignalExpress to read data from DAQ connected via USB. Considering that I want the read data from different sensors to be synced, I was wondering if I could somehow read the DAQ directly on the Arduino?

Some other points:

 1. I also have Arduino Ethernet Shield, if required.
 2. The final goal is to have logged data synced so out of the box solutions are also acceptable for me.
 3. If I'm not mistaken there are some versions of Arduino which you can install Linux on, just like a Rasppbery pi. There are even OSes for normal Arduino boards. There is a [Low Cost USB DAQ Driver for use with Raspberry Pi for NI USB-6008/6009 devices][2]. Is it possible to install this driver on Arduino?
 4. I prefer not use a Raspberry pi because analogue/PWM read and write there is not as straight forward. So if there are other boards which are as easy as an Arduino with an OS compatible with current driver please suggest.

  [1]: http://www.ati-ia.com/products/ft/ft_models.aspx?id=Mini45
  [2]: https://forums.ni.com/t5/NI-Labs-Toolkits/Low-Cost-USB-DAQ-Driver-for-use-with-Raspberry-Pi/ta-p/3533944

body:
Unlikely.

First you would need a USB shield to be able to plug it in.

Second you would have to reverse engineer and then reimplement the proprietary protocols that device uses in order to get the Arduino to control the device.


body:
The main answer for your question is already given by Majenko, and is "no". These protocols are much more complicated than you can think, so no way.

However, if I correctly interpret your point 2 (which is The final goal is to have logged data synced so out of the box solutions are also acceptable for me), you don't need to do this. Just use your PC (or raspberry) to collect all the data and make a synchronization inside it. For instance, connect the arduino to the PC via bluetooth, add a serial connection in the labview program and then send all the data the arduino records to the serial peripheral; you will get all the infos in the labview program.

If for any reason this is not possible, you can use a common signal to sync the acquisitions. For instance, when you start the measurements you let the DAQ generate a long pulse (let's say 100ms), then every second or minute it will generate a shorter pulse (let's say 10ms); the arduino also records this signal, so you will have a way to sync acquisitions. Or you can do the opposite: the arduino generates and the DAQ records.

To sum up, the arduino is not capable of doing what you request, but maybe what you need is not what you asked for...


message:
Sharing a Digital Pin / What to do when two components need a specific Digital Pin?

I am new to the world of Arduino and picked up an Uno R3. I have run into a situation where I have two components that specifically need digital pin 11, 12, 13 as specified by the libraries used to interact with them.

Each component also uses other pins that were able to be specified as different with the libraries but for those 3 the libraries say I cannot change them. What do you do in a situation like this? Is it somehow possible for two components to use the same pins? Any help is appreciated.

The two libraries I am trying to use are https://github.com/nRF24/RF24 (Wifi Receiver & Transmitter using component nrf24l01+) and https://github.com/steigeia/RFID_UNID_LOGGER/blob/master/libraries/AddicoreRFID/AddicoreRFID.h (RFID Reader/Writer using component RC522).

body:
It seems probable that both libraries use SPI which connects to the SPI hardware on the chip via those pins. See https://arduino.stackexchange.com/questions/16348/how-do-you-use-spi-on-an-arduino/

You haven't said what libraries, nor what hardware, but you possibly may be able to share those pins between the two devices. They would both need *separate* slave select pins. Often D10 (digital pin 10) is used as a default for slave select.

Another possible solution is to use "bit-banged" SPI for one device. I have a [page on my forum](http://www.gammon.com.au/spi) about SPI which includes a bit-banged software implementation.

The library is at <https://github.com/nickgammon/bitBangedSPI> and is quite short.


message:
How to record steps a stepper motor takes and how to rotate it backward and forward with analog input?

I am trying to control a stepper motor's movements with a pressure sensor input (0 to 5 V digital). For example, if the input is 4 V then the stepper motor should move forward 4 steps. If the input is 3 V then it should come backward 1 step. Please suggest a command in Arduino to keep record of the previous sensor value and steps taken by stepper motor.

This is the code I have written for simple rotation of the motor:

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

    const int stepPin = 8;
    const int dirPin = 9;
    int sensorValue=A0;
    int i;

    void setup() {
      Serial.begin(9600);
      pinMode(sensorValue, INPUT);
      pinMode(stepPin, OUTPUT);
      pinMode(dirPin, OUTPUT);
    }

    void loop() {
      sensorValue = analogRead(A0);
      float voltage = sensorValue * (5.0 / 1023.0);
      if(voltage==1) {
        digitalWrite(dirPin, HIGH);
        for(int x = 0; x < 200; x++) {
          digitalWrite(stepPin, HIGH);
          delayMicroseconds(5000);
          digitalWrite(stepPin, LOW);
          delayMicroseconds(5000);
        }
        delay(1000); // One second delay
      }
      digitalWrite(dirPin, LOW);
      for(int x = 0; x < 200; x++) {
        digitalWrite(stepPin, HIGH);
        delayMicroseconds(500);
        digitalWrite(stepPin, LOW);
        delayMicroseconds(500);
      }
      delay(1000);
      while(1);//only once
    }

body:
I analyzed your code written in the comment and assuming that it works I prepared a modification that should prevent the motor from moving when the sensor is pressed the same way all the time. The noise values you have to adjust yourself. Make it as low as you can.

I cannot test this code, because I don't have your hardware. Treat it as pseudo code.

    #include <Stepper.h>
    // change this to the number of steps on your motor
    #define STEPS 200
    #define NOISE 0.1

    Stepper stepper(STEPS, 8, 9);
    int previous = 0;
    void setup() {
      // set the speed of the motor to 30 RPMs
      stepper.setSpeed(100);
    }

    void loop() {
      // get the sensor value
      float val = analogRead(A0);

      float difference = previous - val;

      if(difference < -NOISE || difference > NOISE)
      {
        stepper.step(val - previous);
        previous = val;
      }
    }


message:
upload.tool not used in custom boards.txt?

I've created a custom board in `boards.txt` and changed the `upload.tool` to a nonsense value, and yet when I do an upload the IDE still calls `avrdude`.

For example, In boards.txt I've changed the line...

    tile.upload.tool=avrdude

...to...

    tile.upload.tool=nogood

...and added these lines to platform.txt...

    # NOGOOD programmer

    tools.nogood.cmd="dir"
    tools.nogood.program.pattern="dir"
    tools.nogood.upload.pattern="dir"

...and reloaded the IDE and hit upload.. and it still runs AVRDUDE.

(Note that my board ID is `tile`)

I've verified that I am editing the correct boards.txt by changing the `cores` key to `nogood` and this does generate an error.

Is `boardid.upload.tool` not the right place to change the recipe called when upload is hit?

How/where does the `boardid.upload.tool=toolname` key in boards.txt get mapped to the `tools.toolname.upload.pattern` key in platforms.txt?

I am using Arduino IDE version 1.8.3.

The custom boards.txt is in the directory `Arduino\hardware\Move38\avr`.

This full custom platform package is here...

https://github.com/bigjosh/Move38-Arduino-Platform

Thanks!

body:
Custom tools for the Arduino build process are documented in the Boards Manager Package Index spec here...

https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.6.x-package_index.json-format-specification#tools-definitions

So it would seem that it i not possible to use custom tools with a manually installed board since there is no package index file.


body:
From https://github.com/bigjosh/Move38-Arduino-Platform#programmers:
>Since there is no bootloader in a tile, all code must be programmed rather than downloaded.

When you do an "Upload Using Programmer", the tool is specified in the `{programmerID}.program.tool` property in programmers.txt. The `{boardID}.upload.tool` value is only used for a standard upload.

Since programmers.txt is not in your hardware package, this makes it very inconvenient to customize. What's worse is that the platform.txt associated with the selected programmer is used, rather than the one in your hardware package, for "Upload Using Programmer". For this reason, [some popular hardware packages include their own copies](https://github.com/MCUdude/MightyCore/commit/777c5d6a373180c36d08c885c66690ccf2bd5a09#diff-d277425b7f2c4e00ec2a6a653169aa21) of all standard programmers. The downside of this is it really clutters up the **Tools > Programmer** menu if you have multiple of these packages installed.


body:
If you leave the `protocol` unset in the `boards.txt`, then the current version of the Ardunio IDE (1.8.12) will then use the `program` recipe rather than the `upload` recipe in `platform.txt`. The `program` recipe can use the `{protocol}` key to get the programmer selected in the IDE menus.

Relevant source in Arduino IDE `SerialUploader.java`...

    if (usingProgrammer || prefs.get("upload.protocol") == null) {
      return uploadUsingProgrammer(buildPath, className);
    }


message:
How to compare two string?

I meet a terrible problem. I can't compare two string!

My job is simple, every 1ms use `SoftwareSerial read_card(2, 3);`to check if i read a id card.And don't read a card twice.Here are my code:

    bool CardReader::check()
    {
     String str= read_card.readString();
     if (str.length() == 0 ) return false;
     //Log("card:%s", str);
     Serial.println("card_id");
     Serial.println(str);
     Serial.println(card);
     Serial.print("cmp:"); Serial.println(str == card);
     if (str.length() == card.length())
     {
      uchar *p1 = (uchar*)str.c_str(), *p2 = (uchar*)str.c_str();
      for (int i = 0; i < card.length(); i++)
       if (p1[i] != p2[i])
        break;
      return false;
     }
     card = str;
     return true;
    }

Let's see output:

    card_id
     Rq
     僐R
    cmp:1

The hex are:

    00 01 52 71 02
    00 83 52 52 00

Why the two string is equal?

Bugs are fixed.If string begin with '\0',`==` can't work and `=` can't work either.

    bool CardReader::check()
    {
     String str = read_card.readString();
     if (str.length() == 0) return false;
     if (str.length() == card.length())
     {
      uchar *p1 = (uchar*)str.c_str(), *p2 = (uchar*)card.c_str();
      for (int i=0; i < card.length(); i++)
      {
       Log("%d:%d", p1[i],p2[i]);
       if (p1[i] != p2[i])
        goto find_card;
      }
      return false;
     }
    find_card:
     for(int i=0;i<5;i++)
      card[i]=str[i];
     return true;
    }

body:
Because both strings are empty. In fact, calling the method c_str() will give a an array, which has at its first position ([0]) the null terminator (0x00 or '\0'). What follows the 0x00, is just rubbish.

In fact, check the card length, it will be 0.

(btw, there are some bugs in the code too. It always return false if the string have the same length, and it will always return true otherwise. EDIT: following the Nick Gammon's answer I also noticed that you get the pointer of the same string :). I corrected also this).

I think the code should be rewritten to:

    if (str.length() == card.length())
    {
        uchar *p1 = (uchar*)str.c_str(), *p2 = (uchar*)card.c_str();
        for (int i = 0; i < card.length(); i++)
            if (p1[i] != p2[i])
                return false;
    }
    else
        return false;
    return true;

EDIT:

I add there what I wrote in the comments, for future reference, and explained in details.
The problem lies on the String class, which on one hand, it allows adding '\0' characters, through the method concat(char*), but on the other, it uses the strcmp (and other C standard functions) to perform compare between strings. This leads to unpredictable results. Maybe this is a bug in the String class.

In particular, SoftwareSerial extends Stream. Stream::readString() (which is used in the program to get str), is implemented as follows:

    String Stream::readString()
    {
      String ret;
      int c = timedRead();
      while (c >= 0)
      {
        ret += (char)c;
        c = timedRead();
      }
      return ret;
    }

The line `ret += (char)c;` uses operator +=, which is implemented in WString.h as:

    String & operator += (char c)   {concat(c); return (*this);}

**Note that readString() also allows adding any non negative value of c, including 0, i.e. '\0' - see while (c >= 0) in its code above**

In turn, concat(char c) is implemented in WString.cpp as:

    unsigned char String::concat(char c)
    {
     char buf[2];
     buf[0] = c;
     buf[1] = 0;
     return concat(buf, 1);
    }

And concat(const char *cstr, unsigned int length) is implemented as:

    unsigned char String::concat(const char *cstr, unsigned int length)
    {
     unsigned int newlen = len + length;
     if (!cstr) return 0;
     if (length == 0) return 1;
     if (!reserve(newlen)) return 0;
     strcpy(buffer + len, cstr);
     len = newlen;
     return 1;
    }

In the above method, length (instead of strlen) is used to determine the length of the string to add, and the new length is calculated using it:

    newlen = len + length;

**That's the bug**: you can add a '\0' char to the string, and this will also result in an increased length of the string. They should have checked if length <= strlen(cstr), before performing this concat operation.

Now, if you call the method String::equals or use the operator == (it is the same, as it is defined in WString.h as  `unsigned char operator == (const String &rhs) const {return equals(rhs);}`), you call this code:

    unsigned char String::equals(const String &s2) const
    {
     return (len == s2.len && compareTo(s2) == 0);
    }

Which, in turn, calls:

    int String::compareTo(const String &s) const
    {
     if (!buffer || !s.buffer) {
      if (s.buffer && s.len > 0) return 0 - *(unsigned char *)s.buffer;
      if (buffer && len > 0) return *(unsigned char *)buffer;
      return 0;
     }
     return strcmp(buffer, s.buffer);
    }

And strcmp ends its compare operation if it first encounters a null operator (or when a compare mismatch occurs).

Therefore in your case, readString() added a null character to the "ret" String at first, and then some other characters. This created a String which begins with '\0'. Such string is equal to any other string beginning with a '\0', regardless what follows '\0'. But if you call length(), you'll get "len" (which String::concat() does not correctly calculate, and it will be non 0), as you can find in WString.h:

    inline unsigned int length(void) const {return len;}

Disclaimer: future versions of WString.h and WString.cpp could have fixed this bug.


body:
> Why the two string is equal?

            uchar *p1 = (uchar*)str.c_str(), *p2 = (uchar*)str.c_str();

Both p1 and p2 point to the same string so of course they will always compare equal.

---

Do you mean:

    if (str == card)
       // do something


body:
Try strcmp()

See if  it works.


message:
RFID does not respond after Ethernet.begin(mac, ip) initialization

Good day, I have this problem with my simple project. I have a database with all RFID number of employee. What I want to do is to use an rfID to check if it is registered in the database. If it is, it would return a value of 1 else would be a value of 0.

I tried with arduino HanRun Ethernet shield. I was able to get a response from the php web server to the serial monitor. Tried the seeedrfid it successfully get the rfcard number. However, when i tried to combine the two, it would hang on Ethernet.begin(mac, ip) initialization. My code is below.

    #include <Ethernet.h>
    #include <SoftwareSerial.h>
    #include <SeeedRFID.h>

    #define RFID_RX_PIN 10
    #define RFID_TX_PIN 11

    SeeedRFID RFID(RFID_RX_PIN, RFID_TX_PIN);

    char state = '0';
    char c;
    byte mac[] = {0x60, 0xF8, 0x1D, 0xBA, 0x1D, 0x52};
    IPAddress ip(192, 168, 20, 228);

    EthernetClient client;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      Serial.println("Serial set up");

      Ethernet.begin(mac, ip);
      Serial.print("My IP Address: ");
      Serial.println(Ethernet.localIP());
    }

    void loop() {

      long rfID;
      // put your main code here, to run repeatedly:

      if (RFID.isAvailable()) {
        rfID = RFID.cardNumber();
        Serial.println(rfID);
      }
    }

Serial.println(rfID) is not executed unless I remove the Ethernet.begin(mac, ip). Can anybody point me to the right direction?

body: The Arduino Ethernet shield uses pins 4, 10,11,12,13. You have a conflict with the RFID pins.


message:
lcd not display

is it my coding wrong or my board have problem because my lcd does not display anything.
here my coding

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

    // set the LCD address to 0x27 for a 20 chars 4 line display
    // Set the pins on the I2C chip used for LCD connections:
    //                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
    LiquidCrystal_I2C lcd(0x27, 6, 2, 3, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C add 27 / 3F

    void setup()   /*----( SETUP: RUNS ONCE )----*/
    {
      Serial.begin(9600); //
      lcd.begin(16,2);         // initialize the lcd for 16 chars 2 lines, turn on backlight
      lcd.backlight();

    }

    void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
    {

      lcd.setCursor(0, 0);
      lcd.print("HELLO");

      delay(200);

      lcd.setCursor(0, 1);
      lcd.print ("HI");

      delay(2000);

      lcd.clear();

      delay(2000);

      lcd.setCursor(0, 0);
      lcd.print("NICE");

      delay(200);

      lcd.setCursor(0, 1);
      lcd.print ("GOOD ");

      delay(2000);

      lcd.clear();

      delay(2000);
    }

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

this is how i wirring it. what should i do?

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

body:
the black bars indicate that the lcd isn't correctly initialized.

check the hardware / connection and make sure that your software initializes it correctly.


body:
Well, I have the hardware, so I tested OP's configuration. It didn't work for me either. Same OP's problem.

The cause is the I2C address we are using (0x27). That's not my LCD address, probably neither your address. It's 0x3F in my case.

I discovered it I2CScanner, a short sketch that lists all I2C devices connected at that moment. So, run it (with the LCD connected) and watch with Serial Monitor for the address of your LCD.

Then replace all references to 0x27 (like `lcd(0x27, 16, 2)`) with your real address. Just change one value for the other.

[![Hello World][1]][1]

This is I2CScanner

    //
    // Version 1
    //    This program (or code that looks like it)
    //    can be found in many places.
    //    For example on the Arduino.cc forum.
    //    The original author is not know.
    // Version 2, Juni 2012, Using Arduino 1.0.1
    //     Adapted to be as simple as possible by Arduino.cc user Krodal
    // Version 3, Feb 26  2013
    //    V3 by louarnold
    // Version 4, March 3, 2013, Using Arduino 1.0.3
    //    by Arduino.cc user Krodal.
    //    Changes by louarnold removed.
    //    Scanning addresses changed from 0...127 to 1...119,
    //    according to the i2c scanner by Nick Gammon
    //    http://www.gammon.com.au/forum/?id=10896
    // Version 5, March 28, 2013
    //    As version 4, but address scans now to 127.
    //    A sensor seems to use address 120.
    // Version 6, November 27, 2015.
    //    Added waiting for the Leonardo serial communication.
    //
    //
    // This sketch tests the standard 7-bit addresses
    // Devices with higher bit address might not be seen properly.
    //

    #include <Wire.h>

    void setup()
    {
      Wire.begin();

      Serial.begin(9600);
      while (!Serial);             // Leonardo: wait for serial monitor
      Serial.println("\nI2C Scanner");
    }

    void loop()
    {
      byte error, address;
      int nDevices;

      Serial.println("Scanning...");

      nDevices = 0;
      for(address = 1; address < 127; address++ )
      {
        // The i2c_scanner uses the return value of
        // the Write.endTransmisstion to see if
        // a device did acknowledge to the address.
        Wire.beginTransmission(address);
        error = Wire.endTransmission();

        if (error == 0)
        {
          Serial.print("I2C device found at address 0x");
          if (address<16)
            Serial.print("0");
          Serial.print(address,HEX);
          Serial.println("  !");

          nDevices++;
        }
        else if (error==4)
        {
          Serial.print("Unknown error at address 0x");
          if (address<16)
            Serial.print("0");
          Serial.println(address,HEX);
        }
      }
      if (nDevices == 0)
        Serial.println("No I2C devices found\n");
      else
        Serial.println("done\n");

      delay(5000);           // wait 5 seconds for next scan
    }

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


message:
How is interaction with CDC device with no interface endpoints working?

I'm working on uploading to [Digispark board][1]. It uses [micronucleus][2] bootloader and i can see [uploader code][3]. I've modified it a bit to see interfaces and endpoints count:

        nucleus->device = usb_open(dev);

        // added by me - start
        int interfaces, endpoints, j;
        struct usb_interface_descriptor *interface = NULL;

        interfaces = dev->config->bNumInterfaces;
        fprintf(stderr, "Found interfaces: %i\n", interfaces);

        interface = &(dev->config->interface[0].altsetting[0]);
        fprintf(stderr, "Endpoints: %i\n", interface->bNumEndpoints);
        // added by me - end

        // get nucleus info
        unsigned char buffer[4];
        int res = usb_control_msg(nucleus->device, USB_ENDPOINT_IN| USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0, 0, 0, (char *)buffer, 4, MICRONUCLEUS_USB_TIMEOUT);

I wonder how it's working because interface #0 has no endpoints:

    $./micronucleus --type intel-hex /tmp/Start.ino.hex
    > Please plug in the device ...
    > Press CTRL+C to terminate the program.
    Found interfaces: 1
    Endpoints: 0
    > Device is found!
    connecting: 40% complete
    > Device has firmware version 1.6
    > Available space for user applications: 6012 bytes
    > Suggested sleep time between sending pages: 8ms
    > Whole page count: 94  page size: 64
    > Erase function sleep duration: 752ms
    parsing: 60% complete
    > Erasing the memory ...
    erasing: 80% complete
    > Starting to upload ...
    writing: 100% complete
    >> Micronucleus done. Thank you!

Usually i expect interface to have 2 endpoints (in & out from [usb.h][4]):

    #define USB_ENDPOINT_IN   0x80
    #define USB_ENDPOINT_OUT  0x00

Can anyone explain me how `usb_control_msg(nucleus->device, USB_ENDPOINT_IN| USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0, 0, 0, (char *)buffer, 4, MICRONUCLEUS_USB_TIMEOUT);` is working without endpoint?

  [1]: http://digistump.com/products/1
  [2]: https://github.com/micronucleus/micronucleus
  [3]: https://github.com/micronucleus/micronucleus/blob/master/commandline/library/micronucleus_lib.c
  [4]: https://github.com/libusb/libusb-compat-0.1/blob/master/libusb/usb.h

body:
Micronucleus uses control transfers to upload code (it's not a CDC device). You don't need an endpoint for control transfers - they use the implicit endpoint 0 that is always present whether you define one or not.

You only need to define endpoints for interfaces that want to communicate using bulk, interrupt or isochronous transfers.

    Bus 003 Device 073: ID 16d0:0753 MCS Digistump DigiSpark
    Device Descriptor:
      bLength                18
      bDescriptorType         1
      bcdUSB               1.10
      bDeviceClass          255 Vendor Specific Class
      bDeviceSubClass         0
      bDeviceProtocol         0
      bMaxPacketSize0         8
      idVendor           0x16d0 MCS
      idProduct          0x0753 Digistump DigiSpark
      bcdDevice            1.02
      iManufacturer           0
      iProduct                0
      iSerial                 0
      bNumConfigurations      1
      Configuration Descriptor:
        bLength                 9
        bDescriptorType         2
        wTotalLength           18
        bNumInterfaces          1
        bConfigurationValue     1
        iConfiguration          0
        bmAttributes         0x80
          (Bus Powered)
        MaxPower              100mA
        Interface Descriptor:
          bLength                 9
          bDescriptorType         4
          bInterfaceNumber        0
          bAlternateSetting       0
          bNumEndpoints           0
          bInterfaceClass         0 (Defined at Interface level)
          bInterfaceSubClass      0
          bInterfaceProtocol      0
          iInterface              0
    Device Status:     0x18c0
      (Bus Powered)
      Debug Mode

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

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


message:
Arduino and Optoisolators

I am looking for an efficient (and safe) way to use the Arduino to switch a higher voltage device off and on. The first option would be a relay, but they are fairly bulky. I was wondering if I should use an Optoisolator instead ?

Here is a link to the Data sheet for the Optoisolator I am using..

http://www.everlight.com/file/productfile/el817.pdf
I think (if I am reading it correctly) it expects an input voltage of 1V at about 20mA ?

However, I think it may be more involved than I originally thought. Here is a sort of simulation of what I am trying to achieve.
http://tinyurl.com/y9xd7lzb

As you can maybe tell, I am using a voltage divider to reduce the output from the arduino (from 5V to 1V).
My concerns are ..

1. Is this the best approach ?
2. Is it efficient ?
3. are there any problems I should be aware of ? Precautions I need to take ?
4. Is the voltage divider a good approach to feed the input to the Optoisolator ?

Also, efficiency is an issue as the Arduino (probably a Nano) will be running off batteries.

The target device is a 20V DC motor. I am a novice when it comes to electronics, so I would be grateful of any help or advice you can give.

Many thanks..

Dave.

body:
> Is this the best approach ?

Not really, no.

> Is it efficient ?

No, far from it.

> are there any problems I should be aware of ? Precautions I need to take ?

You don't want a voltage divider to power an opto-isolator. An opto-isolator won't be powerful enough to cope with the motor current. You need flyback protection.

> Is the voltage divider a good approach to feed the input to the Optoisolator ?

No, definitely not.

Unless you require galvanic isolation all you need is a simple NPN transistor or N-channel MOSFET circuit:

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

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

<!-- End schematic -->


body:
your optocoupler's 2ndary side isn't powerful enough to switch a load.

use the 2ndary side to switch a switcher, instead.


message:
Yet another display 16x2 not working with arduino

I found hundreds of questions about display not working with arduino.
However, no matter how trivial this looks like I am having the same problem I cannot understand by reading the other posts.

I have an Arduino micro connected to a display from the adafruit kit

RGB LCD SHIELD KIT W/ 16X2 CHARACTER DISPLAY

I haven't been able to understand whether positive or negative, but I think from the picture is RGB positive.

I have connected everything as shown in the diagram in this page:

[LCD "Hello World!"][1]

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

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

Obviously changing the pins as I have

    RS at 8
    E at 7
    d4 = 12
    d5 = 11
    d6 = 10
    d7 = 9;

The potentiometer changes the contrast, if I saturate it I can see the black boxes.

In the code put this as

    const int rs = 8, en = 7, d4 = 12, d5 = 11, d6 = 10, d7 = 9;
    LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

I checked with the multimeter whether the soldering is good and it carries the signal at the end of the wires.

and the rest as the example in the link,

This is my mess (please ignore the other arduino and the thermocople which is not connected, the other orange wire goes to GND of the Arduino).

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

Any ideas that might help?

  [1]: https://www.arduino.cc/en/Tutorial/HelloWorld
  [2]: https://i.stack.imgur.com/koS2x.png
  [3]: https://i.stack.imgur.com/7L1vz.png
  [4]: https://i.stack.imgur.com/rUJKd.jpg

body:
1. disconnect the E line, power up the system and adjust the contrast so you see 1 black bar on the first line;

2. reconnect the E line and see if your code is working.

3. go from there.


message:
Storing a counter to EEPROM - how to extend the life?

I am building a circuit that has a button, which when pressed, should increment a counter. I want to store this counter so that when I power off my circuit, it can be read when I power it back on. However, I am worried about the lifetime of the EEPROM - apparently it is only rated to handle 100k writes.

I am using an Adafruit Trinket Pro. Should I cycle my writes through different addresses so as not to write to a single cell over and over? What other strategies are there? I don't expect to be pressing the button many times in a short period of time - maybe at most one press per minute.

Is there some other external storage option I should look at? I really don't want my little project to die randomly one day because I've exceeded ~100k button presses!

body:
If possible use a combination of wear-leveling like algorithm (as pointed out by Mikael Patel) and an power-down driven interrupt, to save onto EEPROM only when needed. At reset, load the last keypress count into a variable in RAM. Increment that variable in RAM on keypress, and save it to EEPROM only when a power down occurs (i.e. the interrupt is triggered). Optionally, when power down occurs, make sure to save the variable only if the new counter actually differs from the old value (i.e. if there actually were keypresses).

To implement the power-down driven interrupt use the built-in comparator to monitor a Vin (use a resistor divider!) against the internal Vref, and use the analog comparator interrupt to save the value. Remember to put enough capacitance between +5V and gnd, to make sure your arduino has enough time to save the state.

Alternatively, if you can afford errors (which might accumulate over time, and lead to a huge underestimation), save the value to EEPROM only every n keypresses.


body:
Cycling through the EEPROM is possible.

Is that button capable to last more than 100k presses ?

A button press every minute ? Really ? Is that during working hours ? That would take about year to get near the 100k writes (5 days per week, 8 hours per day, every minute).

If you want to count more than 100k key presses, then you probably store it in a 32-bit integer. That is 4 bytes. That means that when the Arduino is turned off while in the middle of writing that number to the EEPROM, that number is corrupted and lost forever.

With 1k EEPROM, you have 256 positions for the 32-bit integer. That means you can handle 25 million key presses.

My suggestion would be to store each new value of the 32-bit integer to the next location (circular). At startup you need code that interprets the numbers to find the last one and ignores a bad one and can handle a new Arduino with cleared EEPROM and even an Arduino that was used by you to develop the code. That means you need a command to clear the EEPROM.


body:
`maybe at most one press per minute.`

That's great! You can just make some sort of timer to save every 2 or 3 minutes automatically. You said `at most`, so that should work. Here is example of code that can allow you to do so!

    int cycleCnt = 0;    //Counter to count cycles
    int cnt = EEPROM.read(0);         //Your press counter
    bool currentlyCounting = false;   //Boolean to store if we are counting now or not
    bool pressedBefore = false;

    void loop() {
      if (digitalRead(button_pin) == HIGH) {    //You are holding the button
        if (!pressedBefore) {                   //And you didn't press it before
          //Here you do something you need with button
          currentlyCounting = true;       //After you pressed the button, we are starting to count time
          cycleCnt = 0;                        //and reset current counter (which would save us EEPROM writes!)
          cnt++;

          pressedBefore = true;                 //Mark button to be pressed so you don't do same code more then one time
        }
      }
      else pressedBefore = false;               //Mark, that you've unpressed the button

      delay(50);      //Delay in 50 mil won't affect speed of your button press, but it will allow us to count time
      if (currentlyCounting) cycleCnt++;          //Count cycles (every 50 mil)

      if (cycleCnt == 20 * 120) { //20 - amount of loop cycles to wait for one second. 120 - seconds in 2 minutes
        cycleCnt = 0;
        EEPROM.write(0, cnt);
        currentlyCounting = false;
      }
    }

This might help you as well!

In case I misunderstood you and you meant "1 minute is the highest delay time beetween presses" then you should save automatically every half of minute or so


body: Use brown out detection. Keep the count in ram until the mcu is losing power - only then save it to eeprom. Read the datasheet on bor.


message:
How can i change by esp8266 baudrate, as I accidentally changed the baudrate to something else(which I dont remember)?

//In order to connect,

    SoftwareSerial esp8266(2,3);

    // the TX pin of esp8266 is connected to pin 3 of
    // arduino uno and RX pin is connected to 2
    // we need to pass baud rate to begin function

    void setup()
    {
      Serial.begin(115200);
      esp8266.begin(???); // what should i do in order to make it work?
    }

What should i do in order to make it work?

body:
I encountered a similar situation where I accidentally set the baudrate to 8000 with the AT commands.

Thankfully I remembered the baud rate I set, so I used PuttY to create a serial communication with the port with the weird 8000 baud rate and changed the baud rate back to 9600.

The method can be found here: http://flower-platform.com/2015/12/16/esp8266-with-at-commands-connect-from-pc-with-putty/

The AT command I used to change the baud rate:
`AT+UART_DEF=9600,8,1,0,0`


message:
how fast does loop() run in Arduino

Hi I am using `Arduino Nano` to gamify my experience on Unity3D. I know that `Update()` in Unity3D runs every frame per second but I because I'm not an electronics guy I don't know how `loop()` function runs on Arduino.

Does it depends on number of CPU cycles(or micro processor chip in case of Arduino) or what? Please explain. I facing some lags in my game. I can fix them only if know how is loop() function running on Arduino

There ain't a lot of information about `loop()` in arduino [documentation][1]

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

body: It depends on what's in the loop. From a few clock cycles to infinite hang.


body:
Loop runs as long as loop needs to run.

Instructions in a CPU run sequentially. The more instructions there are the longer it takes to run.

The more code you put in loop the longer loop will run.

There are two ways to know how long each iteration of loop will take:

1. Profiling: Actively time each iteration of loop, though be warned, the act of timing will affect the amount of time taken.
2. Cycle counting. Compile the source into assembly and total up the number of clock cycles needed for all the instructions (including calls to functions). Arduous for small loops, a gargantuan task for anything else.

Also note that many external factors can affect how long loop() takes to run - such as serial communication speed, etc.


body:
the instructions between the end of loop() and the next run of it are a ret, jmp and a call.

You can consider the main function to be effectively:

    void main(){

        init();
        while(1) loop();

    }

Though in reality there is some setup done before `init()` to make `millis()` and such work.


body:
try looking up arduino functions
micros()
and
delayMicroseconds()
If you might need your loop to wait longer than 16000 microseconds then also look up the other delay() function which does milliseconds.

By the way, the internal clock is very slightly off and varies with room temperature, so don't rely on it staying synchronised to your other device without a handshake.


body:
A look at main.cpp (for avr code in my installation) in file:

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino\main.cpp

shows that the Arduino runs loop() alternately with serialEventRun() in an infinite loop:

    int main(void)
    {
     init();
        initVariant();
     #if defined(USBCON)
     USBDevice.attach();
    #endif

     setup();

     for (;;) {
      loop();
      if (serialEventRun) serialEventRun();
     }

     return 0;
    }

Inspection of HardwareSerial.cpp shows that serialEventRun() simply calls serialEvent<n>(), if you have defined it in your sketch.

This means that you can write your own infinite loop within loop() perfectly safely, unless you have written serialEvent() code and are expecting it to run regularly.

This begs the question: if serialEvent() is called sequentially with loop(), will serialEvent() be called if loop() never returns? In other words, is serialEvent() interrupt-driven as well as being called when loop() returns?  A quick test -see below- shows that it is **not** interrupt-driven, so the previous paragraph is true.

    /*
      Serial Event Checker

      A sketch to see if serialEvent() is interrupt-driven.
      Will serialEvent() be called if loop() never returns?

      This code is based on Tom Igoe's SerialEvent example.

      On (at least) Arduino Uno we find that serialEvent() simply runs
      sequentially with loop().  When loop() never returns serialEvent()
      is never called.

      NOTE: The serialEvent() feature is not available on the Leonardo, Micro, or
      other ATmega32U4 based boards.

      R Symonds-Tayler 2018-02-01

      This example code is in the public domain.

    */

    String inputString = "";         // a String to hold incoming data

    void setup() {
      // initialize serial:
      Serial.begin(115200);
      // reserve 200 bytes for the inputString:
      inputString.reserve(200);
    }

    // comment out this definition to allow loop() to return
    #define INFINITE_LOOP

    void loop() {
    #ifdef INFINITE_LOOP
        while(1);
    #endif

    }

    /*
      SerialEvent occurs whenever a new data comes in the hardware serial RX. This
      routine is run between each time loop() runs, so using delay inside loop can
      delay response. Multiple bytes of data may be available.
    */
    void serialEvent() {
      while (Serial.available()) {
        // get the new byte:
        char inChar = (char)Serial.read();
        // add it to the inputString:
        inputString += inChar;
        // if the incoming character is a newline, set a flag so the main loop can
        // do something about it:
        if (inChar == '\n') {
          Serial.print("Got: '");
          Serial.print(inputString);
          Serial.println("'");
          // clear the string:
          inputString = "";
        }
      }
    }

This means that serialEvent() code might just as well go into your main loop() within a:

    if(serial.available()){
       // your code here...
    }

block.


body:
In [this article][1] [bri_huang][2] made a nice experiment using an oscilloscope and simple write functions.

He calculated the speed of the loop to be 117 kHz even though the microcontroller has a 16 MHz clock.

[https://learn.sparkfun.com/blog/1687][1]

  [1]: https://learn.sparkfun.com/blog/1687
  [2]: https://www.sparkfun.com/users/189969?_ga=2.124669005.630681230.1620644852-511729427.1602060651