message:
How to read sound sensor readings and light up sensor with water sensor if the readings is above threshold & when water is detected for 2 mins?

I am student that is new to Arduino and working on a project to trigger an alert if the sound level detected exceeds the threshold for a period of 2 mins. But I am stuck, would like to check how do I write a code to analog read sound sensor input and light up sensor if the readings is above datum for 2 mins? I had simple code but it triggers the light up immediately. :/

I have combined the coding together and this is the new code that worked with the help gotten:

        #define led 4 // led to D4
    const int soundsensor= A0; //sound sensor to A0
    const int threshold= 100; // to set the threshold value for sound sensor
    int ssanalogread; //name of sound sensor analog read
    bool wasOver;//add to globals
    unsigned long firstDetect;

    void setup() {
      Serial.begin(9600);
      pinMode(led,OUTPUT);
      pinMode(soundsensor,INPUT);// to get input from sound sensor

    } // end void setup

    void loop() {

         sound1();

    } // close void loop

    void sound1() {

      ssanalogread=analogRead(soundsensor); // reads analog data from sound sensor
      Serial.println(ssanalogread);

       if ((ssanalogread > threshold)){ //replace if else
          if(!wasOver){
           firstDetect = millis();
       }
       if(millis() - firstDetect > 1*10*1000){
          digitalWrite(led,HIGH); //turns led on if the sensor reads more than threshold
       } //end if
          wasOver = true;
       } // end first if
      else {
         wasOver = false;
         digitalWrite(led,LOW);
      } // end else

    } //end loop

    //this code works and is ok to run. can adjust the timing

body:
You set a timestamp when the sound first exceeds the threshold and only set the output high when `millis() - firstDetect > 2*60*1000`

    //add to globals
    bool wasOver;
    unsigned long firstDetect;

    //replace if else
    if ((ssanalogread > threshold)){
       if(!wasOver){
           firstDetect = millis();
       }
       if(millis() - firstDetect > 2*60*1000){
          digitalWrite(led,HIGH); //turns led on if the sensor reads more than threshold
       } //end if
       wasOver = true;
    } else {
       wasOver = false;
       digitalWrite(led,LOW);
    }


sender: user

sender: assistant

body:
This is actually a lot harder than you might at first think.

Your "sound sensor" is little more than a microphone and amplifier. It gives you an audio waveform - whereas what you are interested in is the peak power.

An audio waveform goes both positive and negative:

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

The "peak" of the waveform can both be positive (above the line) or negative (below the line).

To get that peak you have to rapidly sample over a short period and find both the maximum and minimum values, and get the difference between them.

However, the Arduino can't see negative values on the ADC - so you only get the upper portion of the waveform, which is less than ideal.  Really you should add a DC offset to the output of the sound sensor to bring the signal up to the middle of the ADC range (adding a 10kΩ + 10kΩ voltage divider across the input pin to +5V/GND would do the job).

If you don't add a DC offset then you can rapidly sample for a short period of time and work out the maximum value:

    uint16_t getMaximum(uint8_t pin, uint32_t t) {
        uint16_t maximum = 0;
        uint32_t ts = millis();
        while (millis() - ts < t) {
            uint16_t sample = analogRead(pin);
            if (sample > maximum) {
                maximum = sample;
            }
        }
        return maximum;
    }

Now to get the maximum over, say, a 10ms period, you can:

    uint16_t maximum = getMaximum(A0, 10);

However, if you add a DC offset it gets a little more tricky, but the results will be better:

    uint16_t getMaximum(uint8_t pin, uint32_t t) {
        int16_t maximum = 0;
        int16_t minimum = 0;
        uint32_t ts = millis()
        while (millis() - ts < t) {
            // The -512 here removes the DC offset from the reading. 512 is half
            // the ADC range.
            int16_t sample = analogRead(pin) - 512;
            if (sample > maximum) {
                maximum = sample;
            }
            if (sample < minimum) {
                minimum = sample;
            }
        }

        // We now have a positive value as the maximum and a negative
        // as the minimum - or zero if none went into the max or min
        // region of the waveform.  Subtract a negative from a positive
        // is like adding a positive to a positive.  But we only want
        // a positive result, so we'll get the absolute value.
        return abs(maximum - minimum);
    }

Now that you actually have your peak-peak value of your waveform over a short period you can use it to work out when the sound goes above a threshold and when it goes below, and how long it's been above that threshold.  The basic method is:

* Is the sound above the threshold?
  * Yes: Was it above the threshold before?
    * No: Set a timestamp and a flag to say it's above the threshold.
    * Yes: Has it been above > 2 minutes?
       * Yes: light the LED
  * No: Was it above the threshold before?
    * Yes: Has it been above > 2 minutes?
       * Yes: Extinguish the LED

The thing here is to know that you are looking for changes in the "above the threshold" state to start your timing.  A simple implementation may look like:

    static uint32_t wentAbove = 0;
    static bool isAbove = false;
    const uint16_t threshold = 300;

    uint16_t maxval = getMaximum(A0, 10);

    if (maxval > threshold) {
        if (!isAbove) {
            isAbove = true;
            wentAbove = millis();
        } else {
            if (millis() - wentAbove > 120000) {
                digitalWrite(13, HIGH);
            }
        }
    } else {
        if (isAbove) {
            isAbove = false;
            digitalWrite(13, LOW);
        }
    }

<sub>*Note: all code untested.*</sub>

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


message:
The ESP8266 connects to open WiFi hotspots, even If I supply a password

This question is more out of curiosity, then out of a need to solve something.

I was trying out some experiments with the ESP8266 Arduino core when I realized that I had programmed an SSID and password for the ESP8266, but the WiFi that I had set up was an open network.

I tried going through the documentation and then the Arduino core source code, but couldn't find if `WiFi.begin(ssid,passphrase)` a function does this on purposes, as in it was designed that way, or did it just happen to work this way.

Also, I would like to know if there is a way to stop the ESP from connecting to an open network when the passphrase is provided.

body:
It's probably by chance - however it's impossible to know.

Connecting is done by `wifi_station_connect()`, which is a function provided by the (closed source) ESP8266 SDK. So we can never know what it's actually doing.

However, the sequence is probably something like:

* -> Connect
* <- Ok, give me a password
* -> Here it is
* <- Right, you're connected

Or, with no PSK:

* -> Connect
* <- Right, you're connected

Although you specify the password (which just gets stored in the configuration) if it never asks for it then it just doesn't use it.

Can you force it? Not without knowing what's going on in the mystery `wifi_station_connect()` function.  There is nothing much [in the documentation](http://www.liot.io/media/liot_esp8266_env/documents/esp8266_non_os_sdk_api_reference.pdf) for the SDK that even hints at a clue.


message:
What is the best serial communication method between an Arduino and a spectral sensor?

I have an Adafruit AS7262 visible spectral sensor. I want to receive the data of the sensor with an Arduino.
The sensor has two serial communication options: UART(asynchronous) or I2C(synchronous). I want to know which method is more suitable for the sensor to communicate with the Arduino microcontroller. I was thinking that UART is more suitable, because the sensor has his own master clock, in other words if I choose I2C then the Arduino needs to work as the "slave" and I dont think that is very suitable, because the Arduino has its own master clock also. For this reason I think that asynchronous method is more reliable, but I am not sure about this.

body:
The I2C on this device is slave, not a master. Even though it has its own clock, it is designed to operate as a slave being read by a master.

You will have no issues using the I2C interface - in fact [Adafruit uses it for their own software library][1].

Since there is already a I2C-based library available from the manufacturer I would use that, unless there is a good reason to use the UART instead.

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


body:
Arduino will serve as the Master controller and will send the call to the slaves. AS7262 is a sensor device, Arduino will send the call commmand then receive the data from its sensors.  Sometime confusion arrises because developers are accustomed to the desktop computer as the Master, but in this case, Arduino receives data and engage a forward action like sending info to USB or WiFi connected computer or just do a feedback control to another digital or analog device.

You will find further reading on this subject at Arduino community [here][1]

Also

  [1]: https://forum.arduino.cc/index.php?board=11.0


message:
getting error 'Serial' was not declared in this scope

I am adding Dust Sensor to my particle photon project at home,

I got [this GitHub project][1] that I want to test before implementing a final code.

I am not an expert in cpp, I wanted to modularise the dust sensor codebase to separate library so I created new dustSensor.cpp file and kept the code linked above.

but I keep getting error:

'Serial' was not declared in this scope

'Serial1' was not declared in this scope

'DEBUG' was not declared in this scope

'DEC' was not declared in this scope [dustSensor.cpp:13:57:][2]

I do have Serial.begin(57600) called in setup() function but still get the above error

  [1]: https://github.com/MartyMacGyver/PMS7003-on-Particle/blob/master/pms7003-photon-demo-1/pms7003-photon-demo-1.ino
  [2]: https://github.com/MartyMacGyver/PMS7003-on-Particle/blob/master/pms7003-photon-demo-1/pms7003-photon-demo-1.ino#L75

body:
I learned that I needed to include `Arduino.h` header file

apart from that I learned .ino files and .cpp files is that the .ino files transparently include particle.h for you.

The other difference is that .ino files generate forward declarations for you. This is necessary when you’ve implemented a function later in the file than when you’ve first used it. For example, if you pass the function to something like Particle.subscribe in setup() but you’ve implemented it farther down the file.


message:
How to build a valid HTTP Response. Recv failure: Connection reset by peer

I'm developing an Arduino server that should respond with a message when it receives a POST Request.

If I test my project with a HTTP Client (like insomnia or postman), I get an error:

    Error: Failure when receiving data from the peer

I still get a response that I can read but with a final error.

That's my client request:

    > POST /SOMETHING/ HTTP/1.1
    > Host: [ARDUINO IP]
    > User-Agent: insomnia/6.2.0
    > Accept: */*
    > Content-Length: 0

And this is my Arduino response considered as not valid:

    < HTTP/1.1 200 OK
    < Connection: close
    < [MY MESSAGE]

    * Recv failure: Connection reset by peer
    * stopped the pause stream!
    * Closing connection 2

As you can notice, I just added 2 strings

    HTTP/1.1 200 OK
    Connection: close
before the real message.

Am I missing something to create a valid response?

Thanks

body:
HTTP requires an empty line after HTTP headers.

First line is status line. Then the header lines. The headers are terminated by an empty line. Then the response body follows. Line terminator for HTTP is \r\n. Arduino println() function uses \r\n.

The response with body should contain Content-type and Content-length header. Alternative to Content-lenght is "chunked" Transfer-Encoding.

ESP8266WebServer library handles HTTP for you.


message:
OV2640 with 18 Pins - No XLCK System Clock

I'm trying to connect an OV2640 camera module to a microcontroller.

This camera module has only 18 pins as seen in this schema:
https://i.stack.imgur.com/wVBwV.jpg

Here an image of the module:
https://i.stack.imgur.com/tUVg0.jpg

These pins are on the module:

 - 3.3V
 - GND
 - VSYNC
 - SCL
 - SDA
 - HREFF
 - D0 - D7
 - DCLK
 - PWDN
 - NC

Maybe I could set XLCK and PLCK via the DCLK pin but I don't know how.

I am pretty new to camera modules and searched the net a lot of times. Most examples are for the OV7670. This module has also 18 Pins but all are used quiet contrary to the OV2640.

Could anybody help me connect and get a signal?

body:
In this specific OV2640 module, it's supposed to have a 12MHz oscillator in the board connected to XLCK pin (you can all time adjust the PLL trough SCCB interface as usual). Remove the plastic lens and see near the CMOS.
Regards


body: I also bought one of these to use with an esp32, not realizing that there was an on-board oscillator and no system clock pin. I just left the pin on the esp that's supposed to connect to XCLK hanging, and set the frequency to 12000000 in my code. It seems to work alright!


message:
Why my light meter's values are blank on Arduino Serial Monitor?

I tried to represent the values of TSL 2591 Adafruit light sensor on my Arduino Serial Monitor, but for some reason, I could not do that. The Arduino Serial Monitor just enters some blank values and scrolls down.
Here is the code:

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

    uint16_t x = tsl.getLuminosity(TSL2591_VISIBLE);
    y = float(tsl.getLuminosity(TSL2591_VISIBLE));
    z = (y, DEC);
    Serial.write((byte)z);

`x`, `y`, and `z` are floats initially.

body:
Use Serial.println(x); to print a number as text. Function write() sends the raw byte and Serial Monitor shows the character with that ASCII code, which is not valid or a not visible control character.

----------

For the `z = (y, DEC);` from Wikipedia:

> In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).

so `z` is always 10 (value of constant DEC), which is ASCII code for the new line character


message:
How to write a script if water sensor comes into contact with water for more than 2 mins and LED lights up

I am a newbie to arduino and programming. I would like to come out with a code for water sensor to detect the presence of water for more than 2mins before lighting up the LED lightbulb. Currently using Arduino, Grove baseshield with grove water sensor http://wiki.seeedstudio.com/Grove-Water_Sensor/.

I have the simple base code but not sure how do i go about adding in the function to detect water for a longer period of time before the light lights up:

    #define watersensor 8               //Grove water sensor to Arduino Digital Pin 8
    #define led 4                      //Grove LED to Digital Pin 4

    int isWater;
    bool wasWater = false;
    //bool isWater, wasWater = false;    // true => currently we are not seeing water
    uint32_t waterstart_ms = 0;        // time first saw water

    void setup() {
      pinMode(watersensor, INPUT);
      pinMode(led, OUTPUT);
    }

    void loop()
    {
       // Is there water?
     isWater = digitalRead(watersensor);     // read sensor
     Serial.println(isWater);

       if( isWater ){
          if( wasWater ) {
          waterstart_ms = millis();  // First water: note the time
          }
            if( millis() - waterstart_ms >= 1*5*1000 ){// Water continues for 5s (trial first); time to light LED?
                digitalWrite(led, HIGH);
            }//end if
                wasWater = true;
       } // end first if
       else {
          wasWater = false; // No water; LED off
          digitalWrite(led, LOW);
       }
    }

body:
Should the LED be latched (stay on forever, once it's on), or go out if the sensor later detects no water? I'll assume the latter. Here's an (untested) state machine that should give you a good start. It keeps track of whether water was already seen, when it started, and whether it is seen now. There is some redundant switching of the LED; removing that (if desired) "is left as an exercise for the reader".

    #define watersensor 8               //Grove water sensor to Arduino Digital Pin 8
    #define led 4                      //Grove LED to Digital Pin 4

    #define TWOMIN (2*60*1000L)

    bool isWater, wasWater = false;    // true => currently/were seeing water
    uint32_t WaterStart_ms = 0;        // time first saw water

    void setup() {
      pinMode(watersensor, INPUT_PULLUP);  // pullup for testing w/a button
      pinMode(led, OUTPUT);
    }

    void loop()
    {
      // Is there water?
      isWater = !digitalRead(watersensor);     // read sensor

      if ( isWater ) {
        if ( !wasWater ){
          // First water: note the time
          WaterStart_ms = millis();
          wasWater = true;
        }
        else {
          // Water continues; time to light LED?
          if ( (millis() - WaterStart_ms) >= TWOMIN )
            digitalWrite(led, HIGH);
        }
      }
      else {
        // No water; LED off
        wasWater = false;
        digitalWrite(led, LOW);
      }
      delay(300);
    }

Update:

Added `wasWater = true;` at line 27. The `delay(300)` at line 40 isn't necessary. Ran correctly when I tested it with a button (also negative logic) for the sensor.

> the light lights up randomly.

See if your sensor gives solid responses (try printing its output in loop() ). If it dithers around transitions, you may need to wait for some number of readings in a row that are opposite to the previous sensor state before you accept its new state as real.


message:
How to use a precompiled library in a project with Arduino-IDE

I'm discovering the Arduino development and after quite some googling, I can't find an answer to the following question.

I'd like to distribute some code as mylib.h + precompiled mylib.o (this will be code ported from sources which I can't divulgate).
How is it possible to build a sketch using this precompiled mylib.o in the Arduino-IDE environment?
Do I simply have to put this mylib.o in a specific path and include the mylib.h in the sketch? If yes, which path? If no, what specific configuration steps do I have to follow?

Thanks in advance.

body:
See https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification

>library.properties file format
>[...]
> precompiled - (available from Arduino IDE 1.8.6/arduino-builder 1.4.0) (optional) set to true to allow the use of .a (archive) and .so (shared object) files. The .a/.so file must be located at src/{build.mcu} where {build.mcu} is the architecture name of the target the file was compiled for. Ex: cortex-m3 for the Arduino DUE. The static library should be linked as an ldflag.

So with the correct metadata and file layout the precompiled objects should be available.
You'll need to set the *architectures* property to indicate you're using esp8266 as your tag suggests.

More info on the library manager here https://github.com/arduino/Arduino/wiki/Library-Manager-FAQ including how to add to the public library list.


message:
How can I tell the resistance of an internal pull-up resistor?

I have a SparkFun ESP8266 Thing Dev board, to which I want to perform a `digitalRead()` on one of the GPIO ports. I'm using `D15`, and I'm configuring it for input like this

    pinMode(15, INPUT_PULLUP);

It does seem to work as intended, and I am able to pull it down by connecting it to ground via a 4.7kΩ resistor.

But how do I know what the actual "correct" resistor would be? I can't find any specs for the internal pullup resistor online. On a related note, I first tried using `D0`, but it didn't seem to have an internal pullup resistor, since even using `INPUT_PULLUP` didn't turn it on.

Perhaps there are specs online and I'm just not able to find them, but is there any other way (measuring?) to find out which pins will work with `INPUT_PULLUP` and if so, what their internal resistance is?

body: io 0 and io 15 are with io 2 boot configuration pins of the esp8266. esp8266 dev boards have external pull-up on io 0 and io 2 and pull-down on io 15.


body:
"The value of internal (built-in) pull-up resistor is between 30Kohm and 100Kohm."

Source: https://bbs.espressif.com/viewtopic.php?t=1079#p4097


message:
Combining two code of two sensor in one program

I'm using two sensors, which is Galvanic Skin Response sensor and Heartrate sensor. The problem is that when I combined both of the codes, the only output that is showing up is from Heartrate only which is at A0. If I run them separately both codes works perfectly fine. My background in coding is basic and both codes came from the internet.

These are the codes:

        #define BLYNK_PRINT Serial
        #include <ESP8266_Lib.h>
        #include <BlynkSimpleShieldEsp8266.h>
        #include <SoftwareSerial.h>
        SoftwareSerial EspSerial(2, 3); // RX, TX

        #define samp_siz 4
        #define rise_threshold 4

        // Your ESP8266 baud rate:
        #define ESP8266_BAUD 9600

        char auth[] = "ba4e5bd1bd9549669a02ac378db9faf6";
        char ssid[] = "vivo";
        char pass[] = "takoyaki";

        /*char auth[] = "b3f01a592b78471f9f720b09d2ff8047";
        char ssid[] = "vivo";
        char pass[] = "takoyaki";
        */
        ESP8266 wifi(&EspSerial);

        BLYNK_CONNECTED()
        {
          Blynk.syncAll();
        }

        BlynkTimer timer;

        // Pulse Monitor Test Script

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

          // Set ESP8266 baud rate
          EspSerial.begin(ESP8266_BAUD);
          delay(10);

          Blynk.begin(auth, wifi, ssid, pass);

          pinMode(A0, INPUT);
          pinMode(A1, INPUT);

          //timer.setInterval(1000L, myTimerEvent);     //send the arduino's                         uptime
          timer.setInterval(350L, sensor);            //send gsr data every         0.35s
        }

        /*void myTimerEvent()
        {
          // You can send any value at any time.
          // Please don't send more that 10 values per second.
          Blynk.virtualWrite(V4, millis() / 1000);
        }
        */
        void sensor(){

          const int GSR=A1;
          int inputvalue=0;
          int gsr_average=0;
          long total=0;
          for(int j=0;j<10;j++)                       //Average the 10                 measurements to remove the glitch
              {
              inputvalue=analogRead(GSR);
              total += inputvalue;
              delay(5);
              }
           gsr_average = total/10;
           Serial.println(gsr_average);
           Blynk.virtualWrite(V6, gsr_average);
        }

        void heartrate ()
        {
            int sensorPin =A0;
            float reads[samp_siz], sum;
            long int now, ptr;
            float last, reader, start;
            float first, second, third, before, print_value;
            bool rising;
            int rise_count;
            int heartrate;
            int n;
            long int last_beat;

            for (int i = 0; i < samp_siz; i++)
              reads[i] = 0;
            sum = 0;
            ptr = 0;

            while(1)
            {
              // calculate an average of the sensor
              // during a 20 ms period (this will eliminate
              // the 50 Hz noise caused by electric light
              n = 0;
              start = millis();
              reader = 0.;
              do
                      {
                reader += analogRead (sensorPin);
                n++;
                now = millis();
              }
              while (now < start + 20);
              reader /= n;  // we got an average

              // Add the newest measurement to an array
              // and subtract the oldest measurement from the array
              // to maintain a sum of last measurements
              sum -= reads[ptr];
              sum += reader;
              reads[ptr] = reader;
              last = sum / samp_siz;
              // now last holds the average of the values in the array

              // check for a rising curve (= a heart beat)
              if (last > before)
              {
                rise_count++;
                if (!rising && rise_count > rise_threshold)
                {
                  // Ok, we have detected a rising curve, which implies a         heartbeat.
                  // Record the time since last beat, keep track of the two previous
          // times (first, second, third) to get a weighed average.
          // The rising flag prevents us from detecting the same rise more than once.
                  rising = true;
                  first = millis() - last_beat;
                  last_beat = millis();

                  // Calculate the weighed average of heartbeat rate
                  // according to the three last beats
                  print_value = 60000. / (0.4 * first + 0.3 * second + 0.3 *         third);

                  heartrate = print_value;

                  //Serial.print(print_value);
                  Serial.print(heartrate);
                  Serial.print('\n');
                  Blynk.virtualWrite(V7, heartrate);

                  third = second;
                  second = first;

                }
              }
              else
              {
                // Ok, the curve is falling
                rising = false;
                rise_count = 0;
              }
              before = last;

              ptr++;
              ptr %= samp_siz;

            }
        }

        void loop()
        {
          Blynk.run();
          //timer.run();
          sensor();
          heartrate();
        }

body:
I have not tested the following code, so it will be up to you to do this and handle small errors. This is more about the coarse way to change the program. And you will have to understand, what the code really does, to be able to change it the way you need it.

First you will have to make some of the variables in the `heartrate()` function to global variables (by writing them near the top of the sketch outside of any function), so that they keep their values between the different executions of the function. I also changed some variable types, which match the type of the assigned values.

    float reads[samp_siz], sum;
    unsigned long now, start, ptr;
    float last, before, reader;
    unsigned long first, second, third;
    bool rising;
    int rise_count;
    float print_value, heartrate;
    unsigned long last_beat;

The sensor pin should be `#define`d at the top of the program (by convention). Then you should put this code:

    for (int i = 0; i < samp_siz; i++)
        reads[i] = 0;
    sum = 0;
    ptr = 0;

into the `setup()` function.

Now we can look at the `while(1)` loop. On Arduino a value of `0` is treated as the boolean `false` and every other value as `true`. So this is the same as writing `while(true)`. The `while()` structure loops as long, as the expression inside the brackets evaluates to `true`. Since this is always the case here, it will loop forever. At this point you can just erase this line (and the corresponding closing bracket `}`).

After these changes the function will only take 1 reading (averaged over 20ms), then check, if a heartbeat was detected, and finally exiting to the `loop()` function. Since not every reading is a heartbeat, you will get more output from the `sensor()` function (which outputs on every execution) than from the `heartbeat()` function. And now, due to your functions being non-blocking, you will get very fast output. You might want to slow that down, by using a `delay()` or (better) the `millis()` function (like in the `BlinkWithoutDelay` example of the Arduino IDE).

Note, that this code exhibits some bad coding styles. You can get much of good code on the web, but also much of bad code. I see wrong types for variables, the usage of totally unnecessary variables and usage of the `millis()` function, which doesn't handle the rollover. This doesn't mean, that the code does not work. But you can get weird and difficult to debug errors through them.


message:
programming relays wit millis code

Trainset info,

    Turnout 1 = relay 1 - makes turnout track go left
              = relay 2 - makes turnout track go right
    Turnout 2 = relay 3 - makes turnout track go left
              = relay 4 - makes turnout track go right
     Signal 1 = relay 5 - makes signal go green - train 1 starts driving
              = relay 6 - makes signal go red - train 1 stops for signal
     Signal 2 = relay 7 - makes signal go green - train 2 starts driving
              = relay 8 - makes signal go red - train 2 stops for signal

I have a arduino - uno and a 8 relay board.
I want to run a program (loop) for 1/2 hour / 1800 seconds.
Switching time should be 2 seconds (relay ON)

Can somebody help me with a millis code please.

Loop times should be:

    relay 1 = (2),1250,(2),546 - total 1800 seconds
    relay 2 = 620,(2),630,(2),546 - total 1800 seconds
    relay 3 = 10,(2)1260,(2),526 - total 1800 seconds
    relay 4 = 630,(2),640,(2),512 - total time 1800 seconds
    relay 5 = 20,(2),1270,(2),505 - total time 1800 seconds
    relay 6 = 600,(2),750,(2),446 - total time 1800 seconds
    relay 7 = 640,(2),640,(2),516 - total time 1800 seconds
    relay 8 = 1240,(2),450,(2),106 - total time 1800 seconds

Regards, Martinus van Walsum
xxxxxxxx@xxxxxxxx.com

body:
This is functional. I would do more by making a function to be called with the time and state information. It would reduce the number of if statements. But this is simple to understand. I started with Blink without delay.

I did two relays. For the others, copy and paste, then change the relay numbers and times.

    /*
      Blink without Delay
      http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
    */

    const int On =  1;
    const int Off =  0;

    // constants won't change. Used here to set a pin number:
    const int ledPin =  LED_BUILTIN;// the number of the LED pin
    const int relay1 =  5;
    const int relay2 =  6;

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

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

    int    secondCount = 0;

    // constants won't change:
    const long interval = 1000;           // interval at which to blink (milliseconds)

    #define onTime  2           //relay on time

    #define relay1_on1 0
    #define relay1_on2 (relay1_on1+onTime+1250)

    #define relay2_on1 62
    #define relay2_on2 (relay2_on1+onTime+630)

    void setup() {
      // set the digital pin as output:
      digitalWrite(relay1, Off);
      digitalWrite(relay2, Off);
      pinMode(ledPin, OUTPUT);
      pinMode(relay1, OUTPUT);
      pinMode(relay2, OUTPUT);
    }

    void loop() {
      // here is where you'd put code that needs to be running all the time.

      // check to see if it's time to blink the LED; that is, if the difference
      // between the current time and last time you blinked the LED is bigger than
      // the interval at which you want to blink the LED.
      unsigned long currentMillis = millis();

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

        //------------------------------
        // Relay 1
        if (secondCount == relay1_on1) {
          digitalWrite(relay1, On);
        }
        if (secondCount == (relay1_on1 + 2)) {
          digitalWrite(relay1, Off);
        }

        if (secondCount == relay1_on2) {
          digitalWrite(relay1, On);
        }
        if (secondCount == (relay1_on2 + 2)) {
          digitalWrite(relay1, Off);
        }

        //------------------------------
        // Relay 2
        if (secondCount == relay2_on1) {
          digitalWrite(relay2, On);
        }
        if (secondCount == (relay2_on1 + 2)) {
          digitalWrite(relay2, Off);
        }

        if (secondCount == relay2_on2) {
          digitalWrite(relay2, On);
        }
        if (secondCount == (relay2_on2 + 2)) {
          digitalWrite(relay2, Off);
        }

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

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

        secondCount++;
        if (secondCount == 180) {
          secondCount = 0;
        }
      }

    }


message:
Arduino losing connection to Serial port after running function

For some reason when I loop my code through a separate function the serial port hangs up. The serial connection appears fine when I call cases within the loop but not when I call outside.

I tried to figure out where the problem is and for some reason using the `Serial.print(ComControlValue);` and the output is

> -1

But the error still persists.

Previous it was this before I changed the baudrate

> -b⸮⸮⸮⸮ Waiting for Command

It's not printing out the -1 I'm using as the main case. Could this be the problem?

    #include <Wire.h>
    /* RPi Army variables */
    int RPi[3] = {3,6,9};                                        // SDA/SCL code names for the different Raspberry pi's

    /* Define parameters for computer control */
    int ComControlValue = -1;

    void setup() {
      Serial.begin(115200);                                     // Establish Serial connection to computer
      Wire.begin();                                             // join i2c bus as master
    }

    void loop() {
     switch(ComControlValue){
      /* -1 : nothing happened yet */
      case -1:
         Serial.println("Waiting for Command");
         while (Serial.available()==0){}
         ComControlValue=Serial.parseInt();                             // Pull value from serial port
         break;

      case 111:
         Serial.println("Eat more Toast");
         ComControlValue = -1;
         break;

      case 210:
         Sendsignals(RPi[0],333);
         Sendsignals(RPi[1],333);
         Sendsignals(RPi[2],333);
         ComControlValue= -1;
         Serial.print(ComControlValue);
         break;
      }
    }

    void Sendsignals(int Rpi, int code){
       char str[4];
       sprintf(str, "=\n", code);
       Wire.beginTransmission(Rpi);                                 // transmit to device of choice
       Wire.write(str);                                             // sends 16 bytes
       Wire.endTransmission();                                      // stop transmitting
    }

body: Your str variable in function Sendsignals is short. sprintf writes 5 bytes to it, 3 digits, the \n and terminating zero. The terminating zero is written outside of the allocated array and causes the crash.


message:
How to combine time into a variable

I have an Arduino Uno project which is recording student attendance using fingerprint sensor. So when sensor found a match, the serial monitor will be printing out Student ID and current time like this:

        DateTime now;
        void setup()
          {
              ...
          }

        void loop()
          {
              .....
              //found a match
              Serial.print("Found ID #");
              Serial.println(finger.fingerID);
              Serial.print("Time->");
              Serial.print(now.hour(), DEC);
              Serial.print(':');
              Serial.print(now.minute(), DEC);
              Serial.print(':');
              Serial.print(now.second(), DEC);
          }

Sample result will be:

    Found ID#1
    Time-> 18:11:54

I would like to store the time into a variable and print it out instead of printing hour, minute, and second separately. How can I do that???

I have tried to do like this as below but I'm getting an error, I would like to store it as a string. How can I do that?

    string time = now.hour() + ':' + now.minute() + ':' + now.second();

body:
You want to use `snprintf` for this:

    char timeString[9];

    snprintf(timeString, 9, "d:d:d", now.hour(), now.minute(), now.second());
    Serial.println(timeString);

By using a format string like this you are taking into account time portions < 10 (like 7 minutes and 23 seconds past 3 am, which would otherwise be 3:7:23) by padding the time with leading zeroes where needed.


message:
Can the function be written without ";" in the end?

I have seen the following code on the Internet:

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(8,9);
    void setup()
    {
      mySerial.begin(9600);
      Serial.begin(9600);
      delay(100);
    }
    void loop()
    {
      if (Serial.available()>0)
      mySerial.write(Serial.read());
      if (mySerial.available()>0)
      Serial.write(mySerial.read());
    }

The command works perfectly fine. How was it possible in the code to write the command without ";" at the end of the line?

The link to the code is: [enter link description here][1]

  [1]: https://roboindia.com/tutorials/send_receive_data_hc10_bluetooth

body:
Do you refer to this block?

    if (Serial.available()>0)   <- here
    mySerial.write(Serial.read());
    if (mySerial.available()>0) <- here
    Serial.write(mySerial.read());

If so, there *is* a `;` at the end of each command. The commands are just split onto two lines each.  It could be written like this:

    if (Serial.available()>0) mySerial.write(Serial.read());
    if (mySerial.available()>0) Serial.write(mySerial.read());

The second and fourth lines are the body of the `if`.  Better indenting with the original arrangement would be:

    if (Serial.available()>0)
        mySerial.write(Serial.read());
    if (mySerial.available()>0)
        Serial.write(mySerial.read());

Or even better, include the brackets around the body:

    if (Serial.available()>0) {
        mySerial.write(Serial.read());
    }
    if (mySerial.available()>0) {
        Serial.write(mySerial.read());
    }


message:
MKR1000 and DS18B20 temperature sensor

I am new to Arduino and electronics in general and I can't get my MKR1000 to read correct data from a DS18B20 temperature sensor.

Here is the [tutorial](https://create.arduino.cc/projecthub/TheGadgetBoy/ds18b20-digital-temperature-sensor-and-arduino-9cc806) I followed.

**The issue is**: I always get the same readings from the sensor: `-127.00`.

I should mention I have tried 2 different sensors and get the same readings.

From the sensor, GND goes directly to GND on the board, and I have the 4.7kΩ resistor in between the data and power wires.

According to the sensor manufacturer, output leads: Yellow (VCC), Red (DATA), Black (GND).

Data line is connected to the pin `~2` on the MKR1000.

    /********************************************************************/
    // First we include the libraries
    #include <OneWire.h>
    #include <DallasTemperature.h>
    /********************************************************************/
    // Data wire is plugged into pin 2 on the Arduino
    #define ONE_WIRE_BUS 2
    /********************************************************************/
    // Setup a oneWire instance to communicate with any OneWire devices
    // (not just Maxim/Dallas temperature ICs)
    OneWire oneWire(ONE_WIRE_BUS);
    /********************************************************************/
    // Pass our oneWire reference to Dallas Temperature.
    DallasTemperature sensors(&oneWire);
    /********************************************************************/
    void setup(void)
    {
     // start serial port
     Serial.begin(9600);
     Serial.println("Dallas Temperature IC Control Library Demo");
     // Start up the library
     sensors.begin();
    }
    void loop(void)
    {
     // call sensors.requestTemperatures() to issue a global temperature
     // request to all devices on the bus
    /********************************************************************/
     Serial.print(" Requesting temperatures...");
     sensors.requestTemperatures(); // Send the command to get temperature readings
     Serial.println("DONE");
    /********************************************************************/
     Serial.print("Temperature is: ");
     Serial.print(sensors.getTempCByIndex(0)); // Why "byIndex"?
       // You can have more than one DS18B20 on the same bus.
       // 0 refers to the first IC on the wire
       delay(1000);
    }

Any idea what I am doing wrong?

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

  [1]: https://i.stack.imgur.com/XNiZL.jpg
  [2]: https://i.stack.imgur.com/Q38Xb.jpg
  [3]: https://i.stack.imgur.com/8cOGk.jpg

body: Looks like you have it wired wrong.  A schematic would really help but it looks like you've got 5V going directly into the sensors data line (yellow wire) it's connected on your breadboard to the orange wire +5V.  The power wire of your temperature sensor (red wire) is running through a 4.7K resistor which is not likely what you wanted here either.


message:
Generated frequency is not as expected

This code sets a pin HIGH for 1 microsecond and then LOW for 1 microsecond. The expected frequency should be about 500 kHz. When measuring the output the frequency is about 96.4khz. Why ?

    int del = 1;

    void setup() {
       // put your setup code here, to run once:
    pinMode(3, OUTPUT);
    }

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

    digitalWrite(3, HIGH);
    delayMicroseconds(del);
    digitalWrite(3, LOW);
    delayMicroseconds(del);

    }

body:
`digitalWrite()` takes a few microseconds to execute as well. There is also some overhead around the `delayMicroseconds()` function.

If you need exactly 500 kHz, you would want to consider using a timer.
You can read up on how to set one up in the microcontrollers [datasheet][1].

Unfortunately, I don't have access to an Arduino Leonardo, but here is an example code for the ATmega328P. The register names will be different, but you should be able to adapt the code to fit your Arduino.

    // 500 kHz frequency

    void setup() {
      cli();                 //Disable interrupt during setup
      TCCR2A = 0;
      TCCR2B = 0;

      TCCR2B |= (1 << CS20); //Enable timer without prescaler
      OCR2A = 15;            //Do interrupt TIMER2_COMPA after reaching this counter value
      TIMSK2 |= (1 << 1);    //Enable TIMER2_COMPA interrupt

      DDRD |= (1 << PORTD3); //Set Digital Pin 3 as Output Pin
      sei();                 //Enable interrupts again
    }

    ISR(TIMER2_COMPA_vect) { //If the counter has reached the point where the output needs to be low
      TCNT2 = 0;
      PIND |= (1 << PORTD3); //Toggle Digital Pin 3
    }

    void loop() {
      //your looping code here
    }

Explanation:
`TIMER2` is an 8-bit timer, which means it will always count from 0 to 255, regardless of what the CPU is doing.

Normally, it counts up at the Arduino's clock frequency, like 16 MHz.

When the counter hits 15, a special code is immediately executed, called an "Interrupt Service Routine". In this code, we reset the timer and change the state of your output pin, resulting in a 500 kHz square wave on that pin.

We count to 15 since there are 16 steps in between "0" where the counter begins and 15, where we reset it.

16'000'000 Hz / 1 (no prescaler) / 16 (counter) / 2 = 500 kHz

The divisor of 2 comes from the fact that we need to change the pin state twice for every full square of the output signal.

  [1]: http://ww1.microchip.com/downloads/en/devicedoc/atmel-7766-8-bit-avr-atmega16u4-32u4_datasheet.pdf


body:
delayMicroseconds() has a minimum lower value of 3-4 us per the IDE documentation. It won't do 1.

loop() also adds some delay mechanisms doing it's background stuff.

You will see better results with a while() :

    loop(){
      while (1){
      digitalWrite(3, HIGH);
      delayMicroseconds(del);
      digitalWrite(3, LOW);
      delayMicroseconds(del);
      }
    }

with direct port manipulation in place of the digital writes.

There will also be jitter from the millis() background time keeping, if you want a smoother signal it will be best to turn off interrupts as well.


message:
How do I use a servo in an interrupt?

I am working on a small circuit now where I increment the rotation of a servo motor and at the same time blink a LED.

I have used all methods I know to do it but still it does not work or it blinks and then the servo start working but never both at the same time.
This is what i am basically working with:

      for(position=0;position<=90;position=position+5){
        digitalWrite(led_pin,HIGH);
        delay(200);
        digitalWrite(led_pin,LOW);
        delay(200);
        servoBar.write(position);
        delay(15);
      }

But it blinks once and then it stops and the servo start working right after that.

I know I must not use delays in interrupts. I am using a function that I can but just to show you what I am working with.

body:
The problem is that the delay routine is blocking. It stops operation and blocks other things from happening. Have a look at the Blink without delay example in the example tab. (also linked below)
https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

What you need to do is to not block. Call the time checker often and check if the time you want delayed has run out. The perform the action needed to be done at that time.

This is a more sophisticated way to deal with timed events. Also look at this
**Demonstration code for several things at the same time.**
https://forum.arduino.cc/index.php?topic=223286.0

Have fun learning. :)


body:
A good way to manage timing without delay is to use:

    if(millis()-lastCheck > delayPeriod){
    lastCheck=millis();
    doStuffHereOrChangeServo();
    }

This code is naturally overflow-safe and is actually how delay() works. **The difference is that delay() uses a while() loop that breaks when this condition is met, so it prevents any code after the delay from running UNTIL delay completes. That's why you are getting odd pauses in your code.**

As a side note, it's actually a fun project to build a simple task scheduler that uses a list of function pointers and a variation on this method to do completely generic scheduling. If you want to try that route, you'd keep a struct holding the function pointer and a *signed* integer larger than your maximum intended delay size. Then, every time the scheduler is called, you subtract the difference between millis() and the stored value of millis() from each of those integers in the struct. Once that goes negative or zero, the task can run!


message:
Problem with Arduuino to breadboard Mega8

I am trying to make an arduino using mega8 mcu. After so much struggling with sync/response/signature  problems and reading the previous questions, finally managed to do it (almost). However I still have some weird problems.

I uploaded the arduinoISP sketch to an Uno for programming the chips: AtMega8A-PU and AtMega8L-8PI (I had a couple of L version from years ago).

For bootloader selected the Mega8 from NG board in IDE 1.8.5 then uploaded to Mega8A-PU
for the L version cloned the ng part in boards.txt and reduced the F_CPU to 8MHz, (same bootloader code) and uploaded to 8l

Now, I'm able to upload sketches to both using a usb-serial breakout board/ avrisp mkII.

my first problem is when I disconnect the converter board neither of the MCUs can start unless I pull up or pull down the RxD pin (#2) which i find accidentally. it seems they both stuck in bootloader part. even if i leave the reset pin floating (using internal pullup) and tie the rxd pin they work fine up on applying power (with like an annoying 15~16s delay). the resistor value I tried 1K and 10K but no difference in operation and delay time. it wont start with rxd open. I couldn't find why?

another question is running the code on mega 8L as reliable as on 8A? (need it for lower V)

More clarification: they both run with Xtals and 22pf caps on breadboard. the 8l also works fine with 16MHz Xtal at 5v.

sketch (I know it's not much of help):

    void setup() {
      Serial.begin(19200);
      pinMode(9, OUTPUT);
      pinMode(10, OUTPUT);
      tone(10,3520);
    }

    volatile unsigned int i, var = 1;

    void loop() {
      digitalWrite(9, HIGH);
      for(i = 0; i < 1500; i++)
                     var += ((var * 3) / 2);
                     // do something (if compiler not wipe it for optimizing :D )
      digitalWrite(9, LOW);
      Serial.println(millis());
    }

sample of 8A and (similarly) uno output:

    7 11 15 19 23 27 31 35 39 44 48 52 56 60 64 68 72 76 80 84 89 93 97 101 106 110

8L output @ 3.3v @8MHz:

    16 24 32 40 51 59 67 75 86 94 102 110

tone() output is the same for all

Appreciate your help

body:
I found here: https://www.arduino.cc/en/Hacking/Bootloader?from=Tutorial.Bootloader

that NG / mega8 bootloader doesn't enable the rx pin internal pullup nor it gets out of the bootloader even if receiving junk data on rx  (which was my case due to leaving it open thus floating). It also has a delay of 6 to 8 seconds intentionally.

Probably I'll use another bootloader since the link to source code on the page was broken or just program the L version without any bootloader and better fuse options.


message:
GPRS Based OTA to the NODEMCU

I need the OTA firmware update. I have the only option in my hand GSM(GPRS SIM800), with the help of this is it possible OTA, plz help me for this how I Do OTA via GPRS, FYI, I completed OTA Via WIFI.

body:
Download the bin file over GPRS and then use the Update singleton object. It is declared in [Update.h][1]. Example is ArduinoOTAClass::_runUpdate() in [ArduinoOTA.cpp][2] or ESP8266HTTPUpdate::runUpdate() in [ESP8266httpUpdate.cpp][3]

  [1]: https://github.com/esp8266/Arduino/blob/master/cores/esp8266/Updater.h
  [2]: https://github.com/esp8266/Arduino/blob/master/libraries/ArduinoOTA/ArduinoOTA.cpp
  [3]: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266httpUpdate/src/ESP8266httpUpdate.cpp


message:
What do the charactors " '/2' " mean in the variable declaration?

I'm working on an RS485 project, In the CPP file there are `const` variables declared in the following manner:

    #include <RS485_protocol.h>
    const byte STX = '\2';
    const byte ETX = '\3';

What does the '\2' and '\3' mean?

body:
The '\2' and '\3' are characters with octal code 2 and 3. Which is nothing more then 2 and 3 in octal and in decimal. The author could simply write `const byte STX = 2; const byte ETX = 3;`.

Characters with ASCII code 2 and 3 are control characters STX (start of text) and ETX (end of text). Control characters are invisible characters used to control the terminal or as mark characters in communication.


message:
Arduino pin 13 as PWM output, not possible?

I have noted on more than one occasion the comments in sketches "reserving pin 13 for future PWM backlight dimming of the LCD" while using Uno and Nano boards.
Am I missing something ?  I always considered it NOT possible as PWM output is only available on pins 3,5,6,9,10 and 11 on most boards.

body: Arduino pin 13 is SCK/BP5 on the ATmega8 MPU, there's no hardware PWM capability on that pin, so any PWM would be software driven.


message:
Measure movement distance - not sure what sensor?

I want to measure the length of a step / stride -not sure what sensor to use.

I am trying to get several people to march a pattern for a band.  I am thinking a Arduino to beep when step is too short or too small.  Thinking the Arduino will be tied to their shoe laces.  IR or Ultrasonic do not seem to be the correct sensor to use.

Ideas?

body:
The sensor to use is an accelerometer. The principle is easy: measure the acceleration, perform a double integration and you have the distance (after the first integration you have the velocity).

The problem is that, because of the double integration, small errors in the acceleration signal lead to big errors in the calculated distance. For example: an error e in the acceleration leads to an error e.t2 in the distance (where t stands for time). For this reason al sorts of filters are used often in combination with gyroscopes and/or gravity sensors. The signals from the gyroscopes and/or gravity sensors are used for the low frequency signals (long term) and te signals from the accelerometer(s) for the high frequency signals (short variations). That's why you find these sensors often combined in one package (for example the BNO055 form Robot Electronics https://robot-electronics.co.uk/bno055.html).

It is a complicated and highly mathematical area of science. In fact you want to do the same thing as fitness trackers do (and I think you are striving to a higher accuracy than they) - and there are not many that do really well.

P.S. Robot Electronics also sell a tilt compensated compass board with this BNO055 chip: the CMPS12 (https://robot-electronics.co.uk/cmps12-tilt-compensated-magnetic-compass.html). With this board you can read out absolute and relative positions straight away without any calculations.


message:
Ultrasonic sensor and ledstrip color problem

So I've made a parking sensor with the Ultrasonic sensor and a ledstrip. But the ledstrip doesn't turn yellow or green. I think it has to do with the Thresholds. Can anyone help me to set this up? I also want a longer distance greater than 1 meter. This is my code:

    #include "FastLED.h"
     #include <math.h>

        #define NUM_LEDS 32
        #define BRIGHTNESS 10
        #define DATA_PIN 4

        // Define the array of leds
        CRGB leds[NUM_LEDS];

        // Module Pins
        #define trigPin 11
        #define echoPin 12

        // Thresholds (in CM)
        long SECTION_SIZE = 80;
        long STOP_DISTANCE = 60;
        long WARNING_THRESHOLD = 50;
        long MAX_THRESHOLD = 375;

        long RED_THRESHOLD = STOP_DISTANCE;
        long YELLOW_THRESHOLD = RED_THRESHOLD + SECTION_SIZE;
        long GREEN_THRESHOLD = YELLOW_THRESHOLD + SECTION_SIZE;

        const int numReadings = 5;

        int readings[numReadings];      // the readings from the analog input
        int readIndex = 0;              // the index of the current reading
        int total = 0;                  // the running total
        int average = 0;                // the average

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

          FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
          FastLED.setBrightness(10);

          // HC-SR04 Setup
          pinMode(trigPin, OUTPUT);
          pinMode(echoPin, INPUT);

          // initialize all the readings to 0:
          for (int thisReading = 0; thisReading < numReadings; thisReading++) {
            readings[thisReading] = 0;
          }
        }

        void loop() {
          long distance, lastRun;
          bool red, yellow, green;
          total = total - readings[readIndex];
          readings[readIndex] = calculateDistance();
          total = total + readings[readIndex];

          readIndex++;
          if (readIndex >= numReadings) readIndex = 0;

          distance = abs(total / numReadings);

          yellow = distance <= YELLOW_THRESHOLD && distance > RED_THRESHOLD;
          red = distance <= RED_THRESHOLD;
          green = distance > YELLOW_THRESHOLD && distance <= GREEN_THRESHOLD;

          if (red) {
            setRed();
          } else if (yellow) {
            setYellow(distance);
          } else if (green) {
            setGreen(distance);
          } else {
            setGreenStandby();
          }

          Serial.print(distance);
          Serial.println(" cm");
          FastLED.show();
          delay(1);
        }

        void lightItUp(const CRGB& pColor, const CRGB& sColor, uint16_t travel) {
          uint16_t travelFix = travel * (NUM_LEDS/SECTION_SIZE);
          uint16_t leftStop = travelFix/2;
          uint16_t rightStop = NUM_LEDS - leftStop;
          for (int i = 0; i < NUM_LEDS; i++) {
            if (i < leftStop || i > rightStop) {
              leds[i] = pColor;
            } else {
              leds[i] = sColor;
            }
          }

          FastLED.show();
        }

        long calculateDistance() {
          long duration;
          digitalWrite(trigPin, LOW);
          delayMicroseconds(2);
          digitalWrite(trigPin, HIGH);
          delayMicroseconds(10);
          digitalWrite(trigPin, LOW);

          duration = pulseIn(echoPin, HIGH);
          return (duration/2) / 29.1;
        }

        void setGreenStandby() {
          return fill_solid(leds, NUM_LEDS, CRGB::Black);
        }

        void setRed() {
          return fill_solid(leds, NUM_LEDS, CRGB::Red);
        }

        void setGreen(long distance) {
          long travel = GREEN_THRESHOLD - distance;
          return lightItUp(CRGB::Yellow, CRGB::Green, travel);
        }

        void setYellow(long distance) {
          long travel = YELLOW_THRESHOLD - distance;
          return lightItUp(CRGB::Red, CRGB::Yellow, travel);
        }

body:
I believe your mistake is in this part of your code:

      yellow = distance <= YELLOW_THRESHOLD && distance > RED_THRESHOLD;
      red = distance <= RED_THRESHOLD;
      green = distance > YELLOW_THRESHOLD && distance <= GREEN_THRESHOLD;

      if (red) {
        setRed();
      } else if (yellow) {
        setYellow(distance);
      } else if (green) {
        setGreen(distance);
      } else {
        setGreenStandby();
      }

In particular, you are defining three boolean variables independently and then switching based on their values.

Assuming you are seeing the right values output on serial monitor (like `90 cm`, `60 cm`, etc...), which is something I'm unsure of as I'm not getting how you are determining the distance, then the following should be easier to follow/understand:

    if (distance > GREEN_THRESHOLD) {
      setGreenStandby();
    } else if (distance > YELLOW_THRESHOLD) {
      setGreen(distance);
    } else if (distance > RED_THRESHOLD) {
      setYellow(distance);
    } else {
      setRed();
    }

You have only one variable determining the led strip configuration, no need to go to 3 and then try to reduce again ;-)

Please note that your `YELLOW_THRESHOLD` is defined as `140`, if you don't ever see a message in the serial monitor greater than that value you don't have a chance of seeing any colour other than red.... I'm asking because you mentioned _I also want a longer distance greater than 1 meter_ that might imply your sensor is unable to go farther than 1 meter...

With the code above I'm checking the distance in a _greater to smaller_ order: the first matching is the only one activated and it's impossible for the `distance` variable to match more than one condition. Generally speaking, simpler is better.


message:
How do I make a toggleable Infrared motion detection module

I just got an Arduino and an Infrared motion detection module. What I tried making is, that if the module detected movement, a led would turn on, and if it detected movement again, it would turn off. So I wrote this code and tried looking online for solutions, but couldn't find it. I really don't know what to change about my code to make it work. Does anyone have solutions for this?

(Sensor value can be 0 or 1, 0 means nothing detected, 1 means something detected. After detection the value automatically goes back to 0 in a few seconds)

    int Sensor = 4;
    int led = 13;
    bool bool1 = false;

    void setup() {
    pinMode(Sensor, INPUT);
    pinMode(led, OUTPUT);
    Serial.begin(9600);
    }

    void loop() {
    int SensorValue = digitalRead(Sensor);

    if(SensorValue == 1){
      bool1 = !bool1;
      }

    if(bool1 == true){
      digitalWrite(led, HIGH);
      }
    if(bool1 == false){
      digitalWrite(led, LOW);
      }
    }

body:
Consider using a [state machine][1] with 4 states.  Currently you only have 2 states.  One where "bool1" is TRUE and another when "bool1" is FALSE.  The 4 states needed are:

 1. When the LED is OFF & the [PIR][2] is NOT-ACTIVE.
 2. When the LED is OFF & the PIR is ACTIVE.
 3. When the LED is ON and the PIR is ACTIVE.
 4. When the LED is ON and the PIR is NOT-ACTIVE.

As you travel between these 4 states, you will find you only want to turn the LED ON when traveling between states 2 & 3.  And you will only want to turn the LED OFF when traveling between states 4 & 1.

  [1]: https://en.wikipedia.org/wiki/Finite-state_machine
  [2]: https://en.wikipedia.org/wiki/Passive_infrared_sensor


message:
Porting the FastNoise c++ library to Due

I'm trying to use the FastNoise library with a Due, however, I get something like the following errors, when I try to complie.

error: 'abs' was not declared in this scope

error: 'mt19937' is not a member of 'std'

error: 'uniform_int_distribution' is not a member of 'std'

so I added the following:

    #include <cstdlib>
    #include <cmath>
    #include <random>

which solved most of the problems, however it still says printf hasn't been declared. So I tried to edit cstdio to comment out the #undef printf, but it just brought back the full list of error messages, so that's not the solution. I googled some solutions but none of these seem to work. Do you have any suggestions I should try?

I'm not trying to use printf, just want to use the library.

Thanks for any help.

body:
The [FastNoise library][1] compiles as it is for the Arduino MKR and Arduino Zero, but there is a "not cool" issue for the Due: https://github.com/arduino/ArduinoCore-samd/issues/308

A issue with `assert` can easily be solved, but the `#include <algorithm>` and `#include <random>` are somehow linked to a `printf` function.
I thought it was very hard, but then @Juraj wrote in his answer about the simple solution to comment out the `#undef printf` line.

In the file cstdio is a list of about fourty `#undef` lines. Only the `printf` requires to be commented out.

    // #undef printf

The file is located in the hidden "Arduino15" folder in the build environment for the Due: Arduino15\packages\arduino\tools\arm-none-eabi-gcc\4.8.3-2014q1\arm-none-eabi\include\c++\4.8.3\cstdio

Then it will also compile for the Arduino Due (even without removing the assert). There are many warnings.

I was able to run it on a SAMD21 processor and it produces random numbers. However, I am not sure that those numbers are correct. I don't know if the many compiler warnings can be ignored.

    #include <FastNoise.h>

    FastNoise myNoise; // Create a FastNoise object

    float heightMap[32][32]; // 2D heightmap to create terrain

    void setup() {
      SerialUSB.begin(9600);
      SerialUSB.println("FastNoise");
      delay(1000);

      myNoise.SetNoiseType(FastNoise::SimplexFractal); // Set the desired noise type

      for(int x=0; x<32; x++) {
        for(int y=0; y<32; y++) {
          heightMap[x][y] = myNoise.GetNoise(x,y);
          SerialUSB.println(heightMap[x][y]);
        }
      }
    }

    void loop() {
    }

Do you know the [XY Problem][2]? You did not explain the reason for trying to make that library run on a Arduino Due. Perhaps there is an other way for what you want to achieve.

The Arduino Due was a major update for the Arduino boards, but nowadays some say to avoid the Arduino Due because it has issues (hardware and software).

  [1]: https://github.com/Auburns/FastNoise
  [2]: http://xyproblem.info/

----------
I have updated my answer with help of the answer from @Juray.


body:
The workaround is in the [issue][1] found by Jot.
In file

`C:\Users\aaaaaa\AppData\Local\Arduino15\packages\arduino\tools\arm-none-eabi-gcc\4.8.3-2014q1\arm-none-eabi\include\c++\4.8.3\cstdio`

comment the line

`#undef printf`

and it will compile

  [1]: https://github.com/arduino/ArduinoCore-samd/issues/308


message:
Are hardware interrupts used while controlling an LCD screen using the LiquidCrystal library?

I'm working on a tone generator project that uses [Mozzi][1] to make sound (sine waves mainly). As I understand, Mozzi can glitch if used along with hardware interrupts.

The plan is to use the classic 2x16 LCD screen, but I don't know the guts of the library or interface. Are hardware interrupts used while interfacing with an LCD screen, or by the LiquidCrystal library?

  [1]: https://sensorium.github.io/Mozzi

body:
The [LiquidCrystal code][1] shows that delays are used. That can cause audio glitches in the sound.
The LiquidCrystal library does not use interrupts.

You could try to change the LiquidCrystal code according to the instruction on the Mozzi page.

  [1]: https://github.com/arduino-libraries/LiquidCrystal/blob/master/src/LiquidCrystal.cpp


message:
Maximum signal frequency obtained at the gpios of arduino mega 2560

Is it possible to obtain the rectangular pulse signals of freuency 10 MHz simultaneously at the GPIOs of arduino mega 2560?

body:
The maximum fundamental frequency you can generate is *fcpu/2* - or 8MHz with the default 16MHz resonator / crystal.

What shape the actual signal is, though, is very much dependant on the load on the IO pin. The IO pin has a specific *drive strength* which will provide limited current into a load. Any capacitance or inductance within that load causes a change in the *slew rate* (also known as the *rise time* or *fall time*) of the IO pin, which affects the shape of the signal by limiting the highest harmonic frequencies you observe.  At the worst case scenario, you get an almost sine wave (only the fundamental frequency gets through). In general though you get more of a rounded-off square wave:

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

You can improve that slew rate by adding a buffer with a higher drive strength to the output (assuming your buffer has a high enough bandwidth).  However, the IO pin itself will always have a certain amount of curvature to the signal due to its own internal capacitances.

For generating higher frequencies you are better off using a chip that is designed to operate at higher frequencies.

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


message:
Multiple sensors connected to Arduino MEGA 2560 Serial ports

I am using Arduino MEGA 2560 to read values from two sensors. Sensor 1 is providing us two values separated by a comma and a space followed by a newline character. e.g.:

    2.277, 7.942
    2.269, 7.897
    2.263, 8.040

Sensor 2 is providing us a single value followed by a newline character. e.g.

    1.213
    1.333
    1.17

Sensor 1 gives twice as many readings as Sensor 2 in the same amount of time. Sensor 1 is connected via `Serial1` and Sensor 2 is connected to `Serial2` on MEGA board. I am using the following code to read the values:

    void setup() {
      Serial.begin(57600);
      Serial1.begin(9600);
      Serial2.begin(9600);
      while (!Serial)
      {
      }
    }
    void loop() { // run over and over
      if (Serial1.available()) {
        {
          Serial.print(Serial1.readStringUntil('\n'));
          Serial1.flush();
        }
      }

      Serial.print("\t\t\t");
      if (Serial2.available()) {
        while(Serial2.available())
        {
          Serial.write(Serial2.read());
          Serial2.flush();
        }
      }
      Serial.println();
      delay(1000);
    }
I am expecting an output similar to this:

    2.409, 8.150   2.134
    2.490, 7.851   2.133
    2.603, 8.759   2.122
    2.634, 8.305   3.12
    2.727, 8.408   1.32
    3.018, 7.982   2.543
    3.030, 7.982   1.345
    3.020, 8.587   2.435
    2.844, 8.034   2.763
    2.690, 8.690   5.433
    2.721, 8.011   2.348
    2.705, 8.242   7.654
    2.670, 8.713   2.123
    2.756, 8.563   2.098
    2.899, 8.413            2.765
    3.464, 8.196   2.654
    3.705, 8.437   2.343
    3.435, 8.558   1.245
    3.446, 8.592   2.345
    3.421, 8.075   1.234
Instead I am getting something like this:

    2.770, 8.332.635, 8.281   2.345
    2.690, 8.690   2.674
    2.721, 8.011   2.356
    2.705, 8.242   2.345
    2.670, 8.713   3.002
    2.756, 8.563   2.094
    2.899, 8.413.102, 8.523   2.984
    3.464, 8.196   2.398
    3.705, 8.437   2.745
    3.435, 8.558   2.789
    3.446, 8.592   2.543
    3.421, 8.075   2.984
    3.504, 8.153.772, 8.770   2.183
    3.705, 8.552   2.784
    3.653, 8.443   2.567
    3.908, 7.971   2.098
    5.020, 8.581   2.20
    3.913, 8.247   2.342
    3.762, 8.023.575, 8.345       2.123

The sensor readings after every few lines are distorted. I understand this might has something to do with the serial buffers. How could I rectify this and obtain the desired output?

body:
Your serial buffers and moving in and out of phase, which is distorting your display.

Try something like:

    void setup() {
      String sensor1;
      String sensor2;
      Serial.begin(57600);
      Serial1.begin(9600);
      Serial2.begin(9600);
      while (!Serial)
      {
      }
    }
    void loop() { // run over and over
      if (Serial1.available()) {
        sensor1 = Serial1.readStringUntil('\n'));
      }

      if (Serial2.available()) {
        sensor2 = Serial2.readStringUntil('\n'));
      }

      Serial.print(sensor1);
      Serial.print(sensor2);
      Serial.println();
      delay(1000);
    }

I would also recommend the method suggested by @Majenko in his comment below your question.


message:
Gsm Sim800l Module

I am using below code for send sms but SMS Sent sucessfully but save in SIM memory & not able to see message text :

    serialSIM800.write(“AT+CMGF=1\r”); //sending SMS in text mode
    delay(1000);
    serialSIM800.write(“AT+CMGS=“9827927887”\r”);
    delay(1000);
    serialSIM800.write(“Emergency at IIST\r”); // message
    delay(1000);
    serialSIM800.write(0x1A);
    delay(1000);
    Serial.println(“SMS sent successfully”);

Please help.![enter image description here](https://i.stack.imgur.com/3Jv7t.jpg)![enter image description here](https://i.stack.imgur.com/GYhKj.jpg)

body:
After few minutes of using Google, I found [a library](https://github.com/cristiansteib/Sim800l) that contains everything you need to send/receive SMS and phone call. Here's the code I made in two minutes.

Currently I don't have SIM800L module, so I can't test it. Be sure you type a valid number format. For Croatia it's +385 XX XXX XXXX. +385 is an "international dialling code" for Croatia. Don't forget to put + before IDC.

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

    serialSIM800.write("AT+CMGF=1\r");
    serialSIM800.write("AT+CMGS=\"");
    serialSIM800.write("PHONE_NUMBER");
    serialSIM800.write("\"\r");
    serialSIM800.write("Emergency at IIST");
    serialSIM800.write("\r0x1A");


body:
Set SMS Text Mode Parameters `AT+CSMP` to `AT+CSMP=17,167,0,0`

This setting  is resolve your issue.


message:
Triggering an SPI transfer with an interrupt in Arduino Due

I have a DDS that is controlled by an Arduino DUE,  loop() waits for Serial commands and based on them calls one or another function that sets the DDS's frequency, phase, amplitude etc via SPI. In addition to that I want to be able to use an external interrupt triggered by a TTL signal to reset the DDS's phase accumulator. The phase reset is done by writing an SPI register - resetPhase().

Somehow the resetPhase() is triggered correctly, but as soon as I add a SPI.transfer to it the SPI communication stops working altogether, not just through interrupts, but also the functions triggered via serial commands stop working.

Is there a way to get it to work?

    SPISettings spiSettings = SPISettings(10000000, MSBFIRST, SPI_MODE0);

    void setup()
    {
     pinmode(chipSelect, OUTPUT);
     int syncPIN = digitalPinToInterrupt( interruptPin);
        SPI.usingInterrupt(syncPIN);
        attachInterrupt(syncPIN, resetPhase, RISING);
    }

    void resetPhase():
    {
     SPI.beginTransaction(spiSettings);
     digitalWrite(chipSelect, LOW);
     SPI.transfer(controlRegister);
     digitalWrite(chipSelect, HIGH);
     SPI.endTransaction();
    }

body:
In general, it's best to do as little as possible in your interrupt service routine (ISR).

`resetPhase` is your ISR here, and typically it would set a flag or semaphore to signal lower priority code that certain work needs to be done and, in this case, probably nothing more. Then your `loop` code on noticing the flag is set would clear the flag and do its work.

I imagine the library authors thought `SPI.usingInterrupt` would ease use of SPI, but performing I/O in an ISR seems a bit contrary to best practices. These concerns are echoed [here](https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/), along with some other caveats regarding interrupts and ISRs. Possibly not the answer you're looking for, but I hope it helps.


message:
Send data to a pc localhost with ESP-01 wifi module

i use a linux machine with a localhost php server installed. Wifi machine is connected to the ESP-01 module (access point mode) and i can send several datas to the Arduino via the ESP-01 set as:

      sendData("AT+RST\r\n",2000,DEBUG); // reset module
      sendData("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
      sendData("AT+CIFSR\r\n",1000,DEBUG); // get ip address
      sendData("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
      sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80

The php server can send data by GET method and Arduino receives pin=11:

     http://192.168.4.1:80/?pin=11

But, now, i would like to send to the php server datas from the Arduino. I tried this configuration but in my sketch but, it returns, error.

    sendData("AT+CIPSTART=0,'TCP','http://localhost',80\r\n",1000,DEBUG);

Serial monitor:

       ERROR
       AT+CIPSTART=0,'TCP','http://localhost/test_php',80

       Link type ERROR

So please, how can i send and receive data with my ESP-01 module?

body:
"localhost" is a name associated with the loopback interface of your computer. That is, 127.0.0.1.

It is *not* the address of your computer on the network. The only computer that can talk to "localhost" is the computer itself.

Instead of "localhost" you *must* use the IP address of your computer (or a FQDN that resolves to the IP address of your computer).

And you cannot open a TCP connection to a URL.  You open a TCP connection to an IP or FQDN.

You really should learn the basics of IP networks before trying to write software for them.

----

Since your PC can communicate with the ESP8266 on 192.168.4.1 I assume that you are running the ESP8266 in SOFTAP mode and you have a WiFi interface connected to that access point. If so that WiFi interface will have a 192.168.4.x address assigned to it.  That is the address you must open with a TCP connection on port 80 to connect to your apache server.

For example:

    sendData("AT+CIPSTART=0,'TCP','192.168.4.3',80\r\n",1000,DEBUG);

Then you can craft a suitable HTTP request to send the data.


body:
Open command prompt and type `ipconfig`
Under `IPv4 Address` you can see IP or your PC.
That IP address is address of localhost(because your PC is a "server" within your local/home network).

Don't forget to config XAMP/WAMP to listen special addresses. And of course if you want use localhost, your PC must be on.

> Yes, pc can send, but how can arduino do the same to the pc

Yes, it can. PC(localhost) is server and Arduino is client, like Stackexchange is host and your PC is a client (to Stackexchange). I hope you get it

     The ESP is not linked to my house network and i don't want it as

You can use public server, but you need to Know IP address of the server.


message:
LED brightness and Arduino ports

Hi I am learning Arduino. Pin 13 lights the LED's very brightly. With subsequent LED's on other ports the LED's are much less bright than the one on 13.

Anyone know what is going on?

regards

body:
You probably have cheap crappy inefficient leds on the other pins. Or you have the wrong value resistor in series with them. If they are not from the same batch, with the same resistor, you can't really complain. Maybe they are for a higher voltage. (because of the resistor value)

Are you sure you set the port pins for output?

    pinMode(Output_PIN, OUTPUT);


message:
esp8266 WiFi Cannot Connect to a PHP Server

I am using a magnetic float switch sensor to monitor water level in a tank. I am using a ESP8266 board.

I am trying to send the data collected by it to a php page in a host called "weris.link". I've checked the WiFi ssid and password for a myriad of times, yet somehow the connection to server still failed.

Did i commit a mistake ?

Here's my code :

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

    #include <ESP8266WiFi.h>
    #define FLOAT_SENSOR  D2     // the number of the pushbutton pin
    #define LED           D8      // the number of the LED pin

    const char* server = "weris.link"; // alamat server
    const char* ssid = "aBee"; // SSID router wifi
    const char* password = "xxxxx"; // password wifi
    const char* SensorID = "Water_Level_Kelompok_1.Unsrat"; // ID sensor

    const char* count1= "Water Tank Full";
    const char* count2= "Water Level Low";
    const char* recommend1= "Turn Off Flow";
    const char* recommend2= "Turn on Flow";

    WiFiClient client;

    void setup()
    {
      Serial.begin(115200);
      // initialize the LED pin as an output:
      pinMode(LED, OUTPUT);
      // initialize the pushbutton pin as an input:
      pinMode(FLOAT_SENSOR, INPUT_PULLUP);

      WiFi.begin(ssid, password);

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

    void loop()
    {
      if(digitalRead(FLOAT_SENSOR) == LOW)
      {
        // turn LED on:
        digitalWrite(LED, HIGH);
        Serial.println(count1);
      }
      else
      {
        // turn LED off:
        digitalWrite(LED, LOW);
        Serial.println(count2);
      }
      // mulai Kirim data sensor
       if (client.connect(server,80 && LED == HIGH)) {
        Serial.print("Posting data...");
        digitalWrite(BUILTIN_LED, LOW);
        Serial.println("Tank Full: " + String(count1) + ", Tank Level Below Normal: " + String(count2));

    // dengan GET /path file php penangkap data
    client.println("GET /iot/terima.php?data1=" + String(count1) + "&data2=" + String(recommend1) + "&sid=" +SensorID+ " HTTP/1.1");
    client.println("HOST: weris.link");
    client.println("Connection: close");
    client.println();
    client.stop();
    Serial.println();
    digitalWrite(BUILTIN_LED, HIGH);
    }

    else if(client.connect(server,80 && LED == LOW)) {
      client.println("GET /iot/terima.php?data1=" + String(count2) + "&data2=" + String(recommend2) + "&sid=" +SensorID+ " HTTP/1.1");
      client.println("HOST: weris.link");
      client.println("Connection: close");
      client.println();
      client.stop();
      Serial.println();
      digitalWrite(BUILTIN_LED, HIGH);
     }
      else {
    Serial.println("Koneksi ke server gagal");
     }
      delay(5000);
    }

Below is the screen capture from the serial monitor

[![Here is my picture][1]][1]

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

body:
This line:

    if (client.connect(server,80 && LED == HIGH)) {

is definitely not going to do anything useful. Nor is this line:

    else if(client.connect(server,80 && LED == LOW)) {

In both lines you're take the logical AND of the number 80 and the result of testing the LED.

Put the closing parenthesis in correct place:

    if (client.connect(server,80) && LED == HIGH) {

and

    else if(client.connect(server,80) && LED == LOW) {

Written this way you're still connecting twice if the LED is LOW. The code would be better written:

    if (client.connect(server,80)) {
        if(LED == HIGH) {
          do stuff
        } else {
          do other stuff
        }
    }

Even better would be to have the *do stuff* and *do other stuff* sections just set some variables and then write the code to talk to the web server once, using those variables. Having a single instance of the code will help avoid bugs in the future if you ever need to change it - the DRY (Don't Repeat Yourself) principle of programming.

Also, I hope you didn't just publish your wifi password here. If you did, you should change it.


message:
The Capacitive Sensor library on a D1 Mini

I want to set up a hand-made capacitive sensor on a D1 Mini, as in [this tutorial][1], so that I can get specific capacitive readings. But I couldn't get the CapacitiveSensor library to work with the D1 Mini. Just to make sure I wasn't crazy, I fired up an Arduino Nano knockoff, and the library worked just fine.

I found [a thread from early 2017][2] on this topic, which had various suggestions, none of which worked.

Does anyone know either how to make this library work with a D1 Mini, or another efficient way of getting capacitive readings on digital pins on a D1 Mini?

  [1]: http://playground.arduino.cc/Main/CapacitiveSensor?from=Main.CapSense
  [2]: https://forum.arduino.cc/index.php?topic=462160.0

body:
Actually it looks like the answer was in [the early 2017 thread][1] all along. I switched to a 400k resistor and it works! (I've only verified this just for pins 5 -> 6, although I'd expect it works for any combination of pins not including D0 / D3 / D4 / D8.)

However, a caveat here -- *it doesn't work well.* With an Arduino and a ~6m resistor, you can sense a change in capacitance from several inches away, with a nice continuous increase in capacitance as you get closer. At least for me, the 400k resistor had very low operational range, only maybe 1/2 in. or so, and even then the differences were subtle. But increasing to a 600k resistor replicated the initial problem -- I just got the "-2" error message consistently. And going down to a 200k resistor just decreased the range as you'd expect. So there seems to be a very narrow operational range of resistance for the D1 Mini, with less utility than the Arduino.

  [1]: https://forum.arduino.cc/index.php?topic=462160.0


message:
Actuating a Hobbywing Skywalker 50A-UBEC ESC with Arduino CNC Shield

I need to control a brushless motor that came connected to this ESC using the [Arduino CNC Shield V3.00](https://blog.protoneer.co.nz/arduino-cnc-shield/) and Grbl 0.9j.

I connected the ESC's black wire to a GND from the shield and the ESC's white wire to the shield's Z+ limit (end stop).

I then tested by connecting everything but leaving the ESC unpowered, sending several `M3 S*`commands, where `0 <= * <= 1000`, then powering the ESC, but nothing happened.

body:
After a lot of research, I found out that the variable spindle speed output is a PWM signal, while the ESC needs a PPM signal to be controlled. Although that, it's a specific PPM signal that actually looks like PWM, so it can be used.

The problem is that, instead of being controlled by the duty cycle, what actually controls it is the amount of time that each pulse stays on high, which depends on the period, which is the inverse of the frequency. Long story short, the frequency is too high.

I managed to change the frequency used by grbl and found one that works. I don't know if this frequency allows the whole throttle range to be controlled but, for my application that doesn't require a very strict RPM, it was enough. Here are the steps (some steps are already explained elsewhere):

1. Import grbl's library in Arduino IDE.
2. Find out where the library got installed and edit `grbl/spindle_control.c`, lines [89](https://github.com/grbl/grbl/blob/3ce1a9d637f05e28462a36cb8b166386aab94afc/grbl/spindle_control.c#L89) and [94](https://github.com/grbl/grbl/blob/3ce1a9d637f05e28462a36cb8b166386aab94afc/grbl/spindle_control.c#L94).
3. Change `0x02` to `0x05`. Save and close the file.
4. Compile and download the library to Arduino Uno.
5. Connect everything but leave the ESC unpowered.
6. Send `M3 S0` (that's a zero).
7. Power the ESC.
8. You should hear a 123 tone (three beeps of different frequencies). It will then continue to beep once from time to time — I have no idea why... It should have stopped after a few.
9. Send `S600`. It should start spinning. If it doesn't, first send lower values from 0 to 600.
10. Send `S500` to stop.


message:
ESP8266 feather huzzah wiring for MFRC522

I'm trying to wire the [mfrc522][1] and the huzzah but i can't seem to figure out the rst pin.

I found the pin out diagram but it doesn't show or idk how its labeled as.
[![enter image description here][2]][2]

  [1]: https://github.com/miguelbalboa/rfid#id15
  [2]: https://i.stack.imgur.com/7VjBt.png

body: Use GPIO0 (D3 on the Wemos).  The reset signal is under program control in the library and isn't the same as the ESP8266 reset input.


body:
use Wemos table from your link. here is the mapping to esp8266 io pins

    RST/Reset  D3 = io 0
    SPI SS    D8 = io 15
    SPI MOSI  D7 = io 13
    SPI MISO  D6 = io 12
    SPI SCK  D5 = io 14

If you want, you can use any pin for SS and reset. See the examples.

    #define SS_PIN 4
    #define RST_PIN 5
    MFRC522 mfrc522(SS_PIN, RST_PIN);


message:
How to use php file_get_contents with ESP8266

A part of my project need to get datas from an ESP8266 with php script. I tested this script and i don't know why i can get the datas in an iframe element and nothing with file_get_content function. In iframe element my browser displayes "Hello my friend!" as wanted:

The ESP8266 server mode at 192.168.4.1 address, part of code:

    String webpage = "
Hello
";
    webpage += "
my
";
    webpage += "
friend!
";

    String cipSend = "AT+CIPSEND=";
    cipSend += 0;
    cipSend += ",";
    cipSend +=webpage.length();
    cipSend +="\r\n";

    sendData(cipSend,1000,DEBUG);
    sendData(webpage,1000,DEBUG);
    sendData("AT+CIPCLOSE=0\r\n", 100, DEBUG);

The php script:

     <?php

     $url="http://192.168.4.1/?cmd=SS,0,0,";
     $lines_string = file_get_contents($url);
     echo htmlspecialchars($lines_string);

    ?>

If i replace the url by:

    $url=https://arduino.stackexchange.com

It works with php script,so what is the issue with the ESP8266 ?

body:
To process the request by php, you must send valid HTTP response. The browser tolerates too much.

    String webpage = "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n";
    webpage += "
Hello
";


message:
Is arduino a single board computer?

First excuse me if tags are not reflecting the content,

While watching a [video](https://youtu.be/Kajlrr5ybpU) about single board computer (SBC) I got confused that it doesn't mention arduino as SBC. I always considered it as SBC.

After digging around a bit I got more confused. It seems single board computer is where processor, memory, I/O this things are built on single circuit board rather than using expansion card attached on to a circuit board (motherboard).
According to that is not arduino a SBC? It's processor, memory,storage are on single ATMega32A (for uno) attached on a single board which provides some I/O port (I/O pin, USB, UART, I2C etc.).

From some digging I learned that arduino code runs on bare metal unlike SBC like Rpi and that's the reason for it not being SBC. This seems weird reason.

(1) Is Arduino a SBC?
If (1) is no then next questions are,

(2) Is Being less powerful is the cause? If yes where do you draw the line?

(3) Not having an OS hosted environment for execution is the cause?

If (3) is Yes then,

(4) Arduino has some bootloader code to load the program through USB. Isn't it  kinda like OS, I admit it's not giving some nice api for h/w usage but is it all?

This [link](https://arduino.stackexchange.com/questions/13313/industry-standard-for-single-board-computers) comment section kind of started a debate but ended without giving clear answer about my question.

body:
The Arduino isn't a computer. It is a programmable microprocessor / microcontroller.

Generally a computer can run multiple applications where most programmed devices like the Arduino are running only one program. This is not an official definition but it is one way to differentiate.

It can be difficult to draw a line where it is one but not the other.

> (4) Arduino has some bootloader code to load the program through USB.
> Isn't it kinda like OS, I admit it's not giving some nice api for h/w
> usage but is it all?

No that isn't like an operating system. The Arduino does not have a real operating system when compared to a computer system. And someone being able to load in a new program is just changing the current single program that is runnable.

> An operating system (OS) is system software that manages computer
> hardware and software resources and provides **common services for**
> **computer programs**.

I think the **programs** being plural is an important factor, but this is only my opinion.

There is no one definition so you will get a number of different opinions. And most will be reasonable.


body:
It all depends on your definition of "computer".  From the point of view that the Arduino is a "Turing complete" architecture, with CPU, memory, storage, IO, etc, then yes, it is a computer. But it's not a "computer" as in what you have on your desk.

Is a mobile phone a "computer"?

We can shift the definition elsewhere if you like:

In general an SBC is taken to be a SoC mounted on a board with the support components.  A SoC is a "System on Chip".  But now we just move the definition to "What is a SoC?" - a question that has been asked many times before.

There is no one specific thing that divides a SoC from a Microcontroller. For instance:

* "A SoC runs an operating system, but a Microcontroller doesn't" - except that there are microcontrollers that can and do run operating systems, and you don't *have* to run an operating system on a SoC.
* "A SoC relies on external memory, but Microcontrollers have it built in" - except that there are SoCs with built in memory, and Microcontrollers than need external memory to function

The list goes on.

My definition of what constitutes a "computer" as opposed to an "embedded system" has nothing to do with what the device *is*, it's *what you do with it*.

If the board is being used with a keyboard, mouse, screen, etc for *generic* operation then it's a computer. If it's being programmed for *one specific task* then it's an embedded system.  The same hardware could be used in both ways, and I would call it a computer if it were running "general" software (operating system, web browser, server software, etc), but I'd call it an "embedded system" if it were running one program only (with or without an OS) gathering data, reporting it back to a central system, etc.

For something to be termed a "Single Board Computer" I would say it has to be *capable* of running *general* software designed to run on a "traditional" computer.  Things like Linux with Apache etc, or a desktop environment.

Mind, this is only my opinion, and as such it will differ from other peoples' opinions.


body:
It may be impossible to draw a sharp line that separates single board
computers from microcontroller boards. There are, however, several
attributes that can help differentiate them and, in a sense, draw a
blurry line. If a specific board has most of the attributes of SBCs it's
probably safe to call it an SBC. Same for MCU boards.

Processing power may be one of those attributes. A typical SBC is many
orders of magnitude more powerful than your typical Arduino. A Raspberry
Pi, for example, has half a million times the RAM of an Arduino Uno.
Although you can find microcontrollers that are a thousand times more
powerful than the Uno, you are unlikely to find many SBCs that are one
hundred times less powerful than a Raspberry Pi.

The operating system may also be a factor. SBCs are typically meant to
run mainstream OSes: some flavor of Linux, Windows or Android.
Microcontrollers, on the other hand, will most often run some kind of
RTOS (real-time OS) specifically designed for the embedded world, if
they do run an OS at all.

A factor that has not been mentioned yet is the I/O capabilities. On an
SBC, you will typically find the kind of I/O ports that are common on
desktop or laptop computers, like HDMI, USB host or Ethernet. A
microcontroller, on the other hand, is more likely to have analog inputs
or outputs, as these are more useful in the “electronics” world than in
the “computer” world. Of course, the lines are blurry: you may find SPI,
I2C and GPIOs on both SBCs and MCUs.

Neither of those factors may be enough to tell an SBC apart from a MCU
board. But taken together, they can allow you to say that board A is
clearly an SBC, board B is clearly an MCU board, and board C is
somewhere in between and hard to classify.


message:
Is it possible to simultaneously acquire 2 values from the Arduino?

I am currently making a project using a resistive touch screen and an Arduino Uno. The resistive touch screen outputs an X and Y coordinate pair, which I then want to be able to read and output on an X-Y scatter plot in Visual Basic. I am wondering if it's possible to collect these X and Y coordinates at the same time, and read them through the serial port so they can be used in Visual Basic.

body: Since this is a Arduino forum I will answer the Arduino part of your question. Yes you can get the coordinates and get them into the computer via a serial port.