message:
Synching local clock usign NTP to milliseconds

I am interested in getting a local clock on an ESP32 module synch to
a network clock using NTP. I am able to read data and time here. But I am interested in synching to the milli second level.
```c++
    #include <WiFi.h>
    #include <WiFiUdp.h>

    char ssid[] = "*************"; //  your network SSID (name)
    char pass[] = "********"; // your network password

    unsigned int localPort = 2390; // local port to listen for UDP packets

    IPAddress timeServerIP; // time.nist.gov NTP server address
    const char* ntpServerName = "time.nist.gov";

    const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes
    byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing
    // A UDP instance to let us send and receive packets over UDP
    WiFiUDP udp;

    void setup() {
      Serial.begin(115200);
      Serial.println();
      Serial.println();
      // We start by connecting to a WiFi network
      Serial.print("Connecting to ");
      Serial.println(ssid);
      WiFi.begin(ssid, pass);
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
      Serial.println("Starting UDP");
      udp.begin(localPort);
      Serial.print("Local port: ");
    }

    void loop() {
      //get a random server from the pool
      WiFi.hostByName(ntpServerName, timeServerIP);
      sendNTPpacket(timeServerIP);
      // send an NTP packet to a time server
      // wait to see if a reply is available
      delay(1000);
      int cb = udp.parsePacket();
      if (!cb) {
        Serial.println("no packet yet");
      } else {
        Serial.print("packet received, length=");
        Serial.println(cb);
        // We've received a packet, read the data from it
        udp.read(packetBuffer, NTP_PACKET_SIZE);
        // read the packet into the buf
        unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
        unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
        // combine the four bytes (two words) into a long integer
        // this is NTP time (seconds since Jan 1 1900):
        unsigned long secsSince1900 = highWord << 16 | lowWord;
        Serial.print("Seconds since Jan 1 1900 = " );
        Serial.println(secsSince1900);
        unsigned long mshighWord = word(packetBuffer[44], packetBuffer[45]);
        unsigned long mslowWord = word(packetBuffer[46], packetBuffer[47]);
        unsigned long mssecs = mshighWord << 16 | mslowWord;
        Serial.print("Frac Seconds = " );
        Serial.println(mssecs);
        // now convert NTP time into everyday time:
        Serial.print("Unix time = ");
        // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
        const unsigned long seventyYears = 2208988800UL;
        // subtract seventy years:
        unsigned long epoch = secsSince1900 - seventyYears;
        // print Unix time:
        Serial.println(epoch);
        // print the hour, minute and second:
        Serial.print("The UTC time is "); // UTC is the time at GMT
        Serial.print((epoch  % 86400L) / 3600);
        // print the hour (86400 equals secs per day)
        Serial.print(':');
        if (((epoch % 3600) / 60) < 10) {
          // In the first 10 minutes of each hour, we'll want a leading '0'
          Serial.print('0');
        }
        Serial.print((epoch  % 3600) / 60); // print the minute
        Serial.print(':');
        if ((epoch % 60) < 10) {
          // In the first 10 seconds of each minute, we'll want a leading '0'
          Serial.print('0');
        }
        Serial.println(epoch % 60); // print the second
      }
      // wait ten seconds before asking for the time again
      delay(10000);
    }

    // send an NTP request to the time server at the given address
    unsigned long sendNTPpacket(IPAddress& address) {
      Serial.println("sending NTP packet...");
      // set all bytes in the buffer to 0
      memset(packetBuffer, 0, NTP_PACKET_SIZE);
      // Initialize values needed to form NTP request
      // (see URL above for details on the packets)
      packetBuffer[0] = 0b11100011; // LI, Version, Mode
      packetBuffer[1] = 0; // Stratum, or type of clock
      packetBuffer[2] = 6; // Polling Interval
      packetBuffer[3] = 0xEC; // Peer Clock Precision
      // 8 bytes of zero for Root Delay & Root Dispersion
      packetBuffer[12]  = 49;
      packetBuffer[13]  = 0x4E;
      packetBuffer[14]  = 49;
      packetBuffer[15]  = 52;
      // all NTP fields have been given values, now
      // you can send a packet requesting a timestamp:
      udp.beginPacket(address, 123); //NTP requests are to port 123
      udp.write(packetBuffer, NTP_PACKET_SIZE);
      udp.endPacket();
```

body:
The NTP timestamp format doesn't use milliseconds. All timestamps are in
**seconds**, in a 32.32 [fixed point][] format. This means that the
fraction field is in units of 2−32 s, or about
233 picoseconds. You can convert that to milliseconds by
multiplying by 1000 and dividing by 232. For example:

    uint32_t frac  = (uint32_t) packetBuffer[44] << 24
                   | (uint32_t) packetBuffer[45] << 16
                   | (uint32_t) packetBuffer[46] <<  8
                   | (uint32_t) packetBuffer[47] <<  0;
    uint16_t mssec = ((uint64_t) frac * 1000) >> 32;

If you want to avoid 64-bit arithmetic, you can instead divide by 128,
then multiply by 125, then divide by 222:

    uint16_t mssec = ((frac >> 7) * 125) >> 22;

That should give the same result except for a potentially larger
rounding error. Note that, if you care about rounding, you would try to
round to nearest rather than towards zero:

    uint16_t mssec = ((frac >> 7) * 125 + (1UL << 21)) >> 22;

[fixed point]: https://en.wikipedia.org/wiki/Fixed-point_arithmetic


sender: user

message:
How to control an 12V 2A Car lamp using relay or MOSFET in Arduino

I am working with the project controlling an 25W 12V Car lamp. I have a 12V car battery. I want to control it with the Arduino using a relay or MOSFET.

Any suggestion for my project would be appreciated.

sender: assistant

body:
You can use a [RFP30N06LE][1] mosfet. It can support up to 60V 30A

Here is a wiring schema
<img src="https://i.stack.imgur.com/7WxDh.png" width="500">

  [1]: https://www.sparkfun.com/datasheets/Components/General/RFP30N06LE.pdf


message:
How can I make an AC analog voltage with Arduino?

I am trying to create an AC voltage in Arduino. Until now I have only managed to get a square wave. How can this be achieved with Arduino?

If I try:

    int up;
    int down;
    int out = 11;

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

    void loop() {
      for (up = 0; up <= 255; up++) {
        analogWrite(out, up);
        delay(1);
      }
      for (down = 255; down >= 0; down--) {
        analogWrite(out, down);
        delay(1);
      }
    }

is it still pulsed DC?

body:
You have a few options:

- Use a low-pass filter to round the square wave's edges some so they look more AC-ish.

- Use a low-pass filter and have your code create steps of voltage that look AC-ish by varying the PWM widths.

- Use an external SPI DAC chip that you can control with more discrete levels to make smoother looking AC.

- Look into Direct Digital Synthesis (DDC) to learn more. Google "analog via ddS", lots of hits.


message:
Why connect a diode between the reset pin of Arduino and 555 timer?

I am trying to create a watchdog timer using 555 IC and I am following [this][1].

I do not understand why a 1N4148 diode is connected between the reset pin of Arduino and the output of the 555 timer.

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

As far as I understand, the reset pin of the Arduino should be high, and when it is pulled low, the Arduino resets. But why should we add a diode over here? What purpose does it serve?

  [1]: https://github.com/mattbornski/Arduino-Watchdog-Circuit
  [2]: https://i.stack.imgur.com/nImsv.png

body:
It's called a "Wired Or" arrangement.

The Arduino's RESET pin has a pullup resistor in it (10KΩ). That keeps the RESET pin normally HIGH. To invoke a reset that pin needs pulling low, and that is done from a number of sources:

* The RESET button
* The DTR pin (through a 100nF capacitor) of the USB interface chip
* The 555 watchdog circuit above

The critical one there is the DTR pin.  That, because it's a brief pulse with quite a high output impedance, needs the reset pin to be easy to pull down. If you connected the output of the 555 directly to RESET it would be constantly trying to pull the RESET pin up to 5V with quite a low output impedance. The DTR circuit would have no chance of overcoming it.

So by adding a diode in there you get Wired Or, using an arrangement direct from the 1950s - DRL - [Diode-Resistor Logic](https://en.wikipedia.org/wiki/Diode_logic).  When the output of the 555 is HIGH the diode is reverse biased (or neutrally biased) and doesn't conduct, so the RESET pin's own resistor pulls the RESET pin up.  However, when the output of the 555 is LOW the diode can then conduct (it's forward biased) and that pulls the RESET pin LOW.


message:
How to make timed loops after switch / case?

I am working on a code, which is running a function once a second:

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

    switch (gearbox1) {
      case 1:
        //manually close
        Serial.println("Closing1");
        digitalWrite(gear1OpenPin, OFF);
        t.setTimer(1000, Close1, 1);

        break;

      case 2:
        //manually open
        Serial.println("Opening1");
        digitalWrite(gear1ClosePin, OFF);
        t.setTimer(1000, Open1, 1);

        break;

This part is working fine. But then i want at case 10: call function `autoClose()` which would work in 10 second cycles.

Struggle is, as my first function is called once a second, it is starting function `autoClose()` once a second as well. How can I overcome this please?

At the moment I have current, non working code:

      case 10:
        //automatic close
        Serial.println("A Close1");
        digitalWrite(gear1ClosePin, OFF);
        digitalWrite(gear1OpenPin, OFF);

        t.enable(autoClose);
        autoClose();
        break;

Edit: Added minimal possible code. I want `autoOpen()` and `autoClose()` to loop in 10 sec. intervals.

    #include <SimpleTimer.h>
    SimpleTimer t;
    int gearbox1;

    #define gear1OpenPin 44
    #define gear1ClosePin 46

    int OFF = HIGH;  // states for relays
    int ON = LOW;

    byte gear1Open = 0;
    byte gear1Close = 0;

    void setup() {

      t.setInterval(1000, Control1);
      int autoOpen = t.setInterval(10000, autoOpen);
      int autoClose = t.setInterval(10000, autoClose);
    }

    void loop() {

      t.run();
    }

    void Control1() {
      //*****************************************
      switch (gearbox1) {
        case 1:
          //manually close
          Serial.println("Closing");
          digitalWrite(gear1OpenPin, OFF);
          t.setTimer(1000, Close1, 1);

          break;

        case 2:
          //manually open
          //   Serial.println("Opening");
          digitalWrite(gear1ClosePin, OFF);
          t.setTimer(1000, Open1, 1);

          break;

        case 5:
          //stop
          Serial.println("Stopping");
          digitalWrite(gear1ClosePin, OFF);
          digitalWrite(gear1OpenPin, OFF);

          break;

        case 10:
          //automatic close

          digitalWrite(gear1ClosePin, OFF);
          digitalWrite(gear1OpenPin, OFF);
          if (t.isEnabled(autoClose)) {
            autoClose();
          } else {
            t.restartTimer(autoClose) ; t.enable(autoClose);
            autoClose();
          }
          break;

        case 20:
          //automatic open

          digitalWrite(gear1ClosePin, OFF);
          digitalWrite(gear1OpenPin, OFF);
          t.restartTimer(autoOpen); t.enable(autoOpen);
          autoOpen();
          break;
     }
    }

    void Open1() {
      digitalWrite(gear1OpenPin, ON);
    }
    //**********************************************
    void Close1() {
      digitalWrite(gear1ClosePin, ON);
    }
    //**********************************************
    void autoOpen() {

      if (gear1Open == ON) {
        gear1Open = OFF;
      } else {
        gear1Open = ON;
      }
      digitalWrite(gear1OpenPin, gear1Open);
    }
    //**********************************************
    void autoClose() {
      if (gear1Close == ON) {
        gear1Close = OFF;
      } else {
        gear1Close = ON;
      }
      digitalWrite(gear1ClosePin, gear1Close);
    }

body:
Create a new variable to hold the state of whether or not you are in autoClose mode:

    uint8_t inAutoClose=0;

Then, add a line in your switch statement to set that flag when you enter that state, but not call the function if you were already in that state:

    case 10:
      //automatic close
      Serial.println("A Close1");
      digitalWrite(gear1ClosePin, OFF);
      digitalWrite(gear1OpenPin, OFF);
      if (!inAutoClose) {
        inAutoClose = 1;
        t.enable(autoClose);
        autoClose();
      }
      break;

Add a line in your other switch branches to clear that flag:

    case 1:
      //manually close
      inAutoClose = 0;
      [...]

If you want `autoClose()` to be called every 10 seconds repeatedly as the "idle" state, then you need to clear `inAutoClose` (set it to zero) at the end of every 10 second period. How and where you do that depends on other factors you haven't shown, like what `autoClose()` does, or what the timer you enable does.

Side note: avoid naming your timer name (`autoClose`) and your function name `autoClose()` the same! Does your code compile that way? It ought to throw an error.

**ANSWER 2** (based on comments)

Your auto-close state is described as

> Turns on for 10 seconds, after that off for 10 seconds.

This can be accomplished with a similar structure to what you have now, with a few changes. (These are my suggestions, but by no means the best or worst way.)

Edit your open and close functions:

    void Open1() {
      digitalWrite(gear1OpenPin, ON);
      if (isAutoOpen) {
        t.setTimeout(10000UL, Close1); // Sets a timer to call closer in 10s
       }
    }

    void close1() {
      digitalWrite(gearClosePin, ON);
      if (isAutoOpen) {
        t.setTimeout(10000UL, Open1); // Sets a timer to call opener in 10s
      }
    }

When you call either `Open1()` or `Close1()`, if your auto-open flag is set, then 10s later, the opposite function is called, and this keeps chaining together, every 10s.

Whenever it's time to stop this, you clear the `isAutoOpen` flag and disable the timers. You may wish to keep track of the timer ID that is created with the `setTimeout()` function, so you can disable it at any time to avoid the system going through the cycle one more time after you clear the flag.


message:
Set a pin HIGH when crash occurs

I'm using an ESP8266 (NodeMCU v3). I want to set a PIN high if a `soft wdt reset` occurs (not expecting one). Is there a way I can do that?

Can I attach something on TX pin of the board and watch for crash dump? Maybe another Arduino?

body:
The ESP provides a reset reason API, which lets you differentiate between a crash and a normal reset:

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

    const char * const RST_REASONS[] =
    {
      "REASON_DEFAULT_RST",
      "REASON_WDT_RST",
      "REASON_EXCEPTION_RST",
      "REASON_SOFT_WDT_RST",
      "REASON_SOFT_RESTART",
      "REASON_DEEP_SLEEP_AWAKE",
      "REASON_EXT_SYS_RST"
    };

    // .. in setup():

    const rst_info * resetInfo = system_get_rst_info(); //populate reset info
    String diag = String(RST_REASONS[resetInfo->reason]); // turn enum index to string

    if(diag == "REASON_SOFT_WDT_RST") digitalWrite(TX, HIGH);// check string, take action


body: The ESP8266 should  hold the pin LOW when it is active, letting it go high then signals that the program has crashed.


message:
Structure Array Initialization

I'm trying to initialize a char array which is part of a structure as follows:

    #define TRUE 1
    #define FALSE 0

    struct s_field_def { // structure for managing display field
      char f_txt[16]; // option text
      bool f_inhibit; // set this to inhibit updating of the field on the display
    };

    enum field_name {F_STATE, F_PULSE};

    void setup() {

      // initialize display fields structure
      struct s_field_def fields[2]; // initialize the display fields
      fields[F_STATE] =  {"HALTED", FALSE}; // displays the current run state
      fields[F_PULSE] =  {"@", TRUE}; // displays indicator of system running
    }

    void loop() {

    }

The initialization of the structure is producing an error at these lines:

      fields[F_STATE] =  {"HALTED", FALSE}; // displays the current run state
      fields[F_PULSE] =  {"@", TRUE}; // displays indicator of system running

    no match for 'operator=' (operand types are 's_field_def' and '<brace-enclosed initializer list>')

What am I doing wrong here?

body:
You can use this (but look at the accepted answer, it shows a much neater way).

      strcpy(fields[F_STATE].f_txt, "HALTED");
      fields[F_STATE].f_inhibit = FALSE;

      strcpy(fields[F_PULSE].f_txt, "@");
      fields[F_PULSE].f_inhibit = TRUE;

I don't have a compiler so I hope it's correct.

When using C++ you can use a constructor or assignment operator, but C does not have these object oriented features.


body:
As explained in Michel Keijzers' answer, you cannot use the `=` operator
to _assign_ something to a string (a character array). However, you can
_initialize_ a string using `=`. There is an important distinction
between _assignment_, which you can do anywhere in a program, an
_initialization_, which can only be done at the time you _define_ a
variable.

For example:

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

    int i = 2;  // initialization

    void setup() {
        i = 4;  // assignment
    }

In your specific case, you can initialize `fields` as follows:

    struct s_field_def fields[2] = {
        {"HALTED", FALSE},  // displays the current run state
        {"@", TRUE}         // displays indicator of system running
    };


message:
Combining code for multiple sensors (Current and Voltage Sensors) in one program

I need to operate 2 different sensors (Current and Voltage) simultaneously. I have managed to run each one of them separately and I don't know how to manipulate the code so they could work together. My background in coding is basic and I'm not the one who wrote these codes.

Here are the sketches:

**1. Current Sensor Code**

    void setup() {

      Serial.begin(9600);
    }

    void loop() {

      float average = 0;
      for(int i = 0; i < 1000; i++) {
        average = average + (.0264 * analogRead(A0) -13.385) / 1000;//this is
        //for the 5A mode, if 20A or 30A mode, need to modify this formula to
        //(.19 * analogRead(A0) -25) for 20A mode and
        //(.044 * analogRead(A0) -3.78) for 30A mode
        delay(3);
      }
      Serial.println(average);
    }

**2. Voltage Sensor Code**

    /*
    DC Voltmeter Using a Voltage Divider
    Based on Code Created By
    T.K.Hareendran
    */

    int analogInput = A1;
    float vout = 0.0;
    float vin = 0.0;
    float R1 = 30000.0; //
    float R2 = 7500.0; //
    int value = 0;
    void setup(){
       pinMode(analogInput, INPUT);
       Serial.begin(9600);
       Serial.print("DC VOLTMETER");
    }
    void loop(){
       // read the value at analog input
       value = analogRead(analogInput);
       vout = (value * 5.0) / 1024.0; // see text
       vin = vout / (R2/(R1+R2));

    Serial.print("INPUT V= ");
    Serial.println(vin,2);
    delay(500);
    }

body:
**WARNING** The following advice does not generally produce compiling or working code, but is one way to start merging two separate sketches.

Without getting into the details of the code (we are not here to write code for free) I can give you the general guidelines:

 - put all the declarations (anything not contained in the `setup` or `loop` functions) at the top, first all from one sketch, then all from the other
 - copy the `setup` function from the first sketch and paste it after all the declarations
 - copy the content (anything inside the curly braces) of the `setup` function from the second sketch and put it inside the same function, but after all the first sketch code
 - rinse and repeat the last two steps for the `loop` functions

At this point the you might have variable name collisions and plenty of other issues, but looking at the type of code you are trying to mesh, it should work


body:
**How to combine two sketches.**

First, make sure every global variable and function name is unique (except setup and loop). Choose the smallest sketch and rename its. variables, function names and any other named items (like DEFINE).

Is convenient to refactor things. I extract the code for reading Voltage and Current to separate functions, to reduce the count of global variable and length of each function, making things easier by reducing the side of setup() and loop().

Now, combine the code inside the setup and loop:

    const int analogInput = A1;

    void setup() {
      Serial.begin(9600);
      pinMode(analogInput, INPUT);
    }

    void loop(){
      Serial.print(getCurrent());
      Serial.print(" ");
      Serial.println(getVoltage(),2);
      delay(500);
    }

    float getCurrent() {
      float average = 0;
      for(int i = 0; i < 1000; i++) {
        average = average + (.0264 * analogRead(A0) -13.385) / 1000;//this is
        //for the 5A mode, if 20A or 30A mode, need to modify this formula to
        //(.19 * analogRead(A0) -25) for 20A mode and
        //(.044 * analogRead(A0) -3.78) for 30A mode
        delay(3);
      }
    return average;
    }

    float getVoltage() {
       const float R1 = 30000.0; //
       const float R2 = 7500.0; //
       float value = analogRead(analogInput);
       float vout = (value * 5.0) / 1024.0; // see text
       float vin = vout / (R2/(R1+R2));
      return vin;
    }


body:
The bigger problem regarding combining the code is timing. You can't use `delay()` because the other code can't run.

You need to do let `loop()` run through as fast as possible and only do things when you need to i.e. when certain time elapses. And you do that with `millis()`, like in the [Blink Without Delay example][1].

In your case, current reading code also needs to keep track of number of samples read and react when the sample count is reached.

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

    const byte current_pin = A0;
    const byte voltage_pin = A1;

    const int max_current_sample_count = 1000;
    const int current_sample_interval = 3;
    const int voltage_sample_interval = 500;

    // voltage divider parameters
    const float R1 = 30000;
    const float R2 = 7500;

    // 5A current sensor parameters
    const float current_sensor_scale = 0.0264;
    const float current_sensor_offset = -13.385;

    float current_sum = 0; // for accumulated measurements
    int current_count = 0; // counter for measurements

    unsigned long last_current_measure = 0; // for timing the current measurement
    unsigned long last_voltage_measure = 0; // for timing the voltagemeasurement

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

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

        if (time - last_current_measure > current_sample_interval) { // if enough time elapsed to make another measurement
            last_current_measure = time; // save the time this action ran

            current_sum += current_sensor_scale * analogRead(current_pin) + current_sensor_offset;
            current_count++; // increase the counter
            if (current_count >= max_current_sample_count) { // when we reached number of samples
                // output the average and reset the sum and counter
                Serial.print("A = ");
                Serial.println(current_sum/current_count);
                current_sum = 0;
                current_count = 0;
            }
        }
        if (time - last_voltage_measure > voltage_sample_interval) { // if enough time elapsed to make another measurement
            last_voltage_measure = time; // save the time this action ran

            int value = analogRead(voltage_pin);
            float vout = (value * 5) / 1024.0;
            float vin = vout / (R2/(R1+R2));
            Serial.print("V = ");
            Serial.println(vin, 2);
        }
    }

It is also a good practice that some values, that might need to be changed, are defined as constants. So you don't need to search for them inside the code which can become a problem, when you write more code. And it can prevent bugs, if you have those values in multiple places and forgot to change one.

  [1]: https://www.arduino.cc/en/tutorial/BlinkWithoutDelay


message:
Connecting arduino ground with battery powered remote control ground

I soldered a cable to the button of a remote control and I want to simulate that button press by setting the pin to input mode and back to output (LOW) again.

For this to work I connected the ground of the battery (black wire) to the GND of the arduino.

Is this 100% safe if I hook the arduino up to the power grid or to my pc?

I also disconnected the ground pins and had my arduino connected to my pc and suddenly it worked too. I got a BSoD shortly after.

body: All grounds should be connected to provide a common reference point.


body:
Unless you use *galvanic isolation* (see below) then yes, you *must* connect the grounds together. That is vital (see [here](https://hackingmajenkoblog.wordpress.com/2016/12/06/the-importance-of-sharing-grounds/)).

The main concern though is the voltage you are switching.  The Arduino cannot connect any of its IO pins directly to any voltage over 5V. Doing so will most likely damage your Arduino.

Instead, you need to use the Arduino to switch a device that will switch the button for you.  The simplest is a BJT or MOSFET:

<!-- 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/D7zhN.png)

<!-- End schematic -->

But there are a couple of other caveats you should consider. The most important one is to do with how far away the remote device is, and how it is powered.  Connecting the grounds of two devices that are very distant can get quite messy, since "ground" at different points may be at completely different potentials, and the voltage drop across the "ground" wire (wires don't have zero resistance) coupled with the existing ground connection through the power supplies creates a *ground loop* and introduces massive amounts of interference.  For this kind of arrangement, it is good to introduce ...

Galvanic Isolation
------------------

This electrically separates the two circuits completely. There is absolutely no electrical connection between your Arduino and the device you are switching.

The most common way of achieving this in low powered digital circuits is to use an opto-isolator (also called an opto-coupler).  This is basically an LED and photo-transistor together in a single package. Turn the LED on and the phototransistor turns on.  The basic arrangement is exactly the same as the circuit above, but the wire going in from the Arduino is connected to an LED:

<!-- 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/zHBsd.png)

<!-- End schematic -->

Now you really don't care what ground potential is at the other end, nor how it is powered. As long as the opto-isolator can cope with the voltage it has to switch all will be good.  Nothing in the remote circuit can do any damage at all to the Arduino since there is no way for current to flow back from that circuit to the Arduino.


message:
Problem "Didn't find PN53x board" in Arduino Uno E-Card Reader

This is component to make E-Card reader, using arduino uno pn532
[![enter image description here][1]][1]
[![enter image description here][2]][2]

**Code**

      if (success) {
        // Display some basic information about the card
        Serial.println("Found an ISO14443A card");
        Serial.print("  UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
        Serial.print("  UID Value: ");
        nfc.PrintHex(uid, uidLength);
        Serial.println("");

        if (uidLength == 4)
        {
          // We probably have a Mifare Classic card ...
          Serial.println("Seems to be a Mifare Classic card (4 byte UID)");

          // Now we need to try to authenticate it for read/write access
          // Try with the factory default KeyA: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
          Serial.println("Trying to authenticate block 4 with default KEYA value");
          uint8_t keya[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };

          // Start with block 4 (the first block of sector 1) since sector 0
          // contains the manufacturer data and it's probably better just
          // to leave it alone unless you know what you're doing
          success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, 4, 0, keya);

          if (success)
          {
            Serial.println("Sector 1 (Blocks 4..7) has been authenticated");
            uint8_t data[16];

            // If you want to write something to block 4 to test with, uncomment
            // the following line and this text should be read back in a minute
            //memcpy(data, (const uint8_t[]){ 'a', 'd', 'a', 'f', 'r', 'u', 'i', 't', '.', 'c', 'o', 'm', 0, 0, 0, 0 }, sizeof data);
            //success = nfc.mifareclassic_WriteDataBlock (4, data);

            // Try to read the contents of block 4
            success = nfc.mifareclassic_ReadDataBlock(4, data);

            if (success)
            {
              // Data seems to have been read ... spit it out
              Serial.println("Reading Block 4:");
              nfc.PrintHexChar(data, 16);
              Serial.println("");

              // Wait a bit before reading the card again
              delay(1000);
            }
            else
            {
              Serial.println("Ooops ... unable to read the requested block.  Try another key?");
            }
          }
          else
          {
            Serial.println("Ooops ... authentication failed: Try another key?");
          }
        }

        if (uidLength == 7)
        {
          // We probably have a Mifare Ultralight card ...
          Serial.println("Seems to be a Mifare Ultralight tag (7 byte UID)");

          // Try to read the first general-purpose user page (#4)
          Serial.println("Reading page 4");
          uint8_t data[32];
          success = nfc.mifareultralight_ReadPage (4, data);
          if (success)
          {
            // Data seems to have been read ... spit it out
            nfc.PrintHexChar(data, 4);
            Serial.println("");

            // Wait a bit before reading the card again
            delay(1000);
          }
          else
          {
            Serial.println("Ooops ... unable to read the requested page!?");
          }
        }
      }
    }

And i find problem, like this :

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

**EDIT:**
Now has ben change to I2C mode and detected RFID. But not detected E-Card:

[![enter image description here][4]][4]
How solve this is problem?

  [1]: https://i.stack.imgur.com/nfkrN.jpg
  [2]: https://i.stack.imgur.com/u5cUQ.jpg
  [3]: https://i.stack.imgur.com/XWVs1.jpg
  [4]: https://i.stack.imgur.com/iBa3g.jpg


body:
This is sir, i check using white card

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

  [1]: https://i.stack.imgur.com/6oxTU.jpg
  [2]: https://i.stack.imgur.com/synCK.jpg
  [3]: https://i.stack.imgur.com/jicU9.jpg


message:
Using While Loop For Accurate Delays

I was trying to get the timing in between events right, (Event time is around 150ms and i need it to be accurate within +-1ms) and came upon this implementation. The actual application will not be affected by the roll over, but would like to see if any of you guys (experts) can point out any flaws in using an empty while loop for time events, besides slightly higher power consumption.

This implementation gave me very accurate time spacings:

    unsigned long previousMillis = millis();
    Serial.print("ONE: ");
    Serial.println(millis());
    while(millis() - previousMillis < 1000);
    Serial.print("SECOND: ");
    Serial.println(millis());

compared with...

    Serial.print("ONE: ");
    Serial.println(millis());
    delay(1000);
    Serial.print("SECOND: ");
    Serial.println(millis());

Which yields some errors after every step.

body:
Those two are not the same "program". The first one start counting before `Serial.print`. The other first print and then delay for a second.

We have two piece of code:

 - The first take 1000ms to reach "SECOND" (plus some overhead).
 - The second take 1000ms + time needed for two Serial.prints and a millis() call to reach "SECOND" (plus the same overhead).

The first approach is better, because you start counting before doing operations of undetermined length. So, it's immune to any factor affecting running time, like time spent in interrupts. And you don't need to retune it if you change the sketch.


body:
For better accuracy, you should not be "delaying until it's time to do something", but instead "checking if it's time to do it yet".

It's all very well saying you want something to happen every 150ms and delaying between actions for 150ms, but that won't yield you an event that happens every 150ms - it yields you an event that takes X amount of time with a delay of Y between each event, resulting in an overall period of X+Y, which is not what you want.

I cover the proper ways to deal with timing of regular events in this existing answer:

* https://arduino.stackexchange.com/questions/47357/delaytime-vs-ifmillis-previoustime-and-drift/47360#47360


body:
There are many options for executing a task periodically. The most
straightforward is to use a slight variation of code given in the [Blink
Without Delay][] Arduino tutorial:

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

    const uint32_t PERIOD = 150000;  // 150 ms

    void loop() {
        static uint32_t last_time;
        if (micros() - last_time >= PERIOD) {
            last_time += period;
            do_periodic_task();
        }
        do_other_tasks();
    }

Note two changes relative to the code in the tutorial:

1. This is using `micros()` instead of `millis()`. This way the timing
   resolution is 4 µs instead of 1 to 2 milliseconds.
2. `last_time` is updated as `last_time += period` instead of
   `last_time = micros()`. This way, even if the periodic task got
   delayed by the other tasks, these delays don't add up.

The timing will not be perfect: you will have both drift and jitter.
The drift comes from the inaccuracy of the ceramic resonator clocking
the microcontroller. These resonators have typically 0.5% frequency
tolerance, although the typical frequency error is more likely to be
around ±0.1% (i.e. 0.15 ms error in a 150 ms period). Note
that a poorly written code would add it's own drift, e.g. if you do
`last_time = micros()`, but this does not.

The jitter comes from the fact that the clock is checked only once per
loop iteration, and your periodic task can then be delayed by the other
tasks. The amplitude of the jitter is the maximum time taken by a loop
iteration.

Despite these imperfections, this would be my first choice unless I
really needed better timing accuracy.

If you need lower drift, one option is to calibrate your Arduino clock.
You measure how fast or slow it is, and you tweak the `PERIOD` constant
accordingly. For example, if you measure the clock to be 700 ppm
slow, you would fix it like this:

    const uint32_t NOMINAL_PERIOD = 150000;  // 150 ms

    // Adjust the period to account for clock drift.
    const float FREQUENCY_OFFSET = -700e-6;  // -700 ppm
    const uint32_t PERIOD = NOMINAL_PERIOD * (1 + FREQUENCY_OFFSET);

This technique allows you to tune the frequency with about 6.7 ppm
resolution, for a period of 150 ms. You cannot reasonably expect
anything better, as the frequency of the ceramic resonator is not very
stable anyway.

If you need lower jitter, one option is to perform a _blocking wait_:
you ask the processor to do nothing but wait until it's time to perform
the periodic task. This is similar to the code you posted in your
question:

    void loop() {
        static uint32_t last_time;
        while (micros() - last_time < PERIOD) ;  // busy wait
        last_time += period;
        do_periodic_task();
    }

This will not completely suppress the jitter, but it will reduce it to
just the time taken by the `while` loop. However, there is a big issue
with this way of coding: now your processor does _nothing_ but the
periodic task. It may not be a problem right now, but as your project
grows, it is more than likely that at some point you will want to handle
extra tasks like, e.g. responding to some user input.

If you want to avoid completely blocking the processor on the busy wait,
yet you want the smallest possible jitter, you could try some sort of
compromise: you let the processor take care of other tasks until it is
_almost_ time to perform the periodic task. Then you switch to the
blocking mode where the processor does nothing but wait for the clock.
Here, “almost time” would be defined by the maximum time your loop can
take:

    const uint32_t MAX_LOOP_TIME = 2000;  // assume 2 ms

    void loop() {
        static uint32_t last_time;
        if (micros() - last_time >= PERIOD - MAX_LOOP_TIME) {
            while (micros() - last_time < PERIOD) ;  // busy wait
            last_time += period;
            do_periodic_task();
        }
        do_other_tasks();
    }

Another option, that has been mentioned in comments, is to trigger the
task by a timer. This will work if it is a very short task that can
safely be run with interrupts disabled. You have four 16-bit timers on
your Mega, so you can presumably spare one for timing this task. This
could be done with Timer 1 as follows (warning: untested code):

    const int TIMER_PRESCALER = 64;
    const float F_TIMER = F_CPU / TIMER_PRESCALER;
    const float PERIOD = 150e-3;
    const uint16_t TIMER_PERIOD = F_TIMER*PERIOD + 0.5;  // round to nearest

    void setup() {
        TCCR1B = 0;            // stop the timer
        OCR1A  = TIMER_PERIOD - 1;
        TIFR1 |= _BV(OCF1A);   // clear TIMER1_COMPA interrupt flag
        TIMSK1 = _BV(OCIE1A);  // enable TIMER1_COMPA interrupt
        TCCR1A = 0;            // no PWM
        TCCR1B = _BV(WGM12)    // CTC mode, TOP = OCR1A
               | _BV(CS10)     // clock at F_CPU / 64
               | _BV(CS11);    // ditto
    }

    ISR(TIMER1_COMPA) {
        do_periodic_task();
    }

Note that `TIMER_PERIOD` will be 37500. If you want to tune it to
account for an inaccurate clock frequency, your tuning resolution will
be about 26.7 ppm.

The interrupt technique should get you sub-microsecond jitter _most of
the time_. However, every now and then the Timer 0 interrupt (the
one responsible for updating the `millis()` counter) will delay your
interrupts for a few microseconds. Beware also that some libraries can
delay interrupts for excessive amounts of time. Software Serial is an
infamous offender.

[Blink Without Delay]: https://www.arduino.cc/en/tutorial/BlinkWithoutDelay


message:
Looking for SPI documentation

I'm trying to use an Arduino as a slave and was searching for examples which I found many. But apart from the examples, I haven't found any documentation explaining many thing that show up in those examples.

For example, I'd like a document that would state what things like the following are:

-SPCR

-SPE

-SPDR

-ISR

-SPI_STC_vect

I'm asking this, because I don't and can't just copy an example and hope that it'll work, I really need to know what I'm doing.

Thank you,

João

body:
You are confusing SPI, a de facto standard, with the Arduino/Atmel hardware support for SPI.

SPCR, SPE and SPDR are registers of the Atmel MCU, part of the hardware support.

ISR is Interrupt Service Routine and SPI_STC_vect is the vector that point to that code. That is where the data received from the cable is read finally.


body:
Take a look at Nick Gammon's SPI explanations also. Very good, with timing explained as well.

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


message:
How to get data from a device using ethernet connection with arduino

I have a question,
I know how to flush the result of a device(using PIN mode) / control a device with help of an Ethernet shield of arduino.

Now, the thing I want is I need to read a device which communicates only via Ethernet. so i have now connected the device with a router and I have the IP address of the device. I need to read the data from the device using arduino + Ethernet shield.

In fine: How to read data from a device connected to a arduino + Ethernet Sheild via lan cable and flash the result in web server or serial portal. Doesn't matter.

Please suggest a solution or help me with code.

regards,
J

body:
You are out of luck: The device talks SMP (Static Managment Program), which is a close-source product of the same vendor.

The protocol used by SMP is not documented. The only way to access it is via the vendor own Windows software management.

Decoding the protocol is out of question.


message:
Using TFT touchscreen with Arduino Uno R3 via I2C

I've recently gotten into Arduino, due to a friend asking to be part of a project. The project requires a few 24V LED strips to be controllable via PWM, probably over MOSFETs (we have someone else in the team that will look after the electronics, I will be mostly responsible for the code) and also various sensors to measure the environment. However, the project should also include a touchscreen that will be used for programming these LEDs based on time and date, and displaying the data from these sensors, or program further events based on their input.

As far as I understand it should be possible to drive a TFT touchscreen via I2C? I've done some googling over the past two hours or so and could barely find any information about what screens to use for such projects, no tutorials, nor if there are any libraries available.

Is it doable to do a project of this magnitude with a Uno R3, or should I consider a Due or Mega?

I have a touchscreen shield right here, but it leaves me with only one PWM and one analogue pin if I don't plan on using the SD card that is on its back.

Maybe I'll find the answer myself, but I have literally only joined the Arduino/microcontroller fun a few days ago and am reading up on the whole topic in a 'for dummies' book which is very interesting, but it only touches on I2C at the very end and I don't want to confuse myself too much by jumping ahead and reading about stuff that doesn't directly answer my questions. So I turn to you guys for at least pointing me in the right direction on what I should read up on or linking me to tutorials.

Also, if you guys have any books to recommend on the topic I'll be glad to take recommendations.

Thanks in advance

body:
A TFT touchscreen actually normally consists of two completely separate items:

* TFT Display
* Touchscreen and optional interface chip

While you can get both of those together on a board with both using I2C it is quite rare. It is far more common to find boards with either SPI or 8- (or 16-) bit parallel interfaces for the TFT screen, and SPI (or sometimes 4 channel analog - a direct connection to the touch screen itself) for the touch screen.

I2C is really only used for very small screens. The slow speed of the I2C protocol means that updating the display is very slow, which results in very poor performance for anything bigger than, say 128x128 pixels. It's usually used for things like small OLED displays rather than larger TFT displays.

Touchscreens with I2C are normally capacitative rather than the cheap resistive, so tend to be a little more expensive and harder to work with. The most common touch screen chip, the XPT2046, is SPI.

Fitting everything you want to do into an Uno is going to be tight, and not just because of the number of IO pins a display usually demands. Working with displays usually means lots of graphics (icons, symbols, fonts, etc), and that means a lot of flash memory. A Mega2560 would be a better choice for that if you want to remain with 8-bit.

However better graphical results would be obtained using a more powerful board. The Arduino Due, with its 32-bit ARM chip, would allow you to do much more graphical manipulation, such as drawing nice graphs etc.

My personal preference, though, is to use a PIC32 based board and the [chipKIT](https://chipkit.net) core, coupled with my own powerful [DisplayCore](http://displaycore.org) library. But then I'm biased.


message:
How I can divide information stream from bluetooth hc-06?

All good afternoon or evening. I am having a problem writing a sketch for Arduino using Arduino UNO and Bluetooth HC - 06.

My program does not divide the input stream of information into several variables. No matter how many variables I specify, they are considered as one.

Maybe I do not know all subtleties of the use of Serial.read(). Apparently from a sketch given below I get through Bluetooth two variables of color and var. A microcontroller perceives these two variables as one and as a result does not execute before him task. As a result we will be able to choose the color and change delay of blinking by this color.

If anybody knows how to correct this problem or can point me to a similar project I will be very thankful for any rendered help

    const int rPin = 3;
    const int gPin = 5;
    const int bPin = 6;
    int chosed_color;
    int val;
    int color;

    void setup()
    {
      Serial.begin(9600);
      pinMode( rPin, OUTPUT );
      pinMode( gPin, OUTPUT );
      pinMode( bPin, OUTPUT );

    }

    void loop()
    {
    while(Serial.available()>0)
      {
         color = Serial.read();
       if(color==1)
          {
           chosed_color = rPin;
          digitalWrite( rPin, HIGH );
          digitalWrite(rPin, LOW);
           return chosed_color;
          }
            else if(color==2)
          {
           chosed_color = bPin;
           digitalWrite( bPin, HIGH );
          digitalWrite(bPin, LOW);
           return chosed_color;
          }
             else if(color==3)
          {
            chosed_color = gPin;
           digitalWrite( gPin, HIGH );
           digitalWrite(gPin, LOW);
           return chosed_color;
          }
      }
    if(Serial.available()>0)
    {
      val = Serial.read();
    }

          digitalWrite( rPin, HIGH );
          delay(val);
          digitalWrite(rPin, LOW);
          delay(val);
    }

body:
Your code have various issues.

This:

       if(color==1)
          {
           chosed_color = rPin;
          digitalWrite( rPin, HIGH );
          digitalWrite(rPin, LOW);
           return chosed_color;
          }

means that when you find a color, you exit `loop()` instead of reading the `val` variable.

**Serial.read**

`Serial.read` read only one byte. If you need to read an arbitrary integer, need `Serial.parseInt` or some elaborate solution. As it, you are only able to read one-digit integer values.

Worse, when you type "1" in the Serial Monitor, what the program received is the value 49 (the ascii code for char 1).

Also, you have to filter non interesting chars, like LF, CR, commas or whatever char you use as delimitir.

Please, read the excelent post by Majenko about [Reading Serial on the Arduino][1].

Here a better version of your code. It is very basic and lacks all error checking, etc.

    const int rPin = 3;
    const int gPin = 5;
    const int bPin = 6;
    int pins[3] = {rPin, gPin, bPin};

    void setup()
    {
     Serial.begin(9600);
     pinMode(rPin, OUTPUT);
     pinMode(gPin, OUTPUT);
     pinMode(bPin, OUTPUT);
    }

    void loop()
    {
     if(Serial.available()>0) {
      int color = Serial.read();
      int chosed_color = pins[color-1];
      digitalWrite(chosed_color, HIGH);
      digitalWrite(chosed_color, LOW);

      if(Serial.available()>0) {
       int val = Serial.read();
       digitalWrite(chosed_color, HIGH); // I suppose you want this
       delay(val);
       digitalWrite(chosed_color, LOW);
       delay(val);
      }
     }
    }

  [1]: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/


body:
Communication is done only with bytes. A byte is ALWAYS a numerical value and you cant' transmit more than one byte at a time.
Saying that, you have two points to understand:

1) how do you want to "see" the result, from a human point of view?

2) how can you transmit more than one byte?

Just test this little sketch:

     void setup() {
    Serial.begin(9600);
    Serial.println(65);
    Serial.println("65");
    Serial.println("A");

    Serial.write(65);
    Serial.write('A');
    }

    void loop()
    {
    }

You will get on the serial monitor:
65
65
A
AA

Check for ASCII table on the internet and you'll see a list of code for letters representation.

Now: Serial.println("65"); don't print the number 65. It prints the "letters" for human representation of this number. In fact, 65 is a number but here is the "human word".

*If you have 65 potatoes in a bag, a french will say "soixante cinq". An Englisman will say "sixty five" and a portuges will say "sesenta y cinquo". But they have all the same number of potatoes.*

So the computer has the **number** but the human has the **visual representation of the number**.

Serial.print convert automaticly the numerical value in a "letter value". So when you do Serial.print(65) you don't print ONE byte... but TWO! First one is the human representation of 6 (which has the ASCII value of 54) and the the human representation of 5 (which has the ASCII value of 53)

Then the next line also print 65 because I have had "quote". So Serial.print dsplay this as a text.

The third write "A" which is a "text"

Then we use Serial.write(). Serial.write **don't** try to create a "human" point of view. So it uses directly the number as an ASCII value.
As 65 is the ASCII value for A, Serial.write(65) send only ONE byte and show it as the ASCII letters so A.
And of course Serial.write('A') give the same result.

For transmission, this is the very first point to understand: if you transmit a byte with value of 65 you'll get this same value on the other side. But depending on the way you display, you can be fooled and believe transmission was wrong (*"I send 'A' and receive 65!"*)

For the second point ("how can I transmit more than a byte"): if you have 2 values to send and each one is on one byte, you have to send two bytes.
While receiving, you put the first byte coming in, in a variable, and the second in an other.

If you have to transmit a values using an INT so two bytes, you have to "break" the INT into bytes.

Eg the INT as a value of 3154 (in décimal). Its Hexa representation is 0x0C52.
You can break this in two blocks: 0x0C it the value of half of the INT and 0x52 is the other part.

So you can transmit 0x0C (higher part of the INT), then 0x52 (lower part of the INT) and while receiving you use the two bytes to "build again" the INT value.

To send 0x0C52 (INT) and 0xF345AC12 (LONG) you must send:
0x0C, 0x52, 0xF3, 0x45, 0xAC and 0x12 so a total of 6 bytes. Then while receiving you "build back" the value.
Of course, if you don't remember the way you "break for sending", you can be confused.
Because 0x0C, 0x52, 0xF3, 0x45, 0xAC and 0x12 can be seen as:

- six bytes
- three INT (0x0C52, 0xF345 and 0xAC12),
- one long and two bytes (0x0C52F345, 0xAC and 0x12)
etc...

So you must "rebuild" according to the way you "break" the data while sending!

Hope this will help understanding.


body:
You have a misconception, how serial communication works. The data is transmitted one byte at a time and not in one bunch (even if you type it in the Serial Monitor in as one string). So, when you use distinct if- or while-statements for each variable, the data may arrive at any step in these statements, without any possibility to distinguish between the variables.

You have to ways dealing with serial messages (I prefer the latter for it is more flexible):

 - **Constant message length:** You can always send messages with the same length. This is suitable for small projects with only one functionality, so that you always send the same amount of data. In this case you can wait for all bytes of a message to arrive and then treat the message as a whole:

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

    if(Serial.available() >= 2){
      variable1 = Serial.read();
      variable2 = Serial.read();
    }

 - **Using a delimiter character for each message:** After each message you can send an extra byte, which value you treat as a delimiter for a message. Normally with this method you save each available byte in an extra buffer, until you receive your delimiter character (often the newline character is used `'\n'`):

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

    void setup(){
      String message="";
    }

    void loop(){
      while(Serial.available>0){
        char c = Serial.read();
        if(c == '\n'){
          // Message is complete in buffer variable
          // Extract values from it
          if(message.length>0){
            byte variable1 = message[0];
          }
          if(message.length>2){
            int variable2 = (message[1] << 8) | message[2];
          }
          // Reset buffer variable
          message = "";
        } else {
          // Message is not complete, add byte to buffer variable
          message += c;
        }
      }
    }

As said in the other answers you have to decide, how to send numerical data.

 - You can send direct byte data as I used in the code above. When you are sending a bigger value to the Arduino than 1 byte, you can take the corresponding number of bytes from the buffer and put them into one variable (`<< 8` shifts the byte data 8 bytes to the left (in the direction of the MSB); `|` makes a bytewise or, that puts the bytes together in this code).
 - If you want to type in values in the serial monitor, you have to consider, that these are simple ASCII encoded strings. In this case you can use the `String.toInt()` function and it's siblings on a substring of your message, that contains the numerical value.


message:
Where can I find the complete list of Arduino Serial Command & Query Strings?

I am planning to use the Arduino as a replacement for a USB-Controlled Digital I/O device, which will be integrated into an existing C++ software package that I created. I understand that the Arduino acts like a Serial device to a PC. Every serial device can be controlled by its own set of commands and queries. However, the only commands and queries that I've found for the Arduino involve flashing one-time programming to it from the "inside" rather than providing real-time automated control from the "outside."

Can anyone tell me where can I find the complete list of Arduino serial command & query strings? Thanks.

body:
Arduino is a computer. It is designed to run programs that interact with real world via multiple digital and analog pins.

It has a USB port (Arduino UNO) to connect with a desktop computer. You develop programs for Arduino with your Windows/Mac/Linux computer and download them to Arduino vía USB port.

So, Arduino do only what you program it to do. No command or query string involved.

An Arduino sketch access use the USB port as a Serial port. It's normally used for debugging purposes (sending back information to the PC) or for configuration/control, if you want not to add a keypad and display to your project.

Some Arduinos doesn't comes with a USB interface.


body:
The Arduino has no "standard" serial commands.

It is a programmable device which you have to program yourself. The only serial commands it can respond to are the serial commands you yourself program it to respond to.

There are projects around that provide a serial interface, but they are generally designed for one specific purpose, and the commands or protocol they implement are unique to that project.

The closest to what you are asking for is the Firmata firmware, which comes with the IDE, and can be used to control the Arduino through the serial port using programs on your PC.


message:
LoRa stops working after several hours. Arduino reset button ineffective

I am designing a master-slave LoRa link between two Arduino Pro Minis. The goal is to control a car heater a few hundred meters from my home. The master sends a command to the slave as needed. The slave acknowledges the command.

If no ACK is received in 5 sec the command is resent. In addition to this the master queries the slave every minute to verify the link.

[This library is used to control the DRF1278F][1]

I presume that a receive callback or a call to LoRa.parsePacket() returns either nothing or a complete packet, so I do not ever have to handle partial packets.

Chinese Arduino Pro Mini 3.3V 8MHz boards are used.
I am using a module DRF1278F module which contains an RFIC SX1278

Connections

    Arduino --> LoRa module
    ----------------------------------
      SS 10 --> NSEL 10k pullup to Vcc
     SCK 13 --> SCK
    MISO 12 --> SDO 100k pulldown to GND
    MOSI 11 --> SDI
     INT  3 --> IO0
     RST  6 --> RST

The device is built on a piece of PCB acting as a ground plane, all GND connections are done to this plane.
It is constructed with short direct wiring.
[![Slave device][2]][2]
**Problem.**

After several hours of operation either the master or the slave sort of hangs up. No radio operations any more. There is activity on the SPI but very different to normal operation. I have tested for weeks and not yet survived for one night.

Pushing the reset button does not restore operations. Removing 3.3V power always restore normal operation, even a very brief short circuit of 3.3V.
There is no need to rest in power down, so probably not an overheat issue.

It can be either the master or the slave end that hangs up. Power cycling only the hung up unit will restore communications. My simple protocol will then resyncronize itself and continue running.

The arduino watch dog timer is activated, however it does not trigger when the hangup occurs as the arduino program loop still runs.

**Things tested.**

The 3.3 V supply has less than 50mV p-p ripple as checked with an oscilloscope set to infinite persistence for 8 hours, while a hangup occurred.

The interface can be run either polled or interrupt driven, no difference.
No String objects are used.

Using different Vcc like 3.0V and 3.6V makes no difference.
Extra Vcc decoupling made no improvement.
Lowering SPI speed from 8MHz to 4MHz made no difference.
Removed Arduino LED on pin 13.

My problem symptoms are similar to [this old question][3]

What can I do to resolve this issue?

Slave code:

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

    /*
    Relay controller, remote end of link
    */
    #include <SPI.h>
    #include <LoRa.h>
    #include <avr/wdt.h>

    //#define TTT

    #define csPin 10
    #define resetPin 6
    #define irqPin 3         // must be a hardware interrupt pin
    #define myLED 8
    #define GNDRET 7
    #define powerPin 9

    unsigned long LEDtime;
    const unsigned long LEDonTime = 500;

    char outgoing[40];
    byte msgCount = 0;
    unsigned long lastLoopTime = 0;
    unsigned long heaterStarted = 0l;
    const unsigned long heaterTime = 60 * 60 * 1000L; // One hour in ms
    unsigned interval = 2000;
    int temp = 2310;
    byte localAddress = 0x11, destination = 0xAA;
    unsigned long ttt;

    volatile char incoming[40];
    volatile int recipient;
    volatile byte sender, incomingMsgId,
    incomingLength, gotMsg, ovrn;

    void setup()
    {
     Serial.begin(9600);
     while (!Serial);
     pinMode(myLED, OUTPUT);
     digitalWrite(myLED, LOW);
     pinMode(GNDRET, OUTPUT);
     digitalWrite(GNDRET, LOW);
     pinMode(powerPin, OUTPUT);
     digitalWrite(powerPin, LOW);

     Serial.println("LoRa Switch 0.1");

     LoRa.setPins(csPin, resetPin, irqPin);
    /*
     LoRa.setTxPower(10);
     LoRa.setSpreadingFactor(12);
     LoRa.setCodingRate4(8);
     LoRa.setSPIFrequency(4E6);
     LoRa.enableCrc();
    */
     wdt_enable(WDTO_1S);

     if (!LoRa.begin(433E6))
     {
      Serial.println("LoRa init failed. Check your connections.");
      {
       // blinking in panic
       LEDtime = millis();
       while (millis() - LEDtime < 75)
       {
        digitalWrite(myLED, HIGH);
       }
       while (millis() - LEDtime < 150)
       {
        digitalWrite(myLED, LOW);
       }
      }
     }

     LoRa.onReceive(onReceive);  // Assign callback
     LoRa.receive();
     Serial.println("LoRa init succeeded.");
    }

    void loop()
    {
     if (millis() - lastLoopTime > 1000)
     {
      // Once per second loop
      lastLoopTime = millis();
     }

    // onReceive(LoRa.parsePacket()); // Polling

     if (gotMsg)  // Flag from CallBack routine
     {
      digitalWrite(myLED, HIGH);
      LEDtime = millis();

    #ifdef TTT
      Serial.print("Received from: 0x");
      Serial.println(sender, HEX);
      Serial.print("Sent to: 0x");
      Serial.println(recipient, HEX);
      Serial.print("Message ID: ");
      Serial.println(incomingMsgId);
      Serial.print("Message length: ");
      Serial.println(incomingLength);
      Serial.print("Message: <<");
      for (int i = 0; incoming[i] != 0; i++)
       Serial.write(incoming[i]);
      Serial.println(">>");
      Serial.print("RSSI: ");
      Serial.println(LoRa.packetRssi());
      Serial.print("Snr: ");
      Serial.println(LoRa.packetSnr());
      Serial.println();
    #endif
      // Command processing
      if (incomingLength == 4)
      {
       // Start heater, it will either timeout or be stopped by a message
       if ((byte)incoming[0] == 0x55 && (byte)incoming[1] == 0xAA)
       {
        Serial.println("Set on");
        digitalWrite(powerPin, HIGH);
        heaterStarted = millis();
       }

       if ((byte)incoming[0] == 0xCC && (byte)incoming[1] == 0x99) // Stop heater
       {
        Serial.println("Set off");
        digitalWrite(powerPin, LOW);
        heaterStarted = 0L;
       }
       // Build ack answer

       if (heaterStarted > 0L)
       {
        // Compute session time in minutes
        ttt = millis() - heaterStarted;
        ttt /= (1000L * 60L); // minutes since start
       }
       else
        ttt = 0L;
       outgoing[0] = (heaterStarted > 0L) ? 'T' : 'F'; // Heater state
       snprintf(outgoing + 1, 30, "%3lu", ttt);

       incoming[0] = 0; // We are done, clear flags
       gotMsg = 0;

       sendAck(outgoing);
      }
      LoRa.receive();

     }

     if (LEDtime) // LED timeout
     {
      if (millis() - LEDtime > LEDonTime)
      {
       digitalWrite(myLED, LOW);
       LEDtime = 0;
      }
     }

     if (heaterStarted) // Heater timeout
     {
      if (millis() - heaterStarted > heaterTime)
      {
       digitalWrite(powerPin, LOW);
       heaterStarted = 0L;
      }
     }
     wdt_reset();
     // END of loop
    }

    void sendMessage(char *outgoing)
    {
     LoRa.beginPacket();                   // start packet
     LoRa.write(destination);              // add destination address
     LoRa.write(localAddress);             // add sender address
     LoRa.write(msgCount++);                 // add message ID
     LoRa.write(bsize(outgoing));        // add payload length
     LoRa.print(outgoing);                 // add payload
     LoRa.endPacket();                     // finish packet and send it
    }

    void sendAck(char *outgoing)
    {
     Serial.println("Send ACK");
     LoRa.beginPacket();
     LoRa.write(destination);
     LoRa.write(localAddress);
     LoRa.write(incomingMsgId);            // report ID
     LoRa.write(bsize(outgoing));        // add payload length
     LoRa.print(outgoing);                 // add payload
     LoRa.endPacket();
    }

    byte bsize(char *ooo)
    {
     byte i = 0;
     while (ooo[i++]);
     return i - 1;
    }

    byte bsize(volatile char *oo)
    {
     return bsize((volatile char *)oo);
    }

    byte insptr;
    void onReceive(int packetSize) // has to be a non blocking function
    {
     if (packetSize == 0) return;     // if there's no packet, return
     if (gotMsg) ovrn = true; // gotMsg should be reset by consumer by now

     // read packet header bytes:
     recipient = LoRa.read();         // recipient address
     sender = LoRa.read();            // sender address
     incomingMsgId = LoRa.read();     // incoming msg ID
     incomingLength = LoRa.read();    // incoming msg length

     insptr = 0;

     while (LoRa.available())
     {
      if (insptr < 38)
       incoming[insptr++] = (char)LoRa.read();
      else
       LoRa.read();  // Flush
     }
     incoming[insptr] = 0;  // End of C string
     gotMsg = true;

    }

    /*
    void setTxPower(int level, int outputPin = PA_OUTPUT_PA_BOOST_PIN);
    void setFrequency(long frequency);
    void setSpreadingFactor(int sf);
    void setSignalBandwidth(long sbw);
    void setCodingRate4(int denominator);
    void setPreambleLength(long length);
    void setSyncWord(int sw);
    void enableCrc();
    void disableCrc();
    */

Master code:

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

    /*
    Relay controller, Controller and GUI base
    */
    #include <SPI.h>
    #include <LoRa.h>
    #include <avr/wdt.h>

    #define TTT

    #define csPin  10
    #define resetPin 6
    #define irqPin 3         // must be a hardware interrupt pin
    #define ackLED 9
    #define LEDGND 8
    #define remoteLED 7

    unsigned long LEDtime;
    const unsigned long LEDonTime = 500;

    char outgoing[40];
    byte msgSequ = 0, mincnt, ack_TO;
    unsigned long lastLoopTime = 0;
    unsigned interval = 2000;
    byte localAddress = 0xAA, destination = 0x11;
    unsigned long ttt;

    volatile char incoming[40];
    volatile int recipient;
    volatile byte sender, incomingMsgId, incomingLength, isACKed, gotMsg, ovrn;

    char cc;

    void setup()
    {
     Serial.begin(9600);
     while (!Serial);
     pinMode(ackLED, OUTPUT);
     digitalWrite(ackLED, LOW);
     pinMode(remoteLED, OUTPUT);
     digitalWrite(remoteLED, LOW);
     pinMode(LEDGND, OUTPUT);
     digitalWrite(LEDGND, LOW);
     isACKed = 1;
     Serial.println("LoRa Master 0.1");

     LoRa.setPins(csPin, resetPin, irqPin);
    /* no specials
     LoRa.setTxPower(10);
     LoRa.setSPIFrequency(4E6);
     LoRa.setSpreadingFactor(12);
     LoRa.setCodingRate4(8);
     LoRa.enableCrc();
    */
     wdt_enable(WDTO_1S);

     if (!LoRa.begin(433E6))
     {
      Serial.println("LoRa init failed. Check your connections.");
      {
       // blinking in panic
       LEDtime = millis();
       while (millis() - LEDtime < 75)
       {
        digitalWrite(ackLED, HIGH);
       }
       while (millis() - LEDtime < 150)
       {
        digitalWrite(ackLED, LOW);
       }
      }
     }

     LoRa.onReceive(onReceive);  // Assign callback
     LoRa.receive();
     Serial.println("LoRa init succeeded.");
    }

    void loop()
    {
     digitalWrite(ackLED, isACKed == 0);

     if (millis() - lastLoopTime > 1000)
     {
      // Once per second loop
      lastLoopTime = millis();

      if (isACKed == 0)
      {
       if (ack_TO++ > 5)
       {
        sendMessage(outgoing); // Resend
        LoRa.receive();
        ack_TO = 0;
        Serial.println("Resend...");
       }
      }

      if (mincnt++ > 60)
      {
       // Once per minute loop
       mincnt = 0;
       if (isACKed)  // Free to ask
       {
        // Heartbeat
        cmdAsk();
        isACKed = 0;
       }
      }
     }

     if ((cc = Serial.read()) > 0)  // Test version, cmd
     {
      if (cc == '1')
      {
       cmdOn();
       isACKed = 0;
      }
      else if (cc == '0')
      {
       cmdOff();
       isACKed = 0;
      }
      else if (cc == 'Q')
      {
       cmdAsk();
       isACKed = 0;
      }
     }
    // onReceive(LoRa.parsePacket()); // Polling

     if (gotMsg)  // Flag from onReceive routine
     {
    #ifdef TTT
      Serial.print("Received from: 0x");
      Serial.println(sender, HEX);
      Serial.print("Sent to: 0x");
      Serial.println(recipient, HEX);
      Serial.print("Message ID: ");
      Serial.println(incomingMsgId);
      Serial.print("Message length: ");
      Serial.println(incomingLength);
      Serial.print("Message: <<");
      for (int i = 0; incoming[i] != 0; i++)
       Serial.write(incoming[i]);
      Serial.println(">>");
      Serial.print("RSSI: ");
      Serial.println(LoRa.packetRssi());
      Serial.print("Snr: ");
      Serial.println(LoRa.packetSnr());
      Serial.println();
    #endif
      // Command processing
      if (incomingLength == 4)
       if (incomingMsgId == msgSequ - 1) // Ack is on last sent
       {
        if (incoming[0] == 'T') digitalWrite(remoteLED, HIGH);
        if (incoming[0] == 'F') digitalWrite(remoteLED, LOW);
        isACKed = 1;
       }
      incoming[0] = 0; // Message is processed, clear flags
      gotMsg = 0;
     }

     if (LEDtime) // LED timeout
     {
      if (millis() - LEDtime > LEDonTime)
      {
       LEDtime = 0;
      }
     }
     wdt_reset();
    } // END of loop

    void cmdOn()
    {
     outgoing[0] = 0x55; // Heater  on
     outgoing[1] = 0xAA;
     outgoing[2] = 'X';
     outgoing[3] = 'Y';
     sendMessage(outgoing);
     LoRa.receive();
    }

    void cmdOff()
    {
     outgoing[0] = 0xCC; // Heater  off
     outgoing[1] = 0x99;
     outgoing[2] = 'A';
     outgoing[3] = 'B';
     sendMessage(outgoing);
     LoRa.receive();
    }

    void cmdAsk()
    {
     outgoing[0] = 0x0F;
     outgoing[1] = 0xF0;
     outgoing[2] = '7';
     outgoing[3] = '7';
     sendMessage(outgoing);
     LoRa.receive();
    }

    void sendMessage(char *outgoing)
    {
     LoRa.beginPacket();                   // start packet
     LoRa.write(destination);              // add destination address
     LoRa.write(localAddress);             // add sender address
     LoRa.write(msgSequ++);                 // add message ID
     LoRa.write(bsize(outgoing));        // add payload length
     LoRa.print(outgoing);                 // add payload
     LoRa.endPacket();                     // finish packet and send it
    }

    byte bsize(char *ooo)
    {
     byte i = 0;
     while (ooo[i++]);
     return i - 1;
    }

    byte bsize(volatile char *oo)
    {
     return bsize((volatile char *)oo);
    }

    unsigned char insptr;
    void onReceive(int packetSize) // is a non blocking function
    {
     if (packetSize == 0) return;     // if there's no packet, return
     if (gotMsg) ovrn = true; // gotMsg should be reset by consumer by now

     // read packet header bytes:
     recipient = LoRa.read();         // recipient address
     sender = LoRa.read();            // sender address
     incomingMsgId = LoRa.read();     // incoming msg ID
     incomingLength = LoRa.read();    // incoming msg length

     insptr = 0;

     while (LoRa.available())
     {
      if (insptr < 38)
       incoming[insptr++] = (char)LoRa.read();
      else
       LoRa.read();  // Flush
     }
     incoming[insptr] = 0;
     gotMsg = true;
    }

    /*
    void setTxPower(int level, int outputPin = PA_OUTPUT_PA_BOOST_PIN);
    void setFrequency(long frequency);
    void setSpreadingFactor(int sf);
    void setSignalBandwidth(long sbw);
    void setCodingRate4(int denominator);
    void setPreambleLength(long length);
    void setSyncWord(int sw);
    void enableCrc();
    void disableCrc();

    RSSI always a value between -30 ( very close) and - 120
    SNR 0 is noise floor… max = 10

    */

  [1]: https://github.com/sandeepmistry/arduino-LoRa
  [2]: https://i.stack.imgur.com/GMSFm.jpg
  [3]: https://arduino.stackexchange.com/questions/29385/arduino-box-stops-working-reading-rfid-tag-and-sending-data-over-network?s=2|22.3533

body:
I feel I want to report the probable solution to this problem.
I hope an answer to my own question is appropriate.

After much testing I found an interaction between the boot loader and the watchdog. This post describes it well: [Watchdog timer blog post][1]
So, replacing the boot loader seems to remove the hangup, so far ...
Why the watchdog triggers in the first place remains to be found out but presently it does little or no harm.

A side note, the reset button seems to reset the ProMini if pushed reasonably soon after the hangup. If pushed hours later it has no effect.

  [1]: https://andreasrohner.at/posts/Electronics/How-to-make-the-Watchdog-Timer-work-on-an-Arduino-Pro-Mini-by-replacing-the-bootloader/


message:
UID value arduino uno

How to read UID value in arduino uno to PHP language?
before, thanks for a lot

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

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

body:
Use this library: https://github.com/rubberneck/php-serial

On GNU/Linux, you may need to be a member of the ‘dialout’ group. Ubuntu solves this problem by making its users members of every group, so you may not need to edit `/etc/group`

Once you have connected via a USB or USB-TTL cable (the latter will not force a reset upon connect), use a buffer to store all the reads, then parse them.


message:
Can not initialize ESP module in Arduino SoftwareSerial

Can not initialize ***ESP module*** in Arduino SoftwareSerial's example sketch in configuring ***WiFi module***.

In the sketch it tells:

    #include "WiFiEsp.h"
    // Emulate Serial1 on pins 6/7 if not present
    #ifndef HAVE_HWSERIAL1
    #include "SoftwareSerial.h"
    SoftwareSerial Serial1(11,12); // RX, TX
    #endif

I plugged jumper wires in from esp8266 RX to Digital 11 of mega which is RX and TX of esp8266 to Digital 12 of mega, and I compile the code and looked at the Serial Monitor, but it says:

    [WiFiEsp] Initializing ESP module
    [WiFiEsp] >>> TIMEOUT >>>
    [WiFiEsp] >>> TIMEOUT >>>
    [WiFiEsp] >>> TIMEOUT >>>
    [WiFiEsp] >>> TIMEOUT >>>
    [WiFiEsp] >>> TIMEOUT >>>
    [WiFiEsp] Cannot initialize ESP module

Advise is greatly appreciated.

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

    #ifndef HAVE_HWSERIAL1
    #include "SoftwareSerial.h"
    SoftwareSerial Serial1(11,12); // RX, TX
    #endif

Because your Mega has a Hardware `Serial1` port, `HAVE_HWSERIAL1` is defined. Thus the lines inside that preprocessor conditional will not be compiled. This means you should connect the ESP8266 to the `Serial1` lines on your Mega:

<!-- language: lang-none -->

    Mega | ESP8266
    --------------
    19   | TX
    18   | RX


message:
LCD not displaying text

I am working with an Arduino due and currently using the Arduino liquid crystal library to display data on an LCD screen (mc42004A6wk-bnmlw) which uses the Hitachi HD44780 controller. The LCD has been update to v2 and is now using the Sitronix ST7066U controller.

From what I have read the two controllers are compatible and the liquid crystal library should work for both. I am using the same software and hardware setup as before but the screen will not display anything.

The software I use is quite complex so I moved to a simple hello world program (below) to test and I still have the same issues. Any advice would be greatly appreciated.

    #include <LiquidCrystal.h>
    #include <Arduino.h>

    LiquidCrystal lcd(30, 31, 32, 33, 46, 47);

    void setup()
    {

      pinMode(36,OUTPUT);

      digitalWrite(36, LOW);

      delay(5000);

      // set up the LCD's number of columns and rows:
      lcd.begin(20, 4);

      lcd.clear();

      // Print a message to the LCD.
      lcd.print("hello, world!");
    }

    void loop()
    {

      delay(5000);
      // set the cursor to column 0, line 1
      // (note: line 1 is the second row, since counting begins with 0):
      lcd.setCursor(0, 1);
      // print the number of seconds since reset:
      lcd.print(millis() / 1000);
    }

body:
Try using this code, I have edited some parts of your code so this should work.

    #include <LiquidCrystal.h>

    const int rs = 30, en = 31, d4 = 32, d5 = 33, d6 = 46, d7 = 47;
    LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

    void setup()
    {

      pinMode(36, OUTPUT);
      digitalWrite(36, LOW);
      delay(5000);    //Its okay to use delay here since its in the setup() function and will run only once

      // set up the LCD's number of columns and rows:
      lcd.begin(20, 4);

      // Print a message to the LCD.
      lcd.print("hello, world!");
    }

    void loop()
    {
      // set the cursor to column 0, line 1
      // (note: line 1 is the second row, since counting begins with 0):
      lcd.setCursor(0, 1);
      // print the number of seconds since reset:
      lcd.print(millis() / 1000);
    }

For this Hello World sketch, avoid using `delay();` statement in the `void loop()` as it is not good to use when you have the `millis();` used.

If the above wont work, **check your LCD Wiring**, many problems usually arouse from wrong wirings.
Also I may suggest you to use some cheap LCD I2C Backpacks as this will ease the coding and will use less wire and pins on your Arduino. Here is a example
[![enter image description here][1]][1][![enter image description here][2]][2]

If your'e going to use a I2C LCD Backpack, here is a working sample code.

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

    #define BACKLIGHT_PIN     13

    LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address

    // Creat a set of new characters
    const uint8_t charBitmap[][8] = {
       { 0xc, 0x12, 0x12, 0xc, 0, 0, 0, 0 },
       { 0x6, 0x9, 0x9, 0x6, 0, 0, 0, 0 },
       { 0x0, 0x6, 0x9, 0x9, 0x6, 0, 0, 0x0 },
       { 0x0, 0xc, 0x12, 0x12, 0xc, 0, 0, 0x0 },
       { 0x0, 0x0, 0xc, 0x12, 0x12, 0xc, 0, 0x0 },
       { 0x0, 0x0, 0x6, 0x9, 0x9, 0x6, 0, 0x0 },
       { 0x0, 0x0, 0x0, 0x6, 0x9, 0x9, 0x6, 0x0 },
       { 0x0, 0x0, 0x0, 0xc, 0x12, 0x12, 0xc, 0x0 }

    };

    void setup()
    {
       int charBitmapSize = (sizeof(charBitmap ) / sizeof (charBitmap[0]));

      // Switch on the backlight
      pinMode ( BACKLIGHT_PIN, OUTPUT );
      digitalWrite ( BACKLIGHT_PIN, HIGH );

      //lcd.begin(16,2);
      lcd.begin(20,4); // initialize the lcd

       for ( int i = 0; i < charBitmapSize; i++ )
       {
          lcd.createChar ( i, (uint8_t *)charBitmap[i] );
       }

      lcd.home ();                   // go home
      lcd.print("LCD TESTER - BY:");
      lcd.setCursor ( 0, 1 );        // go to the next line
      lcd.print ("ABBAS (PRJCT.ME)");
      delay ( 3000 );
    }

    void loop()
    {
       lcd.home ();
       // Do a little animation by writing to the same location
       //for ( int i = 0; i < 2; i++ )
        for ( int i = 0; i < 4; i++ )
       {
          //for ( int j = 0; j < 16; j++ )
          for ( int j = 0; j < 20; j++ )
          {
             lcd.print (char(random(7)));
          }
          lcd.setCursor ( 0, 1 );
           for ( int j = 0; j < 20; j++ )
          {
             lcd.print (char(random(7)));
          }
          lcd.setCursor ( 0, 2 );
           for ( int j = 0; j < 20; j++ )
          {
             lcd.print (char(random(7)));
          }
          lcd.setCursor ( 0, 3 );

       }
       delay (200);
    }

  [1]: https://i.stack.imgur.com/FLavY.png
  [2]: https://i.stack.imgur.com/3LRXV.jpg


body:
So after further investigation into the IDE, Libraries, board manager, hardware etc I discovered what was causing the issue.

On the initial hardware design the hardware engineer placed a capacitor on the enable leg between the LCD screen and the microcontroller. I have no idea why as I have not seen this done in any wiring diagrams but removing it has done the trick. The V2 board now works with all the original code and libraries.


message:
Missing character when introducing delay in the code

I am using the following code for reading any incoming message, and doing something after decoding the incoming string. There is a delay of 10sec in the code. When this delay is not introduced in the code, it is working nice. In this case, the output is like below.

    +CIEV: "MESSAGE",1

    +CMT: "+919080404532",,"2018/02/09,19:30:51+06"
    This is an incoming test message

When the delay is introduced, I am unable to see the message on the serial monitor, and subsequent action is not taken by the code. The output is like below.

    +CIEV: "MESSAGE",1
    +CMT: "+919080404532",,"2018/02/09,1

It is clear that, I am missing some character in serial monitor. If delay is reduced to 400 ms, the output is like below.

    +CMT: "+919080404532",,"2018/02/09,19:30:51+06"
    This is an incoI am working other job

I checked the following, but did not get any improvement.

1. `Serial.flush` and `mySerial.flush`

2. Increased both hardware, and software aerial buffer size

3. used `if (!mySerial.available()` before delay

4. Changed baud rate for both

5. Instead of of `Serial.readString()`, I used `Serial.read()` character by    character inside function loop

Without use of the delay, it is working nice. I Think you guys are experienced, and can sort out the problem easily.

    //while Introducing any delay in function loop, incoming message cant be read
    //working with power failure but with serial monitor
    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(9, 10);  // TX-Pin11, RX-Pin10
    String str="";
    void updateSerial()
    {
      delay(2000);
      while (Serial.available()) {
        mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
      }
      while(mySerial.available()) {
        Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
      }

    }

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

    void loop()
    {
     Serial.println("I am working other job");
     //delay(10000);            //If you give this delay, then incoming message cant be read
     smstask();
    }

    void smstask()
    {
    if(mySerial.available())
    {
    str=mySerial.readString();
    Serial.println(str);
    int bra = str.indexOf('@');
    int ket = str.indexOf('#');
    String str1=str.substring(bra+1,ket);

    if(str1=="server")
    {
    Serial.println(str);
    int i=random(1,500);
    String str2=(String)i;
    String str3="@deviceA#"+str2;
    mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
    updateSerial();
    mySerial.println("AT+CMGS=\"+917602304567\"\r"); // Replace x with mobile number
    updateSerial();
    mySerial.println(str3);// The SMS text you want to send
    updateSerial();
    mySerial.println((char)26);// ASCII code of CTRL+Z
    updateSerial();
    mySerial.println("AT+CMGD=1,4"); // AT Command to receive a live SMS
    updateSerial();
    }
    }

    }

    void modemsetup()
    {
      for(int i=0;i<3;i++)
      {
      mySerial.println("AT");          //Once the handshake test is successful, it will back to OK
      updateSerial();

      mySerial.println("AT+CSQ");      //Signal quality test, value range is 0-31, 31 is the best
      updateSerial();

      mySerial.println("AT+CCID");    //Read SIM information to confirm whether the SIM is plugged
      updateSerial();

      mySerial.println("AT+CREG?");    //Check whether it has registered in the network
      updateSerial();

      mySerial.println("AT+SNFS=0");  //Adjust to earphone mode(AT+SNFS=1 is microphone mode)
      updateSerial();

      mySerial.println("AT+CRSL=2");  //Adjust volume, volume range is 0-15, maximum:15
      updateSerial();

      mySerial.println("AT+CMGF=1");
      updateSerial();

      mySerial.println("AT+CMGD=1,4");
      updateSerial();
      }

      mySerial.println("AT+CMGS=\"+917602304567\"\r");
      updateSerial();

      mySerial.println("I am SMS from GSM Module");
      updateSerial();

      mySerial.println((char)26);// ASCII code of CTRL+Z
      updateSerial();

    }

body:
If serial data is coming in, and your code is doing a `delay`, the incoming data is stored in a buffer (of 64 bytes). But if you wait too long, the buffer will fill-up. Once it's full, any further incoming serial data isn't stored, and will be lost.

In your third output example, you get exactly 63 characters. Which is the maximum size a 64-byte cyclic buffer can store.


message:
Ubuntu class string has no member remove

I am running some code that works fine on my windows system using the .remove method.  On Ubuntu 16.04 I get the following errror:

    error: ‘class String’ has no member named ‘remove’

To see if it was installation, I uninstalled arduino with

    sudo apt-get purge arduino arduino-core

then

    sudo apt-get update
    sudo apt-get upgrade

    sudo apt-get install arduino arduino-core

and the issue remains.  I have seen some people say opening arduino through the terminal ([from this][1]), although that does not fix it.

Arduino version
2:1.0.5+dfsg2-4

Any help is appreciated.

  [1]: https://github.com/arduino/Arduino/issues/2512

body:
The `remove` method was added to the `String` class in 1.0.6.

Installing Arduino IDE from the Ubuntu repository gets you a really old package (1.0.5).

You should [download][1] and install the newest version from the official Arduino page.

  [1]: https://www.arduino.cc/en/Main/Software


message:
Arduino Leonardo RX TX mystery

I'm at the tail end of a project using a Leonardo, a HC-06 bluetooth module and a few cell phone vibration motors.  Everything is working fine except the serial communication between the Leonardo and the HC-06.  I've done some tests to rule out common mistakes

1. TX is connected to RX, and vice versa.
2. Using a multimeter I checked for continuity with the RX TX, no problem there
3. I can upload the script
4. I uploaded the exact same script to an Uno, using the same HC-06.  I was able to connect to the HC-06 with my phone and execute the script.  So I know it's not the script and I know it's not the HC-06.
5. The Leonardo is working properly because I can upload the script and execute it using the Arduino Serial Monitor.

The only clue I have is that I can upload the script with the RX/TX connected and that's not supposed to work.  However, I checked the connections and there is continuity.  So I'm stumped.  The only thing I can think of is that I damaged the RX/TX while I was soldering, but I'm hoping it's not that.  Is there a way to test for that.  Any suggestions?

    /*
     * created by Rui Santos, http://randomnerdtutorials.com
     * Bluetooth App - Turn On and Off LED
    */

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(1, 0); // RX, TX

    int led = 3;
    int state;

    void setup() {
      // initialize the digital pin as an output.
      pinMode(led, OUTPUT);
      // initialize serial communication at 9600 bits per second:
      Serial.begin(9600);
    }

    void loop() {
      if(Serial.available() > 0){
          state = Serial.read();}

      if (state == '1') {
          digitalWrite(led, HIGH);}   // turn the LED on (HIGH is the voltage level)

      else if (state == '2') {
          digitalWrite(led, LOW);}    // turn the LED off by making the voltage LOW

      delay(100);               // wait for 100ms

      //For debugging purpose
      //Serial.println(state);
    }

body:
An Arduino Leonardo has native USB support. Which means that it has separate serial interfaces to the PC and to the hardware pins.

`Serial` is only used for the communication with the PC and is unrelated to the hardware serial pins 0 and 1. Those are exposed trough `Serial1`.

So, if you are using the exact same Uno sketch, that uses the hardware serial pins, it can't work on a Leonardo, because data is just sent-to/read-from the PC and not to the connected Bluetooth module connected on pins 0 an 1.


message:
Sending Float values from Python to Arduino via serial communication

I want to Control the current flowing through a circuit using an Arduino. I have trained a PID controller for this purpose. I am using a current sensor to determine the error. It runs successful on my Arduino.
In my next step I want build a system where I can send the Current setpoint (deter mined by my python code) value to the Arduino through serial communication. I am able to send integer values to Arduino. But I am unable to send and receive float values from Python to Arduino. I want to know the necessary code to be written in both sender and receiver.
I tried of converting float to string and then send it to Arduino. But I failed. Please help.

Arduino Code(edit- Sorry previous code was an old file. Here is the correct one):

    void setup() {
      // put your setup code here, to run once:
    Serial.begin(9600);
    //pinMode(13,OUTPUT);
    }
    float f;

    void loop() {
     if(Serial.available())
          {f=Serial.parseFloat();
            Serial.println(f);
          }
        delay(1000);
       }
    //count=count+1;
          //delay(1);
    //}

Python Code (edit- Sorry, the previous code was from an old file. Here is the correct one):

    import serial
    import time
    import struct

    ser = serial.Serial('/dev/ttyACM0', 9600, timeout = 1) # ttyACM1 for Arduino board
    data=5.7

    while True:
         ser.write(str(data))
         time.sleep(1)
         ser.flush()

When I run this code I get the following output on the Arduino Serial Monitor. As shown in the figure below.

[![Ardiuno Serial Monitor][1]][1]

Thank you.

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

body:
Problem with Serial.parseFloat() is that it blocks until it read the value.

Try this code, which implement a minimal float parse routine (no error checking), and it's not blocking, so you can do other things while waiting for float to come

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

     while(!Serial);

     Serial.println("Start");
    }

    float result = 0;
    bool dec = false;
    int decDiv = 10;

    void loop()
    {
       // Float are positive, with format 999.99 (no sign, variable length integer/dec
       // We read only one char in each execution.

     if(Serial.available()) {
      // Read a single char from serial input.
      char c = Serial.read();

      if(isDigit(c)) {
       int val = (c - '0');  // Convert ASCII to binary.

       if(dec) {
                    // We just read a decimal digit.
        result += (float) val / decDiv;
        decDiv *= 10;
       } else {
                    // We just read a integer digit.
        result = result * 10 + val;
       }
      } else if(c == '.') {
                // Decimal part start now.
       dec = true;
      } else {
                // Any other thing is the end of the float value.
       Serial.println(result);
                // And reset everything for another float value.
       result = 0;
       dec = false;
       decDiv = 10;
      }
     }
    }


body:
It would seem you managed to solve your problem with
`Serial.parseFloat()`. This is probably the easiest solution, but it has
one serious drawback: it is a _blocking_ function. Which means, during
all the time needed by the serial port to transfer the number, your
Arduino does nothing but wait for the incoming characters. This is an
issue if your program has other task to do like, e.g., manage a PID
regulation.

I suggest you consider reading the serial port in a _non blocking_
fashion instead. This should make your PID happier, as it won't feel
neglected while you read the incoming data. Look Alterno's answer is a
good example of a non-blocking function that combines reading and
parsing. However, I would like to point out that you do not need to
implement your own number parser if you don't want to. A very common
pattern is to instead store the incoming characters in a buffer and,
when you see the character chosen as a terminator (e.g. ASCII LF), you
parse the buffer at once using either `strtod()` or `atof()`. For
example:

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

    void loop() {
        static char buffer[32];
        static size_t pos;
        if (Serial.available()) {
            char c = Serial.read();
            if (c == '\n') {  // on end of line, parse the number
                buffer[pos] = '\0';
                float value = atof(buffer);
                Serial.print("received: ");
                Serial.println(value);
                pos = 0;
            } else if (pos < sizeof buffer - 1) {  // otherwise, buffer it
                buffer[pos++] = c;
            }
        }
    }


message:
Why doesn't pin 3 blink? It blinks in another program

I used toneMelody example code (sketch sample 02.Digital->toneMelody) on an Arduino UNO. Then I wanted to blink an LED with the melody.

Here's the code:

    #include "pitches.h"
    #define BLUE 3 // pin 3 does not blink. but, pin 9 ok.
    #define GREEN 5
    #define RED 6

    int melody[] = {
      NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
    };
    int noteDurations[] = {
      4, 8, 8, 4, 4, 4, 4, 4
    };

    void setup() {
      for (int thisNote = 0; thisNote < 8; thisNote++) {
        analogWrite(RED, 0);
        analogWrite(GREEN, 0);
        analogWrite(BLUE, 0);
        int noteDuration = 1000 / noteDurations[thisNote];
        tone(8, melody[thisNote], noteDuration);
        int pauseBetweenNotes = noteDuration * 1.30;
        int color = melody[thisNote] % 5;
        if(color == 0) {
          analogWrite(RED, 200);
        } else if(color == 1) {
          analogWrite(GREEN, 200);
        } else {
          analogWrite(BLUE, 200);
        }
        delay(pauseBetweenNotes);
        noTone(8);
      }
      analogWrite(RED, 0);
      analogWrite(GREEN, 0);
      analogWrite(BLUE, 0);
    }

    void loop() {
      // no need to repeat the melody.
    }

Unfortunately, pin 3 did not blink.
But it worked when I changed pin 3 to pin 9.

To check whether pin 3 or Blue LED is broken,
I checked with the following code.

    #define BLUE 3

    void setup() {
      analogWrite(BLUE, 0);
    }

    void loop() {
      for(int i = 0 ; i < 255 ; i ++) {
        analogWrite(BLUE, i);
        delay(10);
      }
      analogWrite(BLUE, 0);
    }

This code worked. Blue LED blinked.
Why couldn't pin 3 blink with toneMelody?

Thanks.

body:
In [the tone function reference][1] you can read:

> Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).

[analogWrite()][2] is PWM

  [1]: https://www.arduino.cc/reference/en/language/functions/advanced-io/tone/
  [2]: https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/


message:
Two stepper one by one

I want to run two stepper motor one after the other
Stepper1  has to5 rotation
And stepper 2  has to move 1rotation Here is the code

Stepper 1 is nema 34
And stepper 2 is nema 24

    #include <AccelStepper.h>

    // Define a stepper and the pins it will use
    AccelStepper stepper1 (1, 3, 2); // Defaults to 4 pins on 2, 3, 4, 5 mortor (A)
    AccelStepper stepper2 (1, 5, 4); // Defaults to 4 pins on 2, 3, 4, 5 motor (B)

    long Steps_For_Distance1 = 3; // 3cm
    long Steps_For_Distance2 = 5; // 5cm
    long currentPos = 0;
    long targetPos = 200;
    long targetPos_Reverse = -200;
    long Motor_Speed1 = 50;
    long Motor_Speed2 = 400;
    long Motor_Speed3 = 800;
    int Op_Sw = 0;
    const int buttonPin = 2;     // the number of the pushbutton pin

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

    // variables will change:
    int buttonState = 0;         // variable for reading the pushbutton status

    void setup()
    {
      // initialize the LED pin as an output:
      pinMode(ledPin, OUTPUT);

      // initialize the pushbutton pin as an input:
      pinMode(buttonPin, INPUT);
    }

    void checkStepper1_For_DT(AccelStepper &astepper)
    {
      if (astepper.distanceToGo() == 0)
      {
        // Random change to speed, position and acceleration
        // Make sure we dont get 0 speed or accelerations
        astepper.setCurrentPosition(currentPos);
        astepper.moveTo(targetPos);
        astepper.setSpeed(Motor_Speed1);
        astepper.setAcceleration(100);
      }
    }
    void checkStepper2_For_360(AccelStepper &astepper)
    {
      if (astepper.distanceToGo() == 0)
      {
        // Random change to speed, position and acceleration
        // Make sure we dont get 0 speed or accelerations

        astepper.moveTo(targetPos);
        astepper.setMaxSpeed(Motor_Speed2);
        astepper.setAcceleration(100);
      }
    }
    void PatternToBeLooped_For_Cycle1()
    {
      int count = 0;

      for (count == 0; count <= 5; count ++)
      {
        checkStepper1_For_DT(stepper1);
        stepper1.runSpeedToPosition();
      }

      checkStepper2_For_360(stepper2);
      stepper2.runSpeedToPosition();
    }
    void loop() {
        PatternToBeLooped_For_Cycle1();
      }

I had run the code
But it didn't work
Both motor are running at same time

Please help me
Where I made mistake

Thank you in advance

---

I had try by delay (1000);
But
Still they  both stepper are moving  at a same time and get delay at same time

body:
I looked into the source of the AccelStepper library [here][1], which may be your library or one similar to it. The function `runSpeedToPosition()` does not block until the desired position is reached. Instead inside the function you see code that executes a step, when the right time (according to `millis()`), calculated through the speed, is reached, else it will return false. You are supposed to call this function very often while the motor moves. This enables you to drive more than one motor simultaneously with different speeds.

Since you don't want to drive both motors at the same time, you have to loop, until the first motor have reached the desired position; then doing the same with the second motor. Try something like this:

<!-- language: c -->

    void PatternToBeLooped_For_Cycle1()
    {
      int count = 0;
      for (count == 0; count <= 5; count ++)
      {
        checkStepper1_For_DT(stepper1);
        while(stepper1.currentPosition() != stepper1.targetPosition()) stepper1.runSpeedToPosition();
      }

      checkStepper2_For_360(stepper2);
      while(stepper2.currentPosition() != stepper2.targetPosition()) stepper2.runSpeedToPosition();
    }

Note: With this change the function `PatternToBeLooped_For_Cycle1()` blocks the execution of the loop function, until the motors have done their movement. To avoid this you can use an if-statement, which executes the code for stepper1 or stepper2 depending on the `millis()` function. This works the same way as the BlinkWithoutDelay example in the Arduino IDE.

  [1]: https://github.com/adafruit/AccelStepper