message:
MKR GPS Shield Sampling Frequency

I have the MKR 1010 and am working on a circuit that needs realtime GPS positioning.  I bought the MKR GPS Shield, and am using it on the I2C bus (attached via cable to the 1010 board), and am using the Arduino_MKRGPS library in my sketch.

I am attempting VERY basic interaction with the board at the moment, and basically just want to print out the GPS coordinates to the serial.

I am using the GPSLocation sample from the Arduino_MKRGPS library (see [here][1]):

```
  /*
  GPS Location

  This sketch uses the GPS to determine the location of the board
  and prints it to the Serial monitor.

  Circuit:
   - MKR board
   - MKR GPS attached via I2C cable

  This example code is in the public domain.
*/

#include <Arduino_MKRGPS.h>

void setup() {
  // initialize serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // If you are using the MKR GPS as shield, change the next line to pass
  // the GPS_MODE_SHIELD parameter to the GPS.begin(...)
  if (!GPS.begin()) {
    Serial.println("Failed to initialize GPS!");
    while (1);
  }
}

void loop() {
  // check if there is new GPS data available
  if (GPS.available()) {
    // read GPS values
    float latitude   = GPS.latitude();
    float longitude  = GPS.longitude();
    float altitude   = GPS.altitude();
    float speed      = GPS.speed();
    int   satellites = GPS.satellites();

    // print GPS values
    Serial.print("Location: ");
    Serial.print(latitude, 7);
    Serial.print(", ");
    Serial.println(longitude, 7);

    Serial.print("Altitude: ");
    Serial.print(altitude);
    Serial.println("m");

    Serial.print("Ground speed: ");
    Serial.print(speed);
    Serial.println(" km/h");

    Serial.print("Number of satellites: ");
    Serial.println(satellites);

    Serial.println();
  }

  delay(100);
}
```

What I'm seeing is that the GPS takes on the order of 30-90 secs to initialize, and then only provides new updated coords every 20-30 secs.  This is all with a clear view of the sky.

Is that really what to expect from this module?  I was under the impression that it could provide several samples per second.  Documentation seems to be very lacking for the Arduino_MKRGPS library.  Anyone else have insights or experience with this module?

Thanks!

  [1]: https://github.com/arduino-libraries/Arduino_MKRGPS/blob/master/examples/GPSLocation/GPSLocation.ino

body:
It seems that the problem with the GPS was caused by my usage of the arduino delay(...) method in my loop.

I'm assuming that by using delay, the connection to the GPS module was being severed, and in effect, every loop was forcing a reconnect and a new download of satellite details.

In summary, when needing high sample frequency interaction with the GPS, using delay in the sketch won't work.

EDIT:

I've done a lot of digging since originally posting this question/answer and wanted to add my findings for others that are struggling to make the MKR GPS module work for higher than 1Hz sample rate use cases.

I had to make the following two changes to the Arduino_MKRGPS library:

1. increase baud rate of the GPS connection.  In the very last line of GPS.cpp...

```
GPSClass GPS(Serial1, 460800, serialDDC, 400000, 7);
```

2. In GPS.h, make the sendUbx method a public member of the GPS class.  This allows me to send low-level commands to the SAM-M8Q from my sketch.

After this, I can construct low-level messages in my sketch and configure the GPS to my liking.  Here's what I did to increase the sample rate to 3Hz in my sketch's setup method:

```
  Serial.println("Configuring GPS refresh rate...");

  //  UBX-CFG-RATE (0x06 0x08) Navigation/Measurement Rate Settings
  //  See UBX-13003221 section 32.10.23.1
  byte payload[6];

  memset(payload, 0x00, sizeof(payload));

  uint16_t measRate = 333;    // ms between gps data publish  (min of 100)
  uint16_t navRate  =   1;    // ratio between measurements and nav solution calculations
  uint16_t timeRef  =   1;    // The time system to which measurements are aligned (0: UTC, 1:GPS, ...)

  // write out the unsigned shorts in little-endian form
  payload[0] = measRate & 0xff;
  payload[1] = (measRate >> 8) & 0xff;
  payload[2] = navRate & 0xff;
  payload[3] = (navRate >> 8) & 0xff;
  payload[4] = timeRef & 0xff;
  payload[5] = (timeRef >>8) && 0xff;

  GPS.sendUbx(0x06, 0x08, payload, sizeof(payload));

  Serial.println("  > done");
```

Hope this helps someone else struggling with higher data rate use cases.  There's still room for improvement, I think, in particular by reducing the number of sentences returned by the GPS.  I haven't been able to get the sample rate higher than 5Hz, while technically the GPS is supposed to be capable of doing 10Hz.  I'm not sure where the bottleneck is.


sender: user

message:
Blew my Arduino. Did I wire this correctly?

[![Basic Circuit Diagram][1]][1]

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

Hi,

I am currently doing a project and it seems that I may have blown my Arduino Nano (or maybe not). The power LED of the Nano was still on and I believe the L pin blinks once every time I press the reset button.

I wanted to use 4AA alkaline batteries to power my project. The servo is a continuous servo rated for 4-6V and 15-200mA from Parallax. Given that the Nano runs optimally when powered at 7-12V, I decided to buy a step-up converter (adjustable output voltage). It looks like this although I bought it elsewhere:

https://www.ebay.com.au/i/283603471149?chn=ps&norover=1&mkevt=1&mkrid=705-139619-5960-0&mkcid=2&itemid=283603471149&targetid=752505019384&device=c&mktype=pla&googleloc=9071392&poi=&campaignid=1979582348&mkgroupid=72745766764&rlsatarget=pla-752505019384&abcId=1139426&merchantid=7364522&gclid=Cj0KCQjwt5zsBRD8ARIsAJfI4Bh8cSOKugFrugHz-gA-s8nXclnO7H8iQ-WX46FRdhDLchwbl6UyWLgaAr4oEALw_wcB

When I tried to test it with the servo running, my Nano stopped working after several seconds later. Did I wire them up wrongly? I also measured the output of the step-up converter when it was running with a voltmeter between the two terminals of the step-up's output. Would it be possible to short it that way?

Appreciate any help I can get. Thanks

sender: assistant

body:
It would be best if everything ran at the same voltage. (And it is necessary that everything uses the same ground.)  Which is possible as there are 5V Arduino boards.  Interestingly, the Arduino nano, according to [this schematic][1], runs at 5V.

In order to use the Arduino Nano at 5V, instead of using VIN / Pin 1, you should be able to skip the Arduino's 5V regulator and use +5V / Pin 4.  But this must be a regulated 5V power source.

Now, why are you having problems controlling the servo?

It is difficult to tell, but your boost switching power supply negative input may not be directly connected to the negative output.  With out a common ground, it may be difficult to create the proper signal to control the servo.

To be specific, if the ground or negative side of the servo power supply is not at the same potential as the ground or negative side of the Arduino power supply, controlling the servo may be difficult at best and at worst you could burn something out on the servo or Arduino.

To check, measure with a volt meter to see if there is any difference between the boost switcher negative input and negative output.

To solve this problem consider using a USB power supply plugged into the Arduino Nano and powering the servo off the 5V at pin 4 of the Nano.  Or, keep using your 6V battery and 6V to 9V boost switching power supply.  Connect this as you are to VIN Pin 1.  The Arduino Nano's 5V power regulator should kick in and provide 5V at pin 4.

  [1]: https://content.arduino.cc/assets/NanoV3.3_sch.pdf


message:
How to decrease delay for String concatenation + Arduino Due

In my project I need to add a delimiter between integer numbers. In the following code. I add a "," between integer numbers obtained from inputsig matrix. The problem is that concatenation of these numbers with concat() command for a Matrix with 100 rows and 9 columns takes 10 ms.  Is there any efficient way to decrease this delay?

```c++
#include <CStringBuilder.h>

int Max_pack_size = 100;

void setup() {
  SerialUSB.begin(115200);

  while (!SerialUSB) ;

}

void loop() {

  String  datas1;
  String  inputsig[Max_pack_size][9];
  char buff[((8+1)*Max_pack_size+1)*9];
  CStringBuilder sb(buff, ((8+1)*Max_pack_size+1)*9);

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      inputsig[i][j] = 16777215;

    }
  }

  int t0 = micros();

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      //datas1.concat(inputsig[i][j]);
      //datas1.concat(",");
  sb.print(inputsig[i][j]);
  sb.print(F(","));
    }
  }

 SerialUSB.println(float(micros() - t0));
 delay(1000);

 SerialUSB.println(buff);

}
```

body:
I don't have Arduino Due but I have an Arduino Uno so I had to adjust the code to run with much smaller RAM and use the standard Serial.

This is the original code as you can see i can use only Max_pack_size of 5

```c++
#include <CStringBuilder.h>

int Max_pack_size = 5;

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

void loop() {

  String inputsig[Max_pack_size][9];
  char buff[((8 + 1)*Max_pack_size + 1) * 9];
  CStringBuilder sb(buff, ((8 + 1)*Max_pack_size + 1) * 9);

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      inputsig[i][j] = 16777215;
    }
  }

  int t0 = micros();

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      sb.print(inputsig[i][j]);
      sb.print(',');
    }
  }

  int t1 = micros();

  Serial.println(float(t1 - t0) / 1000.0);
  delay(1000);

  Serial.println(buff);
}
```
The timer displays values around 2.08 milliseconds for the code above.

First optimization attempts is to stop using StringBuilder. Everything that's written to be universal and easy to use is usually slow.

Note that when we generate `String` from `long` the [implicit cast][1] allocates `char buf[2 + 3 * sizeof(long)];` so the max length of such string is 14 characters. String is of course terminated by null character `'\0'`

```c++
#include <CStringBuilder.h>

int Max_pack_size = 5;

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

void loop() {

  String inputsig[Max_pack_size][9];
  char buff[((8 + 1)*Max_pack_size + 1) * 9];

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      inputsig[i][j] = 16777215;
    }
  }

  int t0 = micros();

  int p = 0;
  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      for (int k = 0 ; k < 14; k++)
      {
        char c = inputsig[i][j][k];

        if (c == 0)
          break;
        else
          buff[p++] = c;
      }

      buff[p++] = ',';
    }
  }

  int t1 = micros();

  Serial.println(float(t1 - t0) / 1000.0);
  delay(1000);

  Serial.println(buff);
}
}
```

Now the timer displays 0.86 milliseconds. Much better, but we can improve even more!

Let's drop the String. It's just an over complicated wrapper for a char array anyway.

```c++
#include <CStringBuilder.h>

int Max_pack_size = 5;

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

void loop() {

  char inputsig[Max_pack_size][9][14];
  char buff[((8 + 1)*Max_pack_size + 1) * 9];

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      ltoa(16777215, inputsig[i][j], 10);
    }
  }

  int t0 = micros();

  int p = 0;
  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      for (int k = 0 ; k < 14; k++)
      {
        char c = inputsig[i][j][k];

        if (c == 0)
          break;
        else
          buff[p++] = c;
      }

      buff[p++] = ',';
    }
  }

  int t1 = micros();

  Serial.println(float(t1 - t0) / 1000.0);
  delay(1000);

  Serial.println(buff);
}
```

Now the timer shows 0.50 milliseconds. So we optimized the code to the point it runs 4 times as fast.

  [1]: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/WString.cpp


message:
How to use the pushbutton without using if, else

I want to let the led blink for 3 seconds then 2 seconds then one second using the button one time and without using if/else

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

    void loop() {
        // put your main code here, to run repeatedly:
        digitalRead(5, HIGH);
        digitalWrite(6, HIGH);
        delay(3000);
        digitalWrite(6, LOW);
        digitalWrite(6, HIGH);
        delay(2000);
        digitalWrite(6, LOW);
        digitalWrite(6, HIGH);
        delay(1000);
    }

body: As the required operation is finite and short, you can just hard code the sequence.


body:
You could you simple inversion of boolean variable to set state of LED.

    const int LedPin = 5;
    bool ledState = true;

    // in your loop

    // bool will be transformed from true to 1 (HIGH)
    digitalWrite(LedPin, (int)ledState);
    // invert LED state to be false
    ledState = !ledState;
    // false -> 0 (LOW)
    digitalWrite(LedPin, (int)ledState);


body:
Ternary operator maybe helpful. [[Reference]][1]

  [1]: https://www.tutorialspoint.com/arduino/arduino_conditional_operator.htm


message:
Interrupt is activated as soon as I insert a jumper wire into the port

I have written a very simple code to test the interrupt functionality of my Arduino Uno expansion board:

~~~c++
const byte buttonPin3 = 3;

void setup() {
  pinMode(buttonPin3, INPUT);
  attachInterrupt(digitalPinToInterrupt(buttonPin3), trigger, CHANGE);

  Serial.begin(9600);
}

void loop() {
}

void trigger(){
  Serial.println("trigger");
}
~~~

However, the `Serial.println("trigger");` is activated as soon as I insert a jumper wire into pins 2 or 3. It seems like I have broken the microcontroller. I would appreciate if you could help me know if there is something wrong with my code or I need to change the microcontroller? if I have to replace the MCU can I just use any identical AVR and just place it on the DIP IC socket adaptor?

**P.S.** [Filip Franik][1] asked me to draw the schematics:

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

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

<!-- End schematic -->

**P.S.** I used [the official Button's tutorial][2] and now everything works just fine. I can't reproduce the issue anymore for no obvious reason!.

  [1]: https://arduino.stackexchange.com/users/34529/filip-franik
  [2]: https://www.arduino.cc/en/tutorial/button

body:
Connect both Pin2 and Pin3 with two 1K resistors to ground.

When a pin that's set as INPUT is "floating" (it's not connected to anything) the value on it is "undetermined" and interrupt can trigger when a neighboring pin status changes, or even just magically by itself. The 1K resistors (called pulldown resistors) will make sure that pin is set to LOW when it's not connected using the jumper.

This circuit should put a stable 0V on Pin3 when switch is unpressed and 5V when it's pressed. You should be able to verify that using any voltage meter.

[![modified design from the question][1]][1]

If the issue persists then swapping the microcontroller on the Arduino is just one of the steps you need to perform. You would also need to [burn a bootloader][2] on the chip. It's not a hard procedure but it requires a second Arduino.

  [1]: https://i.stack.imgur.com/ASSdN.png
  [2]: https://arduino.stackexchange.com/questions/473/how-do-i-burn-the-bootloader


body:
CMOS inputs "float" when not connected to anything, and will give semi-random values. You can either connect the pin to ground via a medium value resistor (1kΩ-10kΩ), or set the pin to INPUT_PULLUP mode.

You shouldn't move the interrupt pin connections around while the Arduino is running. As soon as you disconnect the wire from the input, it begins floating again, and can detect semi-random HIGH/LOW values.

If you use an external pull-down resistor, put a connector after the ground connection and move that connection, so the pull-down resistor is always connected to the pin.

If you use INPUT_PULLUP mode, you should not use a pull down or pull up resistor. This mode connects the pin weakly to +5V, which will hold it at a HIGH value when not connected to anything. You would then ground it to trigger an interrupt. In INPUT_PULLUP mode you can probably disconnect the wire from the interrupt pin without triggering interrupts.


message:
How to Sort a String with Number by Ascending

I have trouble figuring out how to sort a String that has a Number in it.

The String im sending looks like 112:AAAA and 111:EEEE, how would I sort it so that the 111 will be the first in an array but (and here is what I cant figure out) the sorted array should contain the letters again so it would be a String Array that is sorted by the numbers and look like 111:EEEE, 112:AAAA.

I wanted to use what I have seen on C#, having a key and value, but that does not seem to exist in arduino code. So I improvised by writing everything in 1 char array.

edit: I see I'm mixing up char array and string, im very flexible and its no trouble to change to 1 or the other, currently I use char arrays.

I guess it would also be enough to just sort the strings, but i cant find a function for that also.

body:
You can use the `qsort` function (see [c-library-function-to-do-sort][1]).

With the user definable `comp` function you can get the first two or three characters, convert it to in integer and compare it against the converted integer from another element.

I would not advise to use strings, because of the limited SRAM storage of an Arduino, you might run out of memory too fast.

  [1]: https://stackoverflow.com/questions/1787996/c-library-function-to-do-sort


body:
As Michel Keijzers points out, `qsort` is the standard sorting function
from the libc. Now, since your numbers can start with either two or
three digits, you can not sort them lexicographically, because if you
did so 111 would sort before 82. Instead I suggest to:

* parse the start of the strings as integers
* compare the integers
* if the integers are equal, then sort the strings lexicographically.

The simplest way to parse the strings into integers is `atoi()`. Unlike
functions like `strtol()`, `atoi()` does no error checking, but it is
good enough if you know for sure that the strings have the right format.

Here is the comparison function:

```c++
int compare(const void *a, const void *b)
{
    // Get the strings.
    const char *sa = *(const char * const *) a;
    const char *sb = *(const char * const *) b;

    // First, compare the numeric prefixes.
    int ia = atoi(sa);
    int ib = atoi(sb);
    if (ia < ib) return -1;
    if (ia > ib) return +1;

    // If equal, compare the strings lexicographically.
    return strcmp(sa, sb);
}
```

And here is an example on how to use it:

```c++
#define STR_COUNT 3
const char *strings[STR_COUNT] = { "112:AAAA", "82:FFFF", "111:EEEE" };
qsort(strings, STR_COUNT, sizeof strings[0], compare);
```

Now the array of strings is sorted as ("82:FFFF", "111:EEEE",
"112:AAAA").


message:
How to get current Date

, month and year. I have used RTC, NTPClient, but it didn't work. This gives default output of 1970. What can I do for fixing it.
<!-- language-all: lang-cpp -->

    time_t now = time(nullptr);
    struct tm* newtime = localtime(&now);
    String tmpNow = "";
    tmpNow += String(newtime->tm_year + 1900);
    tmpNow += "-";
    tmpNow += String(newtime->tm_mon + 1);
    tmpNow += "-";
    tmpNow += String(newtime->tm_mday);
    tmpNow += " ";

body:
An [example][1] how to use NTPClient is available at the projects github

```c++
#include <NTPClient.h>
// change next line to use with another board/shield
#include <ESP8266WiFi.h>
//#include <WiFi.h> // for WiFi shield
//#include <WiFi101.h> // for WiFi 101 shield or MKR1000
#include <WiFiUdp.h>

const char *ssid     = "<SSID>";
const char *password = "<PASSWORD>";

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);

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

  WiFi.begin(ssid, password);

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

  timeClient.begin();
}

void loop() {
  timeClient.update();

  Serial.println(timeClient.getFormattedTime());

  delay(1000);
}

```

Form what I found TimeRTC requires an external device called DS1307RTC to keep track of the time as shown in [video here][2] and with it we should be able to get the real time as seen in github [example][3]

```c++
#include <TimeLib.h>
#include <Wire.h>
#include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t

void setup()  {
  Serial.begin(9600);
  while (!Serial) ; // wait until Arduino Serial Monitor opens
  setSyncProvider(RTC.get);   // the function to get the time from the RTC
  if(timeStatus()!= timeSet)
     Serial.println("Unable to sync with the RTC");
  else
     Serial.println("RTC has set the system time");
}

void loop()
{
  if (timeStatus() == timeSet) {
    digitalClockDisplay();
  } else {
    Serial.println("The time has not been set.  Please run the Time");
    Serial.println("TimeRTCSet example, or DS1307RTC SetTime example.");
    Serial.println();
    delay(4000);
  }
  delay(1000);
}

void digitalClockDisplay(){
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print(" ");
  Serial.print(month());
  Serial.print(" ");
  Serial.print(year());
  Serial.println();
}

void printDigits(int digits){
  // utility function for digital clock display: prints preceding colon and leading 0
  Serial.print(":");
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits);
}
```

If what I understand from your code you are actually not using any RTP or NTP. You are only creating a Time object with no values and you read it default values.

Check some more examples [here][4]

  [1]: https://github.com/arduino-libraries/NTPClient/blob/master/examples/Basic/Basic.ino
  [2]: https://www.youtube.com/watch?v=E6wkvTG2Ofs
  [3]: https://github.com/PaulStoffregen/Time/blob/master/examples/TimeRTC/TimeRTC.ino
  [4]: https://github.com/PaulStoffregen/Time/tree/master/examples


message:
MQTT with OLED realy :- display not coming properly

I am very new to Arduino/ESP and I am writing a code to activate 2 relays using MQTT. Also like to display status on OLED

here is my code

```
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <WiFiManager.h>
#include <PubSubClient.h>
#include <Wire.h>
#include "SSD1306Wire.h"
#define wifi_ssid "ssid"
#define wifi_password "wifipassword"
#define mqtt_server "192.168.1.1"
#define mqtt_user "username"
#define mqtt_password "password"

SSD1306Wire  display(0x3c, D2, D1);
const int relay1 = 5;
const int relay2 = 4;
String header;
String display_line2;
String output5State = "off";
String output4State = "off";
const int output5 = 5;
const int output4 = 4;

WiFiClient wificlient;
WiFiClient espClient;
PubSubClient client(espClient);
ESP8266WebServer server(80);

//------------------- MAIN WEB PAGE ------------------------
const char MAIN_page[] PROGMEM = R"=====(
<head><meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>HOME IOT</title>
<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}
.button { background-color: #195B6A; border: none; color: white; padding: 16px 40px
text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer
body{margin-top: 50px;} h1 {color: #444444;margin: 50px auto 30px;
.button2 {background-color: #77878A;
p {font-size: 24px;color: #444444;margin-bottom: 10px;}
</style>
</head>
<body>
<div id="webpage">
<h1>Security Door</h1>
<p><a href="/show/SecurityDoor/Open"><button class="button">Open</button></a></p>
<p><a href="/show/SecurityDoor/Close"><button class="button">Close</button></a></p>
</div>
</body>
</html>
)=====";
//------------------- MAIN WEB PAGE ------------------------

void setup() {
  Serial.begin(9600);
  //dht.begin();
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  //-----------------------------------------
  WiFiManager wifiManager;
  //wifiManager.resetSettings();
  wifiManager.autoConnect("IOT-LivinRoom");
  //-----------------------------------------
  server.on("/", handle_OnConnect);
  server.onNotFound(handle_NotFound);
  server.begin();
  Serial.println("Initializing OLED Display");
  display.init();

  display.flipScreenVertically();
  display.setFont(ArialMT_Plain_10);
  Serial.println("HTTP server started");
}

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(wifi_ssid);
  WiFi.begin(wifi_ssid, wifi_password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  String messageTemp;
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
    messageTemp += (char)payload[i];
  }
  Serial.println();

 if(strcmp(topic, "livingroom/securitydoor") == 0){
     Serial.print("Changing esp01 relay1 to ");
     if(messageTemp == "on"){
       digitalWrite(relay1, LOW);
       Serial.print("On");
       doorOpening();

     }
     else if(messageTemp == "off"){
       digitalWrite(relay1, HIGH);
       Serial.print("Off");
       doorClosing();
     }
 }
 Serial.println();

 if(topic=="livingroom/ac"){
     Serial.print("Changing esp01 relay2 to ");
     if(messageTemp == "on"){
       digitalWrite(relay2, LOW);
       Serial.print("On");
       doorOpening();

     }
     else if(messageTemp == "off"){
       digitalWrite(relay2, HIGH);
       Serial.print("Off");
       doorClosing();
     }
 }
 Serial.println();
}

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (client.connect("ESP8266Client", mqtt_user, mqtt_password)) {
      Serial.println("connected");
      client.subscribe("livingroom/securitydoor");
      client.subscribe("livingroom/ac");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

//--------------------------- void loop-----------------------
void loop() {

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

}

//----------------------------- Web Calls Function --------------------------------------
void handle_OnConnect() {
String s = MAIN_page; //Read HTML contents
server.send(200, "text/html", s);
}

void handle_NotFound(){
  server.send(404, "text/plain", "Not found");
}

//----------------------- LED display--------------------------------------

void doorOpening() {
  display.clear();
    display.setTextAlignment(TEXT_ALIGN_LEFT);
    display.setFont(ArialMT_Plain_24);
    display.drawString(0, 0, "Door");
    display.setFont(ArialMT_Plain_24);
    display.drawString(0, 28, "Opening");
  display.display();
}

void doorClosing() {
  display.clear();
    display.setTextAlignment(TEXT_ALIGN_LEFT);
    display.setFont(ArialMT_Plain_24);
    display.drawString(0, 0, "Door");
    display.setFont(ArialMT_Plain_24);
    display.drawString(0, 28, "Closing");
  display.display();
}

```

actually doorOpening() function is coming and doorClosing() function is not coming on OLED

again i am not very good in programming and arduino/esp8266

body: i found the issue, actually relay pin was defined on D1 & D2 by mistake i connected oled to that pins


message:
Can Chirp Waves be sent using JSN-SR04T?

So i have project for underwater rangefinding using JSN-SR04T. I've read on the datasheet that the module sends square waves. Is it possible to program it so that it sends Chirp waves instead ? (Help with the coding is very appreciated)
Thanks in advance

body:
As I googled the sensor, I found various sites stating, that a JSN-SR04T behaves exactly like the HC-SR04. The difference is mainly the water prooving.

So the answer is: No, you can't do this. The square wave, which drives the ultrasonic transducers, is generated by a hardware circuit and is not meant to be changed. To output a chirp wave you would need to rebuild the signal generation and measurement hardware (leaving only the transducers unchanged). At that point you may just buy the pure ultrasonic transducers and build the rest yourself.


message:
Ultrasonic Sensor - JSN-SR04T 2.0

I would like to use the JSN-SR04T 2.0 in order to find the depth of a body of water. Once I test the sensor in a body of water, the distance measurements are then constant at about 20 cm. I then changed my distance formula to account for the speed of sound in water, but the measurements are still constant despite change in the body of water. Does anyone have any recommendations on how to obtain better measurements underwater?
<!-- language-all: lang-cpp -->

    #define trigPin 2
    #define echoPin 3

    // Define variables:
    long duration;
    int distance;

    void setup() {
      // Define inputs and outputs
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);

      // Begin Serial communication at a baudrate of 9600:
      Serial.begin(9600);
    }
    void loop() {
      // Clear the trigPin by setting it LOW:
      digitalWrite(trigPin, LOW);

      delayMicroseconds(5);
     // Trigger the sensor by setting the trigPin high for 10 microseconds:
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);

      // Read the echoPin. pulseIn() returns the duration (length of the pulse) in microseconds:
      duration = pulseIn(echoPin, HIGH);

      // Calculate the distance:
      distance = duration*0.034/2;

      // Print the distance on the Serial Monitor (Ctrl+Shift+M):
      Serial.print("Distance = ");
      Serial.print(distance);
      Serial.println(" cm");

      delay(100);
    }

body:
According to the data sheet the minimum target distance is 20cm in the open air at a 343 m/s

The speed of sound in water is 1481 m/s so the minimum distance would be 20cm x 1481 / 343 = 86cm.

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

You cannot measure distances under 83cm in water.

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


message:
What is the difference between a Hall effect sensor and an inductive one?

From what I have read, when placed within a magnetic field, a current will flow in both sensors.

My goal is to use this kind of sensors to guide a robot thanks to an existing automower loop wire, such as suggested in [DIY Perimeter Wire Generator and Sensor][1].

I am thus wondering what is the difference between a Hall effect sensor and an inductive one such as the one described in the link above?

  [1]: https://www.instructables.com/id/DIY-Perimeter-Wire-Generator-and-Sensor/

body:
First they physically work differently. In the Hall effect sensor the electrons flowing through a plate will be deflected. Thus there will be a voltage perpendicular to the current, which can be measured. The voltage will be proportional to the magnetic field strengh. So you can sense a magnet, that is near the sensor, even if it doesn't move.

For the inductive sensor you have a guiding wire, that has an AC current flowing through it. This also means, that a magnetic field ist constantly building up and collapsing again around the wire. This change of magnetic field will induce an induction voltage in a nearby wire loop (the actual sensor). The frequency of that voltage is the same as of the guidance wire and the strength depends on the distance between the wires. So you are not measuring the magnetic field strength directly, but you measure how much it is changing (mathematically you differentiate).

Two different measurement methods which can be used to do the same thing. To guide a robot over a predefined course I would use the induction method (as long as the situation allows laying out wires), since it can be made less susceptible to noise. For that you can filter out all frequencies except of the used guiding frequency with a LC circuit. Or even better (though maybe not important) a lock-in amplifier. The hall sensor is an analog device, which can be very noisy.


message:
WiFi connection in loop function

What I am trying to do is while connected locally in the esp8266 and give it a ssid and password, save them in a global variable and use them to start a connection inside loop function with a flag so it happens only once and let the program run while I check when the connection is complete. Do you foresee any problems with this application?:

    setup(){
        wifi.mode(WIFI_AP_STA);
        setup softAP
        server.on("/",handleroot)
        server.begin()
    }
    loop(){
        server.handleClient()
        if(credential_submited){
            Wifi.begin(credentials);
            flag_connection_started =true;
            credential_submited = false;
            flag_for_internet_server=true;
        }
        if(WiFi.status()==WL_CONNECTED && flag_for_internet_server==true){
            server.on("/",handleroot)
            server.begin()
            flag_for_internet_server=false;
        }

I know there is also WifiManager But I am trying to do it on my own. The thing is some wifi networks take a lot of time to connect. More precisely they connect but then the esp doesn't get an ip and disconnects.
Thank you for your time

body:
WiFi.begin() in ESP8266WiFi library doesn't wait until the connection completes, it returns immediately.

You can check if the connection to WiFi network is established using WiFi.status() as most of the examples show. And it is not mandatory to wait for the connection in setup().

BTW: You can use a separate sketch to set the SSID and password in esp8266 and then in all other sketches not use WiFi.begin(), only wait for the connection to WiFi network to finish.


message:
Syntax for stopping loop until the condition has made false

I am taking reading from temperature sensor and from that data. I have to control 3 LEDs. Lets consider LED1, LED2, LED3.

    If temperature range between 0-20
       I have to HIGH LED2.
       else if temperature range between 20-30
    I have to HIGH LED1; HIGH LED3; LOW LED1;

my sketch is something like this:-

    while(1)
    {
    if(temp>=0&&temp<=20)
    {
    digitalWrite(2,HIGH);
    }
    else if (temp>=20&&temp<=30)
    {
    digitalWrite(1,HIGH);
    digitalWrite(3,HIGH);
    digitalWrite(1,LOW);
    }
    }

The problem which I am facing is LED1 is continuously ON (which should be OFF), when temperature is between 20-30 because of continuously running loop so, how can I stop loop, once the statement under second condition has executed till the second condition has made false.

body:
Your code doesn't make sense. You have a `while (1)` statement, which will run forever. Inside the body of that statement, you never change the value of `temp`.

An Arduino sketch's `loop()` function runs continuously. You should not have a `while (1)` loop inside your loop function. You should have a loop function something like this:

    void loop() {
      temp = //read a temp value somehow
      if(temp>=0&&temp<=20)
      {
        digitalWrite(2,HIGH);
      }
      else if (temp>=20&&temp<=30)
      {
        digitalWrite(1,HIGH);
        digitalWrite(3,HIGH);
        digitalWrite(1,LOW);
      }
    }

With that loop function you would fetch a new value of temp on each pass through the loop, then decide what LEDs to light.


body:
You don't want to stop the loop! You want it to run fast and often.

Eventually you want it to not change the current state of a LED, but in your case, I rather do not see enough defined states of LEDs.

>I want to first ON LED1 then ON LED2 then OFF LED1"

if `then` means an amount of time, remember that loop runs fast and does not take time by itself. You will have to notice the starting point in time and compare that with the current time and your desired intervals. (And you do not mention what should happen to LED2 after the second _then_ )

    const unsigned int LED1_DURATION=500;
    const unsigned int LED3_DURATION=1000;
    bool c2 = false;  // true while condition2 is met
    unsigned long start2;  // time when condition2 starts
    void loop() {
      int temp = analogRead(A0); //read a temp value somehow
      if(temp<=20)
      {
        digitlaWrite(1, LOW);
        digitalWrite(2,HIGH);
        digitlaWrite(3, LOW);
        c2 = false;
      }
      else if (temp >20 && temp <= 30)
      {
         digitalWrite(2, LOW);

         if (c2 == false) { c2 = true; start2=millis(); } // detect start time

         if ((millis() - start2 < LED1_DURATION) ||
             (millis() - start2 > LED3_DURATION)   )
              digitalWrite(1,HIGH);
         else digitalWrite(1, LOW);

         if ((millis() - start2 > LED1_DURATION) &&
             (millis() - start2 < LED3_DURATION)    )
              digitalWrite(3,HIGH);
         else digitalWrite(3,LOW);
      }
      else
      {
        digitlaWrite(1, LOW);
        digitalWrite(2, LOW);
        digitlaWrite(3, LOW);
        c2 = false;
      }
    }

This code contains a couple of guesses about states you did not mention, and a slightly different behavior (sorry), but I hope you get an idea...


message:
nodemcu GPIO6 clock

is there a way that i can declare gpio6 (CLK) as an input without getting a wdt reset?  I'm somewhat new to circuitry, but my boss wants to use it(GPIO6) to talk with external devices.  I have more pictures of the schematics if you think that it would help.[![enter image description here][1]][1]

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

body:
No. There is no way you can use it (or not without a lot of messing around...).

According to the [ESP8266 GPIO Reference Guide](https://randomnerdtutorials.com/esp8266-pinout-reference-gpios/):

> GPIO6 to GPIO11 are usually connected to the flash chip in ESP8266 boards. So, these pins are not recommended to use.

If you mess with those pins you won't be able to access the flash chip - and that means that you can't run code. And of course that means that the watchdog then times out.

I say that you can't "without a lot of messing around", because theoretically it *could* be possible if you had a function resident in RAM which reconfigured the pins, then did whatever was needed with them (taking into account the fact that there's a flash chip connected there...), then afterwards reconfigure the pins back to working in XIP SPI Flash mode.  But that's not something I would like to even contemplate doing.


body:
No you can't.
Refer to this: https://tttapa.github.io/ESP8266/Chap04 - Microcontroller.html

However as that article states there is a dedicated SPI set of pins on the esp8266 so you should be able to use that?

From your circuit diagram I see this might not be an option for you as you seem to have most of the pins allocated to a different function.

Your best and most robust solution would probably be to have a separate microcontroller chip handling your I2C and SPI requirements, using the Esp8266 UART functionally to provide your wireless capabilities.

As a side note why do you have so many clock lines?


message:
Reading Data from Google Sheets using Nodemcu

I want to read and writ data on Google sheets using ESP8266 WIfi Nodemcu and I'm able to do it but the time interval between two writing row is 3 seconds which is too much. I can read data but I am able to read only the first row not any other rows i am not able to read even changing the URL parameters.

Here is My Code -

<pre>
#include "ESP8266WiFi.h"
#include "HTTPSRedirect.h"
#include "DebugMacros.h"

// Fill ssid and password with your network credentials

const char* ssid = "Leobotics";

const char* password = "leobotics123";

int sheetHumid = 1;

int sheetTemp  = 2;

int sheetaqu   = 3;

String readaqu = "";

const char* host = "script.google.com";

// Replace with your own script id to make server side changes

const char *GScriptId = "AKfycbyu_JnX7F29Ea5cZUy7HdsFbv9W5UmedmNbhTwt5tznwRUiQhYS";

const int httpsPort = 443;

// echo | openssl s_client -connect script.google.com:443 |& openssl x509 -fingerprint -noout

const char* fingerprint = "ED:83:75:6B:83:FE:01:DE:BA:72:84:05:71:FA:CE:54:FB:6E:23:CA";

//const uint8_t fingerprint[20] = {};

// Write to Google Spreadsheet

String url = String("/macros/s/") + GScriptId + "/exec?value=Hello";

// Fetch Google Calendar events for 1 week ahead

String url2 = String("/macros/s/") + GScriptId + "/exec?cal";

// Read from Google Spreadsheet

String url3 = String("/macros/s/") + GScriptId + "/exec?read";

String payload_base =  "{\"command\": \"appendRow\", \
                    \"sheet_name\": \"Sheet1\", \
                    \"values\": ";
String payload = "";

HTTPSRedirect* client = nullptr;

// used to store the values of free stack and heap
// before the HTTPSRedirect object is instantiated
// so that they can be written to Google sheets
// upon instantiation

unsigned int free_heap_before = 10;

unsigned int free_stack_before = 20;

void setup() {

  Serial.begin(115200);

  Serial.print("Connecting to wifi: ");

  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {

    delay(500);

    Serial.print(".");

  }

  Serial.println("");

  Serial.println("WiFi connected");

//  Serial.println("IP address: ");
//  Serial.println(WiFi.localIP());

  // Use HTTPSRedirect class to create a new TLS connection

  client = new HTTPSRedirect(httpsPort);

  client->setInsecure();

  client->setPrintResponseBody(true);

  client->setContentTypeHeader("application/json");

  Serial.print("Connecting to ");

  Serial.println(host);

  // Try to connect for a maximum of 5 times
  bool flag = false;

  for (int i=0; i<5; i++){

    int retval = client->connect(host, httpsPort);

    if (retval == 1) {

       flag = true;

       break;
    }

    else

      Serial.println("Connection failed. Retrying...");
  }

  if (!flag){

    Serial.print("Could not connect to server: ");

    Serial.println(host);

    Serial.println("Exiting...");

    return;
  }

}

void loop() {

  datasend();

  static int error_count = 0;

  static int connect_count = 0;

  const unsigned int MAX_CONNECT = 20;

  static bool flag = false;

  if (!flag){

    client = new HTTPSRedirect(httpsPort);

    client->setInsecure();

    flag = true;

    client->setPrintResponseBody(true);

    client->setContentTypeHeader("application/json");

  }

  if (client != nullptr){

    if (!client->connected()){

      client->connect(host, httpsPort);

      payload = payload_base + "\"" + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

      client->POST(url2, host, payload, false);

    }
  }

  else{

    DPRINTLN("Error creating client object!");

    error_count = 5;

  }

  if (connect_count > MAX_CONNECT){

    connect_count = 0;

    flag = false;

    delete client;

    return;

  }

  Serial.println("GET Data from cell 'A1':");

  if (client->GET(url3, host)){

    ++connect_count;

    payload = payload_base + "\"" + readaqu + "," + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

    Serial.println("RECIEVED DATA IS GIVEN BELOW   ");

    Serial.println("                              ");

    Serial.println("1");

    Serial.println(readaqu);

    Serial.println("2");

    Serial.println(sheetaqu);

    Serial.println("3");

    Serial.println(sheetTemp);

    Serial.println("4");

    Serial.println(sheetHumid);

    Serial.println("                              ");
    Serial.println("RECEIVE DATA PRINT IS OVER  ");

    sheetaqu ++;

    sheetTemp ++;

    sheetHumid ++;

  }
  else{

    ++error_count;

    DPRINT("Error-count while connecting: ");

    DPRINTLN(error_count);

  }

  Serial.println("POST append memory data to spreadsheet:");

  payload = payload_base + "\"" + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

  if(client->POST(url2, host, payload)){

    ;
  }

  else{

    ++error_count;

    DPRINT("Error-count while connecting: ");

    DPRINTLN(error_count);

  }

  if (error_count > 3){

    Serial.println("Halting processor...");

    delete client;

    client = nullptr;

  }

  delay(4000);

}

void datasend()

{
   // Send memory data to Google Sheets

  payload = payload_base + "\"" + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

  client->POST(url2, host, payload, false);

  payload = payload_base + "\"" + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

  client->POST(url2, host, payload, false);

  // Note: setup() must finish within approx. 1s, or the the watchdog timer
  // will reset the chip. Hence don't put too many requests in setup()
  // ref: https://github.com/esp8266/Arduino/issues/34

  Serial.println("\nGET: Write into cell 'A1'");

  Serial.println("=========================");

  // fetch spreadsheet data

  client->GET(url, host);

  // Send memory data to Google Sheets

  payload = payload_base + "\"" + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

  client->POST(url2, host, payload, false);

  Serial.println("\nGET: Fetch Google Calendar Data:");

  Serial.println("================================");

  // fetch spreadsheet data

  client->GET(url2, host);

  // Send memory data to Google Sheets

  payload = payload_base + "\"" + sheetaqu + "," + sheetTemp + "," + sheetHumid + "\"}";

  client->POST(url2, host, payload, false);

  Serial.println("\nSeries of GET and POST requests");

  Serial.println("===============================");

  // delete HTTPSRedirect object

  delete client;

  client = nullptr;
}
</pre>

body:
I think you'll need to modify your Google Script for that Sheet so that whatever function you are invoking to GET row data takes in an additional parameter for the row value.

Then just add the Javascript logic within that function for retrieving the data at that passed-in row index to be returned.

Does that make sense?


message:
Attiny85 Watchdog fires only once

I build something like a flashlamp with different modi. From the hardware site it's quite simmilar to the Nanjg105c.
There is a Attiny85 which generates a PWM signal to an AMC7135.

I have one push button, if I click it the Attiny go to sleep, if I hold the button the Attiny changes his mode.
[![enter image description here][1]][1]
For checking the battery voltage I use the watchdog timer to make the ADC conversion every 8sec.

        #include "OneButton.h"
    #include <avr/sleep.h>               // Sleep Modes
    #include <avr/power.h>              // Power management
    #include <avr/wdt.h>              // Watchdog Timer
    #include <util/delay.h>

    #define mid 4000                // BAttery Level Mid
    #define low 3200                // Battery Level low, flash and start dimming the Led
    #define crit 2600               // Battery Level critical, shut down

    const byte LEDr = 1;              // pin 1
    const byte LEDw = 4;              // pin 4
    const byte ModeNr = 3;
    volatile bool WDR_flag = false;
    bool PWR_flag = false;

    OneButton button1(2, true);
    int count = 1;
    int flag = 0;
    long Vcc;
    int PWMr = 255;
    int PWMw_l = 50;
    int PWMw_h = 255;

    ISR(PCINT0_vect)
    {
        // do something interesting here
    }

    ISR(WDT_vect){
      WDR_flag=true;
     }

    void setup()
    {
        pinMode(3, OUTPUT);
        pinMode(LEDr, OUTPUT);            // turn the LED on (HIGH is the voltage level)
        pinMode(LEDw, OUTPUT);
        digitalWrite(LEDr, HIGH);           // turn the LED on (HIGH is the voltage level)
        digitalWrite(LEDw, HIGH);
        delay(1000);
        button1.attachClick(sleep);
        button1.attachLongPressStart(changeMode);
        WDT_on();
    }

    void loop()
    {
      uint8_t i = 0;
        button1.tick();               // keep watching the push buttons:
      if(WDR_flag == true){           // do every 8s
        WDR_flag = false;           //reset WDT Flag
        digitalWrite(3, HIGH);      //debug with third LED
        delay(250);
        digitalWrite(3, LOW);
        WDT_off();
        //ADC_on();
        /*Vcc = readVcc();            //read Battery voltage
        if(Vcc < low && count == 3){
          if(PWMw_h <= PWMw_l){       //change Mode to low when PWM output is smaler then low PWM
            count = 2;
          }else
        {
        i = 0;
            while (i++<3 && PWR_flag == false) {         //flash 3 times the red LED befor dimm the white LED
              analogWrite(LEDr, PWMr);
              _delay_ms(500);
              digitalWrite(LEDr, LOW);
              _delay_ms(250);
          PWR_flag = true;
            }
          PWMw_h = PWMw_h / 2;        //halve the PWM output of the white LED
          }
          if(Vcc <= crit){          //go to sleep when Battery is empty
            sleep();
          }
        }
        if(Vcc < low && count == 1){
          i = 0;
          while (i++<3) {
            digitalWrite(LEDr, LOW);
            _delay_ms(250);
            analogWrite(LEDr, PWMr);
            _delay_ms(500);
            }
          PWMr = PWMr / 2;
          if(Vcc <= crit){
            sleep();
          }
        }*/
        //ADC_off();                //save power
        WDT_on;                 //start watchdog again

      }
      switch (count) {
        case 1:                 //Mode red LED
        analogWrite(LEDr, PWMr);
        digitalWrite(LEDw, LOW);
        break;
      case 2:                   //low Mode white LED
        digitalWrite(LEDr, LOW);
        analogWrite(LEDw, PWMw_l);
        break;
      case 3:                   //high Mode white LED
        digitalWrite(LEDr, LOW);
        analogWrite(LEDw, PWMw_h);
        break;
      }
    }

    void sleep()                  // This function will be called when the button1 was pressed 1 time
    {
        digitalWrite(LEDr, LOW);
        digitalWrite(LEDw, LOW);
        //prepare sleep
        WDT_off();
        GIFR |= bit(PCIF);              // clear any outstanding interrupts
        GIMSK |= _BV(PCIE);             // Enable Pin Change Interrupts
        PCMSK |= _BV(PCINT2);             // Use PB2 as interrupt pin
        ADC_off();
        set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement

        sleep_enable();               // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
        sei();                    // Enable interrupts
        sleep_cpu();                // sleep

        cli();                    // Disable interrupts
        PCMSK &= ~_BV(PCINT2);            // Turn off PB2 as interrupt pin
        sleep_disable();              // Clear SE bit
        WDT_on();

        flag = 1;                 //set flag, uc was in sleepmode before
    }

    void changeMode()               // This function will be called once, during pressed for a long time.
    {
        if (flag == 1) {
            flag = 0;
        }
        else {
            if (count < ModeNr) {
                count++;
            }
            else {
                count = 1;
            }
        }
    }

    void WDT_on() {
      // Setup watchdog timer to only interrupt, not reset
      cli();                    // Disable interrupts
      wdt_reset();                // Reset the WDT
      WDTCR |= (1 << WDCE) | (1 << WDE);       // Start timed sequence
      WDTCR = (1 << WDIE) | (1 << WDP3) | (1<<WDP0);      // Watchdog cycle = 8 s
      //WDTCR = (1 << WDIE);             // Watchdog Interrupt enable
      sei();                    // Enable interrupts
    }

    void WDT_off(){
      cli();                    // Disable interrupts
      wdt_reset();                // Reset the WDT
      MCUSR &= ~(1<<WDRF);            // Clear Watchdog reset flag
      WDTCR |= (1<<WDCE) | (1<<WDE);        // Start timed sequence
      WDTCR = 0x00;               // Disable WDT
      sei();                    // Enable interrupts
    }

    void ADC_on() {
      ADCSRA = (1 << ADEN );            // ADC power on
    }

    void ADC_off() {
      ADCSRA &= ~(1<<7);              //ADC off
    }

    long readVcc() {
      // Read 1.1V reference against AVcc
      // set the reference to Vcc and the measurement to the internal 1.1V reference

      ADMUX = _BV(MUX3) | _BV(MUX2);
      delay(2);                  // Wait for Vref to settle
      ADCSRA |= _BV(ADSC);              // Start conversion
      while (bit_is_set(ADCSRA,ADSC));        // measuring

      uint8_t low_adc  = ADCL;              // must read ADCL first - it then locks ADCH
      uint8_t high_adc = ADCH;              // unlocks both

      long result = (high_adc<<8) | low_adc;

      result = 1126400L / result;           // Calculate Vcc (in mV); 1126400 = 1.1*1024*1000
      int x = 0;
      /*while (x++<2) {         //debug with third LED
              digitalWrite(3, HIGH);
              _delay_ms(500);
              digitalWrite(3, LOW);
              _delay_ms(250);
            } */
      return result;                // Vcc in millivolts
    }

my problem is that the watchdog fires only once. after putting the attiny to sleep the watchdog fires also only once.

I think the problem is in the WDT_off() function...

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

body:
The line below lacks parens `()` to make it a function call; as it stands, it's not actually calling `WDT_on`.

    WDT_on;                 //start watchdog again

should be:

    WDT_on();                 //start watchdog again


message:
NodeMCU max draw

1) what is the max draw I can draw from NodeMCU V3 logic and 5v pins?
2) Also, I heard i draw with it more than 500mA, the PC USB port stops working. Is that information actual? Because USB 3 port has 900mA and USB 2 had 500mA max

body:
for ESP8266 (which your NodeMCU is based upon) , the maximum current is about 20mA sinking and 12mA sourcing per [single] pin. so the maximum current of all GPIOs together is a lot lower than the 500mA USB limits.

you have to use external drivers (transistors, MOSFETs) for that purpose.

**Sink current**: the current which is provided when you pull the pin LOW. e.g. when you provide GND for the cathode of an LED. (the Anode is connected to VCC).

**Source current**: the current which is provided when you pull the pin HIGH. e.g. when you provide VCC for the anode of an LED. (the cathode is connected to GND).

*the difference is for different internal resistance for identical N-MOS/P-MOS, due to their structure. that's why many devices like 7segment drivers, or motor drivers supply GND for the Load (common anode drivers) instead of VCC.*


message:
Arduino stops working when servo makes a few rotations

The sketch rotates servo back and forth with buttons.
When I rotate servo MG 995/996R 2-4 times Arduino stops working. Its voltage step-down transformer switches from ~9V to ~3.7V which is not enough for Arduino. To make it work again, I must turn off-on the device.

There is no such a glitch with smaller servos such as SG90.

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

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

body:
[Ground loops][1] can be bad.  Do follow up as suggested in the comments regarding ensuring the power supply grounds are the same. To be specific, connecting the power supply grounds through the Arduino is a bad idea! The trace size should not be assumed adequate for the unknown amount of current passing between the ground outputs of the power supplies.  And a voltage potential can develop causing the processor to behave unexpectedly or worse burn out components.

Also, consider that some Arduino platforms regulate power to 5 volts on the board and that many servos run fine at 5 volts. If this is true here, you could greatly simplify and possibly solve the describe problem by using a single 5 volt power supply.

Lastly, ensure there is a pull up on the 2 inputs connected to the (assumed) normally-open-momentary-contact switches.  There are none in the diagram.  So it is assumed pull ups have been activated in the code such as explained [here][2].

  [1]: https://en.wikipedia.org/wiki/Ground_loop_(electricity)
  [2]: https://www.arduino.cc/en/Tutorial/InputPullupSerial


message:
how can I program my sound sensor and pir motion sensor in 1 arduino uno

int pirPin=2;
    int buzzerPin=12;
    int soundSensor = 19;
    int LED = 3;
    int statusSensor=0;
    int pirVal=0;
    void setup()
    {
    Serial.begin(9600);
    pinMode(pirPin, INPUT);
    pinMode(soundSensor, INPUT);
    pinMode(buzzerPin, OUTPUT);
    pinMode(LED, OUTPUT);
    }
    void loop()
    {
    pirVal=digitalRead(pirPin);
    if(pirVal==HIGH)
    {
    Serial.println("Motion Detected");
    digitalWrite(buzzerPin,HIGH);
    delay(150);
    digitalWrite(buzzerPin, LOW);
    }
    else
    {
    digitalWrite(buzzerPin, LOW);
     }
    statusSensor = analogRead(soundSensor);

      if (statusSensor == 1)
      {
    Serial.println("Sound Detected");
    digitalWrite(LED, HIGH);
    delay(100);
    digitalWrite(LED, LOW);
    }
      else
      {
        digitalWrite(LED, LOW);
      }
    }

body:
First of all there is no pin with pin number 19 (as you defined a soundSensor on it), and there is no problem you can use my sound sensor and pir motion sensor in 1 arduino uno.

But in order to do that please use **millis** instead of **delay** so that your arduino doesn't wait to read reading of other sensor during the reading of first sensor.

Here is a link which shows how to use arduino for multitasking..

[https://learn.adafruit.com/multi-tasking-the-arduino-part-1/overview][1]

  [1]: https://learn.adafruit.com/multi-tasking-the-arduino-part-1/overview


message:
Did I kill my ESP8266?

So I've been playing with the esp8266 controller lately and today my Usb Host Mini came in that I wanted to connect. So for this I followed the following tutorial https://www.hackster.io/139994/plug-any-usb-device-on-an-esp8266-e0ca8a

The only thing is that I didn't do the following, because I wanted to see that it actually wouldn't work without damaging the Usb Host Mini.

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

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

Now I am wondering, because I didn't do that, and just went on with the wiring, did I actually kill my ESP8266 now? Whenever I remove all the wires, and just connect the ESP8266 to my computer, it just won't show up in the ports.

If I did kill it, what did I actually do here? Did I allow 5V to run through the board and did I fry it that way? If I would've actually made the cut shown above, would it have lived? (Because I think what the cut does, is it stops the 5V from going through the circuit.)

body:
Well if it doesn't work then it doesn't work so a safe bet is that chip is damaged.

I found [this document][1]. It states:

> **VBUS pad and jumber** can be used to provide 5V to VBUS. By default VBUS is connected to 3.3V; certain USB devices may have issue with
> this.

So I deduce that this is connected directly to 3.3V rail of the chip. Providing 5V without opening the jumper (cutting the trace) is the same as putting 5V at the 3.3V pin.

> **3.3V.** Power pin of the shield. Do not supply 5V to this pin - MAX3421E won't be able to detect devices on VBUS and may also be
> damaged!

Apparently the "proper" way of doing things is to actually unsolder that jumper or cut the trace.

Sorry.

  [1]: http://tet.pub.ro/pages/altele/Docs/Shield USB Host/USB Host Shield Hardware Manual « Circuits@Home.pdf


message:
Arduino accepting only alternate characters

I am writing an Arduino code to receive SMS from a SIM800 module and then send the same message back to the sender. My code is as follows:

    #include<SoftwareSerial.h>

    SoftwareSerial mySerial(9, 10);//Connect to pin 9&10 on GSM module

    const byte numChars = 128; //character size
    char receivedChars[numChars]; // Store data read from SMS
    boolean newData = false; //flag to check if new data has arrived

    void setup() {
     Serial.begin(9600);
     mySerial.begin(9600);
     Serial.println("<Arduino is ready>");
     mySerial.println("AT");
     mySerial.println("AT+CMGF=1"); //text mode
     mySerial.println("AT+CNMI=1,2,0,0,0");
     mySerial.println("AT+CSQ"); //Check signal strength
       while (Serial.available())
      {
        mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
      }
      while(mySerial.available())
      {
        Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
      }
    }

    void loop() {
      //code for checking sms
      scanSMS();
      //Print if a new data arrived
      showNewData();
      delay(25000);
    }

    void scanSMS() {
        static boolean recvInProgress = false;
        static byte ndx = 0;
        char startMarker = '#'; //Start and end markers. Eg. SMS body will be sent as #status#
        char endMarker = '#';
        char rc;
        while (Serial.available())
        {
          mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
        }

        while (mySerial.available() > 0 && newData == false) {
          Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port

          rc = mySerial.read();

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

    /*PRINT IF THERE IS A NEW DATA*/
    void showNewData() {
     if (newData == true) {
       SendMessage(receivedChars);
     newData = false;
     }
    }

    /*SEND BACK WHATEVER SMS IS RECEIVED*/
    void SendMessage(String receivedChars)
    {
      Serial.print("here");
      mySerial.println("AT+CMGS=\"+xxxxxxxxxx\"\r"); // Replace x with mobile number
      mySerial.println("Humidity Alert!");// The SMS text you want to send
      mySerial.print(receivedChars);
       mySerial.println((char)26);// ASCII code of CTRL+Z
    }

The issue is that the module seems to receive only alternate characters instead of the whole message. For example, if I send the text #program#, the Arduino will only print porm or rga. Am I missing something here? Any help is highly appreciated.

body:
You wrote:

```c++
Serial.write(mySerial.read());
rc = mySerial.read();
```

Here you are calling `mySerial.read()` twice, and thus reading two
characters from the port's input buffer. You then forward the first
character through `Serial`, and process the second one. Note that you
should normally not read two characters unless you have tested that
`mySerial.available() >= 2`.

You probably want to forward and process one character at a time, thus
only call `mySerial.read()` once within this loop:

```c++
rc = mySerial.read();  // read from mySerial
Serial.write(rc);      // forward through Serial
// now process rc
```


message:
Multi dimming led - figuring out which led is available for dimming

TL;DR: I tried to have a random fading pattern on several leds and it leads to flickering.

Edited following @chrisl answer.

I am in the process of creating a simple lamp that show some light patterns using 6 led and an arduino uno. The goal is that depending on some inputs and a bit of randomisation, the patterns will change. For instance, only 2 lights at the same time but fading up and down randomly on all 6 led. Or 4 lights fading up and down randomly on the 6 leds.

I decided to create a struct that would be a light pattern named a particle, and this particle have a variable named led_position that shows which led it is on at a certain moment. The particle can change its position to light up an other led.

I know this is not the clearest of explanation but I hope my code will be more straightforward:

Main code
        #include "MyTypes.h"

    int led1 = 9;    // the PWM pin the LED is attached to
    int led2 = 10;
    int led3 = 11;
    int led4 = 6;
    int led5 = 3;
    int led6 = 5;

    //int led;
    int brightness;
    int fadeAmount;

    // Definition of the different particles
    particle_type particle[]={
      { 0,led1,0, 2,   false },
      { 1,led2,50, 2,   false },
      { 2,led3,100,  2,   false },
      { 3,led4,80,  2,   false },
      { 4,led5,30,  2,   false},
      { 5, led6,70,  2,   false},
    };

    led_type led[]={
      { 3,false },
      { 5,false },
      { 6,false },
      { 9,false },
      { 10,false },
      { 11,false },
    };

    //initiation of the particles

    void initiate_particle(particle_type& particle_example,led_type led[]){

     //take a random led from list of led
      int number=random(5);
      led[number];
      if (led[number].busy == false){ //if led non-occupied
        particle_example.led_position=led[number].led_position;
        led[number].busy = true ;//take this led as output
        }

      else{
    //    particle_example.led_position=particle_example.led_position; //keep same led
      }

      particle_example.reset = false; //reset turned off
     // delay(30);

    }

    void update_light(particle_type& particle_example,led_type led[]){ //updating led brightness

      analogWrite(particle_example.led_position, particle_example.brightness);  //updating led brightness
      if (particle_example.brightness >=  160) {
        particle_example.fadeAmount = -particle_example.fadeAmount;

      }

      if (particle_example.brightness <=  160 && particle_example.brightness >=  100 ) {
        particle_example.brightness = particle_example.brightness + 2*particle_example.fadeAmount;

      }

      if (particle_example.brightness >= 50 && particle_example.brightness <=  100){
          particle_example.brightness = particle_example.brightness + particle_example.fadeAmount;

      }

      if (particle_example.brightness >= 0 && particle_example.brightness <=  50){
          particle_example.brightness = particle_example.brightness + 0.5*particle_example.fadeAmount;

      }

      if (particle_example.brightness <= 0){
        particle_example.reset= true;
        int number = particle_example.led_position;
        led[number].busy=false;
        particle_example.fadeAmount = -particle_example.fadeAmount;
      }

    }

    void activate_particle(particle_type& particle_example,led_type led[]){ //function to keep led activated

      if (particle_example.reset==true){ //if led not initiated or has finished its dimming down
        initiate_particle(particle_example, led); //initiate it again
      ;}

      else {
       update_light(particle_example,led); //update its brightness
      }
    }

    void setup() { //create led outputs

      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);
      pinMode(led4, OUTPUT);
      pinMode(led5, OUTPUT);
      pinMode(led6, OUTPUT);
      Serial.begin(9600); //serial for debug

    }

    void loop() {

      activate_particle(particle[0],led);
    //  activate_particle(particle[1],led);

    //  activate_particle(particle[2],led);
    //  activate_particle(particle[3],led);
    //  activate_particle(particle[4],led);
    //  activate_particle(particle[5],led);
    //

     delay(5); // 20-17-15-12-10-7-2

    }

Mytypes.h

    typedef struct {
        int id;
        int led_position;
        int brightness;
        int fadeAmount;
        bool reset;
    } particle_type;

    typedef struct {
        int led_position;
        bool busy;
    } led_type;

This seems to work more or less but I still have the problem of particles "choosing" the same led to light up and it make the led flickers.

I am struggling on this. I have tried to add a data field for busy and create a new struct for led to no avail.

Even when only one particle is on, the different leds seems to deactivate after a few rounds.

Let me know if you figure it out, thanks!

EDIT 2:

        #include "MyTypes.h"

    int led0 = 3;    // the PWM pin the LED is attached to
    int led1 = 5;
    int led2 = 6;
    int led3 = 9;
    int led4 = 10;
    int led5 = 11;

    //int led;
    int brightness;
    int fadeAmount;

    // Definition of the different particles
    particle_type particle[]={
      { 0,led0,0, 4,   false },
      { 1,led1,50, 4,   false },
      { 2,led2,100,  4,   false },
      { 3,led3,80,  4,   false },
      { 4,led4,30, 4,   false},
      { 5,led5,70,  4,   false},
    };

    led_type led[]={
      { 3,false },
      { 5,false },
      { 6,false },
      { 9,false },
      { 10,false },
      { 11,false },
    };

    //initiation of the particles

    void initiate_particle(particle_type& particle_example,led_type led[]){

     //take a random led from list of led
      int number=random(6);
      Serial.println(number);
      led[number];
      if (led[number].busy == false){ //if led non-occupied
        for (int i=0;i<6;i++){
          if (led[i].led_position==particle_example.led_position){
          led[i].busy=false;
          Serial.println("success");
          Serial.println(led[i].led_position);
          }
        }
        particle_example.led_position=led[number].led_position;
        Serial.println(particle_example.led_position);
        led[number].busy = true ;//take this led as output
        particle_example.reset = false; //reset turned off
        }

      else{
    //  initiate_particle( particle_example,led);
    }

      delay(30);

    }

    void update_light(particle_type& particle_example,led_type led[]){ //updating led brightness
          analogWrite(particle_example.led_position, particle_example.brightness);  //updating led brightness

      if (particle_example.brightness >=  160) {
        particle_example.fadeAmount = -particle_example.fadeAmount;
        particle_example.brightness = particle_example.brightness + 2*particle_example.fadeAmount;
      }

      else if (particle_example.brightness <  160 && particle_example.brightness >=  100 ) {
        particle_example.brightness = particle_example.brightness + 1.5*particle_example.fadeAmount;

      }

      else if (particle_example.brightness > 50 && particle_example.brightness <=  100){
          particle_example.brightness = particle_example.brightness + particle_example.fadeAmount;

      }

      else if (particle_example.brightness > 0 && particle_example.brightness <=  50){
          particle_example.brightness = particle_example.brightness + 0.25*particle_example.fadeAmount;

      }

      else if (particle_example.brightness <= 0){
        particle_example.reset= true;
        particle_example.brightness =0;
        int number = particle_example.led_position;

        if (particle_example.fadeAmount<0){
          particle_example.brightness = 0;
          particle_example.fadeAmount = -particle_example.fadeAmount;
        }
        else{
          particle_example.brightness = particle_example.brightness + 0.5*particle_example.fadeAmount;
        }

      }

    }

    void activate_particle(particle_type& particle_example,led_type led[]){ //function to keep led activated

      if (particle_example.reset==true){ //if led not initiated or has finished its dimming down
        initiate_particle(particle_example, led); //initiate it again
      ;}

      else {
       update_light(particle_example,led); //update its brightness
      }
    }

    void setup() { //create led outputs
      pinMode(led0, OUTPUT);
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);
      pinMode(led4, OUTPUT);
      pinMode(led5, OUTPUT);

      Serial.begin(9600); //serial for debug

    }

    void loop() {

      activate_particle(particle[0],led);
      activate_particle(particle[1],led);
      activate_particle(particle[2],led);
    //  activate_particle(particle[3],led);
    //  activate_particle(particle[4],led);
    //  activate_particle(particle[5],led);
    //

     delay(10); // 20-17-15-12-10-7-2

    }

    void loop() {

      activate_particle(particle[0],led);
      activate_particle(particle[1],led);
      activate_particle(particle[2],led);
      activate_particle(particle[3],led);
    //  activate_particle(particle[4],led);
    //  activate_particle(particle[5],led);
    //

     delay(10); // 20-17-15-12-10-7-2

    }

Now the code works well up to 3 particles but messes things up for 4,5,6 particles with flickering and absence of light.

body:
That seems like a logic problem for me. You define a "particle", which is not bound to a special LED (like a particle, that is jumping from one position to another). Then you included a busy flag, that should prevent, that a LED is used by more than one particle at a time. But you included this flag in the particle. Being busy is a state of the LED, not of the particle, so including this in the particle won't do, what you want.

If you want to use this logic, you need to create a struct, which represents the individual LED. The struct's fields would be the pin number and the busy flag. You can create the LED list with instances of this struct. Then to choose a new position for the particle, you need to check if the busy flag of that position is set. If not, choose this position and set the busy flag. Clear the flag, when you remove the particle from the position.

---

After your edit I see more problems. First a general problem: Currently a new particle, that want's to change it's position, needs a free (not busy) position to move to. You have 6 LED positions, so with 6 particles, there won't be any move. You can change this by freeing a LED position (setting it's busy flag to false), when the fading of a particle is finished. Still there might be timing problems with this way, depending on the overall timing behavior of the sketch (The first particle to free a LED position will not find a different free position and has to wait. This might lead to 2 particles just exchanging there positions).

Then in `void update_light()` you have multiple if statements, which all test the particles brightness. But inside these statements you change the brightness. So it is possible, that multiple of the if statements will execute. You should use `if else if` instead, so that only one of the statements can execute.

And in `void initiate_particle()` you check for the chosen LED position to be busy. But if the position is already busy, you are setting the particles `reset` flag to false anyway. That means that `activate_particles()` will update the particles brightness despite the fact, that the particles does not have a valid LED position currently. You should not set `reset` to false, if the particles hasn't got a valid LED position. And the delay at the end of the initiate function does not serve a function in my eyes.


message:
Which sensors to choose to detect movement direction

So I'm planning to build a sort of light switch for my Philips Hue bulbs with an Arduino. This project will be mounted on a shelf next to my door to the room, parallel to the walking direction. In order to detect the movement direction to either turn on or off the lights when a person is entering or leaving the room, I need one or two sensors. I've tried HC sr04 before but got inaccurate results which resulted in random changes of the lightstate.

So what sensors will be best for my application? I was thinking about the Sharp IR sensors (i.e. Sharp GP2Y0A60SZLF) but I'm not sure about any possible interference that comes with it when I mount to of these right next to each other. Any ideas?

Thanks in advance!

body:
1. I guess you want to use 2 IR sensors with a little distance, so that you can check the direction by checking, which one detected an object first. You surely can do this with the mentioned sensor. To avoid interference, you can measure by one one, deactivating the other over it's enable pin during that time. It should be fast enough, so that you can do this sufficiently.

2. I would say using a distance sensor is overkill here. For checking, if someone comes in or out, you don't need distance information. Just 2 light barriers would be sufficient. For example a little laser pointer (could also be IR), a little mirror at the other side and a fitting photodiode. I think there are ready made modules to buy. Their output would only be digital, not analog.


body:
The PIR sensors can work in your case. They are passive and detect only moving objects that emit IR radiation. So anything that's hotter than background like people, cats, dogs but not doors.

The raw sensor looks like this:

[![PIR sensor][1]][1]

But it's usually available as a part of an IC that includes a plastic lens that focuses IR rays from broader area on the sensor.

[![PIR IC][2]][2]

Remove that lens (or not) and add something made of cardboard to limit the area that sensor sees and you have a directional sensor that detects moving hot things.

Technically you can completely hack the raw sensor and get info if the hot object is moving left or right. Read [this article][3] and look at the sensor response graph.

  [1]: https://i.stack.imgur.com/4jTjV.png
  [2]: https://i.stack.imgur.com/wArQ9.png
  [3]: https://learn.adafruit.com/pir-passive-infrared-proximity-motion-sensor/how-pirs-work
  [4]: https://www.youtube.com/watch?v=x8vmd3DkzDg


message:
multiple graphs on serial plotter

I'm trying to  run an Arduino code that simultaneously:
1) blinks an led on-off every 3 seconds
2) gets a voltage input from an EMG sensor and positions a servo motor accordingly

While I run this program, I'd like to plot the following on the same graph
1) LED status on/off printed as 600 if on and 0 if off
2) EMG value being fed to the arduino
3) The angle the Arduino is sending to the servo motor

I wrote the following code which works to an extent but the problem I'm facing is, I only get two graphs on the plotter instead of 3, I think the EMG value and the angle have combined into a single line as seen in this picture:

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

However, if I remove the angle print statement, I get a proper graph for the other 2 as this:

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

How do I change my code so I can plot all three separately?
Thanks in advance.

```c++
#include <Servo.h>
Servo myservo;
const int ledPin =  LED_BUILTIN;
int ledState = LOW;
unsigned long previousMillis = 0;
const long interval = 3000;
int led=0;
int servovalue=0;
void setup() {
  Serial.begin(9600);
  myservo.attach(9);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  int sensorValue = analogRead(A0);
int angle = map(sensorValue, 0, 1023, 0, 180);
myservo.write(angle);
Serial.print(sensorValue);
Serial.print(“ ”)
Serial.println(angle);
delay(15);
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    if (ledState == LOW) {
      ledState = HIGH;
      led = 600;
    } else {
      ledState = LOW;
      led = 0;
    }
    digitalWrite(ledPin, ledState);
  }
  Serial.print(" ");
    Serial.println(led);
}
```

  [1]: https://i.stack.imgur.com/lYAp0.png
  [2]: https://i.stack.imgur.com/94JRa.png

body:
The part of your code that prints data to the serial looks like this:

```c++
void loop() {
    (...)
    Serial.print(sensorValue);
    Serial.print(“ ”)
    Serial.println(angle);
    (...)
    Serial.print(" ");
    Serial.println(led);
}
```
The bug is in the `Serial.println(angle);` line. The `println` method inserts a "newline" character at the end. Try changing it to `Serial.print(angle);` so there is only one "newline" character.

```c++
void loop() {
    (...)
    Serial.print(sensorValue);
    Serial.print(“ ”)
    Serial.print(angle);
    (...)
    Serial.print(" ");
    Serial.println(led);
}
```


message:
Need to know what USB cable to get for Arduino Nano-33-BLE-Sense

I have recently purchased an Arduino Nano-33-BLE-Sense with Headers and wrongly assumed that it would come with a USB cable with it. I was searching the online store for the cable but the only cable on the store that I see is for Type A to Type B which in its description does not mention my board.

Does anyone have any experience with this board and know which cable I need? Thanks in advance!

body:
Looks like this board

[![Nano-33-BLE-Sense][1]][1]

Is connected to the PC with connector commonly named simply "Micro USB". [Wikipedia][2] calls it "USB 2.0 Micro-B"
It's the same cable that all mobile phones used (before USB-C standard arrived). Check your phone charger.

[![cable][3]][3]

  [1]: https://i.stack.imgur.com/SjqvO.jpg
  [2]: https://en.wikipedia.org/wiki/USB_hardware
  [3]: https://i.stack.imgur.com/ZQohd.jpg


message:
Library compilation error

Need help for this [Tutorial][1]. I tried to compile the code, but I'm getting compiling error.

I tried to ask on that forum too but got no answer, the error is:

    In file included from C:\Program Files (x86)\Arduino\libraries\SD\src/utility/SdFat.h:32:0,
    Multiple libraries were found for "SD.h"from C:\Program Files (x86)\Arduino\libraries\SD\src/SD.h:20,
     Used: C:\Program from D:\FEMV3FKI7YLJVQQ\FEMV3FKI7YLJVQQ.ino:1:
     Not used: C:\Users\IBNUM
    C:\Program Files (x86)\Arduino\libraries\SD\src/utility/BlockDriver.h:31:10: fatal error: FatLib/BaseBlockDriver.h: No such file or directory
    Multiple libraries were found for "SPI.h"
     #include "FatLib/BaseBlockDriver.h"
     Used: C:\Program
              ^~~~~~~~~~~~~~~~~~~~~~~~~~
    compilation terminated.
    exit status 1
    Error compiling for board Arduino/Genuino Mega or Mega 2560.

  [1]: https://www.instructables.com/id/Arduino-Ethernet-Camera/

How can I fix this Arduino compile error?

body:
I have the same problem since version 1.8.10.

With a good running sketch I don't get any message "Multiple libraries were found" (and no warnings also)

But with every small compiler error I get a whole list of "Multiple libraries were found"

My custom libraries are in a sketchbook location
D:\DATA BACKUPPED\Documenten Albert\Arduino\Sketchbook-and-user-libraries


message:
What sensors to measure grass growth?

I would like to make a small project, which would allow me to recognize if the grass has grow enough to lawn. I don't know too much the ecosystem of available sensors for such problem. And I have a lot of grass and some irregular areas to clean once in a while.

Is that something I can do with an arduino and some sensors, or should I need to use more processing power and cameras/AI?

TIA!

body: My idea: Two light sensors on a short stick embedded in the ground. If the top sensor detects light, but the bottom one does not it means that it's daytime, and grass is long enough that it covered the bottom sensor. You will probably need several of those, because there is no guarantee that grass will actually cover the bottom sensor, and you will need to filter out random elements by testing if values don't change to much.


message:
Variable updated in ISR is miscounting

I'm using a timer to fire a interrupt in configurable time periods.
In that ISR, a pin is toggled, and a `uint32_t` variable is incremented.

In the main program, a `while` loop waits until that variable has reached a certain threshold - to then disable the timer via its clock source selection.

    while(stepcounter <= threshold) {
    }
    disablecounter();

Sometimes - depending on optimization level, whether I put a small delay in the while loop, etc., this check seems to fail - advancing to `disablecounter()` even though `stepcounter` has not reached `threshold`.

If I stack the `while` loop like this:

    while(stepcounter <= threshold) {
    }
    while(stepcounter <= threshold) {
    }
    disablecounter();

it runs just fine. This also works:

    while(stepcounter <= threshold) {
      while(stepcounter <= threshold) {
      }
    }
    disablecounter();

I'm assuming there's some odd behaviour when comparing rapidly changing 32-bit numbers against a threshold.
This issue also occurs when using a `uint16_t` for `stepcounter`, but after a higher number of cycles.

For analysis, I'm simply running this loop over and over again; setting `stepcounter` back to `0` and restarting the timer. With `uint32_t`, it usually fails after the 5th or so loop. For `uint16_t`, it fails after around 25 loops.

Using a `tempstepcounter` like this also seems to work, but only when comparing against both counters at the same time:

    while(tempstepcounter <= threshold || stepcounter <= threshold) {
      tempstepcounter = stepcounter;
    }
    disablecounter();

Any ideas on this? It this because 32-bit numbers take longer to read from the registers than the time from ISR to ISR?
ISR frequency should be around 32 kHz during this.

ISR code:

    ISR(TIMER1_COMPA_vect) {
      PORTF ^= (1 << PORTF0));
      stepcounter++;
    }

body:
You need to declare it volatile in both places *and* shut off interrupts while reading it. The mainline  has to read it byte-by-byte, and an interrupt could otherwise occur between any two byte-reads, rendering the result of the 4-byte read as garbage.

'volatile' informs the compiler that the variable might not contain what it did last time (which the compiler might otherwise expect if the code being compiled doesn't change it. Turning off the interrupts protects the variable being changed while it's being read.

An even better way to protect the reads than turning off interrupts, is for the ISR to update the counter, then set a single-byte flag to indicate that there's a new count. The mainline would monitor that flag and read the counter only when the flag gets set, then clear the flag. This can work as long as the mainline checks the flag frequently enough that it will never not notice the flag until just before the next update by the ISR. But if you can keep to that constraint, this is a better idea than turning off interrupts.

If too many sub-tasks resort to turning off interrupts, it can have a negative effect on response time or even cause missed interrupts in some cases. This is less likely to be a problem for the relatively simple programs most of us write and run, most of the time. But when you get to tracking and controlling more complex processes and make heavier use of the interrupt system, bad habits have a way of coming back to bite you.


message:
Follow black and white line simultaneously

I have a line following bot which uses IR sensors (LSA08, more specifically) to detect the white line on black surface and stay on track. For the project however, there is a trick in the track. At a certain point, the line changes from white to black and the bot is expected to follow the black line on the white surface.

My question is, how would I design the algorithm which will make the bot recognise that the track and conditions have changed.

body: It depends a bit on your precise requirements. Currently you are following the black line (meaning sensing black in the middle and white on the sides). Instead you could follow the border of that line. To do this you would have to control the motors in a way, so that in at the middle of the sensors there is a high contrast (black at the right, white at the left, or vice versa). It will not follow the exact same path as before, but a bit to the side.


body:
Assume the "road" line is narrower than the bot's width. Sense light/dark across the road-width by enough more that it can see both edges plus enough to regain the roadway at a sharp bend.

Now pretend we don't know what color the roadway is - which is in fact, true! But we do know that the sensors should see either:
[W, W, W, ... W, B, B, ..., B, W, ..., W] (black stripe), or
[B, B, B, ... B, W, W, ..., W, B, ..., B] (white stripe).

Call W(hite) a 1 and B(lack) a zero. The above conditions, stored in an unsigned int, might look (in binary) like:

1111110000111111, or
0000001111000000.

One is just an inversion of the other, right? So read your sensors (and I'm going to assume perfect robo-vision for a moment: no noisy signals and we know we're on the roadway), and if necessary, *invert the result* so it look like my second case, 0000001111000000, a group of ones surrounded by a group of zeros shows we're (somewhat) centered on the track. *You no longer need to know what color the roadway is!*

We assumed perfect signals - in reality you'll need some smarts to detect and correct an odd 1 in the midst of a bunch (technical term here) of 0s, or vice versa.

We assumed your bot is kind of centered on the track; able to see both roadway edges. In reality, sometimes you may be losing it - 111000000000000, or drifting to the right. If you can't ensure this won't happen, you'll need to be able to recognize it and correct it. And, here is where we need to know something about the roadway color. We knew what color it was recently, just before we started to drift off, so we'll just continue inverting (or not inverting) our stored sensor data - IF the color doesn't change until the bot re-centers itself (nasty track designers)! If your design criteria can include that the bot doesn't lose either edge of the track, you can always recover, even during a color change. Otherwise you'll have to recognize and respond to a color change even when you can only see one edge. Use the recent road-color to keep track of this.

Hope that helps.


message:
How to use external libraries in CLion

I would like to use the external libraries that are downloaded by Arduino IDE into the default sketchbook location (*~/Arduino/libraries/*).

If you open Library Manager in Arduino IDE and if you install an external library (e.g **DHT sensor library 1.3.7** and its dependency **Adafruit Unified Sensor 1.0.3**) then it will be downloaded to the sketchbook location and you can use them freely in case of writing code in Arduino IDE.

However I really like auto code completion, managing source code in GIT repository, formatting source lines, etc. which functionalities are not provided by Arduino IDE, so I changed to CLion.

I have installed **CLion** and **Arduino Support 1.4.4 Plugin** and created a new Arduino Sketch Project.

Project Structure:
-
```
.
+--cmake
   +--Platform
      +--Arduino.cmake
   +--ArduinoToolchain.cmake
+--libs
   +--Adafruit_Sensor
      +--Adafruit_Sensor.h
      +--library.properties
      +--README.md
   +--DHT
      +--DHT.cpp
      +--DHT.h
      +--DHT_U.cpp
      +--DHT_U.h
      +--keywords.txt
      +--library.properties
      +--README.md
+--CMakeLists.txt
+--first_test_project.ino
+--User_Setup.h
```
first_test_project.ino:
-
```lang-c
#include <Arduino.h>
#include "User_Setup.h"
#include <libs/Adafruit_Sensor/Adafruit_Sensor.h>
#include <libs/DHT/DHT.h>

DHT *dht;

void setup() {
    dht = new DHT(7, DHT22);
}

void loop() {

}
```

So I have copied over the downloaded libraries from *~/Arduino/libraries* folder to the project folder under *libs* folder.

When I try to upload the code to Arduino Board I am getting the following in the log:
```
undefined reference to `DHT::DHT(unsigned char, unsigned char, unsigned char)'
```

Could somebody please explain what is wrong here.

Thank you very much!

body:
Did you add your libraries to the cmake files?

I don't have any experience with CLion but `undefined reference` normally means that
the linker couldn't find the function/class your are using.

So make sure the libraries are compiled and the linker knows where to find the object files.


body:
In my opinion, the easiest way for the beginner is to use Platformio, it sets up CLion project automatically.

See [docs][1] for more info.

  [1]: https://docs.platformio.org/en/latest/ide/clion.html


message:
I2C Wire.onRequest not detected

I want to know why `Wire.onRequest` can not detect below massage and what I can do to detect it.(I am not able to change I2C massage)

I was able to read this part of the massage with `wire.onReceive`:

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

But I can not read this massage at all, which is requesting:
[![enter image description here][2]][2]

    #include <Wire.h>
    byte val = 170;
    int sendv;

    char c;

    byte dataArray[16];

    void setup() {
      Wire.begin(0x77);                // join i2c bus with address #8
      Wire.onReceive(receiveEvent); // register event
      Wire.onRequest(requestEvent); // register event
      Serial.begin(9600);           // start serial for output
    }

    void loop() { }

    void receiveEvent(int howMany) {
      Serial.println(howMany);

      if (howMany >= 2) {
        for (int i = 0 ; i < howMany; i++) {
          dataArray[i] =  Wire.read();
          Serial.println(dataArray[i], HEX);
        }

      } else {
        c =  Wire.read();
        Serial.println(c, HEX);
      }
    }

    void requestEvent() {
      Serial.println("REqEVENT");
    }

  [1]: https://i.stack.imgur.com/MCtZ4.png
  [2]: https://i.stack.imgur.com/PJ9v5.png

body:
I was able to solve the issue with by adding  twi_stop(); to twi.c

base on this website
[enter link description here][1]

  [1]: https://github.com/helenarobotics/Arduino/commit/8aff39a229362e0167e5f48f6c15d02b39b0fbca


message:
HM-10 doesn't responde after RENEW

Today I finally got two HM-10 modules. I did flash firmware using [this][1] tutorial. It worked until I didn't send `AT+RENEW` command. Now, LED blinks, I see device in BT terminal(Android phone) but I can't connect to it. Terminal says `Connection failed: write descriptor failed`. I tried sending commands over COM port from PC, but it doesn't responde.
Also I connected pin 11 to GND, problem is still here. Strange thing - After firmware flash, `AT+HELP` doesn't exist, while `AT+HELP?` returns some website.

For second module, LED doesn't blink but I see module in BT terminal. It also stopped working after `AT+RENEW`. When I try to connect, I get same error.

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

body: change your COM serial baud rate to 115200. I had the same problem and the moment I change the baud rate on my Serial Com or Serial monitor. it works for me