text:
Ethernet module ENC28C60 doesn't connect to internet when DHCP on router is disabled.
Update: Examples from library are working if DHCP is enabled!
Using this library I try to connect with static IP but it always say DNS failed. Ethernet module is blinking that means is good connection also static ip is correct..
Question: What is hisip and how can this module connect to internet with static IP`?
Connections :
VCC -   3.3V
GND -    GND
SCK - Pin 52
SO  - Pin 50
SI  - Pin 51
CS  - Pin 53 # Selectable with the ether.begin() function

Code:
// This demo does web requests via DNS lookup, using a fixed gateway.
// 2010-11-27 <jc@wippler.nl> http://opensource.org/licenses/mit-license.php

#include <EtherCard.h>

#define REQUEST_RATE 5000 // milliseconds

// ethernet interface mac address
static byte mymac[] = { 0x74, 0x69, 0x69, 0x2D, 0x30, 0x31 };
// ethernet interface ip address
static byte myip[] = { XXX, XXX, 216, 199 };
static byte gwip[] = { XXX, XXX, 216, 126 };
static byte dnsip[] = { 8, 8, 8, 8 };
// remote website name
const char website[] PROGMEM = "google.com";

byte Ethernet::buffer[300];   // a very small tcp/ip buffer is enough here
static long timer;

// called when the client request is complete
static void my_result_cb (byte status, word off, word len) {
  Serial.print("<<< reply ");
  Serial.print(millis() - timer);
  Serial.println(" ms");
  Serial.println((const char*) Ethernet::buffer + off);
}

void setup () {
  Serial.begin(57600);
  Serial.println("\n[getViaDNS]");

  if (ether.begin(sizeof Ethernet::buffer, mymac, 53) == 0)
    Serial.println( "Failed to access Ethernet controller");

  ether.staticSetup(myip, gwip);

  if (!ether.dnsLookup(website))
  Serial.println("DNS failed");
  ether.printIp("Hisip: ", ether.hisip);
  ether.printIp("Myip: ", ether.myip);
  ether.printIp("Gateway: ", ether.gwip);
  ether.printIp("DNS: ", ether.dnsip);

  timer = - REQUEST_RATE; // start timing out right away
}

void loop () {
  ether.packetLoop(ether.packetReceive());

  if (millis() > timer + REQUEST_RATE) {
    timer = millis();
    Serial.println("\n>>> REQ");
    ether.browseUrl(PSTR("/foo/"), "bar", website, my_result_cb);
  }
}

Output:
[getViaDNS]
DNS failed
Hisip: 0.0.0.0
Myip: XXX.XXX.XXX.199
Gateway: XXX.XXX.216.126
DNS: 8.8.8.8

>>> REQ

>>> REQ
...


text:
Remove hanging PS3 input via bluetooth to arduino
I am working on a remote controlled vehicle based project. I am using a PS3 bluetooth controller for this purpose & am facing the problem described below. Any help would be appreciated.
Basically, the motors are connected to the MEGA which is connected to a USB Host Shield. A bluetooth dongle is connected to the shield. This dongle & shield enable MEGA to communicate with PS3 wirelessly. I am using the USB Host 2.0 library available for Arduino on GitHub.
My code to take input from the PS3 is as follows:
USB.Task();
if ( PS3.PS3Connected || PS3.PS3NavigationConnected )
{
    if ( PS3.getAnalogButton(UP) )
        Serial.println("UP");
    if ( PS3.getAnalogButton(DOWN) )
        Serial.println("DOWN");
    if ( PS3.getAnalogButton(LEFT) )
        Serial.println("LEFT");
    if ( PS3.getAnalogButton(RIGHT) )
        Serial.println("RIGHT");
}

This is the code inside loop(). If anyone is wondering why getAnalogButton is used instead of getButtonClick, the reason is to enable the vehicle to move ahead as long as UP is pressed & so on. This was an improvisation on our part.
As can be seen, the function prints UP, DOWN, LEFT or RIGHT as long as they are pressed continuously. The problem is that it works perfect for a while. But then, it enters an infinite loop & stops taking input from the PS3.
Basically, the input is like
UP
UP
UP
UP
UP
UP
UP
.....
LEFT
LEFT
LEFT
// At this point it hangs without printing any further inputs.

Can someone help tackle this problem? It is essential for us to move the vehicle as long as the buttons are pressed & stop when button is released. Unfortunately, there is no feature to detect PRESSED or RELEASED state for PS3. Any help would mean a lot.
Also, we initially thought that the hang was because of overflowing the serial input. So, we removed all Serial messages & tested with LEDs. But, the same problem is still faced.

I think the most precise answer you can get is "Something is blocking your loop". If you want more help, you'll have to share more information. For instance, what else is there in your program? Which library are you using? Can you understand what is the function blocking everything (I mean, does the USB.task hang or the checks are failing?)? Moreover the title and the text are different: are you actually experiencing lag or it hangs?

Depending on how you are reading the serial data, there might be a read buffer that's getting full and not getting purged.  I had this when using SoftwareSerial on a recent project.  I don't have the code handy, and my Google-fu is failing me on finding the same solution, but I had to "redeclare" a SoftwareSerial buffer variable on each loop.  I'll try to remember to look this up after work tonight, because I know what I said isn't clear.

What other details would it take to answer the question??? @frarugi87 Let me know. I'll provide those straight away.

The same goes for you too @computercarguy

You need to figure out where it is hanging, if it is even doing so - a fairly likely possibility could be the BT connection dropping at which point your posted code would seemingly do nothing.

@SamagraSinghTomar quoting from my previous comment, " For instance, what else is there in your program? Which library are you using? Can you understand what is the function blocking everything (I mean, does the USB.task hang or the checks are failing?)? "

It hangs randomly after a certain amount of time. No further input is received unless the connection is reset. Although, the connection seems to be intact when it hangs.

I am unable to figure out the reason for the hang. For your reference, I am using the PS3BT library example from USB Host 2.0 library whose GitHub link is posted above. I don't think there is any other library availbale for this purpose. I'm a beginner at arduino. So, if you can help me find out the reason for the hang, I would show you my complete code for better understanding. @frarugi87

@SamagraSinghTomar try to add a println after the USB.task call and another inside the if. If it totally hangs, the other printlns will stop printing. If the USB connection drops but the task can exit, you will see the println inside the loop stop printing. In any case try also another BT adapter (I'm not sure whether the authors recommend a specific BT dongle)

Will do that & get back to the conversation...Thanks for your time @frarugi87.

source: Stack Exchange

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

sort: votes


text:
Yún not detecting SD card
My Arduino Yún is not detecting my previously working SD card. The metal contacts are closed. There is no dmesg output after plugging in the SD. It does not detect a different SD.
Any ideas for what's wrong?

I wrote about the contacts because other people have had that issue, and my yun is upgraded

Looking at the image, that SD card is not completely inserted into the Yún.

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


text:
Simultaneously reading data from multiple serial ports
I have three sensors latched on to three different Arduino devices.
The respective Arduino devices are connected on to an Arduino Mega on Serial1, Serial2 and Serial3.
The data from each device component (i.e., an Arduino with an accompanying sensor) were sent in data packets with different starter byte headers ('$' , '/' & '#' ) accompanying the buffered data from each individual device component onto the Mega on the Tx/Rx lines.
My question here is, how can I simultaneously read out all the data from the different serial ports on the Arduino mega sketch?

My question here is how can I simultaneously read out all the data from the different serial ports on the arduino mega sketch.

As you are using several serial ports data can already be received simultaneously. Each serial software class (Serial1, Serial2, Serial3) has an internal buffer where data is stored until it is read.
You only need to read the data before the internal buffers are filled and there is a risk for over-flow. Check that data is available and read as usual per serial port. Avoid any blocking calls to avoid buffer over-flow.
Cheers!

I had my arduino mega receiving the data from Serial2 and Serial3, by adopting a sketch that was developed by @Majenko in answer to the post Processing Serial data. The sketch below outputs data to the serial monitor. The NEW problem I have now is trying to develop a python sketch that would seperate the data from the buffers into two different csv files, with each csv files representing the data from each of the two sensors.
    static char buffer[20];
    int count =0;

    void setup()
   {
    Serial.begin(115200);
    Serial2.begin(115200);
    Serial3.begin(115200);
    delay(50);

    }

    void loop(){

if (Serial.available()){  //Slide the window
   for(count=0; count<10; count++){
      buffer[count] = Serial.read();
      //Add the new character
      buffer[9] = Serial.read();

      //Check the framing window
   if((buffer[0] == '$') && (buffer[9] == 0xAC)){
     //Calculate the checksum
      uint16_t cs = 0;
   for (uint16_t i = 2; i < 8; i++){
    cs += buffer[i];
    }
    //if the checksum matches....
    if(cs == buffer[8]){
      //Send the byte to serial port three
      Serial2.write(buffer, count);
  }
  }

 }
}

 if (Serial2.available()){
    for(count=0; count<10; count++){
      buffer[count] = Serial2.read();
      //Send the byte to serial port three
      Serial.write(buffer, count);
     }
 }

 if (Serial.available()){  //Slide the window
   for(count=11; count<20; count++){
      buffer[count] = Serial.read();
      //Add the new character
      buffer[19] = Serial.read();

      //Check the framing window
   if((buffer[11] == '+') && (buffer[19] == 0xAE)){
     //Calculate the checksum
      uint16_t cs2 = 0;
   for (uint16_t i = 6; i < 18; i++){
    cs2 += buffer[i];
    }
    //if the checksum matches....
    if(cs2 == buffer[18]){
      //Send the byte to serial port three
      Serial3.write(buffer, count);
  }
  }

 }
}

 if (Serial3.available()){
    for(count=11; count<20; count++){
      buffer[count] = Serial3.read();
      //Send the byte to serial port three
      Serial.write(buffer, count);
     }
 }

}

The easiest and most overlooked way to read ANY hardware serial ( Serialx) is to utilize Arduino IDE main() function layout and let the serialEventx do the work.
Here is much simplified layout of IDE main () function.
main()
{
Setup()
for(;;)
{
loop()
serialEventx()
}
}
However using serialEvent requires much different approach to your program flow - the loop() cannot have any logic which would introduce a delay.
Your program must process the serialEvent FIRST, loop() processing is secondary.

SerialEvent adds nothing and solves nothing.  It is just as susceptible to delay as any code in (or called from) loop.  The user-written serialEvent must still check available before doing read, so it is truly equivalent.  It essentially moves the serial handling to the end of loop, without adding any capability.  In spite of its name, the event routine is still blocked by loop, whether there are delays or not.  If serialEvent had been called from the ISR, well, that would have been useful. :-/


text:
Measure current and consumption
I'm trying to measure kWh with an Arduino that I have connected to a ESP8266 that communicates this value to a web server I have. And I've been trying to find the best and easiest way to go about this.
I'm thinking that I can hook a PMAC903 up to the Arduino using the interrupt pins and measuring the pulses, but I don't really know how I'm supposed to do that? Will it even work? Is this the way it's normally done? I can't really say I've found an easy solution to measure current.
You can find documentation for the PMAC903 here and I'm currently in possession of an Arduino Uno that I'm using.

You might get away with only the ESP8266, it's good enough to count pulses. The PMAC also seems to talk "Modbus-RTU protocol" RS485. I figure you're trying to measure consumption of a house and not something like the consumption/current of an LED?

Somewhat related project

The state of this meter can be read in 3 ways:

Pulse, this is very easy to implement. But depending on the stability of the hardware u can miss pulses leading to inaccurate values. In this way u have to calculate the meter value yourself.
RS485, this is a communication bus not default on arduino. But given this link https://arduino-info.wikispaces.com/RS485-Modules i think it is doable but not easy. This will read the value from the meter.
M-Bus: There is special hardware needed to interact with it. This is the industry standard of doing it. It's not cheap. But u can link many meters together. This will read the value from the meter.

Depending on your time/knowledge/other requirements u have to make a chose what way your going to use.


text:
exit(0) function shows up an error
So I have been trying to write a code where I use the millis() function to print the milliseconds of on-time of the board using Serial. But the condition is I want to stop printing the value once it reaches 10 seconds (10000ms).
I have been trying to use the exit() function but I get no output then.
#include<stdlib.h>

void setup()
{

  Serial.begin(9600);          //  setup serial

}

void loop()

{

unsigned long timer1;

while(timer1%10000!=0)

{

timer1=millis();

Serial.println(timer1);

}

    exit(1);

}

What do you imagine exit() is supposed to do in an embedded system?

exit() is probably a bad idea in a bare-metal embedded system unless you know for a fact how the environment will respond.  Consider either an infinite while(1); loop explicit in your own code, or shutting down the processor.  Make sure to wait until the serial output buffer is empty before shutting down or disabling interrupts, or you may see your messages truncated.

Where do you suppose exit() would exit to in a microcontroller? Your desk?

The AVR library documentation for exit() is great help. It explains that the interrupts are turned off and an infinite loop is entered. As the interrupts get turned off the last characters in the Serial buffer are not transmitted.
You can use Serial.flush() to wait for the transmission to complete before calling exit().
Cheers!


text:
Adafruit TLC5947 breakout board is not working with my Arduino Uno
I am trying to use this board (setup tutorial on left hand nav) with my Arduino Uno.  I have tried using their example code, as well as my own simplified code, to turn on a single blue LED.
The simplified code I "wrote" is as follows:
#include "Adafruit_TLC5947.h"

#define NUM_TLC5974 1

#define data   3
#define clock   5
#define latch   6

Adafruit_TLC5947 tlc = Adafruit_TLC5947(NUM_TLC5974, clock, data, latch);

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

void loop() {
  tlc.setPWM(0, 4095);
  tlc.write();
}

Scroll to the bottom for reference. (TLC5947)

This compiles and uploads successfully.  I have DIN connected to 3, CLK to 5, and LAT to 6.  V+ is connected to the Arduino 5V pin, and GND to Arduino ground.
Using this setup, the LED does not turn on when connected to channel 0 on the board.  Using a multimeter, I have verified that the voltage between common ground and the channel 0 pin is ~0V.  Checking voltage on the board between GND and V+, I see 4.8V, which looks good.  Connecting the LED directly to the V+ line lights it up, but obviously isn't switchable.
I have no clue why I'm not seeing anything on channel 0's output when I directly write it to 100% duty cycle.
Why is this not working?

... the LED does not turn on when connected to channel 0 on the board. [...] Connecting the LED directly to the v+ line lights it up, but obviously isn't switchable.

From this I suspect that you have connected the LED between pin 0 and ground. The problem with doing this is that the TLC594x LED driver outputs are current sinks, and connect the output to ground when on. The LEDs must connect between V+ and the output as shown in the datasheet.


text:
What is wrong with my state machines?
My goal is to make an automatic gate and garage door, and it has a servo as the lock mechanism on the gate, and alarm systems that notify when the gate or garage door is open too long, more than the interval (in my case 10 seconds) through a buzzer.
It also uses:

Bluetooth to send a command (which is readChar) to open/close the gate and open/close the garage.
4 limit switches (2 switched located at both end of gate and garage to stop its movement).

I want that the gate and garage doors can be opened/closed at the same time, so there are 2 state machines. And the alarm system (if it is activated) will stop when the gate reaches limit switch 1, and the garage reaches limit switch 3.
However with my current code (compiled), I get:

The first state machine (stateGate) can open and close the gate, but the buzzer does not buzz when it exceeds the limit.
The second state machine (stateGarage) did not do anything/did not operate.

Can someone point out/correct what is the mistake? Because I can't seem to find what is wrong. Thank you in advance!
Here is my current full code:
#include <Servo.h>

Servo Servokey;

// Motor for Gate (MotorA)
const byte IN1 = 9;
const byte IN2 = 8;
const byte EnableMotorA = 6;

// Motor for Garage Door (MotorB)
const byte IN3 = 4;
const byte IN4 = 3;
const byte EnableMotorB = 5;

const byte LimitSwitch1 = A1;
const byte LimitSwitch2 = A2;
const byte LimitSwitch3 = A3;
const byte LimitSwitch4 = A4;

const int piezoPin = 10; // piezo for the alarm system

int StateGate;
int StateGarage;
boolean gateClosed = false;
boolean garageClosed = false;

unsigned long GateMillis; //will hold the timer for Gate
unsigned long GarageMillis; // will hold the timer for Garage
unsigned long interval = 10000;

void setup() {
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(EnableMotorA, OUTPUT);

  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
  pinMode(EnableMotorB, OUTPUT);

  pinMode(LimitSwitch1, INPUT);
  pinMode(LimitSwitch2, INPUT);
  pinMode(LimitSwitch3, INPUT);
  pinMode(LimitSwitch4, INPUT);

  Servokey.attach(11); // lock mechanism for Gate
  Servokey.write(70);

  unsigned long GateMillis = 0; //will hold the timer for Gate
  unsigned long GarageMillis = 0;

  Serial.begin(9600);
}

void loop() {
  byte readChar = 0;
  if (Serial.available() > 0)
    readChar = Serial.read();
  stateGate(readChar);
  stateGarage(readChar);
}

void stateGate(byte readChar) {
  static enum { StateGate_Idle, StateGate_Opening, StateGate_Open, StateGate_Closing, StateGate_Close, StateGate_Alarm} StateGate;
  switch (StateGate) {
    case StateGate_Idle:
      { // If we received a valid command, start the operation
        if (readChar > 0) {
          switch (readChar) {
            case 'A':
              StateGate = StateGate_Opening;
              break;
            case 'B':
              StateGate = StateGate_Closing;
              break;
            default:
              // Here you can notify that there was a bad command
              break;
          }
        }
      }
      break;
    case StateGate_Opening:
      Servokey.write(140);
      delay(50);
      digitalWrite(IN1, LOW);
      digitalWrite(IN2, HIGH);
      analogWrite(EnableMotorA, 250);
      StateGate = StateGate_Open;
      break;
    case StateGate_Open:
      if (digitalRead(LimitSwitch2)) {
        digitalWrite(IN1, LOW);
        digitalWrite(IN2, LOW);
        analogWrite(EnableMotorA, 0);
        GateMillis = millis();
        gateClosed = false;
        StateGate = StateGate_Idle;
      }
      break;
    case StateGate_Closing:
      digitalWrite(IN1, HIGH);
      digitalWrite(IN2, LOW);
      analogWrite(EnableMotorA, 250);
      StateGate = StateGate_Close;
      break;
    case StateGate_Close:
      if (digitalRead(LimitSwitch1)) {
        digitalWrite(IN1, LOW);
        digitalWrite(IN2, LOW);
        analogWrite(EnableMotorA, 0);
        Servokey.write(70);
        delay(50);
        gateClosed = true;
        StateGate = StateGate_Idle;
      }
      break;
    case StateGate_Alarm:
      if ((millis() - GateMillis) > interval && gateClosed == false) {
        tone(piezoPin, 5000);
        StateGate = StateGate_Idle;
      } else if (gateClosed == true) {
        StateGate = StateGate_Idle;
      }
      break;
    default:
      StateGate = StateGate_Idle;
      break;
  }
}

void stateGarage(byte readChar) {
  static enum { StateGarage_Idle, StateGarage_Opening, StateGarage_Open, StateGarage_Closing, StateGarage_Close, StateGarage_Alarm} StateGarage;
  switch (StateGarage) {
    case StateGarage_Idle:
      { // If we received a valid command, start the operation
        if (readChar > 0) {
          switch (readChar) {
            case 'C':
              StateGarage = StateGarage_Opening;
              break;
            case 'D':
              StateGarage = StateGarage_Closing;
              break;
            default:
              // Here you can notify that there was a bad command
              break;
          }
        }
      }
      break;
    case StateGarage_Opening:
      digitalWrite(IN3, LOW);
      digitalWrite(IN4, HIGH);
      analogWrite(EnableMotorA, 250);
      StateGarage = StateGarage_Open;
      break;
    case StateGarage_Open:
      if (digitalRead(LimitSwitch4)) {
        digitalWrite(IN3, LOW);
        digitalWrite(IN4, LOW);
        analogWrite(EnableMotorA, 0);
        GarageMillis = millis();
        garageClosed = false;
        StateGarage = StateGarage_Idle;
      }
      break;
    case StateGarage_Closing:
      digitalWrite(IN3, HIGH);
      digitalWrite(IN4, LOW);
      analogWrite(EnableMotorA, 250);
      StateGarage = StateGarage_Close;
      break;
    case StateGarage_Close:
      if (digitalRead(LimitSwitch3)) {
        digitalWrite(IN3, LOW);
        digitalWrite(IN4, LOW);
        analogWrite(EnableMotorB, 0);
        garageClosed = true;
        StateGarage = StateGarage_Idle;
      }
      break;
    case StateGarage_Alarm:
      if ((millis() - GarageMillis) > interval && garageClosed == false) {
        tone(piezoPin, 5500);
        StateGarage = StateGarage_Idle;
      } else if (garageClosed == true)
        StateGarage = StateGarage_Idle;
      break;
    default:
      StateGarage = StateGarage_Idle;
      break;
  }
}

I made another code like what @CodeGorilla had suggested, however it turned out that both state machines did not operate.... I think I am still missed out something
Here's the other code:
#include <Servo.h>

Servo Servokey;

enum StateGate { StateGate_Idle = 0, StateGate_Opening, StateGate_Open, StateGate_Closing, StateGate_Closed, StateGate_Alarm, StateGate_Last };
enum StateGarage { StateGarage_Idle = 0, StateGarage_Opening, StateGarage_Open, StateGarage_Closing, StateGarage_Closed, StateGarage_Alarm, StateGarage_Last };

struct Data1
{
  byte IN1;
  byte IN2;
  bool Enable;
  int NextState;

  Data1(byte in1, byte in2, bool enable, int nextstate)
       :IN1(in1), IN2(in2), Enable(enable), NextState(nextstate)
  {}
};

struct Data2
{
  byte IN3;
  byte IN4;
  bool Enable;
  int NextState;

  Data2(byte in3, byte in4, bool enable, int nextstate)
       :IN3(in3), IN4(in4), Enable(enable), NextState(nextstate)
  {}
};

struct MotorData1
{
  byte IN1;
  byte IN2;
  byte Enable;
  MotorData1(byte i1, byte i2, byte enable)
       : IN1(i1), IN2(i2), Enable(enable)
  {}
  void pinMode() const
  {
    :: pinMode(IN1, OUTPUT);
    :: pinMode (IN2, OUTPUT);
    :: pinMode (Enable, OUTPUT);
  }
  int Set(const Data1& data1) const
  {// Set the motors to the given state
    digitalWrite(IN1, data1.IN1);
    digitalWrite(IN2, data1.IN2);
    analogWrite(Enable, data1.Enable?250:0);
    return data1.NextState;
  }
};

struct MotorData2
{
  byte IN3;
  byte IN4;
  byte Enable;
  MotorData2(byte i3, byte i4, byte enable)
       : IN3(i3), IN4(i4), Enable(enable)
  {}
  void pinMode() const
  {
    :: pinMode(IN3, OUTPUT);
    :: pinMode (IN4, OUTPUT);
    :: pinMode (Enable, OUTPUT);
  }
  int Set(const Data2& data2) const
  {// Set the motors to the given state
    digitalWrite(IN3, data2.IN3);
    digitalWrite(IN4, data2.IN4);
    analogWrite(Enable, data2.Enable?250:0);
    return data2.NextState;
  }
};
// Define the motors
const MotorData1 MotorsA(9, 8, 6);
const MotorData2 MotorsB(4, 3, 5);

const byte LimitSwitch1 = A1;
const byte LimitSwitch2 = A2;
const byte LimitSwitch3 = A3;
const byte LimitSwitch4 = A4;

const int piezoPin = 10; // piezo for the alarm system

StateGate CurrentGateState = StateGate_Idle;
StateGarage CurrentGarageState = StateGarage_Idle;
boolean gateClosed = false;
boolean garageClosed = false;

unsigned long GateMillis(0); //will hold the timer for Gate
unsigned long GarageMillis(0); // will hold the timer for Garage
unsigned long interval = 10000;

void setup() {
    MotorsA.pinMode();
    MotorsB.pinMode();

    pinMode(LimitSwitch1, INPUT);
    pinMode(LimitSwitch2, INPUT);
    pinMode(LimitSwitch3, INPUT);
    pinMode(LimitSwitch4, INPUT);

    Servokey.attach(11); // lock mechanism for Gate
    Servokey.write(70);

    Serial.begin(9600);
}

void loop()
{
    byte readChar = 0;
    if (Serial.available() > 0)
        readChar = Serial.read();
    stateGate(readChar);
    stateGarage(readChar);
}

void stateGate(byte readChar)
{// Define the state machine
    static const Data1 stateData1[StateGate_Last] =
    {
          Data1(LOW, LOW, false, StateGate_Idle)  // StateGate_Idle
        , Data1(LOW, HIGH, true, StateGate_Open)  // StateGate_Opening
        , Data1(LOW, LOW, false, StateGate_Idle)  // StateGate_Open
        , Data1(HIGH, LOW, false, StateGate_Closed)  // StateGate_Closing
        , Data1(LOW, LOW, false, StateGate_Idle)  // StateGate_Closed
        , Data1(LOW, LOW, false, StateGate_Idle)  // StateGate_Alarm
    };
switch (CurrentGateState)
    {
        case StateGate_Idle:
        { // If we received a valid command, start the operation
            if (readChar > 0) {
                switch (readChar) {
                case 'A':
                    if (CurrentGateState != StateGate_Open)
                    {  // Prevent opening the gate if its already open
                        CurrentGateState = StateGate_Opening;
                    }
                    break;
                case 'B':
                    if (CurrentGateState != StateGate_Closed)
                    {// Prevent closing the gate if its already closed.
                        CurrentGateState = StateGate_Closing;
                    }
                    break;
                default:
                    // Here you can notify that there was a bad command
                    break;
                }
            }
        }
        break;
    case StateGate_Opening:
        Servokey.write(140);
        delay(50);
        CurrentGateState = MotorsA.Set(stateData1[StateGate_Opening]);
        break;
    case StateGate_Open:
        if (digitalRead(LimitSwitch2))
        {
            CurrentGateState = MotorsA.Set(stateData1[StateGate_Open]);
            GateMillis = millis();
            gateClosed = false;
        }
        break;
    case StateGate_Closing:
        CurrentGateState = MotorsA.Set(stateData1[StateGate_Closing]);
        break;
    case StateGate_Closed:
        if (digitalRead(LimitSwitch1))
        {
            CurrentGateState = MotorsA.Set(stateData1[StateGate_Closed]);
            Servokey.write(70);
            delay(50);
            gateClosed = true;
        }
        break;
    case StateGate_Alarm:
        if ((millis() - GateMillis) > interval && gateClosed == false) {
            tone(piezoPin, 5000);
            CurrentGateState = StateGate_Idle;
        }
        else if (gateClosed == true) {
            CurrentGateState = StateGate_Idle;
        }
        break;
    default:
        CurrentGateState = StateGate_Idle;
        break;
    }
}

void stateGarage(byte readChar)
{// Define the state machine
    static const Data2 stateData2[StateGarage_Last] =
    {
          Data2(LOW, LOW, false, StateGarage_Idle)  // StateGate_Idle
        , Data2(LOW, HIGH, true, StateGarage_Open)  // StateGate_Opening
        , Data2(LOW, LOW, false, StateGarage_Idle)  // StateGate_Open
        , Data2(HIGH, LOW, false, StateGarage_Closed)  // StateGate_Closing
        , Data2(LOW, LOW, false, StateGarage_Idle)  // StateGate_Closed
        , Data2(LOW, LOW, false, StateGarage_Idle)  // StateGate_Alarm
    };
switch (CurrentGarageState)
    {
        case StateGarage_Idle:
        { // If we received a valid command, start the operation
            if (readChar > 0) {
                switch (readChar) {
                case 'A':
                    if (CurrentGarageState != StateGarage_Open)
                    {  // Prevent opening the gate if its already open
                        CurrentGarageState = StateGarage_Opening;
                    }
                    break;
                case 'B':
                    if (CurrentGarageState != StateGarage_Closed)
                    {// Prevent closing the gate if its already closed.
                        CurrentGarageState = StateGarage_Closing;
                    }
                    break;
                default:
                    // Here you can notify that there was a bad command
                    break;
                }
            }
        }
        break;
    case StateGarage_Opening:
        CurrentGarageState = MotorsB.Set(stateData2[StateGarage_Opening]);
        break;
    case StateGarage_Open:
        if (digitalRead(LimitSwitch2))
        {
            CurrentGarageState = MotorsB.Set(stateData2[StateGarage_Open]);
            GarageMillis = millis();
            garageClosed = false;
        }
        break;
    case StateGarage_Closing:
        CurrentGarageState = MotorsB.Set(stateData2[StateGarage_Closing]);
        break;
    case StateGarage_Closed:
        if (digitalRead(LimitSwitch1))
        {
            CurrentGarageState = MotorsB.Set(stateData2[StateGarage_Closed]);
            Servokey.write(70);
            delay(50);
            garageClosed = true;
        }
        break;
    case StateGarage_Alarm:
        if ((millis() - GarageMillis) > interval && garageClosed == false) {
            tone(piezoPin, 5000);
            CurrentGarageState = StateGarage_Idle;
        }
        else if (garageClosed == true) {
            CurrentGarageState = StateGarage_Idle;
        }
        break;
    default:
        CurrentGarageState = StateGarage_Idle;
        break;
    }
}

you check for state StateGarage_Alarm, but you have no command that actually causes the state machine to enter that state. .... your state machine has some questionable functionality ... the StateGate_Opening state code sets the state to StateGate_Open without checking if the gate actually opened.  ... similar thing is being repeated in other parts of the code

the StateGate_Open is actually the problem with the code

for state 'StateGarage_Alarm', i've been doubting where should connect it to, and thought that with 'if' function it can be worked, so is it better to connect it to 'StateGate_Open' or 'StateGate_Closing' ?

what is the problem with 'StateGate_Open'? do i need to create 'boolean openGate'?

You could refactor this code and make it much easier to debug.  Each case could be reduced to a 5 element structure {IN1State, IN2State, EnableA, EnableB, StateGArage}.  garageClosed could be replaced with two extra StateGarage_ entries Opened and Closed.

There a couple of places where you define variables which hide other variables. eg Line 27 is hidden by 48 for a little bit.  More importantly line 22 is hidden by 63 and this is probably why your state machine doesn't work.
As I said in my comment you could make life easier for yourself by refactoring it.  Most of the states have the same lines of code in, so by using a structure you can reduce the number of lines and hopefully the number of bugs.  I had a play a roughed out this to show what I mean.  (I have not compiled it, let alone run it, but it might be a starting point.
Servo Servokey;
// Global to prevent accidental variable declaration.
static enum StateGate { StateGate_Idle = 0, StateGate_Opening, StateGate_Open, StateGate_Closing, StateGate_Closed, StateGate_Alarm, StateGate_Last };
// Defines the state machines
struct Data
{
    byte IN1;
    byte IN2;
    bool Enable;
    int NextState;

    Data(byte in1, byte in2, bool enable, int nextState)
        : IN1(in1), IN2(in2), Enable(enable), NextState(nextState))
    {}
};
// Group the motor data to make things tidier
struct MotorData
{
    byte IN1;
    byte IN2;
    byte Enable;
    MotorData(byte i1, byte i2, byte enable)
        :IN1(i1), IN2(i2), Enable(enable)
    {}
    void pinMode() const  // Set the pin mode
    {
        ::pinMode(IN1, OUTPUT);  // Use the global pinMode not this function
        ::pinMode(IN2, OUTPUT);
        ::pinMode(Enable, OUTPUT);
    }
    int Set(const Data& data) const
    { // Set the motors to the given state
        digitalWrite(IN1, data.IN1);
        digitalWrite(IN2, data.IN2);
        analogWrite(Enable, data.Enable?250:0);
        return data.NextState
    }
};
// Define the motors
const MotorData MotorsA(9, 8, 6);
const MotorData MotorsB(4, 3, 5);

const byte LimitSwitch1 = A1;
const byte LimitSwitch2 = A2;
const byte LimitSwitch3 = A3;
const byte LimitSwitch4 = A4;

const int piezoPin = 10; // piezo for the alarm system

StateGate CurrentGateState = StateGate_Idle;  // It is best to initialise the variables.
int StateGarage;
boolean gateClosed = false;
boolean garageClosed = false;

unsigned long GateMillis(0); //will hold the timer for Gate
unsigned long GarageMillis(0); // will hold the timer for Garage
unsigned long interval = 10000;

void setup() {
    MotorsA.pinMode();
    MotorsB.pinMode();

    pinMode(LimitSwitch1, INPUT);
    pinMode(LimitSwitch2, INPUT);
    pinMode(LimitSwitch3, INPUT);
    pinMode(LimitSwitch4, INPUT);

    Servokey.attach(11); // lock mechanism for Gate
    Servokey.write(70);

    Serial.begin(9600);
}

void loop()
{
    byte readChar = 0;
    if (Serial.available() > 0)
        readChar = Serial.read();
    stateGate(readChar);
    stateGarage(readChar);
}

void stateGate(byte readChar)
{// Define the state machine
    static const Data stateData[StateGate_Last] =
    {
          Data(LOW, LOW, false, StateGate_Idle)  // StateGate_Idle
        , Data(LOW, HIGH, true, StateGate_Open)  // StateGate_Opening
        , Data(LOW, LOW, false, StateGate_Idle)  // StateGate_Open
        , Data(HIGH, LOW, false, StateGate_Closed)  // StateGate_Closing
        , Data(LOW, LOW, false, StateGate_Idle)  // StateGate_Closed
        , Data(LOW, LOW, false, StateGate_Idle)  // StateGate_Alarm
    };

    switch (CurrentGateState)
    {
        case StateGate_Idle:
        { // If we received a valid command, start the operation
            if (readChar > 0) {
                switch (readChar) {
                case 'A':
                    if (CurrentGateState != StateGate_Open)
                    {  // Prevent opening the gate if its already open
                        CurrentGateState = StateGate_Opening;
                    }
                    break;
                case 'B':
                    if (CurrentGateState != StateGate_Closed)
                    {// Prevent closing the gate if its already closed.
                        CurrentGateState = StateGate_Closing;
                    }
                    break;
                default:
                    // Here you can notify that there was a bad command
                    break;
                }
            }
        }
        break;
    case StateGate_Opening:
        Servokey.write(140);
        delay(50);
        CurrentGateState = MotorsA.Set(stateData[StateGate_Opening]);
        break;
    case StateGate_Open:
        if (digitalRead(LimitSwitch2))
        {
            CurrentGateState = MotorsA.Set(stateData[StateGate_Open]);
            GateMillis = millis();
            gateClosed = false;
        }
        break;
    case StateGate_Closing:
        CurrentGateState = MotorsA.Set(stateData[StateGate_Closing]);
        break;
    case StateGate_Closed:
        if (digitalRead(LimitSwitch1))
        {
            CurrentGateState = MotorsA.Set(stateData[StateGate_Closed]);
            Servokey.write(70);
            delay(50);
            gateClosed = true;
        }
        break;
    case StateGate_Alarm:
        if ((millis() - GateMillis) > interval && gateClosed == false) {
            tone(piezoPin, 5000);
            CurrentGateState = StateGate_Idle;
        }
        else if (gateClosed == true) {
            CurrentGateState = StateGate_Idle;
        }
        break;
    default:
        CurrentGateState = StateGate_Idle;
        break;
    }
}

void stateGarage(byte readChar) {
    static enum { StateGarage_Idle, StateGarage_Opening, StateGarage_Open, StateGarage_Closing, StateGarage_Close, StateGarage_Alarm } StateGarage;
    switch (StateGarage) {
    case StateGarage_Idle:
    { // If we received a valid command, start the operation
        if (readChar > 0) {
            switch (readChar) {
            case 'C':
                StateGarage = StateGarage_Opening;
                break;
            case 'D':
                StateGarage = StateGarage_Closing;
                break;
            default:
                // Here you can notify that there was a bad command
                break;
            }
        }
    }
    break;
    case StateGarage_Opening:
        digitalWrite(IN3, LOW);
        digitalWrite(IN4, HIGH);
        analogWrite(EnableMotorA, 250);
        StateGarage = StateGarage_Open;
        break;
    case StateGarage_Open:
        if (digitalRead(LimitSwitch4)) {
            digitalWrite(IN3, LOW);
            digitalWrite(IN4, LOW);
            analogWrite(EnableMotorA, 0);
            GarageMillis = millis();
            garageClosed = false;
            StateGarage = StateGarage_Idle;
        }
        break;
    case StateGarage_Closing:
        digitalWrite(IN3, HIGH);
        digitalWrite(IN4, LOW);
        analogWrite(EnableMotorA, 250);
        StateGarage = StateGarage_Close;
        break;
    case StateGarage_Close:
        if (digitalRead(LimitSwitch3)) {
            digitalWrite(IN3, LOW);
            digitalWrite(IN4, LOW);
            analogWrite(EnableMotorB, 0);
            garageClosed = true;
            StateGarage = StateGarage_Idle;
        }
        break;
    case StateGarage_Alarm:
        if ((millis() - GarageMillis) > interval && garageClosed == false) {
            tone(piezoPin, 5500);
            StateGarage = StateGarage_Idle;
        }
        else if (garageClosed == true)
            StateGarage = StateGarage_Idle;
        break;
    default:
        StateGarage = StateGarage_Idle;
        break;
    }
}

EDIT ----------------
This code is a complete version of the code refactored to reduce the repetitive statements and try and minimise the number of potential bugs.  I have also removed one of the state functions, since apart form the lock and acting on different motors and switches they seemed to be the same.
#include "Servo.h"

Servo Servokey;

enum State { State_Idle = 0, State_Opening, State_Open, State_Closing, State_Closed, State_Alarm, State_Last };

struct Data
{
    byte IN1;
    byte IN2;
    bool Enable;
    State NextState;

    Data(byte in1, byte in2, bool enable, State nextstate)
        :IN1(in1), IN2(in2), Enable(enable), NextState(nextstate)
    {}
};

struct MotorData
{
    byte IN1;
    byte IN2;
    byte Enable;
    MotorData(byte i1, byte i2, byte enable)
        : IN1(i1), IN2(i2), Enable(enable)
    {}
    void pinMode() const
    {
        ::pinMode(IN1, OUTPUT);
        ::pinMode(IN2, OUTPUT);
        ::pinMode(Enable, OUTPUT);
    }
    State Set(const Data& Data) const
    {// Set the motors to the given state
        digitalWrite(IN1, Data.IN1);
        digitalWrite(IN2, Data.IN2);
        analogWrite(Enable, Data.Enable ? 250 : 0);
        return Data.NextState;
    }
};

/// Defines all the data for the gate or garage.
struct Object
{
    State           CurrentState;               // The current state of the object
    char            OpenCommand;                // The command to open the gate/garage
    char            CloseCommand;
    MotorData&      Motors;                     // A reference to the motors object
    byte            LimitSwitchA;
    byte            LimitSwitchB;
    bool            LockObject;                 // True if the object should be locked/ unlocked
    unsigned long   OpenTime;                   // The time the object was last opened.
    bool            IsClosed;                   // True when the object is closed.
    Object(char o, char c, MotorData m, byte la, byte lb, bool lock)
        : CurrentState(State_Idle)
        , OpenCommand(o)
        , CloseCommand(c)
        , Motors(m)
        , LimitSwitchA(la)
        , LimitSwitchB(lb)
        , LockObject(lock)
        , OpenTime(0)
        , IsClosed(false)
    {}
};

// Define the motors
const MotorData MotorsA(9, 8, 6);
const MotorData MotorsB(4, 3, 5);

const byte LimitSwitch1 = A1;
const byte LimitSwitch2 = A2;
const byte LimitSwitch3 = A3;
const byte LimitSwitch4 = A4;

const int piezoPin = 10; // piezo for the alarm system

Object Gate('A', 'B', MotorsA, LimitSwitch1, LimitSwitch2, true);
Object Garrage('C', 'D', MotorsB, LimitSwitch3, LimitSwitch4, false);

unsigned long interval = 10000;

/// Lock or unlock the lock.
void LockGate(bool lock=true)
{
    if (lock)
        Servokey.write(70);
    else
        Servokey.write(140);
    delay(50);
}

void setup() {
    MotorsA.pinMode();
    MotorsB.pinMode();

    pinMode(LimitSwitch1, INPUT);
    pinMode(LimitSwitch2, INPUT);
    pinMode(LimitSwitch3, INPUT);
    pinMode(LimitSwitch4, INPUT);

    Servokey.attach(11); // lock mechanism for Gate
    Servokey.write(70);

    Serial.begin(9600);
}

void loop()
{
    byte readChar = 0;
    if (Serial.available() > 0)
        readChar = Serial.read();
    StateMachine(readChar, Gate);
    StateMachine(readChar, Garrage);
}

void StateMachine(const byte readChar, Object& objectData)
{// Define the state machine
    static const Data stateData[State_Last] =
    {
        Data(LOW, LOW, false, State_Idle)  // State_Idle
        , Data(LOW, HIGH, true, State_Open)  // State_Opening
        , Data(LOW, LOW, false, State_Idle)  // State_Open
        , Data(HIGH, LOW, true, State_Closed)  // State_Closing
        , Data(LOW, LOW, false, State_Idle)  // State_Closed
        , Data(LOW, LOW, false, State_Idle)  // State_Alarm
    };
    switch (objectData.CurrentState)
    {
    case State_Idle:                // If we received a valid command, start the operation
        if (readChar > 0)
        {
            if (readChar == objectData.OpenCommand)
            {
                objectData.CurrentState = State_Opening;
            }
            else if (readChar == objectData.CloseCommand)
            {
                objectData.CurrentState = State_Closing;
            }
            else
            {
                // Here you can notify that there was a bad command
            }
        }
        break;
    case State_Opening:
        if (objectData.LockObject)
            LockGate(false);
        objectData.CurrentState = objectData.Motors.Set(stateData[State_Opening]);
        break;
    case State_Open:
        if (digitalRead(LimitSwitch2))
        {
            objectData.CurrentState = objectData.Motors.Set(stateData[State_Open]);
            objectData.OpenTime = millis();
            objectData.IsClosed = false;
        }
        break;
    case State_Closing:
        objectData.CurrentState = objectData.Motors.Set(stateData[State_Closing]);
        break;
    case State_Closed:
        if (digitalRead(LimitSwitch1))
        {
            objectData.CurrentState = objectData.Motors.Set(stateData[State_Closed]);
            if (objectData.LockObject)
                LockGate(true);
            objectData.IsClosed = true;
        }
        break;
    case State_Alarm:
        if ((millis() - objectData.OpenTime) > interval && objectData.IsClosed == false) {
            tone(piezoPin, 5000);
            objectData.CurrentState = State_Idle;
        }
        else if (objectData.IsClosed == true) {
            objectData.CurrentState = State_Idle;
        }
        break;
    default:
        objectData.CurrentState = State_Idle;
        break;
    }
}

As before I can't test it, without righting myself a test harness and "it doesn't work" doesn't really help me know what the fault is.  One thing I did notice is the Alarm won't work.  This is because nothing ever puts it into that state, maybe the check to see if the alarm has been triggered should be in the idle state and if it occurs the state machine should move into the alarm state.
What I have tried to show you is if you are doing the same things repeatedly on different data then define the data outside of the function and reduce the amount of code you write.  You would never write these functions would you?
int Add2and2 ()
{return 2+2;}
int Add2and3 ()
{return 2+3;}
int Add2and4 ()
{return 2+4;}

But its often very difficult to spot that you are doing that in your own code.
If there is still something wrong, please describe what the fault is and I'll see what I can do.

I have made the code like your example, but I made the structures separately for both state machines. It has 269 lines in total (longer than the first one). And both of the state machines did not operate....
Could you please tell me what is wrong? I left the code on my question above

I don't understand why you have duplicated the data and motor structures, there is no need.  You have also copied the state machine from the gate and used it for the garage, you have even left the letters the same.  This answer was not about making your code shorter, it was about making it easier to debug an maintain.

Feel free to mark it as an answer then.


text:
how to implement AES in LoRa Module with Hardware Flow control using ESP8266?
I am working on project where I have to do  AES encryption of plain text  received through normal UART port of ESP8266 create a cipher text and sending it to LoRa module (EByte E32 868T30D) through Software Serial port and recieve on the other end decrypt and get the plain text back. the problem I am facing is when I try to sendlarge array of bytes more than 300 or so I am getting garbled values on the other end. I am well aware of the 512 byte limit in LoRa module and so I tried using Hardware flow control by AUX pin that is available. Eventhough I am not successfull in implementing a working code. I have a grey area in how to implement such a hardware flow control in ESP8266. since its my first time I am seeking for help from experts in this field. My project requires me to send about 10kB of data over LoRa with minimum possible delay between each 512 byte transmission

/*===========================================================================================================================================================================
   ---------------------------------------------------- ESP8266 EByte 32 Lora Encryption Test ----------------------------------------------------
   Author: Mister.B
   Date: 10 May 2020
   Objective: To test AES256 ECB Encryption on LoRa Modules
   Third-Party ibraries used:
   1) aes256 - https://github.com/qistoph/ArduinoAES256
  ===========================================================================================================================================================================*/
#include "aes256.h"
#include <SoftwareSerial.h>

//EByte E32 Pin Configuration

#define M0 D5
#define M1 D6
#define AUX D2 // AUX HIGH means BUSY LOW means READY
#define RX_Pin D3
#define TX_Pin D4

//BaudRate Selection

#define E32_BAUD 9600
#define SERIAL_BAUD 9600

//AES Parameters
#define BUFFER_SIZE 2048 //2kB buffer to store the values
#define BLOCK_SIZE 16

//Timeout selection
#define UART_SERIAL_TIMEOUT 5000
#define E32_SERIAL_TIMEOUT 5000

//Debug Selection
#define DEBUG_CONSOLE true

//Class Instances
aes256_context ctxt;
SoftwareSerial E32(RX_Pin, TX_Pin);
//#define E32 Serial
//======Global Variables Declaration======
uint8_t key[] = {
  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f
};
uint8_t data_buffer[BUFFER_SIZE] = {};
int i = 0, in_count = 0, out_count = 0;
unsigned long last_packet_arrival = 0;

//MACROS
#define ARRAY_SIZE(arr) ((sizeof(arr))/(sizeof(arr[0])))
#if DEBUG_CONSOLE == true
#define DUMP(str,i,buf,sz){Serial.println(str);\
    for(i=0;i<sz;++i){if(buf[i]<0x10)Serial.print('0');Serial.print(char(buf[i]),HEX);}\
    Serial.println();}
#else
#define DUMP(str,i,buf,sz)
#endif

void setup()
{
  Serial.begin(SERIAL_BAUD);
  E32.begin(E32_BAUD);
  pinMode(M0, OUTPUT);
  pinMode(M1, OUTPUT);
  pinMode(AUX, INPUT);
  /*
     Setting Ebyte 32 in Normal Mode (M0=LOW and M1=LOW)
  */
  digitalWrite(M0, LOW);
  digitalWrite(M1, LOW);
  delay(1000);
  DUMP("\nKey:", i, key, sizeof(key));
  aes256_init(&ctxt, key); // Send key for key scheduling
}
void loop()
{
  int frame_count = 0;
  out_count = 0;
  in_count = 0;
  last_packet_arrival = millis();
  /*
     RECEIVE DATA FROM EBYTE E32 LoRa
  */
  if (E32.available()) {
    out_count = 0;
    last_packet_arrival = millis();
    frame_count = (int)E32.read();
    while ((millis() - last_packet_arrival < E32_SERIAL_TIMEOUT) or (frame_count > out_count)) {
      out_count += E32.readBytes(data_buffer+out_count,58);
      if (out_count >= BUFFER_SIZE)Serial.printf("\n Input Buffer[%d] full :(", BUFFER_SIZE); break; //Prevent buffer overflow
    }
    Serial.printf("\nFc:%d", frame_count);
    frame_count = 0;
    Serial.printf("\nReceiveCount:%d\n", out_count);
    DUMP("\nRecived Data:", i, data_buffer, out_count);
    for (int n = 0; n <= (out_count / BLOCK_SIZE); n += BLOCK_SIZE)aes256_decrypt_ecb(&ctxt, data_buffer + n);
    DUMP("\nDecrypted Data:", i, data_buffer, out_count);
    for (int i = 0; i < out_count; i++)Serial.print((char)data_buffer[i]); yield();
    memset(data_buffer, 0x00, BUFFER_SIZE);
    out_count = 0;
  }
  /*
     RECEIVE DATA FROM UART Port
  */
  if (Serial.available()) {
    in_count=0;
    last_packet_arrival = millis();
    while ((millis() - last_packet_arrival) < UART_SERIAL_TIMEOUT) {
      in_count += Serial.readBytes(data_buffer + in_count, 58);
      if (in_count >= BUFFER_SIZE)Serial.printf("\n Output Buffer[%d] full :(", BUFFER_SIZE); break; // Prevent buffer overflow
    }
    /*
       Padding with zeros
    */
    if (in_count < 58) { // if Serial data entered is smaller than 58
      for (int i = in_count; i < 58; i++)data_buffer[i] = 0x00;
    }
    if (in_count > 58 && (in_count % 58 != 0)) { // if the Serial data is not multiple of 58 do padding with 0x00
      for (int i = in_count; i < in_count + (in_count % 58); i++)data_buffer[i] = 0x00;
    }
    Serial.printf("\nSendCount:%d", in_count);
    DUMP("\nData Entered:", i, data_buffer, in_count);
    //for (int n = 0; n <= (in_count / BLOCK_SIZE); n += BLOCK_SIZE)aes256_encrypt_ecb(&ctxt, data_buffer + n); // Encrypting whole data by 16 byte blocks
    //DUMP("\nEncrypted Data:", i, data_buffer, in_count);
    /*
       Add the length number of 512 byte in data frame
    */
    //uint8_t data_frame[BUFFER_SIZE + (BUFFER_SIZE % 58)] = {};
    //for (int i = 0; i <= BUFFER_SIZE; i++) data_frame[i + 1] = data_buffer[i];
    //data_frame[0] = (in_count / 58) + 1;
    //DUMP("\nSent Data:", i, data_frame, in_count + 1);
    /*
       Prevent buffer overflow in LoRa module using Hardware Flow control
    */
    uint8_t buff[58] = {};
//    for (int i = 0; i < (in_count / 464)+1 ; i++) //divide the data buffer into 464 byte frames
//    {
//      for (int j = 464 * i; j < (464 * i) + 464; j += 58) { //divide the 464 byte frames into 58 byte frames
        byte* f_count=(in_count<58) ? in_count : (in_count / 58) + 1;
        E32.write(f_count,1);
        for (int j = 0 ; j < in_count ; j+=58){
        memcpy(buff, data_buffer + j, 58);
        aes256_encrypt_ecb(&ctxt,buff);
        DUMP("\nEncrypted Data:", i, buff, 58);
        while (digitalRead(AUX) == HIGH) yield(); // wait for the pin to get LOW
        if (digitalRead(AUX) == LOW) { //if the module is READY send
          E32.write(buff, 58);
//          E32.flush();
        }
      }
//    }
    in_count = 0;
    memset(data_buffer, 0x00, BUFFER_SIZE);
    //memset(data_frame, 0x00, ARRAY_SIZE(data_frame));
  }
}

The ESPSoftwareSerial bundled with the esp8266 Arduino boards package supports transmit flow control with setTransmitEnablePin

@Juraj can we use this pin as an input in ESP8266 and hold say 10kB data in buffer until the pin is asserted to given logic and send data as chunks of 512 byte?

yes the transmit enable pin is an input. you can test availableForWrite to check if you can write more data to SoftwareSerial instance

@Juraj will test this tommorow and will revert back

sorry, I was wrong. the transmit enable has other purpose (as for RS485) and availableForWrite doesn't work as it should on ESPSoftwareSerial

Thanks for disclosing @Juraj. Luckily I didn't start test otherwise I would have been breaking my head. I would appreciate If you could help me with defining a function or a statergy to overcome this issue

it looks like the ESPSoftwareSerial doesn't have internal buffer. so you can simply check the state of the lora pin to decide if you can send.

@Juraj thats where I am facing a problem The User Manual saysWhen the module receives the first package from user, the AUX outputs low level. After all the data are transmitted into RF chip and transmission start, the AUX outputs high level At this time , it means that the wireless data package transmission is started, which enables the user to input another 512 bytes continuously. from this what I understand is I can send data whenever the AUX pin is LOW (in my case is it is HIGH bcoz of transisitor in between).

So, I tried sending a large byte array say more than 2kB and sniffed with a logic analyzer and I noticed the AUX pin stay continuously LOW even after the first 512 byte and aserts HIGH only 500ms after the TX transmission stopped

so you should send 512 bytes and then wait until the AUX pin changes from LOW to HIGH, before sending next 512 bytes?

@Juraj Thats what I understood from the statement given in User manual and tested the hypothesis with logic analyzer but the AUX pin stays low even after sending 512 bytes to the module and only returns HIGH only after 500ms from stopping transmission to the LoRa Module. I don't know is it what its supposed to be then I there is not point in checking at AUX pin and I have to work on something to stop the buffer overflow inside LoRa module and also I need a way for the receiving module to wait until all the send bytes are received and the receive has to send the data all at once through UART

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


text:
How to dynamically set pinMode and dynamically write value to pins in Arduino using arrays?
I am trying to create a library called "LED" for LED Sequencer in Arduino IDE,where the user has to configure the LED pins using an array and pass it to  LED constructor in program and then will be able to use BlinkAll(),LeftToRight() and RightToLeft() Functions which lights the LED from Left to Right or Right to Left based on the sequence mentioned in the array. The problem is when I initiate the array and pass it to the constructor Pins 4,5,7 are not working at all , Please help me find what is the possible issue
the code in LED.cpp file is shown below
#include <Arduino.h>
#include "LED.h"

LED::LED(int channel, int* a){
  _channel = channel;
  for(int i = 0 ; i < channel; i ++)
  {
    _pins[i] = a[i] ;
    pinMode(_pins[i],OUTPUT);
  }
}
void LED :: BlinkAll(int delay_ms)
{
   for (int i = 0 ; i<_channel;i++)
   {
    digitalWrite(_pins[i],HIGH);
   }
   delay(delay_ms);
   for (int i = 0 ; i<_channel;i++)
   {
    digitalWrite(_pins[i],LOW);
   }
   delay(delay_ms);
}
void LED :: LeftToRight(int numberofLEDs, int delay_ms)
{
  for(int i =0 ;i<_channel; i++)
  {
    digitalWrite(_pins[i], LOW);
  }
  for(int i =0 ;i<_channel; i++)
  {
//    if (i > 0)
//    {
//     digitalWrite(_pins[i-1], LOW);
//    }
  for(int i =0 ;i<_channel; i++)
  {
    digitalWrite(_pins[i], LOW);
  }
    digitalWrite(_pins[i], HIGH);
    delay(delay_ms);
  }
}
void LED :: RightToLeft(int numberofLEDs,int delay_ms)
{
    for(int i =_channel ;i>0; i--)
  {
    digitalWrite(_pins[i], LOW);
  }
  for(int i = _channel ;i>0; i--)
  {
    if (i < _channel)
    {
     digitalWrite(_pins[i+1], LOW);
    }
    digitalWrite(_pins[i], HIGH);
    delay(delay_ms);
  }
}

LCD.h
#ifndef LED_h
#define LED_h

#include <Arduino.h>

class LED
{
public:
  LED(int channel, int* pins);
  void BlinkAll(int delay_ms);
  void LeftToRight(int numberofLEDs, int delay_ms);
  void RightToLeft(int numberofLEDs, int delay_ms);
  void BlinkAlternate(int delay_ms);
private:
  int _channel;
  int _pins[16];
};

#endif

Sample Code
#include "LED.h"

int const LED_pins[8]={5,6,7,8,9,10,11,12};
int const No_of_LED = 8;

LED led(8,LED_pins);

void setup()
{
  Serial.begin(9600);
}
void loop()
{
  led.LeftToRight(1,500);
  led.RightToLeft(1,500);
}

Please show us a full code. Meaning also the LED.h and a small test sketch, which uses your library and exhibits the problem.

Directly I think you have unballanced curly brackets in the LeftToRight() function and you use an array index out of bounds in the RightToLeft() function (by effectively doing _pins[_channel] though the greatest index should be _channel-1)

if you correct the indentation levels in your code, then you may be able to see the problem area yourself

pinMode shouldn’t be in the constructor.  You need a begin method that can be called from setup for that.  The constructor May get run before setup and before the hardware is ready for pinMode.

It seems in the LeftToRight method, you didn't comment out enough (or too much), because  you use a for loop inside another for loop which is probably unintended.
In the RightToLeft' method I will try to fix the problem, so you can change theLeftToRight` method similarly.
void LED :: RightToLeft(int numberofLEDs,int delay_ms)
{
  for(int i =_channel ;i>0; i--)
  {
    digitalWrite(_pins[i], LOW);
  }
  for(int i = _channel ;i>0; i--)
  {
    if (i < _channel)
    {
     digitalWrite(_pins[i+1], LOW);
    }
    digitalWrite(_pins[i], HIGH);
    delay(delay_ms);
  }
}

The first for loop is to switch off the LEDs, I would make this a separate method, so it can be reused in both the LeftToRight and RightToLeft method, so you get:
void LED::RightToLeft(int numberofLEDs, int delay_ms)
{
  switchAllLedsOff();

  for(int i = _channel; i > 0; i--)
  {
    if (i < _channel)
    {
     digitalWrite(_pins[i + 1], LOW);
    }
    digitalWrite(_pins[i], HIGH);
    delay(delay_ms);
  }
}

void LED::SwitchAllLedsOff()
{
  for(int i = _channel; i > 0; i--)
  {
    digitalWrite(_pins[i], LOW);
  }
}

The problem is also, that you always write HIGH to a pin, since it overwrite the possible LOW assignment within the if statement. To correct this you get:
void LED::RightToLeft(int numberofLEDs, int delay_ms)
{
  switchAllLedsOff();

  for(int i = _channel; i > 0; i--)
  {
    digitalWrite(_pins[i + 1], i >= _channel ? HIGH : LOW);
    delay(delay_ms);
  }
}

You also can use an if statement, but in this case the ternary (? :)  statement is more clear since the assignment is for a single destination (_pins[i + 1]). So in case i >= channel, it is set to HIGH, otherwise set to FALSE. I also inverted the operator, but you can keep it inverted too.
Third, _channel seems to be the number of elements in the array, if you use it in an index it should start with _channel - 1, so you get:
void LED::RightToLeft(int numberofLEDs, int delay_ms)
{
  switchAllLedsOff();

  for(int i = _channel - 1; i >= 0; i--)
  {
    digitalWrite(_pins[i + 1], i >= _channel - 1 ? HIGH : LOW);
    delay(delay_ms);
  }
}

There might be more problems, but the above are at lest some of them.
Also I changed your way of using spaces, although it's a matter of personal style, yours I never saw before (which doesn't mean it's incorrect of course).
(note I have not tested the program).

Thanks Mr.Michel Keijers. Will work on it and let you know

Mr.Michel I tried the RightToLeft() Code of yours but nothing is lit so I changed i>=_channel to i <= _Channel then it is lit but the LED keeps glowing without turning off like a bargraph instead of a LED scroll

I thought you wanted a graph, not a single LED, in that case you can remove the for loop and use set one pin only to high.

Thats usefull, Thanks Mr.Michel Keijzers. But I also figured out some hardware loose connections which made the led in 5th pin not glow . Still I can't figure out why 6th pin is not glowing. other than that It works .

Check if the wire is good, by measuring it with a multi meter, or replace the led, and the wire ( so 4 combinations), until you find out if at least the component and the wire is ok.

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


text:
Using ModbusRTU.h, what would cause holding registers all read 0?
I'm working with a 32-Input Modbus RTU module using RS485. I'm trying to read/poll the inputs to check for ON(1) states.  I have tested this module with Arduino UNO, Radzio! Modbus Master simulator, and Modbus Poll -- all worked as expected, (displaying 0=off, 1=on). Using an Arduino Nano with a TTL to RS485 Module like this.
So using the below code, the output is all 0s regardless of input state.  It compiles and runs without errors.
#include <ModbusRtu.h>
#include <SoftwareSerial.h>

// data array for modbus network sharing
uint16_t au16data[32];
uint8_t u8state;

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

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

unsigned long u32wait;

SoftwareSerial mySerial(2, 3);//Create a SoftwareSerial object

void setup() {
  Serial.begin(9600);
  master.begin( &mySerial, 9600 ); // begin ModBus object 9600baud
  master.setTimeOut( 2000 ); // if no answer in 2000 ms, roll over
  u32wait = millis() + 1000;
  u8state = 0;
}

void loop() {
  switch( u8state ) {
  case 0:
    if (millis() > u32wait) u8state++; // wait state
    break;
  case 1:
    telegram.u8id = 1; // slave address
    telegram.u8fct = 3; // function code (this one is registers read)
    telegram.u16RegAdd = 128;// start address in slave 0x0080-0x009F(128-159)
    telegram.u16CoilsNo = 32; // number of elements to read  0x00 0x01
    telegram.au16reg = au16data; // pointer memory array in Arduino

    master.query( telegram ); // send query (only once)
    u8state++;
    break;
  case 2:
    master.poll(); // check incoming messages
    if (master.getState() == COM_IDLE) {
      u8state = 0;
      u32wait = millis() + 2000;
        Serial.println(au16data[0]);//Or do something else!
        Serial.println(au16data[1]);//Or do something else!
        Serial.println(au16data[2]);//Or do something else!
        Serial.println(au16data[3]);//Or do something else!
        Serial.println(au16data[4]);//Or do something else!
        Serial.println(au16data[5]);//Or do something else!
        Serial.println(au16data[6]);//Or do something else!
        Serial.println(au16data[7]);//Or do something else!
        Serial.println(au16data[8]);//Or do something else!
        Serial.println(au16data[9]);//Or do something else!
        Serial.println(au16data[10]);//Or do something else!
        Serial.println(au16data[11]);//Or do something else!
        Serial.println(au16data[12]);//Or do something else!
        Serial.println(au16data[13]);//Or do something else!
        Serial.println(au16data[14]);//Or do something else!
        Serial.println(au16data[15]);//Or do something else!
        Serial.println(au16data[16]);//Or do something else!
        Serial.println(au16data[17]);//Or do something else!
        Serial.println(au16data[18]);//Or do something else!
        Serial.println(au16data[19]);//Or do something else!
        Serial.println(au16data[20]);//Or do something else!
        Serial.println(au16data[21]);//Or do something else!
        Serial.println(au16data[22]);//Or do something else!
        Serial.println(au16data[23]);//Or do something else!
        Serial.println(au16data[24]);//Or do something else!
        Serial.println(au16data[25]);//Or do something else!
        Serial.println(au16data[26]);//Or do something else!
        Serial.println(au16data[27]);//Or do something else!
        Serial.println(au16data[28]);//Or do something else!
        Serial.println(au16data[29]);//Or do something else!
        Serial.println(au16data[30]);//Or do something else!
        Serial.println(au16data[31]);//Or do something else!
    }
    break;
  }
}

Could this be caused by the 'Number of elements" to read?
Any suggestions greatly appreciated.
This is the 32-input module manual
and programming guide
Code is based on this example.

Your code would be more readable with proper indentation. Can you clarify what you mean with "never displayed"? What is actually displayed? Is the actual amount of received bytes correct?

What is actually displayed is a 0, not a 1 when the input is ON.

If you change your code completely, you should added it as an UPDATE than total replace your original code.

What RS485/Modbus interface board you have? other than the Pin2 for RX, and P3 for TX, How do you wire the RE(Receiver Enable) and DE(Driver Enable) pins?

"Code courtesy of: [He who shall not be named]"  No, what that guy does is leech off these sites with an automatic video generation system. Real credit goes to (or more to) one of the authors here of an ESE Q&A.

I am using this RS485 interface board: https://m.media-amazon.com/images/W/IMAGERENDERING_521856-T2/images/I/61JTdn25ryL.AC_SL1500.jpg
I apologize for the code replace and didn't know about an Update.  I've been fussed at before for posting a second too similar of a question.

I think the library somehow changed the API for creating an instance of master and deprecated the master.begin() in favour of master.start().

I found a working solution here: https://www.youtube.com/watch?v=zTanigwP5ow (see link to his blog-bottom) that was very simple using the same two libraries.


text:
Error while uploading code with Arduino on breadboard using FTDI 232
My circuit is as seen and I hope there is no error with the wiring. I'm using an ATmega328P. The error suggests that the programmer is not responding and ten attempts issuing not in sync code. There isn't any bootloader issue as pin 13 LED flickers as soon as I plug in USB cable. I have selected the following board specification in the Arduino IDE:

Board: Arduino Uno
Programmer: Arduino as ISP

Schematics I followed:

ATmega pinout reference:

Connections:

Pin 1: 10k resistor to 5V, 0.1uF capacitor pin series with DTR of FTDI
Pin 2: Tx of FTDI
Pin 3: Rx of FTDI
Pins 9 & 10: 16 MHz oscillator and 22pf capacitor in series
Pins 7, 20, 21: 5v
Pins 8, 22: ground
Pin 19: status LED (similar to pin 13 LED on standard Arduino Uno)

I used both ways of uploading (directly and upload using programmer) and nothing worked. The bootloader in the chip is that of the Arduino Uno and it was burned using another Uno board. SPI programming using another Uno board works fine. I tried different combination of programmer in IDE but futile. The capacitor for reset is 0.1 µf and it seems that connections are fine as there was no issue with uploading using another Uno board as ISP.I would love if anyone can help me out with this.
Related images are:

PS:
[Post comment changes]
-I added a 47uF and 0.1uF caps for cleaner supply to the chip based on suggestions in comment section.

board with changes[by pass capacitors ,resistor visible on pin 19]
[]5
IDE specifics

Solution-

credits- @Nickgammon
had problem with bootloader which was initially uploaded . later solved it by following instructions from NickGammon Forum -
http://www.gammon.com.au/breadboard

related images-

snap shot from bootloading window in arduino IDE

Comments are not for extended discussion; this conversation has been moved to chat.

Here is a photo of the setup I used on this page about a breadboard Arduino. I can't see any material differences between yours and mine, except that I wouldn't connect Aref (pin 21) to anything.

Close-up of the FTDI connection:

I have 0.1 µF capacitors as decoupling capacitors on both sides of the breadboard.

I used both ways of uploading (directly and upload using programmer) and nothing worked.

Assuming you have the Uno bootloader installed (and that the fuses are still set to what they should be for a Uno) then you want direct uploading (with board type set to Uno), not uploading via a programmer.

I have a 47uF and 0.1 uF as decouplers. I'll see if removing AREF will help. I believe there isn't any issue with bootloader as i could program it using an actual arduino board as ISP and program runs effectively.

If you program using and Arduino as ISP then you are doing SPI programming, so that doesn't prove much. It also will remove any existing bootloader. The flashes you see on the LED might just be the blink sketch.

If you run run my board detector sketch it will confirm whether or not there is a bootloader there.

I realize the flaw in my point regarding bootloader, I'll check through "board detector sketch".By flickering i mean,rapid flashes and also the same when i hit upload button during FTDI serial programming method,but error crops up at the end.It seems like chip is communicating and resetting the board but still cannot upload


text:
How to set up one second interrupt/ISR for ds3231 RTC
I am able to set up one hz interrupts using millis and other timers, but would like to do it instead using the RTC I have attached (DS3231)
I am not sure how I can do that.  Can someone point me to a reference for this?
EDIT/UPDATE
I tried to use the square wave to trigger a call back/interrupt, but it's not working for me.  I followed what I thought was the wiring diagram here and
here and here
I also added a led in the circuit to see if I could figure out something that way, but no dice.
Here is some simple code for a sketch that I think should trigger a 1 second interrupt and call my function:
#include <DS3232RTC.h>    //http://github.com/JChristensen/DS3232RTC
#include <Time.h>         //http://www.arduino.cc/playground/Code/Time
#include <Wire.h>         //http://arduino.cc/en/Reference/Wire (included with Arduino IDE)

const int rtcTimerIntPin = 2;
bool flag = false;

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

    bool stopped = gRTC.oscStopped();
    if (stopped)
    {
        Serial.println("Detected clock power loss - resetting RTC date");
        time_t newTime = cvt_date(__DATE__, __TIME__);
        adjustTime(newTime);
        setTime(newTime);
    }
    else {
        Serial.println("Clock did not lose power");
    }

    pinMode(13, OUTPUT);    // onboard LED
    pinMode(rtcTimerIntPin, INPUT);
    attachInterrupt(rtcTimerIntPin, rtc_interrupt, RISING);
    gRTC.squareWave(SQWAVE_1_HZ);

    digitalClockDisplay();
}

void rtc_interrupt(void)
{
    flag = true;
}

void loop(void)
{
    //digitalClockDisplay();

    if (flag) {
        digitalWrite(LED_BUILTIN, HIGH);    // flash the led
        digitalClockDisplay();              // this just prints time to serial port
        delay(500);                         // wait a little bit
        digitalWrite(LED_BUILTIN, LOW);     // turn off led
        flag =  false;                      // clear the flag until timer sets it again
    }
}

void digitalClockDisplay()
{
// do something
}

What sort of precision are you looking for? The interrupt (once you get that working) should fire within a few microseconds of when the clock actually generates the signal. Are you looking for microseconds, or milliseconds? What is the purpose of this? If you are just flashing an LED very high precision is probably not required.

And if you just want to flash an LED every second, connect it to the clock output directly! (via a resistor). :P

I want to have a signal so that I do some check/processing every second.  For this project tens of milliseconds is fine.  It is for a timer to do time lapse photography.

This answer addresses the original question of why the interrupts didn't work. I happened to have a DS3231 lying around so I made up a test.

Interrupt vs pin number
First, this is wrong in your code:

attachInterrupt(rtcTimerIntPin, rtc_interrupt, RISING);

You need an interrupt number, not a pin number. This is correct:
  attachInterrupt (digitalPinToInterrupt (rtcTimerIntPin), rtc_interrupt, CHANGE);

I also made it a CHANGE interrupt so you get both the rising and falling pulse.

Pull-up resistor
Next, the 1 Hz output needs a pull-up resistor, so you should add that or make it INPUT_PULLUP like this:
  pinMode (rtcTimerIntPin, INPUT_PULLUP);

Testing
I used this library from Adafruit.
Adapting one of their examples, and putting in your interrupt code (with my modifications), it worked!
#include <Wire.h>
#include "RTClib.h"

RTC_DS3231 rtc;

const byte rtcTimerIntPin = 2;

volatile byte flag = false;

void rtc_interrupt ()
{
  flag = true;
}  // end of rtc_interrupt

void setup () {

  Serial.begin(115200);

  while (!Serial); // for Leonardo/Micro/Zero

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

  if (rtc.lostPower()) {
    Serial.println("RTC lost power, lets set the time!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }

  // enable the 1 Hz output
  rtc.writeSqwPinMode (DS3231_SquareWave1Hz);

  // set up to handle interrupt from 1 Hz pin
  pinMode (LED_BUILTIN, OUTPUT);
  pinMode (rtcTimerIntPin, INPUT_PULLUP);
  attachInterrupt (digitalPinToInterrupt (rtcTimerIntPin), rtc_interrupt, CHANGE);
}

void loop () {
  if (flag) {
    digitalWrite(LED_BUILTIN, HIGH);    // flash the led
    delay(100);                         // wait a little bit
    digitalWrite(LED_BUILTIN, LOW);     // turn off led
    flag =  false;                      // clear the flag until timer sets it again
  }
}

I was missing two things:
I used INPUT rather than INPUT_PULLUP and I did not have the digitalPinToInterrupt() in the first param for attachInterrupt()
thanks!

I tried to use the square wave to trigger a call back/interrupt, but it's not working for me.

 bool flag = false;
 ...
 void rtc_interrupt(void)
 {
     flag = true;
 }

Flags set in interrupts should be declared volatile otherwise the compiler may optimize away the comparison to the flag. That is:
volatile bool flag = false;

If you are using the Adafruit library (from the page you linked to) then it should have a couple of functions that can be used to detect when the second has changed, for example:
DateTime now = rtc.now();
int second = now.second();
unsigned long unixtime = now.unixtime();

In either case you just have to check if either one has changed in loop. For example:
void loop(void)
{
  static unsigned long previousTime = 0;
  DateTime now = rtc.now();
  unsigned long timeNow = now.unixtime();

  if (timeNow != previousTime) {
      digitalWrite(LED_BUILTIN, HIGH);    // flash the led
      digitalClockDisplay();              // this just prints time to serial port
      delay(500);                         // wait a little bit
      digitalWrite(LED_BUILTIN, LOW);     // turn off led
      previousTime = timeNow;             // remember previous time
    }
}

thanks @nick  - I fixed the volatile bit.  Note that I want a callback/trigger/squarewave - not to delay()/check the time each iteration of the loop.

Does it work once you added volatile? The delay was from your own code. The delay is not part of working out if the second is up. I don't see a huge difference between checking the time from the clock, as you go around loop and checking a flag, each time you go around loop. Reading the time from the clock might take slightly longer, I suppose.

Volatile didn't fix the desired method of having an ISR triggered by a square wave, but I changed the loop() code to look like what you suggested.  That works.  Thanks for the help.  It's going to bother me about the interrupt though...

Try the following code. It pretty much detects a change in time and when a change has been detected, it will do something. In this case, it will print "do something".
#include <DS3231.h>
DS3231 rtc(SDA, SCL);
String t; //time as a string
String s;    //second
String Ps;   //previous second

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

void loop() {
  t = rtc.getTimeStr();             //finding time
  s = t.substring(6, 8);            //finding seconds

  if(s != Ps)                       //if the time has changed
  {
    Serial.println("do something"); //put whatever you want here
    Ps = t.substring(6, 8);         //redeclaring the previous second because it has advanced
  }
}

I advise against using the String class for something done every time around loop. String uses dynamic memory allocation, and if you aren't careful you will get heap fragmentation. To calculate seconds just use the "modulus" operator (ie. time mod 60).

I don't think it is possible because the DS3231 libray that I have only returns strings.

Can you give a link to the library please? You should be able to get something other than Strings.

http://www.RinkyDinkElectronics.com/  Your the pro so see if you can find anything. Even I would like for it to be able to return ints

Well for one thing the prototype is char *getTimeStr(uint8_t format=FORMAT_LONG); which means you get back a char * not a String. You can use char * without needing dynamic memory allocation. Also there is a function long getUnixTime(Time t); which gives you a long. AFAIK Unix Time is in seconds, so just call that and take modulus 60 of the result.

Where did I get 60 from? Assuming Unix time changes every second, then you just need to compare if the time changes.

Use this DS3231 library. It has a method to set the squarewave RTC.squareWave(SQWAVE_1_HZ)

Thanks Gerben - I will try to set up the squarewave to an input/interrupt.  No success yet.

You could temporarily add an led, to see if you are getting any signal.

Yep, I tried that - and no luck there.  In fact, I used two different 3231 'boards' to see if it was my wiring/soldering.  It may very well be that I wrecked two boards, but it seems more likely I am doing something else wrong.  I will try to post a stripped down version of what i am doing.

You should add a little more detail.


text:
Getting an error while uploading a code to the Arduino when ethernet shield is attached
I bought ethernet Shield today and connected it to Arduino Uno, now when I try to upldoad I get the following error, however if I remove the shield from the UNO it works fine.
Sketch uses 10,486 bytes (32%) of program storage space. Maximum is 32,256 bytes.
Global variables use 661 bytes (32%) of dynamic memory, leaving 1,387 bytes for local variables. Maximum is 2,048 bytes.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

Is it something wrong with he ethernet shield ?
Ethernet is not plugged in but even when i plug in the ethernet wire the indicators at Jack does not lit up

Unplug your ethernet shield. Then upload your program. Plug in your ethernet shield  and check if your program is working fine. If your program is not working as expected, there may be some issues with the shield.

I have tried that already it didn't helped

What was not working. Your program was not working or you were getting errors uploading code.?

Error uploading code when shield is plugged in

Upload the code and then plug in your shield. Then check if your uploaded code is working correct or not.?

I have tried that already , then nothing comes in serial monitor tried all baud rate

If you are sure enough that all the connections and your code is correct, that means your shield is not working.

I learned yesterday late night that it's duminloev shield while I have UNO R3

I fixed the problem by cleaning the soldering near the SD card slot on ISCP, see image below.


text:
Serial communication between PC and Arduino via RS232 using C++
I am trying to communicate with my Arduino Duemilanove via an RS232 cord. I simply want to be able to send a byte (or char) to my Arduino from a desktop application.  The Arduino is plugging into USB COM5 on my computer.  I have the RS232 plugged into COM1, and then I have pins 2, 3 and 5 on the other end of the RS232 connected to Arduino pins TX, RX, and GND, respectively.
I found a serial comm class for C++ at the following link: Arduino and C++ (for Windows)
I have added the .h and .cpp files from the above example as Serial.h and Serial.cpp (I think the example uses SerialClass.h and SerialClass.cpp, I just changes the names).

On my Arduino, I have the following code running:
// ARDUINO
char incomingByte = 0;

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

void loop() {

        // send data only when you receive data:
        if (Serial.available() > 0) {
                // read the incoming byte:
                incomingByte = Serial.read();

                // say what you got:
                Serial.print("I received: ");
                Serial.println(incomingByte, HEX);
        }
}

And my C++ program is the following:
// C++
#include <iostream>
#include <Windows.h>
#include "Serial.h"

using namespace std;

int main(void)
{
    Serial port("COM1");

    char* msg = "Hello Arduino!";
    int msgLen = strlen(msg);
    bool writeSuccess = port.WriteData(msg, msgLen);

    cout << "\n\n";
    system("PAUSE");
}

When I use the Arduino's serial port viewer to see what is bring printed, I'm getting very strange values that don't match what I'm sending (as far as I can tell).
When I send "Hello Arduino!", the arduino prints the following:
I received: FFFFFFAB
I received: 3A
I received: 3A
I received: A
I received: FFFFFFFA
I received: FFFFFFEB
I received: 6D
I received: 37
I received: 15
I received: 2D
I received: 23
I received: 21
I received: FFFFFFBD
I received: 0

This does not appear to be the correct hex for "Hello Arduino!", but I have no idea why it's not correct.  Does anyone have any clue what I'm doing wrong?

You cannot connect RS232 cable pins directly to microcontroller pins for two reasons.  First, the excessive voltage will likely destroy the inputs.  Second, the signals must be inverted in sense when moving between RS232 standards and logic level signals used by the ATMEGA's UART.  You need a level translator, or to replace the true serial connection with a logic-level USB-serial one.  Is there a reason you can't use the Arduino's existing USB serial interface?

Additionally the "FFFFFFFA" most likely comes from sign exstension when a mistakenly-signed byte value is implicitly converted to a larger int type. Declare your variable unsigned char instead.

@ChrisStratton The only problem with working with the existing USB serial interface is I cannot figure out how to send data through USB using C++.  It was trivial to learn how to send data through RS232, but I can't find any info on doing it through USB.  Additionally, wouldn't there be a conflict if I tried to have one program writing COM5 while the Arduino's terminal was viewing COM5?

The existing USB interface emulates a serial port, so you would use the exact same serial APIs, and simply a different port name (whichever one you use for downloading sketches).  Also make sure to close the Arduino serial monitor before you try talking to it from your program.

You don't send it through USB, you send it through the virtual COM port.

@ChrisStratton i didn't realize that...well thanks! That did exactly what I was hoping!

It because that in your c++ application you haven't explicitly mentioned serial port speed.
Mention the same baudrate which you have used in arduino here(c++).
Assuming that you have used rs232 to ttl converter, as you are getting some output,
Which in other case wouldn't as you would have already burned your mcu.

You need some voltage converter between arduino and pc. PC uses "real" RS232 and arduino uses TTL level RS232. Check more in this site. You need something like this RS232 to TTL.


text:
How to pass a filename to a function? What type of variable is the filename?
In the example below, I have two functions that write numbers to two different files on an SD card. I'm using the SdFat library.
Is there any way I can combine the two functions into one, so that I can call (for example): writeToFile(int t, FileName "filename1.txt");?
In the example below, to write a value to the "temperature.txt" file, I would like to be able to call: writeToFile(7, "temperature.txt"); In my sketch I have about a dozen functions that are writing to a dozen different files, so it would be very handy to be able to combine them into one function.
I think the main part I'm stuck on is I have no idea what the filename variable would be, or how to pass the filename to the function.
#include <SdFat.h>
SdFat sd;

void setup() {
  if (!sd.begin(chipSelect, SPI_HALF_SPEED)) {
    sd.initErrorHalt();
  }

  setTemperature(7);
  setFanSpeed(4);
}

void setTemperature(int t) {
  SdFile rdfile("temperature.txt", O_WRITE);
  rdfile.rewind();
  rdfile.println(t);
  rdfile.close();
}

void setFanSpeed(int t) {
  SdFile rdfile("fanspeed.txt", O_WRITE);
  rdfile.rewind();
  rdfile.println(t);
  rdfile.close();
}

String literals are of type const char *. Ordinary char *s can be passed to it though; the const means that the compiler will make sure that the function doesn't attempt to change the contents.
void setFileParameter(const char *filename, int value)
{
   ...
}

Thanks! It worked! I had assumed I'd be able to do the next part on my own, but ran into a smaller problem. I have another function to read the parameter from a file, so for example: readFileParameter(const char *filename, int value). I would like to call: readFileParameter("temperature.txt", currentTemp);, and have it store the value from the file into the integer currentTemp. What would I have to use instead of "int value", in order for it to change a global variable (like currentTemp)? I'm sorry that this is probably very basic stuff that I'm missing.

I think I might've figured out my 2nd problem on my own. It seems to be working if I declare the function like this: void readFile(const char *filename, int &value). I guess the '&' causes it to modify the variable that is passed to it? It's a little too complex for my current understanding, but so far it seems to work. It would be nice if anyone points out if it's incorrect. :)

@Jerry: That's the correct way to do it in C++. https://en.wikipedia.org/wiki/Reference_%28C%2B%2B%29


text:
Arduino + HM-10/11 + ANCS to get notifications for iPhone
I am wondering if there are any current solution to receive notifications on iPhone through ANCS and HM-10/11 Bluetooth LE module. An Arduino library?
https://stackoverflow.com/questions/28488529/is-it-possible-to-use-hm-10-or-hm-11-ble-module-with-arduino-to-communicate-with/30625967#30625967
One of the answer of this question talked about a number of AT commands that can be used to configure the HM-10/11 to use the ANCS. But the part receiving and getting the notification details seems to be quite complicated. In addition, it should also require an iOS app to establish the connection according to the note below 1.5.
There seemed to be no information online about this even though the manufacturer confirmed with me they do provide support for ANCS for this module.
Are there anyone working on this with an Arduino? Could you please share more about this?
Or are there anyone who can help develop this library together?

I don't see anything about needing an app. Try searching for ANCS CC2541


text:
Extend program space by getting rid of bootloader on NANO
I just have a complex program that runs on a NANO. Now when I use my printlns for debugging I am running out of memory.
I read about using a programmer to get rid of the bootloader that uses 2K space on a NANO. I bought an USBTinyIsp and got it to work successfully... almost I can program the nano as I wanted, but I do not get any additional space.
When programming with debug printlns I run into the same message as before which states the same maximum space within (I guess it was 30700).
Why is this the case? I thought the bootloader gets overridden when using a programmer and so frees 2K of programmable space.
Please note: I am not asking how to optimize my program code! Thank you for taking notice ;)
Thank you very much.

the 'New bootloader' has only 0.5 kB, but arduino didn't change nano.menu.cpu.atmega328.upload.maximum_size

When I get in space crunch I will do the code on a mega then when it is debugged shrink it to the nano. Not a perfect answer but a workable one.

It's enforcing this line from the arduino:avr boards.txt
nano.menu.cpu.atmega328.upload.maximum_size=30720

To be clear, the board is assumed to have a bootloader, even if you're not using it to get the code onto the board, that is upload via programmer.
You could edit that and change some fuses yourself.  But you could also probably just use MCUdude MiniCore, choosing an option that does not use a bootloader, e.g. ATmega328P with No bootloader, which gives you maximum upload of 32768:
328.menu.bootloader.no_bootloader.upload.maximum_size=32768

Keep in mind that in either case you'll have needed to set the fuses for not having a bootloader.  As weird as this sounds, choosing the No Bootloader option in MCUdude MiniCore for the ATmega328P, and then doing Burn Bootloader sets these fuses for you, despite the name not actually burning a bootloader in this case.  If you were to edit the maximum upload size for the Nano board, you would need to manually set the fuses similarly to what Burn "Bootloader" does for the MiniCore ATMega328P with No-bootlader option.

Thank you very much! Just tried your first point which worked like a charm! Saved me a lot of time, I owe you a beer!

Additional information: As i had a reinstall of my System, I also had to reconfigure my boards.txt. I stumbled over this blog, which is explaining the fuses quite well: http://www.martyncurrey.com/arduino-atmega-328p-fuse-settings/

I would make a point of reading the datasheet rather than that.  For one thing it says "I imagine RSTDISBL is implemented for security reasons to stop the chip being reprogrammed or the firmware being downloaded".  No, not really, there other features for that.  RSTDISBL exists mostly to allow that pin to function as normal GPIO.  Anyway, read the datasheet for more accurate descriptions.


text:
Arduino UNO - analogRead() returning mixed results
I have created a small circuit with a 220 Ohm resistor and a LED connected to PIN9 for power.
I want to measure the Voltage of the current flowing through the circuit. In order to do that I connected a bridge from between the resistor and the LED to the A3 PIN and used this code:
int ledPin=9;
int inPin=A3;
long int in=0;
float V_in=0;
int val;

void setup() {
  analogReference(DEFAULT);
  pinMode(ledPin, OUTPUT);
  pinMode(inPin, INPUT);
  Serial.begin(9600);
  }

  void loop() {
    if (Serial.available() > 0) {
      val = Serial.parseInt();

      if (val>=0 && val<=155) {
        analogWrite(ledPin, val);
        //Serial.println(val);

        for (int i=0; i<10; i++) {
          val+=5;
          analogWrite(ledPin, val);
          //Serial.println(val);

          delay(1000);
          in = analogRead(inPin);
          V_in=float(5.0)*(float(in)/float(1023));
          Serial.println(V_in);
          delay(1000);
          }

        }
        else {
          Serial.println("Dio è morto.");
          }
      }
    }

The problem is that when I run it, with an Input of 55, I get what seams to be a random arrangement of 0s and 2.56s. While I expect a increasing sequence of numbers between 0 and 2.5.
What am I doing wrong?
I measured the Voltage on the A3 Pin using a voltimeter, and it increases every step by 0.2, exactly as expected.
This is an output example:

That's to be expected. The analogWrite function doesn't output an analog voltage. It can only output 5V or 0V, nothing in between. It's called PWM.

It's strange your observation seams to make sense if considering the output data. The officiial Arduino documentation states that the return value for this function is an int(0 to 1023). Why should it return either 0 or 5V? https://www.arduino.cc/reference/en/language/functions/analog-io/analogread/

Note that @tttapa is referring to analogWrite, not analogRead.

It returns either 0v or Vf of the LED since that is where you have it connected.

@EdgarBonet The LED is being driven with analogWrite, so the signal being sampled is PWM.

Also, "Measure the voltage of the current flowing through..." makes no sense whatsoever.

The analogWrite function, despite its name, outputs PWM (pulse width modulation) which is either fully on or fully off, with varying duty cycles. If you run that through a RC network (eg. 4.7k in series and 10 µF to ground), it will smooth out the pulses and you will actually get a varying voltage.
So in your case you are measuring on or off depending on the timing. However since you are measuring between the resistor and the LED, you won't get 5V because of the voltage drop over the resistor. An LED, depending on the colour, might have a voltage drop of around 2.2V, and thus you might expect 2.8V at that junction. This is approximately what you got.

I want to measure the Voltage of the current ...

This doesn't make any sense electrically. You are either measuring the voltage (in volts) or the current (in amps). You don't measure the "voltage of the current". I suppose you mean "the voltage at that point".

Reference
Arduino functions reference:
Reference > Language > Functions > Analog io > Analogwrite

Measuring the voltage of the current does make sense if you measure the voltage across a known, fixed resistor. You can then use Ohm's law to determine the current through that resistor (and through the LED).

Thank you for the grat and detailed answer. I am quite new to arduino, but this answer clarified the doubts I had