text:
LCD not displaying text (16x2)

(https://circuitdigest.com/microcontroller-projects/arduino-based-accident-alert-system-using-gps-gsm-accelerometer)
the code is
Serial.println(zValue);
..... .....
........ ...

Here we have also created some other function for various purposes like void gpsEvent() to get GPS coordinates, void coordinate2dec() for extracting coordinates from the GPS string and convert them into Decimal values, void show_coordinate() for displaying values over serial monitor and LCD, and finally the void Send() for sending alert SMS to the predefined number.
Complete code and demo video is given below, you can check all the functions in the code.
Code
#include<SoftwareSerial.h>
SoftwareSerial Serial1(2,3); //make RX arduino line is pin 2, make TX arduino line is pin 3.
SoftwareSerial gps(10,11);
#include<LiquidCrystal.h>
LiquidCrystal lcd(4,5,6,7,8,9);

#define x A1
#define y A2
#define z A3

int xsample=0;
int ysample=0;
int zsample=0;

#define samples 10

#define minVal -50
#define MaxVal 50

int i=0,k=0;
int  gps_status=0;
float latitude=0;
float logitude=0;
String Speed="";
String gpsString="";
char *test="$GPRMC";

void initModule(String cmd, char *res, int t)
{
  while(1)
  {
    Serial.println(cmd);
    Serial1.println(cmd);
    delay(100);
    while(Serial1.available()>0)
    {
       if(Serial1.find(res))
       {
        Serial.println(res);
        delay(t);
        return;
       }

       else
       {
        Serial.println("Error");
       }
    }
    delay(t);
  }
}

void setup()
{
  Serial1.begin(9600);
  Serial.begin(9600);
  lcd.begin(16,2);
  lcd.print("Accident Alert  ");
  lcd.setCursor(0,1);
  lcd.print("     System     ");
  delay(2000);
  lcd.clear();
  lcd.print("Initializing");
  lcd.setCursor(0,1);
  lcd.print("Please Wait...");
  delay(1000);

  Serial.println("Initializing....");
  initModule("AT","OK",1000);
  initModule("ATE1","OK",1000);
  initModule("AT+CPIN?","READY",1000);
  initModule("AT+CMGF=1","OK",1000);
  initModule("AT+CNMI=2,2,0,0,0","OK",1000);
  Serial.println("Initialized Successfully");
  lcd.clear();
  lcd.print("Initialized");
  lcd.setCursor(0,1);
  lcd.print("Successfully");
  delay(2000);
  lcd.clear();
  lcd.print("Callibrating ");
  lcd.setCursor(0,1);
  lcd.print("Acceleromiter");
  for(int i=0;i<samples;i++)
  {
    xsample+=analogRead(x);
    ysample+=analogRead(y);
    zsample+=analogRead(z);
  }

  xsample/=samples;
  ysample/=samples;
  zsample/=samples;

  Serial.println(xsample);
  Serial.println(ysample);
  Serial.println(zsample);
  delay(1000);

  lcd.clear();
  lcd.print("Waiting For GPS");
  lcd.setCursor(0,1);
  lcd.print("     Signal    ");
  delay(2000);
  gps.begin(9600);
  get_gps();
  show_coordinate();
  delay(2000);
  lcd.clear();
  lcd.print("GPS is Ready");
  delay(1000);
  lcd.clear();
  lcd.print("System Ready");
  Serial.println("System Ready..");
}

void loop()
{
    int value1=analogRead(x);
    int value2=analogRead(y);
    int value3=analogRead(z);

    int xValue=xsample-value1;
    int yValue=ysample-value2;
    int zValue=zsample-value3;

    Serial.print("x=");
    Serial.println(xValue);
    Serial.print("y=");
    Serial.println(yValue);
    Serial.print("z=");
    Serial.println(zValue);

    if(xValue < minVal || xValue > MaxVal  || yValue < minVal || yValue > MaxVal  || zValue < minVal || zValue > MaxVal)
    {
      get_gps();
      show_coordinate();
      lcd.clear();
      lcd.print("Sending SMS ");
      Serial.println("Sending SMS");
      Send();
      Serial.println("SMS Sent");
      delay(2000);
      lcd.clear();
      lcd.print("System Ready");
    }
}

void gpsEvent()
{
  gpsString="";
  while(1)
  {
   while (gps.available()>0)            //Serial incoming data from GPS
   {
    char inChar = (char)gps.read();
     gpsString+= inChar;                    //store incoming data from GPS to temparary string str[]
     i++;
    // Serial.print(inChar);
     if (i < 7)
     {
      if(gpsString[i-1] != test[i-1])         //check for right string
      {
        i=0;
        gpsString="";
      }
     }
    if(inChar=='\r')
    {
     if(i>60)
     {
       gps_status=1;
       break;
     }
     else
     {
       i=0;
     }
    }
  }
   if(gps_status)
    break;
  }
}

void get_gps()
{
  lcd.clear();
  lcd.print("Getting GPS Data");
  lcd.setCursor(0,1);
  lcd.print("Please Wait.....");
   gps_status=0;
   int x=0;
   while(gps_status==0)
   {
    gpsEvent();
    int str_lenth=i;
    coordinate2dec();
    i=0;x=0;
    str_lenth=0;
   }
}

void show_coordinate()
{
    lcd.clear();
    lcd.print("Lat:");
    lcd.print(latitude);
    lcd.setCursor(0,1);
    lcd.print("Log:");
    lcd.print(logitude);
    Serial.print("Latitude:");
    Serial.println(latitude);
    Serial.print("Longitude:");
    Serial.println(logitude);
    Serial.print("Speed(in knots)=");
    Serial.println(Speed);
    delay(2000);
    lcd.clear();
    lcd.print("Speed(Knots):");
    lcd.setCursor(0,1);
    lcd.print(Speed);
}

void coordinate2dec()
{
  String lat_degree="";
    for(i=20;i<=21;i++)
      lat_degree+=gpsString[i];

  String lat_minut="";
     for(i=22;i<=28;i++)
      lat_minut+=gpsString[i];

  String log_degree="";
    for(i=32;i<=34;i++)
      log_degree+=gpsString[i];

  String log_minut="";
    for(i=35;i<=41;i++)
      log_minut+=gpsString[i];

    Speed="";
    for(i=45;i<48;i++)          //extract longitude from string
      Speed+=gpsString[i];

     float minut= lat_minut.toFloat();
     minut=minut/60;
     float degree=lat_degree.toFloat();
     latitude=degree+minut;

     minut= log_minut.toFloat();
     minut=minut/60;
     degree=log_degree.toFloat();
     logitude=degree+minut;
}

void Send()
{
   Serial1.println("AT");
   delay(500);
   serialPrint();
   Serial1.println("AT+CMGF=1");
   delay(500);
   serialPrint();
   Serial1.print("AT+CMGS=");
   Serial1.print('"');
   Serial1.print("9821757249");    //mobile no. for SMS alert
   Serial1.println('"');
   delay(500);
   serialPrint();
   Serial1.print("Latitude:");
   Serial1.println(latitude);
   delay(500);
   serialPrint();
   Serial1.print(" longitude:");
   Serial1.println(logitude);
   delay(500);
   serialPrint();
   Serial1.print(" Speed:");
   Serial1.print(Speed);
   Serial1.println("Knots");
   delay(500);
   serialPrint();
   Serial1.print("http://maps.google.com/maps?&z=15&mrt=yp&t=k&q=");
   Serial1.print(latitude,6);
   Serial1.print("+");              //28.612953, 77.231545   //28.612953,77.2293563
   Serial1.print(logitude,6);
   Serial1.write(26);
   delay(2000);
   serialPrint();
}

void serialPrint()
{
  while(Serial1.available()>0)
  {
    Serial.print(Serial1.read());
  }
}

Please make your code readable by putting it in a code block. Also reduce your code to what you need to examine your problem (which is trouble printing to the LCD display). All the other GPS/coordinate calculation code you've included is just noise at this moment. Also, it would be nice if you could include the image in your question instead of in a link. You mention a demo video but it's not there.

One more question: have you tried to adjust the LCD contrast with the potentiometer?

Can you see anything on the LCD?

@Ch Murali, Please answer our questions.


text:
Initialize object with PROGMEM constants
I have a class which has a const char * property:
    class A
    {
    public:
        const PROGMEM char* text;
    };

    void setup()
    {
        // A a{"Hello World!"};
        // A a{PSTR("Hello World!")};

        A a;
        a.text = PSTR("Hello World!");

        Serial.begin(9600);
        delay(30);
        Serial.println(a.text);
    }

    void loop()
    {
    }

I’d like to spare some RAM using PROGMEM.
How to initialize a object then?
Obviously, it can’t be like this:
    A a{PSTR("Hello World!")};

This will do:
    A a;
    a.text = PSTR("Hello World!");

However, I need to pass string to the constructor.

does a.text = F("Hello World!"); do what you want?

@dandavis, it does not. you've missed that a.text is not const __FlashStringHelper* - it's const char*

It is a shame that gcc only supports the __flash qualifier in C mode,
not in C++, so we have to use PROGMEM instead. Unlike __flash, which
qualifies a variable just like const, the PROGMEM attribute only has
effect when allocating room for a variable. Once the allocation is done,
the compiler forgets about the attribute. In particular, a declaration
such as
const PROGMEM char* text;

does not allocate flash space, so it generates the warning
warning: ‘__progmem__’ attribute ignored [-Wattributes]
     const PROGMEM char* text;
                         ^

You can thus forget the attribute when declaring a pointer, as there is
no such thing as a “pointer to PROGMEM”. You just use a const char *
instead.
Now, the second issue is that, as far as Serial.println() is
concerned, the pointer above is a plain const char *, so it will
interpret it as an address in RAM, and print garbage. If you want
Serial.println() to know you are giving it an address in flash, you
should provide it with a const __FlashStringHelper* pointer.
Here is the solution I propose. Tested on an Uno-compatible board:
class A
{
public:
    A(const char* s)
        : text(reinterpret_cast<const __FlashStringHelper *>(s)) {}
    const __FlashStringHelper* text;
};

void setup()
{
    A a{PSTR("Hello World!")};
    Serial.begin(9600);
    Serial.println(a.text);
}

void loop(){}

Edit: After seeing the last version of Juraj’s answer, I must say
that I agree with him. Since we are using the Arduino API, it makes more
sense for the constructor to take a const __FlashStringHelper*, and
for the caller to use the F() macro.

your solution works fine! thank you very much!

const char* text; is a pointer to constant not a constant pointer (char * const text is a constant pointer). So you can assign a pointer to a constant char array to const char* text; even a pointer to an array in PROGMEM.
The compiler doesn't know the difference between a PROGMEM pointer and a pointer in SRAM. It is on you to work in code with a pointer to PROGMEM the right way.
so remove PROGMEM from const PROGMEM char* text;

add constructor to initialize an object.
A(const char* _text) {
  text = _text;
}

and then
A a(PSTR("Hello World!"));

EDIT:
you could use Arduino's F() macro and __FlashStringHelper type, because it is supported by Serial print and co.
class A
{
public:
  A(const __FlashStringHelper* _text) {
    text = _text;
  }
  const __FlashStringHelper* text;
};

void setup()
{
    A a(F("Hello World!"));

    Serial.begin(9600);
    delay(30);
    Serial.println(a.text);
}

void loop()
{
}

__FlashStringHelper type is trick to distinguish PROGMEM strings from char arrays in SRAM..

This is not an answer on my question. How to store strings in flash memory? Strings must be passed to the contructor.

it is unclear what is what you don't know. I enhanced the answer

Hum... Your solution won't let use Serial.println. And added user-defined  constructor does not any difference here.

@zhekaus, yes, your question combined 3 problems. Edgar got them all, but the true solution is to use F macro, not PSTR, if possible. I enhanced the answer

source: Stack Exchange

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

sort: votes


text:
Gauss solver for IIR filter
I write a piece of code in online GDB using c++, the code calculates some coefficients for a IIR filter which tries to approximate a fractional derivative and integral for a fractional PID control. The code works as expected in the online IDE, but when I try to execute it in a Arduino Due, the results and only overflows and nan, and really don't know what's the problem so,
Here is the code in GDB online https://onlinegdb.com/rycwt62XL which gives the expected results:
Array A, Array B
1.41421,1
-0.707107,0.5
-2.12132,-1.5
0.883883,-0.625
0.883883,0.625
-0.265165,0.1875
-0.0883883,-0.0625
0.0110485,-0.0078125
And here is the code for the Arduino Due, which only change the printing method using the serial commands, https://onlinegdb.com/ByAs5xyVU, and the results are:
Array A, Array B
ovf,1.00
ovf,ovf
ovf,0.00
inf,ovf
ovf,0.00
inf,ovf
ovf,3.89
inf,ovf
And really don't know where to start for fix this results, thanks. The Method is  exactly the same.

Works fine on every piece of hardware I have tested, except the Due. I've never liked the Due - the compilation has always been really really shaky...

Majenko, I tested on the arduino Mega and works really well, but I've donde all the programming in the Due, but thanks

I can't find the root cause of the problem - it's probably because the Due is possibly the worst board that Arduino ever made, and the compiler / linker / support libraries barely work at the best of times.
However, some things you need to look at in your code:
    double* h = new double[L];
    for(int n = 0; n <= L; n++){
        for(int k = 0; k <= n; k++){
            h[n] += pow(operador,-alpha-n+k)*pow(1.0-operador,n-k)*Binomial_E(alpha,k)*Binomial(-alpha,n-k);
        }
    }

There you allocate L (15) doubles in an array. But then you go on to access array slices 0-15. That's 16 entries in an array of size 15, so you're overflowing it and corrupting other memory.
Also you have no delete to balance the new, so you have a memory leak.  You would be better using:
double h[L+1];

instead of new.

You are right, I avoid using arrays with variable size and works, thanks so much

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


text:
ESP8266/Android app: slow response when using soft access point and keeps dropping connection
I have an ESP8266 which I'm using the Arduino IDE to compile a program which
uses soft access points to talk to an Android App compiled using MIT App Inventor. The app seems to work the first couple times but then my cell phone looses connection and I have to go to Settings->Wifi connections and rescan and wait for it to connect. Sometimes it says: "Denied access to network" and sometimes (most always) after I connect I will get a message that says I'm not connected to the internet, which I don't want, and then choose 'No' to stay connected to the current network. My cell phone is right next to the ESP8266 and the signal strength is 'Excellent'. I'm only powering the board via the USB cable connected to it. Do I need to run 3v3 to the pin marked '3V3'?
Here's the code:
// server running on ESP8266 to get commands from Android App
// Load Wi-Fi library
#include <ESP8266WiFi.h>

// Replace with your network credentials
const char *ssid = "PanzerD"; // The name of the Wi-Fi network that will be created
const char *password = "testasdf";   // The password required to connect to it, leave blank for an open network
// Set web server port number to 80
WiFiServer server(80);
IPAddress local_IP1(192,168,0,15);
IPAddress gateway1(192,168,0,1);
IPAddress subnet(255,255,255,0);

// Variable to store the HTTP request
String header;

// Auxiliar variables to store the current output state

// Assign output variables to GPIO pins
int tool_box_lights = 0;
int pass_side_lights = 0;
int drv_side_lights = 0;
int rear_lights = 0;
int winch = 0;

// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;

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

  Serial.print("Setting soft-AP configuration ... ");
  Serial.println(WiFi.softAPConfig(local_IP1, gateway1, subnet) ? "Ready" : "Failed!");
  Serial.println(WiFi.softAP(ssid,password,1,4) ? "Ready" : "Failed!");

  Serial.print("Soft-AP IP address = ");
  Serial.println(WiFi.softAPIP());

  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
/*
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
*/
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
//  Serial.println("IP address: ");
//  Serial.println(WiFi.localIP());
  server.begin();
}

void loop(){
  WiFiClient client = server.available();   // Listen for incoming clients

  if (client) {                             // If a new client connects,
//    Serial.print("Client: ");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    currentTime = millis();
    previousTime = currentTime;
    while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
      currentTime = millis();
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
//        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();
            //Serial.println(header);
            // turns the GPIOs on and off
            if (header.indexOf("/tb/on") >= 0)
            {
              Serial.println("toolbox on");
              client.println("toolbox on");
              tool_box_lights = 1;
            } else if (header.indexOf("/tb/off") >= 0)
            {
              Serial.println("toolbox off");
              client.println("toolbox off");
              tool_box_lights = 0;
            } else if (header.indexOf("/ps/on") >= 0)
            {
              Serial.println("pass side on");
              client.println("pass side on");
              pass_side_lights = 1;
            } else if (header.indexOf("/ps/off") >= 0)
            {
              Serial.println("pass side off");
              client.println("pass side off");
              pass_side_lights = 0;
            } else if (header.indexOf("/ds/on") >= 0)
            {
              Serial.println("drv side on");
              client.println("drv side on");
              drv_side_lights = 1;
            } else if (header.indexOf("/ds/off") >= 0)
            {
              Serial.println("drv side off");
              client.println("drv side off");
              drv_side_lights = 0;
            } else if (header.indexOf("/rr/on") >= 0)
            {
              Serial.println("rear lights on");
              client.println("rear lights on");
              rear_lights = 1;
            } else if (header.indexOf("/rr/off") >= 0)
            {
              Serial.println("rear lights off");
              client.println("rear lights off");
              rear_lights = 0;
            } else if (header.indexOf("/wc/in") >= 0)
            {
              Serial.println("winch in");
              client.println("winch in");
              winch = 1;
            } else if (header.indexOf("/wc/out") >= 0)
            {
              Serial.println("winch out");
              client.println("winch out");
              winch = 2;
            } else if (header.indexOf("/wc/off") >= 0)
            {
              Serial.println("winch off");
              client.println("winch off");
              winch = 0;
            }
            // Display the HTML web page
            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
//    Serial.println("Client disconnected.");
//    Serial.println("");
  }
}

Here's the blocks for the MIT App Inventor:

Each one of the blocks responds to a button press and depending on what the global variable is (upper left block is for toolbox lights) it will send the URL "/tb/on" in the case for turning the toolbox lights on.
[Edit:] It works fine when I use the modem as an access point but I need soft access points because I don't want to have to carry a router around in my truck.

Apparently I'm not formatting the html right and it's causing the connection to drop.


text:
Which board to use for wireless communication of small packages?
I was hoping to get your advice on what Arduino boards to look at for a project I'm working on. The project involves two separate boxes in different rooms of my apartment (~ 5-10 feet away from each other) and needs to allow wireless communication of very small amounts of information (think like 5 bytes). However, this transfer needs to be very rapid (within 200 milliseconds).
While I have worked a good bit with the Arduino Uno, I haven't worked with boards with Wifi capabilities.
The boards I know of are: Esp32, Esp8266, Arduino MKR 1010, Arduino Mega RobotDyn.
What would be the best board for a project like this / are there other boards that are well-suited for a project like this?
Thanks!

i would consider ESP-NOW. It's under-appreciated imho for what it can do, but it's taken my smart home to a new level with cheap battery-powered "infinite standby"  sensors and actuators.

WiFi round trip time is about 2-50 ms (50 is the worst case), so, you can use the ESP's and the UDP/TCP.
On the other hand, you can use the NRF433 module, but in this case, you have to develop your own channel level protocol, with error detection/correction and so on.
Also, there are ZigBee module. They developed for home automation specially.


text:
Stepper motor is only moving one step at a time with an IR sensor
I am trying to get both the motors to run simultaneously once the motion detector senses an obstacle. Both motors run fine by themselves but when I implement the sensor the motors only move one step per motion detected.

Arduino Mega (ATMega 2560)
(2) NEMA 17 stepper motor/ A4988
Digital IR Sensor Module

#include <Arduino.h>
#include <avr/io.h>
#include <AccelStepper.h>

AccelStepper stepper(1,5,4); // w/Driver (1,Step, Direction)
AccelStepper stepper2(1,9,8);

const int pin_ir_in = 3;
int prev_state = 1;
int curr_state = 1;
int counter =0;

void setup() {
  Serial.begin(9600);
  pinMode(6,OUTPUT); // Enable
  pinMode(10,OUTPUT);

  digitalWrite(6,LOW); // Set Enable low
  digitalWrite(10,LOW);
}

void loop() {
  digitalWrite(6,LOW); // Set Enable low
  if (stepper.distanceToGo() == 0)
  {
    delay(1000);
    stepper.moveTo(100);
    stepper.setMaxSpeed(200);
    stepper.setAcceleration(100);

  }

   digitalWrite(10,LOW); // Set Enable low
     if (stepper2.distanceToGo() == 0)
  {
    delay(1000);
    stepper2.moveTo(100);
    stepper2.setMaxSpeed(200);
    stepper2.setAcceleration(100);

  }

int curr_state = digitalRead(pin_ir_in);
if (curr_state != prev_state)
{
  if (curr_state == 0)
  {
    stepper.run();  // Actually makes stepper move
    stepper2.run();
    delay(500);
  }
  prev_state = curr_state;

}

}

I think the run function must be called repeatedly until you reach the position and not just once

As chrisl said, you need to call run repeatedly.
I tried to rewrite the code you've given, though I'm not entirely sure what it is you try to achieve.
void loop()
{
  stepper.run();  // Actually makes stepper move
  stepper2.run();

  int curr_state = digitalRead(pin_ir_in);
  if (curr_state != prev_state)
  {
    if (curr_state == 0) // Motion sensor activated
    {
      stepper.moveTo(100);
      stepper.setMaxSpeed(200);
      stepper.setAcceleration(100);
      stepper2.moveTo(100);
      stepper2.setMaxSpeed(200);
      stepper2.setAcceleration(100);
    }
    prev_state = curr_state;
  }
}


text:
Which libraries for DS1302 real time clock and WS2811 LED strip do not conflict?
I am making a custom wall-clock, and need the Arduino (Uno or Nano) to connect to a DS1302 real time clock module and a WS2811 LED chain.
So I’m using DS1302 for the clock, and FastLED for the lights. Individually these two libraries work fine, so I can either echo the time to the serial console, or I can drive the LEDs as I need.
But when I combine them there is some conflict happening and I get no LED output. The LED data goes over pin 6 and the clock uses pins 2,3,4 (these pins are customisable in code).
Even just adding a DS1302 initialisation to a working FastLED sketch causes no more LED output
#include <FastLED.h>
#include <DS1302.h>

#define NUM_LEDS 50
#define DATA_PIN 6

// Init the DS1302 - stops LEDs working
DS1302 rtc(2, 3, 4);

CRGB leds[NUM_LEDS];

void setup() {
  FastLED.addLeds<WS2811, DATA_PIN, RGB>(leds, NUM_LEDS);
}

void loop() {
  for (int i=0; i<NUM_LEDS;i++) {
    leds[i] = CRGB::Red;
  }
  FastLED.show();
  delay(100);
}

What are my troubleshooting steps - should I try alternative libraries, or could I dig into the libraries themselves and see what hardware resources they might be using?
I guess as both the lights and the clock probably operate over a serial protocol, it could be a conflict with the serial drivers - maybe both using the same time-critical operations.
Edit: inserted sketch which demonstrates the issue

Don’t have access to actual code at the moment, the above hopefully is a minimum working example to demo the issue, also the light sequence is fairly complex and arbitrary, so at this stage just want to find any way of getting both rtc and leds operating at same time

Do you ever try to switch pin 3 to 9?

That DS1302 library you point to is very old. Did you try using a more recent library like the one from Richard C. Miller that can be installed from the Arduino IDE?

There are more precise RTC modules (DS3231) using I2C, which is supported by hardware: won't affect FastLED timing.

I installed a library from within the IDE as StarCat suggested.
https://github.com/Makuna/Rtc
#include <FastLED.h>
#include <ThreeWire.h>
#include <RtcDS1302.h>

#define NUM_LEDS 50
#define DATA_PIN 6

ThreeWire myWire(3,4,2); // IO, SCLK, CE
RtcDS1302<ThreeWire> Rtc(myWire);

CRGB leds[NUM_LEDS];

void setup() {
   FastLED.addLeds<WS2811, DATA_PIN, RGB>(leds, NUM_LEDS);
   Rtc.Begin();
}

void loop() {
   RtcDateTime dt = Rtc.GetDateTime();

   for (int i=0; i<NUM_LEDS;i++) {
     leds[i] = CRGB::Red;
   }

FastLED.show();
delay(100);
}

I am able to get and use the time, and the LED output works.


text:
NEO-6M is working but it doesnt show data
So I'm having a little bit of difficulty here in my NEO-6M. The problem is it doesn't show any data in my serial monitor. My NEO-6M Led is already blinking so its already ok.
RX -> Pin3 , TX -> Pin4 , VCC -> 3.3v , GND -> GND

Serial Monitor:

Code:
https://github.com/mikalhart/TinyGPSPlus/blob/master/examples/FullExample/FullExample.ino

Have you crossed the serial lines? Arduino RX to GPS TX, Arduino TX to GPS RX

I have but I already fix it, does it broke my neo?

What do you mean? The lines need to be crossed. And having them not crossed most likely doesn't break it

Iv'e updated it now. @chrisl

I found a solution to my problem. On my first setup, I separate my GND of NEO-6M to Arduino and put connect it in breadboard that has powerboard on it because I thought it is only for electrical purposes but it doesn't since I encounter it.
Solution:

The GND of every module must still connect on the Arduino.


text:
upload sketch via bluetooth for android
How can i convert file .ino to hex file so that i can compile new sketch via bluetooth. Can you help me to figure out the way to do this? thanks for helping

You press the "verify" button in the IDE. That makes a .hex file. But I don't think that's really your question, though, is it? Getting a HEX file is the easy part. Uploading from android isn't. You would need something to implement the Arduino bootloader protocol in Android. No clue if there is anything out there to do that for you or not. Maybe Google can help?

https://play.google.com/store/apps/details?id=io.iotool.iotoolarduinohex&hl=en_GB

i mean like bluino app or arduinodroid app they can compile code via bluetooth, so i really wants to understand  how arduino receives data. Sorry sir because my question isn't clear. hope you help

You don't compile code via bluetooth. You compile code on your computer, then copy the compiled .hex file to your phone to upload with whatever app you choose.

so i need to find way compile it by java or computer, and then send compiled .hex file to arduino via bluetooth to make it work

You press the "verify" button in the IDE.  -- Then you use your favourite file transfer tool over whatever protocol you prefer (I use Amaze to access a share through the network). Then you use the Arduino programmer app.

let me explain what i aim to do , that i want to make an android app that can create ino  then upload it via bluetooth to arduino to make robot work and instead of controlling just send a string to control that i would want replace a whole file in arduino chip

So you want to write your own Android-based IDE, and port the compiler to Android? Good luck with that. There's a reason people write web-based applications...

thank you sir, you are so nice.

It is very hard to understand exactly what you want to do, but from what I can gather you want to:

Write an Android application that lets you edit sketches
Compile those sketches on an android device, and
Upload those compiled sketches to an Arduino over Bluetooth

While what you are asking is technically possible, it is not realistically practical.
Writing a text editor in Android is easy enough. That's not a problem. It's the compilation of the code that is not practical.
You would need to port the compiler (a very large project written in C) to Android. That would essentially need to remain as compiled C code, and so you would have to individually port it to each possible platform you want it to run on (various different types of ARM, Intel, etc) and for different versions of android.
Unless you're a genius at Android and C programming that's just not going to happen.
A more practical way would be to write a web-based application that allows you to edit your sketches, which can then run the compiler on a real computer (no porting needed then), which can then download the compiled HEX file to your Android device, then use a pre-existing application to program that HEX file over bluetooth.
Alternatively, just use the Arduino Create website to compile and download your HEX file.


text:
Arduino-compatible Bluetooth classic module to use in a product
I've been designing a product for some time using arduino language, but on our own hardware. Recently a need arose to add some Bluetooth capability to our product. We decided to use BT classic instead of BLE, because not every phone has BLE capability yet. Of course immediately I went to check HC-05 modules and their cousins. The issue is I believe they are a chinese product and have no FCC certification and I can't buy them from any reputable source (digikey,mouser,farnell etc.).
Seeing that this is an issue for a product I went and checked the mentioned suppliers to see what they offer. The thing is though, I'd like to stay in the arduino environment so I'm looking for a module that has some support from the arduino side.
I found this module from Cypress, that has this "arduino-compatible" code. However when a tried to find any library that I could use to program this board using arduino environment on Cypress's site I only found mentions of their own SDK.
Thus comes the question: are there any FCC compliant bluetooth modules that have an easy to use arduino library available?

You've got the same compatibility issue whether you choose BLE or BT-2. Not every phone has BT-2 either: iPhones have had BLE (only) for some time.

Hmm didn't know that. Thanks for the heads-up.

You should choose chip that support at least bluetooth 4.0 or above (i.e. BLE capable) as this is most of the phones or other products supporting now. BT2.0 probably only supported by products that are more than 10 years old.

There are plenty of FCC pre-certified modules to choose from, look at their FCC certified ID which is usually available on the RF shield cover of the module.


text:
ESP-12 + FTDi + platformio
I have 2 questions.

Why we have to put our functions before void loop and void setup into VScode+platformio?
I switched from arduino IDE to VScode+platformio today, when I upload the sketch with platformio into my esp-12, it doesn't work. (It works with arduino IDE)

I have this Warning: src\main.cpp:46:24: warning: large integer implicitly truncated to unsigned type [-Woverflow]
 const byte menuColor = 0XF206;
[EDIT]The problem comes from these lines:
attachInterrupt(digitalPinToInterrupt(enA), enAin, RISING);
attachInterrupt(digitalPinToInterrupt(enB), enBin, RISING);
attachInterrupt(digitalPinToInterrupt(enBtn), enBtnIn, FALLING);

read [Functions in C++](For question 1, read Function in C++ for better understanding on function declaration. For question 2, 0xF206 is 16-bit long, or 2 bytes, so you should declare your variable as use const unsigned int menuColor = 0xF206;, and read more here.

"when I upload the sketch"   .... that should say when I compile the sketch .... the upload happens after your sketch is successfully compiled .... in your case, the upload to the ESP-12 never happens

Why we have to put our functions before void loop and void setup into VScode+platformio?

Because that is how C works. The Arduino IDE hides it from you by adding function prototypes at the start of your code.

I switched from arduino IDE to VScode+platformio today, when I upload the sketch with platformio into my esp-12, it doesn't work. (It works with arduino IDE)

const byte menuColor = 0XF206;

That can never work. The value 0x06 will be assigned to menuColor since a byte is only 8 bits.  You need to learn to use data types that are suitable for the values you are trying to store in them.

Thank, you I understand my error with menuColor. Now I know what's the problem.
#include <Arduino.h>

const int enBtn = 3;

void en(){
    digitalWrite(2,1);
    delay(500);
    digitalWrite(2,0);
    delay(500);
}

void setup() {
  pinMode(2, OUTPUT);
  pinMode(enBtn, INPUT);
  attachInterrupt(digitalPinToInterrupt(enBtn), en, FALLING); //Doesn't work into platformio
}

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


text:
MB-102 BreadBoard Power Supply Limitation

Does the MB-102 can handle Arduino Uno, SIM900 and 3 other modules that requires 5v? If yes, does 9v battery is enough? If no, please suggest me what should I use that uses only 1 barrel jack(if possible).

Im afraid that I might fry it if I try cause I dont have enough knowledge about electric currents.

breadboards can handle a few amps. the limit is the socket, not the busbar, so you can use 2+ wires per column to increase power handling or lower dropout if needed.

Does the MB-102 can handle Arduino Uno, SIM900 and 3 other modules that requires 5v?

You mean because the current requirements? The answer is yes and no. No, because the needed current must not flow through the Arduino. The SIM900 draws up to 2A, that current would fry the protection diode/voltage regulator on the Arduino (though you may get away with a bit less than that by using a big capacitor to accommodate current spikes). Depending on the version of the Uno, it can provide 200mA or 1A (in case of rev3)(including what is needed for the Uno to operate). You need to provide the 5V of these modules from outside of the Arduino, via an extra voltage regulator, which can handle the big current.

does 9v battery is enough?

If you mean the standard 9V block battery, then no, never. These batteries are meant for low power applications and are almost never a good choice for an Arduino project (unless you have really a low power application). You need to use different batteries, for example a series of AA batteries or a LiPo pack (including the needed circuitry for such a pack).

I'am connecting Arduino Uno into MB-102 power supply(usb socket) and also the other 5v modules and SIM900 so it is consider that I connect the 5v modules outside of Arduino Uno. The problem is does the MB-102 can handle that?

Yes, thats outside the Arduino. You need to google the maximum output current (or check with your supplier). This site states an output cutrrent of only 700mA. Don't know, if this os the same as yours. Also you need to make sure, that your USB port can provide enough current. USB ports of a PC only provide up to 500mA.


text:
Can I control a 28BYJ-48 5V stepper with a DVR8825 driver?
I have a stepper motor 28BYJ-48 rated 5 V and I want to use a DVR8825 driver so I can use the 1/32 micro-stepping feature. My problem is that DVR8825 has a minimum operating voltage of 8.2 V. Would the 28BYJ-48 stand a 10 V input?
Is there any alternative to the DVR8825 that operates at 5 V and has at least 1/32 micro-stepping?

just because the DVR8825 uses a 10 V power supply, it does not mean that it necessarily delivers 10 V to the motor

Having the same concerns. There is a 12 volt variation of that motor. I just ordered a pair and found this article. I'll now try Towe's remedy above. Thank you.

Stepper motors are rated in two different ways. Some provide a "rated voltage" in combination with a "DC resistance", others provide a "phase current" and a "phase resistance". The way they operate is identical.
Stepper motors such as your 28BYJ-48 are usually intended to be driven with a fixed voltage, their rated voltage. At this voltage, the maximum permittable current flows in the steppers windings - determined mostly by cooling and wire thickness. If you exceed that voltage, more current will flow and will damage / destroy the stepper motor.
The DRV8825 is a current controlled stepper motor driver - it always uses the full available supply voltage - 8.2V+ - but uses PWM to limit the current actually flowing in the stepper. This is possible because the stepper motor coils are inductors, which inhibit the flow of current.
To use your stepper motor with a DRV8825 driver, you'll have to calculate the steppers equivalent "maximum phase current". According to this datasheet, it's rated 5 V at 50 Ohms, giving us a current of 0.1 A. You can then set this current via the potentiometer on the driver chip. The Vref voltage should be set so that Vref = Imax / 2.
Start at a Vref of 50 mV, and see how warm the motor gets and whether it's as strong as you would expect it to be.


text:
Reading from 2 serial ports
I have 2 Arduino Nano, they are connected via ports 2 and A2
While I use only one port to receive, it works properly. But if I activate the second port, system crash (and even first port don't work properly)
Code of first Arduino:
#include <SoftwareSerial.h>
SoftwareSerial SerialPort2(2,A2);
SoftwareSerial SerialPort3(3,A3);

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

void loop() {
  delay(500);
  SerialPort2.listen();
  if(SerialPort2.available()){
    char value = SerialPort2.read();
    Serial.print(value);
    Serial.print(" First port\n");
  }
  // IF YOU REMOVE PART BELLOW, THE 'SerialPort2' WILL WORK PROPERLY
  SerialPort3.listen();
  if(SerialPort3.available()){
    char value = SerialPort3.read();
    Serial.print(value);
    Serial.print(" Second port\n");
  }
  // END OF THIS PART
}

Code of second Arduino:
#include <SoftwareSerial.h>
SoftwareSerial SerialPort2(2,A2);

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

void loop() {
  SerialPort2.write('a');
  delay(1000);
}

PS in real system I need to listen 6 ports

you think the other side will wait until you listen? you switch listen() so fast so no port will listen

@Juraj yes of course

so no it will not wait. it has no clue to know if the port listens

switching listen() clears the receive buffer. after listen() wait for data

@Jurai each serial has own buffer

no. buffer is static

@Juraj,thnks much for your answer ,  but if I wait after listen(), I can loose data from another serial. Is any way to receive data from 2+ ports simultaneously?

@Juraj to be correct, I don't know the port from what I receive the data. I don't receive data from 2 ports simultaneously, only from one, but it may be any port

can you use RS485?

@Juraj no way, it is too big

@Jurai only ard to ard without any accessories

SoftwareSerial is only a "good" choice (for certain values of "good") if you only use one instance, and that is the only serial port in the system.
Using SoftwareSerial to read from 2 ports simultaneously is not possible.  Using SoftwareSerial to read data in tandem with any other hardware serial ports will result it data loss.
SoftwareSerial is only any real use when you are using it to request data from another device and times when you command it to happen.
To receive data in an "unsolicited" fashion SoftwareSerial is not good.
Instead you need a hardware serial port for each incoming signal. And obviously you can't do that with a small board like a nano.  So you need to think more creatively.
If you have one real serial port you can talk to one device. But there are other communication channels at your disposal. So you take one board and have that communicate to one of your serial devices. Then you take the data read and convert it into another communication protocol that is capable of sharing time with other boards. Then that, and 5 other boards, all send their data (or get data from) one central "master" board.  In effect you have 6 "UART to Protocol X" converter boards, and one "Protocol X" master board.
Alternatively choose a board that has 6 UARTs. There are many higher-end chips like some ATSAMD, SAMX, and PIC32 chips, that have 6 UARTs available to you.

SoftwareSerial can only listen to one port at a time. You cannot listen to both, no way. To really listen to both, you need an Arduino with more hardware Serial ports, where most of the protocol is done in hardware, thus can receive without CPU intervention. The Arduino Mega has 4 hardware Serial ports.
Or you could impose a protocol on the Serial stream to make the listening Arduino the master. You would listen to the first serial interface, send a start byte over this interface, that tells the slave Arduino to start sending. It sends and the listening interface receives (The transmission has to be delimited by either a time limit, e.g. listen for a specific time, or by a stop byte). Then you listen to the next interface, send again the start byte and receive. And so on.
With such a protocol, you could even use a single serial interface. The protocol makes sure, that only one slave is transmitting at a time. Though you should add resistors to every slave to protect their TX pins.

in real system I need to listen 6 ports

Serial (UART) is really not the best interface type for such topology. You should consider using interfaces like SPI. It doesn't need additional electronics and is better fit for multiple slaves.

In my system I have 6 masters and 1 slave. What interface do you recommend to use?

I have written about using 1 master, because I suggested to overthink your topology. Multi master is difficult with every interface, that you have on the Nano. You should think about, if you really need multi master functionality. You didn't describe your application, so I cannot know about that. Or, if you need it, then you may have to extend to a more complex interface, that is not supported by the Nano itself.


text:
How to create a USB CDC device. (I'm using stm32f103c8 black pill board) and I want to read the data through USB in my raspberry pi as a serial port
How to create a USB CDC device. (I'm using stm32f103c8 black pill board) and I want to read the data through USB in my raspberry pi as a serial port.
I am using a black pill to read RFID-rf522 to read a tag (SPI) and send it to raspberry pi through a USB (using DM and DP pins).
Quick responses are welcomed.

It depends on what the core provides. If it's like others, then Serial.begin(115200); or maybe USBSerial.begin(115200); will do it. Read the manual for the STM32F1 core on the website for that core.

Could it be that you might be better off just to use the STMicro code for what you are doing?

if you use the core by STM select USB support in Tools menu

You can use the one provided by generating it with STMCubeMx. This is going beyond arduino though. But it is highly feasible.


text:
10 DOF gyro and accelerometer to x,y,z displacement
I have a 10 DOF sensor with wire outputs labeled "VIN", "GND", "SCL", and "SDA".  I would like to wire these into my arduino and ultimately obtain x, y, and z displacement.  This might sound like a simple problem for a veteran but I have gotten lost in the literature and code.  Where can I learn how to do this or is there a library that I can use?

Google "10 DOF IMU" should give you plenty of information. Here is a learning resource based on Adafruit products https://learn.adafruit.com/products/1604/guides

When asking a question here it is always appreciated if you include part numbers.  Or vendor web pages.  Guessing, SCL is a serial clock line and SDA is the serial data line.  So it sounds like you have a chip which talks over an I2C serial bus.  So you need the I2C Arduino library.  But, the real problem - what does the chip look like inside?  How many registers?  What do the bits mean in those registers?  How do you control this chip?  That's why you need a part number.

Step one: Read the number(s) on the chip(s). Step two: find libraries and tutorials for those chips.

I think this is it.  https://www.dfrobot.com/product-818.html

The link to the datasheets is at the bottom of this page, https://wiki.dfrobot.com/10_DOF_Mems_IMU_Sensor_V2.0_SKU__SEN0140, but I don't know what is relevant in my case.


text:
Arduino Analog to Digital Conversion from 56V DC Batteries
I have a problem, I am using 56V DC combined batteries system. I get ADC values comes to Arduino like 211, 217 etc... I have to find out when the DC volt drop to 42V. How do i know the digital value for the ADC from Aruino.

Your code and circuit please, or we are just not able to help you. Ypu cannot measure voltages greater than 5V with the Uno, so you need circuitry to divide the voltage down to that range

I'll assume you're using Li-Ion batteries in 14s configuration. You'll want to measure voltages up to around 60 V while charging. With a bit of safety margin, I'd set it up to measure up to 72V without damaging the Arduino - which can measure voltages up to 5 V, but the input on that pin should never exceed 5.5 V.
To bring your battery voltage down to something the Arduino can use, you'll need to use a voltage divider, as chrisl suggested.

With R1 = 10 kOhm and R2 = 680 Ohm, you'd get readings up to an input voltage of 78 Volts.
With analogRead() returning values between 0 and 1023, your 42 V cutoff would be around 546.

Warning: this is going to get math-heavy
Ok. So you have a battery with a voltage divider on it, and you are using the Aruino ADC to read the output of that voltage divider. And you want to "back-calculate" the battery voltage from the ADC reading.
First let's look at exactly what happens with a voltage divider and just how it works. For that we'll turn to good ol' Ohm's Law.
Rule number one is that two resistors in series sum their resistances. So if you have a 10kΩ and 680Ω resistor in series (as suggested in @towe's answer) the total resistance is 10680Ω.  We'll use this arrangement as our example.
Now Ohm's Law states that the current flowing through a resistive load is directly proportional to the voltage across it. So for a fixed resistance and a given voltage we can calculate the current that will be flowing through the resistors.  That formula is:
I=V/R
So for a voltage of 56V and a resistance of 10680Ω we can say that the current is 56/10680 amps - or about 5.24mA.
Great. But so what? Well, now we can reverse the formula and find the voltage across a given resistance for that specific current. Which we can do for, for example, the 680Ω resistor.  We know that the same current is flowing through both resistors (since they are in series), so flipping the formula around we get:
V=I×R
So at 0.00524 amps and 680Ω that's 0.00524×680 = 3.57V.  We can do the same for the 10kΩ resistor: 0.00524×10000 = 52.43V.  And oh look - if we add those two voltages together, what do we get? We get 56V. The resistors have divided the voltage into two portions.
You can combine those two formulae together to give you:
VOUT = VIN × (R2 / (R1 + R2))
And if we move the VIN to the left hand side we get:
VOUT / VIN = (R2 / (R1 + R2))
And that is known as the transfer function, or the ratio of the input to output voltage of the voltage divider.
For a 10kΩ (R1) and 680Ω (R2) resistor pair we get 680/10680 = 0.0637.
And that is the "magic number" we want to calculate back from the ADC to the battery voltage.  Whatever the voltage we read at the ADC the battery voltage is the reciprocal of that number times bigger (reciprocal is "one over the value").  The reciprocal of 0.0637 is 15.7.  So if you read the value from the ADC then convert that into a voltage relative to the internal reference voltage (approximately 5V for a normal Arduino) then multiply that voltage by 15.7 you will get your battery voltage.
So next is to get the ADC voltage. And again, it's all ratios.  The ADC gives you a number that is a ratio of the incoming voltage to the reference (5V) voltage.  At 1023 you get "5V minus 1 LSB", so about 4.995V. We don't need that kind of accuracy for this, really, so we'll just call it 5V.
Say you read 482 from the ADC, if you convert that into a voltage you take the ratio 482/1024 and multiply it by the reference voltage (1024 is the range of a 10-bit ADC - you would change that for other types of ADC):
VIN = 482 / 1024 × 5 = 2.35V
Multiply that by our "magic number" 15.7 and you get 36.95V - and that's the battery voltage.


text:
Aruino UNO not getting programmed on MAC OSX
I am using MAC OSX Mojave and trying to program an Arduino UNO board. However, whenever I start the Arduino IDE, I only find one port in the ports section called: /dev/cu.Bluetooth-Incoming-Port.
When I select that, since there is no other option, I get the following error code on pressing 'Upload' button. The error code I receive is given in image.
My programmer is ArduinoISP and the board is Arduino UNO

Kindly help me resolve this issue.
Note
I have reinstalled CH34x drivers (latest version v.5)

It is either a driver, cable, or physical USB port issue - "/dev/cu.Bluetooth-Incoming-Port" is not an Arduino. Have you tried moving the Arduino and cable to another computer (just to see if it is even recognized)? Substituting another cable?

Mojave is known to be a complete pig. Read this: https://forum.arduino.cc/index.php?topic=570440.0

Your newly installed driver might be quarantined by Mac security, Click on System Preferences -> Security & Privacy to see if it is blocked.

@Majenko Thanks a lot! The first suggestion on the forum that deals with removing the serial files and rebooting worked! Finally, I can actually use my Arduino. Thank you.


text:
Arduino RS485 communication protocol - minimising overheads and best practice
I'm building a single master multiple slave RS485 network for remote sensors on test equipment. I have the hardware built and working, and I can do a Serial.print on the master and have the slaves display the values received on their attached OLED screens. The goal is for the master to cycle through the slave addresses one by one and request data, then wait for the slave to respond (or timeout and register as a fail on the master's GUI).
The issue I have is that to work out if a packet is intended for a slave device I have to parse the entire packet, wait for start and end packets, and check the address. This means every device has to capture and check every packet on the network for its own address byte. If I compare on the fly I can exit the serial loop as soon as I know which device the packet is intended for, but the next received packet will just re-open the serial loop part way through transmission.
Other than disabling the RS485 transceiver between packets, is there an elegant way to solve this issue without massive overheads?
My hardware uses Arduino Nanos (master is currently an Uno but will be a piece of National Instruments hardware) and MAX13487 transceivers.
Thanks!

Have you looked into BACnet / MS/TP (Master-Slave/Token Passing) or TDMA (Time Division Multiple Access) protocols? I don't know enough about your project to recommend one or the other.

@StarCat Those look like they'd help avoid collisions, but I'm not so worried about that. I'm not sure they avoid the slaves having to listen for a request packet destined for them.

Are you using modbus?

@haresfur no, should I be?

RS485 is the hardware layer and MODBUS is a software layer for communicating over RS485 that is commonly used for sensors so it may have done some of the heavy lifting for you. I don't know enough to say if it will help or not.


text:
Read amount of I/Os in code
I want to write an Arduino code, that runs on several different Boards. The code can perform digitalRead/Write operations, but the pin number will be set from the user/outside. I want to include a check, if the selected pin exists.
Is it possible, to read the amount of I/Os (digital and analog) of the Arduino the code is currently running on, to check if the users selection is in the given range? Or is it possible to check, if a certain pin number exists?

It depends on the core, but most provide the macro NUM_DIGITAL_PINS which tells you the number of digital pins the board has.  In general this doesn't equate to the actual number, but to one more than the highest number (there are boards with gaps in the pin number sequence).
So you can use:
if (pinNumber < NUM_DIGITAL_PINS) {
    digitalWrite(pinNumber, HIGH);
} else {
    Serial.println("Invalid pin number");
}

In tandem with that you also usually have NUM_ANALOG_INPUTS.

The number of the GPIO pins available depends on how the chip is wired on the Arduino Board and which microcontroller one is running on. For example, an Arduino Uno with a ATMega328p chip has 14 Digital I/O pins, whereas an Arduino Mega 2560 with a chip has 54 digital I/O pins.


text:
What to do with Arduino floating pins?
I have some unused pins, should I connect them together and to the ground or leave them floating?

Just leave them floating. The only problem with that is that under certain circumstances this can cause the MCU to use a bit more current. This is only a problem if you run of batteries. The datasheet suggest enabling the internal pull-ups, like Majenko suggested, but I never had much luck with that, as it ended up drawing more current somehow. In the end I set them to OUTPUT and LOW.

@Gerben With the pullups enabled you can only get leakage current through the MOSFETs and internal resistor (which will be in the order of nano amps, if that). With an input floating current gets drawn every time the input switches state as it flaps around. Actively driving a disconnected output will theoretically cause more current consumption through the input circuitry since it is only the leakage current of the FETs that limits it, not the leakage current plus the resistance of the pullup.

@Gerben Leakage current is stated as 1µA @ 5.5V through the input circuitry in the datasheet. That means a resistance of 5.5MΩ. Add to that the ~30kΩ of the pullup and the leakage would be 0.995µA with the pullup enabled, compared to 1µA with the output being driven.

@Gerben You might find this interesting: http://www.ti.com/lit/an/scea046/scea046.pdf

@Majenko I think that's what the datasheet mentioned. Having the input voltage float and fluctuate in between Vih and Vil making the input(compare) circuitry consume more power. I think that's probably pretty rare. Also, only applies if the MCU is awake, which isn't a lot in all of my battery powered projects.

@Gerben In sleep mode the input is disconnected and the input to the schmitt trigger is clamped to ground.

The simplest thing to do is set them to INPUT_PULLUP.  If you want a purely hardware solution then you could connect them to GND through some resistors (10kΩ or whatever you have in that kind of order of magnitude will do).
You don't want to just tie them directly to ground, and you don't want to link them directly together - that could lead to short circuits and dead IO ports if any of the pins happened to get set as output and HIGH in software.

How would using the internal pull-up resistors lead to higher current consumption (Gerben's comment)? Perhaps address that in your answer (whether it is true or not)?

It wouldn't. It would do the opposite. A pulled up pin can only use current that flows as "leakage current" through the input circuitry (minuscule amounts). A floating pin uses current every time it causes the input circuitry to switch states.

It was just my observation in one or two of my projects. So take that with a grain of salt.

I saw instability with a kiosk audio player I built years ago, when I left the unused pins floating.  Once I grounded them through a 10k resistor, all was OK.  This was in a very dry environment so I suspect static was the problem.

Leaving them floating in most cases won't do any harm. Even touching the pins won't destroy anything. Tying extra external hardware is just unnecessary (though a 10k resistor would be harmless as well). Of course, you could also think about potential extra usages for those pins if you want to make your design a bit "future-proof". For example, adding 4k7 pull-up resistors to A4 and A5 and a connector could allow you to use the I2C interface for additional functions.


text:
Decoding RF receiver signals
By using the following draft i decode the signals from an RF receiver
#define CH1 2
#define CH2 3
#define CH3 4
#define CH4 5
#define CH5 6
#define CH6 7

int ch1Time, ch2Time, ch3Time, ch4Time, ch5Time, ch6Time = 0;
void channels()
{
  TCNT1 = 0;
  ch1Time = 0; ch2Time = 0; ch3Time = 0; ch4Time = 0; ch5Time = 0; ch6Time = 0;

  while ((PIND & ((1 << CH1) | (1 << CH2) | (1 << CH3) | (1 << CH4) | (1 << CH5) | (1 << CH6))))
  {
    if (PIND & (1 << CH1))
      ch1Time = TCNT1;

    if (PIND & (1 << CH2))
      ch2Time = TCNT1;

    if (PIND & (1 << CH3))
      ch3Time = TCNT1;

    if (PIND & (1 << CH4))
      ch4Time = TCNT1;

    if (PIND & (1 << CH5))
      ch5Time = TCNT1;

    if (PIND & (1 << CH6))
      ch6Time = TCNT1;
  }
}

The issue is that i need also to use the 6 PWM's of the nano board.
So i thought of moving the channels 1-6 to the analog pins like so..
#define CH1 A0
#define CH2 A1
#define CH3 A2
#define CH4 A3
#define CH5 A4
#define CH6 A5

while ((PINC & ((1 << CH1) | (1 << CH2) | (1 << CH3) | (1 << CH4) | (1 << CH5) | (1 << CH6))))
  {
    if (PINC & (1 << CH1))
      ch1Time = TCNT1;
etc...

but it simply does not work. Any thoughts please?

I see two immediate problems:

The macros A0-A5 are the numbers 14 to 19, not the numbers 0 to 5 - so you're looking at (1 << 14) for CH1 not (1 << 0).
The analog pins are port C not port B, so you need to use PINC not PINB.
Your ch?Time variables should be volatile.

Oups. I am actually using PORTC and that is a typo. I will edit it asap. The channels method is called by... attachInterrupt(0, channels, RISING);

Actually i do not get it. (PINC & (1 << 0)) for CH1 does not work also, with pinMode(A0, INPUT);

Added the volatile option but the issue remains.

@OrElse Are you sure you want to be clearing TCNT1 just before you read from it?

Actually yes. This way by counting the time, i decode the RF receiver signal which is from 1ms to 2ms. Plus this works great on digital inputs. TCCR1A = 0;
TIMSK1 = 0;
TIFR1 = 0;
TCNT1 = 0;
TCCR1B = (1 << CS10); Thank you for all your effort

Ah yes, I see what you're doing with it now.


text:
serial 1 was not declared in the scope
#include <LiquidCrystal.h>
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
#include <SoftwareSerial.h>

char Mob[20]="+923319020922";
String stringGPS = "";
String stringGPS1 = "";
char c=0;
int t=0,i;
int buzzer = 9;
int buttonState = 0;

SoftwareSerial mySerial(10, 11); // RX, TX

//const int buttonPin1 =9 ;
int buttonState1 = 0;
int helmetstate=0;
const int relay=8;
char inByte=0;

void setup()
{
  lcd.begin(20, 4);
  lcd.setCursor(0, 0);
  pinMode(relay, OUTPUT);
  pinMode(buzzer, OUTPUT);
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial2.begin(9600);
  digitalWrite(relay, LOW);
  delay(15000);
  lcd.print("Config modem....");

  Config();

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Smart helmet      ");
}

void loop()
{
  if(Serial2.available())
  {
    inByte = Serial2.read();
    //Serial.write(inByte);
    if(inByte=='A'||inByte=='B'||inByte=='C'){
    inByte=0;
    SMS(Mob);

    while(Serial2.available()>0)
    {
      i = Serial2.read();
    }
  }

  if(inByte=='D')
  {
    digitalWrite(relay, LOW);
    inByte=0;
  }

  if(inByte=='E')
  {
    digitalWrite(relay, HIGH);
    inByte=0;
  }
  else
  {
  }
}

 //buttonState = digitalRead(buttonPin);
 // if (buttonState == LOW) {
 //Serial.print("ok");
 //lcd.clear();
 // lcd.setCursor(0, 0);
 //lcd.print("Sending msg       ");
 // lcd.setCursor(0, 0);
 //lcd.print("Smart helmet      ");
 // checkGPS();
 // SMS(Mob);

 //helmet();
 checkGPS();
 lcd.setCursor(0, 1);
 lcd.print(stringGPS1);
 //Serial.println(stringGPS1);
}

/*
void helmet()
{
  buttonState1 = digitalRead(buttonPin1);
  if (buttonState1 == HIGH)
  {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("SWITCH ON  .......    ");
    digitalWrite(relay, HIGH);
  }
  else
  {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("SWITCH OFF .......    ");
    digitalWrite(relay, LOW);
  }
}
*/

void checkGPS()
{
  // Serial.print("check gps");
  // while (Serial.available())
  // {
  if (Serial.available()>0)
  {
   // c = Serial.read();
   // stringGPS  = c;
   //Serial.print(c);
   while (c != 'R')
   {
     c = Serial.read();
     // Serial.print(c);
   }
    // if (c== 'R')
    // {
    //   Serial.print(c );
         while(t!=41)
         {
           if (Serial.available())
           {
             c = Serial.read();
             stringGPS += c;
             t++;
             //Serial.print(stringGPS );
          }
  }
  stringGPS1= stringGPS.substring(15, 41);
  // Serial.println(stringGPS1);
  t=0;
  c=0;
  stringGPS = "";
    // }
  }
  }

void SMS(char Mob[20])
{
   digitalWrite(buzzer, HIGH);
   lcd.setCursor(0, 0);
   lcd.print("Sending msg       ");
   Serial1.print("AT+CMGS=\"");     // send the SMS number
   Serial1.print(Mob);/// Send mobile number
   Serial1.print("\"\r");
   delay(4000);
   Serial1.print(stringGPS1);// send the SMS Data
   Serial1.print("\r");
   delay(2000);
   Serial1.write(0x1A);  ///Ctrl+Z
   delay(1000);
   Serial1.write(0x0A);  ///Carrige return
   delay(1000);
   Serial1.write(0x0D);    ///line feed
   delay(1000);
   stringGPS1 = "";
   lcd.setCursor(0, 0);
   lcd.print("Smart helmet      ");
   digitalWrite(buzzer, LOW);
}

void Config()/////configuration for sim900
{
  delay(4000);
  Serial1.print("ATE0\r"); ////Disable Echo
  delay(4000);
  Serial1.print("AT\r"); ///checking echo
  delay(4000);
  Serial1.print("AT+CMGF=1\r");///msg format
  delay(4000);
}

when i run this code it give me error that serial1 was not decleared in the scope

The board, that you are compiling for, does not have Serial1 and Serial2. Why did you try to use them? Or are you simply compiling for the wrong board type? What Arduino do you have?

What board are you using? If it's not one of the bigger boards then what makes you think it would have Serial1 and Serial2?

If you had formatted your code in a readable manner you would see, that there are too many closing curly braces . One in your loop function and two in the code at the end. Correct formatting makes the code readable and let you find your mistakes easier.

The only SoftwareSerial you a declaring is SoftwareSerial mySerial(10, 11); // RX, TX

(And you you didn't use it afterwards).
If the hardware serials Serial1, Serial2 or Serial3 are available
(and already declared in the arduino.h header depends on the board you are using.


text:
program evaluating if clause incorrectly
As the title says i'm having a problem with an if clause evaluating incorrectly in one particular function
uint16_t    getSleepTime()
{
    volatile uint8_t flag = EEPROM.read(3);

    uint8_t high    = EEPROM.read(0);
    uint8_t low     = EEPROM.read(1);

    if(flag != 0xaa);
    {
        Serial.println(flag);
        Serial.println("ERROR: SLEEP TIME NOT DEFINED, CANNOT CONTINUE.");
        while(true)
        {
            digitalWrite(PIN_LED, true);
            delay(250);
            digitalWrite(PIN_LED, false);
            delay(250);
            wdt_reset();
        }
    }

    return word(high, low);
}

the result is that the if function evaluates as true always
my first thought was, ok the eeprom wasn't written properly, hence i added the println, the returned value was 170 == 0xaa
then i thought well maybe the flag variable is optimized out, hence the volatile
and then, well maybe its a type comparison issue so i also defined a const uint8_t flagv with value 0xaa
same results in every case
13:21:00.991 -> 170
13:21:00.991 -> ERROR: SLEEP TIME NOT DEFINED, CANNOT CONTINUE.
and the corresponding blink

the thing is that being such a trivial code i'm out of ideas right now, as anyone here experienced something like this?

when debugging, put Serial.println(flag); before the if statement

Do not put a ; after an if:
if(flag != 0xaa);

is the same as
if(flag != 0xaa)
{
}

Meaning that the code after the if statement is always executed.

ouch, dumb mistake

No problem, however, I also have to vote for closing, since it's not related to Arduino.


text:
can Arduino IDE link to other libs / files in other directories?
can Arduino IDE point to a file in another directory? If yes how?
With my code
../../main.h

the compile fails.
Error:
In file included from D:\Eigene Dateien\Entwicklung\SIGNALDuino_MR\src\arduino-ide\SIGNALDuino\SIGNALDuino.ino:1:0:

main.h:1:1: error: expected unqualified-id before '.' token

 ../../main.h

 ^

exit status 1
expected unqualified-id before '.' token

--------------- structure ------------------
TEST
  |--main.h
  |-----Ordner 1
             |-----Ordner 3
                       |--files.h
  |-----Ordner 2
             |-----Ordner 4

#include "../../main.h"

No it doesn't work. The file exists in the directory (2 times back in the structure)
:-( `#include "../../main.h"
                    ^

compilation terminated.
exit status 1
../../main.h: No such file or directory`

I  didn't expect it to work. the Arduino IDE builds the sketch in a temporary folder, not in the sketch folder. but to include the #iinclude directive is the only possible syntax

But he should read the file from there :-( No absolute position should be given. The file is 2 levels up.

it is not two levels up from the temporary folder

to avoid misunderstandings, it is a path \ src \ which has the first main.h. This contains the structure \ arduino-ide \ project \ where the main.h file is located. This should call the "first" main.h.

The answer is in the wrong direction. The user wants from MCUa.ino in TimerLib.h.
But my plan is backwards. Jump back directories. Based on the example, from TimerLib.h to MCUa.ino

it is the same question as yours. include in sketch something on relative path

it does not work #include ../../main.h or  #include "../../main.h"

read the answer to the other question.


text:
Esp32(Arduino Core) + Blynk Wifi Connection Problems
So I am making a football playing robot which consists of 3 servo motors. Currently,i am only checking only a single servo(myservoKicker)which is operated via button in the blynk app and trying to read x and y values from joysticks in blynk. I am using wifi communication. I have seen that wifi.begin never properly starts as the serial.print("Blynk Connected") after it does not run, plus on my blynk app the project constantly connects and disconnects.
Note: The code for steering other servo's is not implemented yet and is just a stub.
Board: DoIt ESP32 Devkit V1 30 GPIO
Blynk: 0.6.1
myservoKicker connected to pin 13
#include <ESP32Servo.h>
#include <SPI.h>
#include <Ethernet.h>
#include <ETH.h>
#include <WiFi.h>
#include <WiFiAP.h>
#include <WiFiClient.h>
#include <WiFiGeneric.h>
#include <WiFiMulti.h>
#include <WiFiScan.h>
#include <WiFiServer.h>
#include <WiFiSTA.h>
#include <WiFiType.h>
#include <WiFiUdp.h>
#include <BlynkSimpleEsp32.h>

Servo myservoKICKER;
Servo myservoLEFTWHEEL;
Servo myservoRIGHTWHEEL;
int pos;

char auth[] = "9Itekdu3vf_B_3YmNxxHu9G3Bs_1IWs9";
char ssid[] = "RO IMRAN RO";
char pass[] = "xxxxxxxxxxx";
char localserver[16]= "192.168.1.1";
BLYNK_WRITE(V1)
{
    int xAxis = param[0].asInt();
    int yAxis = param[1].asInt();

    // Do something with x and y
    Serial.print("X = ");
    Serial.print(xAxis);
    Serial.print("; Y = ");
    Serial.println(yAxis);

}
BLYNK_WRITE(V4){                                        //WHEEL CALIBRATION
    int WheelCalibration=param.asInt();
    if(WheelCalibration == 1)
    {
        myservoLEFTWHEEL.attach(26);
        myservoRIGHTWHEEL.attach(27);
        delay(100);
        myservoLEFTWHEEL.write (90);
        myservoRIGHTWHEEL.write (90);
        delay(30000);

    }
}
BLYNK_WRITE(V5){                                        //KICKER 90 DEGREE CALIBRATION
    int KickerCalibration= param.asInt();
    if(KickerCalibration == 1)
    {
        myservoKICKER.attach(13);
        delay(100);
        myservoKICKER.write (90);
        delay(200);

    }
}

void setup(){
    // Attach servos to pins
    myservoLEFTWHEEL.attach(26);                        //1
    myservoRIGHTWHEEL.attach(27);                       //2
    myservoKICKER.attach(13);                           //3

    // detach servos to avoid jitter on power up
    myservoLEFTWHEEL.detach();
    myservoRIGHTWHEEL.detach();
    myservoKICKER.detach();

    Serial.begin(115200);
    delay(10);
    Serial.print("Connecting to ");
    Serial.println(ssid);
    WiFi.begin(ssid,pass);
    int wifi_ctr = 0;
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("WiFi connected");
    Blynk.begin("9Itekdu3vf_B_3YmNxxHu9G3Bs_1IWs9",ssid,pass);
    Serial.println("Blynk connected");
}

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

1st - try to set option EraseFlash -> Sketch+WiFi Settings
2nd - try to set WiFi.hostname() before WiFi.begin()

the Blynk.begin does WiFi.begin. so remove your WiFi.begin

Your code is not indented properly, which makes it confusing and hard to follow.

just focus on this bit of code:

Serial.begin(115200);
delay(10);
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid,pass);
int wifi_ctr = 0;
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
Blynk.begin("9Itekdu3vf_B_3YmNxxHu9G3Bs_1IWs9",ssid,pass);
Serial.println("Blynk connected");
}

Did you erase  "Sketch+WiFi Settings"? Did you call WiFi.hostname(...);?

@gbg, how is it relevant? if the wifi settings are deleted they will be stored again, since the sketch passes the ssid and password. and what with hostname? Blynk doesn't care about hostname

@Juraj WiFI.hostname() - sets hostname for DHCP query. My WiFi router does not answer on DHCP query without the hostname set, so, the ESP does'n connect to the WiFi.

@gbg, hostname is always set somehow

@Juraj, IDK, in my case, without this line, connection fails


text:
How to Set the Control Register on the DS3231 RTC module for Arduino UNO R3?
I am using the DS3231 RTC connected to an Arduino UNO R3 for a project. I won’t go into detail, but I need to save power, therefore I am using the DS3231 Alarm Interrupt to wake the Arduino from sleep. The Alarm Interrupt works fine when the Arduino is sleeping and connected to the 5V and GND pins of the Arduino, however it turns out that the DS3231 won’t fire a square wave interrupt when on battery power. In order to turn it on, I need to set bit 7 of the Control Register (0Eh) to logic 1, and bit 6 to logic one. I can’t find any documentation on how to do this, except for a few forums talking about it. What is the specific code to do this, and where would I place the code?
DS3231 Data Sheet (Control Register on p.13)
#include <Wire.h>
#include <RTClibExtended.h>
#include <LowPower.h>

#define wakePin 2    //use interrupt 0 (pin 2) and run function wakeUp when pin 2 gets LOW
#define ledPin 13    //use arduino on-board led for indicating sleep or wakeup status

RTC_DS3231 RTC;      //we are using the DS3231 RTC

byte AlarmFlag = 0;
byte ledStatus = 1;

//-------------------------------------------------

void wakeUp()        // here the interrupt is handled after wakeup
{
}

//------------------------------------------------------------

void setup() {
  //digitalWrite(wakePin,HIGH);
  //Set pin D2 as INPUT for accepting the interrupt signal from DS3231
  pinMode(wakePin, INPUT);

  //switch-on the on-board led for 1 second for indicating that the sketch is ok and running
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, HIGH);
  delay(1000);

  //Initialize communication with the clock
  Wire.begin();
  RTC.begin();
  RTC.adjust(DateTime(__DATE__, __TIME__));   //set RTC date and time to COMPILE time

  //clear any pending alarms
  RTC.armAlarm(1, false);
  RTC.clearAlarm(1);
  RTC.alarmInterrupt(1, false);
  RTC.armAlarm(2, false);
  RTC.clearAlarm(2);
  RTC.alarmInterrupt(2, false);

  //Set SQW pin to OFF (in my case it was set by default to 1Hz)
  //The output of the DS3231 INT pin is connected to this pin
  //It must be connected to Arduino D2 pin for wake-up
  RTC.writeSqwPinMode(DS3231_OFF);

  //Set alarm1 every day at 18:33
  RTC.setAlarm(ALM1_MATCH_HOURS, 16, 19, 0);   //set your wake-up time here
  RTC.alarmInterrupt(1, true);
}

//------------------------------------------------------------

void loop() {

  //On first loop we enter the sleep mode
  if (AlarmFlag == 0) {
    attachInterrupt(0, wakeUp, LOW);                       //use interrupt 0 (pin 2) and run function wakeUp when pin 2 gets LOW
    digitalWrite(ledPin, LOW);                             //switch-off the led for indicating that we enter the sleep mode
    ledStatus = 0;                                         //set the led status accordingly
    LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);   //arduino enters sleep mode here
    detachInterrupt(0);                                    //execution resumes from here after wake-up

    //When exiting the sleep mode we clear the alarm
    RTC.armAlarm(1, false);
    RTC.clearAlarm(1);
    RTC.alarmInterrupt(1, false);
    AlarmFlag++;
  }

  //cycles the led to indicate that we are no more in sleep mode
  if (ledStatus == 0) {
    ledStatus = 1;
    digitalWrite(ledPin, HIGH);
  }
  else {
    ledStatus = 0;
    digitalWrite(ledPin, LOW);
  }

  delay(500);
}

Also, how would I set it to go to sleep after the alarm?
Thanks!
P.s sorry about that Thomas, I'm a bit new here.

What RTC library are you using? Do you know how to directly address an I2C device using the Wire library?

You have a pullup resistor on the line also, yes?

I took a look at the FabioCuomo-DS3231 library, as I
guess that is what you are using, and I saw nothing related to setting
those two bits. However, you can take inspiration from the code in the
library to implement the functionality yourself.
I would try this:
void enableAlarmInLowPower(void) {
    // Read the control register.
    Wire.beginTransmission(DS3231_ADDRESS);
    Wire.write(DS3231_CONTROL);
    Wire.endTransmission();
    Wire.requestFrom((uint8_t)DS3231_ADDRESS, (uint8_t)1);
    uint8_t value = Wire.read();
    Wire.endTransmission();

    // Update it.
    value |= bit(6) | bit(7);  // set bits 6 and 7

    // Write it back.
    Wire.beginTransmission(DS3231_ADDRESS);
    Wire.write(DS3231_CONTROL);
    Wire.write(value);
    Wire.endTransmission();
}

Warning: not tested.


text:
Arduino Connect Long Wires/Cables
i am completely new to hardware programming and micro controllers and i am unable to figure out what search-engine search-term to use to find the answer i am looking for.
the project
i am working on a project that will use an arduino to control the opening and closing of a window; in a shed. the project i am trying to achieve is further described here.
the question
i want to know what are the limitations of wire length in an arduino project and what do i need to have to be able to extend that wire length capacity?
i currently have those "common" 20cm wires you get off ebay... which i dont think will be long enough.

If 20 cm is not long enough, what is long enough then? 2 m, 200 m, 20 km?

for this example lets say 3m... i plan the window to be on the roof... i figure my options are to either "stick" the arduino on a wall nearby or have long cables to the floor. i think the second option better achieves safety for the arduino because i could put the arduino inside some waterproof box on the floor.
i dont expect it to get wet inside... but i cant guarantee that.

What kind of motor are you going to use to open and close the window? What type and voltage? The distance will depend on that.

i dont mean to advertise amazon products or anything... but something like this is a type of motor  that seems easy to control... (i have micro servo SG90 working as expected. my expectation is that the large one will work similarly (of course with more power requirements))... i do not think the window will be too heavy... but this motor seems sufficient... perhaps my expectation here are too optimistic. feel free to advise on anything you think i may not have considered.

The stepper motor 28byj-48 seems to be a 5V motor (datasheet). I've seen it being used with a A3967 driver, which means that it does not draw more than 750 mA of current.
I'll go with the length you mentioned in the comments:

for this example lets say 3m

The rest is Physics: the resistance of a wire is
R = p * l/A

where l is the length of the wire and A is the area (dependent on the diameter).
A voltage drop calculator can now tell you how much voltage is left at the end of the wire.
I would have estimated a 0.75 mm² (AWG 18), but you might even be fine with 0.5mm² (AWG 20) according to the calculator. But: better safe than sorry.

Also from the comments:

i have micro servo SG90 working as expected. my expectation is that the large one will work similarly (of course with more power requirements)

A stepper motor needs a totally different setup than a servo. The servo is connected with simple 4 pins, the stepper needs a motor driver (H-bridge). Connecting the stepper motor directly to the Arduino may destroy your board.

thanks for you reply... i have decided to not use the stepper as described in a previous post. i think the mechanical requirements are simpler with the use if a servo motor because i do not need continuous rotation to open a window and i have a working proof of concept working with cheap SG90 servo you can get with some "cheap" arduino kit.

@X0r0N: be aware: the SG90 can hold ~1 kg in 1 cm distance, 100 g in 10 cm distance and 10 g in 1 m distance. You'll need a much more powerful servo.

i think so too... my plan is to use this one or similar.

Wire length is hard to define. It depends if it is in your case powering a motor or has control signals connected directly to the Arduino. Take a good look at the answer provided by Thomas Weller, by sizing the wire appropriately you can get extremely long lines for motors and other types of loads, you have some voltage to work with. The wires connected to the Arduino are also antennas and can pick up a lot of nasties in a very short run, especially around motors. These antennas on the inputs are high impedance making them more sensitive to noise. Regardless of which wires you are looking at they need to be properly conditioned for your environment and application.


text:
Thermocouple and multimeter
I've put together this script that should allow my Arduino Mega to be show thermocouple readings on the serial monitor, whilst also showing readings of voltage and ohms across a given component. I'd be grateful for any advice on how it can be improved/streamlined:

#include <SparkFun_MCP9600.h>
MCP9600 tempSensor;
int analogPin = 0;
int raw = 0;
int Vin = 5;
float Vout = 0;
float R1 = 220;
float R2 = 0;
float buffer = 0;
float volt = 0;
int input = 0;

void setup() {
  Serial.begin(115200);
  Wire.begin();
  Wire.setClock(100000);
  tempSensor.begin();

  if (tempSensor.isConnected()) {
    Serial.println("Device will acknowledge!");
  }
  else {
    Serial.println("Device did not acknowledge! Freezing.");
    while (1); //hang forever
  }

  if (tempSensor.checkDeviceID()) {
    Serial.println("Device ID is correct!");
  }
  else {
    Serial.println("Device ID is not correct! Freezing.");
    while (1);
  }

  pinMode(A4, INPUT);
}

void loop() {

  input = analogRead(A4); //analogRead function is used to receive analog data
  volt = (input * 5.0) / 1024.0; //formula using for perform action

  if (tempSensor.available()) {
    Serial.print("Thermocouple: ");
    Serial.print(tempSensor.getThermocoupleTemp());
    Serial.print(" °C   Ambient: ");
    Serial.print(tempSensor.getAmbientTemp());
    Serial.print(" °C   Temperature Delta: ");
    Serial.print(tempSensor.getTempDelta());
    Serial.print(" °C");
    Serial.println();
  }

  raw = analogRead(analogPin);
  if (raw)
  {
    buffer = raw * Vin;
    Vout = (buffer) / 1024.0;
    buffer = (Vin / Vout) - 1;
    R2 = R1 * buffer;
    Serial.print("Vout: ");
    Serial.println(Vout);
    Serial.print("R2: ");
    Serial.println(R2);
    Serial.print("voltage is:");
    Serial.println(volt);
    Serial.print("current is:");
    Serial.println(volt / R2);
    delay(1000);
  }
}

"should allow": does it, or doesn't it?

Does the code work as it is? I see you’re defining some variables  (like Vin, R1, analogPin) that are never changed and actually only used as constants. You should define them as “const” or use #define (for example for the analog port numbers).

Your code is not very long, but I already see a few things that I would change.
int analogPin = 0;
[...]
pinMode(A4, INPUT);

These usages of pins are inconsistent. I personally prefer settings at the beginning of the file, so I'd expect
int analogPin = 0;
int whateverPin = A4;  // I don't have a good name yet

While you have
pinMode(A4, INPUT);

there's no
pinMode(analogPin, INPUT);

The main loop is doing 2 things: a) show temperature reading and b) show the component specs. This would be more obvious if written like this:
void loop() {
  input = analogRead(A4); //analogRead function is used to receive analog data
  volt = (input * 5.0) / 1024.0; //formula using for perform action

  showTemperatureReadings();
  showComponentReadings();
}

Now, that looks a bit strange, don't you think? What about the stuff before these two big show...() methods? These two lines clearly belong into showComponentReadings().
Now, a lot of variables are declared outside of methods. This makes them global variables. It's possible to change them from anywhere in the code. When the project grows, side effects are evil. Let's remove as many of them as possible.
You can get rid of:
int input = 0;
float volt = 0;
float buffer = 0;
float R2 = 0;
float Vout = 0;
int raw = 0;

After this change, I think the setup() method could be more concise. A lot of stuff just deals with the temperature sensor. I would extract a method as well.
The error messages like

Device did not acknowledge! Freezing.

could not mean very much to the user. A message like

Temperature sensor did not acknowledge! Check the wiring and press the reset button to retry.

could give more meaningful instructions.
The final code with these suggestions applied:
#include <SparkFun_MCP9600.h>
MCP9600 tempSensor;
int analogPin = 0;
int whateverPin = A4;
float R1 = 220;
int Vin = 5;

void setupTemperatureSensor() {
  tempSensor.begin();
  if (tempSensor.isConnected()) {
    Serial.println("Temperature sensor acknowledged.");
  }
  else {
    Serial.println("Temperature sensor did not acknowledge! Check the wiring and press the reset button to retry.");
    while (1); //hang forever
  }

  if (tempSensor.checkDeviceID()) {
    Serial.println("Temperature sensor ID is correct.");
  }
  else {
    Serial.println("The temperature sensor ID does not have the expected value. Do you use a different sensor type? Use a SparkFun MCP9600.");
    while (1);
  }
}

void setup() {
  Serial.begin(115200);
  Wire.begin();
  Wire.setClock(100000);

  setupTemperatureSensor();

  pinMode(whateverPin, INPUT);
  pinMode(analogPin, INPUT);
}

void showTemperatureReadings() {
    if (tempSensor.available()) {
    Serial.print("Thermocouple: ");
    Serial.print(tempSensor.getThermocoupleTemp());
    Serial.print(" °C   Ambient: ");
    Serial.print(tempSensor.getAmbientTemp());
    Serial.print(" °C   Temperature Delta: ");
    Serial.print(tempSensor.getTempDelta());
    Serial.print(" °C");
    Serial.println();
  }
}

void showComponentReadings() {
  int input = analogRead(whateverPin); //analogRead function is used to receive analog data
  float volt = (input * 5.0) / 1024.0; //formula using for perform action
  int raw = analogRead(analogPin);
  if (raw)
  {
    float buffer = raw * Vin;
    float Vout = (buffer) / 1024.0;
    buffer = (Vin / Vout) - 1;
    float R2 = R1 * buffer;
    Serial.print("Vout: ");
    Serial.println(Vout);
    Serial.print("R2: ");
    Serial.println(R2);
    Serial.print("voltage is:");
    Serial.println(volt);
    Serial.print("current is:");
    Serial.println(volt / R2);
    delay(1000);
  }
}

void loop() {
  showTemperatureReadings();
  showComponentReadings();
}

With code folding active, I'd say it's now very simple to get an overview of what the code is doing and what can be configured:

Edit:
After you linked to the schematics, I would

rename whateverPin to voltageDividerPin.
change the calculation float volt = (input * 5.0) / 1024.0; to a mapping, because it maps the 1024 input values to 5V, so float volt = map(voltageReading, 0, 1024, 0, Vin);
remove analogPin completely, because it's not used in the original code as well.

I also hope that read the article and you understood the consequences of using a 220 Ohm resistor.

Re “I'm not sure whether analogRead() works [with 0 as an argument]”: It does. analogRead() treats A0 (defined as 54 on the Mega) as equivalent to 0.

The ohmmeter code came from here: http://www.circuitbasics.com/arduino-ohm-meter/
I'm guessing the circuit layout is still fine?

@Chris: I've updated the answer according to the schematics

It'll be 220mOhm in my case as the unknown resistance should be around there. Thanks again!

@Chris: 5V/440mOhm=11A. The Arduino can handle a maximum of 500 mA on its 5V pin. Also, you need a 28W resistor to handle the power, otherwise it'll go up in flames. It's ok, if you have considered all the electrical stuff. I just don't consider that the "normal" Arduino usage.

I'm using 1kOhm resistors to keep the overall circuit resistance down. There are three connecting the breadboard to the 5V source, GND and the analog-read pin.  But fundamentally I need the Arduino to identify the unknown resistance, which just happens to be tiny in this case.


text:
mp3 trigger, output to antoher input, no switch
I have two Arduinos: one is transferring on its output pin to other Arduino's input_pullup low or high signal depend on servo action (rotating/stop).
I need an action on slave Arduino with dfmini player: actually I need a code with which mp3 sample is triggered on slave Arduino.
servo rotates -output pin goes low = sample is played just once until servo reaches desired position
servo stopped -output pin goes high = sample stops
solving this issue will be really helpful for my project.
here is example code
tnx.
***************************************************
  DFPlayer - A Mini MP3 Player For Arduino
  <https://www.dfrobot.com/index.php?route=product/product&product_id=1121>

 ***************************************************
  This example shows the basic function of library for DFPlayer.

  Created 2016-12-07
  By [Angelo qiao](Angelo.qiao@dfrobot.com)

  GNU Lesser General Public License.
  See <http://www.gnu.org/licenses/> for details.
  All above must be included in any redistribution
 ****************************************************/

/***********Notice and Trouble shooting***************
  1.Connection and Diagram can be found here
  <https://www.dfrobot.com/wiki/index.php/DFPlayer_Mini_SKU:DFR0299#Connection_Diagram>
  2.This code is tested on Arduino Uno, Leonardo, Mega boards.
 ****************************************************/

#include "Arduino.h"
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"
#define pin 2 // connect to master digital output "pin"

SoftwareSerial mySoftwareSerial(10, 11); // RX, TX
DFRobotDFPlayerMini myDFPlayer;
void printDetail(uint8_t type, int value);

void setup()
{
 mySoftwareSerial.begin(9600);
 Serial.begin(115200);
 pinMode(2,INPUT_PULLUP);

 Serial.println();
 Serial.println(F("DFRobot DFPlayer Mini Demo"));
 Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));

 if (!myDFPlayer.begin(mySoftwareSerial)) {  //Use softwareSerial to communicate with mp3.
   Serial.println(F("Unable to begin:"));
   Serial.println(F("1.Please recheck the connection!"));
   Serial.println(F("2.Please insert the SD card!"));
   while (true);
 }
 Serial.println(F("DFPlayer Mini online."));

 myDFPlayer.volume(15);  //Set volume value. From 0 to 30
}

void loop(){
  if (digitalRead(2)==LOW) myDFPlayer.play(1); // 5 sec mp3 sample, turn on , then debounce or return ?

}

}

wiring scheme

output cobmination on master arduino

What exactly is your problem in writing the necessary code?

im newbie, i know little about coding, is it solution complicated ?

The normal way is to start learnimg coding with tutorials and simple examples from the web. You most likely won't find an example, that exactly fits your goal, but you can use them to learn enough to solve your problem. You can always ask a specific question here and we will try to help you.

i have searched online , but i cant find any example with direct connection between output and input pins, always button or switch is included.

For the slave Arduino it is just an input pin. It doesn't know, what is connected to the pin. Thus it is irrelevant, if you connect a button or a second Arduino to that input pin. For the slave these options are the same

yes, thats true, but stil waiting for possible solution.

you are going to have a long wait


text:
ESP8266, sporadically no write access to the file system
I have an ESP8266 project which reads my gas consumption. The hardware and the project run satisfactorily. Sporadically, the ESP8266 can no longer write to its file system and therefore cannot save any data. As soon as I upload the complete data and the sketch to the device again, it works for a few months. After that, the mistake occurred again and again. What could that be?
The ESP8266 then has an "Exception" error. Unfortunately, I have not yet been able to find the reason for the error, why it always happens.
Does anyone have a tip on how I can isolate the problem?
https://github.com/HomeAutoUser/ESP-Gaszaehler-GZ16/tree/pre-release_v1.91

what is what you write? configuration or log files? if you upload the data does it contain the files with logged data? isn't the file system simply full?

does https://github.com/me-no-dev/EspExceptionDecoder give you any more info about what's exploding? Does rebooting once a day fix it?

The link is broken, I believe. It may also be that the module's flash is wearing out, although I'm not sure how reuploading would fix that, if that is the case.

The link is now revised.

I have faced the same issue with my water leak detector, based on esp8266. It was caused by memory leak in the ESP binaries, so, I've updated it to ver 2.6.3
So, you can try to log (print to serial) free memory amount:
extern "C"
{
    #include "user_interface.h"
}
uint32_t free = system_get_free_heap_size();

Thanks for the answer. I now have the problem that it can be compiled with the Core 2.5.2 but not with the Core 2.6.3.
I added the code above.
Suddenly a variable should not be declared.
exit status 1 StaticRequestHandler has not been declared

The line 'extern "C" {
#include "user_interface.h"
}' is in code already in.

the memory leak was with WiFiClient in 2.4.1 2 years ago

@Juraj, okay, so, any other ideas?


text:
can ModbusRtu.h library send data from slave to master using modbus(RS485) module?
i am using ModbusRtu.h library for modbus protocol. it works for sending data from master to  slave but it can not send data from slave to master.
master code:
#include <ModbusRtu.h>
  #define SERIAL_BUFFER_SIZE 64
// data array for modbus network sharing
uint16_t au16data[26];
uint8_t u8state;

/**
 *  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 master(0,Serial1,8); // this is master and RS-232 or USB-FTDI

/**
 * This is an structe which contains a query to an slave device
 */
modbus_t telegram;

unsigned long u32wait;

void setup() {
  Serial1.begin( 19200 ); // baud-rate at 19200
  Serial.begin( 19200 ); // baud-rate at 19200
//  master.start();
 master.begin();
  master.setTimeOut( 2000 ); // if there is no answer in 2000 ms, roll over
  u32wait = millis() + 1000;
  u8state = 0;
}

void loop() {

    telegram.u8id = 2; // slave address
    telegram.u8fct = 3 ; // function code (this one is registers read)3
    telegram.u16RegAdd = 0; // start address in slave 1     slave array index 0 dhora
    telegram.u16CoilsNo = 2; // number of elements (coils or registers) to read 4  //master array er koyta(not start from 0) value show korba
    telegram.au16reg = au16data; // pointer to a memory array in the Arduino
    int x = master.poll(); // check incoming messages
    Serial.print("x: ");
    Serial.println(x);
                if (master.getState() == COM_IDLE)
                {
                   master.query( telegram ); // send query (only once)

                }
Serial.print("Recieve: ");
      for (int i = 0; i < 5; i += 1)
      {
        Serial.print(au16data[i]);
        Serial.print(",");
      }
      Serial.println("");
}

slave code:
#include <ModbusRtu.h>
#define SERIAL_BUFFER_SIZE 64
// data array for modbus network sharing
//uint16_t au16data[26] = {
//  3, 1415, 9265, 4, 2, 7182, 28182, 8, 0, 0, 0, 0, 0, 0, 1, -1 };
uint16_t au16data[26] = {4,17,89};
int led = 13;
/**
 *  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(2,Serial1,8); // this is slave @1 and RS-232 or USB-FTDI

void setup() {
  Serial1.begin( 19200 ); // baud-rate at 19200
  Serial.begin( 19200 ); // baud-rate at 19200
  pinMode(led, OUTPUT);
  slave.begin();
  //slave.start();
}

void loop() {

  slave.poll( au16data, 26 );

   Serial.print("Recieve: ");
      for (int i = 0; i < 5; i += 1)
      {
        Serial.print(au16data[i]);
        Serial.print(",");
        if(au16data[3] == 1)
        {
          digitalWrite(led, HIGH);
         // Serial.println("in");
        }
         if(au16data[3] == 2)
        {
           digitalWrite(led, LOW);
           //Serial.println("else");
        }
      }
         Serial.println("");

       memset(au16data, 0, 26 * sizeof(uint16_t)); // recieveLargeArray = {}
}

and which one of the many ModbusRTU libraries do you use?

i used this library https://github.com/smarmengol/Modbus-Master-Slave-for-Arduino/find/master