text:
Blinking LEDs in sequence with a class
I am trying to make a program that accepts four digit password using a 3*4 keypad.
The program should start with flashing LED1 and when password 1 is entered it switches this LED and blinks LED2. If password 2 is entered it switches to LED3 and so on.
Here is the code:
#include <Keypad.h>
#include <TimedBlink.h>

#define Password_Length 5

TimedBlink led1(14);
TimedBlink led2(15);
TimedBlink led3(16);
TimedBlink led4(17);

const unsigned long PERIOD1 = 1000;
char  buffers[4][4] = {{'1', '2', '3', '4'}, {'6', '5', '4', '3'}, {'9', '8', '7', '6'}, {'1', '2', '5', '6'}}; // this is how to initialise a 2d array
unsigned long previousMillis[5]; //[x] = number of leds
char Data[Password_Length]; // 6 is the number of chars it can hold + the null char = 7

byte data_count = 0;
bool Pass_is_good;
char customKey;

const byte ROWS = 4;
const byte COLS = 3;
char keys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins[ROWS] = {2, 3, 4, 5}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {6, 7, 8}; //connect to the column pinouts of the keypad
int ledservos[4] = {14, 15, 16, 17};
Keypad customKeypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS); //initialize an instance of class NewKeypad

void setup() {
  pinMode(14, OUTPUT);
  pinMode(15, OUTPUT);
  pinMode(16, OUTPUT);
  pinMode(17, OUTPUT);
  led1.blink(150, 50); // On for 150ms, off for 50ms
  led2.blink(150, 50);
  led3.blink(150, 50); // On for 150ms, off for 50ms
  led4.blink(150, 50);
  Serial.begin(9600);
  Serial.print("Enter Password");
  Serial.println();
}

void loop() {
  led1.blink();
  led2.blink();
  led3.blink();
  led4.blink();
  customKey = customKeypad.getKey();
  if (customKey) {
  // makes sure a key is actually pressed, equal to (customKey != NO_KEY)
    Data[data_count] = customKey; // store char into data array
    data_count++; // increment data array by 1 to store new char, also keep track of the number of chars entered
  }
  if (data_count == Password_Length - 1) {
    // if the array index is equal to the number of expected chars, compare data to master
    Serial.print("Password is ");
    for (byte i = 0; i < Password_Length; i++)
      Serial.print(Data[i]);
    for (x = 0; x < 4; x++) { //this loop for number of passwords in the array
      for (y = 0; y < 4; y ++) { //this loop for number of characters in each of the password array
        if (strcmp(Data[y], buffers[x][y]) != 0) {
          break;
        }
      }
      if (y == 4) {
        break;
      }
    }
    if (x < 4) {
      Serial.print(" Found at index ");
      Serial.println(x);
      switch (x) {
        case 0:
          led1.blinkOff();
          break;
        case 1:
          led2.blinkOff();
          break;
        case 2:
          led3.blinkOff();
          break;
        case 3:
          led4.blinkOff();
          break;
      }
    }
    clearData();
  }
}

void clearData() {
  Serial.println();
  while (data_count != 0) {
    // This can be used for any array size,
    Data[data_count--] = 0; //clear array for new data
  }
}

void BlinkLed (int led, int interval, int arry) {
  //(long) can be omitted if you dont plan to blink led for very long time I think
  if (((long)millis() - previousMillis[arry]) >= interval) {
    previousMillis[arry] = millis(); //stores the millis value in the selected array
    digitalWrite(led, !digitalRead(led)); //changes led state
  }
}

Now I can make the program, but all LEDs start blinking and switch off after the password is entered and I got stuck at this point.
Here is a link to the TimedBlink Library.
I have tried the millis() function to be used to blink LEDs in the next code:
#include <Keypad.h>
#include <Wire.h>

#define buzzer 13
#define greenled 20
#define redled 21
#define Password_Length 5

unsigned long previousMillisLED14 = 0;
unsigned long previousMillisLED15 = 0;
unsigned long previousMillisLED16 = 0;
unsigned long previousMillisLED17 = 0;
// different intervals for each LED
int intervalLED14 = 500;
int intervalLED15 = 600;
int intervalLED16 = 700;
int intervalLED17 = 800;
// each LED gets a state varaible
boolean LED14state = false;     // the LED will turn ON in the first iteration of loop()
boolean LED15state = false;     // need to seed the light to be OFF
boolean LED16state = false;     // need to seed the light to be OFF
boolean LED17state = false;     // need to seed the light to be OFF
const unsigned long PERIOD1 = 1000;
char  buffers[4][4] = {{'1', '2', '3', '4'}, {'6', '5', '4', '3'}, {'9', '8', '7', '6'}, {'1', '2', '5', '6'}}; // this is how to initialise a 2d array
unsigned long previousMillis[5]; //[x] = number of leds
byte i, x, y;
char Data[Password_Length]; // 6 is the number of chars it can hold + the null char = 7
byte data_count = 0;
bool Pass_is_good;
char customKey;
const byte ROWS = 4;
const byte COLS = 3;
char keys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};
byte rowPins[ROWS] = {2, 3, 4, 5}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {6, 7, 8}; //connect to the column pinouts of the keypad
int ledservos[4] = {14, 15, 16, 17};
Keypad customKeypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS); //initialize an instance of class NewKeypad

void setup() {
  pinMode(14, OUTPUT);
  pinMode(15, OUTPUT);
  pinMode(16, OUTPUT);
  pinMode(17, OUTPUT);
  Serial.begin(9600);
  pinMode(buzzer, OUTPUT);
  pinMode(redled, OUTPUT);
  pinMode(greenled, OUTPUT);
  Serial.print("Enter Password");
  Serial.println();
}

void loop() {
  unsigned long currentMillis = millis();
  if ((unsigned long)(currentMillis - previousMillisLED14) >= intervalLED14) {
    LED14state = !LED14state;
    digitalWrite(14, LED14state);
    // save current time to pin 12's previousMillis
    previousMillisLED14 = currentMillis;
  }
  customKey = customKeypad.getKey();
  if (customKey) {
    // makes sure a key is actually pressed, equal to (customKey != NO_KEY)
    Data[data_count] = customKey; // store char into data array
    data_count++; // increment data array by 1 to store new char, also keep track of the number of chars entered
  }
  if (data_count == Password_Length - 1) {
    // if the array index is equal to the number of expected chars, compare data to master
    Serial.print("Password is ");
    for (byte i = 0; i < Password_Length; i++)
      Serial.print(Data[i]);
    for (x = 0; x < 4; x++) {
      //this loop for number of passwords in the array
      for (y = 0; y < 4; y ++) {
        //this loop for number of characters in each of the password array
        if (strcmp(Data[y], buffers[x][y]) != 0) {
          break;
        }
      }
      if (y == 4) {
        break;
      }
    }
    if (x < 4) {
      Serial.print(" Found at index ");
      Serial.println(x);
      switch (x) {
        case 0:
          digitalWrite(14, LOW);
          digitalWrite(16, LOW);
          digitalWrite(17, LOW);
          if ((unsigned long)(currentMillis - previousMillisLED15) >= intervalLED15) {
            LED15state = !LED15state;
            digitalWrite(15, LED15state);
            // save current time to pin 12's previousMillis
            previousMillisLED15 = currentMillis;
          }
          break;
        case 1:
          digitalWrite(15, LOW);
          digitalWrite(14, LOW);
          digitalWrite(17, LOW);
          if ((unsigned long)(currentMillis - previousMillisLED16) >= intervalLED16) {
            LED16state = !LED16state;
            digitalWrite(16, LED15state);
            // save current time to pin 12's previousMillis
            previousMillisLED16 = currentMillis;
          }
          break;
        case 2:
          digitalWrite(15, LOW);
          digitalWrite(14, LOW);
          digitalWrite(16, LOW);
          if ((unsigned long)(currentMillis - previousMillisLED17) >= intervalLED17) {
            LED17state = !LED17state;
            digitalWrite(17, LED17state);
            // save current time to pin 12's previousMillis
            previousMillisLED17 = currentMillis;
          }
          break;
        case 3:
          digitalWrite(15, LOW);
          digitalWrite(14, LOW);
          digitalWrite(16, LOW);
          digitalWrite(17, LOW);
          break;
      }
    }
    clearData();
  }
}

void clearData() {
  Serial.println();
  while (data_count != 0) {
    // This can be used for any array size,
    Data[data_count--] = 0; //clear array for new data
  }
}

But it blinks the first LED only, then each of the following LEDs according to the condition got permanent on.
I have tried the solution that Adafruit suggested, to use a class in code but unfortunately I got the same result as the previous code.
Here is the code:
#include <Keypad.h>
#include <Wire.h>

class Flasher {
    // Class Member Variables
    // These are initialized at startup
    int ledPin;      // the number of the LED pin
    long OnTime;     // milliseconds of on-time
    long OffTime;    // milliseconds of off-time
    // These maintain the current state
    int ledState;                 // ledState used to set the LED
    unsigned long previousMillis;   // will store last time LED was updated
    // Constructor - creates a Flasher
    // and initializes the member variables and state
  public:
    Flasher(int pin, long on, long off) {
      ledPin = pin;
      pinMode(ledPin, OUTPUT);
      OnTime = on;
      OffTime = off;
      ledState = LOW;
      previousMillis = 0;
    }
    void Update() {
      // check to see if it's time to change the state of the LED
      unsigned long currentMillis = millis();
      if ((ledState == HIGH) && (currentMillis - previousMillis >= OnTime)) {
        ledState = LOW;  // Turn it off
        previousMillis = currentMillis;  // Remember the time
        digitalWrite(ledPin, ledState);  // Update the actual LED
      } else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime)) {
        ledState = HIGH;  // turn it on
        previousMillis = currentMillis;   // Remember the time
        digitalWrite(ledPin, ledState);   // Update the actual LED
      }
    }
};

Flasher led1(14, 100, 400);
Flasher led2(15, 350, 350);
Flasher led3(16, 100, 400);
Flasher led4(17, 350, 350);

#define buzzer 13
#define greenled 20
#define redled 21
#define Password_Length 5

char  buffers[4][4] = {{'1', '2', '3', '4'}, {'6', '5', '4', '3'}, {'9', '8', '7', '6'}, {'1', '2', '5', '6'}}; // this is how to initialise a 2d array
unsigned long previousMillis[5]; //[x] = number of leds
byte i, x, y;
char Data[Password_Length]; // 6 is the number of chars it can hold + the null char = 7

byte data_count = 0;
bool Pass_is_good;
char customKey;
const byte ROWS = 4;
const byte COLS = 3;
char keys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};
byte rowPins[ROWS] = {2, 3, 4, 5}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {6, 7, 8}; //connect to the column pinouts of the keypad
int ledservos[4] = {14, 15, 16, 17};
Keypad customKeypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS); //initialize an instance of class NewKeypad

void setup() {
  Serial.begin(9600);
  pinMode(buzzer, OUTPUT);
  pinMode(redled, OUTPUT);
  pinMode(greenled, OUTPUT);
  Serial.print("Enter Password");
  Serial.println();
}

void loop() {
  led1.Update();
  customKey = customKeypad.getKey();
  if (customKey) {
    // makes sure a key is actually pressed, equal to (customKey != NO_KEY)
    Data[data_count] = customKey; // store char into data array
    data_count++; // increment data array by 1 to store new char, also keep track of the number of chars entered
  }
  if (data_count == Password_Length - 1) {
    // if the array index is equal to the number of expected chars, compare data to master
    Serial.print("Password is ");
    for (byte i = 0; i < Password_Length; i++)
      Serial.print(Data[i]);
    for (x = 0; x < 4; x++) {
      //this loop for number of passwords in the array
      for (y = 0; y < 4; y ++) {
        //this loop for number of characters in each of the password array
        if (strcmp(Data[y], buffers[x][y]) != 0) {
          break;
        }
      }
      if (y == 4) {
        break;
      }
    }
    if (x < 4) {
      Serial.print(" Found at index ");
      Serial.println(x);
      switch (x) {
        case 0:
          led2.Update();
          digitalWrite(14, LOW);
          digitalWrite(16, LOW);
          digitalWrite(17, LOW);
          break;
        case 1:
          led3.Update();
          digitalWrite(15, LOW);
          digitalWrite(14, LOW);
          digitalWrite(17, LOW);
          break;
        case 2:
          led4.Update();
          digitalWrite(15, LOW);
          digitalWrite(14, LOW);
          digitalWrite(16, LOW);
          break;
        case 3:
          digitalWrite(15, LOW);
          digitalWrite(14, LOW);
          digitalWrite(16, LOW);
          digitalWrite(17, LOW);
          break;
      }
    }
    clearData();
  }
}

void clearData() {
  Serial.println();
  while (data_count != 0) {
    // This can be used for any array size,
    Data[data_count--] = 0; //clear array for new data
  }
}

Any idea why is this happening?

why don't you try to determine  why all the LEDs start flashing when the program starts

actually ia m trying to get help cz totally stuck after this step

look at the first command in the loop() block .....  think about its function

dear i understand what u r meaning,but when i tried to put led.blink function in the switch cases i did not get any reults ,though they r supposed to work there

Put a link to the TimedBlink library you are using In your question, not in a reply to an answer. You need to provide enough information for the people reading your question to be able to understand your problem.

EDIT
Now that you added a link to the TimedBlink library I was able to go look at it. That is not a very well written library, and its documentation is horrible.
It seems that blink(int,int) starts a TimedBlink LED blinking, and blinkOff stops it. So you should not call LEDx.blink(150,50) on any of your LEDs until you want them to start blinking.
You need to refactor your code to only call LEDx.blink(150,50) on one LED at a time. You probably want your switch statement to call LEDx.blink(150,50) on the LED that you want to blink and ledOff() on the others.

thank u 4 ur reply,
this is the link for the timed blink
link,
i have tried the suggested way in  ur answer but it did not work ,the leds remain off

See the edit to my answer. You need to edit your question and provide the link to the library in the question, not buried in a comment to my answer. Other people reading this thread will want the same information and they should not have to hunt for it. When you are getting ready to post a question, stop and think: “What information will the readers of my question need in order to understand my question? Have I provided everything?”

i have tried that but unfortunately no result


text:
Looking for a cheap small arduino ish board
I'm looking for a cheap and small bluetooth board for a project.
I found this one, but I find this one too expensive, are there cheaper alternatives, in similar size?
Thank you!

An ESP32 module?

preferably an all in one, for the project I currently use a wemos d1 mini, which works fine, but wifi isn't the best way of controlling it. that's why I'm looking into bluetooth

And that's why I suggested ESP32.

Oh sorry, I was confused by something else, this was indeed what I was looking for, thank you!

I guessed you'd confused it with the ESP8266, which is WiFi only. The ESP32 is WiFi and BLE combined in one chip.

I'd suggest investigating the ESP32.
It's not only a far more powerful chip than any normal Arduino, but it has both WiFI and Bluetooth Low Energy, all on the one chip.
It's available as surface mount modules, similar to the ESP8266, and there are a number of small development boards that have been created around it as well.

source: Stack Exchange

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

sort: votes


text:
What is /dev/tty.usbserial-1420
I'm a complete newbie with Arduino. I've bought a couple of Nano clones from China. According to supplier description, it is Arduino Nano V3.0 ATMEGA328P ATMEGA328 CH340. Not sure why they list both 328 and 328P, but my struggle is to make it work anyway: IDE doesn't see it.
Power LED is on, L-LED is blinking regularly.
After some online reading, I conclude that the root cause may be in the USB-serial chip. My question is: if, when connecting this device to my Mac, I see a /dev/tty.usbserial-1420 device appearing, does it mean that the USB-serial interface actually works correctly? Or does it not, and I should continue trying with installing some extra drivers etc.?
I am on Macbook Pro 2015, Mac OS 10.14.3. Many thanks in advance.
The error I am getting in IDE is:

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

Note: In a similar question the user didn't have the usbserial device in his /dev list.

Have you installed a CH340 driver for Mac OSX? https://arduino.stackexchange.com/a/17358/37523

The question was not how to solve the problem, but what is the device that I do see in /dev.

Also note that in the linked answer, the user didn't have the usbserial device. So presumably nothing at all was happening when connecting his Arduino. In my case, the usbserial device appears. So I don't see how this question is a duplicate.

What happens when you select /dev/tty.usbserial-1420 as your serial port in the IDE, then try to upload a sketch? Does it upload? If not, install the driver.

@VE7JRO, indeed, it didn't work, I installed the driver, it does work. That's why I am wondering what this device is.

These China clones are frequently shipped with no bootloader burned to the chip. There is a way to get it working but, you need a working Arduino or programmer to burn the bootloader. I have used an Arduino Uno to burn a bootloader on my nano. The Uno and nano were both purchased from the same seller, on the same order, from AliExpress. Here are the instructions that worked for me.
The instructions provide a link to download the Windows drivers so here’s a link to the macos drivers. CH341_MAC.ZIP (CH340 uses CH341 drivers)

This one does have the bootloader, and with the WCH driver, IDE works. I was only wondering what usbserial is, if it's not what is needed to "talk" to Arduino.

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


text:
How to execute operation once till a condition then restart it from start
I am making a project using IR sensor,servomotor and Push button.
I am not able write code for the logic as stated:
it will execute the operation when it reads the digital value of IR high and rotates the servomotor till a threshold and then rotates the servo reverse  on using push button.It will perform no actions till the push button is used altough IR sensor is reading value.Then it will again perform the same action after push button is used.

I am not able write code for the logic - so, you want someone to do it for you for free? Sounds fair

logic as stated .... you have not clearly stated the desired behavior

My suggestion is, even if it seems to be a simple example, to start with an analysis of what you really want to achieve. In this example I would try to start with an state diagramm. With this you could clarify simple questions, e.g. what happens if the IR goes low while the motor is turning. In my draft, the motor would keep running, but maybe the IR is for safety reason and you want to stop motor if something approaches. If that is your intention, you can easy add aditional transitions at all states to return to state 00.
Such an approach helps you in creating code easy to maintain and change to new requirements

After having your state diagramm finished it is often easy to start programming with switch/case sturctures for first learning experiences.
Switch(state) {
  case 00:
  // if IR set state = 10;
  break;
  case 10:
  // if button was pressed set state = 11
  break;
  case 11:
  // turn motor
  // if treshold set state = 12
  break;
.
.
.

}


text:
Possible to connect 3 MPU9250 to Node MCU without multiplixer?
Is the idea of connecting AD0 pins of MPU9250 is still valid like the 2nd answer of this question? - How to change i2c address for mpu9250?
I have connected 2 sensor as test. SCL & SDA of both parallel with D1 & D2 of node mcu. Then connected AD0 of both sensors to different I/O pin of node mcu but it didnt work. What could be the solution?
Code to control 1 sensor:- It worked when I set AD0 to high and changed address to 0x69
#include "MPU9250.h"

// an MPU9250 object with the MPU-9250 sensor on I2C bus 0 with address 0x68
MPU9250 IMU(Wire,0x68);
int status;

void setup() {
  // serial to display data
  Serial.begin(115200);
  while(!Serial) {}

  // start communication with IMU
  status = IMU.begin();
  if (status < 0) {
    Serial.println("IMU initialization unsuccessful");
    Serial.println("Check IMU wiring or try cycling power");
    Serial.print("Status: ");
    Serial.println(status);
    while(1) {}
  }
}

void loop() {
  // read the sensor
  IMU.readSensor();
  // display the data
  Serial.print(IMU.getAccelX_mss(),6);
  Serial.print("\t");
  Serial.print(IMU.getAccelY_mss(),6);
  Serial.print("\t");
  Serial.print(IMU.getAccelZ_mss(),6);
  Serial.print("\t");
  Serial.print(IMU.getGyroX_rads(),6);
  Serial.print("\t");
  Serial.print(IMU.getGyroY_rads(),6);
  Serial.print("\t");
  Serial.print(IMU.getGyroZ_rads(),6);
  Serial.print("\t");
  Serial.print(IMU.getMagX_uT(),6);
  Serial.print("\t");
  Serial.print(IMU.getMagY_uT(),6);
  Serial.print("\t");
  Serial.print(IMU.getMagZ_uT(),6);
  Serial.print("\t");
  Serial.println(IMU.getTemperature_C(),6);
  delay(100);
}

Code to control 2 sensors:-
#include "MPU9250.h"

// an MPU9250 object with the MPU-9250 sensor on I2C bus 0 with address 0x68
MPU9250 IMU1(Wire,0x68);
MPU9250 IMU2(Wire,0x68);

int status;

void setup() {
  // serial to display data
  Serial.begin(115200);
  pinMode(D7, OUTPUT);
  pinMode(D8, OUTPUT);

}

void IMU_1() {
  digitalWrite(D7, LOW);
  digitalWrite(D8, HIGH);
  IMU1.begin();
  IMU1.readSensor();
  Serial.print("IMU 1 is active: "); Serial.print(IMU1.getAccelX_mss(),6);
  digitalWrite(D8, LOW);
}

void IMU_2() {
  digitalWrite(D7, HIGH);
  digitalWrite(D8, LOW);
  IMU2.begin();
  IMU2.readSensor();
  Serial.println("IMU 2 is active: "); Serial.print(IMU2.getAccelX_mss(),6);
  digitalWrite(D7, LOW);
}

void loop() {

IMU_1();
IMU_2();

  delay(500);

}

Result:- It Shows reading on one sensor but the 2nd sensor shows '0' every time.
What's the best way to use 3 I2C sensors when there is only 1 I2C bus?

Possible duplicate of Control multiple MPU9250 to start collecting data at the same time

It sounds like the MPU9250 has a pin, AD0, that lets you switch the device between 2 fixed I2C addresses.
That gives you an easy solution if you need to use 2 of them.
For more, the post you linked suggests keeping them all at the same AD0 state except the one you want to talk to. You’d switch that one’s AD0 pin to the other state, which would cause it’s I2C address, and then talk to it at that address, which would be unique on the I2C bus.
That approach should work, but it’s a bit of a hack.
You say "I have connected 2 sensor as test. SCL & SDA of both parallel with D1 & D2 of node mcu. Then connected AD0 of both sensors to different I/O pin of node mcu but it didn't work." What didn't work? What happens? What output do you get What pins on your mcu are connected to AD0 on your 3 different MPU9250 modules? Where is the code that manipulates the digital pins to select one and only one of your MPU9250 modules for reading?
You need to throughly explain your setup, including the different pin assignments and how they are supposed to work. Don't leave us to read your code and try and figure out your intentions.
Looking at your code it looks like you're using D7 and D8 on your mcu to try to control which MPU9250 is active. However i don't see any code the sets D7 and D8 as outputs.
Why don’t you want to use an I2C address mapping chip? They are readily available, and the ones I’ve seen would let you address up to 8 I2C devices that are hard-wired with the same address.

thanks, have updated the code and errors :) . It doesn't work even when i updated the code. I want to change the address to 0x69 and see but my node mcu has some problem.

You likely need to set up 2 IMU devices, IMU1 and IMU2, both at address 0x68. Configure your D7 and D8 pins to put the first one at address 0X68, and issue the IMU1.begin() command. Then switch the pins so that the 2nd one is on address 0x68 and do IMU2.begin().

What about the above code? I updated it but it shoes reading of 2nd sensor as zero. Also I am worried about the power supply. Looks like node mcu can give 550mA max current while both IMU chip takes 740mA so could this problem be due to current shortage?

Yes, that is a problem. If a single IMU can draw more than the total output of your power supply you have a problem with just one IMU. I found some inexpensive 5V 2A related power supplies online. I am using them for my project. I suggest you do the same.

Thanks Duncan :)

One las thing, which method will get the imu data faster? Using above method or using multiplexer? (except for using node mcu on each sensor) Because I want to control robot arm in realtime using those sensors so need to extract data from IMU ASAP.

I doubt you'd be able to detect the difference in speed between the 2 methods. The software method adds a few instructions to manipulate pins before issuing I2C commands, so would introduce a few microseconds of additional delay. The impact of using the hardware multiplexer would depend on how much propagation delay the multiplexer adds to I2C commands being passed back and forth to the "downstream" devices. If you use it by first selecting one of it's multiplexed I2C devices, it probably routes messages with nanosecond delay, but you would have to run code to control the I2C multiplexer.


text:
HC-05 with ELM327 mini OBD2 Bluetooth adapter connection problem
I am using Arduino Uno and HC05 Zs-040 Bluetooth module to establish a connection with ELM327 mini OBDII Bluetooth adaptor.
I have tried more than 15 different sequences of AT commands and most of them works successfully and HC05 reply with "ok" with no errors.
When I switch off the power from the HC05 and reconnect it again to connect automatically to the MAC address stored in it during configuration, the HC05 connects to the ELM327 OBDII adaptor for a time interval ranges from 2 to 5 seconds then the connection is lost.
I was able to notice that from the LED blinking on the HC05. This process of connection and disconnection is repeated automatically and the LED on the HC05 blinks in different patterns.
Also, I was able to connect to the ELM327 OBDII adaptor using a python script and it connects to it (I did that at the same time when the HC05 was trying to connect to OBDII adaptor which confirms that the connection between HC05 and the adaptor was not established).
In addition, I was able to connect to ELM 327 adaptor using Torque application and Bluetooth terminal application and both work fine.
Can anyone help me figuring out why does the connection is lost as soon as it is established?

I faced a similar problem when working with HC-05 module with an Android terminal application and connection was lost after some time and many it was just not able to connect.
Upon some hit and trials I found that it was just an power issue with HC-05 and as soon as I tried it out by reducing load on HC-05 by connecting it alone on 5V supply from Arduino and switching others to a 3V supply it worked like butter and I didn't faced any problem till now.
This worked for me try this out.


text:
Arduino acts odd when disconnected from computer
I'm building an self-navigating robot with an arduino, an ultrasonic sensor, and two DC motors. I'm currently within the process of coding the robot but I've discovered I have an unusual problem; whenever I run the project via the USB cable operations run fine, however once I take the cable out and run the system on batteries alone performance diminishes.
I have checked the code thoroughly, however I don't understand how this could be an issue that's coding related. I also (as part of the testing) built a basic program which only operated the motors, and was able to run this via USB and via batteries alone with no difference in performance.
So what possible reasons could there be for a drop in performance? I have included a link to a youtube video I had taken of it earlier below to maybe give a better understanding of how performance diminishes:
https://youtu.be/Tp5LtOKBKHw
(Also it could be important to note if I take the cable out while motors are currently moving performance stays at where it should be)
Thanks!

Can you show us the sketch you are using? Are you using Serial to write to the serial monitor?

What are you using to power the board? Looking at the video, it looks like the motors are using more current than the batteries can supply, which causes the voltage to drop, which causes the arduino to reset (brown-out reset). You can see the following sequence in the video: Arduino turns on motor; voltage drops and Arduino resets (motors also turn off); Arduino bootloader does it's 3 second timeout; and the again start the motor, etc. etc. PS Starting a motor takes more current than when it's running. That is probably why unplugging the USB doesn't immediately reset the Arduino.

Ahhh I see, so that's why it's fine when it's running but it can't get started! A brownout makes a lot of sense, thanks. The motors are being powered by 4 AA batteries connected in series, these batteries also power the arduino so I might swap in a 9V battery for the arduino and see if that impacts it

Yeah, 6V is barely enough to power the Arduino voltage regulator. 7.5V or 9V would be better. If the voltage droops at all at 6V the Arduino’s regulator doesn’t have enough to work with. Using a separate 9V battery connected to the Arduino’s barrel connector would be a good idea.

The recommended minimum to the voltage regulator is 7V, so 6V is already lower than you want to go.

What seems is that you are facing an power shortage while working with on board power supply.
While running DC motors and Arduino on same battery set your Arduino is not getting enough power.
Try switching to a better power supply which can maintain a constant EMF, as eventually you'll always run out of power.
Try an adaptor to use wall socket current.
This way you'll not lose any functionality of Arduino project.


text:
Blinking LED's at changing rate
I am trying to blink two LED's, starting at slow rate then increasing to fast s follows: 1 on, 1&2 on, 2 on, 1&2 on, 1 on, etc. The blinks go through the loop twice then speed up and repeat until both are on continuously. Then I want LED's 3 & 4 to come on.
I got the 1 & 2 LED's to blink as I want but anything I put following my for / if loop goes into the loop.
This works for blinking the 1 & 2 LED's:
int led1 = 9;
int led2 = 10;
int led3 = 11;
int led4 = 12;
int delay1 = 700;
int delayAmount1 = delay1 / 10;

void setup() {

pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(led4, OUTPUT);
}

void loop() {{
delay1 = delay1 - delayAmount1;

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

if (delay1 > 10)

digitalWrite(led1, HIGH); //yellow on (yellow)

delay(delay1);

digitalWrite(led2, HIGH); //red and yellow on (orange)

delay(delay1);

digitalWrite(led1, LOW); //yellow off (red)

delay(delay1);

digitalWrite(led1, HIGH); //yellow on (orange)

delay(delay1);

digitalWrite(led2, LOW); //red off (yellow)

digitalWrite (led1, LOW); //yellow off (all off)

}
}

// digitalWrite(led3, HIGH); //blue on

//delay(1000);

//digitalWrite(led4, HIGH); //green on

}

If I remove the // from
// digitalWrite(led3, HIGH); //blue on
//delay(1000);
//digitalWrite(led4, HIGH); //green on

they become part of the loop. Can someone tell me what I am doing wrong? Kind of new to this.

check the line if (delay1 > 10)

The if(delay1>10) does not have the conditional code in {}, so it should look like
if(delay1>10) {
//conditional code, what happens if statement == true
}

And if I understood your project and code correctly, when delay1 <= 10 then you want the led3 and led4 to light up. So you want to add an optional else{} block. This optional block will be skipped, if the if statement is executed. If the if statement is not executed, because for example your delay1 is smaller or equal to 10, then the else block will be executed.
else{
//led3 and led4 light up
}

You have a number of code formatting problems, some aesthetic, and some structural.
You need to indent your code, and you need to use braces. If you don't format your code well you will have a very hard time figuring out what you are doing.
Here is an attempt to clean up your code:
void loop() {
delay1 = delay1 - delayAmount1;

for (int i=0 ; i <2 ; i++) {
    if (delay1 > 10) {
        digitalWrite(led1, HIGH); //yellow on (yellow)
        delay(delay1);
        digitalWrite(led2, HIGH); //red and yellow on (orange)
        delay(delay1);
        digitalWrite(led1, LOW); //yellow off (red)
        delay(delay1);
        digitalWrite(led1, HIGH); //yellow on (orange)
        delay(delay1);
        digitalWrite(led2, LOW); //red off (yellow)
        digitalWrite (led1, LOW); //yellow off (all off)
    }
}
// digitalWrite(led3, HIGH); //blue on
//delay(1000);
//digitalWrite(led4, HIGH); //green on

}
(I'm not sure what's supposed to be inside the if statement or not since you didn't have an opening brace.)
You also had 2 opening braces on your loop statement, which is very odd.
Note that using delay() to try to control more than one thing at a time is a bad idea. The delay() function causes your program to freeze everything until the delay is over. If you try to blink different LEDs at different rates, you can't. If you try to detect button presses while you are also blinking LEDs, you miss the button presses while your code is in a delay. There are lots of threads on the various Arduino boards on how to avoid using delay. Search on "Arduino blink no delay" to find the basics.


text:
Can't push data to ThingSpeak - Status 400 Bad Request
I'm trying to push some data to ThingSpeak using the EtherCard library with the ENC28J60 ethernet module.
At the moment I'm using the exemple code that comes with the library just for tests. But no matter what I do, always receive the same reply:
REPLY recieved....
HTTP/1.1 400 Bad Request
Date: Sat, 09 Mar 2019 17:26:52 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: close
Status: 400 Bad Request
X-Frame-Options: SAMEORIGIN
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS, DELETE, PATCH
Access-Control-Allow-Headers: origin, content-type, X-Requested-With
Access-Control-Max-Age: 1800
Cache-Control: no-cache
Set-Cookie: request_method=POST; path=/
X-Request-Id: 9184d325-402d-4512-a942-e7

Code:
#include <EtherCard.h>

// Simple demo for feeding some random data to Pachube.
// 2011-07-08 <jc@wippler.nl>
//
// License: GPLv2

// Handle returning code and reset ethernet module if needed
// 2013-10-22 hneiraf@gmail.com

// Modifing so that it works on my setup for www.thingspeak.com.
// Arduino pro-mini 5V/16MHz, ETH modul on SPI with CS on pin 10.
// Also added a few changes found on various forums. Do not know what the
// res variable is for, tweaked it so it works faster for my application
// 2015-11-09 dani.lomajhenic@gmail.com

// change these settings to match your own setup
//#define FEED "000"
#define APIKEY "XXXXXXXXXXXX" // put your key here

// ethernet interface mac address, must be unique on the LAN
static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x32 };
const char website[] PROGMEM = "api.thingspeak.com";
byte Ethernet::buffer[700];
uint32_t timer;
Stash stash;
byte session;

//timing variable
int res = 100; // was 0

void setup () {
  Serial.begin(9600);
  Serial.println("\n[ThingSpeak example]");

  //Initialize Ethernet
  initialize_ethernet();
}

void loop () {
  //if correct answer is not received then re-initialize ethernet module
  if (res > 220){
    initialize_ethernet();
  }

  res = res + 1;

  ether.packetLoop(ether.packetReceive());

  //200 res = 10 seconds (50ms each res)
  if (res == 200) {

    //Generate random info
    float demo = random(0,500);
    //word one = random(0,500);
    //String msje;

//    if (demo < 250){
//      msje = "low";
//    }
//    else{
//      msje = "high";
//    }

    // generate two fake values as payload - by using a separate stash,
    // we can determine the size of the generated message ahead of time
    // field1=(Field 1 Data)&field2=(Field 2 Data)&field3=(Field 3 Data)&field4=(Field 4 Data)&field5=(Field 5 Data)&field6=(Field 6 Data)&field7=(Field 7 Data)&field8=(Field 8 Data)&lat=(Latitude in Decimal Degrees)&long=(Longitude in Decimal Degrees)&elevation=(Elevation in meters)&status=(140 Character Message)
    byte sd = stash.create();
    stash.print("&field1=");
    stash.println(demo);
    //stash.print("&field2=");
    //stash.print(one);
    //stash.print("&field3=");
    //stash.print(msje);
    stash.save();

    //Display data to be sent
    Serial.println(demo);

    // generate the header with payload - note that the stash size is used,
    // and that a "stash descriptor" is passed in as argument using "$H"
    Stash::prepare(PSTR("POST /update HTTP/1.1" "\r\n"
      "Host: $F" "\r\n"
      "Connection: close" "\r\n"
      "X-THINGSPEAKAPIKEY: $F" "\r\n"
      "Content-Type: application/x-www-form-urlencoded" "\r\n"
      "Content-Length: $D" "\r\n"
      "\r\n"
      "$H"),
    website, PSTR(APIKEY), stash.size(), sd);

    // send the packet - this also releases all stash buffers once done
    session = ether.tcpSend();

 // added from: http://jeelabs.net/boards/7/topics/2241
 int freeCount = stash.freeCount();
    if (freeCount <= 3) {   Stash::initMap(56); }
  }

   const char* reply = ether.tcpReply(session);

   if (reply != 0) {
     res = 0;
     Serial.println(F(" >>>REPLY recieved...."));
     Serial.println(reply);
   }
   delay(300);
}

void initialize_ethernet(void){
  for(;;){ // keep trying until you succeed
    //Reinitialize ethernet module
    //pinMode(5, OUTPUT);  // do notknow what this is for, i ve got something elso on pin5
    //Serial.println("Reseting Ethernet...");
    //digitalWrite(5, LOW);
    //delay(1000);
    //digitalWrite(5, HIGH);
    //delay(500);

    // Change 'SS' to your Slave Select pin, if you arn't using the default pin
    if (ether.begin(sizeof Ethernet::buffer, mymac, SS) == 0){
      Serial.println( "Failed to access Ethernet controller");
      continue;
    }

    if (!ether.dhcpSetup()){
      Serial.println("DHCP failed");
      continue;
    }

    ether.printIp("IP:  ", ether.myip);
    ether.printIp("GW:  ", ether.gwip);
    ether.printIp("DNS: ", ether.dnsip);

    if (!ether.dnsLookup(website))
      Serial.println("DNS failed");

    ether.printIp("SRV: ", ether.hisip);

    //reset init value
    res = 180;
    break;
  }
}

I searched the site and saw that the Bad Request is related to syntax error.
Any attempt I made was in this part of the code, almost every change I tried was on the first line:
Stash::prepare(PSTR("POST /update HTTP/1.1" "\r\n"
      "Host: $F" "\r\n"
      "Connection: close" "\r\n"
      "X-THINGSPEAKAPIKEY: $F" "\r\n"
      "Content-Type: application/x-www-form-urlencoded" "\r\n"
      "Content-Length: $D" "\r\n"
      "\r\n"
      "$H"),
    website, PSTR(APIKEY), stash.size(), sd);

I think that is the part responsible for the URL syntax.
I tried to change the POST for GET, to put all the URL on the first line, something like: "POST https://$F/update?api_key=$F HTTP/1.1"(that one I saw on StackOverflow).
But I don't have any more idea where is the problem.
To confirm that the channel is OK I tried to send data directly via URL, and everything is OK.
URL Exemple:
https://api.thingspeak.com/update?api_key=XXXXXXXXXXXXX&field1=0

I don't know what to do to get it work. Thanks for your help!

Please add info/link to the library and the example. Also high-light any changes you might have done.

If your GET request https://api.thingspeak.com/update?api_key=XXXXXXXXXXXXX&field1=0 works, but the POST request is not, the only thing that could be incorrect is your payload sent by POST request. that is, the value of sd. If you print it out, what do you see?

Generates a float like 307.0. I tested the URL with this value and worked. I tested the URL manually, just put the URL on the browser. When i changed on the code to GET doesn't worked too


text:
GPS led not blinking and wrong LAT Long values
I want to extract the latitude and longitude values of my location but my gps led is not blinking. Also result appearing on the serial monitor is wrong.
This is my Arduino code:
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

SoftwareSerial gpsSerial(3, 4);
TinyGPSPlus gps;
float latitude,longitude;
void setup() {
  // put your setup code here, to run once:
  gpsSerial.begin(9600);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
while(gpsSerial.available())
  {
    int data=gpsSerial.read();
    if(gps.encode(data))
       {
          latitude = (gps.location.lat());
          longitude = (gps.location.lng());
          Serial.print("Latitude");
          Serial.println(latitude);
          Serial.print("Longitude ");
          Serial.println(longitude);
       }
   }
}

Please tell me what is wrong in the code?

The first thing you are doing wrong is not indenting your code. That makes anything else that's wrong with your code all but impossible to figure out.

Sounds like you're not getting a lock on the satellites. You do know that it can take a LONG time to get your first lock, don't you? And also that GPS doesn't work well indoors - unless you have a high gain antenna, or lots of open windows around you.

if you are going to say something like my gps led is not blinking, then you also need to explain what that means

at a guess, if the GPS led should be blinking but it isn't, then the second problem of wrong position is irrelevant, since, if GPS isn't working, how do you expect correct GPS data

There could be multiple problems here. Firstly, try doing near an open Window. GPS signals need LOS. Then, check your connections. If these are good, then what is the variable type you have initialized for Lat and Long? Are they long or long double? Start over from an example like this


text:
Serial read multiple digits and always reading 10 at the end?
So I'm trying to make a program that allows you to enter a number in decimal and it displays it in binary, and it's going fairly well after some initial struggles (for some reason it read integers as 48 more than they are (5 read as 53)) but there's something I still don't understand, and I'm scared that it may be a hardware issue.
For some reason, I can't display two-digit numbers. For example, if I input 12, it displays 1, and THEN it displays 2. Also, to make things worse, it ALWAYS outputs 10 after I input ANY number. For example, if I input 5, it displays 5, and then ALWAYS 10.
    void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);

}

void loop() {
  // put your main code here, to run repeatedly:
  int number;
  if (Serial.available() > 0) {

    number = Serial.read();
    Serial.print("Number to display: ");
    Serial.println(number);

    if (number <= 15){
      int LEDPin = 2;
      digitalWrite(2, LOW);
      digitalWrite(3, LOW);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
        for (int n = 0; n <= 4; n++){
          int binval = bitRead(number, n);
          Serial.println(binval);
          digitalWrite(LEDPin, binval);
          LEDPin++;
      }
    }
    else{
    Serial.println("Number must be less than 16!");
    }

    delay(1000);
  }
}

EDIT: And of course, after asking the question I re-ran the code and its AGAIN showing ints as 48 bigger than they are (5 as 53).
At this point, I'm extremely confused. Am I doing something wrong? Is this a hardware issue? What can I do?

It's called ASCII, and yes, '5' is the same as 53.

Possible duplicate of Why am I always getting 48 with serial communication?

I would suggest getting the user input with Serial.readBytesUntil(), store it in a char array, then use itoa() to get the integer value. Here is a modified version of your sketch.
char inputBuffer[5];
byte number = 0;

void setup() {
  Serial.begin(9600);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
}

void loop() {

  if (Serial.available() > 0) {

    Serial.readBytesUntil('\n', inputBuffer, 4);
    number = atoi(inputBuffer);
    Serial.print("Number to display: ");
    Serial.println(inputBuffer);

    if (number <= 15){
      int LEDPin = 2;
      digitalWrite(2, LOW);
      digitalWrite(3, LOW);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
        for (int n = 0; n <= 4; n++){
          int binval = bitRead(number, n);
          Serial.println(binval);
          digitalWrite(LEDPin, binval);
          LEDPin++;
      }
    }
    else{
      Serial.println("Number must be less than 16!");
    }
    delay(1000);
  }
}

or use parseInt()

Using parseInt() will produce the same result as readBytesUntil() with the input buffer and atoi(). Changing the OP's sketch to useparseInt() will be 2 lines less code, but will cost you and extra 98 bytes compile size. One of the benefits of using parseInt() would be the ease at which you can parse a comma separated list of integers from the serial monitor. If the OP plans on doing anything more complicated than entering one integer, then parseInt() is the way to go. Thank you for your comment Juraj.

for some reason it read integers as 48 more than they are (5 read as 53)

That's because you're not entering numbers, you're entering ASCII characters that represent numbers.
Everything you see on a computer or similar device is not really what is there. It is all translated into a form that we mere humans can see.  Every number is translated into readable characters, and readable characters have to be converted into numbers.
For example, the number 165 is the characters 1 (49), 6 (54) and 5(53).  When you enter that number you are sending those three individual characters.
You see the entire ASCII table here.
Another effect of sending individual characters is that you also send a marker to say "This is the end of the line". That can either be character 13 (Carriage Return), character 10 (Line Feed), or a combination of the two.  You can select which is sent in the Serial Monitor.
You should really use that line ending character or combination of characters to work out how many characters there are in your number so you can convert them into a proper integer value.
Some further reading:

Reading Serial on the Arduino (my blog)
The atoi() function

Regarding your "it ALWAYS outputs 10 after I input ANY number", I had the same problem using ASCII, and I think I finally figured it out. When you use Serial.println anywhere, it will output a line feed. In ASCII that is called newline and its value is 10. I have not yet figured a way to get around that.

byte ASCII_Number;

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

void loop() {
  Serial.println("Enter any single ASCII character:");
  while (Serial.available()==0) {}
  char ASCII_Character = Serial.read();
  ASCII_Number = (int)ASCII_Character;
  Serial.print("For your ASCII Character: ");
  Serial.print(ASCII_Character);
  Serial.print(" the ASCII Number is: [");
  Serial.print(ASCII_Number);
  Serial.println("] "); // print line always generates ASCII 10 (newline).
  //This runs the loop again with a newline for the character.
  delay (5000);
  ASCII_Number = 0;
}

As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

The original question is about getting LF on input. 2. Serial.println() outputs both a CR (13) and LF (10).


text:
RadioHead and Servo compile problems
I am having this problem when trying to compile my sketch. I am using RF frequency modules to send data between devices and a servo motor to control the tilt of a ramp. I understand that both libraries use TIMER 1 but I am unsure how to change one of them to use TIMER 2 thanks.
Arduino: 1.8.7 (Windows 10), Board: "Arduino/Genuino Uno"

libraries\Servo\avr\Servo.cpp.o (symbol from plugin): In function `ServoCount':

(.text+0x0): multiple definition of `__vector_11'

libraries\RadioHead\RH_ASK.cpp.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Arduino/Genuino Uno.
Board at COM4 is not available

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

You can force the RadioHead library to use Timer 2 instead. This can be done by enabling the define RH_ASK_ARDUINO_USE_TIMER2 near the top of RH_ASK.cpp.
More details about how to do this may be found in the RadioHead library documentation. Please see https://www.airspayce.com/mikem/arduino/RadioHead/classRH__ASK.html.
Cheers!


text:
Higher precision logarithms
I need to produce a log to base 10 with at least 4 decimal places. However, the log10 inbuilt function is giving the output with only two decimal places. What do I do? Is there a different function or a library that I can use?

How are you displaying the values? The number of decimal places you are seeing is probably a byproduct of the way you are converting them to strings, not of the underlying math. Most Arudino math is done with the float type, which should have about 6 or 7 decimal digits of precision.

I was just using a Serial.print without specifying any precision. This works, thanks

You should be able to get 6 or 7 decimal places out of the Arudino float type. Try using Serial.print for floats with a number of decimal places. Something like this:
float x = log10(3.141592658);
Serial.print(x, 6);


text:
Connecting DAC output from Arduino Due to another arduino
I have an Arduino Due and I want to connect the output from the DAC as an input to an Arduino Uno's analog input pin. From this link http://forum.arduino.cc/index.php?topic=164763.0, user DuaneB suggested that a resistor should be used in series with the DAC output to prevent an excessive flow of current that could damage the pin. But he was talking about this when the question was about powering a motor using the current generated from the DAC's voltage.
However, is this series resistor required when simply connecting the output of the pin to the input of another pin? I haven't seen any issue when connecting the output of my Raspberry Pi's GPIO to an arduino's input.

The inputs to Arduino pins are CMOS inputs, and present very high impedance.  (There is a tiny capacitor on every CMOS input, and the only current into the input is the very small amount needed to charge that capacitor.)
You don't need resistors when connecting inputs and outputs (digital or analog) between Arduinos. Should be the same with Raspberry Pi GPIO lines, or any other CMOS devices.

Do you mean the gate-channel capacitor in the MOSFETs or something totally different?

I’m not an electrical engineer, and don’t remember the specifics. Google CMOS and read up on it. CMOS inputs present very high impedance to DC, and only require a tiny flow of current to switch states.


text:
nRF24L01+ Unable to set address
I'm trying to communicate between Arduino Nano and Arduino Uno using nRF24L01+.
I tried using RF24 by ManiacBug and TMRH20, but when I open the serial monitor after uploading the Example Programs Getting Started from ManiacBug and pingpair Program from TMRH20, it does not change its address.
The addresses for reading and writing I'm using are 0xF0F0F0F0E1LL and 0xF0F0F0F0D2LL, but the response I'm receiving is as follows:

I check all the connection and tried different examples available on the internet, but nothing worked at all.

You can set addresses using SPI commands.  For example a 5-byte transmitter address could be written as (MSB first):
  digitalWrite(CSN_pin, LOW);
  SPI.transfer(0x30); // write TX_ADDR register
  SPI.transfer(tx_addr[0]);
  SPI.transfer(tx_addr[1]);
  SPI.transfer(tx_addr[2]);
  SPI.transfer(tx_addr[3]);
  SPI.transfer(tx_addr[4]);
  digitalWrite(CSN_pin, HIGH);

where tx_addr is an array of 5 bytes.  Similarly you can write to the RX_ADDR registers, see the nRF24L01+ datasheet, section 9 for the register map.
Furthermore, the following code allows you to read the TX_ADDR register:
  digitalWrite(CSN_pin, LOW);
  SPI.transfer(0x10); // read TX_ADDR register
  data_out[0] = SPI.transfer(0x0);
  data_out[1] = SPI.transfer(0x0);
  data_out[2] = SPI.transfer(0x0);
  data_out[3] = SPI.transfer(0x0);
  data_out[4] = SPI.transfer(0x0);
  digitalWrite(CSN_pin, HIGH);

  Serial.print("TX_ADDR=");
  Serial.print(data_out[0]);
  Serial.print(data_out[1]);
  Serial.print(data_out[2]);
  Serial.print(data_out[3]);
  Serial.println(data_out[4]);

@MichaeIT I tried this solution, but no luck. I've gone through  https://github.com/nRF24/RF24/issues/211 thread, but still no luck.

Try writing and reading, as suggested in the above example.  If this does not work, then there is some problem with the SPI.

I tried this, and getting the response 00000. SPI of arduino is problem or nRF? As I tried different nRF and Arduino.

@MichaeIT I am successful in making it work on Arduino Uno by connecting MISO, MOSI and SCK pins directly to the ICSP header pins, but not successful in Arduino Nano.


text:
I want to reset a variable after each 1 second on an Arduino
I want to reset this counter variable which I created after each 1 second, but I don't want to disturb the if statement.
Here is the code:
int button=A0;
int val;
int count=0;
int presss;

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

void loop() {
  val=analogRead(button);
  if(val>1000){
   presss=count++;
   delay(200);
 }
  Serial.println(presss);
  delay(1000);
 }

I would do it the following way:

Use a variable declared as: unsigned long time_passed;
In the setup() section I would add the line time_passed = millis();
In the loop() section I would add the if condition:

if(millis()-time_passed > 1000) {
   time_passed = millis();
   presss = 0;
   }
I think this is still not working properly with your example, I recommend to make two changes in your code:

you have a delay of 1000 implemented, which means the cycle time of your loop is minimum 1000ms,that means you are never able to count more than 1, since your counter is resetted every loop
I cannot understand how presss = count++; should work. For proper counting I would suggest to do it this way: presss = presss + 1;
Note: max. value of your counter would be 5, since the delay in the if Statement will enable maximum 5 detections of your button within 1000ms

You could do something like this:
void loop() {
  for (int i = 0; i < 5; i++) {
    val = analogRead(button);
    if (val > 1000) count++;
    delay(200);
  }
  Serial.println(count);
  count = 0;
 }

This will sample the button five times and count the number of times the value is larger than 1000, with a 200 ms delay between each read. This give approx. 1 s.
But this might not be the logic you are looking for.
Cheers!

If I understood the project, you want to count how many button clicks you did in one second, so I've adjusted your code a little bit. If you don't want your program to do something after a certain amount of time, but don't want it to wait don't use delay(ms) use millis() instead (see https://www.arduino.cc/reference/en/language/functions/time/millis/ )
int button=A0;
int val;
int presss=0;

int millisBegin = 0;
int millisNow;
int millisBorder = 1000;

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

void loop()
{
  val=digitalRead(button);

  if(val==HIGH)
  {
    presss++;     //If the button is pressed it will count + 1

    while(val==HIGH)
    {
      val=digitalRead(button); //It will wait till you release the button here
    }
  }

  Serial.println(presss);

  millisNow = millis();

  if(millisNow-millisBegin >= millisBorder)
  {
    presss = 0;
    millisBegin = millisNow;
    Serial.println("~1 second passed");
  }
}

I checked it and it worked for me (I changed the if(val>1000) to if(val==HIGH), otherwise it might not always detect a button press


text:
L293D with arduino's 5V
I am trying to use L293D with relay to power a 12V DC motor. Can I use arduino's 5V to provide L293D inputs 4 and 8 such as in the drawing? Or do I need to use a separate source, e.g. a power module?

I have to ask... why the relay...?!

@Majenko I am following the guide https://www.elegoo.com/tutorial/Elegoo%20Super%20Starter%20Kit%20for%20UNO%20V1.0.2019.03.04.zip page 150. Say I wanted to power some other device, with AC current, I would need a relay anyway.

That "guide" seems completely pointless. Nothing more than a demonstration of what a relay is. Throw that whole thing away. You don't want to use a relay to control a DC motor, especially when you already have a motor driver chip, and the previous "guide" shows you how to use it. Why they included that relay thing in there is anyone's guess. Yes, if you wanted to control something AC, or very high voltage, then a relay would be used. You wouldn't use a motor driver to control it though - you'd just use a simple transistor.

it looks like that motor controller chip has separate logic level and motor power inputs.
VCC1, at pin 16, is a low current logic level power input. You should be able to drive that from the Arduino's power supply.
VCC2, at pin 8 is the motor power input. You should NOT drive that from your Arduino's power supply. You should have a separate power supply for that (+5V with enough current for all the motors you are powering - 600mA is the max that chip can drive for a single motor, so a 1A power supply for VCC2 would be fine.
It looks like you are feeding the Arduino's +5V line into VCC2. DON'T DO THAT.


text:
REST API on Industrial 101 (Yún family) lags, then crashes
I have tried to set up a very simple REST API on an Arduino Industrial 101 (which is, as far as I understand, equivalent to a Yún). The Arduino is hooked up to a temperature sensor, which value is returned over the REST interface. Everything works fine at first, but over the course of a day it starts taking longer and longer for the device to respond until it completely crashes and becomes unresponsive. (At that point it also doesn't respond to ping and ssh anymore.)
On the Arduino forum there are several threads reporting similar problems (e.g. this one) but they all seem to be at least a few years old and have been solved in the mean time. (The solution reported here, for instance, has already been incorporated in my Linino version.)
If I reset the ATMega the problem persists, but if I reboot the OS it is solved for a day, so I have reason to suspect something on the Linino side is not working properly. Any help would be much appreciated, although I realize this is quite an old board.
My sketch is basically a dumbed-down version of the Bridge example:
#include <Bridge.h>
#include <BridgeServer.h>
#include <BridgeClient.h>

BridgeServer server;

void setup() {
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
  Bridge.begin();
  digitalWrite(13, HIGH);

  server.listenOnLocalhost();
  server.begin();
}

void loop() {
  // Get clients coming from server
  BridgeClient client = server.accept();

  // There is a new client?
  if (client) {
    // Process request
    process(client);

    // Close connection and free resources.
    client.stop();
  }

  delay(50); // Poll every 50ms
}

void process(BridgeClient client) {
  // no matter what the command is, return value on A1 sampled 4096 times

  int pin = 1;
  float val = 0;
  for (int i = 0; i < 4096; i++){
    val += float(analogRead(pin))/4096.0;
  }
  client.println(val*5.0/1024.0, 5); //multiply by 5/1024 to get volts

}

I inspected the source code of the Bridge library. It is very simple.
There are no dynamic memory allocations. It uses String in client.connect(), but your sketch doesn't use it. You could print free memory in ATmega with MemoryFree library. But I am 99% percent sure it will show no memory leak.
There is no 'background' processing in the Bridge library as suggested by other answers. All commands and data are sent to the WRT on Atheros and wait for result or acknowledge. The WRT side of the Bridge library is coded in python.
The fact that the restart of the WRT is what helps to continue, confirms that the problem is on the python side of the Bridge.
Python on WRT is very far from Arduino knowledge base, so I doubt you will get a solution here.

It's a WiFi module so there is background processing to keep the TCP or just any connection up

@Zunzullaalagaty, the WiFi processing is done in the Atheros chip not in ATmega and input is checked only in library calls like available or read .

First of all you should try changing the delay(50);. Try using millis(); instead and see if the problem still persists.
int borderMillis = 50;
int startMillis = millis();

void loop()
{
  int nowMillis = millis();
  if(nowMillis >= borderMillis)
  {
    //ask for new client etc.

    startMillis = millis();
  }
}

If that doesn't help, try adding the yield(); method after the delay(50); / at the end of the loop. Sometimes the board just needs time to get the background duties finished, so this comes in handy.
My very last guess would be a memory leak. You could try to get the amount of heap you have left, and see if it continuously drops and won't get released. There are libraries that can help you to retrieve the amount of memory you've left.

I'll try this soon, but just to make sure I understand your millis() suggestion: the conditional that's used by the if, shouldn't that be (nowMillis - startMillis) >= borderMillis?

@Julius for me it always worked without the brackets. But if that doesn't work for you, go ahead

I wasn't concerned so much about the brackets, it just seems to me that if you define nowMillis as millis() on every iteration it will almost always be larger than 50, and so the if will almost always evaluate to true.

@Julius I assume yield() didn't help?

I tried, but the Scheduler library is not available for my board.


text:
How to write a more compact ANDed conditions with if statement?
I'm working on the rfid module and found an example that do it well. But it has a long testing the 5 bytes of the rfid received bytes, and I've tried to write it in a more compact way.
I did it with a for loop, but how to AND the conditions of the if statement?
How to change this:
if(bt0[cnt-1] == rfid.serNum[0] &&
   bt1[cnt-1] == rfid.serNum[1] &&
   bt2[cnt-1] == rfid.serNum[2] &&
   bt3[cnt-1] == rfid.serNum[3] &&
   bt4[cnt-1] == rfid.serNum[4]){
   lcd.clear();
   lcd.print("card accepted");
   digitalWrite(green_led,HIGH);
   digitalWrite(red_led,LOW);
 }
 else{
    lcd.clear();
    lcd.print("card denied");
    digitalWrite(green_led,LOW);
    digitalWrite(red_led,HIGH);
}

To something like this:
    for(byte i=0;i<MXCD;i++){
      if(bt[i] == rfid.serNum[i%5]){
        cnt++;
      }
    }
    if(cnt==5){
      lcd.clear();
      lcd.print("card accepted");
      digitalWrite(green_led,HIGH);
      digitalWrite(red_led,LOW);
      cnt = 0;
    }
    else{
      lcd.clear();
      lcd.print("card denied");
      digitalWrite(green_led,LOW);
      digitalWrite(red_led,HIGH);
      cnt = 0;
    }

In this way, I did it with 'cnt' variable to count the number of successful matched bytes then test of the number is equal to 5.
Is there a better way than this one ?
Thanks for any comments or suggestions :)

Hint: There is a standard C function for this, memcmp(). You would use it like, if (!memcmp(bt, rfid.serNum, 5)) .... Ref. http://www.cplusplus.com/reference/cstring/memcmp/

wow thanks !! this function actually isn't new to me, but I didn't thought of it and its usage at this situation ! thanks again man ..

@MikaelPatel you should post that as an answer so the OP can accept it.

Yes, you're right.

Perch Eagle and @MikaelPatel, I want to learn something out of this question and your accepted answer, but I do not understand how it works. You write you want to compare elements of five different arrays (bt0[], bt1[], … bt4[]) with elements of one array (rfid.serNum[]). As an answer you are fine with a comparison with a new array bt[]. To make this work there must be a relation between bt[] and bt0[], bt1[], … bt4[]. Where in your sketch is this done or is this naturally but only I cannot understand?

There is a standard C function for this, memcmp(). It performs a memory block compare and can be used like this:
if (!memcmp(bt, rfid.serNum, sizeof(bt))) {
  lcd.clear();
  lcd.print("card accepted");
  digitalWrite(green_led,HIGH);
  digitalWrite(red_led,LOW);
}
else {
  ...
}

Ref. http://www.cplusplus.com/reference/cstring/memcmp/

Yep, it works perfectly! Thank you dude ..


text:
Data received by Arduino from ESP8266 01 Module is not complete
I am sending some data from ESP8266 01 module to Arduino. But the data received by Arduino is not complete.
Below are the images of the output from ESP8266 01 module and Arduino.

Here is the ESP8266 01 Module code:-
#include <ESP8266WiFi.h>
#include<String.h>

char c,e;                       //stores the bytes coming from the server
int DEBUG = 0;

int co=0;                       //control the sending of Alert

const char* ssid     = "ssid";            //your SSID of WIFI
const char* password = "password";       // password of Wifi
//--------------------------------------------

const char* host = "api.thingspeak.com";

void setup() {
  //dht.begin();
    Serial.begin(115200);
    delay(10);
  // We start by connecting to a WiFi network

    if (DEBUG){
      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);
  }

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

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

    if (DEBUG){
      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
    }
}

int value = 0;

void loop() {
  delay(1000);
  ++value;

  if (DEBUG){
    Serial.print("connecting to ");
    Serial.println(host);
  }

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }

  if (DEBUG){
    Serial.print("Requesting URL: ");
  }

//============================================================================================================
//                                Sending Control info to arduino Serially
//============================================================================================================
  // This will send the request to the server
  client.print(String("GET ")  + "/channels/******/feeds.json?api_key=*****************&results=2 HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");         // get information about device control
  unsigned long timeout = millis();
  while (client.available() == 0) {
    if (millis() - timeout > 5000) {
      Serial.println(">>> Client Timeout !");
      client.stop();
      return;
    }
  }

  // Read all the lines of the reply from server and print them to Serial
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);                         // received by arduino serially
  }
 //Serial.println("closing connection");
}

Here is the Arduino code:-
    //This sketch in the implementation of home automation
#include <SoftwareSerial.h>// import the serial library
#include<String.h>
//-----------------------------------------
//    pin definations
//-----------------------------------------
#define Light 2              // pin 2 to control light
#define fan 3                 // pin 3 to control fan
//------------------------------------------
//       variables
//------------------------------------------
char e;
int p=0,q=0;        //these variables prevent switching ON/OFF of already turned ON/OFF devices
int DEBUG = 1;

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

char control_data; // the data transmitted over Bluetooth

void setup() {
  // put your setup code here, to run once:
  home_monitor.begin(115200);
  Serial.begin(9600);
  pinMode(13,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (home_monitor.available()){
     control_data=home_monitor.read();   // getting control information from ESP8266 serially
     e=control_data;
     if (DEBUG){
      Serial.print(control_data);
     }
     //Serial.print(e);
 //============================================================================================================
 //                                        Device Control
 //============================================================================================================

 // Performing required operations based on the value of channel
    //-------------------------------------------------------------
    //                        LIGHT
    //-------------------------------------------------------------

    if(e=='0'&&p==0)         //Light ON
    {
      if (DEBUG){
        Serial.println("Light ON");
      }
      digitalWrite(Light,LOW);
      p=1;
    }
     if(e=='1'&&p==1)        //Light off
    {
      if (DEBUG){
        Serial.println("Light OFF");
      }
      digitalWrite(Light,HIGH);
      p=0;
    }

    //-------------------------------------------------------------
    //                        Heater
    //-------------------------------------------------------------

    if(e=='2'&&q==0)
    {
      if (DEBUG){
        Serial.println("Fan ON");
      }
      digitalWrite(fan,LOW);
      q=1;
    }
    if(e=='3'&&q==1)
    {
      if (DEBUG){
        Serial.println("Fan OFF");
      }
      digitalWrite(fan,HIGH);
      q=0;
    }
  }
}

You are using client.print() and the Arduino uses home_monitor.read() to receive the message (if I understood correctly). What I did in my sketch was change the home_monitor.read() to home_monitor.readStringUntil('\n').
Also before your ESP sends a message via client.print() it is recommended to run the client.flush() method so it waits until all outgoing characters in the buffer have been sent, before sending the next.
When using the ESP you should be aware of the useful yield() method (call it at the end of the loop). This let's the ESP get his background duties finished before going on (not calling this method may result in some issues.


text:
Why would using the += operator on an unsigned long crash my sketch?
I wrote a simple Timer class that's designed to work even in the face of the 49 day wrap of the millis() counter. I wanted a library that I could easily re-use and I could never remember the right way of dealing with the wrap-around so I thought: do it once, right. However, it has not gone according to the script!
Here's the source code, header first.
class Timer
    {
public:
    Timer();
    void SetDuration(unsigned long duration);
    bool Expired();
    unsigned long Elapsed();
    unsigned long Remaining();
    void Repeat();
    bool Enabled();
    void Stop();
private:
    unsigned long startedAt;
    unsigned long interval;
    };

...and the implementation...
#include "Timer.h"

Timer::Timer()
    {
    startedAt = 0;
    interval = 0;
    }

/*
 * Sets the timer interval and establishes the reference datum as the instant when this method was called.
 */
void Timer::SetDuration(unsigned long duration)
    {
    startedAt = millis();
    interval = duration;
    }

unsigned long Timer::Elapsed()
    {
    if (!Enabled())
        return 0UL;
    unsigned long elapsed = millis() - startedAt;
    return elapsed;
    }

unsigned long Timer::Remaining()
{
    return interval - Elapsed();
}

bool Timer::Expired()
    {
    return Enabled() ? Elapsed() >= interval : false;
    }

/*
 * Repeats the timer interval but does not reset the reference datum.
 * This should be used when repeatedly timing the same interval, and it is
 * intended that the intervals be consistent _on average_.
 */
void Timer::Repeat()
    {
    startedAt += interval;
    }

bool Timer::Enabled()
{
    return interval > 0;
}

void Timer::Stop()
{
    interval = 0;
}

Now my problem is this. My sketch gets to a certain point then crashes (re-runs from the start). The behaviour seems a lot like an odd stack corruption that's causing the code to branch to Oblivion. I've spent several hours doing a binary-chop on the code to narrow down the cause (it's a big sketch) and much to my surprise, the culprit appears to be the Repeat() method in my timer class. I use it in just one place in my code. When I call the Repeat() method, it crashes my sketch; If I don't call Repeat() but instead call SetDuration(n), the program doesn't crash and everything is fine. I've tried this in two different sketches with consistent results.
I've got spots before my eyes from trying to understand what's happening here. I'm a C# programmer most of the time although I'm not completely new to C and C++, but I've made dumb mistakes in Arduino code before. Repeat() could hardly be simpler or safer code - but is it? Is there anything wrong with my code that I'm just not seeing?
UPDATE: Stack Overflow effect (where you see the solution yourself as soon as you post a question) has kicked in and I've solved it. My implementation of Repeat() was moving startedAt ahead of millis() giving a negative amount of elapsed time (which in unsigned math means a very large positive amount of elapsed time). This was causing immediate time-out of the timer and causing the sketch to think the sky was falling in. So not a memory corruption, just some poorly implemented unsigned math.

gets to a certain point what point? how long? Can you provide some code that uses your whatever it is and demonstrates the issue

@JaromandaX Stack Overflow effect (where you see the solution yourself as soon as you post a question) has kicked in and I've solved it. My implementation of Repeat() was moving startedAt ahead of millis() giving a negative amount of elapsed time (which in unsigned math means a very large amount of elapsed time). This was causing immediate time-out of the timer and causing the sketch to think the sky was falling in.

Indeed - I hate it when MCU's think the sky is falling :p I had similar effect after approximately 50 days when millis "overflows"

You can answer your own question and accept it. That helps mark it as answered and may help future visitors find the solution to this issue.


text:
Question on pin management using PCA9534PW IO Extender
There is an IO expander PCA9534PW, Arduino UNO. I don’t really understand how I can manage this expander using UNO over I2C.
I found an example, but here is the reading mode.
What I need:
Set the IO0 pin to exit mode,
set the HIGH / LOW level to IO0.
In the datasheet, I just realized that to enter the settings mode - you need to write Wire.write(0x03).
How can I do it?

Hint: There is more or less always someone that has done this before you, and shared it. Please see, for instance, https://github.com/alotaiba/PCA9534.

Answer: Write to the configuration register to set the pin mode. See https://github.com/alotaiba/PCA9534/blob/master/src/PCA9534.cpp#L14.

You set the pin mode by setting the configuration register.
Wire.beginTransmission(0x20);
Wire.write(0x03);                   // Configuration Register
Wire.write(0xfe);                   // IO7-IO1 Input, IO0 Output
Wire.endTransmission();

Then write the output port register with HIGH and LOW.
Wire.beginTransmission(0x20);
Wire.write(0x01);                   // Output Port Register
Wire.write(0x01);                   // IO0 HIGH
Wire.endTransmission();
delay(500);
Wire.beginTransmission(0x20);
Wire.write(0x01);                   // Output Port Register
Wire.write(0x00);                   // IO0 LOW
Wire.endTransmission();

But using a library is much easier. See, for instance, https://github.com/alotaiba/PCA9534.

Many thanks for the example! I have seen this library, but it does not compile under Arduino. https://github.com/alotaiba/PCA9534/issues/1

It should be very easy to port from Particle. Have you tried to comment out this line, https://github.com/alotaiba/PCA9534/blob/master/src/PCA9534.h#L14, or just create an empty file with the name "Particle.h".


text:
Matrix keyboard and 7segment display countdown combination
I'm working on an escape room for my university with an Arduino Mega.
The last part consists of a 7segment display representing a time countdown, and the participants have to introduce the correct number in a matrix keyboard before it reaches zero.
My problem comes when for representing the seconds in the countdown, I have to use a delay, and this stops the matrix keyboard from getting the numbers.
The code I have so far:
char keys[4][4] =
{
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};

byte rowPins[4] = { 5, 4, 3, 2 };
byte colPins[4] = { 9, 8, 7, 6 };

int pinA = 26; //2
int pinB = 34; //3
int pinC = 31; //4
int pinD = 27; //5
int pinE = 25; //6
int pinF = 28; //7
int pinG = 33; //8
int D1 = 24; //9
int D2 = 30; //10
int D3 = 32; //11
int D4 = 35; //12

Keypad mykeypad = Keypad( makeKeymap(keys), colPins, rowPins, 4, 4);

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

pinMode(pinA, OUTPUT);
pinMode(pinB, OUTPUT);
pinMode(pinC, OUTPUT);
pinMode(pinD, OUTPUT);
pinMode(pinE, OUTPUT);
pinMode(pinF, OUTPUT);
pinMode(pinG, OUTPUT);
pinMode(D1, OUTPUT);  //Turns the first digit on.
pinMode(D2, OUTPUT);  //Turns the second digit on.
pinMode(D3, OUTPUT);  //Turns the third digit on.
pinMode(D4, OUTPUT);  //Turns the forth digit on.
}

//
void showTime(){

  digitalWrite(D1, LOW);
  digitalWrite(D2, LOW);
  digitalWrite(D3, LOW);
  digitalWrite(D4, LOW);

 //3
  digitalWrite(pinA, HIGH);
  digitalWrite(pinB, HIGH);
  digitalWrite(pinC, HIGH);
  digitalWrite(pinD, HIGH);
  digitalWrite(pinE, LOW);
  digitalWrite(pinF, LOW);
  digitalWrite(pinG, HIGH);
  delay(1000);

//2
  digitalWrite(pinA, HIGH);
  digitalWrite(pinB, HIGH);
  digitalWrite(pinC, LOW);
  digitalWrite(pinD, HIGH);
  digitalWrite(pinE, HIGH);
  digitalWrite(pinF, LOW);
  digitalWrite(pinG, HIGH);
  delay(1000);

  //1
  digitalWrite(pinA, LOW);
  digitalWrite(pinB, HIGH);
  digitalWrite(pinC, HIGH);
  digitalWrite(pinD, LOW);
  digitalWrite(pinE, LOW);
  digitalWrite(pinF, LOW);
  digitalWrite(pinG, LOW);
  delay(1000);

  //0
  digitalWrite(pinA, HIGH);
  digitalWrite(pinB, HIGH);
  digitalWrite(pinC, HIGH);
  digitalWrite(pinD, HIGH);
  digitalWrite(pinE, HIGH);
  digitalWrite(pinF, HIGH);
  digitalWrite(pinG, LOW);
  delay(1000);

}

//Receives the chars from the matrix keyboard.
void getCode(){
   char key = mykeypad.getKey();
  if(key){
     Serial.print(key);
  }
}

void loop()
{

  showTime();

}

Any idea on how can I archieve this combination? Have been trying to find something similiar to a Thread, but Arduino doesn't support it.
Thanks in advance.

You do not have to use delay(), however. Take a look at some examples of how to set up timed actions without using delay() https://learn.adafruit.com/multi-tasking-the-arduino-part-1/using-millis-for-timing

Try using millis(), it returns the number of milliseconds passed since the Arduino board began running the current program.
When you start the countdown you set a variable for a beginning time
int millisBegin = millis(); //put this at the end of your setup() {}.
You will also need a "border" to know when one second is over, so
int millisBorder = 1000; //one second border
Every time your the loop() {} starts over you can check if one second has passed so far
int millisNow = millis();
if(millisNow - millisBegin >= millisBorder){} //if one second over, do {}

Now I would work on the segment showing thingy. In the {} I would put a new variable, let's call it counter = 4; //4 because I found 3 numbers in your sketch. Every time the if() {} is being executed, you go through more if () {} statements, checking what number to display next.
if (counter == 3)
{
  //show number 3
}

if (counter == 2)
{
  //show number 2
}

if (counter == 1)
{
  //show number 1
}

if (counter == 0)
{
  //show number 0
}
counter = counter - 1;

At the end we take one off the counter, so the next time we enter the if(one second over) the number displayed will get lower
And well now there are multiple ways of doing the keyboard thingy. You can keep checking if there is a key available, and if so you can safe it as a String (most people hate strings, but I never had a problem with them to be honest).
After you've saved the key as a String you can use the strcmp(); method to compare the string with the solution/answer strcmp(key,answer);. If the key and the answer are the same, it will return 1.
if(strcmp(key,answer) == 1)
{
  Serial.println("you made it");
}

Use the "blink without delay" examples in the IDE, whereby you perform an action and then basically watch the clock until and let the rest of the code run until the time elapes.  For example, this blinks the onboard LED on and off, you can add to it for your keypad reading and time outputs.
unsigned long currentTime;
unsigned long previousTime;
unsigned long elapsedTime;
const byte ledPin = 13;
byte ledState = 0;

void setup(){
pinMode (ledPin, OUTPUT);
previousTime = millis();
}
void loop(){
currentTime = millis();  // capture the 'time' now
elapsedTme = currentTime - previousTime; // how much 'time' has passed
if (elapsedTime >= 1000){  // at least one second?
ledState = 1 - ledState; // results in 1,0,1,0,1,0 ...
digitalWrite (ledPin, ledState); // toddle the L led
previousTime = currentTime;   // set up for the next pass thru loop
// update the to display, and output it
}
// now add keypad reading stuff
}


text:
Use PWm and zero_cross_detect interrupt
I use an Arduino Uno for controlling one DC motor speed with PWM and one dimmer for control heater.
The dimmer and PWM control worked standalone, but when I want them to work together, the dimmer doesn't work.
#include  <TimerOne.h>          /
#include <Wire.h>

 //////////////                    //pin 2 zero kesmesi icin
int isiticiPWM = 9;                //  Opto Triac isitici PWM icin
int fanPWM=11;                     //motor pwm pini

int hiz=0;

volatile int i=0;               // Variable to use as a counter volatile as it is in an interrupt
volatile boolean zero_cross=0;  // Boolean to store a "switch" to tell us if we have crossed zero

char   data ;
int dim = 255;                    // Dimming level (0-128)  0 = on, 128 = 0ff
int inc=5;    // counting up or down, 1=up, -1=down
int freqStep = 75;    // This is the delay-per-brightness step in microseconds.

void zero_cross_detect() {
  zero_cross = true;               // set the boolean to true to tell our dimming function that a zero cross has occured
  i=0;
  digitalWrite(isiticiPWM, LOW);       // turn off TRIAC (and AC)
}

// Turn on the TRIAC at the appropriate time
void dim_check() {
  if(zero_cross == true) {
    if(i>=dim) {
      digitalWrite(isiticiPWM, HIGH); // turn on light
      i=0;  // reset time step counter
      zero_cross = false; //reset zero cross detection
    }
    else {
      i++; // increment time step counter
    }
  }
}
///////////////
void setup() {

  pinMode(fanPWM,OUTPUT);
  pinMode(isiticiPWM, OUTPUT);

    attachInterrupt(0, zero_cross_detect, RISING);    // Attach an Interupt to----------------------------------->  Pin 2 (interupt 0) for Zero Cross Detection <<------------------------------------------------
    Timer1.initialize(freqStep);                      // Initialize TimerOne library for the freq we need
    Timer1.attachInterrupt(dim_check, freqStep);

}

void loop()
{
hiz=450;analogWrite(fanPWM,hiz);

for(int k=0;k<=255;k++)
{dim=k;
}

  }

hiz=450;analogWrite(fanPWM,hiz); -- PWM goes from 0 to 255. 450 is too high.

Your loop function doesn't make sense to me. You are ramping dim from 0 to 255 in full speed. I guess you want dim to be the currently set time to turn on the triac. Most likely dim will change so fast, that the Timer interrupt does not have time to actually apply the value. Somewhat a racing condition.

Zero crossing is used for AC to detect when the alternating current is as close to zero as possible so when a TRIAC/MOSFET doesn't generate a lot of transients!    https://en.wikipedia.org/wiki/Zero_cross_circuit


text:
Arduino based attendance system
I am working on a RFID based attendance system. I am using Grove-125 kHz RFID reader, SD card module, DS1307 RTC and Arduino Mega. Each component works alone (separately) with the Arduino well, but whenever I combine them, nothing happens. If I remove the ground or VCC pin of the SD card module, than the code works well. Here is my code:
#include <SPI.h> // for the RFID and SD card module
#include <SD.h> // for the SD card
#include <RTClib.h> // for the RTC
#include <SoftwareSerial.h>
SoftwareSerial RFID(10,11); // RX and TX
#define CS_SD 4
File myFile;
RTC_DS1307 rtc;
int count=0;
const int buzzer1= 5;
int data1 = 0;
int tag1[14] = {2,48,67,48,48,55,52,51,52,66,66,70,55,3};
int tag2[14] = {2,48,67,48,48,55,52,57,48,48,55,69,70,3};
int tag3[14] = {2,48,67,48,48,55,52,56,65,65,55,53,53,3};
int tag4[14] = {2,48,67,48,48,55,52,51,68,65,70,69,65,3};
int tag5[14] = {2,48,67,48,48,55,52,57,51,69,68,48,54,3};
int newtag[14] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0}; // used for read comparisons

void setup()
{
  pinMode(buzzer1, OUTPUT);
  RFID.begin(9600);    // start serial to RFID reader
  Serial.begin(9600);  // start serial to PC
  while(!Serial);
  SPI.begin();
  Serial.print("Initializing SD card...");
  if(!SD.begin(CS_SD)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  // Setup for the RTC
  if(!rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while(1);
  }
  else {
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }
  if(!rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
  }

}

boolean comparetag(int aa[14], int bb[14])
{
  boolean ff = false;
  int fg = 0;
  for (int cc = 0 ; cc < 14 ; cc++)
  {
    if (aa[cc] == bb[cc])
    {
      fg++;
    }
  }
  if (fg == 14)
  {
    ff = true;
  }
  return ff;
}

void checkmytags() // compares each tag against the tag just read
{
  if (comparetag(newtag, tag1) == true)
  {
  count=1;
     Serial.print(count);
   Serial.println("Amimul");
  }
  else if (comparetag(newtag, tag2) == true)
  {
  count=2;
     Serial.print(count);
   Serial.println("Amimul");
  }
   else if (comparetag(newtag, tag3) == true)
  {
   count=3;
      Serial.print(count);
   Serial.println("Amimul");
      Serial.print(count);
   Serial.println("Amimul");
  }
   else if (comparetag(newtag, tag4) == true)
  {
   count=4;
   Serial.print(count);
   Serial.println("Amimul");
  }
   else if (comparetag(newtag, tag5) == true)
  {
   count=5;
      Serial.print(count);
   Serial.println("Amimul");
  }
}

void readTags()
{
  if (RFID.available() > 0)
  {
    delay(100); // needed to allow time for the data to come in from the serial buffer.
    for (int z = 0 ; z < 14 ; z++) // read the rest of the tag
    {
      data1 = RFID.read();
      newtag[z] = data1;
    }
    RFID.flush(); // stops multiple reads
    tone(buzzer1,4000);
    delay(300);
    noTone(buzzer1);
    checkmytags();
  }
}
void logCard(){
     digitalWrite(CS_SD,LOW);
    myFile=SD.open("Sir.txt", FILE_WRITE);
    if(myFile){
      if(count=="1"){
        myFile.print("Ridwanul basit,1\n");
        Serial.println("Ridwanul basit");
      }
        if(count=="2"){
        myFile.print("Afik Arman,2\n");
        Serial.println("Afik Arman");
        }
        if(count=="3"){
        myFile.print("Afnaf Tahmid,3\n");
        Serial.println("Afnaf Tahmid");
        }
        if(count=="4"){
        myFile.print("Al Mahmud,6\n");
        Serial.println("Al Mahmud");
        }
       if(count=="5"){
        myFile.print("Fahim Muntasir,11\n");
        Serial.println("Fahim Muntasir");
      }
    myFile.print(", ");
    DateTime now = rtc.now();
    myFile.print(now.year(), DEC);
    myFile.print('/');
    myFile.print(now.month(), DEC);
    myFile.print('/');
    myFile.print(now.day(), DEC);
    myFile.print(',');
    myFile.print(now.hour(), DEC);
    myFile.print(':');
    myFile.println(now.minute(), DEC);
    myFile.close();
    }
    digitalWrite(CS_SD,LOW);
    delay(100);
}
void loop()
{
  readTags();
  logCard();
  delay(10);
}

Does the initializing code send the correct messages, marking that the initialization was successfull? You should see some serial output, if the sketch is running. Please copy&paste the serial output to your question.

why do you use SoftwareSerial on Mega with 4 hardware serials?

what did you try to debug the problem? some debug prints? removing one of the components?

Yes.It initializes the sd card.And then nothing happens.@chrisl

Because I have to change the code multiple time.So,if i use hardware serial,i will have to remove Tx and Rx pin again and again.@Juraj

The Serial output is only this line:"Initializing Sd card..........Initialization done"

Please don't post images of text. Copy&Paste the text directly into the question an format it with the {} button as code. (Is easier to read then)

Get's something written into the file on the SD card?

And please show us your wiring (schematics or wiring diagram)

@amimulahsan Only Serial (pins 0/1) are affected by uploading the sketch. The other three serial ports are completely independent. You should be using those, not SoftwareSerial. SoftwareSerial is a last resort.

RFID.flush(); // stops multiple reads -- No it doesn't. It blocks until all pending writes have completed. Flush changed in operation with Arduino 1.0.0.

Yes.Only an empty text file is written.@chrisl

So what should i do@Majenko

can anyone please give me a better coding idea to make a 125hz rfid reader based attendence system?

@amimulahsan What should you do with what? The flush? Just delete it, it's pointless. The SoftwareSerial? Use TX1/RX1 pins and the Serial1 object. Or TX2/RX2 and Serial2. Or TX3/RX3 and Serial3.

I just deleted it.But the result are still the same@Majenko


text:
Arduino Mega not receiving data from Neo-6M
I am using the trying to get data from the Neo-6M GPS module with an Arduino mega, but, the condition 'While (gpsSerial.available() > 0' is being met. I believe this means the no bytes are being transferred from the module to the serial port but I'm not sure why.
The light on the Neo-6M was blinking which means it getting a lock but not giving out the data.
#include <SoftwareSerial.h>

// Choose two Arduino pins to use for software serial
int RXPin = 19;
int TXPin = 18;

//Default baud of NEO-6M is 9600
int GPSBaud = 9600;

// Create a software serial port called "gpsSerial"
SoftwareSerial gpsSerial(RXPin, TXPin);

void setup()
{
  // Start the Arduino hardware serial port at 9600 baud
  Serial.begin(9600);

  // Start the software serial port at the GPS's default baud
  gpsSerial.begin(GPSBaud);
  Serial.write("123");
}

void loop()
{
  // Displays information when new sentence is available.
  while (gpsSerial.available() > 0)
    Serial.write(gpsSerial.read());
}

I had it working on an Uno by connecting to pins 2,3 rather then 18 and 19. I have also tried swapping the 18 and 19 pins over but still noting.
Thanks for the help
EDIT:
I have the RX and TX plugged into the mega at pins 1 and 2, however, it will only print GPS information when the reset button is pressed or held down

Not all pins on the Mega support software serial, have a read below:
https://www.arduino.cc/en/Reference/SoftwareSerial
Pins 18 / 19 are actually hardware serial pins so should not need the use of software serial.
Edit, should have noted to use hardware pins 18 / 19 you would use the constructor Serial1.begin(9600)


text:
Measure voltage changes with unknown baseline
I would like to monitor an audio stream and detect when it is "active" and music is playing or when it is "inactive" and is silent. What is a good way to measure when an audio stream changes state and continues to be "active?"
Each audio stream is amplified with this circuit.
Each audio stream has a different baseline voltage when it is not playing and "silent", but that voltage tends to drift slightly and change. This may be an artifact of my amp. I don't have an OScope and my multimeter is rubbish for low voltage so I can't quite pin down where the drift is coming from.
Currently, I'm using the method shown below, but that isn't as effectivewhen the audio stream is loud (e.g. has a compressed dynamic range).
Also, low volume tracks (e.g. classical music) tends have too low of a dynamic range to measure accurately and I get a lot of false "off" states.
#include <elapsedMillis.h>    //measure elapsed time

const int analogInPin = A0;   //Analog input pin - reads from amplifyer circuit
const int statusLight = 10;   //Digital output pin for indicator light
int sensorValueA = 0;         //Sensor reading now
int sensorValueB = 0;         //Previous sensor reading
int sensorDeltaA = 0;          //Change in sensor reading
int sensorDeltaB = 0;          //Record the last delta - useful for prefenting accidental triggering on start
int sensorThreshold = 50;      //Threshold in delta to trigger action
elapsedMillis turnOverTime;   //Timer for measuring the turnover between changes in sensor reading

void loop() {
  //measure the analog input
  sensorValueA = analogRead(analogInPin);
  sensorDeltaA = abs(sensorValueA - sensorValueB);

 //check if the data is over the threshold and switch on
  if ((sensorDeltaA >= sensorThreshold) and (sensorDeltaB != 0)) {
    turnOverTime = 0;
    powerStateA = true;
  }

  sensorValueB = sensorValueA;

  //check if no sensor data beyond the threshold has been returned within the delay window, switch off
  if (turnOverTime >= delayTime) {
    turnOverTime = 0;
    powerStateA = false;
  }

  //if the powerstate changes act acordingly
  if (powerStateA != powerStateB) {
    digitalWrite(statusLight, powerStateA);
  }
}

Sound like you need to AC couple the signal, and add a few MegaOhms resistor to ground on that.

Where in the circuit would I want to pull to ground? Before or after the amp? And what is an AC couple? I'm pretty new to the audio handling scene and finding out exactly how little I know.

An audio signal consists of two main components:

An AC signal
A DC offset

What you are interested in is the AC signal, but not the DC offset.  That DC offset is what is drifting in your current model.
So you need to AC couple the signal. That is, couple the signal to your Arduino in such a way that only the AC portion gets through.
The simplest way is with a capacitor.
But the Arduino can't handle negative voltages, and an AC signal has negative voltages. So you need to get rid of them.
The simplest way is to add a DC offset.
But didn't we just get rid of a DC offset that we didn't want? Yep. But that was an unknown DC offset. If we then add in a DC offset that we do know, and is stable, then we can work with it.
Here's a very simple circuit:

simulate this circuit – Schematic created using CircuitLab
The capacitor C1 removes the existing DC offset.  R1 and R2 then form a voltage divider giving 2.5V (half of 5V), which is then added to the pure AC signal.
That means that the signal now varies around 2.5V.  Silence is 2.5V, and noise is other values above and below that.
Since 2.5V is half of the 5V the Arduino runs on, silence should read at somewhere near half the ADC value. That's about 512.  Sound will be both above and below that value.
So if you subtract 512 from your analog reading you will effectively be subtracting the DC offset you just added, giving you a value that can be either positive or negative.
For simplicity, since you don't care whether it's positive or negative, you can then remove the sign from the number to just give you a magnitude.
int audio = analogRead(A0); // Get a sample
audio = audio - 512; // Remove DC offset
audio = abs(audio); // Remove sign

You can now compare that to a threshold value:
if (audio > 100) {
    // do something
}

Aren't you making an assumption that the audio signal does not exceed +/- 2.5V? (That may well be a valid assumption).

This answer is exceptionally well described. Thank you! My audio source is coming from the RCA output of a Squeezebox and the headphone jack of a Chromecast Audio. I've measured (poorly, with a junk RadioShack multi meter) the voltage to be well under 1v. Will I need to send the audio stream through an amplifier first before using this circuit?

A standard line level output won't exceed about 1.5v.

If I have two audio sources and I want to measure them independently would this still work? Wouldn't I end up putting two voltage dividers in parallel effectively making each branch of the divider 5K instead of 10K?

No, The dividers are separate entities. Each divider is still a pair of 10K resistors (20K in total). The total resistance across the power supply would halve (10K instead of 20K), but each divider knows nothing at all about that.