text:
Why delay of more than 64 millisecond stops the servo motor from rotating? I am not using "Servo.h" instead i am just managing the length of pulse
The code I used was this
int servo = 5;
int angle;

void setup() {

  pinMode(servo, OUTPUT);

}

void loop() {

  for (angle = 0;angle<180;angle++){

    digitalWrite(servo, HIGH);
    delayMicroseconds((angle*(11))+365);
    digitalWrite(servo,LOW);
    delay(65);
  }

  for (angle = 179;angle>0;angle--){

    digitalWrite(servo, HIGH);
    delayMicroseconds((angle*(11))+650);
    digitalWrite(servo,LOW);
    delay(65);

}
}

as u can see I have set the delay after a particular step to be 65 milliseconds but it won't work, any delay greater than 64 milliseconds do not work and the motor just stops rotating.
what is the reason for this??

Go here:  https://www.arduino.cc/reference/en/language/functions/time/delaymicroseconds/  and read the second sentence.

A servo motor doesn't just require a single pulse to send it to a specific angle. It requires a constant stream of pulses at the right frequency for it to track what the angle should be.
By sending one pulse you're just hinting where it might like to go to, then stopping. It's never going to get there, unless you keep sending those pulses fast enough.
Also if you don't send pulses then the servo will go into a "low power sleep mode" where it's not actively driving the output and it will go "floppy" where you can move the servo by hand.
Typically you need to send pulses at about 50Hz, which is one pulse every 20ms. Many servos will be more forgiving, but if you send too slowly they just won't know what to do.
If you want to be handling the pulses yourself then you need to do it in the right way.  That is:

Send a pulse of your desired length
Delay for 20ms minus your desired length
Go to 1 until your desired elapsed time has been reached.

For example:
for (angle = 0; angle<180; angle++){
  uint32_t ts = millis();
  while ((millis() - ts) < 100) { // 100ms delay
    digitalWrite(servo, HIGH);
    delayMicroseconds((angle * 11) + 650);
    digitalWrite(servo,LOW);
    delayMicroseconds(20000 - ((angle * 11) + 650));
  }
}

That won't be exact, owing to the latency of the loop instructions, but it will be close enough.


text:
Instantiate class in the constructor rather in the top end?
Is there a way to define class variables in the constructor or in a method rather than at the top of the document?
I have the following code in my custom library:
#include "DHT.h"

// DHT settings.
#define DHTPIN 7 // Digital pin connected to the DHT sensor.
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor.

void DhtLib::doSomeStuff() {
  dht.begin();
  float temp = dht.readTemperature();
  ...
}

I would like to be able to set the pins with a function. But for this to work I have to find a way to define the dht variable in a different place than at the top of the document within the // DHT settings.. Best would be in a method such as:
void DhtLib::begin(int dhtPin) {
  DHT dht(dhtPin, DHTTYPE);
}

This works, but only within this function. I need this to be accessible in the entire document, not just a single function.
How can I achieve that?
EDIT 1:
Entire code of the custom DhtLibrary.h file:
#ifndef DhtLibrary_h
#define DhtLibrary_h

#if (ARDUINO >= 100)
  #include "Arduino.h"
#else
  #include "WProgram.h"
#endif

class DhtLib {
  private:
    DHT dht;
    float readTemperatureFromDHT();
    float readHumidityFromDHT();
    float calculateHeatIndex(float temperature, float humidity);

  public:
    // Constructor.
    DhtLib(int dhtPin) : dht(dhtPin, DHT22) {}

    // Methods.
    void begin();
    String getHumiTempJson();
};

#endif

The error with this above code is:
In file included from /home/myuser/Documents/Codes/temperature-control/slave2-arduino/slave2-arduino.ino:2:0:
DhtLibrary.h:12:5: error: 'DHT' does not name a type
     DHT dht;

There's numerous ways of doing this. The best is probably to have a DHT object as a class property and set it up with an initializer list:
#include "DHT.h"

class DhtLib {
    private:
        DHT dht;

    public:
        DhtLib(int dhtPin) : dht(dhtPin, DHT22) {}
        void begin();
        void doSomeStuff();
};

void DhtLib::begin() {
    dht.begin();
}

void DhtLib::doSomeStuff() {
    float temp = dht.readTemperature();
}

DhtLib thing(7);

void setup() {
    thing.begin();
}

void loop() {
    thing.doSomeStuff();
}

Thanks for the quick answer! Can you please elaborate the part DhtLib(int dhtPin) : dht(dhtPin, DHT22) {}? I don't quite understand the parts of what it does exactly. Is that still a constructor definition? And don't I have to also declare the DHT dht; from the DhtLibrary.h in the DhtLibrary.cpp file?

That is the "initializer list". Yes it's the constructor. When you construct it passes the variables up to the DHT object you set up in the private section. The DHT dht is declared inside the DhtLib class.

Ok, got it. Well, if I place the DHT dht; in the private: section the compiler is unhappy, giving the error DhtLibrary.h:20:5: error: 'DHT' does not name a type. It expects DHT dht(DHTPIN, DHTTYPE);.

Which library are you using? The one I have here works fine.

I use the DHT sensor library by Adafruit Version 1.3.10.. Which one are you using?

Can you link to it?

Well, the More info link points to this url: https://github.com/adafruit/DHT-sensor-library

Compiles fine for me with that library.

I don't quite get where I would do the error. I put my entire code into the EDIT 1 in my post above. Do you see any error with that?

You have to include the DHT.h library in your header so it knows what a DHT is.

You said that you use another library for the DHT. Which one is it? Is there any particular reason you use a different library for the DHT?

I just happened to have the Grove library on hand that uses DHT.h for the header name, so I just used it. No other reason.

Alright, thanks for the info and for your help!

Say I had another variable that I wanted to take, i.e. DhtLib(int dhtPin, int anotherVariable) : dht(dhtPin, DHT22) {}, how could I make use of it? Having defined private: int privateVariable; in the DhtLibrary.h I tried DhtLib(int dhtPin, int anotherVariable) : dht(dhtPin, DHT22) {privateVariable = anotherVariable}, but I get the error error: 'privateVariable' was not declared in this scope. How can I set privateVariable with anotherVariable?

You would usually just add it to the initializer list: DhtLib(int dhtPin, int anotherVariable) : dht(dhtPin, DHT22), privateVariable(anotherVariable) {}

Ok, so what are the curled-braces for? Is it possible to put logic into them?

Yes, that's just an empty function body where you would put the code for the constructor if you should ever want any.

Do you have any link for a description to this particular syntax?

https://en.cppreference.com/w/cpp/language/constructor

Thanks a lot! You've been a great help!

source: Stack Exchange

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

sort: votes


text:
Is this circuit risky for an Arduino Uno?
I will show a connection diagram between my Arduino Uno and a DSC HS2032 panel (alarm system).
The DSC panel uses 12V and I don't know the voltage fluctuation.
The yellow and green are RX/TX ports.
Github file: https://github.com/taligentx/dscKeybusInterface/blob/master/examples/Arduino/KeybusReader/KeybusReader.ino
DIAGRAM (I assume the vertical "+--+" means a simple "OR" connection):
  DSC Aux(+) --- Arduino Vin pin

  DSC Aux(-) --- Arduino Ground

                                 +--- dscClockPin (Arduino Uno: 2,3)
  DSC Yellow --- 15k ohm res ----|
                                 +--- 10k ohm resistor --- Ground

                                 +--- dscReadPin (Arduino Uno: 2-12)
  DSC Green ---- 15k ohm res ----|
                                 +--- 10k ohm resistor --- Ground

I need to make sure this diagram is SAFE, and will not overheat or do something risky to my Arduino.
Why is this circuit not going to burn my Arduino if it is using 12V?

There is a schematic editor built in to the question editor, you know... No need for dodgy ASCII art...

The vertical +-+ is not an or, but an and. You need to connect both. These are pulldown resistors

@Majenko I also think that dodgy ASCII art is disgusting, but I took it "as it is" from the Github file which I don't own.

That circuit is fine as long as the input signals don't go above 12.5V.  You can protect it further by adding a 5.2V zener diode across each of the signals as they enter the Arduino:

simulate this circuit – Schematic created using CircuitLab

Why is this circuit not going to burn my Arduino if it is using 12V?

Because it uses a voltage divider to reduce the voltage to 4.8V.

This is perfect. May I connect the grounds into the Arduino's ground? Sorry about my lack of knowledge and thank you.

Not only "may" you - you must. https://majenko.co.uk/blog/importance-sharing-grounds

Yes, adding a zener diode will offer further protection to your Arduino, and is a very good idea. (Voted). If I read the specs right that 1N4733A diode can dissipate a watt of power? (https://www.jameco.com/Jameco/Products/ProdDS/36097VIS.pdf)

No idea, that's just the default in the editor.

The Arduino also has clamping diodes inside the MCU, that will clamp the voltage to VCC (+0.6V).

Yeah, but they can only take about 1mA before burning out. Should be fine at 12V with the 15kΩ resistor if the ground should get disconnected, but it's still abusing the diodes.

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


text:
Strange Arduino Serial Behavior
I have a quirky question today.
I have an Arduino MEGA 2560 with a very simple setup. It's connected to my pc over usb, and has one device connected on its onboard TX/RX2 port group. Whenever I open the COM port on my pc I see a short spike in voltage on the TX2 pin. An analogous behavior happens on even the simplest sketches so I don't think it's the library I'm using to talk to this device.
With the sketch below instead of a short spike in voltage, the TX2 line stays high and when the pc's COM port is opened that TX2 line drops to 0v for maybe a half second.
Not super relevant info about device
It's a Noritake GU140X32F-7000 display. The mfg website doesn't list it's model directly but the
info on the 'B' variant, and it's supplied AVR code, work just fine.

MFG Website for this model>> https://noritake-vfd.com/gu140x32f-7000b.aspx
Code Library>> https://www.noritake-elec.com/codeLibrary.php#gu7000

Relevant bare-minimum code to see this effect on an oscilloscope connected
GRD <-> AVR Ground, POS <-> Pin16(TX2)
void setup() {
  Serial.begin(115200); // Connection to computer
  Serial2.begin(38400); // Connection to TX2 pin 16
  Serial2.write('akjlahsdkjahsdkjlhasdkjhaskldjhaksjhd');
}

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

What happens, which I don't want happening, is after I've had the Arduino draw to the Noritake screen, and I open or reopen the COM port from my pc to the Arduino, the screen blanks itself. Doesn't matter if I use PUTTY, python's serial library with
ser = serial.Serial('COM4', 115200, R timeout=0,parity=serial.PARITY_NONE, rtscts=1)
or Serial Port Monitor's trial version from https://www.com-port-monitoring.com/ via the send dialog - it happens either way.
Especially weird is I don't see data going over this COM port in the Serial Monitor software when the COM port is opened and yet my oscilloscope (fairly crappy DSO138) catches a spike in voltage happen the moment this serial line is opened from my pc. When I use the Noritake library the TX line is normally low when there's no data, whereas the Arduino built in Serial2 line is normally high until there's data. Then when I connect it goes low for about a half second. The code Noritake uses to communicate over this serial line is a bit odd, not actually using the Serial or Stream built in classes, instead opting to write data manually to this port and only including these two external libraries.
#include <avr/pgmspace.h>
#include <util/delay_basic.h>

What causes Serial2 to go low when my PC opens the COM port to Serial on my Arduino? What can I do to prevent it from writing to Serial2?

You're probably over-researching things and finding a problem that isn't a problem. The simplest reason: when you open serial the Arduino resets and your sketch runs from the start again.

Ok this answered my question. Thank you! Do you want to get credit for it or should I answer this thread myself?

Why would we delete this question? I suggest @Majenko post his comment as an answer and the answer get selected. Don't delete valuable debugging info. like this from the internet.

Interrobang, you can also answer your own question, and then select it as the right answer in 2 days. I suggest keeping the question and answering it yourself, quoting Majenko.

I'm going to wait the two days, thanks Gabriel!

As to why this happens: connecting to the Arduino with the built in USB port would wipe the display because the Arduino would reset and re-initiate the display initialization routine. The spike in current was actually the initialization signal. In the bare minimum sketch the signal going high, low, then back high was again due to the Arduino resetting.
The solution I'm going with is just changing how I connect to my Arduino with python by adding dsrdtr = 1 to my serial declaration. I tested this and my Arduino no longer resets, and uploading sketches is not impacted.
# Python 3.7.5
import serial
ser = serial.Serial('COM4', 115200, timeout=0, parity=serial.PARITY_NONE,
                   rtscts=1, dsrdtr = 1)

I removed the part with links to mostly obsolete and not applicable information about auto-reset. Leonardo is very different in this and the current Uno/Mega boards have pads which can be cut to disable auto-reset and eventually connected again with solder. the solution for Python is nice. upvote for this


text:
How to Fix mouse cursor lag on voice & movement based head mouse in wireless setting?
For my head mouse project which is based on the voice recognition module V3.1 for left click, double click, right-click operations, I am facing a problem. I am using 433Mhz Radio Frequency one-way Transceiver for sending data. When I use the MPU 6050 accelerometer and gyroscope for mouse cursor movement and the voice recognition module together on only one Arduino board, the mouse cursor moves smoothly and the voice commands work smoothly. But when I use the 433Mhz RF one-way transmitter for one Arduino board to calculate the mouse movement and figure out the voice command to send it in a wireless manner and receive the values and voice commands using the receiver module of the rf433 Mhz, the mouse cursor starts to lag. It doesn't move smoothly. Please help me solve the problem. The code and circuit diagram are given below:

Transmitter.ino
  /*433 MHz RF Module Transmitter Demonstration 1
  RF-Xmit-Demo-1.ino
  Demonstrates 433 MHz RF Transmitter Module
  Use with Receiver Demonstration 1

  DroneBot Workshop 2018
  https://dronebotworkshop.com
*/

// Include RadioHead Amplitude Shift Keying Library
#include <RH_ASK.h>
// Include dependant SPI Library
#include <SPI.h>
#include <SoftwareSerial.h>
#include "VoiceRecognitionV3.h"
#include <Mouse.h>
#include <Wire.h>
#include <I2Cdev.h>
#include <MPU6050.h>

VR myVR(8,9);    // 9:RX 8:TX

uint8_t records[7]; // save record
uint8_t buf[64];

MPU6050 mpu;
int16_t ax, ay, az, gx, gy, gz, oax, oay, oaz, ogx, ogy, ogz;
int16_t vx, vy;
//
#define leftRecord    (0)
#define rightRecord   (1)
#define doubleRecord  (2)

/**
  @brief   Print signature, if the character is invisible,
           print hexible value instead.
  @param   buf     --> command length
           len     --> number of parameters
*/
void printSignature(uint8_t *buf, int len)
{
  int i;
  for(i=0; i<len; i++){
    if(buf[i]>0x19 && buf[i]<0x7F){
      Serial.write(buf[i]);
    }
    else{
      Serial.print("[");
      Serial.print(buf[i], HEX);
      Serial.print("]aurav");
    }
  }
}

/**
  @brief   Print signature, if the character is invisible,
           print hexible value instead.
  @param   buf  -->  VR module return value when voice is recognized.
             buf[0]  -->  Group mode(FF: None Group, 0x8n: User, 0x0n:System
             buf[1]  -->  number of record which is recognized.
             buf[2]  -->  Recognizer index(position) value of the recognized record.
             buf[3]  -->  Signature length
             buf[4]~buf[n] --> Signature
*/
void printVR(uint8_t *buf)
{
  Serial.println("VR Index\tGroup\tRecordNum\tSignature");
  Serial.print(buf[2], DEC);
  Serial.print("\t\t");

  if(buf[0] == 0xFF){
    Serial.print("NONE");
  }
  else if(buf[0]&0x80){
    Serial.print("UG ");
    Serial.print(buf[0]&(~0x80), DEC);
  }
  else{
    Serial.print("SG ");
    Serial.print(buf[0], DEC);
  }
  Serial.print("\t");

  Serial.print(buf[1], DEC);
  Serial.print("\t\t");
  if(buf[3]>0){
    printSignature(buf+4, buf[3]);
  }
  else{
    Serial.print("NONE");
  }
  Serial.println("\r\n");
}

struct dataStruct{
  int16_t moveX;
  int16_t moveY;
  int flag;
  }myData;

byte tx_buf[sizeof(myData)] = {0};

// Create Amplitude Shift Keying Object
RH_ASK rf_driver;
int flag = 15;

void setup()
{

   /** initialize */

  Wire.begin();
  mpu.initialize();
  if (!mpu.testConnection()) {
    while (1);
    }

  myVR.begin(9600);
  Serial.begin(115200);
  Serial.println("Elechouse Voice Recognition V3 Module\r\nControl LED sample");

  if(myVR.clear() == 0){
    Serial.println("Recognizer cleared.");
  }else{
    Serial.println("Not find VoiceRecognitionModule.");
    Serial.println("Please check connection and restart Arduino.");
    while(1);
  }

  if(myVR.load((uint8_t)leftRecord) >= 0){
    Serial.println("leftRecord loaded");
  }

  if(myVR.load((uint8_t)rightRecord) >= 0){
    Serial.println("rightRecord loaded");
  }

  if(myVR.load((uint8_t)doubleRecord) >= 0){
    Serial.println("doubleRecord loaded");
  }

    // Initialize ASK Object
    rf_driver.init();
    if(!rf_driver.init()) Serial.println("Init failed");

}

void loop()
{

  int ret;

  ret = myVR.recognize(buf, 50);
    const char *msg = "Welcome to the Workshop!";

  if(ret>0){

  switch(buf[1]){

    case leftRecord:
    flag = 0;
    break;

    case rightRecord:
    flag = 1;
    break;

    case doubleRecord:
    flag = 2;
    break;

    default:
    flag=3;
    Serial.println("Record function undefined");
    break;
    }
    /** voice recognized */
    printVR(buf);
  }

  mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

  oax = ax+72;
  oay = ay-382;
  oaz = az-505;
  ogx = gx+99;
  ogy = gy-29;
  ogz = gz-50;

  vx = gx/200;
  vy = -gz/200;
  myData.moveX = vx;
  myData.moveY = vy;
  myData.flag = flag;

  memcpy(tx_buf, &myData, sizeof(myData));
  byte bufSize = sizeof(myData);
  Serial.println("movX\tmovY\tmovZ\toax\toay\toaz\togx\togy\togz\tvx\tvy:");
  Serial.print(myData.moveX, HEX);
  Serial.print("\t");
  Serial.print(myData.moveY, HEX);
  Serial.print("\t");
  Serial.print(myData.flag, HEX);
  Serial.print("\t");
  Serial.print(oax, DEC);
  Serial.print("\t");
  Serial.print(oay, DEC);
  Serial.print("\t");
  Serial.print(oaz, DEC);
  Serial.print("\t");
  Serial.print(ogx, DEC);
  Serial.print("\t");
  Serial.print(ogy, DEC);
  Serial.print("\t");
  Serial.print(ogz, DEC);
  Serial.print("\t");
  Serial.print(vx, HEX);
  Serial.print("\t");
  Serial.println(vy, HEX);

  rf_driver.printBuffer("Buffer values [vx, vy, status flag respectively]: ", tx_buf, bufSize); //each value is 16 bit. and serail monitor will show in 8 + 8 = 16 bit format
    rf_driver.send((uint8_t *)tx_buf, bufSize);
    //Serial.println();
    rf_driver.waitPacketSent();

    flag = 15;
    delay(1);

}

Receiver.ino
// Include RadioHead Amplitude Shift Keying Library
#include <RH_ASK.h>
// Include dependant SPI Library
#include <SPI.h>
#include <Mouse.h>
#include <Wire.h>
#include <I2Cdev.h>
#include <MPU6050.h>

#define leftRecord    (0)
#define rightRecord   (1)
#define doubleRecord  (2)
// Create Amplitude Shift Keying Object
RH_ASK rf_driver;

struct dataStruct{
  int moveX, moveY, flag;
  }myData;

void setup()
{
    // Initialize ASK Object
    Wire.begin();
    rf_driver.init();
    // Setup Serial Monitor
    Serial.begin(115200);
    if(!rf_driver.init()) Serial.println("Init failed");
}

void loop()
{
    // Set buffer to size of expected message
    uint8_t buf[RH_ASK_MAX_MESSAGE_LEN];
    uint8_t buflen = sizeof(buf);
    // Check if received packet is correct size
    if (rf_driver.recv(buf, &buflen))
    {
      int i;

      // Message with a good checksum received, dump it.
  rf_driver.printBuffer("Got:", buf, buflen);
        memcpy(&myData, buf, sizeof(myData));
        Serial.println("");

        Serial.print("moveX: ");
        Serial.print(myData.moveX);

        Serial.print("  moveY: ");
        Serial.print(myData.moveY);

        Serial.print("  Command Status: ");
        Serial.print(myData.flag);

      // Message received with valid checksum
      Serial.print(" Message Received: ");
      Serial.println((char*)buf);

      Mouse.move(myData.moveX, myData.moveY);

  if(myData.flag!=15){

  switch(myData.flag){

    case leftRecord:
    Mouse.click(MOUSE_LEFT);
    delay(10);
    break;

    case rightRecord:
    Mouse.click(MOUSE_RIGHT);
    delay(10);
    break;

    case doubleRecord:
    Mouse.click(MOUSE_LEFT);
    Mouse.click(MOUSE_LEFT);
    delay(10);
    break;
    default:
    break;
    }

    }
}
}

In general, you want to stream some data. and the mouse lag is one of the main obstacles in data streams; lag. so many classic causes such as buffer over-runs and timing problems come to mind.
The cheap 433MHz modules are not a good choice in case of streams. they lack any robust protocol, ACKing and security.
I would do this things to make it better:

use a better transmitter. maybe the cheap nRF24L01 ones.
use a bigger buffer
use two threads on the transmitter side. (e.g. use something like this, but two threads). one thread to collect data and writing it to a buffer, the next one to send data using nrf. furtunately, the nRF24 can send up to 32Bytes in one buffer transmission and the SPI interface is fast enough to fill it's buffer as quick as possible.
if you have to, use another thread to calculate movements from MPU6050. so you don't have to read it continuouesly and send all that raw data to reciever. you may use some interpolation on the receiver side though.

But when I use the nRF24L01 the Arduino turns on and then turns off. I've tried this with the Arduino Leonardo as well as the Micro. How can I fix this? It also causes power surges and overheating occassionally.

make sure the power pins are correct. this problem is mainly due to VCC/GND pins being swaped


text:
Write a Struct using ArduinoBLE library
Hello I'm trying to send some Structs such as:
typedef struct __attribute__ ((__packed__)) myohw_command_set_mode {
    myohw_command_header_t header; ///< command == myohw_command_set_mode. payload_size = 3.
    uint8_t emg_mode;              ///< EMG sensor mode. See myohw_emg_mode_t.
    uint8_t imu_mode;              ///< IMU mode. See myohw_imu_mode_t.
    uint8_t classifier_mode;       ///< Classifier mode. See myohw_classifier_mode_t.
} myohw_command_set_mode_t;

To another device via BLE using the Arduino BLE library.
I have the services and characteristics all set up correctly.
My problem is that arduino BLE .writeValue() function expects some specific formats and i'm not quite sure the best way to convert this struct to one of them.
  int writeValue(const uint8_t value[], int length);
  int writeValue(const void* value, int length);
  int writeValue(const char* value);
  int writeValue(uint8_t value);
  int writeValue(int8_t value);
  int writeValue(uint16_t value);
  int writeValue(int16_t value);
  int writeValue(uint32_t value);
  int writeValue(int32_t value);

What format should i use? And what is the best way to cast the Struct to the format?
Thanks,

What format should i use?

int writeValue(const uint8_t value[], int length);

And what is the best way to cast the Struct to the format?

writeValue((uint8_t *)&myStruct, sizeof(myStruct));

Thank you for the help!


text:
I'm getting an error while uploading my code to esp8266 via an arduino (FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error)))
Arduino: 1.8.13 (Windows 10), Board: "Generic ESP8266 Module, 80 MHz, Flash, Legacy (new can return nullptr), All SSL ciphers (most compatible), dtr (aka nodemcu), 26 MHz, 40MHz, DOUT (compatible), 1MB (FS:64KB OTA:~470KB), 2, nonos-sdk 2.2.1+100 (190703), v2 Lower Memory, Disabled, None, Only Sketch, 115200"

Executable segment sizes:

IROM   : 228624          - code in flash         (default or ICACHE_FLASH_ATTR)

IRAM   : 26756   / 32768 - code in IRAM          (ICACHE_RAM_ATTR, ISRs...)

DATA   : 1248  )         - initialized variables (global, static) in RAM/HEAP

RODATA : 688   ) / 81920 - constants             (global, static) in RAM/HEAP

BSS    : 24880 )         - zeroed variables      (global, static) in RAM/HEAP

Sketch uses 257316 bytes (26%) of program storage space. Maximum is 958448 bytes.

Global variables use 26816 bytes (32%) of dynamic memory, leaving 55104 bytes for local variables. Maximum is 81920 bytes.

esptool.py v2.8

Serial port COM3

Connecting........_____....._____....._____....._____....._____....._____.....____Traceback (most recent call last):

  File "C:\Users\Reghunaath A A\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.2/tools/upload.py", line 65, in <module>

    esptool.main(cmdline)

  File "C:/Users/Reghunaath A A/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.7.2/tools/esptool\esptool.py", line 2890, in main

    esp.connect(args.before)

  File "C:/Users/Reghunaath A A/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.7.2/tools/esptool\esptool.py", line 483, in connect

    raise FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error))

esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header

esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header

_

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

I'm getting the above stated error message while I'm trying to upload a code to esp8266 via an arduino(I've removed the ATMEGA32 from my arduino). Sometimes it gets uploaded without a problem(very rarely) but mostly the upload fails.
I connected rx of arduino to rx of esp and same for tx too. 3.3v of arduino to enable and vcc of esp. graund of arduino to ground of esp and gpio0.
The code that I'm trying to upload:
void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forevervoid lop() {
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
  // but actually the LED is on; this is because
  // it is active low on the ESP-01)
  delay(1000);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}

My settings:

EDIT: Also, I want to add one more thing when the message box says "Connecting........_____....._" during that time if i reset the esp the code starts uploading

@jsotola bruh half of my question is missing. Let me update it.

@jsotola please check it out now.

do you put the esp8266 in flashing mode?

@Juraj yes I connected the esp0 to groung

io 0 to gnd, then reset?

@Juraj I left reset unconnected

@Juraj yes after connecting io 0 to ground i do a reset by unplugging and plugging back the groud of the esp8266

add to question the module you have, how did you wire it and how do you put it in flashing mode

@Juraj I aded the wiring info to the question and I want to share with you one more thing that I observed recently, when the message box says "Connecting........_____....._" during that time if i reset the esp the code starts uploading

to put the esp8266 in flashing mode, io 0 must be pulled-down at boot (power up or reset) simply to tell the bootloader to start in flashing mode. the bootloader checks if the pin is HIGH or LOW. no magic. for normal run io 0 must be pulled up.

You need to set esp 8266 to flash mode.
Please connect en PIN to Gnd pin.
Then flash again.


text:
Wemos D1 mini and JSN-SR04T-2.0: Type of power supply affects the sensor readings
Pretty similar to what is described here I have the strange problem that my sensor readings are affected by the type of power supply I use.
Whenever I connect my D1 mini through USB with laptop everything works fine. The readings make sense and are quite accurate.
But as soon as I disconnect it from the laptop and use a USB power supply (I tested different ones) the readings do not make sense anymore.
I also tried to apply the sketch to a NodeMCU board. The results are the same. So I assume it has something to do with either the sensor or the ESP 12E.
Any suggestions?

How are you powering the sensor?

The sensor is powered by the 3.3V output of the Wemos/NodeMCU Board. But I also tested it with the 5V output. Always with the same results.

I'll bet your laptop's charger has 3 prongs that plug into the wall, but your USB power supplies only have 2 prongs. If so, try grounding to earth.

Easier said than done in this case :) But I'll try. Sounds like a good idea.

Try a different supply or computer, it sounds like that one has a lot of ripple and or noise on it.  Not all USB power supplies are clean and some do not have much filtering.


text:
NodeMCU ESP8266
I am doing a project and using NodeMCU ESP8266. My project includes sensors for UART, I2C and 4 interrupts. I need to read the data from these sensors and get these data via microUSB in real time. While reading about NodeMCU ESP8266 there are so many points that came across and have certain questions.

Do flash uses GPIO6-11 all the time? Can we use any of these pins for our purpose? What if someone needs an SPI communication, as these pins are locked by flash.
Can I use GPIO-0 (flash pin) for my purpose, as after flashing the MCU the pin will get free.
Do CP2102 uses GPIO 1 and GPIO 3? Can I use these pins for my purpose? (Given I need the data via USB, which I guess comes through CP2102)
Can I receive the sensor data from SoftUART bus and get that data to my computer via USB?

I am confused from the articles given over internet. I request if anyone knows how these work, please explain.
Thank you

Related to the first question: https://arduino.stackexchange.com/questions/76091/why-do-esp-boards-break-out-the-spi-flash-pins

#3+4: if you only send data to usb, you don't need RX for that, just TX.

Do flash uses GPIO6-11 all the time? Can we use any of these pins for our purpose? What if someone needs an SPI communication, as these pins are locked by flash.

It is Quad SPI. The CS pins for this SPI interface are controlled by low level code. So you can't use this pins as GPIO and they have limited use as SPI too. If the flash access is set to normal SPI, the two pins io 9 and io 10 used for quad mode can be used as GPIO.

Can I use GPIO-0 (flash pin) for my purpose, as after flashing the MCU the pin will get free.

You can use io 0 as GPIO. Only make sure it is HIGH at boot. The bootloader reads it at boot to determine if it should go to flashing mode. Other boot config pins are io 2, it must be HIGH at boot and io 15, which must be LOW at boot.

Do CP2102 uses GPIO 1 and GPIO 3? Can I use these pins for my purpose? (Given I need the data via USB, which I guess comes through CP2102)

Pins io 1 and io 3 are wired to the USB chip and used for Serial. They can be used as io pins, if you don't need Serial communication over them. Serial in esp8266 Arduino can be swapped to different set of pins for use with a serial device. For output printing you can use Serial1 which has only TX. To relay this output to USB bridge io 2 (Serial1 TX) to io 4 (Serial TX wired to USB).

Can I receive the sensor data from SoftUART bus and get that data to my computer via USB?

You can use SoftwareSerail or the trick mentioned above.
see NodeMCU pins


text:
Arduino Due Master Programming
I am newbie. In my application Arduino Due is configured as Master and Arduino Uno as Slave. I need to transfer 24-bit Hexadecimal data of about 79-registers to slave device. At the slave end in serial monitor window I would like to display the transmitted data. I have developed an array at slave side, and I am comparing the master data with slave one. I have divided the 24-bit data into 3 Bytes. I will attach the Master and Slave codes below. I am getting Invalid data in serial monitor window as the data (Hexa Decimal) transmitted by Master is converted into decimal format internally and I think this was the reason I am not able to print the Valid data in serial monitor window.
Any help will be greatly appreciated. Thanks in Advance.
MASTER Code
#include <SPI.h>

SPISettings mySettting(125000, MSBFIRST, SPI_MODE0);
const uint8_t ss = 10;

//pinMode(10, OUTPUT)
void setup() {
  pinMode(ss, OUTPUT);

  SPI.begin();
SPI.beginTransaction(mySettting);

 digitalWrite(ss, LOW);
  SPI.transfer('@');
  SPI.transfer(0x1C);
  SPI.transfer(0x25);
  SPI.transfer(0x00);
  SPI.transfer('$');
  delay(100);
  digitalWrite(ss, HIGH);

digitalWrite(ss, LOW);
  SPI.transfer('@');
  SPI.transfer(0x08);
  SPI.transfer(0x08);
  SPI.transfer(0x01);
  SPI.transfer('$');
  delay(100);
  digitalWrite(ss, HIGH);

digitalWrite(ss, LOW);
  SPI.transfer('@');
  SPI.transfer(0x00);
  SPI.transfer(0x05);
  SPI.transfer(0x02);
  SPI.transfer('$');
  delay(100);
  digitalWrite(ss, HIGH);

digitalWrite(ss, LOW);
  SPI.transfer('@');
  SPI.transfer(0x42);
  SPI.transfer(0x06);
  SPI.transfer(0x03);
  SPI.transfer('$');
  delay(100);
  digitalWrite(ss, HIGH);

digitalWrite(ss, LOW);
  SPI.transfer('@');
  SPI.transfer(0x43);
  SPI.transfer(0x0A);
  SPI.transfer(0x04);
  SPI.transfer('$');
  delay(100);
  digitalWrite(ss, HIGH);

digitalWrite(ss, LOW);
  SPI.transfer('@');
  SPI.transfer(0xC8);
  SPI.transfer(0x00);
  SPI.transfer(0x05);
  SPI.transfer('$');
  delay(100);
  digitalWrite(ss, HIGH);

digitalWrite(ss, LOW);
  SPI.transfer('@');
  SPI.transfer(0x02);
  SPI.transfer(0xC8);
  SPI.transfer(0x6C);
  SPI.transfer('$');
  delay(100);
  digitalWrite(ss, HIGH);

digitalWrite(ss, LOW);
  SPI.transfer('@');
  SPI.transfer(0xB2);
  SPI.transfer(0x40);
  SPI.transfer(0x07);
  SPI.transfer('$');
  SPI.transfer('&');
  delay(100);
  digitalWrite(ss, HIGH);
SPI.endTransaction();
}

void loop() {
}

SLAVE Code
#include <SPI.h>
#include <stdio.h>
#include <string.h>
int buff[100] = {0x001C2500,0x00080801,0x00000502,0x00420603,0x430A04,0xC80005,0x02C806,0xB24007};

uint32_t buff_1 [100];
volatile byte indx;
volatile boolean process;
int i = 0;
uint32_t var_byte = 0x00000000;
uint32_t var_byte_1 = 0x00000000;
int byte_pos = 0;
short int status_1 = 0;

void setup (void) {
   Serial.begin (115200);
   pinMode(MISO, OUTPUT); // have to send on master in so it set as output
   SPCR |= _BV(SPE); // turn on SPI in slave mode
   indx = 0; // buffer empty
   process = false;
   SPI.attachInterrupt(); // turn on interrupt
   memset(buff_1,'\0',sizeof(buff_1));
}

ISR (SPI_STC_vect) // SPI interrupt routine
{
   byte c = SPDR; // read byte from SPI Data Register

   if(c == '@')
   {
      var_byte = 0x00000000;
      byte_pos = 2;
   }
   else if(c == '$')
      buff_1 [indx++] = var_byte;
   else if(c == '&')
      process = true;
   else
   {
      var_byte_1 = 0x00000000;
      var_byte_1 = (var_byte_1 | c) << byte_pos;
      var_byte |= var_byte_1;
      byte_pos--;
   }

}
void loop (void) {
   if (process) {
      process = false; //reset the process
      status_1 = 0;
      for(i=0;i<79;i++)
      {
        if (buff[i]==buff_1[i])
        {
          Serial.println ("Valid data_1");
        }
        else
        {
          status_1 = 1;
          break;
          //Serial.println ("Inavlid data");
        }
      }
      if (status_1 == 0)
        Serial.println ("Valid data");
      else
        Serial.println ("Inavlid data");
      indx= 0; //reset button to zero
      memset(buff_1,'\0',sizeof(buff_1));
   }
}

Try to print out the data, that you received. Then you might see, what the problem is, meaning how exactly the data is "invalid"

24-bit Hexadecimal data ... do you want to transmit 6 text characters, or 3 bytes?

I want to transmit 3 bytes of hexadecimal data, I mean 0x1A, 0x25, 0x00 in this way I would like to send the data.

Your process turn true for every receive of a "$", i.e. at end of receiving 3 bytes of data, but you are comparing it with 80-bytes of data, of course it won't match and will be "invalid". And BTW, where that 80 bytes come from? it looks that your data only consists of 32 bytes.


text:
digital input pins on arduino nano with standard firmata and pyfirmata are always 'None'

I have connected pin D2 on my arduino nano to high, and tried it out with an arduino c program and it works.  However, when I load standard firmata onto the the controller from the arduino IDE and try the following python program:
import pyfirmata

board = pyfirmata.Arduino('/dev/ttyUSB0')

for x in range(2,14):
    print("%s %s" % (x, board.get_pin("d:%s:i" % x).read()))

I get this:
$ venv/bin/python test.py
2 None
3 None
4 None
5 None
6 None
7 None
8 None
9 None
10 None
11 None
12 None
13 None

I can write digital pins with fermata and pyfirmata, but I can't read.
I have also tried this:
import pyfirmata

board.digital[2].mode = pyfirmata.INPUT
board.digital[3].mode = pyfirmata.INPUT

for x in range(2,14):
    print("%s %s" % (x, board.digital[x].read()))

and other combinations, and always get None
(disconnecting the wire in the picture doesn't change anything either)

I have also just repeated the experiment with an arduino uno and get the same result

so I guess my questions are:

Can anybody spot anything obvious that I am doing wrong?
Can anybody confirm that pyfirmata input ever works?
What did you do that I am not doing?

what should the resistor do?

Unless I have done something totally wrong, it is a pull down resistor in case I want to disconnect the yellow wire to see a low signal on D2.  It was necessary when I tested the set-up with arduino-c.

"None" indicates that there is no data to be found by read() because the incoming serial stream has never been serviced.  Launch an Iterator to start a new Python thread that services the serial port in the background.
it = pyfirmata.util.Iterator(board)
it.start()


text:
motor driver shield covering ports for ultrasonic sensor
im new to arduino and am making an arduino car. the motor driver shield covers the ports (am connecting an ultrasonic sensor) and i know that we can connect it to the 'holes' on the motor driver shield (l293d) but i do not have a solder or header pins. there's a lockdown and i cannot get any of those. can i make a makeshift arrangement? (refer img): it is a little loose, is there any fix using jumper wires or any other arrangement? please let me know!

There is such a thing as home delivery you know...

my area is under strict lockdown, deliveries have been stopped

@majenko is there any other fix?

Do you have a breadboard available?

Of course any way will be very hacky and non-permanent. Often the pins of jumper wires are actually small pieces of thin folded metal. In that case you could try to unfold them a bit, to make them bigger. That might give them better grip in the holes. Otherwise you might be able to improvise something with materials, that you already have. You could try paper clips, which are typically a bit thicker, than jumper pins. It really depends, what types of conductive material you have. You cannot really advice you further, since the standard way is not possible for you currently.

try this .... push the pin through the hole as far as it will go ... use pliers to flatten the end of the pin .... gently pull the pin back out of the hole (or push pin from back of board) ... it should bind because of the flattening ... experiment with the amount of flattening required .... start with slight flattening and keep increasing in small amounts

You might also try very small machine screws and nuts, if you can find any. You'd put a screw and nut through one of the breadboard holes, and then wrap a bare wire around the screw. When you tighten down the nut on the screw it should press the wire against the pad on the breadboard. For this to work you will need really tiny screws however.

Your home is in such tight lockdown that you can't take deliveries, even those left on your porch?

You really need a soldering iron with some electronics solder, and ideally some headers. Anything you try and do without a soldering iron is going to be a hacky, poor solution. I would focus on finding a way to get ahold of a soldering iron. Perhaps someone in walking distance of your home has one they can leave at their front door for you to borrow?

@DuncanC your comment about the screws gave me an idea ... put thin wire through the hole and jam the end of a toothpick through the hole next to the wire ... that should hold the wire fairly tight

True. Especially if you can use the tapered ends of round toothpicks. However, they are going to be prone to falling out.


text:
Arduino Modbus Slave Library Needed
We are building a circuit based on ATMega328* that :

Reads 32 current transducers, multiplexed into one Analog Input,
Reads 12 voltage transducers, multiplexed into one Analog Input,
Reads 6 temperature sensors, multiplexed into one Analog Input,
Manipulates all the readings with some math (like scaling, averaging etc.),
Calculates new variables (power, crest factor, etc.),
Tracks trends (max/min/avg) of certain (calculated) readings,
Stores some events (peaks/dips - max/min values) etc. with time stamps from RTC,
Generates Alarm Flags (by comparing readings to software-set thresholds),

The circuit should be connected as a ModBus Device (Slave) to an existing
Modbus network with several other devices on an RS485 interface.
The circuit should communicate all these calculated values and alarms
as well as some other info, like peak/max values with date and
time stamps that were recorded at their time of occurrence, to the
Modbus Master. We have the freedom of allocating the register numbers
and their formats etc. (Modbus Map) to the controller's vendor (SAUTER).
For example we tell them Register 30001 is the current sensor x,
30002 is voltage sensor y, etc.
We think that sending time stamps (of certain events) will be based on
"agreed-upon" coding of register values (MM, DD, YYYY, etc.) and the
same for alarms (to be sent as hex codes).
We have searched for libraries and got really confused from the
multitude of libraries out there, as well as the lack of documentation -:)
Can you please kindly help us :
select the proper Arduino Modbus Slave Library that :

Has MAX485 support,
Assigns Modbus registers to any arbitrary variables,
Issues Exception Responses to Modbus requests (e.g. non-existing registers
or un-supported Function Codes.
Complies to Modbus Standards
Has a manual !!

We found the "yaacov" library on Github but it assigns registers directly to "Pins".
Also we looked at its "issues" and one of them was very serious : in which frames
coming from the Master with corrupted CRC gets responded to and causes collision
with other slaves. We dont like that ! as it indicates that the library was not tested
in true industrial environment.
We also found that the Library at :
https://electronhacks.com/2014/04/arduino-modbus-plc-rtu/
somewhat fits to our requirements, however it lacks the RS485 support, and more
important, it has no documentation.
We really appreciate any kind support.

The ATmega328 will be probably replaced with a larger CPU, but we are still
in development phase.

Thank you.

The ATmega328 will be probably replaced with a larger CPU ... then you will back to searching for a livrary

With my post approaching one month without a single reply  :smiley-confuse: !
(for whichever reason) I would like to post for those who may need this library :

https://drive.google.com/file/d/0Bx5wWRfN_z7oMDlZMDhWbXM2VFU/view
The library is based on the original one written by Jason Vreeland [CodeRage]
Released 3/7/2010 under GNU license
and was used (and possibly modified) by "jhottell" on electronhacks.com :
https://electronhacks.com/2014/04/arduino-modbus-plc-rtu/
The major difference is the use of RS485.
I have written code and tested it on an "UNO" which worked perfectly with more
than one ModBus Slave Simulator under windows, including DAQ Factory which
is a professional package used in actual industry.

This is an awesome Modbus slave and Master Library
Required this library <ModbusRtu.h>
#include <ModbusRtu.h>
unsigned long TIME = 0;
unsigned long LASTTIME = 0;
unsigned long INTERVAL = 5000;

int i = 0;
// data array for modbus network sharing
uint16_t au16data[16] = {
  3, 1415, 9265, 4, 2, 7182, 28182, 8, 0, 0, 0, 0, 0, 0, 1, 11 };

/**
 *  Modbus object declaration
 *  u8id : node id = 0 for master, = 1..247 for slave
 *  port : serial port
 *  u8txenpin : 0 for RS-232 and USB-FTDI
 *               or any pin number > 1 for RS-485
 */
Modbus slave(1,Serial,0); // this is slave @1 and RS-232 or USB-FTDI

void setup() {
  Serial.swap();
  Serial.begin( 19200 ); // baud-rate at 19200
  Serial1.begin( 19200 );
  slave.start();
}

void loop() {

  if ((millis() - TIME) > INTERVAL) {
    i++;

    if(i == 16){
      i = 0;

      for (int ii = 0; ii < 16; ii++)
      {
        au16data[ii] = 0;
      }
    }

    au16data[i] = 1;

    TIME = millis();
  }

  slave.poll( au16data, 16 );
}


text:
2xArduinos, 2xDevices, I2C setup
Is it valid configuration using hardware I2C pins:

Especially: can NanoEvery initialize communication with DS2482, while it is slave for Mega2560? Using Wire library or should I use software I2C when talking to Mega2560 and leave NanoEvery as master to DS2482?
Needed to use additional Nano due to long times of reading temperatures connected to DS2482 that blocks Mega controller.
Graph source

why would the reading block the Mega? ATmega 4809 has "Independent Master and Slave operation– Combined (same pins) or Dual mode (separate pins)", but I don't know if the Arduino libraries support it

@Juraj firstly Nano and Mega were connected by serial, now I'm trying to combine them in one rail mounted case and save 2 pins, trying to not add new hardware.

you don't need the Nano. in Mega start the reading in sensor, do other things and later read the result from the sensor


text:
ESP8266 OTA update with different flash size settings?
I have an ESP8266 in a project.  It's specifically this ESP8266 SMT Module - ESP-12F item.  It's been working great with OTA, but I realized belatedly that I didn't change the flash settings when I started compiling through the Arduino IDE several versions ago.  I had been using the setting "1 MB (FS:64KB OTA:~470KB)", and I've updated OTA over multiple versions with the same basic structure of firmware and using the same server-side set-up.
I can no longer update with that setting because my compiled sketch is now over the OTA size limit.  My chip actually has 4 MB, however, so this limit is artificial.  I tried changing to "4 MB (FS:2 MB OTA:~1019KB)", and that works under the following test conditions:

I compile the "old" program with the 4-MB settings and I re-upload the old program via wired connection.
I compile the "new" program that's to come via OTA with those same 4-MB settings.

That's fine for a test, but I already have one of these chips "deployed" in a location where it's hard to access it.  I'd like to update that deployed chip OTA while also changing the flash partition.  I'm willing to lose any files stored outside of the program itself.  So I'd like instead to have:

A deployed, OTA-enabled chip with firmware running on the 1-MB partition structure noted above:
(Any intermediate step needed)
OTA update to new firmware that has been compiled with the 4-MB partition structure.

I'm willing to upload a dummy sketch at "Any intermediate step needed" to work around the current size of the sketch, but, after some experimentation, OTA seems to fail when the partition structure is different regardless of the size of the binary.
That's consistent with #2 in the answer here: esp8266 OTA issue, but that older question took a different direction with the OP and the #2 point there is stated without any detail.  I understand that in a broad sense, the prior answer covers my case, but I'm looking for more detail on the specific aspect of the flash partition settings.  Especially for these related questions:

Is there any work-around strategy available to change the flash partitioning between different versions served OTA?
If no, is the limitation determined by the software in the current OTA framework in the public libraries, or is it somehow fundamental to how the program is laid out in the hardware memory?

In theory at least, it seems like I ought to be able to force the new program to be written OTA at the same location that it would have been written had the old program also had the 4-MB partition. (Again noting that I'm willing to lose any other data in the flash to make this update work.)

afaik, if your flash settings are wrong, you can only OTA once. (don't ask how i know).

The basic problem is that when you upload over OTA you don't upload the partition structure.
The ESP32's flash is split into a number of "partitions" or areas.  It might look something like:
+----+-+-------------+-------------+---------------------+
|BOOT|P|OTA Program 1|OTA Program 2| SPIFFS              |
+----+-+-------------+-------------+---------------------+

When you upload over UART you upload all that structure, and that structure can be changed.  When you upload over OTA you only upload one of "OTA Program 1" or "OTA Program 2". One of those is active and the other is inactive. You upload to the inactive one and then at the next reboot that becomes the active one. This allows the system to confirm that the program has been written correctly before running it to reduce the chances of bricking a device in the field.
Because of this you can never upload anything that doesn't fit into one of the OTA program partitions.
One risky option which you would have to do thorough local testing of first, is to write a program which, when executed, will change the partitioning. You would have to make sure that it runs in the lower OTA partition so that the inactive one is the one that gets both moved and expanded, which may take a little trial and error.
Once that has happened you should be able to upload a larger OTA program into the new, bigger, inactive OTA segment.
But that's only supposition and it's not something I have ever done or heard of anyone doing.

OK, fixed this using the ladder method.  Got out my ladder, climbed up, unscrewed casing, and uploaded fresh via UART.

Oh, I would have loved to hear that the proposed method works.


text:
Esp32: is OTA compatible with FREERTOS
Can I use OTA along with FreeRTOS tasks on ESP32. I ask this because in the following  example OTA seems to be enabled if FreeRTOS is disabled. Can for example upload firmware that runs on both cores over OTA?
Example taken from OTA template project by Andrea's Speiss

You can't not use FreeRTOS on the ESP32. The whole ESP-IDF is based around it.

yes, you can...

You can't not use FreeRTOS. The whole ESP-IDF is based around it. The Arduino setup() and loop() run in their own FreeRTOS thread.
If you "turn off" FreeRTOS then nothing will work.
Whatever that "template" is from it's of no use to you.

I was also believing that it is not possible but I handle it thanks to this post below;
https://github.com/SensorsIot/ESP32-OTA/issues/8
I applied what ever shared and it works like a charm together both FreeRTOS and OTA features.
As summary you need to create 2 custom header which includes your wifi credentials and OTA function. The remaining is same mostly.
credentials.h
#pragma once
const char* mySSID = "SSID of your AP";
const char* myPASSWORD = "Password of your AP";

OTA.h
#ifdef ESP32
#include <WiFi.h>
#include <ESPmDNS.h>
#else
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#endif

#include <WiFiUdp.h>
#include <ArduinoOTA.h>

#if defined(ESP32_RTOS) && defined(ESP32)
void ota_handle( void * parameter ) {
  for (;;) {
    ArduinoOTA.handle();
    delay(3500);
  }
}
#endif

void setupOTA(const char* nameprefix, const char* ssid, const char* password) {
  // Configure the hostname
  uint16_t maxlen = strlen(nameprefix) + 7;
  char *fullhostname = new char[maxlen];
  uint8_t mac[6];
  WiFi.macAddress(mac);
  snprintf(fullhostname, maxlen, "%s-%02x%02x%02x", nameprefix, mac[3], mac[4], mac[5]);
  ArduinoOTA.setHostname(fullhostname);
  delete[] fullhostname;

  // Configure and start the WiFi station
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  // Wait for connection
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Connection Failed! Rebooting...");
    delay(5000);
    ESP.restart();
  }

  // Port defaults to 3232
  // ArduinoOTA.setPort(3232);

  // No authentication by default
  // ArduinoOTA.setPassword("admin");

  // Password can be set with it's md5 value as well
  // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
  // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");

  ArduinoOTA.onStart([]() {
    String type;
    if (ArduinoOTA.getCommand() == U_FLASH)
      type = "sketch";
    else // U_SPIFFS
      type = "filesystem";

    // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
    Serial.println("Start updating " + type);
  });

  ArduinoOTA.onEnd([]() {
    Serial.println("\nEnd");
  });

  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  });

  ArduinoOTA.onError([](ota_error_t error) {
    Serial.printf("Error[%u]: ", error);
    if (error == OTA_AUTH_ERROR) Serial.println("\nAuth Failed");
    else if (error == OTA_BEGIN_ERROR) Serial.println("\nBegin Failed");
    else if (error == OTA_CONNECT_ERROR) Serial.println("\nConnect Failed");
    else if (error == OTA_RECEIVE_ERROR) Serial.println("\nReceive Failed");
    else if (error == OTA_END_ERROR) Serial.println("\nEnd Failed");
  });

  ArduinoOTA.begin();

  Serial.println("OTA Initialized");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

#if defined(ESP32_RTOS) && defined(ESP32)
  xTaskCreate(
    ota_handle,          /* Task function. */
    "OTA_HANDLE",        /* String with name of task. */
    10000,            /* Stack size in bytes. */
    NULL,             /* Parameter passed as input of the task */
    1,                /* Priority of the task. */
    NULL);            /* Task handle. */
#endif
}

OTA Template sketch.ino
#define ESP32_RTOS  // Uncomment this line if you want to use the code with freertos only on the ESP32
                    // Has to be done before including "OTA.h"

#include "OTA.h"
#include "credentials.h"

void setup() {
  Serial.begin(115200);
  Serial.println("Booting");

  setupOTA("TemplateSketch", mySSID, myPASSWORD);

  // Your setup code
  /*  Example
  pinMode(2, OUTPUT);
  */
}

void loop() {
#ifdef defined(ESP32_RTOS) && defined(ESP32)
#else
  ArduinoOTA.handle();
#endif

  // Your code here
  /* Example
  digitalWrite(2, HIGH);
  delay(500);
  digitalWrite(2, LOW);
  delay(1000);
  */
}


text:
How can I get my LCD display to display Chinese and Japanese characters?
I'm making a project that requires me to display Chinese and Japanese characters on an LCD. However, the 16x2 LCD display I have does not seem to support displaying Chinese and Japanese characters.
If I do something like lcd.print("おはよう世界"); or lcd.print("简体中文测试");, it seems to display just a bunch of jumbled random characters (which I am assuming have their character values add up to the values of the characters in the code).
How can I get my LCD to display Chinese and Japanese characters?
Or, if there's no way to do it without buying a new one that supports it, where can I buy one?

Displaying Kanji or Chinese characters is way beyond the ability of an LCD that displays 5 pixel by 7 pixel characters.
To understand the limitations, take a piece of graph paper and draw out a set of 5x7 rectangles. See if you can define ANY recognizable Japanese or Chinese characters on your graph paper.
Maybe a couple of characters? (Then again, maybe not.)
You need a display with a lot more resolution, like an OLED graphics display. You are also struggling against a microcontroller that doesn't have support for Unicode. It's just not up to the job. You'd be much better off with a Raspberry Pi and a screen like a smart-phone color LCD screen. Install Linux and you can have native support for Unicode.
As others have pointed out, hiragana or katakana would be more practical, and there are some low-res LCDs that support those characters.

There are two ROMs available for those LCDs. One has Latin extended characters in 128-255. The other has Japanese hiragana (or maybe it's katakana, I forget). These Japanese characters can be displayed fine. Kanji is a no no of course, so is Chinese, both simplified and traditional. Select the right model of LCD and you get some Japanese.

This one has a single ROM, with what looks like a mix of extended Latin, Katakana and Greek. It can also display up to eight different user-defined glyphs.

Good point about Katakana/Hiragana, Majenko and Edgar Bonet. Those are a lot easier to manage. I should have specified that Kanji and Chinese were beyond a 5x7 LCD (And an Arduino) in my answer.

Your LCD uses a single byte for the character to display, so there are < 256 characters possible. 8 of them are userdefineable, the others are predefined in the LCD-ROM.
The Arduino IDE uses utf-8 code, which takes more than a single byte for all non-ascii characters like in your "おはよう世界".
Even if the character set contains the ones you want to display, you need an escape sequence to have them properly in your print statement.


text:
regarding ardunio error
Arduino: 1.8.13 (Windows 10), Board: "Arduino Uno"
c:\program files (x86)\arduino\hardware\tools\avr\bin../lib/gcc/avr/7.3.0/../../../../avr/bin/ar.exe: unable to rename 'core\core.a'; reason: Permission denied
exit status 1
Error compiling for board Arduino Uno.
continue error is coming having downloading over more than 15 times. How can i overcome this problem

Have you tried turning off your antivirus software for a single compilation? Described in this issue on github


text:
MPU6050 Problem with NodeMCU
I am using MPU6050 as a part of IMU of my drone, and I wrote this program for Arduino Nano to fetch the orientation of the MPU6050 module in 3D space. And that works perfectly fine, but when I uploaded this exact code to a NodeMCU, the output started getting increased only, i.e., whenever there's any change of orientation of the module, the output, instead of showing the specific orientation, gets increased on and on. Can you please help me out with interfacing the MPU6050 with my NodeMCU. I am providing the program underneath.
#include <Wire.h>
const int MPU = 0x68; // MPU6050 I2C address

char status;                // Declaring all the necessary variables
double T, P;
float AccX, AccY, AccZ;
float GyroX, GyroY, GyroZ;
float accAngleX, accAngleY, gyroAngleX, gyroAngleY, gyroAngleZ;
float roll_sensor, pitch_sensor, yaw_sensor;
float AccErrorX, AccErrorY, GyroErrorX, GyroErrorY, GyroErrorZ;
float elapsedTime, currentTime, previousTime;
int c = 0;

void setup() {
  Serial.begin(115200);
  Wire.begin();                      // Initialize comunication
  Wire.beginTransmission(MPU);       // Start communication with MPU6050 // MPU=0x68
  Wire.write(0x6B);                  // Talk to the register 6B
  Wire.write(0x00);                  // Make reset - place a 0 into the 6B register
  Wire.endTransmission(true);        // end the transmission
  calculate_IMU_error();  // Call this function if you need to get the IMU error values for your module
  delay(20);
}
void loop() {
  // === Read acceleromter data === //
  Wire.beginTransmission(MPU);
  Wire.write(0x3B); // Start with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 14, true); // Read 6 registers total, each axis value is stored in 2 registers

  //For a range of +-2g, we need to divide the raw values by 16384, according to the datasheet
  AccX = (Wire.read() << 8 | Wire.read()) / 16384.0; // X-axis value
  AccY = (Wire.read() << 8 | Wire.read()) / 16384.0; // Y-axis value
  AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0; // Z-axis value

  // Calculating roll_sensor and pitch_sensor from the accelerometer data
  accAngleX = (atan(AccY / sqrt(pow(AccX, 2) + pow(AccZ, 2))) * (180 / PI)) - AccErrorX;
  accAngleY = (atan(-1 * AccX / sqrt(pow(AccY, 2) + pow(AccZ, 2))) * (180 / PI)) - AccErrorY;

  // === Read gyroscope data === //
  previousTime = currentTime;        // Previous time is stored before the actual time read
  currentTime = millis();            // Current time actual time read
  elapsedTime = (currentTime - previousTime) / 1000; // Divide by 1000 to get seconds
  Wire.beginTransmission(MPU);
  Wire.write(0x43); // Gyro data first register address 0x43
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 14, true); // Read 4 registers total, each axis value is stored in 2 registers

  GyroX = (Wire.read() << 8 | Wire.read()) / 131.0; // For a 250deg/s range we have to divide first the raw value by 131.0, according to the datasheet
  GyroY = (Wire.read() << 8 | Wire.read()) / 131.0;
  GyroZ = (Wire.read() << 8 | Wire.read()) / 131.0;

  // Correct the outputs with the calculated error values
  GyroX = GyroX - GyroErrorX;
  GyroY = GyroY - GyroErrorY;
  GyroZ = GyroZ - GyroErrorZ;

  // Currently the raw values are in degrees per seconds, deg/s, so we need to multiply by sendonds (s) to get the angle in degrees
  gyroAngleX = gyroAngleX + (GyroX * elapsedTime); // deg/s * s = deg
  gyroAngleY = gyroAngleY + (GyroY * elapsedTime);
  yaw_sensor =  yaw_sensor + (GyroZ * elapsedTime);

  // Complementary filter - combine acceleromter and gyro angle values
  roll_sensor = (0.94 * gyroAngleX) + (0.06 * accAngleX);
  pitch_sensor = (0.94 * gyroAngleY) + (0.06 * accAngleY);

  // Print the values on the serial monitor
  Serial.print("                   roll_GY: "); Serial.print(roll_sensor);
  Serial.print("         pitch_GY: "); Serial.print(pitch_sensor);
  Serial.print("         yaw_GY: "); Serial.print(yaw_sensor);
  Serial.println();

}
void calculate_IMU_error() {
  // We can call this funtion in the setup section to calculate the accelerometer and gyro data error. From here we will get the error values used in the above equations printed on the Serial Monitor.
  // Note that we should place the IMU flat in order to get the proper values, so that we then can the correct values
  // Read accelerometer values 300 times
  while (c < 300) {
    Wire.beginTransmission(MPU);
    Wire.write(0x3B);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 6, true);
    AccX = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    AccY = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    // Sum all readings
    AccErrorX = AccErrorX + ((atan((AccY) / sqrt(pow((AccX), 2) + pow((AccZ), 2))) * (180 / PI)));
    AccErrorY = AccErrorY + ((atan(-1 * (AccX) / sqrt(pow((AccY), 2) + pow((AccZ), 2))) * (180 / PI)));
    c++ ;
  }
  //Divide the sum by 200 to get the error value
  AccErrorX = AccErrorX / 300;
  AccErrorY = AccErrorY / 300;
  c = 0;
  // Read gyro values 300 times
  while (c < 300) {
    Wire.beginTransmission(MPU);
    Wire.write(0x43);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 6, true);

    GyroX = Wire.read() << 8 | Wire.read();
    GyroY = Wire.read() << 8 | Wire.read();
    GyroZ = Wire.read() << 8 | Wire.read();

    // Sum all readings
    GyroErrorX = GyroErrorX + (GyroX / 131.0);
    GyroErrorY = GyroErrorY + (GyroY / 131.0);
    GyroErrorZ = GyroErrorZ + (GyroZ / 131.0);
    c++;
  }

  //Divide the sum by 300 to get the error value
  GyroErrorX = GyroErrorX / 300;
  GyroErrorY = GyroErrorY / 300;
  GyroErrorZ = GyroErrorZ / 300;
}

"output started getting increased only" - What exactly does this mean?

Ohh I am sorry for being unspecific before and I edited that!

gyroAngleX is never reset, only added to.

No, that's alright, as depending on the sign of the GyroX, GyroY, GyroZ, it provides the expected figures.

I see that you are reading 16-bit integers from the IMU like this:
// doesn't work on 32-bit systems
void loop() {
    ...
    AccX = (Wire.read() << 8 | Wire.read()) / 16384.0; // X-axis value
    AccY = (Wire.read() << 8 | Wire.read()) / 16384.0; // Y-axis value
    AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0; // Z-axis value
    ...
    GyroX = (Wire.read() << 8 | Wire.read()) / 131.0; // ...
    GyroY = (Wire.read() << 8 | Wire.read()) / 131.0;
    GyroZ = (Wire.read() << 8 | Wire.read()) / 131.0;
    ....
}

While all too often I am forced to use "#ifdef" to set up platform-specific code for each platform,
in this case I'm pretty sure it's possibly to write cross-platform compatible code that will work on both platforms;
perhaps something more like this:
// warning: untested, but I think it should work
int16_t wire_read_16(){
    int16_t value = (Wire.read() << 8 | Wire.read());
    return value;
}

void loop() {
    ...
    AccX = (wire_read_16()) * (1.0f / 16384.0f); // X-axis value
    AccY = (wire_read_16()) * (1.0f / 16384.0f); // Y-axis value
    AccZ = (wire_read_16()) * (1.0f / 16384.0f); // Z-axis value
    ...
    GyroX = (wire_read_16()) * (1.0f / 131.0f); // For a 250deg/s range we have to divide first the raw value by 131.0, according to the datasheet
    GyroY = (wire_read_16()) * (1.0f / 131.0f);
    GyroZ = (wire_read_16()) * (1.0f / 131.0f);
    ....
}

I see that
onehorse is apparently having exactly the same problem at
"integer type definitions on Teensy 3.1"
It sounds like maybe you've stumbled over a quirk of the C programming language where "int" varies from system to system.
(See Ido Gendel, "The problem with ints").
The "int" in some systems (such as the ATmega based Arduinos) is a 16-bit integer.
The "int" in some other systems (such as the ARM based Arduinos, perhaps including NodeMCU) is a 32-bit integer.
(
inttypes vs Arduino defined integral types
; "Arduino reference: int"
)
In yet other systems, "int" is a variety of other sizes.
For example, when your IMU is trying to send you a "-2",
it sends 0xFFFE.
When the nano puts that into its "int" which is a 16-bit integer, it then later properly interprets that as meaning "-2".
I suspect what's happening is that
when the other system puts that value into its "int" which is a 32-bit integer, that somehow ends up containing
0x0000FFFE which means +65534,
but what should have happened is "sign extension" so that 32-bit integer ends up containing
0xFFFFFFFE which means "-2".
By sticking that value into an intermediate "int16_t" variable, we're explicitly telling the compiler that it's a signed 16-bit integer,
so later when that compiler sticks it into a 32-bit integer it sign-extends properly.
The C compiler (correctly) handles an int divided by a float by converting both values to floats (and sign extending properly), and then dividing. Likewise with an int divided by a double.

yes! I resolved that, with typecasting the raw MPU6050 data into int16_t as
AccelX = (((int16_t)Wire.read()<<8) | Wire.read()), but one problem prevails again, which is the millis(), which is applicable for Arduino Nano, but its problematic interfacing with Nodemcu is still misunderstood to me, can you please suggest a way to measure the execution time, in NodeMCU! Thanks a lot, by the way!

Does https://arduino.stackexchange.com/questions/56712/nodemcu-millis-simple-counter-how-long-is-led-on answer your question? If not, could you post a fresh new question?


text:
Unable to use ir receiver and motor shield together
#include <IRremote.h>
#include <AFMotor.h>
AF_DCMotor motor(1);

int RECV_PIN = 14;//The definition of the infrared receiver pin 11
IRrecv irrecv(RECV_PIN);
decode_results results;

void setup()
{
  Serial.begin(9600); //Open serial
  irrecv.enableIRIn(); // Initialization infrared receiver
  motor.setSpeed(255);
  motor.run(RELEASE);
  Serial.println("start");
  motor.run(FORWARD);
  delay(1000);
}

void loop()
{
  if (irrecv.decode(&results)) {
    if(results.value==0x3D9AE3F7)
    {

      motor.run(FORWARD);
      delay(2000);
    }
    else if(results.value==0x1BC0157B)
    {
      motor.run(RELEASE);
      motor.run(BACKWARD);
    }
    Serial.println(results.value, HEX);//Wrap output in hex receive code
    Serial.println();//For ease of viewing the output to add a blank line
    irrecv.resume(); //Receiving the next value
  }
}

Motor shield is not working when I use an IR receiver.
I tried connecting the ir receiver in different analog pins but it didn't work. I guess it's due to some error in my code but unable to figure out.

Is the motor using pin 1?

Yes I've connected the motor to pin1 also. I tried running the motor using a separate code and its working fine. @Delta_G

No by pin 1 I meant I connected the motor to the M1(motor ) pin of the motor shield. @Delta_G

What pin on the Uno is it connected to?   It says 1 in the constructor call.

I've tried connecting it (the ir sensor) in all the analong pins as they are not used by the shield @Delta_G

No the motor.  What arduino pin is the motor using?

It's an motor sheild so it's connected to all the pins and it sits on top of the arduino @Delta_G

But most of the pins come through.  Only some of them are used for the actual driving of the motor.  What pins does it use?   Oh never mind.  Just wait until someone who has one of those shields comes along and they may already know.

@Delta_G This shield runs 4 motors so it takes up a lot of pins. Only the analog pins and digital io 2 is free.

That seems unlikely but if true explains your problem.  If it is using pin 0 or 1 then you can’t use Serial.  What motor shield do you have exactly?   Do you have a link?

It's a normal adafruit motor shield https://learn.adafruit.com/adafruit-motor-shield

Are you sure it's the V1 and not the V2?

This would be a lot easier to example if you specified (1) Exactly how are the motors connected to the Arduino -- how are the pins connected to the motor shield, exactly which motor shield are you using, etc. ? (2) Exactly what code are you using when the motors do work? (3) What do you expect to happen with the above code? (4) exactly what actually happens with the above code? (Is it a syntax error in the IDE? Does the IR reciever stuff seem to work, but not the motors? etc.)


text:
What exactly does the return type do in a function?
something I've never understood and still don't is, what does the return type do specifically? Everyone in tutorials just say that void returns nothing and int returns int, etc. But what does that mean? Where is it returning to?  I can't seem to understand what everyone's talking about when they discuss functions.

it's the same as declaring a variable as the result of the function instead of a hard-coded literal.

It returns it to whatever the function is being assigned to.
Take the function:
int plus(int a, int b) {
    return a + b;
}

That function takes two integers, adds them together, and "returns" them as an integer.
You can then do:
int c = plus(3, 4);

and c will be handed the value 7 by the function.
Equally you can do:
Serial.println(plus(3, 4));

And the Serial.println() function will be handed the value 7 for printing.
The type of the return defines the kind of data that can be returned.
Oh, and void doesn't mean "returns nothing", but means "doesn't return anything" - which means you can't assign it to anything since there's nothing returned to assign.

To add to And the Serial.println() function will be handed the value 7 for printing. Especially, it will be handed an int value of 7, which will eventually produce a different output than other data types.

The reason is that a function is evaluated just as any other expression would be. Every expression - `(x**x - 3*x + 5), for instance - has a value and a type (unless the type is void, then it has no value, or not a defined one), and that includes functions. The compiler needs to know the type of every element of the expression in order to know how to use that element in an operation (arithmetic or other kinds). Sometimes a value has to be converted from one type to another to combined with another element or assign to a variable, and knowing the type of each element is the only the compiler knows how to accomplish this.
Here is an example:
float squareroot(float x); could declare a function that takes a floating point number and returns its square root as a floating point number. If you assign that value to an integral of variable, the compiler needs to see that the functions does not return an integer but a float, so it includes the appropriate code to convert the float to an integer (by truncating the fractional part, in this case).
If the function could be written without declaring its return value type, the compiler would be unable to make the conversion, or even to know whether one will be needed.


text:
Running Arduino with 2 outputs and 2 inputs
Totally new to Arduino, 3 weeks old!
I am doing a project with 2 inputs (2 x ultrasonic sensors) and 2 outputs (buzzer and send SMS)
The code to run the buzzer and sms works perfectly individually. For the buzzer, it will stop buzzing after approx 5 seconds.
I would love them to run concurrently but it didn't work as planned when I upload the code on the board.
I've read on forums to use millis / blinkwithoutdelay but am unsure how I can incorporate those functions on my mode as the examples posted online are different from my project.
The following is the code I have created.
Would appreciate if I can get some help from the experienced folks here.
#define TRIG A0 //Module pins
#define ECHO A1
#define TRIG1 A2 //Module pins
#define ECHO1 A3
#define Buzzerpin 13

int ctn = 0;

void setup() {
  Serial.begin(9600); // Serial monitoring
  pinMode(TRIG, OUTPUT); // Initializing Trigger Output and Echo Input
  pinMode(ECHO, INPUT_PULLUP);
  pinMode(TRIG1, OUTPUT); // Initializing Trigger Output and Echo Input
  pinMode(ECHO1, INPUT_PULLUP);
  pinMode(Buzzerpin, OUTPUT);
}

void loop() {

  digitalWrite(TRIG, LOW); // Set the trigger pin to low for 2uS
  delayMicroseconds(2);

  digitalWrite(TRIG, HIGH); // Send a 10uS high to trigger ranging according to specs
  delayMicroseconds(20);

  digitalWrite(TRIG, LOW); // Send pin low again
  delayMicroseconds(2);

  digitalWrite(TRIG1, LOW); // Set the trigger pin to low for 2uS. Give a short LOW pulse beforehand to ensure a clean HIGH pulse
  delayMicroseconds(2);

  digitalWrite(TRIG1, HIGH); // Send a 10uS high to trigger ranging according to specs
  delayMicroseconds(20);

  digitalWrite(TRIG1, LOW); // Send pin low again
  delayMicroseconds(2);

  int distance = pulseIn(ECHO, HIGH, 26000); // Read in times pulse
  int distance1 = pulseIn(ECHO1, HIGH, 26000); // Read in times pulse
  distance = distance/58;
  distance1 = distance1/58;

  if (distance < 25) {
    Serial.print("\r");
    delay(1000);
    Serial.print("AT+CMGF=1\r");
    delay(1000);
    /*Replace XXXXXXXXXX to 10 digit mobile number & ZZ to 2 digit country code*/
    Serial.print("AT+CMGS=\"+YYXXXX\"\r"); // YY is the country code XXX is the number
    delay(1000); //
    //The text of the message to be sent.
    Serial.print("HELLO There");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);
  }
  else {}

  if (distance1 < 25 && ctn < 150) {
    ctn += 1;
    digitalWrite(Buzzerpin, HIGH);
  }
  else {
    digitalWrite(Buzzerpin, LOW);
  }

  if (distance1 > 25 && ctn >= 150) {
    ctn = 0;
    digitalWrite(Buzzerpin, HIGH);
  }
}

First thing: you should call pulseIn() right after sending the TRIG
pulse. If you wait too much, you will miss the start of the echo pulse.
For instance, here:
int distance = pulseIn(ECHO, HIGH, 26000);
int distance1 = pulseIn(ECHO1, HIGH, 26000);

the second pulseIn() is starting too late, because of the time taken
by the first one.
Next, the general approach for doing things is a non-blocking fashion
(and thus being able to handle concurrent tasks) is to program each task
in the form of a finite state machine. Combine this with the
timing technique used in the “Blink without delay” Arduino tutorial if
you need time-triggered actions.
Here I would use one state machine for sending the SMS and another one
for the buzzer. The first one is the most complex:
Edit: I expanded on how I designed this state machine.
In a canonical finite state machine implementation, each action is
associated with a state transition. We then have a transition for each
command sent to the GSM module, and we can label the states according to
which commands have already been sent, like this:
SENT_NOTHING → SENT_CR → SENT_CMGF → SENT_CMGS → SENT_MSG →
SENT_ALL.
All of the above transitions send a string to the GSM module. The first
one (SENT_NOTHING → SENT_CR) is triggered by the distance detected
being less than 25 cm. The following ones are time-triggered one
second after the previous one. We have to add one final transition
(SENT_ALL → SENT_NOTHING) that performs no action but lets the system
“forget” it has sent an SMS and thus makes it ready to send a new one.
This transition would also be time-triggered, after a potentially long
delay (how often would the user like to receive those reminders?). In
the code below, this last delay is one second, which I believe is too
short, but matches the last delay(1000) in the code you posted. The
implementation would be like this:
static enum {
  SENT_NOTHING, SENT_CR, SENT_CMGF, SENT_CMGS, SENT_MSG, SENT_ALL
} sms_state = SENT_NOTHING;
static uint32_t time_last_command_sent;
uint32_t now = millis();
switch (sms_state) {
  case SENT_NOTHING:
    if (distance < 25) {
      Serial.print("\r");
      time_last_command_sent = now;
      sms_state = SENT_CR;
    }
    break;
  case SENT_CR:
    if (now - time_last_command_sent >= 1000) {
      Serial.print("AT+CMGF=1\r");
      time_last_command_sent = now;
      sms_state = SENT_CMGF;
    }
    break;
  case SENT_CMGF:
    if (now - time_last_command_sent >= 1000) {
      Serial.print("AT+CMGS=\"+YYXXXX\"\r");
      time_last_command_sent = now;
      sms_state = SENT_CMGS;
    }
    break;
  // and so on for the cases SENT_CMGS and SENT_MSG...
  case SENT_ALL:
    if (now - time_last_command_sent >= 1000) {
      sms_state = SENT_NOTHING;  // forget we sent an SMS
    }
    break;
}

I have an issue with this implementation though: it is overly
repetitive, as the cases SENT_CR, SENT_CMGF, SENT_CMGS and SENT_MSG
are essentially copies of the same code. In order to make the code
dryer, I prefer merging them into a single state, and splitting
the state information into two variables: sms_state and
commands_sent. The new possible values for sms_state are now:

SMS_READY: the code is ready to send the message as soon as it is
required by the detected distance.
SMS_SENDING: it has started to send the commands to the GSM module,
but is not done yet.
SMS_DONE: the SMS has been sent, but no other one will be sent until
some time has elapsed, after which it will transition to SMS_READY.

The mapping to the “full” machine states is then:
 full state    │ sms_state   commands_sent
───────────────┼───────────────────────────
 SENT_NOTHING  │ SMS_READY         0
 SENT_CR       │ SMS_SENDING       1
 SENT_CMGF     │ SMS_SENDING       2
 SENT_CMGS     │ SMS_SENDING       3
 SENT_MSG      │ SMS_SENDING       4
 SENT_ALL      │ SMS_DONE          5

It could be argued that sms_state is redundant, as all the state
information is contained in commands_sent. I still wanted to keep
sms_state in order to easily switch on it. This is not the only
possible approach though, and it would be perfectly sensible to write
something like
if (commands_sent == 0) {
  // handle the case SMS_READY
} else if (commands_sent < command_count) {
  // handle the case SMS_SENDING
} else {
  // handle the case SMS_DONE
}

For the buzzer, there are only two states: BUZZER_OFF and BUZZER_ON.
The transitions are conditioned by the measured distance and, for the ON
→ OFF transition, also by the time it has been ON.
Here is my tentative, untested implementation of this approach:
#define TRIG A0 //Module pins
#define ECHO A1
#define TRIG1 A2 //Module pins
#define ECHO1 A3
#define Buzzerpin 13

// Commands to be sent to the GSM module.
const int command_count = 5;
const char * const commands[command_count] = {
  "\r",
  "AT+CMGF=1\r",
  "AT+CMGS=\"+YYXXXX\"\r",
  "HELLO There",
  "\x1a"
};

void setup() {
  Serial.begin(9600);
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT_PULLUP);
  pinMode(TRIG1, OUTPUT);
  pinMode(ECHO1, INPUT_PULLUP);
  pinMode(Buzzerpin, OUTPUT);
}

void loop() {
  // Measure both distances.
  digitalWrite(TRIG, LOW);
  digitalWrite(TRIG, HIGH);
  delayMicroseconds(20);
  digitalWrite(TRIG, LOW);
  int distance = pulseIn(ECHO, HIGH, 26000) / 58;
  digitalWrite(TRIG1, HIGH);
  delayMicroseconds(20);
  digitalWrite(TRIG1, LOW);
  int distance1 = pulseIn(ECHO1, HIGH, 26000) / 58;

  // Timing for both state machines.
  uint32_t now = millis();

  // Send the SMS.
  static enum {SMS_READY, SMS_SENDING, SMS_DONE} sms_state;
  static uint32_t time_last_command_sent;
  static int commands_sent = 0;
  switch (sms_state) {
    case SMS_READY:
      if (distance < 25) {
        Serial.print(commands[commands_sent++]);
        time_last_command_sent = now;
        sms_state = SMS_SENDING;
      }
      break;
    case SMS_SENDING:
      if (now - time_last_command_sent >= 1000) {
        Serial.print(commands[commands_sent++]);
        time_last_command_sent = now;
        if (commands_sent >= command_count) {
          sms_state = SMS_DONE;
        }
      }
      break;
    case SMS_DONE:
      if (now - time_last_command_sent >= 1000) {
        commands_sent = 0;
        sms_state = SMS_READY;
      }
      break;
  }

  // Drive the buzzer.
  static enum {BUZZER_OFF, BUZZER_ON} buzzer_state;
  static uint32_t time_buzzer_started;
  if (buzzer_state == BUZZER_OFF && distance1 < 25) {
    digitalWrite(Buzzerpin, HIGH);
    buzzer_state = BUZZER_ON;
    time_buzzer_started = now;
  } else if (buzzer_state == BUZZER_ON && distance1 >= 25
             && now - time_buzzer_started >= 2000) {
    digitalWrite(Buzzerpin, LOW);
    buzzer_state = BUZZER_OFF;
  }
}

Wow. You did a major rewrite of the OPs code. I decided to treat this as a "give a man a fish/teach a man to fish" situation, and instead offer general guidance.

@DuncanC, more important is that this is a nice example of the technique

Agreed, it's is an elegant reworking of the OPs code.

Hi Edgar, thank you so much for the code. Can I check, can I change the time in 'if (now - time_last_command_sent >= 1000) {' for both SMS_SENDING and SMS_DONE? Will it disrupt the flow of the circuit?

@Zac: I encourage you to study this code (start with the “finite state machine” link I provided), understand it (ask questions if needed) and then change anything you want. Actually I believe you really have to play with it in order to fully comprehend its working.

Using the blinkwithoutdelay approach is not incorporating functions, it is a coding style.
The idea is that you write your loop code to pass through without any delays, or with only very tiny delays. On each pass through the loop, you see how much time has passed, and if it's been 5 seconds since you started the buzzer, you turn off the buzzer.
You can probably get away with the microsecond delays that you use in your ultrasonic sensor code. Those delays are so small that they will only cause very short pauses in your app.
The delay(1000) calls in your loop are not going to work. Each one of those causes EVERYTHING to stop for a full second. You won't check the ultrasonic sensor, you won't change the buzzer state, you won't do ANYTHING, for 5 seconds, once you enter the body of that if statement. Those delay calls have to go.


text:
Arduino Nano - How to add multiple sensors? Lithium battery requirements? LED requirements?
I am new to arduino and need help with a couple projects I am working on. One involves the use of 2 sensors - one pulse sensor, and one vibration sensor. Both need to be plugged into the "5v" pin but there seems to be only one. Is there a way I could split the pins to add multiple sensors? Will data be taken in simultaneously, and be cross compared with each other for code execution? I dont want to use breadboaard and want to wire directly to chip.
Also, I need to wire up a rechargeable lithium battery to both projects, I have a 3.7v 1000 Mah lithium battery and a charging port, but do I need more? Ive seen battery regulators, and other parts people recommend, but I want to make sure it will work with just those 2 parts.
I also need to wire a multicolor LED to the board, but do I need any resistors? I see them often for others people projects, but I do not have any and am wondering if I need them.
Thanks if you can answer any of these questions. Totally new to EE

Try reading some basic tutorials and stuff on Arduino.   This kind of stuff is covered in thousands of different places all over the internet in all different types of presentations.  There’s no need for someone to try to reproduce all of that work here.

it may be much easier for you to develop your project if you have a breadboard available .... you can remove the breadboard when the project is completed

So, if you don't want to use a breadboard, you need to solder.

This is an addition to the answer of Thomas Weller.

Also, I need to wire up a rechargeable lithium battery to both projects, I have a 3.7v 1000 Mah lithium battery and a charging port, but do I need more? Ive seen battery regulators, and other parts people recommend, but I want to make sure it will work with just those 2 parts.

I guess with "charging port" you simply mean a plug, where you can connect a power supply to charge the Li battery. Then the answer is: No, you cannot do it with only the battery and the plug. Lithium batteries are rechargeable, yes, but there is much to consider for charging. You must never ever overcharge the battery or discharge it beyond a certain point. Otherwise the battery gets broken (the result can be between simply holding less and less or no power, to the battery exploding).
Also you need to know the battery level to accurately charge or turn of the device, when the battery is empty. Lithium batteries mostly don't change their voltage enough between the full and empty states. Thus Li battery devices have a circuit, that measures, how much power is coming in (while recharging) and how much power is taken out (for powering a device), to determine the current battery level.
At your stage you cannot build that yourself, and also I wouldn't recommend that to anyone. You can by Li battery charger/regulator boards, which will do all that for you, and they are not expensive. There are also microcontroller boards, that incorporate that support for Li batteries.

For the 5v pin:
If you wire 2 sensors to the 5v pin, it will not effect sensor readings of either sensors, and should return separate sensor values regardless of whether or not they are both wired to the 5v pin.
In order to wire both sensors to 1 5v pin, without involving a breadboard you have 2 options:

wire both sensor pins, and the 5v pin onto a custom pin header PCB that connects 3 or more pin headers together
Strip 3 jumper wires and solder them together (2 for the sensors and 1 for the 5v pin)

For the lithium batteries:
It says on their website: that the operating voltage is 5v, So your battery voltage needs to be at least that. It might be a good idea to get 2
(store.arduino.cc)
For the LEDs:
If it is a standard LED, it should be able to withstand voltages of 3.3v or under. Thus the resistor is only absolutely essential for higher voltages. However, it is recommended to use a resistor even with voltages of 3.3v or below, because low resistance could shorten the lifespan of the LED

Warning: unexperienced experiments even with low voltage may result in dangerous situations. E.g. a typical 10 Ohm resistor on 5 V may get so hot that it starts burning. Make yourself familiar with basic electronics, ideally with the help of someone else who can explain it to you. That person should especially explain the safety instructions first.

Both need to be plugged into the "5v" pin but there seems to be only one.

5 Volts means that this is a voltage source. In an ideal voltage source, you can basically plug in as many components as you like.
A real world voltage source will have a power limit. So you need to find datasheets of all components: the Arduino and the sensors. You can then read how much power the Arduino can provide and you can read how much power the sensors need.
As long as the Arduino can provide more power than the sensors need, that's ok. If it can't stuff will become more complicated, since you'll need another 5 V source and find a way to connect them safely.

Is there a way I could split the pins to add multiple sensors?

One does not split pins, one connects additional wires to a pin.

Will data be taken in simultaneously, and be cross compared with each other for code execution?

The 5V pin is only a voltage source. It will not provide or receive data. You'll need another pin or even multiple other pins to send and receive data.
Sometimes you can only have one device per pin (like a digital out pin), sometimes you can have multiple devices on a few pins (like I²C, SPI, 1Wire).
Typically, you would define what you need and then buy the components so you can build it. This requires a bit of knowledge, so watch some tutorials or introduction videos first.

I dont want to use breadboaard and want to wire directly to chip.

Sorry to be that direct, but at your level of understanding, that's probably not a good idea. Build it on a breadboard first and once it works as intended, make it a soldered circuit.

I need to wire up a rechargeable lithium battery to both projects, I have a 3.7v 1000 Mah lithium battery and a charging port, but do I need more?

As you said your components need 5 V, a 3.7 V battery will not help you at all.
You also need to be careful with the terms: a Mah is something totally different than a mAh. Don't confuse other people by mixing Mega (millions) with milli (1/1000).
Other than that, again, read the data sheets, find out how much current each component needs and sum it up. Then divide the 1000 mAh by the value you found, e.g. 100 mA and you'll get 10 h. That's how long it will last. Maybe it's good for your purpose, maybe not. How should we know that?

I want to make sure it will work with just those 2 parts.

That's great. Just consider all the aspects written in the data sheets of the components and it'll be fine.

I also need to wire a multicolor LED to the board, but do I need any resistors?

Yes. Read the data sheet of the multicolor LED and build a voltage dividor according to the values you find.

Totally new to EE

That's probably true. Maybe you want to start at the beginning and not jump into such a complex project. Get some resistors, measure voltages, measure currents. Make an LED light up. Learn about Ohms law, you'll need it very often. Once you got familiar with the basic stuff, come back to this project.
Honestly, I think you'll destroy components if you start with "a couple of projects".

A multicolor LED as in an RGB LED?
To power and LED you will need current limiting resistors.
For an RGB LED you'll need 3, one each for the red, green, and blue channels. You'll need to do some math to figure out what resistance values you need. You need to know the supply voltage (5V) the voltage drop of the LED, and the current to supply to the LED.
Here is a link to an LED resistor calculator: https://ohmslawcalculator.com/led-resistor-calculator
The formula is R = (source_voltage -  LED_voltage_drop) / LED_current
So if you have a 20 mA LED with a 1.3V voltage drop, and you are powering it from 5V (all fairly common values) you'd get:
(5-1.3)/0.02 = 185 Ω.
Then you would round up to the nearest resistor value.
You can safely use a higher resistance value than what you calculate. That will cause the LED to be dimmer. If you use a lower resistance you risk burning out the LED, or even burning out your Arduino.
For 20% resistors, that would be a 220Ω resistor. (The percent is a tolerance value. 20% resistors can have their actual resistance vary by as much as 20% from one to the next. You can get resistors in 20%, 10%, 5%, 2%, 1% tolerances, and even lower. The lower the tolerance value, the more they cost, and the more resistors you need to have all the possible values.
Don't use that value however. Look up the voltage drop and current for your LED and plug them into the above formula.
If you want to vary the apparent color of an RGB LED through software you can hook each color channel to a different PWM output pin on your Arduino. You then set each color channel to a different "duty cycle" to vary the brightness of that color.


text:
Is it required to delete variables before going to sleep?
This tutorial shows how to put the arduino to sleep and use a watchdog to wake up at intervals:
https://youtu.be/urLSDi7SD8M
I been studding c++ and as I am getting better I am instantiating objects with the new keyword. I have learned that if you create something with the new keyword you are responsible for deleting it from memory when you no longer needed. But I do not know if this applies when you put arduino to sleep.
Anyways my question is in the comments of the code:
Foo * someObject;

void setup()
{
    someObject = new Foo(arg1, arg2, ..); // crete an instance of someObject
   // init pins etc..
}

void loop()
{
     if(button1Pressed())
     {

          // **** DO I HAVE TO DELETE OBJECTS BEFORE GOING TO SLEEP? Do I need this line? ****
          delete someObject;

          gotToSleepAndWakeUpIn4Seconds() ;  // places arduino in sleep mode and wakes up again in 4 seconds

          int x = 0; // this line never executes arduino is on sleep mode and will wake up again in 4 seconds
     }

     // more code
     if(something)
        someObject->executeFunction1();

     // etc...
     // ....
}

No you don’t.  You just have to free it before you try to use that memory for anything else.  Really on a microcontroller I would create the object in a smaller scope and try to do everything in my power to avoid having to use new or any other form of dynamic allocation.  There are usually better ways around it in this kind of environment.  Very different from writing code to run on a PC.

You have probably learnt that objects created with new are stored in
the heap, while globals are stored in the .data and .bss sections, and
locals on the stack¹. This distinction, however, only exists in the
software. At the hardware level, .data, .bss, heap and stack are just
arbitrary portions of the RAM.
Think of what would happen if the RAM was erased, or somehow corrupted,
when the microcontroller sleeps. Not only would that affect the
heap-based objects, but also every variable in the program. And even the
return address from the call to gotToSleepAndWakeUpIn4Seconds() would
be lost, so the CPU would not know where to resume execution when it
wakes up. The only reasonable thing to do at wakeup would then be to
restart the program from scratch. And this is actually what happens when
you reset the microcontroller².
But a sleep is not a reset. The contents of the RAM is preserved while
sleeping. This means that the whole state of the program is preserved:
locals, globals and heap-based objects. No need to delete and re-create
stuff.
As a side note, if you can allocate memory statically, this is usually
better than dynamic allocation, ans you avoid the risk of heap
fragmentation:
Foo someObject(arg1, arg2, ..);  // static global instance

void loop()
{
    // Some code, then,

    if (something)
        someObject.executeFunction1();
}

Notes:
¹ As an optimization, locals of the current stack frame may be in CPU
registers, but this doesn't change the conclusion.
² On AVR, a warm reset doesn't loose the RAM, but it is then
reinitialized by the C runtime. A cold reset (power-cycle) does loose
the RAM.


text:
I2C comunication, ESP->Nano on endTransmission no ACK fron nano
i am trying to communicate between ESP(master) and arduino nano(slave). This is only a prototype and all works fine. But i want to  add multiple arduinos and therefor i need to detect if the arduino is connected.
I use the return function from wire.endTransmission as shown in i2c scanner to detect devices. But it doesnt work.
On the arduino i have this program:
#include <Wire.h>

const int16_t I2C_SLAVE = 0x22; // 0x22 = 34 cize izba 3(30)

void setup() {
  Wire.begin(I2C_SLAVE);

}

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

}

on the ESP i am trying this:
Wire.beginTransmission(I2C_adress[adress]);
int error = Wire.endTransmission();

Serial.println(error);

It returns only 2 (received NACK on transmit of address)
Why? When i have other code on the slave (with onRecive and onRequest all works and comunicates)
Thank you.

you have two aduinos with the above program?

Please show complete compilable programs for both Arduino and ESP

Thank you guys.

I'm a fool, I tried to detect other devices in the setup function before the Wire.begin(PIN_SDA, PIN_SCL,  I2C_MASTER);
I Found it only because of you. The rubber duck. I started to write the program down to post it here and bingo.
That was the reason why the master had the "NACK" answer. The master was not started yet.
Thank you