text:
RTC DS3231 Not resetting time on power loss
I'm completely removing power from a DS3231 RTC module and my call to rtc.lostPower() is never hit when I reconnect everything. I'm also removing the battery, I left it overnight and it remembers the time just before I disconnected everything, but doesn't register a power loss. I'm using this with a D1 mini.
void setup() {
  // put your setup code here, to run once:
  Serial.begin(baud);

  if (!rtc.begin()) {
    Serial.println("Couldn't find RTC.");
    while (1); // while true
  }

  if (rtc.lostPower()) {
    Serial.println("RTC lost power, resetting time.");
    ConnectWiFi();
    GetNtpTime();
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    Serial.println("Time set after power loss");
  }
}

please add a link to the module datasheet and to the DS3231 datasheet

@jsotola: Here is the datasheet of the DS3231. The lostPower() method returns the “Oscillator Stop Flag” from the status register (c.f. datasheet, p. 14).


text:
Multiple serial monitors with the same arduino mega
I’ve got mega 2560.
In my project serial port is used for communicating with PC.
However, I’d like to see debug info in serial monitor. Mega has a few hardware Serial ports. How to use one of them got extra serial monitor?

Use an USB to TTL Serial adapter. Wire it to one of the RX/TX pin pairs and in code use the corresponding Serial object Serial1, Serial2 or Serial3. Don't forget to wire Ground.
You can use some terminal program or Serial Monitor in Arduino IDE to communicate over the adapter. You can open a second instance of the Arduino IDE by starting it with the Desktop or menu shortcut. In this instance you can select a different port then the sketch upload port.

https://arduino.stackexchange.com/questions/57653/can-i-have-two-separated-serial-monitor-for-the-same-arduino-board-connected-to/57669

You need to connect one (or more) to your PC. To do that you would use a USB to TTL UART adaptor, like an FT232 board.
That will give you a new COM port that you can open with your terminal program of choice, though opening the Arduino "serial monitor" multiple times might be somewhat difficult.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Extra `eecfbba=.@aa` file in sd card
I am doing a project, and I need an SD card. Everything worked well, but after a while when I read the SD card from my PC(Windows 10 64 bit, Intel Core), I found a file called eecfbba=.@aa. It's so big that it almost ate up one GB storage of my SD card. But when I tried to open it with notepad, notepad tells me that there is actually no such file, and asks me if I want to create it. I tried to delete it, but file explorer also told me there is no such file. What is it?
This is my code:
#include <ArduinoJson.h>

// Version 0.20.1.19.3.7:
// 2020/01/19, 16:10, button record test, 7th version.

#include <SD.h>
#include <SPI.h>
#include <TMRpcm.h>
#include <Wire.h>
#include "RTClib.h"
//#include <string.h>

RTC_DS1307 rtc;
String strdoc;
char daysOfTheWeek[7][2] = {"su", "mo", "tu", "we", "th", "fr", "sa"};
#define SD_ChipSelectPin 10  // 如果使用 arduino nano 328 可使用Pin4

TMRpcm audio;
void setup() {
  audio.speakerPin = 8;
  Serial.begin(9600);
  pinMode(25, INPUT_PULLUP);
  pinMode(7, INPUT_PULLUP);
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }
  else
  {
    Serial.println("rtc started");
  }

  if (!SD.begin(SD_ChipSelectPin)) {
    Serial.println("SD Fail");
    return;
  } else {
    Serial.println("SD OK");
  }

  audio.setVolume(6);
  audio.CSPin = SD_ChipSelectPin;

  StaticJsonDocument<200> doc;
  doc["sensor"] = "gps";
  doc["time"] = 1351824120;
  JsonArray data = doc.createNestedArray("data");
  data.add(48.756080);
  data.add(2.302038);
  serializeJson(doc, strdoc);
}
bool isrecording = false;
bool recordButtonPressed()
{
  return (digitalRead(25) == LOW);
}
bool playButtonPressed()
{
  return (digitalRead(7) == LOW);
}
void loop() {
  delay(200);
  // Below is the formatted datetime.
  DateTime now = rtc.now();
  // Below is the serialized datetime.
  String filename = (String)(now.unixtime() % 10000000) + ".j";
  //  Serial.println(filename);
  if (recordButtonPressed())
    if (!isrecording)
    {
      isrecording = true;
      audio.startRecording("test.wav", 16000, A0);
      Serial.println("stt");
    }
    else
    {
      isrecording = false;
      Serial.println("stp");
      audio.stopRecording("test.wav");
    }
  Serial.println("sdsad991===`=`");
  if (playButtonPressed())
  {
    audio.play("test.wav");
    Serial.println("ply");
  }
  String dataString = strdoc;
  if (!isrecording)
  {
    File dataFile = SD.open(filename, FILE_WRITE);

    if (!dataFile) {
      Serial.println(F("Failed to create file"));
    }
    else
    {
      dataFile.println(dataString);
      Serial.println("Wrote string.");
      dataFile.close();
      Serial.println("Closed file.");
    }
  }
  /* Please ignore this line */
  //  //    audio.play("test.wav"); break;audio.volume(1); break;audio.volume(0); break;audio.stopPlayback(); break;
}

P.S. I'm using Mega 2560, so MISO, MOSI, SCK and CS pins are different.(Which is 50,51,52,10).
Edit 2020/1/25, 14:15(Beijing Time) At 1/20 I have bigger problems. There are more and more big files. All of them are the same situation. For details, take a look at this photo(ignore selected files): Imgur or 咱们中国人上不去imgur，用这个：File-up（直接下载）

@ jsotola thank you for your quick reply. But now I have bigger problems: there are tons of other files! Screenshot of my SD card (P.S. Ignore the selected ones, they're what I want. Focus on the others)

I want to know whet are they and do I need to do anything?

don't use String class

@Juraj thank you I will try that out. But can you please tell me the real reason , why String class would produce such files?

https://majenko.co.uk/blog/evils-arduino-strings

Ok, thank you very much.

Thanks to @Juraj, I fixed the problem. Deleted those files by manually formatting the SD card.
This is not really the answer, you can see the answer in this comment under the question.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
SPI command versus data?
I have bough an LCD screen display TFT Touch Screen Board For Arduino UNO R3.
Aand the following commands are given to me for the initialization:
write_SPI_commond(0xFF);
write_SPI_commond(0xFF);
delay_nms(5);
write_SPI_commond(0xFF);
write_SPI_commond(0xFF);
write_SPI_commond(0xFF);
write_SPI_commond(0xFF);
delay_nms(10);

write_SPI_commond(0xB0);
write_SPI_data(0x00);

write_SPI_commond(0xB3);
write_SPI_data(0x02);
write_SPI_data(0x00);
write_SPI_data(0x00);
write_SPI_data(0x10);

write_SPI_commond(0xB4);
write_SPI_data(0x11);//0X10

write_SPI_commond(0xC0);
write_SPI_data(0x13);
write_SPI_data(0x3B);//
write_SPI_data(0x00);
write_SPI_data(0x00);
write_SPI_data(0x00);
write_SPI_data(0x01);
write_SPI_data(0x00);//NW
write_SPI_data(0x43);

write_SPI_commond(0xC1);
write_SPI_data(0x08);
write_SPI_data(0x15);//CLOCK
write_SPI_data(0x08);
write_SPI_data(0x08);

write_SPI_commond(0xC4);
write_SPI_data(0x15);
write_SPI_data(0x03);
write_SPI_data(0x03);
write_SPI_data(0x01);

write_SPI_commond(0xC6);
write_SPI_data(0x02);

write_SPI_commond(0xC8);
write_SPI_data(0x0c);
write_SPI_data(0x05);
write_SPI_data(0x0A);//0X12
write_SPI_data(0x6B);//0x7D
write_SPI_data(0x04);
write_SPI_data(0x06);//0x08
write_SPI_data(0x15);//0x0A
write_SPI_data(0x10);
write_SPI_data(0x00);
write_SPI_data(0x31);//0x23

write_SPI_data(0x10);
write_SPI_data(0x15);//0x0A
write_SPI_data(0x06);//0x08
write_SPI_data(0x64);//0x74
write_SPI_data(0x0D);//0x0B
write_SPI_data(0x0A);//0x12
write_SPI_data(0x05);//0x08
write_SPI_data(0x0C);//0x06
write_SPI_data(0x31);//0x23
write_SPI_data(0x00);

write_SPI_commond(0x35);
write_SPI_data(0x00);

//write_SPI_commond(0x36);
//write_SPI_data(0x00);

write_SPI_commond(0x0C);
write_SPI_data(0x66);

write_SPI_commond(0x3A);
write_SPI_data(0x66);

write_SPI_commond(0x44);
write_SPI_data(0x00);
write_SPI_data(0x01);

write_SPI_commond(0xD0);
write_SPI_data(0x07);
write_SPI_data(0x07);//VCI1
write_SPI_data(0x14);//VRH 0x1D
write_SPI_data(0xA2);//BT 0x06

write_SPI_commond(0xD1);
write_SPI_data(0x03);
write_SPI_data(0x5A);//VCM  0x5A
write_SPI_data(0x10);//VDV

write_SPI_commond(0xD2);
write_SPI_data(0x03);
write_SPI_data(0x04);//0x24
write_SPI_data(0x04);

write_SPI_commond(0x11);
delay_nms(150);

write_SPI_commond(0x2A);
write_SPI_data(0x00);
write_SPI_data(0x00);
write_SPI_data(0x01);
write_SPI_data(0x3F);//320

write_SPI_commond(0x2B);
write_SPI_data(0x00);
write_SPI_data(0x00);
write_SPI_data(0x01);
write_SPI_data(0xDF);//480

//write_SPI_commond(0xB4);
//write_SPI_data(0x00);
delay_nms(100);

write_SPI_commond(0x29);
delay_nms(30);

write_SPI_commond(0x2C);

These commands do not look like Arduino commands to me. I have placed them like this
#include <Arduino.h>
#include <SPI.h>

void setup()
{
    Serial.begin(9600);
    Serial.println("Test!");

    SPI.begin();

    write_SPI_commond(0xFF);
    write_SPI_commond(0xFF);
    delay_nms(5);
    write_SPI_commond(0xFF);
    write_SPI_commond(0xFF);
    write_SPI_commond(0xFF);
    write_SPI_commond(0xFF);
    delay_nms(10);

    write_SPI_commond(0xB0);
    write_SPI_data(0x00);

    write_SPI_commond(0xB3);
    write_SPI_data(0x02);
    write_SPI_data(0x00);
    write_SPI_data(0x00);
    write_SPI_data(0x10);

    write_SPI_commond(0xB4);
    write_SPI_data(0x11);//0X10

    write_SPI_commond(0xC0);
    write_SPI_data(0x13);
    write_SPI_data(0x3B);//
    write_SPI_data(0x00);
    write_SPI_data(0x00);
    write_SPI_data(0x00);
    write_SPI_data(0x01);
    write_SPI_data(0x00);//NW
    write_SPI_data(0x43);

    write_SPI_commond(0xC1);
    write_SPI_data(0x08);
    write_SPI_data(0x15);//CLOCK
    write_SPI_data(0x08);
    write_SPI_data(0x08);

    write_SPI_commond(0xC4);
    write_SPI_data(0x15);
    write_SPI_data(0x03);
    write_SPI_data(0x03);
    write_SPI_data(0x01);

    write_SPI_commond(0xC6);
    write_SPI_data(0x02);

    write_SPI_commond(0xC8);
    write_SPI_data(0x0c);
    write_SPI_data(0x05);
    write_SPI_data(0x0A);//0X12
    write_SPI_data(0x6B);//0x7D
    write_SPI_data(0x04);
    write_SPI_data(0x06);//0x08
    write_SPI_data(0x15);//0x0A
    write_SPI_data(0x10);
    write_SPI_data(0x00);
    write_SPI_data(0x31);//0x23

    write_SPI_data(0x10);
    write_SPI_data(0x15);//0x0A
    write_SPI_data(0x06);//0x08
    write_SPI_data(0x64);//0x74
    write_SPI_data(0x0D);//0x0B
    write_SPI_data(0x0A);//0x12
    write_SPI_data(0x05);//0x08
    write_SPI_data(0x0C);//0x06
    write_SPI_data(0x31);//0x23
    write_SPI_data(0x00);

    write_SPI_commond(0x35);
    write_SPI_data(0x00);

    //write_SPI_commond(0x36);
    //write_SPI_data(0x00);

    write_SPI_commond(0x0C);
    write_SPI_data(0x66);

    write_SPI_commond(0x3A);
    write_SPI_data(0x66);

    write_SPI_commond(0x44);
    write_SPI_data(0x00);
    write_SPI_data(0x01);

    write_SPI_commond(0xD0);
    write_SPI_data(0x07);
    write_SPI_data(0x07);//VCI1
    write_SPI_data(0x14);//VRH 0x1D
    write_SPI_data(0xA2);//BT 0x06

    write_SPI_commond(0xD1);
    write_SPI_data(0x03);
    write_SPI_data(0x5A);//VCM  0x5A
    write_SPI_data(0x10);//VDV

    write_SPI_commond(0xD2);
    write_SPI_data(0x03);
    write_SPI_data(0x04);//0x24
    write_SPI_data(0x04);

    write_SPI_commond(0x11);
    delay_nms(150);

    write_SPI_commond(0x2A);
    write_SPI_data(0x00);
    write_SPI_data(0x00);
    write_SPI_data(0x01);
    write_SPI_data(0x3F);//320

    write_SPI_commond(0x2B);
    write_SPI_data(0x00);
    write_SPI_data(0x00);
    write_SPI_data(0x01);
    write_SPI_data(0xDF);//480

    //write_SPI_commond(0xB4);
    //write_SPI_data(0x00);
    delay_nms(100);

    write_SPI_commond(0x29);
    delay_nms(30);

    write_SPI_commond(0x2C);
}

void loop(void)
{
    delay(1000);
}

and I get many errors like
error: ‘write_SPI_commond’ was not declared in this scope

Even fixing the typo to write_SPI_command does not work. I have no problem with using the default SPI.transfer of the Arduino library. But, I am wondering how to translate write_SPI_commond and write_SPI_data into a proper SPI.transfer?

What do you mean by “the following commands are given to me”? Given by whom? Is that a documentation accessible on the Web? If so, please provide the link.

@EdgarBonet, By the vendor. Under "Initialization Code".

The “commands” provided by the vendor are not code meant to be copied
as-is. They are pseudocode. If you need to know the real difference
between “write command” and “write data”, you have to look at the
datasheet of the interface chip.
See for example the ILI9481. On pages 28–29 you can see a data
transfer mode compatible with SPI (type C interface, option 3). Here you
have to wire one digital output of the Arduino to the D/CX pin on the
interface chip. This pin is used to tell whether you are writing a
command (pin LOW) or data (pin HIGH).

It is very cryptic. Can you please explain the data and command in a clear language?

@ar2015: No, I only know what I saw by looking at the datasheet. A careful read would be needed for fully understanding the protocol. I could do it. So can you.

To answer the question in the title "SPI command versus data?":
TLDR
Some SPI drivers will separate the data sent on the COPI/PICO lines into subsections to make it easier on the programmer.
SPI command versus data?
I am currently working with the ESP32 myself and have come accross the more generic question of "What is the difference between command and data when using SPI?". After some reading around, I have come to the conclusion that certain SPI drivers will allow users to separate the generic data sent in SPI protocal into subsections such as ADDRESS, COMMAND, and ADDITIONAL_DATA. This is simply to make it easier for the programmer to understand what they are sending.
Not all applications will require the an ADDRESS, COMMAND, and ADDITIONAL_DATA. For example, some chips will have pre-programmed commands such as this Inclinometer (SCA61T) which then may or may not require ADDRESS and ADDITIONAL_DATA. But others, such as the MAX7219 (which I am using), only require an ADDRESS and ADDITIONAL_DATA, no COMMAND.
Example
Using the ESP32 SPI driver, I played around with setting the length of the command bits and address bits from 0 to some nonzero number as seen in the code snippet below.
spi_device_interface_config_t devcfg={
                .command_bits=4,           ///< Default amount of bits in command phase (0-16), used when ``SPI_TRANS_VARIABLE_CMD`` is not used, otherwise ignored.
                .address_bits=4            ///< Default amount of bits in address phase (0-64), used when ``SPI_TRANS_VARIABLE_ADDR`` is not used, otherwise ignored.
}

Then I specified the data to be sent in the command and address bits (along with the data to be sent in the tx buffer) as seen in the code below.
     char data[1]= {0x97};

            spi_transaction_t spi_trans={
                .cmd={0x05},          ///< Command data, of which the length is set in the ``command_bits`` of spi_device_interface_config_t.
                .addr={0x00},         ///< Address data, of which the length is set in the ``address_bits`` of spi_device_interface_config_t.
                .length=8,            ///< Total data length, in bits
                .rxlength=0,          ///< Total data length received, should be not greater than ``length`` in full-duplex mode (0 defaults this to the value of ``length``).
                .rx_buffer=data,      ///< Pointer to receive buffer, or NULL for no MISO phase. Written by 4 bytes-unit if DMA is used.
                .tx_buffer=data,      ///< Pointer to transmit buffer, or NULL for no MOSI phase

            };

where spi_trans.cmd = {0x05} with 4 bits length corresponds to a binary 0101, spi_trans.addr = {0x00} with 4 bits length corresponds to a binary 0000, and spi_trans.tx_buffer = {0x97} with 8 bits length corresponds to a binary 10010111.
When using an o-scope to measure the chosen COPI and clock pins, we see the following waveform.

We realize the ordering of the data sent over the COPI pin is command, then address, and lastly tx data. This ordering may differ depending on which driver is used (I am using the ESP32 SPI Master driver).


text:
How to run my servo until an input is recieved?
I am VERY new to this so please excuse any silly questions.
I am trying to run an FS90 micro servo in a sweeping motion until I receive a certain value from my Adafruit TCS34725 colour sensor. I currently have my loop set that it checks the colour sensor red value using an if statement and then performs a single sweep and then checks again. Rinse Repeat. Is there a way I can get it to check the sensor and stop mid sweep if there is a red colour change?

I guess, that you use delay() in your for loop. Instead of the blocking delay() call use a non-blocking coding style like in the BlinkWithoutDelay example, that comes with the Arduino IDE. It uses millis() as clock and checks, wether a specific time period has passed. If yes, it does what it needs to do, if not, it will exit fast to execute different code, until it is time to do something.

Please show us the sketch you're using.


text:
How can I set a timer?
I would like to set a stopwatch timer that will determine how long an input is in a certain state before changing. I want to set it so that, depending on the output my code executes one of 2 switch cases. But my trouble comes in on setting a timer. Is there a function I could use? Or a method that somebody knows? The time that the input will be for each case is not fixed so I cannot use a delay.

As I suggested in the comments to your other question, you can also use millis() here to measure time differences (use micros() if the time to measure is smaller than a few milliseconds).

Even though you are not running an actual (complex) Operating System, you should adhere to common practices.  For an Arduino, you should, in many cases, avoid directly controlling the hardware so as to be compatible with as many existing libraries for your particular Arduino platform as possible.
Setting the timer directly (if you are using an official Arduino Uno which contains an Atmel328P processor the processor's timers are covered in section 14 of the Atmel328P Specifications) may cause unexpected results should you use a library which expects the timer to run without being altered.
Instead, consider using the millis() function built into the Arduino IDE.  The function returns the current number of milliseconds since the Arduino was powered up.  Record this value in your code.  Then, if you want to know if One Second has elapsed, get the new value of millis and subtract this saved value from it and see if it is greater than 1000.  When that is true, One Second has elapsed.

Re “consider added the code to detect this roll over”: better to just write rollover-safe code, like if (millis() - start_time >= duration). “check to see if millis() returns a number which exceeds this value” is not rollover-safe.

True Edgar.  @Damon Swart is brand new to the site and I like trying, testing & vetting 1 idea at a time (using millis()) - then, after the 1st idea is working, adding to it (roll-over).  Also, I rather not include code.  It takes longer to post answers w/code and the code may not be correct or complete.  Besides, describing the solution makes the Original Poster think through the problem.

@Damon Swart, if you try the answer and it works for you, accept the answer as correct so that others can also find and use the answer.  If it doesn't work for you, post a comment here and we can try to change the answer so that it does work for you.

This answer should be edited to do things the safe way.  There’s no reason anyone should have to check for rollover if you write code correctly.  Always see how long it has been.  Never try to predict a future time.

Please see my proposed edit.

Use micros() (reference page) to obtain a microsecond timestamp, and millis() (reference page) to obtain a millisecond timestamp.
Full Disclosure: I link to a library I maintain in my answer below, and I mention a few products (no links) I created with various techniques presented here in order to act as representative examples of when one approach might be preferred over another.
Example 1: simple linear (synchronous) software timing measurement, including low-resolution (micros()) and high-resolution (timer2.get_count())
In the simplest sense, let's measure how long it takes to set an output pin HIGH and then LOW again:
void setup()
{
    Serial.begin(115200);
    // I'll just leave pin 9 as an input; but uncomment the line below to make it an output
    // pinMode(9, OUTPUT);
}

void loop()
{
    // Measure and print how many microseconds it takes just to set an output pin HIGH and then
    // LOW again.
    uint32_t time_start_us = micros();    // <=== START TIMESTAMP
    digitalWrite(9, HIGH);
    digitalWrite(9, LOW);
    uint32_t time_end_us = micros();      // <=== END TIMESTAMP
    uint32_t time_elapsed_us = time_end_us - time_start_us;
    Serial.print("time_elapsed_us = ");
    Serial.println(time_elapsed_us);
    delay(100);
}

The really cool ShowInfo Arduino speed profiling sketch shows that Arduino's digitalWrite() function takes about 5us each, so expect the code above to print ~10us. Let's see if that's correct. I ran this on an Arduino Nano and got this output:
time_elapsed_us = 8
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 8
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 8
time_elapsed_us = 12
time_elapsed_us = 8
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 12
time_elapsed_us = 8

That's weird. Why only 8 or 12 us? Why not 10? Or 9? Or something else? Well, it turns out the Arduino micros() function only has a resolution of 4us, so it will actually print out either 8 or 12 us since those are multiples of 4 us. To get better resolution you'd have to modify the hardware timer registers, as I've done in my eRCaGuy_Timer2_Counter library, which has 0.5us-resolution. Full Disclosure: I wrote and maintain this library. It is free and open source, but I have it on my personal website, which has ads, and I solicit donations for downloads. A fully-functional snippet is also available in code at the bottom of that web-page without downloading anything.
Here is how to do the above code with my library:
#include <eRCaGuy_Timer2_Counter.h>

// Convert timer2 clock counts, which are 0.5us each, to us.
float counts_to_us(uint32_t time_counts)
{
    float time_us = (float)time_counts/2.0;
    return time_us;
}

void setup()
{
    Serial.begin(115200);
    // I'll just leave pin 9 as an input; but uncomment the line below to make it an output
    // pinMode(9, OUTPUT);

    // Configure Timer2. This MUST be done before the other Timer2_Counter functions work.
    // Note: since this messes up PWM outputs on pins 3 & 11, as well as interferes with the tone()
    // library (http: arduino.cc/en/reference/tone), you can always revert Timer2 back to normal by
    // calling `timer2.unsetup()`
    timer2.setup();
}

void loop()
{
    // Measure and print how many microseconds it takes just to set an output pin HIGH and then
    // LOW again.
    uint32_t time_start_counts = timer2.get_count();    // <=== START TIMESTAMP
    digitalWrite(9, HIGH);
    digitalWrite(9, LOW);
    uint32_t time_end_counts = timer2.get_count();      // <=== END TIMESTAMP
    uint32_t time_elapsed_counts = time_end_counts - time_start_counts;
    float time_elapsed_us = counts_to_us(time_elapsed_counts);
    Serial.print("time_elapsed_us = ");
    Serial.println(time_elapsed_us);
    delay(100);
}

Now look at the output. Here's the more accurate and precise results with my eRCaGuy_Timer2_Counter library. Much better! But why those spurious 14.50us values I have marked with <===? Why are they off by 4us? I will explain below.
time_elapsed_us = 10.00
time_elapsed_us = 10.50
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 14.50  <===
time_elapsed_us = 10.50
time_elapsed_us = 10.50
time_elapsed_us = 10.50
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 14.50  <===
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 10.50
time_elapsed_us = 10.50
time_elapsed_us = 10.50
time_elapsed_us = 10.50
time_elapsed_us = 10.00

The tradeoff of doing what Im doing is that you will get a 4us jitter introduced more often. Every time the 8-bit timer2 counter overflows, an ISR (Interrupt Service Routine) is called. This counts overflows to keep track of the 32-bit software timer from an 8-bit hardware counter. Entering this ISR takes about 4us, which means that if you try to grab a timestamp but then the ISR is called, you have to wait 4+us to get that timestamp, so it is off by that much. One of the several Arduino experts I really look up to, Nick Gammon, mentions this here in his Interrupts article where he says, "There is a tweaking figure of 4 µS...". So, this 8-bit counter counts at 1 tick per 0.5us, which means it rolls over every 256 ticks * 0.5us/tick = 128us. So, every 128us you will have at least a 4us delay error introduced if you try to call the timer2.get_count() exactly when the ISR is called. If you get really unlucky you may even get this effect twice and be off by as much as 8us. When using the standard micros() function, since it rolls over only every 256 ticks * 4us/tick = 1024us, you get this 4us error effect 8x less frequently. That's the tradeoff of getting better resolution: you also get more-frequent 4+us jitter.
And just for kicks, here's a really bad one. Notice the 20.50us value--off by 10.50us!
time_elapsed_us = 15.00 <===
time_elapsed_us = 10.50
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 15.00 <===
time_elapsed_us = 10.50
time_elapsed_us = 10.00
time_elapsed_us = 20.50 <======
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 10.50
time_elapsed_us = 10.00
time_elapsed_us = 10.50
time_elapsed_us = 10.50
time_elapsed_us = 10.00
time_elapsed_us = 10.00
time_elapsed_us = 10.00

Using mode filters, median filters, or other filters, these spurious results can be removed, at, of course, the cost of reduced frequency response to the thing being measured (all this means really is it takes multiple measurements to know the true value, just as we need to see with our eyes multiple measurements above to deduce 10.0us seems to be the right answer).
Example 2: non-blocking (asynchronous) timing measurement of external event
More-complicated Example: measure how long INPUT pin 9 is HIGH, and print out the HIGH time out each time it goes LOW again.
In general, use this approach for any and all input events you need to measure at the 100us to ~200us resolution or larger level. You can use this on every single pin at once and get good results with resolutions around that level, depending really just on how long your main loop takes to run each iteration.
constexpr uint8_t PIN = 9;

void setup()
{
    Serial.begin(115200);
    pinMode(PIN, INPUT);
}

void loop()
{
    // This will measure how long `SOME_PIN` is HIGH, in microseconds.

    static uint32_t time_start_us = micros();
    bool time_just_acquired = false; // true if a new time value was just measured
    uint32_t time_elapsed_us = 0;

    bool pin_state = digitalRead(PIN);
    static bool pin_state_old = LOW;

    if (pin_state == HIGH && pin_state_old == LOW)
    {
        // The pin just barely went HIGH, so "start the timer" by obtaining a timestamp of the
        // start time
        time_start_us = micros();
        pin_state_old = pin_state; // update
    }
    else if (pin_state == LOW && pin_state_old == HIGH)
    {
        // The pin just barely went LOW, so "stop the timer" by obtaining a timestamp of the
        // end time
        uint32_t time_end_us = micros();
        pin_state_old = pin_state; // update
        time_elapsed_us = time_end_us - time_start_us;
        time_just_acquired = true;
    }

    // In some other place later down the code where you need this value,
    // you can use it like this. Here I just print the value.
    if (time_just_acquired)
    {
        time_just_acquired = false; // reset
        Serial.print("time_elapsed_us = ");
        Serial.println(time_elapsed_us);
    }
}

IMPORTANT: notice in all my examples above I use ONLY UNSIGNED INTEGER variables for timestamps. This is ESSENTIAL. Using signed integers for timestamps in the same way I've written them here would be a violation of the C standard because it will produce undefined behavior when you do subtraction which results in underflow, or when the integer has overflow. Using unsigned integers, however, is perfectly valid. Ex: (uint8_t)0 - (uint8_t)1 = 255, because it is an unsigned 8-bit integer which safely underflows from its lowest value back around to its highest value. Similarly, (uint8_t)255 + (uint8_t)1 = 0 because it is an unsigned 8-bit integer which safely overflows from its highest value back around to its lowest value. This is how time_elapsed_us = time_end_us - time_start_us works in both of my examples as well. As the 32-bit microsecond counter overflows, which it will every 70 minutes or so, it wraps around back to 0. This means that sometimes time_end_us will be SMALLER than time_start_us, and you could end up with a measurement like this: time_elapsed_us = 124 - 4294967295, which equals 125.
Example 3: use external interrupts to detect changes on pins to measure external events
Use this approach when you need to measure external events at the 4~10us or larger resolution level on 2 pins maximum at a time.
This is a really good approach for measuring external events, but you get only 2 pins per Arduino Uno or Nano or similar that can do it. They are pins 2 or 3. See the table here: https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/.
For a demo, see Edgar Bonet's answer here.
Example 4: use pin change interrupts to measure external events
Use this approach when you need to measure external events at the 4~10us or larger resolution level on > 2 pins maximum at a time.
These are like external interrupts except you have to manage up to 8 pins in a single interrupt service routine (ISR), instead of only 1 pin per ISR, so they aren't quite as good as "external interrupts". Every single digital-capable pin on an Arduino Uno or Nano can do this. I use this approach when reading many PWM signals from a radio control receiver, for instance, but it requires some sophistication and a ring buffer to do it right, as the time in the ISR must be minimized or else you get tons of jitter all over the place! That means you just grab the timestamp in the ISR, store it in a ring buffer, and exit. You do NOTHING ELSE! No subtraction, no math, no determining which pin fired, nothing! You then process the ring buffer of timestamps and pin states in your main loop to determine which pin changed and do the math to obtain a new time reading on that pin. I used this for passing signals through a fire-shooting battlebots hexacopter that flew on ABC TV. It worked well. It made me happy to see the ISR do its job.
Example 5: use input capture (on pin 8 only) to measure an external event
This is the "golden", or "best" approach. But, you get 1 pin per Arduino Uno or Nano that can do it. Use this approach when you need to measure external events at the 62.5 nanosecond or larger resolution level jitter-free. There will be NO ISR TIMESTAMP DELAY WHATSOEVER with this approach, which is really cool.
Input Capture is only available on 16-bit timers on the 8-bit AVR microcontrollers such as the ATmega328. Since an Uno or Nano only has 1 16-bit timer, this means they get 1 single input capture pin. It is pin 8. Don't waste this pin for anything else if you need perfect time measurements of external events using input capture. Input capture is the "perfect" way to measure external events since it stores the time count in a hardware register at the moment the event happens, without CPU interaction through an ISR, which, as we know, would cause a delay and 4+us jitter.
I first did this on a commercial product I made which needed to read a single Radio Control receiver PWM pin. It made me happy to see it work right, as it has zero jitter. I'll come back and add a demo (code only, no more mention of the product) if I get a chance. This technique is also perfect for reading PPM (Pulse Position Modulation) signals, which are just a bunch of multiplexed Radio Control PWM signals.

Your last link points the user to a website that is full of advertisements and solicits either a monetary donation or your email address to continue. This question has been locked.

That isn't supposed to happen. Can you screenshot it? I updated my ads recently to Google auto-ads. I need to adjust it and reduce them. I'll take care of it as soon as I can, but I don't know what email address or donation would possibly be requested to continue.

Also, I've never heard of locking an entire question over one link. That seems really weird.

I'm voting to close this answer because the last link points the user to a website that is full of advertisements and solicits either a monetary donation or your email address to continue.

Your title is about “setting a timer”, but your actual question is about
measuring the length of a pulse. There are two functions provided by the
Arduino IDE for this purpose, pulseIn() and pulseInLong():

pulseIn() is based on a carefully timed delay loop. It
has a resolution of the order of one microsecond, but will not count
the time spent servicing interrupt requests. It works best for very
short pulses timed with interrupts turned off.
pulseInLong() is based on micros(). It has a
resolution of 4 µs and will not work properly if interrupts are
turned off. It works best for longer pulses where its limited
resolution and interrupt latency are tolerable.

Both of these are blocking functions: they completely block your
sketch while they perform the measurement. If you don't want your sketch
to be unresponsive during this time, you can write a non-blocking
version of pulseInLong() using a finite-state machine like
this:
// Measure the length of a pulse in a non-blocking manner.
// Returns 0 if no measurement is available at the time of the call.
void get_pulse_length() {
    static enum {
        INITIAL_WAIT,    // wait for the first (partial) pulse to end
        BETWEEN_PULSES,  // wait for the pulse to start
        WITHIN_PULSE     // wait for the pulse to end
    } pulse_state = INITIAL_WAIT;
    static uint32_t pulse_start;  // when the current pulse started

    uint8_t pin_state = digitalRead(pulse_pin);
    uint32_t now = micros();
    switch (pulse_state) {
        case INITIAL_WAIT:
            if (pin_state == LOW)
                pulse_state = BETWEEN_PULSES;
            break;
        case BETWEEN_PULSES:
            if (pin_state == HIGH) {
                pulse_start = now;
                pulse_state = WITHIN_PULSE;
            }
            break;
        case WITHIN_PULSE:
            if (pin_state == LOW) {
                pulse_state = BETWEEN_PULSES;
                return now - pulse_start;
            }
            break;
    }
    return 0;
}

Note that this measures high pulses. You will have to swap HIGH and
LOW if you want to measure low pulses. You would use it like this:
void loop() {
    uint32_t pulse_length = get_pulse_length();
    if (pulse_length) {
        // handle the pulse
    }
}

The resolution of the measurement is the execution time of loop(), so
you have to make sure there is nothing blocking there, and specially no
calls to delay(). If you need a better resolution from a non-blocking
method, you can use interrupts to trigger the measuring process:
volatile uint32_t pulse_start, pulse_length;
volatile bool pulse_valid;

void on_rise() {
    pulse_start = micros();
    attachInterrupt(digitalPinToInterrupt(pin), on_fall, FALLING);
}

void on_fall() {
    pulse_length = micros() - pulse_start;
    pulse_valid = true;
    attachInterrupt(digitalPinToInterrupt(pin), on_rise, RISING);
}

uint32_t get_pulse_length()
{
    if (!pulse_valid) return 0;
    noInterrupts();
    uint32_t pulse_length_copy = pulse_length;
    pulse_valid = false;
    interrupts();
    return pulse_length_copy;
}

void setup() {
    attachInterrupt(digitalPinToInterrupt(pin), on_rise, RISING);
}

This should give you the resolution of micros(), i.e. 4 µs, but
occasionally you may get results that are slightly off if interrupts
happen to be disabled when the input transitions. If this is
unacceptable, the only other options I see is to use a hardware timer
with input capture capability. You will have to look at the datasheet
of your microcontroller to see how it works, and maybe do a Web search
for “Arduino input capture”.


text:
Can you make Arduino Uno send information through a WiFi module to a server?
A lot of tutorials are about how to control Arduino through WiFi, but I need my Arduino to send information about motion sensor activity to a server. Is that possible?

The key words to search are "web request" together with arduino. I think there is a client library, that you can use. Depending on your used hardware

What do you want the server to do with your sensor activity? Have you looked into things like IoT (“internet of things”)?

Can you make Arduino Uno send information through a WiFi module to a server?

Yes, I can.
The simplest way is through an HTTP "GET" request. Every time you request a web page (and there are plenty of examples of that) you are sending data to the server to tell it both what web page to get (/foo/bar.php) and what data to submit to that web page (?baz=4).
It's then up to you to craft that GET request, such as:
GET /foo/bar.php?baz=4 HTTP/1.1
Host: example.com
Content-length: 0

and write the PHP web page (or whatever language you prefer to write web pages in) to do something meaningful with the "baz = 4" parameter.


text:
Latest news about alternative Arduino IDEs
I simply hate the default Arduino "IDE".
On Windows I use Visual Studio Code with the related plugin.
Now I have a Ubuntu machine and I'm looking for the definitive IDE.
Questions:

I'm not sure whether to use VSC I need to install the default IDE as well
is there something better?

By the way, I also have QtCreator, PHPStorm, MPLAB X, STM32Cube (Eclipse based).

I use Eclipse Sloeber. It is an Eclipse plugin (or product - customized Eclipse). It adds Arduino toolchain to Eclipse C/C++ development tools. https://eclipse.baeyens.it/

I have my own that I release for people to use if they want. UECIDE.

@Juraj, FYI I tried Sloeber. It seems a great project but it has too may bugs for me. After two days I still not able to compile a project. Perhaps in the future it might be a suitable option!

it works for me. the future of Sloeber is now. it is not actively developed anymore

Under Ubuntu 19.10 is unusable. And if it's not developed anymore it's another reason to avoid it :-)

I use the Arduino IDE to 'build' everything.
However, in case of a bigger project, I use a 'decent' code editor (Visual Studio in my case) to edit, and the Arduino IDE to build.
Also, because I prefer testing all non-Arduino related code on the PC (not on the Arduino), the Visual Studio (C++) project uses some stub classes I created (specifically for my project), and I can run the application on my PC.
When some part is finished, I can build the same code in Arduino IDE, but without the stubs (because these are acquired from Arduino.h and related Arduino files).
What IDE is best to 'edit' code is very subjective I think. But in the above way I can see many classes/files at a glance on the left side (and not in the top like Arduino IDE where only like 5 tabs fit on a screen), and to test lots of code on the PC already before sending it to an Arduino.
The GitHub repository can be found here: https://github.com/michelkeijzers/Mestra
Project inside is DmxLightShow.

Unfortunately, for my specific needs, I do the opposite :) I have to test the code on the target. For this reason I'm looking for a complete IDE, where I can manage libraries/boards, download software etc... like in the default one.

@Mark Even in that case you can make two projects: one on your favorite editor, where you can open multiple files and store them in different folders, and use Arduino IDE to build.

Arduino creators toughed of you.
Personally I use Geany, but you can use eclipse, but I find the Arduino plugin rather hostile, especially when it comes to editing default libraries (to add printf) and pointlessly complex serial monitor settings default above the NANO's range.
Although its missing testing feature without upload
Although most other editors would be quite happy with arduinos file too, but  you have to always create new project with native IDE.
You will find use external editor feature in Arduino-ide's settings in which case every time file is saved it gets immediately updated in Arduino's IDE, so you can use it for your tasting as a sub-window.


text:
Arduino Bluetooth upload problem HC-05 v4.0
I upload code into arduino nano using a self-made PCB with bluetooth using this method. I was initially using Arduino Nano (chinese Clone, the one with CH340G) and Bluetooth module HC-05 (version 3.0) (Lets assume this bluetooth is BT1)
At command response for BT1
AT+NAME?
+NAME:H-C-2010-06-01
OK
AT+POLAR?
+POLAR:1:1
OK
AT+VERSION
VERSION:3.0-20170601
OK
AT+UART?
+UART:9600,0,0
OK

All the things were working perfectly till the new nano as well as latest version of bluetooth arrived.
Bluetooth problem: I was trying to configure the newer bluetooth BT2 and I faced the error highlighted in code.
AT Commands response for BT2
    AT+NAME?
    +NAME:HC-05
    OK
    AT+VERSION?
    +VERSION:4.0-20190815
    OK
    **AT+POLAR**
    **ERROR:[0]**
    AT+UART?
    +UART:9600,0,0
    OK

The problem I am facing is I am unable to change the state pin with AT+POLAR command. I think this version of bluetooth has different AT Commands. If anyone knows about this particular problem please help.
Also I tried uploading code using old bluetooth to a newer version of Arduino Nano (New bootloader OPTIBOOT) and it was successful. Needed to change the baud rate of program as well as Bluetooth to 115200.


text:
Setting Time Function With DS3232 Library
I am trying to set the time on my DS3231, then read that time on my arduino nano. This is for a digital clock project. I am using DS3232 library by JChristensen.
He has an example that can set the DS3231 time through the serial monitor, and it works great, but I don't understand how to implement it into my sketch.
I can confirm that once the external RTC is set using said example, I can then upload my code, and the clock holds time when unplugged. It's setting the time within my sketch that I can't figure out. I've been at it for about 8 hours today and read through the github resources.
Here's my code. Towards the top you can see my attempt to set the system time, then set it to the RTC.
 #include "SevSeg.h";
    #include <DS3232RTC.h>; //Jack Christensen
    https://github.com/JChristensen/DS3232RTC
    #include <Streaming.h>; //Mikal Hart https://github.com/janelia-
     arduino/Streaming
    //Also requires time library https://github.com/PaulStoffregen/Time

    SevSeg sevseg;

    void setup() {
    // put your setup code here, to run once:

    //Serial.begin(9600);

    setSyncProvider(RTC.get);// the function to get the time from the RTC
    setTime(8,0,0,20,1,2020);
    time_t t = now();
    RTC.set(now());

     byte numDigits = 4;
     byte digitPins[] = {2, 3, 4, 5};
     byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12};
     bool resistorsOnSegments = false; // 'false' means resistors are on digit
     pins
     byte hardwareConfig = COMMON_CATHODE; // See README.md for options
     bool updateWithDelays = false; // Default 'false' is Recommended
     bool leadingZeros = false; // Use 'true' if you'd like to keep the leading
     zeros
     bool disableDecPoint = true; // Use 'true' if your decimal point doesn't
     exist or isn't connected. Then, you only need to specify 7 segmentPins[]

     sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins,
      resistorsOnSegments,
       updateWithDelays, leadingZeros, disableDecPoint);

    }

     void loop() {

    sevseg.setChars("hola");
    sevseg.refreshDisplay();

     if(millis()>6000) {

    int adj = 0;
    int timenumber;
    int hr = hourFormat12();
    int Min = minute();

    timenumber = (hr*100) + Min; //converts time into a number for the seven
    segment display

   sevseg.setNumber(timenumber);
   sevseg.refreshDisplay();
    }

    }

And JChristensen's Example Code:
// Arduino DS3232RTC Library
// https://github.com/JChristensen/DS3232RTC
// Copyright (C) 2018 by Jack Christensen and licensed under
// GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html
//
// Example sketch to display the date and time from a DS3231
// or DS3232 RTC every second. Display the temperature once per
// minute. (The DS3231 does a temperature conversion once every
// 64 seconds. This is also the default for the DS3232.)
//
// Set the date and time by entering the following on the Arduino
// serial monitor:
//  year,month,day,hour,minute,second,
//
// Where
//  year can be two or four digits,
//  month is 1-12,
//  day is 1-31,
//  hour is 0-23, and
//  minute and second are 0-59.
//
// Entering the final comma delimiter (after "second") will avoid a
// one-second timeout and will allow the RTC to be set more accurately.
//
// No validity checking is done, invalid values or incomplete syntax
// in the input will result in an incorrect RTC setting.
//
// Jack Christensen 08Aug2013

#include <DS3232RTC.h>      // https://github.com/JChristensen/DS3232RTC
#include <Streaming.h>      // http://arduiniana.org/libraries/streaming/

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

    // setSyncProvider() causes the Time library to synchronize with the
    // external RTC by calling RTC.get() every five minutes by default.
    setSyncProvider(RTC.get);
    Serial << F("RTC Sync");
    if (timeStatus() != timeSet) Serial << F(" FAIL!");
    Serial << endl;
}

void loop()
{
    static time_t tLast;
    time_t t;
    tmElements_t tm;

    // check for input to set the RTC, minimum length is 12, i.e. yy,m,d,h,m,s
    if (Serial.available() >= 12) {
        // note that the tmElements_t Year member is an offset from 1970,
        // but the RTC wants the last two digits of the calendar year.
        // use the convenience macros from the Time Library to do the conversions.
        int y = Serial.parseInt();
        if (y >= 100 && y < 1000)
            Serial << F("Error: Year must be two digits or four digits!") << endl;
        else {
            if (y >= 1000)
                tm.Year = CalendarYrToTm(y);
            else    // (y < 100)
                tm.Year = y2kYearToTm(y);
            tm.Month = Serial.parseInt();
            tm.Day = Serial.parseInt();
            tm.Hour = Serial.parseInt();
            tm.Minute = Serial.parseInt();
            tm.Second = Serial.parseInt();
            t = makeTime(tm);
            RTC.set(t);        // use the time_t value to ensure correct weekday is set
            setTime(t);
            Serial << F("RTC set to: ");
            printDateTime(t);
            Serial << endl;
            // dump any extraneous input
            while (Serial.available() > 0) Serial.read();
        }
    }

    t = now();
    if (t != tLast) {
        tLast = t;
        printDateTime(t);
        if (second(t) == 0) {
            float c = RTC.temperature() / 4.;
            float f = c * 9. / 5. + 32.;
            Serial << F("  ") << c << F(" C  ") << f << F(" F");
        }
        Serial << endl;
    }
}

// print date and time to Serial
void printDateTime(time_t t)
{
    printDate(t);
    Serial << ' ';
    printTime(t);
}

// print time to Serial
void printTime(time_t t)
{
    printI00(hour(t), ':');
    printI00(minute(t), ':');
    printI00(second(t), ' ');
}

// print date to Serial
void printDate(time_t t)
{
    printI00(day(t), 0);
    Serial << monthShortStr(month(t)) << _DEC(year(t));
}

// Print an integer in "00" format (with leading zero),
// followed by a delimiter character to Serial.
// Input value assumed to be between 0 and 99.
void printI00(int val, char delim)
{
    if (val < 10) Serial << '0';
    Serial << _DEC(val);
    if (delim > 0) Serial << delim;
    return;
}

Can you format your code a little bit? It is impossible to read it in this way... With wrong tabs and a lot of line feeds. An error is this: if(millis()>6000). This means that your loop will not do anything for 6 seconds and then it will refresh the display so fast as possible... If you just want update your clock, you can do it 1 time every second with a delay, or better, update the display only if the second value changed.

Do you understand, how the example sketch is setting the time? If yes, what exactly is your problem in implementing it?

It’s set through the serial monitor. So I need to make a function to send input to the serial. I haven’t yet figured out how the example code it able to do this

I figured it out. You must first set the built in arduino RTC using the time library, then set the DS3232 from there. It did not work for my code before because it has to be called outside of the setup function.
For instance, I made a function that adjusts the hour:
void adjHr() { //hour adjustment function

if(millis() >= time_now + period){
        time_now += period;
        time_now = millis();
        setTime(hour()+1,minute(),second(),day(),month(),year());
        RTC.set(now());
    }

My setup function also includes:
setSyncProvider(RTC.get);

Allows the code to get time from the DS3232.

it is not the best way

It is “a” way. But if you have a better way, do share and i’ll mark your’s as the answer

you have a better way in the code in question. tmElements_t

I assume you’re referring to using the serial monitor to set the time. That seems like a very straightforward way to do it, but I have yet to figure that out. For now, setting the time with my alternate method is good enough.

it has nothing to do with Serial. in the example the values are read from Serial (read by parseInt) and are set into the tmElements_t structure. but you can use the variables to set the elements of date and time.  Then the makeTime from TimeLib function calculates the 'epoch' value and it is set to RTC. the way in your answer will have a problem, because the time runs in TimeLib

What problem will it encounter? My clock seems to work just fine and holds time with the backup battery.


text:
How to add another condition in the loop?
I am using mpu6050 for counting the twitch movement. The algorithm is counting the peak/twitch whenever it goes above the threshold value. Now, I want to add that the algorithm count twitch only when it goes above threshold value and all the twitch within 90s are counted as one twitch movement. Kindly help me with this. Also try to integrate this in my code.
Here is the code:
#include "I2Cdev.h"
#include "MPU6050.h"

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

MPU6050 accelgyro;

int16_t ax, ay, az;
float threshhold=5000.0;
float conmove=4;
const int sampletime=90000;

float xval[100]={0};
float yval[100]={0};
float zval[100]={0};
float xavg;
float yavg;
float zavg;

int twitch,flag=0;
MPU6050 mpu6050;

int16_t tr;          // raw temperature data register value
char buffer[7];      // temporary string buffer; used with dtostrf() function
#define OUTPUT_READABLE_ACCELGYRO

#define LED_PIN 13
bool blinkState = false;

void setup() {

    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    Serial.begin(115200);

    // initialize device
    Serial.println("Initializing I2C devices...");
    accelgyro.initialize();
    mpu6050.initialize();  // initialize MPU6050 sensor module

    // verify connection
    Serial.println("Testing device connections...");
    Serial.println(accelgyro.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed");

    pinMode(LED_PIN, OUTPUT);
    calibrate();
    delay(5000);
}

void loop() {

    accelgyro.getAcceleration(&ax, &ay, &az);
    tr = mpu6050.getTemperature();

    #ifdef OUTPUT_READABLE_ACCELGYRO
    +
        // display tab-separated accel/gyro x/y/z values
        Serial.print("a/g:\t");
        Serial.print(ax); Serial.print("\t");
        Serial.print(ay); Serial.print("\t");
        Serial.print(az);
    #endif

    #ifdef OUTPUT_BINARY_ACCELGYRO
        Serial.write((uint8_t)(ax >> 8)); Serial.write((uint8_t)(ax & 0xFF));
        Serial.write((uint8_t)(ay >> 8)); Serial.write((uint8_t)(ay & 0xFF));
        Serial.write((uint8_t)(az >> 8)); Serial.write((uint8_t)(az & 0xFF));
    #endif

    // blink LED to indicate activity
    blinkState = !blinkState;
    digitalWrite(LED_PIN, blinkState);
    int acc=0;
    float totvect[100]={0};
    float totave[100]={0};
    float xaccl[100]={0};
    float yaccl[100]={0};
    float zaccl[100]={0};

    for (int i=0;i<100;i++)
    {
        xaccl[i]=float(ax);
        delay(1);
        yaccl[i]=float(ay);
        delay(1);

        zaccl[i]=float(az);
        delay(1);

        totvect[i] = sqrt(((xaccl[i]-xavg)* (xaccl[i]-xavg))+ ((yaccl[i] - yavg)*(yaccl[i] - yavg)) + ((zval[i] - zavg)*(zval[i] - zavg)));
        totave[i] = (totvect[i] + totvect[i-1]) / 2 ;
        //acc=acc+totave[i];
        Serial.println(totave[i]);
        Serial.print("T = ");  Serial.print(dtostrf(tr/340.0+36.53, 5, 1, buffer));  Serial.println(" °C");

        // delay(200);

        //cal twitch
        if (totave[i]>threshhold && flag==0)
        {
            twitch=twitch+1;
            flag=1;
        }
        else if (totave[i] > threshhold && flag==1 )
        {
            //do nothing
        }
        if (totave[i] <threshhold  && flag==1 )
        {flag=0;}

        Serial.println('\n');
        Serial.print("twitch=");
        Serial.println(twitch);
    }

    //float tim=acc/100;
    //Serial.println(tim);
    delay(1000);
    // stepcal(totave);
}

void calibrate()
{
    digitalWrite(13,HIGH);
    accelgyro.getAcceleration(&ax, &ay, &az);

    float sum=0;
    float sum1=0;
    float sum2=0;

    for (int i=0;i<100;i++)
    {
        xval[i]=float(ax);

        sum=xval[i]+sum;
    }
    delay(100);
    xavg=sum/100.0;

    Serial.println(xavg);

    for (int j=0;j<100;j++)
    {
        yval[j]=float(ay);

        sum1=yval[j]+sum1;
    }
    yavg=sum1/100.0;

    Serial.println(yavg);
    delay(100);
    for (int i=0;i<100;i++)
    {
        zval[i]=float(az);

        sum2=zval[i]+sum2;
    }
    zavg=sum2/100.0;
    delay(100);
    Serial.println(zavg);

    digitalWrite(13,LOW);
}

You can do this with the millis() function. It returns the number of milliseconds since startup and can be used as a simple clock. Take the if statement, where you increment twitch:
if (totave[i]>threshhold && flag==0)
{
  if(millis()-last_twitch_timestamp > 90000){
    twitch=twitch+1;
    flag=1;
    last_twitch_timestamp = millis();
  }
}

This will check, if at least 90 seconds (90000ms) have passed since the last registered twitch (time difference between the current time and the timestamp of the last twitch). If yes, it will register another twitch and reset the timestamp to the current time (return value of millis()). This deactivates twitch registering for 90s after each twitch.
For this to work, you need to define the last_twitch_timestamp variable at global scope:
unsigned long last_twitch_timestamp = 90000;

I initialize the timestamp to 90000, so that the very first twitch can be registered. If you initialize it to zero, you would need to wait 90s, until the first twitch can be registered.

Btw: The following delays don't make any sense. You can remove them:
xaccl[i]=float(ax);
delay(1);
yaccl[i]=float(ay);
delay(1);

zaccl[i]=float(az);
delay(1);

And you should really really keep all lines indented correctly. The Arduino IDE has an autoformat feature to make it simpler for you.

thank you for your response. Yes,it is counting all those twitch that occurs within 90s as one but after 90s it recognize next twitch for approx after 5s delay. so, this 5 second delay in the count would effect the our data. kindly help me with that.

Moreover, how can we add that the twitch is counted as one within 90s but there should be minimum 4 movements within that 90s.

@zuni What do you mean by 5s delay?. Do you mean, that the next twitch is only recognized after 95s, but not after 90s?

yes you can say not immediately after 90s.

You have a total of about 1.5s delay in your code. That reduces your reaction time. If you need faster reaction time, you should ditch the delay calls totally, going to non-blocking code like in the BlinkWithoutDelay example

okay that helped. kindly help me with this Moreover, how can we add that the twitch is counted as one within 90s but there should be minimum 4 movements within that 90s.

count up another variable right before the millis if statement. Then you can check it inside the if statement and reset it there to zero

would you write the syntax for this??


text:
OTA update for ESP32 in Arduino ide from a different nework
I am trying to use the OTA to update my code in esp32. I have used Web updater so far and it has worked perfectly. But I want to update the code even when I am not connected in the same network with my esp32. Say, the esp32 have an ip from my phone Ap : 192.168.1.43 and I am connected in a different one say, 192.168.25.12 As both of them are class C ip having default subnet mask then we are in different network.
I have found this following question
OTA updating the ESP32 from a separate server
It did not clarify things to me.

I know nothing about OTA updates, but isn't this just a routing problem between the networks?

then it is better to download he update with the HTTPUpdate library

there's 3 different OTA routines i've seen, (IDE, self-hosted web, WWW) maybe more exist. the one where your bin files are on a web server should work across different nets, as long as they have internet.

dandavis by self hosted do you mean the bin file and esp32 are connected in the same network?? And by www, in other networks??


text:
I2C Communication Matlab - FDC1004
I have a ProtoCentral FDC1004 board (datasheet: http://www.ti.com/lit/ds/symlink/fdc1004.pdf) connected to an Arduino. I am then trying to connect to the system via matlab.
I have found the address (0x50) using addrs = scanI2CBus(a) and I am now trying to read measurements from it.
Page 15 of the datasheet says the following to trigger measurements:
 1. Setting REPEAT (Register 0x0C:bit[8]) to 0.
 2. Setting the corresponding MEAS_x field (Register 0x0C:bit[7:4]) to 1.
    – For example, to trigger a single measurement of Measurement 2 at a rate of 100S/s,
    set Address 0x0C to 0x0540.

Q1: How do I work out where the value "0x0540" comes from?
Q2: I don't seem to be able to write this value, I'm able to write other values to this register and read them back however. How can I write 0x0540 to this register?
My matlab script is as follows:
a = arduino('COM7', 'Uno', 'Libraries', 'I2C');
capdev = device(a,'I2CAddress',0x50);

writeRegister(capdev, 0x0C, 0x0540,'uint16');
readRegister(capdev,0x0C,'uint16')
value1 = readRegister(capdev,0x02,'uint16')
value2 = readRegister(capdev,0x03,'uint16')

readRegister(capdev,0x0C,'uint16') simply displays the last value I wrote to this register during testing (eg 3)
0x02 and 0x03 are supposedly where measurement 2 is stored. These read as 0.
Q3: Any idea what I'm doing wrong, or how to implement this correctly?
Thank you!

Q1 ... see Table 5 ... convert 0x0540 to binary

Q1 - converting to decimal (which i need for matlab) gives 1344. I still cannot write this in matlab (returns "0" when I read it back)

Matlab seems happy for me to specify in whatever (https://uk.mathworks.com/help/supportpkg/arduinoio/ref/writeregister.html#d117e17865) but I can't get this value to write in any format for some reason

why do you believe that you can read back the value that you wrote to register 0x0c?

regarding Q1, why are you converting to decimal? ... have you forgotten what you asked in Q1?

Why do I believe I can read it back? a) because I can read it back when I write test data to it (small integers, 0-15) b) because why wouldn't I be able to

Why convert to decimal? Because I still need to write it in matlab which I can't seem to do with the hex value. The matlab examples I've seen write to registers using decimal so that seemed like a good thing to try. Alas, that didn't seem to work either

converting to decimal has nothing to do with Q1

Why do I believe I can read it back? ... a) makes sense ... try values up to 0xff .... b) you cannot assume that all registers read back what you wrote to them ... always refer to the device datasheet to make sure


text:
Set slide potentiometer values
I am using the Grove - Slide Potentiometer (http://wiki.seeedstudio.com/Grove-Slide_Potentiometer). How can I set the potValue so that at maximum it will 128?
int potPin= A0;
int readValue;
int potValue;

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

void loop() {
 readValue = analogRead(potPin);
 potValue = (255./500.) * readValue;
 Serial.print("You are writing a value of ");
 Serial.println(potValue);
}

You can use the map function, see https://www.arduino.cc/reference/en/language/functions/math/map/.
Example: If your pot meter gives values from 100 to 1000 and you want to map that range to a range of 0 to 128 you can easily write:
potValue = map(readValue, 100, 1000, 0, 128);

High likely, in your case and if the potentiometer is 'perfect' it returns values from 0 to 1023 and you can write:
potValue = map(readValue, 0, 1023, 0, 128);

with potValue = map(readValue, 0, 1023, 0, 128); I get the max value of 186.

What is the maximum raw value you get? … you can increase the value of 1023 to assume a higher  maximum (set it to the maximum value you get from the pot).

the mx. value of readValue is 728

According to the documentation, map(728, 0, 1023, 0, 128) should be something like 91.  (728/1023*128). If you would use map(value, 0, 728, 0, 128) you should get values upto 128.

Consider that map is using integer arithmetics (truncating). To get evenly spaced areas, you'd rather map (readValue,0,1024, 0,129);( Will transform 0..1023 to 0..128 and everything > 1016 will show 128)   If this is really what you want.

analogRead() returns 0x0000 to 0x03ff
If the max data 0x03ff is shifted to the right by 3 bits (or divide by 8),
then 0x03ff becomes 0x007f, or 127.
I think this will do it:
desiredMax = analogRead(A0) >> 3; // divide 1023 max by 8, becomes 127 max

fast and simple, but less readable. +1

Less readable?  // add a comment to the line

No need for (less readable) bitshifting - dividing by 8 yields the same compiled code as the right shifts (https://godbolt.org/z/V82L6Z)


text:
Daisy chaining of multiple blocs of 4x(8x8) MAX7219 matrix
Thanks for your presentation https://arduino.stackexchange.com/tags/max7219/info.
You say that multiple MAX7219 8x8 blocs can easily be daisy-chained and you show an example of at least 12 blocs displaying "Testing12345".
Trying several programs I found for Arduino, I never succeeded to chain more than 8 blocs with 8x8 matrix (either 8 individual blocs or 2 groups of 4 as on your image).
So I'ld be very happy if you send me examples of programs managing more than 8 blocs for fixed or scrolling displays.
Many thanks in advance.

The person who wrote the presentation will probably not see this... I suggest you make this question more 'generic'  (not using 'you' ), and add a comment in his post to mention yours (since it's a new question).

I never succeeded to chain more than 8 blocs with 8x8 matrix is a useless description of the problem because it contains no information that can be used to resolve the problem .... something like if i chain more than 8 blocs, then XYX happens is way more useful

Try using @Majenko 's MAX libary https://github.com/MajicDesigns/MD_MAX72XX .  It allows you to specify how many modules are to be addressed.

Thanks for your answer. Very intersting library. But, with its examples, there is an addressing issue on my display. For each 8x8 matrix the columns seem to be inverted, displaying first the column #8 instead of column #1. So the global scrolling is OK from right to left (first to last matrix of the daisy-chain), but each matrix is scrolling its columns from left to right with inverted display!

With static display of a text, it's the same: the columns of each 8x8 matrix are inverted.

All is OK changing the proposed statement
define HARDWARE_TYPE MD_MAX72XX::PAROLA_HW
to
define HARDWARE_TYPE MD_MAX72XX::FC16_HW


text:
Need my code to do multiple commands when inputs are pressed
Hello all I am back again with another issue concerning a code for my job. The code I have been working on is meant to connect to a IP server where some options are listed and I can control the servo motor through there. The options listed are FORWARD, BACKWARD, STEP, and STOP. Each command makes the servo motor move a certain way but the problem I need help with is I need the edited the code to work with three input switches which when pressed in real time they allow the motor to make turns without the need of pressing any button on the server and so far the code is not working. They work with some LED lights which when the input switches are pressed also light up each input is paired with an output (LED) respectively and I tried to create a marker that when the input is pressed also says on the server that "LED1 is on" for example. Each input corresponds to an INPUT switch and each output corresponds to an LED light. The Pin variable corresponds to the motor. Here is the code in question:
#include <ESP8266WiFi.h>
#include <Servo.h>

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

WiFiServer server(80);

int Pin = 16; // GPIO13
int var = 0;
int D1 = 5;
int D2 = 4;
int D4 = 2;
int D5 = 14;
int D6 = 12;
int D7 = 13;
int temp1 = 0;
int temp2 = 0;
int temp3 = 0;

Servo servoMotor;

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

  pinMode(D1, INPUT);
  pinMode(D2, OUTPUT);
  pinMode(D4, INPUT);
  pinMode(D5, OUTPUT);
  pinMode(D6, INPUT);
  pinMode(D7, OUTPUT);
  pinMode(Pin,INPUT);
  //pinMode(LED_BUILTIN, OUTPUT);
  //digitalWrite(LED_BUILTIN, LOW);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");

  //servoMotor.attach(Pin);

}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  temp1 = digitalRead(D1);
  temp2 = digitalRead(D4);
  temp3 = digitalRead(D6);
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }

  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();

  // Match the request
  if(temp1 == HIGH) {
    digitalWrite(D2,HIGH);
    servoMotor.attach(Pin);
    servoMotor.write(90);
  }
  else{
    digitalWrite(D2,LOW);
  }

  if(temp2 == HIGH) {
    digitalWrite(D5,HIGH);
    servoMotor.attach(Pin);
    servoMotor.write(-90);
}
  else {
    digitalWrite(D5,LOW);
}

  if(temp3 == HIGH) {
    digitalWrite(D7,HIGH);
}
  else{
    digitalWrite(D7,LOW);
}

  int value = LOW;
  while (value = LOW); {
  if (request.indexOf("/LED=ON") != -1)  {
    //digitalWrite(LED_BUILTIN, HIGH);
    value = HIGH;
    servoMotor.attach(Pin);
    servoMotor.write(0);
    delay(1000);

  }
  if (request.indexOf("/LED=OFF") != -1)  {
    //digitalWrite(LED_BUILTIN, LOW);
    value = LOW;
    servoMotor.attach(Pin);
    servoMotor.write(180);
    delay(1000);

  }
  if (request.indexOf("/LED=STP") != -1){
      var = 1;
      while(var < 10){
    //digitalWrite(LED_BUILTIN, LOW);
    value = LOW;
    servoMotor.attach(Pin);
    servoMotor.write(90);
    delay(200);
    servoMotor.write(-90);
    delay(200);
    var=var+1;
    }
  }
  if (request.indexOf("/LED=STOP") != -1)  {
    //digitalWrite(LED_BUILTIN, LOW);
    value = LOW;
    servoMotor.detach();
    delay(1000);
  }

// Set ledPin according to the request
//digitalWrite(ledPin, value);

  // Return the response
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("");

  client.print("Robot is now: ");

  if(value == HIGH) {
    client.print("Moving Forward");
  } else if(value == LOW) {
    client.print("Moving Backward");
  } else if(request.indexOf("/LED=STP") != -1) {
    client.print("Moving in Step");
  }else {
    client.print("Stopped");
  }

  if(temp1 == HIGH) {
    client.print("Led_1 is on");
  }else if (temp1 == LOW);{
    client.print("Led_1 is off");
  }

  if(temp2 == HIGH) {
    client.print("Led_2 is on");
  }else if (temp2 == LOW);{
    client.print("Led_2 is off");
  }

  if(temp3 == HIGH) {
    client.print("Led_3 is on");
  }else if (temp3 == LOW);{
    client.print("Led_3 is off");
  }

  client.println("

");
  client.println("<button>Move Forward </button>");
  client.println("<button>Step </button>");
  client.println("<button>Move Backward </button>
");
  client.println("<button>STOP </button>
");
  client.println("<Input>LED_1 ON </Input>
");
  client.println("<Input>LED_2 ON </Input>
");
  client.println("<Input>LED_3 ON </Input>
");
  client.println("");

  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");
  }
}

P.S. I just edited the code to do the turns when the input is pressed for the third input it is supposed to make a random turn (either left or right the machine needs to decide on its own) and I am not sure how to write that in the code.

https://www.arduino.cc/reference/en/language/functions/random-numbers/random/

rewrite your code so that received commands and button presses are separated from actions being performed ... right now you use something like if received motorON then run motor and if buttonPressed then run motor ............ instead use something like if received motorON then set flag and if buttonPressed then set flag then take action depending on state of the flag if flagIsSet then run motor

@jsotola how would i write that in the form of code?

Your code will only do anything if a client has connected to it because of this line
if (!client) {
    return;
  }

Your physical button will never do anything on their own unless a client has connected and has sent some data.
For the random direction you use a line like the following to randomly pick a direction
int direction = random(0,2) ? 1 : 0 ;

your direction variable will be with either 1 or 0 randomly

random(0,2) ? 1 : 0 is a convoluted way to write random(0, 2).

Wow, you're right. hehe.


text:
Voltage divider and NodeMCU inputs
Some sensors give as output a voltage between 0 and 5V. The analog inputs of the NodeMCU require voltages between 0 and 3.3V. I plan to make a voltage divider with two resistors like in this link for compatibility.
To provide the desired voltage the quotient of the values of the resistances is fixed (approx. 1/2 for this case). However, the absolute values of the resistances are not.
Q: How to choose those absolute values? Which are the criteria and why?
I have a good background in electromagnetism but I know very few about electronic Engineering.
I think that low values must work, e.g. 1Ω and 2Ω (and surely greater values). But I am unsure of VERY high resistance values because I suspect that there should be some current intensity requirements.
Thank you.

As @Majenko commented, the A0 input has a fixed voltage divider (see NodeMCU Schematics) that connects the A0 input to a 220kOhm resistor, then to the ADC pin of the ESP8266, then to ground via a 100kOhm resistor.

This effectively fixes the resistor values that can be used to scale the input of the NodeMCU. For a 0-5.0V input range (with sufficiently low impedance) you need to scale the ADC pin from 0-1.0V by adding a ~180kOhm resistor between the 5V output and the A0 input of the NodeMCU, creating a 400kOhm-> ADC -> 100kOhm divider like this:

simulate this circuit – Schematic created using CircuitLab

what are the trade-off with this compared to adding a parallel resistor between A0 and GND?

I don't think there are any trade-offs to be honest. You need to divide your 0-5.0V sensor output by 5 to create a 0-1.0V signal on the ADC pin of the ESP8266 and this is about the simplest and most efficient way to achieve that. The resistor values are sufficiently high as to create very little load on your sensor output. The only drawback I can think of is in the case of very high frequency signals.

For digital inputs, do I need to add two resistances, right?

Digital inputs dont’t have an internal voltage divider on the NodeMCU board and accept 3.3V input. To scale from 5V to 3.3V you need a divider 3/5 divider. For example:        5V Input->2.2kOhm->NodeMCU input->3.3kOhm->GND

The low end of the values is limited by how much current your sensor can provide. If you use 1Ω and 2Ω resistors in series then your sensor will need to provide 1.67A to create 5V across the divider. I doubt that your sensor can do that. For most sensors, you would want to use resistors in the kilohm or tens of kilohm range.
The high end is limited by the input impedance of the analog input pin. If your resistor values are large compared to this input impedance then the input impedance of the analog pin will affect how the voltage divider works. If the analog input is multiplexed and the ADC has a sample-and-hold at the input, then very large resistances in the divider will not allow the sampling capacitor to charge fast enough. For most ADC inputs, you would want to use resistors in the tens or hundreds of kilohms.

Thank you! There is still something that I do not get about low values: If the sensor works giving an output up to 5V when it is connected to an Arduino, and the sensor cannot provide 1.67A, it implies that there is already an enough large resistor in the Arduino board (or NodeMCU). Doesn't it? In such case, there should not be a problem using small resistances in the divisor. In other words, if the sensor can work with the board without any additional resistance, how can it be that adding resistances forces the sensor to provide greater currents? Excuse if it is a silly question. Thanks.

the less resistance in the divider, the more wasted heat and constant current consumption there is to deal with. Sure a 1ohm pair scales 5v into 2.5v, but it also wastes 2.5W of power and makes enough heat to fry 10 common resistors. If the sensor cannot supply those amps, it will drop the voltage or fry the sensor.

@user1420303 The problem is that the resistance of the divider is in parallel with the input resistance of the microcontroller, not in series. Putting resistances in parallel results in an equivalent resistance that is less than either of the original resistances. Very large currents will flow through your divider.

For ATMega based Arduinos the effective resistance seen by the ADC should not be higher than 10kohm for the reason you describe. Since it is the Thevenin resistance that is seen a two to 1 divider using 20kohm resistors would give 10k effective. In general use something between 1k and 10k.

To better understand voltage divider, one can look at this online calculator https://ohmslawcalculator.com/voltage-divider-calculator to see the actual formula and try the calculator to compute the unknown wanted.
It is not well publish the existing voltage divider on the NodeMCU, of course you need to browse the schematic to figure it out.
It goes the same with existing pullup resistor for some GPIO.
@Majenko your explanation is excellent!


text:
ESP-01 Deep Sleep not waking up properly
I have a temperature/humidity project using an ESP-01 and DHT11.  I want to be able to put t into deep sleep to preserve battery life.  I have soldered a wire from GPIO16 to RST.
#include <SimpleTimer.h>  //https://github.com/jfturcot/SimpleTimer
#include <ESP8266WiFi.h>
#include <PubSubClient.h>  //https://github.com/knolleary/pubsubclient
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>  //https://github.com/esp8266/Arduino/tree/master/libraries/ArduinoOTA
#include "DHT.h"

//USER CONFIGURED SECTION START//
#define DHTPIN 2     // what digital pin we're connected to

const char* ssid = "mySSID";
const char* password = "password";
const char* mqtt_server = "mqttserverip";
const int mqtt_port = 1883;
const char *mqtt_user = "usser";
const char *mqtt_pass = "pass";
const char *mqtt_client_name = "DryerMCU"; // Client connections can't have the same connection name
//USER CONFIGURED SECTION END//

// Uncomment whatever type you're using!
#define DHTTYPE DHT11   // DHT 11
//#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors.  This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);

WiFiClient espClient;
PubSubClient client(espClient);
SimpleTimer timer;

bool boot = true;
int status = WL_IDLE_STATUS;

//Functions
void setup_wifi()
{
  Serial.println();
  Serial.print("Connecting to ");
  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());
}

void getTemperature()
{
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hic);
  Serial.print(" *C ");
  Serial.print(hif);
  Serial.println(" *F");

  char temperature[50];
  char humidity[50];

   // Update temperature and humidity
  String temp_str = String(f);
  temp_str.toCharArray(temperature, temp_str.length() + 1);
  client.publish("dryer/temperature", temperature);

  String hum_str = String(h);
  hum_str.toCharArray(humidity, hum_str.length() + 1);
  client.publish("dryer/humidity", humidity);

}

void setup() {
  Serial.begin(38400);
  delay(2000);
  Serial.println("Booting");

  dht.begin();
  setup_wifi();
  client.setServer(mqtt_server, mqtt_port);
  getTemperature();

  Serial.println("Going to sleep");
  ESP.deepSleep(10000000,RF_DEFAULT);
}

void loop() {

}

When I start it up it takes one measurement, goes to sleep and then wakes up, but nothing happens once it wakes up.  Serial output:
Booting

Connecting to SSID
  ......
WiFi connected
IP address:
mqttip
Humidity: 51.00 %   Temperature: 20.00 *C 68.00 *F  Heat index: 19.39 *C 66.90 *F
Going to sleep

ets Jan  8 2013,rst cause:5, boot mode:(3,7)

ets_main.c

I added a Serial.println("woke up"); right after ESP.DeepSleep and it never prints that line.  Also, I was under the impression that the setup() method gets called again when it wakes up as if it had just been reset

That did not help.  It still doesn't do anything after the ESP.DeepSleep

reduce your code to minimum ... example code is here at "basic deep sleep" ... https://www.losant.com/blog/making-the-esp8266-low-powered-with-deep-sleep   .... i was very wrong about putting code in loop() ... looks like the esp resets when it wakes up

I tried the very basic version from your link and still get the same result.  It appears to sleep, but nothing runs after it wakes up.  What else could it be?

please post a picture that shows the wire you soldered onto the circuit

Did the same project.  Used ESP-Now instead of normal WIFI protocol and 3 ESP8266 ESP-01 boards (1 for the sensor and 2 to make a ESP-Now to WIFI bridge).  I abandon the DHT11 as I had one fail in a very hard to get to location & switched to the Si7021.  The remote ESP-01 which goes to sleep needed to be modified in order for the onboard timer to wake it up.  Has been running outside for over 2 months now.  Should really push this code back to github.  Add a comment if you want to try this route instead of normal WIFI.

I'd try putting Serial.flush();  before the deepsleep.

In the question the OP said:

I have soldered a wire from GPIO16 to RST.

But, I'm going to post an answer for the people who find this question and need the ESP-01 modification instructions in order to wake an ESP-01 module up from deep-sleep:
The ESP8266 mounted on an ESP-01 board will not wake up from deep-sleep because the ESP8266 wake up signal is not connected to the reset pin of the ESP8266 on an ESP-01 board.  You need to add this connection which can be difficult for most people.  You can see the modification in this picture:

...which comes from this instructables posting.
If this is too difficult, consider using a different ESP8266 board which brings these ESP8266 pins to board edge connectors.

I guess you have a race condition between automatic connection to WiFi by the Espressif SDK and your WiFi.begin(). You have two options how to solve it.
1. option: Don't use WiFi.begin in this sketch. Use an utility sketch to set the SSID and password and the SDK remembers it persistent on flash. Then it is able to connect fast to WiFi specially on reset, because it has the WiFi channel number in RTC memory which is not cleared at reset (only on power down).
2. option: turn of remembering of the SSID and password and the automatic connection at start. Then the esp8266 will connect to the WiFi only with your WiFi.begin call. The commands are WiFi.persistent(false) and WiFi.setAutoConnect(false).
You can turn of the SoftAP too. At default it starts automatically. The command is WiFi.softAPdisconnect()

I don't think the issue has to do with WiFi at all.  I have completely stripped down the code to just have it go into Deep Sleep and I get the same behavior.

@Brian, try setAutoConnect(false). the automatic connection starts before the sketch


text:
Problem interfacing CR95HF with Arduino Uno
I am interfacing a CR95HF with an Arduino to detect NFC tags. I have taken the code from this link as reference. I am able to get the response to the IDN command, and also set the protocol (ISO/IEC 14443-A). But the tag is not detected. What should I do to detect the tag?

is the tag functional?

yes tag is working ,I have tested with other nfc reader


text:
Distance Measurement - between 6 points, individually moving in (almost) any direction within 1m
I'm trying to find a solution for a given task in a problem I want to solve.
Assume I have 6 individual Points in a 3D environment of about 1m³. Each point will be able to change position (almost) freely.
Is there a way I can get the information of which distance each point is to any of the remaining 5 points?
Background Idea for understanding: Say its 2 wooden triangles (one of those points on each angle) and I need to calculate how far and in which direction one is moving from or towards the other.
By comparing all those distances, direction and step-width may be easily calculated.
Are there like "coded" distance-sensors so they don't mix their signals?
Any thoughts highly appreciated.

Not a very easy task. A distance sensor always points in 1 direction, so you would need to target each individual other point with one distance sensor, while it is moving. I would think, at this point it is easier to use 2 cameras (pointed from different angles to the space) and computer vision to calculate their positions and thus get their distances.

thanks chris,
i was afraid to hear that ;)

Camera would have to be mounted on one of the triangles since they may be positioned anywhere with no outer bounds.  Only limit is that they always stay together within a given maximum distance from each other.

You may try to implement some kind of ultrasonic transponders. The
emitter sends a code addressing a specific receiver. Upon recognizing
its address, the receiver replies after a short, fixed delay. The
emitter measures the time it took the response to reach it, and from
there computes the distance.
You may need some kind of omnidirectional transducers (e.g. this
models) if you want the measurement to work in any
direction. And also a protocol to avoid several emitters talking at the
same time.
This seems to me like a very complex project though.

addressing the receiver is going into the direction I was looking for. I only knew of those sending like a small angled beam and waiting for its reflection. I didn't know of a possibility to address a specific receiver or better to have a receiver only answer to a specific emitter instead of whatever is calling.
As soon as I can locally separate emitter and receiver and have the receiver only respond to that one specific request, I'm fine to go on from here. Thank you.

The vertices of two (wooden) triangles already constrains the problem - in a positive way - since the inter-point distances of each triangle's vertices is constant. If they were 6 individual, free-floating points, the job would be that much more complex -- 30 unknown distances (each point to each other point), instead of only 18 (each vertex to each of 3 vertices on the other triangle). That's the math part.
The technology part - what kind of sensors - will need more specifics to answer. For instance, ultrasonic sensors may have an interference problem with wooden triangles drifting about. Light and radar may have visibility issues - i.e., can't see certain of the points, depending on the physical shape and implementation of the drifting objects.

okay, lets change triangles to shoes on feet. Lets say I want to keep track of tip to tip, heel to heel, shaft to shaft distances. Does that make it easier to find the right sensors? Sensors will most likely stay within visibility to each other as being mounted on the inner side and turns usually wont exceed 70-80° angles.

You counted each unknown twice: the distance from A to B is the same as the distance from B to A. Six free points is 15 distances, two triangles is 9 distances.

@EdgarBonet: Right you are - missed that.


text:
Unable to compile SimpleTimer code - Exit status 1
I downloaded the SimpleTimer library from the Arduino's library manager and navigated to Arduino Playground website for some sample code for testing - SimpleTimer - Arduino Playground. After copying the following code into the Arduino IDE:
#include <SimpleTimer.h>

// the timer object
SimpleTimer timer;

// a function to be executed periodically
void repeatMe() {
    Serial.print("Uptime (s): ");
    Serial.println(millis() / 1000);
}

void setup() {
    Serial.begin(9600);
    timer.setInterval(1000, repeatMe);
}

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

I receive the following error:
exit status 1
no matching function for call to 'SimpleTimer::setInterval(int, void (&)())'

Please help me out here as I am doing everything according to the instructions given in the arduino playground page of SimpleTimer.

Did you install the library?

int setInterval(long d, timer_callback f) the function needs a long value, you're trying to pass an integer.

There are quite a few Arduino libraries called “SimpleTimer”. According
to arduinolibraries.info, the one you get through the
library manager is Alexander Kiryanenko's SimpleTimer. The
one described in Arduino Playground is Marcello Romani's
version. You should try the examples that come with the
specific library you install.


text:
How to declare a pointer for arduino neopixels library so I can set it up in the setup function with dynamic variables?
I am using NeoPixel strips, and I want to be able to declare a pointer to them, but not initialize them until the setup function (because they will initialize with certain variables only made available in setup).
For simpler data types, I am just doing:
int totalNumColors = 4; //number of colors user can cycle through`
uint32_t* colorArray = new uint32_t[totalNumColors];
void setup() {
  for (int i=0;i<totalNumColors;i++){
    colorArray[i] = totalColorArray[i];
  }
}

How do I do this for NeoPixel strip intializers? I tried:
Adafruit_NeoPixel* pixels = new Adafruit_Neopixel;`

but I get the error:
expected type-specifier before 'adafruit neopixel'

I am trying to wrap my head around using pointers for Neopixels -- I am not a C expert but trying to learn as I go. I went over some documentation (read some sites, watched some YouTube videos) and understand the basics of pointers and I am able to use then in more basic ways. But I am confused how you use pointers when setting up Neopixels. Would you mind sharing some of your code so I can get an idea how the Neopixels are setup and how you are using them? I would greatly appreciate it. David

You can assign the pointer to NULL, and in the setup function give it a value. Note you have to add () for the arguments, even if there are none like in this case. Also you have to include the library (but probably you did but not added in your question).
#include "Adafruit_NeoPixel.h"

Adafruit_NeoPixel* pixels = NULL;

void setup()
{
  pixels = new Adafruit_NeoPixel();
}

I did include the library, but thanks, yes - this is exactly what I was looking to do.

Good luck with your project.


text:
Pseudo-code of a program
I have written a code but I am facing a problem in pseudo-code that I am not able to change this code, so can anyone help me in translating the Arduino IDE program code to pseudo-code?
#define BLYNK_PRINT Serial
#include <SPI.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <SimpleTimer.h>
#include<DHT.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
char auth[] = "py0oKurvtk_Rv2GGkKtghpKqlxLQug8F";
char ssid[] = "Hostal1";
char pass[] = "shakajutt7867";
DHT dht(D4, DHT11);
SimpleTimer timer;
int Relay = D5;
int PIR = D3;
void sendSensor()
{
  float humi = dht.readHumidity();
  float temp = dht.readTemperature();
  int value = digitalRead(PIR);
  if (value == 1)
  {
  digitalWrite(Relay, HIGH);
  Serial.print("Detected");
  Serial.print('\n');
  lcd.setCursor(0,0);
  lcd.print("PIR = Detected");
  lcd.setCursor(0,1);
  lcd.print("T: ");
  lcd.print(temp);
  lcd.setCursor(7,1);
  lcd.print(" H:");
  lcd.print(humi);

  }
  else if (value== 0)
  {
    digitalWrite(Relay, LOW);
    Serial.print("Not Detected");
    Serial.print('\n');
  lcd.setCursor(0,0);
  lcd.print("PIR = Not Det");
  lcd.setCursor(0,1);
  lcd.print("T:");
  lcd.print(temp);
  lcd.setCursor(7,1);
  lcd.print(" H:");
  lcd.print(humi);

  }
  Blynk.virtualWrite(V7, value);
  Blynk.virtualWrite(V5, humi);
  Blynk.virtualWrite(V6, temp);
  delay(1500);
}
void setup()
{
  pinMode(Relay, OUTPUT);
  pinMode(PIR, INPUT);
  digitalWrite(Relay,LOW);
  Serial.begin(115200);
  Blynk.begin(auth, ssid, pass);
  dht.begin();
  lcd.begin(16,2);
  lcd.init();
  lcd.clear();
  lcd.backlight();
  lcd.setCursor(0,0);
  timer.setInterval(1000L, sendSensor);
}
void loop()
{

  Blynk.run();
  timer.run();
}

What exactly is your problem in writing this as pseudo code? Do you understand, what the code does (since this is essential to write it as pseudo code)?

what do you mean by pseudo-code?

You can format it by selecting the code and pressing ctrl-k

Although I know how the program line by line but how to write #INCLUDE libraries and there are many lines that I can't explain /?

Michel Keijzers ........... I couldn't get your point? How? Although ctrl+k doesn't work.

So it is more about understanding the program? If yes, then I can write an answer. What do you mean with "how to write #include libraries"? Pseudo code doesn't need any includes, since it is not compilable anyway. You just write, what the code should do on a level of higher abstraction.

"Pseudo-code" isn't a programming language. It is just a term that we use when we write code that looks like code but can't be compiled, because it's half-English, half-code. You write pseudo code when you want to communicate to another human how code is supposed to work without getting bogged down in the details.


text:
Using digital rotary encoders for HID input using the Joystick library
I have been working on a small switch panel for flight sims, but I wanted to use  the CYT1100 Digital Rotary encoders to move instruments in-game. I have the code  set up to press a certain joystick button for each pulse. The code seems to work fine, but I might have some issues with hardware.
Components:

Arduino Micro
CYT1100 Digital Rotary Encoders
Acer Aspire E5 (Windows 10)

I get serial monitor outputs when I move the board, but the rotary encoders aren't plugged in. The values are around 2 to -2 but don't change depending on the encoders. The joystick buttons are getting almost randomly pressed with no certain pattern. I was wondering if anyone has had issues like this in the past or if I'm missing something.
Here's my code:
#include <Joystick.h>

#define outputA 2
#define outputB 3

int counter = 0;
int aState;
int aLastState;

void setup() {
  Joystick.begin();
  pinMode(2, INPUT);
  pinMode(3, INPUT);
}

void loop() {
  aState = digitalRead(outputA);
  if (aState != aLastState) {
    if (digitalRead(outputB) != aState) {      // Clockwise
      Joystick.pressButton(1);
      delay(10);
      Joystick.releaseButton(1);
      counter ++;
    } else {                   // Counterclockwise
      Joystick.pressButton(2);
      delay(10);
      Joystick.releaseButton(2);
      counter --;
    }
    Serial.print("Counter:  ");
    Serial.println(counter);
  }
  aLastState = aState;
}

you have it partially backward ... wait for a transition in outputA in one direction only, either a rising edge or falling edge, but not both ... when transition occurs, read value of outputB and press joystick button depending on the value

Sorry I'm sort of new to C++ but not programming in general, so I the logic. I wait for a change in outputA, and directly after, if outputB is not down, I have a falling edge and vice versa?

no ... the rotary encoder probably has two outputs that are 90 degrees apart  ... read the state of B everytime A changes from LOW to HIGH .... A always changes in middle of B ... http://www.bristolwatch.com/ele2/img/Encoder.jpg ........ it has nothing to do with C++

Okay thanks! I'll try that and it should fix some issues.

I updated the code... Does that look about right?

definitely not ... the code does not check for a transition in the signal ... your previous code did ... it acted on both transitions instead of only one