body:
I am very new to Arduino (and fritzing so please excuse my poor layout).
I am trying to automate my patio sun shade, eventually it will incorporate a photocell but I wanted a proof of concept first with buttons. The first and last buttons represent limit switches and the middle button represents a toggle switch (which will eventually become the photocell).

 An example of what I am trying to do is;
If the upper limit switch is active and I press the toggle button, the stepper runs until it hits the lower limit switch, if the lower limit switch is active and I press the toggle button then the stepper should run the other direction until it hits the upper limit switch.

 I have serial prints to show what is happening, if I hold either of the "limit switches" then the serial monitor displays (rather spams) the corresponding print line, however the stepper motor is not moving how I would expect it to. I have to be holding a limit switch and holding the toggle for it to move in a direction, even then it only moves approximately 1 step per second. If I release the limit switch and continue to hold the toggle then the stepper steps one back and one forward for the duration that I depress the switch. The code I have is based off of someone attempting the same thing but with a DC motor, I tried to accommodate it to a stepper motor and am having trouble.
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/sxYpQ.jpg

        // constants won't change. They're used here to set pin numbers:
    const int uplimitPin = 9;     // pin number for upper limit switch
    const int togglebuttonPin = 10;     // pin number for the toggle switch
    const int downlimitPin = 11;     // pin number for the lower limit switch
    const int dirPin =  2;      // direction pin for stepper
    const int stepPin =  3;      // step pin for stepper

    // variables will change:
    boolean uplimitState = 0;         // variable for reading the status of the upper limit switch
    boolean togglebuttonState = 0;         // variable for reading the toggle switch status
    boolean downlimitState = 0;   // variable for reading the status of the lower limit switch

    int shadePosition = 2;  // Tells progam what position the shade is in

    /**
     *  setup inputs for switches and outs for motor pins
     *  serial begin to read the switches to test for errors
     */
    void setup() {
        // initialize the stepper pins as outputs:
        pinMode(dirPin, OUTPUT);
        pinMode(stepPin, OUTPUT);
        // initialize the pushbutton pins as an inputs:
        pinMode(uplimitPin, INPUT);
        pinMode(togglebuttonPin, INPUT);
        pinMode(downlimitPin, INPUT);
        Serial.begin(9600);
    }

    /**
     * this function turns motor foward
     */
    void shadeDown() {
         // turn motor foward:
        digitalWrite(dirPin, HIGH);
        digitalWrite(stepPin, HIGH);
        delayMicroseconds(1000);
        digitalWrite(stepPin, LOW);
        delayMicroseconds(1000);
    }

    /**
     * this function turns motor backwards
     */
    void shadeUp() {
         // turn motor in other direction:
        digitalWrite(dirPin, LOW);
        digitalWrite(stepPin, HIGH);
        delayMicroseconds(1000);
        digitalWrite(stepPin, LOW);
        delayMicroseconds(1000);
    }

    /**
     * Stop the motor form moving
     */
    void stopShade() {
      digitalWrite(stepPin, LOW);

    }

    /**
     *
     */
    void loop() {
       // read the state of the pushbutton value:
       uplimitState = digitalRead(uplimitPin);
       togglebuttonState = digitalRead(togglebuttonPin);
       downlimitState = digitalRead(downlimitPin);

       // check if the limit is active. If it is, the limitState is HIGH:
       if (uplimitState == HIGH) {
          shadePosition = 2;
          Serial.println(F("The shade is up"));
          stopShade();
       }else if (downlimitState == HIGH) {
          shadePosition = 1;
          Serial.println(F("The shade is down"));
          stopShade();
      }

      if (togglebuttonState == HIGH) {
        if( shadePosition  == 1 ){
          shadeUp();
          delay(100);
          shadePosition = 2;
          delay(100);
        }else if (shadePosition == 2 ) {
          delay(100);
          shadeDown();
          delay(100);
          shadePosition = 1;
        }

      }
    }

title: I am trying to automate my sun shade on my back porch with a Nema17 Stepper motor

Answers: 2

body:
Assuming you're asking how debug the unexpected behavior your described (and not having any steppers on-hand to have a go at your code) I'll offer some observations and suggestions.

Pushbuttons "bounce" (not really, but their output signal looks like they bounce). For the limit switches, you won't really care - the first make (and I'm assuming positive logic, for simplicity of the discussion) tells you that the shade has reached it's limit, and you don't need to (probably shouldn't!) wait for the switch to settle before stopping the shade. The 'break' of a limit switch is uninteresting except possibly to confirm that the shade is moving when you expected it to, and again, who cares about the bounces? But the toggle button's bounces may well confound your logic unless you debounce it (can be done either electrically or in software - search the topic). And even though the eventual photocell may not bounce (or it may: are there shade-trees within it's view, f/ex?), right now, you're testing with a button which certainly does.

This is a would be a good application to implement as a state-machine, and even if you don't do that formally, diagramming a state-machine to operate your shade should make it clear what your code will need to do. If you're new to software as well as to Arduino, learning about state-machines might be a longer detour than you want to take at the moment, but if this kind of control system is what interests you, you will encounter them sooner or later, because they model your control system pretty directly, both graphically (because you usually sketch them out first) and in software.

State diagrams turn out to be one of the best tools a software designer has to communicate the details of a proposed control system between them and the typically-non-software-trained people who are the experts at building and/or using the devices being automated (think printing presses, copiers, assembly robots, .... ). The picture says it all.

body:
# System State Machine
As JRobert suggested, a state machine would make the code a lot cleaner! Below is some pseudocode (I'll leave the debugging up to you ;)) of how you might set that up.

When you break up your system into 4 distinct states, it's easy to reason about what should be happening at each state and what is required to get to the next state. You can draw a diagram showing this (google "state machine") to help you reason.

```C++
...

enum SystemState {
    SystemState_Opening,
    SystemState_Closing,
    SystemState_Open,
    SystemState_Closed
};

void main()
{
    // Set initial state
    SystemState state;
    if (digitalRead(upLimitState))
    {
        state = SystemState_Closed;
    }
    else
    {
        state = SystemState_Open;
    }

    // Run state machine
    while (1)
    {
        switch (state)
        {
            case SystemState_Closed:
            {
                if (digitalRead(toggleButtonPin))
                {
                    state = SystemState_Opening;
                }
                break;
            }
            case SystemState_Open:
            {
                // TODO: Implement this yourself!
                break;
            }
            case SystemState_Closing:
            {
                if (digitalRead(upLimitState))
                {
                    state = SystemState_Closed;
                }
                shadeUp();
                break;
            }
            case SystemState_Opening:
            {
                // TODO: Implement this yourself!
                break;
            }
    }
}
```
# What's Wrong With Your Code
The actual issue with the code you provided is that you're only calling the `shadeUp()` function once. You need to call it many times to send the step pin many pulses to rotate the motor.

Each time you send a pulse to the step pin (eg. `shadeUp()`), you rotate the motor by one step (or microstep) which is likely only 1.8 degrees!


body:
If the WDT ever fires, from the ISR I save some info in EEPROM for later diagnostics before I drive the reset pin. Stack size, heap size, etc.

It might also be useful to know where the code was when the WDT fired, i.e. the ISR's return address. How do I get that?

title: Save Watchdog ISR Return Address in EEPROM

Answers: 1

body:
GCC has a handy function `__builtin_return_address(depth)` which should do what you want.  To get the return address of the current function (which should be the same whether it's a normal function or an ISR on AVR) you set the `depth` to 0:

```c++
void *addr = __builtin_return_address(0);
```

**EDIT**

The address returned above is a word address. Multiply by two to get a byte address as found in the disassembly from `avr-objdump -SC firmware.elf >disassembled.txt`

The latter is found at `~/.platformio/packages/toolchain-atmelavr/bin/avr-objdump`


body:
**I Want to know if there is a library that can be used in order to make a PS4 controller with Arduino.**
I have a PS2 steering wheel and I want to use it thorugh Arduino with PS4. I know that PS4 has his own protocol but I think there may be a way to do it.

Cheers!

**EDIT:** I already have the code for reading the PS2 steering wheel, but now I need to "transform" that into PS4 protocol

title: Can Arduino UNO be used to emulate a PS4 joystick?

Answers: 1

body:
TLDR: Not sure but the PS4 protocol is known and written for other MCUs, and can be found on github.

Not sure if there is a library for it in Arduino, but there are libraries out there (such as Passing Link) that emulate the protocol on other platforms. You can look at that.

BUT...

PS2 and PS4 are completely different beasts. PS2 uses SPI for its protocol. PS4 uses USB with specific USB drivers. Even if you manage to get the PS4 protocol working, the next problem is authenticating you are a legit/licensed controller. For every legit controller, there lies a security chip inside. And that chip also has a proprietary way to be talked to as well. When a legit controller is talking to a PS4, the PS4 will sometimes ask for the contents in the security chip for authentication. If you can't deliver the contents it wants, your controller is locked out until next power up (maybe even next PS4 power up, not sure).

So while it may be possible, the two huge hurdles are:
1) Implementing the USB code properly with custom drivers defined by Sony.
2) Circumventing the security chip by either ripping contents off a legit controller or mining it and placing it in your own circuit. Both of which will require an understanding how how to communicate with said chip.


body:
The L1 is the value i will get from firebase database, but now i wanna send the value that i receive in realtime database to arduino to on LED, how to solve? any suggestion? which mean when arduino receive value 1 from firebase then led will on

ESP8266 code :

    #include <ESP8266WiFi.h>
    #include <FirebaseArduino.h>

    // Set these to run
    #define FIREBASE_HOST ""
    #define FIREBASE_AUTH ""
    #define WIFI_SSID "Home "
    #define WIFI_PASSWORD ""

    int value1;

    void setup() {
      //Initializes the serial connection at 9600 get sensor data from arduino.
      Serial.begin(9600);

      delay(1000);

      WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
      while (WiFi.status() != WL_CONNECTED)
      {
        delay(500);
      }

      Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
      Firebase.setInt("L1",0);
    }

    void loop()
    {
      while(Serial.available())
      {
            value1 =  Firebase.getString("L1").toInt();
      }

      delay(1000);
    }

Arduino code:

    #define LED 13;

    int value1;

    void setup()
    {
      pinMode(LED,OUTPUT);
      Serial.begin();
    }

    void loop()
    {
      if (value1 == 1)
      {
         digitalWrite(LED, HIGH);
      }
    }

title: How to send data from esp-01 Wi-Fi module to arduino

Answers: 2

body:
Your ESP needs to

 - receive data from Firebase over WiFi;
 - send the received data (or the useful part of it) to the Arduino, over its serial port.

Your Arduino needs to:

 - watch its own serial port for data becoming available;
 - read the data;
 - decide whether turn the LED on or off.

Your loop() code on the Esp is watching its serial port, but from your description, it shouldn't expect any data from its serial port - that is connected to the Arduino. You need to watch for data arriving *via WiFi* instead.

Your Arduino code is testing the variable `value` but value never gets set to anything. You should set it according to what you receive from the Esp.

Also, since I'm not familiar with Firebase, does the Esp need to tell Firebase each time it wants new data? Or does Firebase send data at intervals without you having to ask for it? If it's the former, your Esp will need code to ask for the data and wait for it to arrive before it can send it on to the Arduino.

body:
ESP8266 code :

       #include <ESP8266WiFi.h>
    #include <FirebaseArduino.h>

    // Set these to run
    #define FIREBASE_HOST ""
    #define FIREBASE_AUTH ""
    #define WIFI_SSID "Home "
    #define WIFI_PASSWORD ""

    int value1;
    String string_value;
    void setup() {
      //Initializes the serial connection at 9600 get sensor data from arduino.
      Serial.begin(9600);

      delay(1000);

      WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
      while (WiFi.status() != WL_CONNECTED)
      {
        delay(500);
      }

      Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
      Firebase.setInt("L1",0);
    }

    void loop()
    {

            value1 =  Firebase.getString("L1").toInt();
            string_value = String(value1);
            Serial.print(string_value);

      delay(1000);
    }

Arduino code:

        #define LED 13

    int value1;
    String data;

    void setup()
    {
      pinMode(LED,OUTPUT);
      Serial.begin(9600);
    }

    void loop()
    {

      bool Sr =false;

      while(Serial.available()){

            data=Serial.readString();
            value1 =data.toInt();
            Sr=true;

        }

        delay(500);

        if(Sr){

            if (value1 == 1)
            {
               digitalWrite(LED, HIGH);
            }else if(value1 == 0){

                digitalWrite(LED, LOW);
              }
       }
    }

For More details:

[https://www.youtube.com/watch?v=ji71cHaGW8w][1]

  [1]: https://www.youtube.com/watch?v=ji71cHaGW8w


body:
When I run this script serial communication just stops after a random period of time. There is no error it just stops outputting data and does not respond to inputs in IDE. Does anyone know a fix for this?. This is not an IDE issue as serial communication also stops without any reported error when reading serial in a python script.

    // mpu9250 stuff
    #include <MPU9250_WE.h>
    #include <Wire.h>
    #define MPU9250_ADDR 0x68
    MPU9250_WE myMPU9250 = MPU9250_WE(MPU9250_ADDR);
    // motor stuff
    #include <AFMotor.h>
    AF_DCMotor motorA(1);
    AF_DCMotor motorB(2);
    int lf;
    int rf;
    void setup() {
      Serial.begin(115200);
      Serial.setTimeout(10);
      // compass stuff
      Wire.begin();
      if(!myMPU9250.init()){
        Serial.println("MPU9250 does not respond");
      }
      else{
        Serial.println("MPU9250 is connected");
      }
      if(!myMPU9250.initMagnetometer()){
        Serial.println("Magnetometer does not respond");
      }
      else{
        Serial.println("Magnetometer is connected");
      }

      Serial.println("Position you MPU9250 flat and don't move it - calibrating...");
      delay(1000);
      myMPU9250.autoOffsets();
      Serial.println("Done!");
      myMPU9250.setSampleRateDivider(5);
      myMPU9250.setAccRange(MPU9250_ACC_RANGE_2G);
      myMPU9250.enableAccDLPF(true);
      myMPU9250.setAccDLPF(MPU9250_DLPF_6);
      myMPU9250.setMagOpMode(AK8963_CONT_MODE_100HZ);
      delay(200);

      // motors
      motorA.setSpeed(50);
      motorB.setSpeed(50);
      motorA.run(RELEASE);
      motorB.run(RELEASE);

    }

    void loop() {
      xyzFloat angles = myMPU9250.getAngles();
      xyzFloat magValue = myMPU9250.getMagValues();
      Serial.print(magValue.x);
      Serial.print(",");
      Serial.print(magValue.y);
      Serial.print(",");
      Serial.print(magValue.z);
      Serial.print(",");
      Serial.print(angles.x);
      Serial.print(",");
      Serial.println(angles.y);

      //motors
      if (Serial.available()>0){
        String ser = Serial.readString();
        String left = (split(ser, '.', 0));
        String right = (split(ser, '.', 1));
          if (ser.length() > 0){
            int lf = left.toInt();
            int rf = right.toInt();
            Serial.print(lf);
            Serial.print("   ");
            Serial.println(rf);
            motorA.setSpeed(lf);
            motorB.setSpeed(rf);
            if (lf > 0){
              motorA.run(BACKWARD);
              }
            if (lf == 0){
              motorA.run(RELEASE);
              }
            if (lf < 0){
              motorA.run(FORWARD);
              }
            if (rf > 0){
              motorB.run(BACKWARD);
              }
            if (rf == 0){
              motorB.run(RELEASE);
              }
            if (rf < 0){
              motorB.run(FORWARD);
              }
        }
      }

      if(!Serial) {  //check if Serial is available... if not,
        Serial.end();      // close serial port
        delay(10);
        Serial.begin(115200); // reenable serial again
        Serial.println("reset");
      }

    }
    String split(String data, char separator, int index)
    {
        // spliting a string and return the part nr index
        // split by separator

        int stringData = 0;        //variable to count data part nr
        String dataPart = "";      //variable to hole the return text

        for(int i = 0; i<data.length()-1; i++) {    //Walk through the text one letter at a time

          if(data[i]==separator) {
            //Count the number of times separator character appears in the text
            stringData++;

          }else if(stringData==index) {
            //get the text when separator is the rignt one
            dataPart.concat(data[i]);

          }else if(stringData>index) {
            //return text and stop if the next separator appears - to save CPU-time
            return dataPart;
            break;

          }

        }
        //return text if this is the last part
        return dataPart;
    }

title: Serial communication problems

Answers: 0


body:
I'm building a small project to maintain a copper plating tank's temperature and filter pump duty cycle. I'm using the Adafruit Feather platform to hold an 8 segment matrix coupled with a Teensy 3.2 (on a Feather shield) to calculate and display temp. There is a 10K Pot on A0 and an 8 segment NeoPixel Strip to set and display pump duty cycle from 1 to 8 corresponding to .125*hour and 100% on. There is also a push and hold set switch to operate temperature target point setting using the same pot.

Things that work: Almost Everything!
Thing that doesn't work:

Changing the Duty Cycle knob (which changes the duty cycle global variable) after turning the unit on doesn't seem to change the on/off times other than to successfully change the NeoPixel display. If the unit is turned on at a particular duty cycle, the program will run that duty cycle successfully. While running, if I change the duty Cycle to 8, I don't get a "100% On". In other words the change in the duty cycle variable doesn't seem to change the on time and off time variables in the code while running.

Q: What do I need to do to make the duty cycle setting work on the fly?

Oh... That Volatile Float declaration was my last desperate attempt, Please ignore / forgive. ;-)

Hopefully the fix is as simple as the code. ;-) I just don't see it and my (perhaps flawed) understanding of global variables is hit a wall.

Any help will be much appreciated. Thanks.

Jeff

Code:

```

/***************************************************
  Copper Plating Tank Control - v1.1
  by Jeff W. Parisse - July 7st, 2021
  www.coppercholla.com

  This program runs a programmable interval timer for chemical pump
  duty cycle and a programmable temperature setting and heating control
  for maintaining plating solution temperature.

  Processor: PJRC Teensy 3.2
  Additional Libraries: Adafruit Industries LLC
  Temperature Sensor: Adafruit MAX31865 w/P1000 Platinum Wire Probe
  Pin Outs:
    Setting Knob: Pin A0
    Matrix Display: Feather Matrix I2C 0x70
    Neopixels: Pin 5
    MAX31865: CLK Blue
    MAX31865: SDO Yellow
    MAX31865: SDI White
    MAX31865: CS Pin 6 Green
    Temp Set Switch: Pin 8
    Chemical Pump: Pin 9
    Tank Heater: Pin 10

 ****************************************************/

#include <Adafruit_MAX31865.h>
#include <Adafruit_GFX.h>
#include "Adafruit_LEDBackpack.h"
#include <Adafruit_NeoPixel.h>

#define knobPin A0
#define ledPin 5
#define csPin 6
#define switchPin 8
#define pumpPin 9
#define heaterPin 10
#define ledCount 8
#define sampleNum 4
#define RREF      4296.0
#define RNOMINAL  1000.0

Adafruit_MAX31865 thermo = Adafruit_MAX31865(csPin);
Adafruit_7segment matrix = Adafruit_7segment();
Adafruit_NeoPixel strip(ledCount, ledPin, NEO_GRB + NEO_KHZ800);

float targetTemp = 77.0;                // Starting Value
float readTemp = 0;
float toleranceTemp = 0.25;
float tempSum = 0;
float cTemp = 0;
float fTemp = 0;
volatile float dutyCycle = 4;
unsigned long previousTime = 0;
unsigned long oneHour = 3600000;       // 1 Hour in Milliseconds
unsigned long timeOn = 450000;         // 7.5 Minutes in Milliseconds
unsigned long pumpInterval = timeOn;
boolean pumpState = true;

void setup() {
  thermo.begin(MAX31865_3WIRE);;
  matrix.begin(0x70);
  strip.begin();
  strip.show();
  pinMode(csPin, OUTPUT);
  pinMode(heaterPin, OUTPUT);
  pinMode(pumpPin, OUTPUT);
  pinMode(switchPin, INPUT_PULLUP);
  digitalWrite(csPin, LOW);
  digitalWrite(heaterPin, LOW);
  digitalWrite(pumpPin, LOW);
}

void loop() {
  // Read Set Switch
  int setSwitch = (digitalRead(switchPin));
  while (setSwitch == LOW) {
    int readKnob = analogRead(knobPin);
    targetTemp = map(readKnob, 1, 1023, 67, 87);
    matrix.print(targetTemp, 1);
    matrix.writeDisplay();
    setSwitch = (digitalRead(switchPin));
  }

  // Read, Convert, and Display Temp
  tempSum = 0;
  for (int i = 1; i <= sampleNum; i++) {
    readTemp = thermo.temperature(RNOMINAL, RREF);
    tempSum = tempSum + readTemp;
  }
  cTemp = tempSum / sampleNum;
  fTemp = (cTemp * 1.8) + 32;
  matrix.print(fTemp, 1);
  matrix.writeDisplay();

  // Heater Logic
  if (fTemp < targetTemp - toleranceTemp) {
    digitalWrite(heaterPin, HIGH);
  }
  else if (fTemp > targetTemp + toleranceTemp) {
    digitalWrite(heaterPin, LOW);
  }

  // Read and Display Duty Cycle
  int readKnob = analogRead(knobPin);
  dutyCycle = map(readKnob, 1, 1023, 1, 8);
  for (int i = 0; i <= ledCount; i++) {
    strip.setPixelColor(i, 0, 0, 0);
  }
  strip.show();
  for (int i = 0; i <= dutyCycle - 1; i++) {
    strip.setPixelColor(i, 0, 0, 20);
  }
  strip.show();

  // Pump Timer
  digitalWrite(pumpPin, pumpState);
  unsigned long timeOn = ((dutyCycle / 8UL) * oneHour);
  unsigned long timeOff = (oneHour - timeOn);
  unsigned long currentTime = millis();
  if (currentTime - previousTime >= pumpInterval) {
    if (pumpState) {
      pumpInterval = timeOff;
    }
    else {
      pumpInterval = timeOn;
    }
    pumpState = !(pumpState);
    previousTime = currentTime;
  }
}

```

title: Global Variable not updating…

Answers: 1

body:
I do not really understand what may be the cause of your problem, but I
have identified two issues that could potentially be related.

You have:

> ```c++
> dutyCycle = map(readKnob, 1, 1023, 1, 8);
> ```

Because of some rounding issues in the Arduino `map()` function, this
may not work as you expect: the output will be 8 only if the input
reaches 1023. If `readKnob` is 1022, `dutyCycle` will be 7. This may
explain why you never see the pump being constantly on.

The way `map()` works makes most sense if you think in terms of
_half-open_ intervals, open on the right. If you write:

```c++
dutyCycle = map(readKnob, 0, 1024, 1, 9);
```

you will get a perfect mapping from [0, 1024) to [1, 9). Perfect in the
sense that there will be exactly 128 input values mapped to each output
value:

    [  0, 128) → 1
    [128, 256) → 2
    [256, 384) → 3
    ...

And later:

> ```c++
> for (int i = 0; i <= ledCount; i++) {
>     strip.setPixelColor(i, 0, 0, 0);
> }
> ```

The strip has `ledCount` pixels, numbered 0 to `ledCount-1`. This loop
will set the color of pixels 0 through `ledCount` inclusive. The last
iteration goes beyond the end of the strip, and it is most likely
corrupting memory, i.e. overwriting whatever data happens to sit right
after the memory area used for the strip. If this is overwriting some
variable related to the duty cycle, that may explain the weird behavior
you experience.


body:
I have a CNC router table that came into my local makerspace. The board looks like it has some standard parts, but also has some parts I don't recognize. At the heart of it is an Arduino Uno. I would like to get the code from the UNO, as a back up. I will have to do testing on this board, but I don't want to overwrite something I don't have a back up of.

is there a way to get the firmware off of the arduino, without having the ino files that generated it?

(This is a standard function on many other platforms such as PIC, I just don't know how to do it in Arudino. I am assuming the functionality also exists.)

title: Can I get the hex file from an Arduino without the .ino code

Answers: 1

body:
Cool I got it using avrdude.
$ `avrdude -c arduino -P /dev/ttyUSB0 -b 9600 -p m328p -U  flash:r:CNCArdunio.hex:i`

    > -c the platform (basically)
    > -P the port where your harware is.
    > -b the baudrate.
    > -p the chip architecture.
    > -U momory type flash  :r option to read to file  :i option to format into Intel HEX.

caveats.Upon closer inspection this is either a very early model UNO, or a cheap clone. It comes up at /dev/ttyUSB0, and required that I press the reset button shortly before sending the avrdude command, else it resulted in

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


body:
I'm new to Arduino and need assistance from knowledgeable people.
I'm having a problem with my code, which allows the user to increase or decrease the number by pressing buttons. From time to time, the number does not change by one, but by two or three. This occurs on a sporadic basis. This is known as "bouncing." I googled "attachInterrupt debounce" in vain, but I couldn't find a suitable solution. My code is here.
```
int digit_state = 0;
void increment(void){
  digit_state = digit_state + 1;
  }
void decrement(void){
  digit_state = digit_state - 1;
  }
String user_input = "";
String password = "3452";
int enterbutton = 11;
int increment_button = 2;
int decrement_button = 3;
int counter = 0;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(enterbutton,INPUT);
  attachInterrupt(digitalPinToInterrupt(increment_button),increment,FALLING);
  attachInterrupt(digitalPinToInterrupt(decrement_button),decrement,FALLING);
}

void loop() {
  // put your main code here, to run repeatedly:
  lastButtonState = reading;
  while(counter<=3){
    delay(500);
    Serial.println(digit_state);
    if(digitalRead(enterbutton)==LOW){
      user_input = user_input + digit_state;
      Serial.println("Saved input so far is "+user_input);
      if(user_input == password){
        Serial.println("検証できた");
      }
      delay(500);
      digit_state = 0;
      counter++;
  }
}
}

```
As the user presses, I need to stop it from bouncing and get an accurate password all the time.

title: Push button unexpected increment/decrement. I'm using attachInterrupt

Answers: 1

body:
First: It is not necessary to use interrupts for buttons, because when humans press buttons they will be at least actived for about 100ms, which is very slow for a microcontroller. You would just need to rewrite your code to be non-blocking (for example by ditching all `delay()` calls and instead use `millis()` like in the `BlinkWithoutDelay` example, that comes with the Arduino IDE). Then you can also use existing libraries for debouncing like [Bounce2][1].

---

A very simple approach would be to set a timeout after each button press, where no new button press will be registrated, like 10ms (should be plenty enough for debouncing, though you can test for your setup yourself). This can be done with `millis()` by maintaining a timestamp of the last button press:

    #define DEBOUNCE_TIME  10
    volatile unsigned long button_press_timestamp = 0;

    void increment(void){
      if(millis()-button_press_timestamp > DEBOUNCE_TIME){
          digit_state = digit_state + 1;
          button_press_timestamp = millis();
      }
    }

First in global scope we are defining our debounce time and a variable for holding the timestamp, when the last button press was registered. In the ISR (here only `increment()` as example) we then check the difference between this timestamp and the current time. If that is bigger than the debounce time we execute the buttons action (incrementing in this case). Then we update the timestamp to the current time.

On a button press the first falling edge will trigger the button action. Any falling edges from the bouncing will appear inside the debounce time and thus will be ignored (the ISR gets called but the code in the if statement is not executed).

This debouncing principle is not perfect but easy to implement and it might be enough for you.

  [1]: https://github.com/thomasfredericks/Bounce2


body:
I am trying to build a robotic arm and also using a lot of metal in it, now the real challenge for me have arrised at first I was using tower pro mg995 but that servo is worse than scrap. So I ditched them and got myself Johnson geared motors. Now as long as I apply the voltage the motor running holds the weight and move it to the desired position but when current is shut down it drops it. Please help me understand the concept of holding torque or even how much duty cycle will be required to hold the motor in place. I am using external potentiometers for position feedback and have achieved accuracy with it. Also I have cut open the tower pro servo to use its gear mechanism and found it worked nice so I wonder if I could use them too.
I aim to control 8 motors but for the time being struggling with just one. Please help.
And one more question should I consider using L298N IC for the motor control and not build my own H-Bridges.

Thank you, you guys are awesome.

title: How can I get a holding torque on dc motor if I am using an H-bridge?

Answers: 0


body:
I'm using [this](https://www.amazon.com/gp/product/B07VL725T8/ref=ox_sc_act_title_5?smid=A30QSGOJR8LMXA&psc=1) HC-05 Bluetooth module to communicate between my Arduino mega 2560 and my laptop. I am using processing to send the data from my computer to the Arduino.

The module connects nicely and start blinking and when it is paired with my computer it blinks twice every seconds. The problem is that every time the module blinks twice, it ignores the data I am trying to send. Everything else seems to work fine.

Does anyone why this is happening and what I can do to avoid it?

Here is the arduino code:
```
/*
 * bluetooth_rbg_led.ino
 * Uses bluetooth communication to adjust the
 * values of an rgb LED.
 *
 * Sahibjot Singh
 * July 2021
 */

// Servo library to control servos
#include <Servo.h>

// Global variables
Servo servo;
const byte servoPin = 2;
int servoAngle;

// Exeuctes once, at the start
void setup() {
  // Attaches the servo to it's pin
  servo.attach(servoPin);
  servo.write(0);

  // Begins the serial communication with the
  // bluetooth module at pins 18 and 19
  Serial1.begin(9600);
}

// Loops infinitely
void loop() {
  // Reads the values from the serial port
  if (Serial1.available()) {
    servoAngle = Serial1.read();
  }

  // Writes the value to the led pin
  servo.write(servoAngle);
}
```

Here's the processing code:
```
/*
 * bluetooth_rgb_led.pde
 * Simple program to take user input and
 * write it to the serial port.
 *
 * Sahibjot Singh
 * July 2021
 */

// The library needed to write to the serial port
import processing.serial.*;

// Serial variables
Serial port;
int servoAngle;
int userInput;

// Slider variables
int sliderX = 100;
int sliderY = 195;
int sliderWidth = 400;
int sliderHeight = 10;

// Slider rect variables
int sliderRectX = 100;
int sliderRectY = 175;
int sliderRectWidth = 50;
int sliderRectHeight = 50;

// Executes once, at the start
void setup() {
  // Makes the window 600 pixels by 600 pixels
  size(600, 600);

  // Starts serial communication
  port = new Serial(this, "COM7", 9600);
  port.bufferUntil('\n');
}

// Loops infinitely
void draw() {
  // Gets the input from the slider
  if (mousePressed && mouseX > sliderX && mouseX < sliderX + sliderWidth &&
      mouseY > sliderY - 20 && mouseY < sliderY + sliderHeight + 20) {
      sliderRectX = mouseX - sliderRectWidth / 2;
      userInput = sliderRectX - (sliderX - sliderRectWidth / 2);
      servoAngle = (int)map(userInput, 0, 400, 0, 180);
  }

  // Writes the LED value to the serial port
  port.write(char(servoAngle));

  // Clears the window
  clear();
  background(200, 200, 200);

  // Draws the slider
  stroke(30);
  strokeWeight(2);
  fill(150, 150, 150);
  rect(sliderX, sliderY, sliderWidth, sliderHeight, 10);
  fill(255, 0, 0);
  rect(sliderRectX, sliderRectY, sliderRectWidth, sliderRectHeight, 10);

  // Draws the text on the side of the slider
  fill(255, 255, 255);
  textSize(32);
  text("0", 50, 210);
  text("180", 530, 210);

  // Draws the text about the led's brigthness
  fill(0, 0, 255);
  textSize(40);
  text("Servo Angle: " + Integer.toString(servoAngle), 100, 320);
}
```

title: HC-05 bluetooth module stops working when blinking

Answers: 0


body:
After running the Arduino Program on my Windows machine I got the following error my code and error are as below.

Also the COM port was turned grey i.e. disbaled.

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12,11,5,4,3,2);

    void setup()
    {
      lcd.begin(16, 2);
    }

    void loop()
    {
      lcd.print("Hello, World!");
      delay(500);
      lcd.clear();
      delay(500);
    }

It displayed as shown below

> Arduino: 1.8.14 (Windows 10), Board: "Arduino Uno" Sketch uses 1894
> bytes (5%) of program storage space. Maximum is 32256 bytes. Global
> variables use 59 bytes (2%) of dynamic memory, leaving 1989 bytes for
> local variables. Maximum is 2048 bytes. Serial port not selected.

title: Error After running Arduino code on Windows 10

Answers: 1

body:
I know this problem from Arduino Uno clones. You need a proper driver. Here are a few:

* [CH341 serial driver](http://www.wch.cn/download/CH341SER_ZIP.html) (e.g. for Vendor ID 1A86, Product ID 7523)
* [Holtek UART bridge](https://www.holtek.com/productdetail/-/vg/42B534-x) (e.g. for Vendor ID 04D9, Product ID B534)
* [FTDI Drivers](https://ftdichip.com/drivers/vcp-drivers/) (e.g. for Vendor ID 0403, Product ID 60xx)
* [CP210x Drivers](https://www.silabs.com/developers/usb-to-uart-bridge-vcp-drivers) (e.g. for Vendor ID 10C4, Product ID EAxx)
* [Prolific PL2303](http://www.prolific.com.tw/US/ShowProduct.aspx?p_id=225&pcid=41) (e.g. for Vendor ID 067B, Product ID 23xx and AAxx)
* [Microchip MCP2221](https://www.microchip.com/wwwproducts/en/MCP2221) (for Vendor ID 04D8, Product IDs 00xx and 020x)
* [Cypress CDC](https://www.cypress.com/documentation/software-and-drivers/usb-serial-software-development-kit) (e.g. for vendor ID 04B4, Product ID 00xx)

After installing the driver, Windows recognizes the board as a serial port and Arduino IDE will list the serial ports identified by Windows.

Look up the details in device manager. You'll find the IDs in the details of the device named `Device instance path`. It looks like `...VID_xxxx?PID_yyyy...` where xxxx is the vendor ID and yyyy is the product ID. You can also install all drivers, if you don't know which one to choose.

Another (but rare) issue could be that you interrupted the driver setup during Arduino IDE installation. In that case, run the Arduino IDE installation again and make sure you allow the driver installations (for Vendor ID 2341 and 2A03, Product IDs 0043, 0001, 0243).

Any of these suggestions will require administrator permissions.


body:
I saw a tutorial on linking a keypad using one pin, utilising several resistors:
http://razibshahdat.blogspot.com/2018/05/one-single-analog-pin-keypad-control.html

I have this keypad, a 16x2 LCD, a PIR motion detector, and a DHT11 temperature & humidity sensor attached. Furthermore, I have an additional 5V power supply connected to the breadboard for additional power, although I'm not sure if this is required?

All components work as expected in the current configuration when only loading their relevant Arduino template code, except for the keypad. The keypad worked initially when nothing else was connected, but now the resistance values fed to the serial seem to jump, particularly in the first column. I tried to add some resistance between the first input of the keypad matrix and the live wire, which dampens the fluctuations but does not remove them completely.
[![!\[Schematic using Fritzing][1]][1]
I have created a Fritzing sketch to try to make it a bit easier to understand, although I realise that it is still rather chaotic. I am new to Fritzing and Arduino and am still figuring things out.

Here is the isolated code for the keypad, which I am using to find the output values (which, as mentioned, are varying unpredictably), although this was working previously, on a more simple setup:

        // code adapted from: https://www.youtube.com/watch?v=W8ZSeLD90KA
        void setup() {
             Serial.begin(9600);  /* Define baud rate for serial communication */
        }

        void loop() {
          int keyIn;
          int keyVals [16] = {976, 450, 333, 244, 166, 138, 124, 109, 90, 81, 76, 70, 61, 57, 54, 51};
          char keys[16] = {'1','2','3','A','4','5','6','B','7','8','9','C','*','0','#','D'};
          int range = 1;

          keyIn = analogRead(A1);

          String temp = "";

          if (keyIn > 2)
          {
            Serial.print(keyIn);
            for(int i=0; i<=15; i++)
            {
              // The values of the keys changed, that's why the following is commented out
              //if (keyIn >= keyVals[i]-range && keyIn <= keyVals[i]+range)
              //{
              //  temp = keys[i];
              //}
            }
           Serial.print(temp);
           Serial.println("");
           delay(500);
        }
   }

Lastly, I intend for this board to be my master. I then intend to connect a slave through I2C with a DC motor, a servo motor, and an RGB LED. Does this seem feasible?

Please assist if you can.

If you have any additional advice, that too would be highly appreciated - thank you in advance!

  [1]: https://i.stack.imgur.com/ngMHd.png

title: How to stop Single Analog Pin Keypad Matrix (Using Resistors) from receiving Interference from Livewire/other Sensors?

Answers: 1

body:
Your key values are:

```cpp
int keyVals [16] = {976, 450, 333, 244, 166, 138, 124, 109, 90, 81, 76, 70, 61, 57, 54, 51};
```

The formula for the key values given in the [OnewireKeypad library][1] is:

```cpp
float V = (voltage * float( R3 )) / (float(R3) + (float(R1) * float(R)) + (float(R2) * float(C)));
float Vfinal = V * ANALOG_FACTOR;
```

where:
 - voltage = 5 V
 - R1 = 1,000 Ω (the three horizontal ones in the schematic)
 - R2 = 4,700 Ω
 - R3 = 1,000 Ω (the pulldown to GND in the schematic)
 - R = row number 0 to 3
 - C = column number 0 to 3
 - ANALOG_FACTOR = 1023 / 5.0;

The keypad schematic given in the [blogspot article][2] is:

[![Onewire keypad schematic][3]][3]

I put the formula and parameters into an Excel spreadsheet and produced this:

[![Excel spreadsheet of Onewire formula][5]][5]

...which is different to your key values.

Have I misunderstood your circuit setup? Are you doing something different?

  [1]: https://github.com/AndrewMascolo/OnewireKeypad/blob/abdea336ec177d5f483a064c4d9d8577397f1c87/OnewireKeypad.h#L164
  [2]: http://razibshahdat.blogspot.com/2018/05/one-single-analog-pin-keypad-control.html
  [3]: https://i.stack.imgur.com/CGYaP.png
  [4]: https://i.stack.imgur.com/uZFZT.png
  [5]: https://i.stack.imgur.com/tzM2O.png


body:
I have two sunfounder mega2560s. I am using one as an ISP programmer and the other is my target. The programmer has the original bootloader on it. I have placed the ArduinoISP sketch on my programmer and connected LEDs and stuff as here: https://www.arduino.cc/en/pmwiki.php?n=Tutorial/ArduinoISP

I have connected all six pins on my programmer to all six pins on the target. I'm using the ICSP towards the middle of the board on both boards as opposed to the one near the USB cable.

I am trying to place megacore on the target. I have followed the directions here: https://github.com/MCUdude/MegaCore#how-to-install.

I am running Arduino IDE on Windows 10. I am selecting Tools->Board->megacore->Mega2560 and then Tools->Programmer->Arduino as ISP.

I believe all of this setup is correct, so I Click Burn Bootloader. I get the following results:

    Arduino: 1.8.15 (Windows Store 1.8.49.0) (Windows 10), Board: "ATmega2560, Yes (UART0), EEPROM retained, Arduino MEGA pinout, BOD 2.7V, LTO disabled, External 16 MHz"

    avrdude: Version 6.3-20201216

             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/

             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Users\ThomH\Documents\ArduinoData\packages\MegaCore\hardware\avr\2.1.3/avrdude.conf"

             Using Port                    : COM19

             Using Programmer              : stk500v1

             Overriding Baud Rate          : 19200

             AVR Part                      : ATmega2560

             Chip Erase delay              : 9000 us

             PAGEL                         : PD7

             BS2                           : PA0

             RESET disposition             : dedicated

             RETRY pulse                   : SCK

             serial program mode           : yes

             parallel program mode         : yes

             Timeout                       : 200

             StabDelay                     : 100

             CmdexeDelay                   : 25

             SyncLoops                     : 32

             ByteDelay                     : 0

             PollIndex                     : 3

             PollValue                     : 0x53

             Memory Detail                 :

                                      Block Poll               Page                       Polled

               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack

               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------

               eeprom        65    10     8    0 no       4096    8      0  9000  9000 0x00 0x00

               flash         65    10   256    0 yes    262144  256   1024  4500  4500 0x00 0x00

               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00

               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00

               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00

               lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00

               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00

               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : STK500

             Description     : Atmel STK500 Version 1.x firmware

             Hardware Version: 2

             Firmware Version: 1.18

             Topcard         : Unknown

             Vtarget         : 0.0 V

             Varef           : 0.0 V

             Oscillator      : Off

             SCK period      : 0.1 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x000000 (retrying)

    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x000000 (retrying)

    Error while burning bootloader.

    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x000000

    avrdude: Yikes!  Invalid device signature.

             Double check connections and try again, or use -F to override

             this check.

    avrdude done.  Thank you.

I have double checked all of my connections and am powering the target 2560 from a power block on a USB cable.

All research on the web turned up only issues with connections or separate power. Also, I don't know how to use the avrdude from the command prompt to add the `-F` as suggested.

Having tried everything, I'm looking for help here. Thanks.

title: Mega2560 programming megacore avrdude: Device signature = 0x000000

Answers: 1

body:
The answer was that you must connect the reset pin of the target ICSP to pin 10 of the programmer Mega 2560. This was not very clear in the tutorial here: https://www.arduino.cc/en/pmwiki.php?n=Tutorial/ArduinoISP.

This fixed the problem for me, so it was a connection issue.


body: So I have an arduino nano hooked up to hc-06 however every diagram of the hookup wires shows some kind of resistors (1K and 2K, rather high resistances to ignore), and I completely overlooked them. I hooked it up to my computer and it all lit up nice, however I am wondering why those resistors would be included if it still lights up. Am I slowly damaging my equipment over time?

title: How to hook up a HC-06 to Arduino Nano

Answers: 2

body: Welcome! You have a good question but a little light on details. You may have damaged something, there is not enough detail to tell. You state hc-06 but no link to the module you used. They come in 3.3 and 5V models. The resistors are used to translate the voltage down, this you should never do, you are playing with tolerances and if wrong you could destroy the part. If you have a 5V Arduino and a 3.3V HC-06 Get a translator or a 5V HC-06. Lighting up only tells you there is power there. The lights (LEDs) are operational even if the micro is not even on the board. Are you slowly damaging your equipment over time? Possibly I cannot tell with what you have told us. You have not even stated it worked or not and if you even powered up.

body:
The HC-06 itself is a 3.3V device, while the Arduino Uno/Nano is a 5V device. When using electronic devices you need to stay within their corresponding voltage limits, both in power and IO connections.

Most HC-06 boards, that you can buy, will also include a voltage regulator for the power, regulating the 5V from the Arduino down to 3.3V. If you have one of these, you can provide 5V to the HC-06 as power (otherwise you would need to use the 3V pin of the Arduino as power source for the HC-06). But these boards mostly don't have a level translation for the IO lines. And that's where the resistors come in.

The HC-06 has 2 IO lines: RX and TX.

- TX will send data to the Arduino and thus be driven by the HC-06 with its 3.3V. The Arduino runs on 5V, but will still be reading 3.3V as a digital HIGH level. Thus this line is not a problem.
- The RX line will be driven by the Arduino at 5V. Most devices don't like a voltage on their IO pins, that is significantly higher than their working voltage (for power). Thus you can damage the HC-06 receiving hardware, if you directly connect Arduino and HC-06.

To solve that problem you have 2 options for level translation between 3.3V and 5V:

- The proper way would be to use a transistor based level translator you can get these as ready-to-use board for rather cheap (search on the big online platforms for "level translator" or "level converter"), or you can build them yourself using transistors and resistors.
- Or you can use a voltage divider consisting of two resistors. When you connect them like ground -> 2kOhm resistor -> 1kOhm resistor -> TX of the Arduino, you will get the Arduinos TX signal divided down to 3.3V at the point between the two resistors. There you can connect the HC-06 RX pin. This method has drawbacks, since it also acts as parasitic low pass filter. That limits the transmission speed (baud rate). Though you can still easily drive baudrates as high as 115200 baud, which is sufficient in most cases.

So it is not a good option to just omit the resistors. It can lead to damaging the HC-06. You can choose between the above options.


body:
I have connected 4 Grove - RGB LED (WS2813 Mini) to D2,D3,D4,D5 on Grove Base Shield V2.0 for Arduino. How can I control the brightness and color of each LED? At the moment I only know to activated one.

Code:

    #include "Adafruit_NeoPixel.h"
    #define PIN            2
    #define NUMPIXELS      1
    Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

    void setup() {
      pixels.setBrightness(125);
      pixels.begin();
    }

    void loop() {
        pixels.setPixelColor(1, pixels.Color(255,255,255));
        pixels.show();
    }

Thanks

title: Control 4 Grove - RGB LED (WS2813 Mini) color and brightness

Answers: 1

body:
Here is one of the multiple ways possible to address the problem, Basically, use a for loop and iterate the first parameter setPixelColor function to address all the LEDs. Try experimenting [here][1]:

    #include "Adafruit_NeoPixel.h"
    #define PIN            2
    #define NUMPIXELS      4
    Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

    void setup() {
      pixels.setBrightness(125);
      pixels.begin();
    }

    void loop()
    {
      pixels.clear(); // Set all pixel colors to 'off'

      // The first NeoPixel in a strand is #0, second is 1, all the way up
      // to the count of pixels minus one.
      for (int i = 0; i < NUMPIXELS; i++) { // For each pixel...

        // pixels.Color() takes RGB values, from 0,0,0 up to 255,255,255
        // Here we're using a moderately bright green color:
        pixels.setPixelColor(i, pixels.Color(0, random(0,255), 0));

        pixels.show();   // Send the updated pixel colors to the hardware.

        delay(100); // Pause before next pass through loop
      }
    }

here is quick view:

[![enter image description here][2]][2]

>!Since you are using NeoPixels, [here][3] is a list of simulated examples. you can play with the code and make your own projects online.

  [1]: https://wokwi.com/arduino/projects/303848371358007874
  [2]: https://i.stack.imgur.com/Dkw4b.gif
  [3]: https://wokwi.com/arduino/libraries/Adafruit_NeoPixel


body:
I’m trying to send and receive data from my laptop to arduino nano via hc05 Bluetooth for a rocket flight computer. For some reasons which I don’t know, I can send data from processing software using myPort.write() but cannot send a String back from arduino back to processing for telemetry purpose. At some point it was working, then stopped. I tried another code from HowToMechatronics.com and still it didn’t work. I’m using the Serial.println function on Hardware serial.
Pls help

In the processing code, I use all necessary libraries and functions e.g serialEvent(), myPort.bufferUntil(\n), myPort.readStringUntil(‘\n’)![enter image description here](https://i.stack.imgur.com/fKiJY.jpg)

  [1]: https://i.stack.imgur.com/V3Jqn.jpg![enter image description here](https://i.stack.imgur.com/usvad.jpg)![enter image description here](https://i.stack.imgur.com/SR1xB.jpg)![enter image description here](https://i.stack.imgur.com/R3Uog.jpg)

title: Can’t send string from arduino to processing via hc05

Answers: 1

body: Update: After trying numerous codes, I was  sure that it wasn’t a software problem. I then removed the Hc05 module from the circuit, and I was able to put it in AT mode(this means my module is working fine). This leaves only one possible problem I.e the circuit. I used a multimeter to measure the voltage between Hc05 RX and GND. I got 1.8v(but how?). After retracing the connections, I figured out the problem was with the voltage divide I used to step down 5v to 3.3v. I used a 2k Ohm resistor in place of a 1k, and a 1k in place of the 2k resistor. So that’s why I’m getting a voltage of around 1.8v. Turns out 1.8v is too low for Hc05 rx pin to use. After correcting it, everything works fine


body:
I am wiring up a light show for my pickup truck.

I have installed various high power spotlights and light bars into a dedicated relay/fuse box in the engine bay. These relays are wired into a switch panel in the dashboard and work beautifully using the manual switches.

I have subsequently set up a brain...

* An Arduino Uno R3, programmed with 3 different light sequences;
* An 8 bank 5v relay module, driven from Digital Out Pins 6 to 12, each relay on the module fires a separate light (via the existing relays in the engine bay).
* A 4 Channel RF receiver, provides Digital In Pins 3 to 5, to select one of the three sequences, and Digital In Pin 2 Interrupt as a stop/reset button.

I have set this up to start a sequence from an RF button, and programmed the Arduino to fire the relays, including strobe, which was working great on the LED's I attached while testing.

However, when I wire them up to bridge the switches on the dashboard (in turn firing the relays in the engine bay), the Arduino receives a positive signal on INPUT_PULL Pin 2 after a couple of flashes. I think this is something to do with an interference caused by the back EMF from the relay coils in the engine bay, possibly striking the relay module causing it to fire the interrupt pin 2 and causing a reset.

Looks like I need a snubber. I think the best answer is to install a flyback diode across the coil on the relay in the engine bay, but have been trying to figure out how I can wire these up within the blue box, without dismantling the relays installed in the engine bay. I thought maybe I could connect general ground to the manual switch (long route of achieving the same circuit), which helped but after a few more flashes the Arduino gets a signal to reset again. I have lots of diodes and RC Snubber circuits from Amazon which I was going to try, maybe across the Module Relay contacts.

This is a circuit for one of the eight lights.

Please advice how I can reduce this interference using snubbers or some other modification, ideally within the blue box.

Thanks

[![Circuit][1]][1]

UPDATE:

I have managed to get a working setup by removing the resistor and the 5v feed to the RF Relay. Also adding a Diode from earth to the top side of the Module Relay connector. See updated circuit below. Seems to be working, though I'll have a go at adding RC Snubbers as suggested.

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/yRFoz.png
  [2]: https://i.stack.imgur.com/8wrkp.png

title: Back EMF from Relay causing trigger on INPUT pin

Answers: 2

body:
There are two things to tackle in your schematic. First is snubber networks. These are used to aid in the prevention (or rapid extinguishing) of sparks between the contacts of switching gear (like relays). You should attach one across the contacts of each relay. It is these sparks that create most of the "airborne" EMI.

A diode across a relay's coil only deals with "wire-born" EMI (in the form of induced back-EMF) and has no relevance in your circuit due to the galvanic isolation of the first stage relay and the driver circuit in the module.

The second, and more important, thing to deal with is your input pin.  Firstly the built-in pull-up resistor is very very weak. It's usually around 30kΩ, and that is very easy for "airborne" EMI to overcome.  You should avoid using it. Instead an external pull-up resistor of no more than 10kΩ (I'd recommend 1kΩ as a good value) should be used.

Secondly you have a 10kΩ resistor in series with your switching contacts. This will not be helping to get a logic LOW level when the switch contacts are closed since it forms a resistive divider with the pull-up resistor. As it is it happens to *just* work with the internal pull-up, since the internal pull-up is greater than the 10kΩ series resistor. Reduce the pull-up with an external and that will no longer be the case.

That 10kΩ resistor should be removed completely.

Here is your circuit with modifications in red:

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/Wz4K7.png

body:
Here is a general idea of a MOSFET alternative for switching the light on and off.

<a href="https://www.falstad.com/circuit/circuitjs.html?ctz=CQAgjCAMB0l3BWcMBMcUHYMGZIA4UA2ATmIxAUgpABZsKBTAWjDACgA3CmmkbBFN15NsgqlRpUwYqFGhgExBTWJ1IxFGwBO4aSBQpeaPPsOyw8NgHdaNEyMEIeIB1Gu2T-R869uAZrRw4CgmPCbSnvRg0EgwkJpgeBBh4M4pvlS4MNIIrJiQlCEYhPp44WLQvDA0bAGiVAa82IQmjXyC0bGwmgHGpkYIJW2i4DFy8dp8LcGe065S8JDuza34U+UmSzYrM4FSIW7b0xH6g7tbp0NrKGcnFzuGmdMZ7jdDkpd8Am469f3tmW+C0sOj6bT6GWQlgAzgDaJ40LoZBA-ABDAA20IYbEkvBSrhSeVkcUIYHohGgOFkaMx2NxcNcfzsxNgpPJlPoVBpWPc+JGO3myzm-MRgps6W+OxeR08ksR0rhvjeXzErzOSrWLwA5kIVbqduI2AAZJH-PANMxSEDchjUJYADwoGCkhHIhGwvDAztowWCAB1oQA1AMAI1RABdwwwtABPSZ-YaIsDOYH3JN6P7JqpsR00BDkFBgYgUfimQSewRGgCWWoAFuGA2AAwAKEJ4ADqAEoc7QEEhmiXPMWKyAAGIAVyxAb8AHstAHq3WG9D2GhyES2kSvSVeABBLQAE3HVYAdjOAwAHU8BvBsNdwje3PS8AAiqOhtZDM9Rh4D0KsVbhgAxrWPZoMWrB8JAnp4r6E5TtCs7ztCADKAHAbWDDQmwM58OSVSBKQdqwPAZCEIMNyyII2D0NgOF8LwhAEZIRFxPAxQoMQ2CqAg2A5OMpHFBRsT6AxfD0UgTGyCxxZxNxkCEJR0QlA01B0UAA">
Click to simulate in Falstad.

You can click the switch and the H/L input to see how it operates while running the simulation.

The p-channel MOSFET in series with Light 1 could be [FQP27P06][1].

The n-channel MOSFETs are of much lower power.

Using MOSFETs eliminates both the RFI/EMI interference from sparks across relay contacts and the surges/noise from the collapsing electric field of the coils of the relays.

  [1]: https://www.sparkfun.com/products/10349


body: I am new to esp8266 esp-01 and trying to figure out how to use it, in many tutorials on internet, I have seen people have connected Arduino uno's TX pin directly to esp8266 esp-01 without any voltage divider, we know that Arduino TX pin uses 5v, so isn't that will kill the esp-01 which is not 5v tolerant ?

title: Connecting Arduino Uno's TX pin directly to Esp8266 esp-01

Answers: 0


body:
[![enter image description here][1]][1]
So I'm a beginner at Arduino and I have to light up an LED grid to show digits from 0-9. I wrote a bit of code (with the help of some people) and it's like 90% done but there's this ONE problem. I used a switch case to light up the LEDs (so if the user writes a 5 then the switch case will make the LEDs show the digit 5) but it only shows up for like a SPLIT second.Any fixes for this?

```c++
#define ROW_1 3
#define ROW_2 4
#define ROW_3 5
#define ROW_4 6
#define ROW_5 7

#define COL_1 8
#define COL_2 9
#define COL_3 10
#define COL_4 11
#define COL_5 12
#define COL_6 13

const byte rows[] = {
    ROW_1, ROW_2, ROW_3, ROW_4, ROW_5
};

byte Zero[]  = {B011110, B010010, B010010, B010010, B011110};
byte One[]   = {B001100, B000100, B000100, B000100, B000100};
byte Two[]   = {B011110, B000010, B011110, B010000, B011110};
byte Three[] = {B011110, B000010, B001110, B000010, B011110};
byte Four[]  = {B010010, B010010, B011110, B000010, B000010};
byte Five[]  = {B011110, B010000, B011110, B000010, B011110};
byte Six[]   = {B011110, B010000, B011110, B010010, B011110};
byte Seven[] = {B011100, B000100, B000100, B000100, B000100};
byte Eight[] = {B011110, B010010, B011110, B010010, B011110};
byte Nine[]  = {B011110, B010010, B011110, B000010, B011110};

void setColumns(byte b) {
    digitalWrite(COL_1, (~b >> 0) & 0x01);
    digitalWrite(COL_2, (~b >> 1) & 0x01);
    digitalWrite(COL_3, (~b >> 2) & 0x01);
    digitalWrite(COL_4, (~b >> 3) & 0x01);
    digitalWrite(COL_5, (~b >> 4) & 0x01);
    digitalWrite(COL_6, (~b >> 5) & 0x01);
}

void  drawScreen(byte buffer2[]){
    for (byte i = 0; i < 5; i++) {
        setColumns(buffer2[i]);
        digitalWrite(rows[i], HIGH);
        digitalWrite(rows[i], LOW);
    }
}

void setup() {
    Serial.begin(9600);
    for (byte i = 2; i <= 13; i++)
        pinMode(i, OUTPUT);
}

void loop()
{
    int digit;
    if(Serial.available()) {
        digit = Serial.read();
        Serial.println(digit);
    }
    switch (digit) {
        case 48:
            drawScreen(Zero);
            break;
        case 49:
            drawScreen(One);
            break;
        case 50:
            drawScreen(Two);
            break;
        case 51:
            drawScreen(Three);
            break;
        case 52:
            drawScreen(Four);
            break;
        case 53:
            drawScreen(Five);
            break;
        case 54:
            drawScreen(Six);
            break;
        case 55:
            drawScreen(Seven);
            break;
        case 56:
            drawScreen(Eight);
            break;
        case 57:
            drawScreen(Nine);
            break;
    }
}
```

  [1]: https://i.stack.imgur.com/0ue3r.png

title: Stuck In While Loop

Answers: 2

body:
Your drawScreen() function executes very quickly and therefore, lights the LEDs once, very briefly. There are a few choices; here are a couple to try:

One is to write surround the existing `for{}` loop in drawScreen() with another one, to redisplay the digit enough times to make it visible. Experiment with the count of the outer loop starting with, maybe, 50000 (guessing here...), until you have something you like.

Another is to use a `while( Serial.available() == 0 ){}` loop, exactly the same way, which will have the effect of maintaining the displayed digit until you type a new one.

body:
If you want the display to persist, you should call `drawScreen()` on
every loop iteration. You will need a variable for “remembering” what
glyph you should draw. Then, the serial-processing code has only to
update this variable when a new character is received:

```c++
// Remember which glyph we should draw.
byte *glyph = Zero;

void loop() {
    if (Serial.available()) {
        char digit = Serial.read();
        Serial.println(digit);
        switch (digit) {
            case '0': glyph = Zero;  break;
            case '1': glyph = One;   break;
            case '2': glyph = Two;   break;
            case '3': glyph = Three; break;
            case '4': glyph = Four;  break;
            case '5': glyph = Five;  break;
            case '6': glyph = Six;   break;
            case '7': glyph = Seven; break;
            case '8': glyph = Eight; break;
            case '9': glyph = Nine;  break;
        }
    }
    drawScreen(glyph);
}
```

The `glyph` variable is a “pointer to `byte`” because what is what an
array of `byte` [decays to][] when it is assigned to a variable.

[decays to]: https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay


body:
I want to be able to use my HC-05, currently on Serial3 to download code to on my 2560 from a connected android tablet. I'm currently running MegaCore, which has optiboot on it.

I've looked for examples of this and can't find one. Surely someone is doing this and the optiboot documentation says you can do it.

I am currently planning on downloading the hex file, but let me know if there's a better approach.

Thanks.

title: Program a mega2560 from a different Serial port

Answers: 0


body:
I'm interfacing a 3.3 V device (a GPS module with a serial interface) to a 5 V Arduino Nano. The circuit I am using is this:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/1ppnF.png)

<!-- End schematic -->

I don't have the [GPS Module](https://proto-pic.co.uk/product/neo-6m-gps-module-for-arduino-with-large-antenna/) connected at the moment and have added LED D1 and R2 to visualise the Arduino TX signal (which is currently just setting TX GPIO pin high and low on a 1 second cycle). I am measuring the voltage at NODE1 with a DMM.

My understanding is that D3 blocks the 5V high from Arduino TX and then NODE1 is pulled to 3.3 V by R1. When Arduino TX is low (0 V) D3 conducts and pulls NODE2 to 0 V.

What I measure at NODE1 is 3.1 V and 0.8 V. Am I right in thinking that ...

1. The difference between 3.3 and 3.1 is simply the voltage drop across R1 due to the load of my LED and 5 K resistor. The RX input of the GPS module will have some similar effect.

2. The difference between 0.8 V and 0.0 V is mostly due to the forward voltage of the 1N4148? Is there significant contribution from the ATMega328P GPIO port circuitry or elsewhere?

3. This is pretty much OK and as expected.

title: Level shifter with diode - not pulling to zero

Answers: 2

body:
> The difference between 3.3 and 3.1 is simply the voltage drop across R1 due to the load of my LED and 5 K resistor.

Correct.

> The RX input of the GPS module will have some similar effect.

No, the RX will have little to no effect. It is "high impedance" - looking to the circuit like a very small capacitor and very large resistor in series to ground. Negligible to your circuit.

> The difference between 0.8 V and 0.0 V is mostly due to the forward voltage of the 1N4148?

Yes. The datasheet shows the forward voltage can be up to 1V.

> Is there significant contribution from the ATMega328P GPIO port circuitry or elsewhere?

No.

> This is pretty much OK and as expected.

It is.

----

Now my comments:

* You should use a larger pullup and isolate your LED (if you want to keep it) with a BJT or MOSFET so it doesn't load the circuit. That will reduce the current and thus the forward voltage drop over the diode slightly.
* You should use a *Schottky* diode to considerably reduce the forward voltage drop even further. These also switch faster allowing for higher baud rates.

body: That is correct. The most reliable solution is to use a level shifter. They are inexpensive and generally come with more than 1 channel. Use one of the additional channels to drive your led. You are reducing your logic low to 0.32 volts. Typically the threshold is 40% of VCC or 1.32 volts. - 1 volt (worse case) for the 4148 uses almost all of your marjin. That can be reduced even further by loads on the pins. The level shifter is one small board, not a handful of parts to connect which increases your chance of errors but it will help your debugging skills.


body:
I bought the PN5180 module a few weeks back and I am having quite a bit of trouble interfacing it with my Arduino Uno. The library that I am using is ATrappmann PN5180 Library. The link of which is here [https://github.com/ATrappmann/PN5180-Library][1]. I have followed his connections to the letter and have tested each component individually.
The Uno is fine since I have used it extensively for other testing. The Level Shifter is also working fine. The one I am using is similar to [this][2]. The jumper wires are also fine. I have tried working with both examples given in the library and the code gets stuck during the looping. I have attached a screenshot here.

[![enter image description here][3]][3]

I can't seem to figure out where is it going wrong. Is there any way I can use the RC522 Library for setting up the PN5180 reader? I have successfully integrated both RC522 and PN532 NFC readers with Uno but they don't have the required range. I plan on using the reader for localization. It will read the cards and compare it with an array of UID characters to figure out where it is. Any suggestion would be greatly appreciated honestly!

Edit:
Adding the circuit diagram and code so that It is easier to understand

[![enter image description here][4]][4]

Code:

    // NAME: PN5180-Library.ino
    //
    // DESC: Example usage of the PN5180 library for the PN5180-NFC Module
    //       from NXP Semiconductors.
    //
    // Copyright (c) 2018 by Andreas Trappmann. All rights reserved.
    //
    // This file is part of the PN5180 library for the Arduino environment.
    //
    // This library is free software; you can redistribute it and/or
    // modify it under the terms of the GNU Lesser General Public
    // License as published by the Free Software Foundation; either
    // version 2.1 of the License, or (at your option) any later version.
    //
    // This library is distributed in the hope that it will be useful,
    // but WITHOUT ANY WARRANTY; without even the implied warranty of
    // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
    // Lesser General Public License for more details.
    //
    // BEWARE: SPI with an Arduino to a PN5180 module has to be at a level of 3.3V
    // use of logic-level converters from 5V->3.3V is absolutely necessary
    // on most Arduinos for all input pins of PN5180!
    // If used with an ESP-32, there is no need for a logic-level converter, since
    // it operates on 3.3V already.
    //
    // Arduino <-> Level Converter <-> PN5180 pin mapping:
    // 5V             <-->             5V
    // 3.3V           <-->             3.3V
    // GND            <-->             GND
    // 5V      <-> HV
    // GND     <-> GND (HV)
    //             LV              <-> 3.3V
    //             GND (LV)        <-> GND
    // SCLK,13 <-> HV1 - LV1       --> SCLK
    // MISO,12        <---         <-- MISO
    // MOSI,11 <-> HV3 - LV3       --> MOSI
    // SS,10   <-> HV4 - LV4       --> NSS (=Not SS -> active LOW)
    // BUSY,9         <---             BUSY
    // Reset,7 <-> HV2 - LV2       --> RST
    //
    // ESP-32    <--> PN5180 pin mapping:
    // 3.3V      <--> 3.3V
    // GND       <--> GND
    // SCLK, 18   --> SCLK
    // MISO, 19  <--  MISO
    // MOSI, 23   --> MOSI
    // SS, 16     --> NSS (=Not SS -> active LOW)
    // BUSY, 5   <--  BUSY
    // Reset, 17  --> RST
    //

    /*
     * Pins on ICODE2 Reader Writer:
     *
     *   ICODE2   |     PN5180
     * pin  label | pin  I/O  name
     * 1    +5V
     * 2    +3,3V
     * 3    RST     10   I    RESET_N (low active)
     * 4    NSS     1    I    SPI NSS
     * 5    MOSI    3    I    SPI MOSI
     * 6    MISO    5    O    SPI MISO
     * 7    SCK     7    I    SPI Clock
     * 8    BUSY    8    O    Busy Signal
     * 9    GND     9  Supply VSS - Ground
     * 10   GPIO    38   O    GPO1 - Control for external DC/DC
     * 11   IRQ     39   O    IRQ
     * 12   AUX     40   O    AUX1 - Analog/Digital test signal
     * 13   REQ     2?  I/O   AUX2 - Analog test bus or download
     *
     */

    //#define WRITE_ENABLED 1

    #include <PN5180.h>
    #include <PN5180ISO15693.h>

    #if defined(ARDUINO_AVR_UNO) || defined(ARDUINO_AVR_MEGA2560) || defined(ARDUINO_AVR_NANO)

    #define PN5180_NSS  10
    #define PN5180_BUSY 9
    #define PN5180_RST  7

    #elif defined(ARDUINO_ARCH_ESP32)

    #define PN5180_NSS  16
    #define PN5180_BUSY 5
    #define PN5180_RST  17

    #else
    #error Please define your pinout here!
    #endif

    PN5180ISO15693 nfc(PN5180_NSS, PN5180_BUSY, PN5180_RST);

    void setup() {
      Serial.begin(115200);
      Serial.println(F("=================================="));
      Serial.println(F("Uploaded: " __DATE__ " " __TIME__));
      Serial.println(F("PN5180 ISO15693 Demo Sketch"));

      nfc.begin();

      Serial.println(F("----------------------------------"));
      Serial.println(F("PN5180 Hard-Reset..."));
      nfc.reset();

      Serial.println(F("----------------------------------"));
      Serial.println(F("Reading product version..."));
      uint8_t productVersion[2];
      nfc.readEEprom(PRODUCT_VERSION, productVersion, sizeof(productVersion));
      Serial.print(F("Product version="));
      Serial.print(productVersion[1]);
      Serial.print(".");
      Serial.println(productVersion[0]);

      if (0xff == productVersion[1]) { // if product version 255, the initialization failed
        Serial.println(F("Initialization failed!?"));
        Serial.println(F("Press reset to restart..."));
        Serial.flush();
        exit(-1); // halt
      }

      Serial.println(F("----------------------------------"));
      Serial.println(F("Reading firmware version..."));
      uint8_t firmwareVersion[2];
      nfc.readEEprom(FIRMWARE_VERSION, firmwareVersion, sizeof(firmwareVersion));
      Serial.print(F("Firmware version="));
      Serial.print(firmwareVersion[1]);
      Serial.print(".");
      Serial.println(firmwareVersion[0]);

      Serial.println(F("----------------------------------"));
      Serial.println(F("Reading EEPROM version..."));
      uint8_t eepromVersion[2];
      nfc.readEEprom(EEPROM_VERSION, eepromVersion, sizeof(eepromVersion));
      Serial.print(F("EEPROM version="));
      Serial.print(eepromVersion[1]);
      Serial.print(".");
      Serial.println(eepromVersion[0]);

      /*
      Serial.println(F("----------------------------------"));
      Serial.println(F("Reading IRQ pin config..."));
      uint8_t irqConfig;
      nfc.readEEprom(IRQ_PIN_CONFIG, &irqConfig, 1));
      Serial.print(F("IRQ_PIN_CONFIG=0x"));
      Serial.println(irqConfig, HEX);

      Serial.println(F("----------------------------------"));
      Serial.println(F("Reading IRQ_ENABLE register..."));
      uint32_t irqEnable;
      nfc.readRegister(IRQ_ENABLE, &irqEnable));
      Serial.print(F("IRQ_ENABLE=0x"));
      Serial.println(irqConfig, HEX);
      */

      Serial.println(F("----------------------------------"));
      Serial.println(F("Enable RF field..."));
      nfc.setupRF();
    }

    uint32_t loopCnt = 0;
    bool errorFlag = false;

    void loop() {
      if (errorFlag) {
        uint32_t irqStatus = nfc.getIRQStatus();
        showIRQStatus(irqStatus);

        if (0 == (RX_SOF_DET_IRQ_STAT & irqStatus)) { // no card detected
          Serial.println(F("*** No card detected!"));
        }

        nfc.reset();
        nfc.setupRF();

        errorFlag = false;
      }

      Serial.println(F("----------------------------------"));
      Serial.print(F("Loop #"));
      Serial.println(loopCnt++);

    /*
      // code for unlocking an ICODE SLIX2 protected tag
      uint8_t password[] = {0x01, 0x02, 0x03, 0x04}; // put your privacy password here
      ISO15693ErrorCode myrc = nfc.unlockICODESLIX2(password);
      if (ISO15693_EC_OK == myrc) {
        Serial.println("unlockICODESLIX2 successful");
      }
    */

      uint8_t uid[8];
      ISO15693ErrorCode rc = nfc.getInventory(uid);
      if (ISO15693_EC_OK != rc) {
        Serial.print(F("Error in getInventory: "));
        Serial.println(nfc.strerror(rc));
        errorFlag = true;
        return;
      }
      Serial.print(F("Inventory successful, UID="));
      for (int i=0; i<8; i++) {
        Serial.print(uid[7-i], HEX); // LSB is first
        if (i < 2) Serial.print(":");
      }
      Serial.println();

      Serial.println(F("----------------------------------"));
      uint8_t blockSize, numBlocks;
      rc = nfc.getSystemInfo(uid, &blockSize, &numBlocks);
      if (ISO15693_EC_OK != rc) {
        Serial.print(F("Error in getSystemInfo: "));
        Serial.println(nfc.strerror(rc));
        errorFlag = true;
        return;
      }
      Serial.print(F("System Info retrieved: blockSize="));
      Serial.print(blockSize);
      Serial.print(F(", numBlocks="));
      Serial.println(numBlocks);

      Serial.println(F("----------------------------------"));
      uint8_t readBuffer[blockSize];
      for (int no=0; no<numBlocks; no++) {
        rc = nfc.readSingleBlock(uid, no, readBuffer, blockSize);
        if (ISO15693_EC_OK != rc) {
          Serial.print(F("Error in readSingleBlock #"));
          Serial.print(no);
          Serial.print(": ");
          Serial.println(nfc.strerror(rc));
          errorFlag = true;
          return;
        }
        Serial.print(F("Read block #"));
        Serial.print(no);
        Serial.print(": ");
        for (int i=0; i<blockSize; i++) {
          if (readBuffer[i] < 16) Serial.print("0");
          Serial.print(readBuffer[i], HEX);
          Serial.print(" ");
        }
        Serial.print(" ");
        for (int i=0; i<blockSize; i++) {
          if (isprint(readBuffer[i])) {
            Serial.print((char)readBuffer[i]);
          }
          else Serial.print(".");
        }
        Serial.println();
      }

    #ifdef WRITE_ENABLED
      Serial.println(F("----------------------------------"));
      uint8_t *writeBuffer = malloc(blockSize);
      for (int i=0; i<blockSize; i++) {
        writeBuffer[i] = 0x80 + i;
      }
      for (int no=0; no<numBlocks; no++) {
        rc = nfc.writeSingleBlock(uid, no, writeBuffer, blockSize);
        if (ISO15693_EC_OK == rc) {
          Serial.print(F("Wrote block #"));
          Serial.println(no);
        }
        else {
          Serial.print(F("Error in writeSingleBlock #"));
          Serial.print(no);
          Serial.print(": ");
          Serial.println(nfc.strerror(rc));
          errorFlag = true;
          return;
        }
      }
    #endif /* WRITE_ENABLED */

    /*
      // code for locking an ICODE SLIX2 protected tag
      ISO15693ErrorCode myrc = nfc.lockICODESLIX2(password);
      if (ISO15693_EC_OK == myrc) {
        Serial.println("lockICODESLIX2 successful");
        delay(5000);
    */
      delay(1000);
    }

    void showIRQStatus(uint32_t irqStatus) {
      Serial.print(F("IRQ-Status 0x"));
      Serial.print(irqStatus, HEX);
      Serial.print(": [ ");
      if (irqStatus & (1<< 0)) Serial.print(F("RQ "));
      if (irqStatus & (1<< 1)) Serial.print(F("TX "));
      if (irqStatus & (1<< 2)) Serial.print(F("IDLE "));
      if (irqStatus & (1<< 3)) Serial.print(F("MODE_DETECTED "));
      if (irqStatus & (1<< 4)) Serial.print(F("CARD_ACTIVATED "));
      if (irqStatus & (1<< 5)) Serial.print(F("STATE_CHANGE "));
      if (irqStatus & (1<< 6)) Serial.print(F("RFOFF_DET "));
      if (irqStatus & (1<< 7)) Serial.print(F("RFON_DET "));
      if (irqStatus & (1<< 8)) Serial.print(F("TX_RFOFF "));
      if (irqStatus & (1<< 9)) Serial.print(F("TX_RFON "));
      if (irqStatus & (1<<10)) Serial.print(F("RF_ACTIVE_ERROR "));
      if (irqStatus & (1<<11)) Serial.print(F("TIMER0 "));
      if (irqStatus & (1<<12)) Serial.print(F("TIMER1 "));
      if (irqStatus & (1<<13)) Serial.print(F("TIMER2 "));
      if (irqStatus & (1<<14)) Serial.print(F("RX_SOF_DET "));
      if (irqStatus & (1<<15)) Serial.print(F("RX_SC_DET "));
      if (irqStatus & (1<<16)) Serial.print(F("TEMPSENS_ERROR "));
      if (irqStatus & (1<<17)) Serial.print(F("GENERAL_ERROR "));
      if (irqStatus & (1<<18)) Serial.print(F("HV_ERROR "));
      if (irqStatus & (1<<19)) Serial.print(F("LPCD "));
      Serial.println("]");
    }

Edit 2:

So i tried one of the forks of ATrappmann library. the link is [https://github.com/tueddy/PN5180-Library][5], and the problem of the code stalling at loops have been resolved. But now, the reader won't read any of my cards :(

  [1]: https://github.com/ATrappmann/PN5180-Library
  [2]: https://www.google.com/url?sa=i&url=https://www.daraz.pk/products/logic-shifter-i196276735.html&psig=AOvVaw1dmpmv3R7k6qsGQNMAiIqE&ust=1626208643777000&source=images&cd=vfe&ved=0CAoQjRxqFwoTCJivprWx3vECFQAAAAAdAAAAABAD
  [3]: https://i.stack.imgur.com/GI5hj.png
  [4]: https://i.stack.imgur.com/yyUhZ.png
  [5]: https://github.com/tueddy/PN5180-Library

title: Trouble interfacing PN5180 RFID Module with Arduino Uno

Answers: 0


body:
I'm currently working on project to operate three motors while sending accelerometer value to computer via bluetooth module. I want the motor operation and value transmission to work seperatly. But when motors operate, the transmission stops. I used the ArduinoThread library, but since I don't understand all the usage, it still has some kind of delay. Plus, I want two of the motors work first(just once) and the other works after specific time(also just once). But the first setup of two motors and the latter doesn't work. Please check my code and give me some advice. Thank you!

    #include <Wire.h>
    #include <SoftwareSerial.h>
    #include <Servo.h>
    #include <Thread.h>

    const int MPU_addr=0x68;  // MPU-6050 I2C address
    int16_t AcX,AcY,AcZ,GyX,GyY,GyZ;

    SoftwareSerial BTSerial(3,2);   // TX,RX

    Servo servoMini;
    Servo servoUp;
    Servo servoDown;
    int pinMini = 6;
    int pinUp = 9;
    int pinDown = 10;
    int i = 1;
    unsigned long tPrev, tNow = 0;

    Thread myThread = Thread();

    void readAcc(){
      Wire.endTransmission(true);
      Wire.beginTransmission(MPU_addr);
      Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
      Wire.endTransmission(false);
      Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers   // 14bit??

      AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
      //AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
      //AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
      //GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
      //GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
      //GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)

      BTSerial.println(AcX);   // 16bit
      Serial.println(AcX);

      // delay(25);
    }

    void setup(){
      // I2C
      Wire.begin();
      Wire.beginTransmission(MPU_addr);
      Wire.write(0x6B);  // PWR_MGMT_1 register
      Wire.write(0);     // set to zero (wakes up the MPU-6050)

      // serial, bluetooth
      Serial.begin(9600);
      BTSerial.begin(9600);
      Serial.println("CLEARDATA");
      Serial.println("ONLY AcX");

      // servo
      servoMini.attach(pinMini);
      servoUp.attach(pinUp);
      servoDown.attach(pinDown);
      pinMode(pinMini, OUTPUT);
      pinMode(pinUp, OUTPUT);
      pinMode(pinDown, OUTPUT);
      servoMini.write(145);
      servoUp.write(180);
      servoDown.write(0);

      // Thread(MPU-6050)
      myThread.onRun(readAcc);
      myThread.setInterval(20);
    }

    void loop(){
      while(i == 1){
        tNow = millis();
        myThread.run();

        servoUp.attach(pinUp);
        servoDown.attach(pinDown);
        servoUp.write(60);
        servoDown.write(120);

      if((tNow - tPrev)>= 1000){
        servoMini.attach(pinMini);
        servoMini.write(180);
        i++;
      }
    }

      servoMini.detach();
      myThread.run();
    }

title: arduino acclerometer with servo motor

Answers: 2

body:
I think you want something like [Blink Without Delay][1], but with more tasks.

Here is my interpretation of your description which extends Blink Without Delay by adding three more tasks to:
 - read the accelerometer
 - perform "just once"
 - perform "also just once"

I've added several `Serial.print()` statements to give a running commentary on what's occurring for debug purposes.

```cpp
#include <Wire.h>
#include <SoftwareSerial.h>
#include <Servo.h>

SoftwareSerial BTSerial(3, 2);  // TX, RX

Servo servoMini;
Servo servoUp;
Servo servoDown;

const byte pinMini = 6;
const byte pinUp = 9;
const byte pinDown = 10;

// Timings for each event.
const unsigned long READ_ACCELEROMETER_INTERVAL = 50;
const unsigned long JUST_ONCE_INTERVAL = 1000;
const unsigned long ALSO_JUST_ONCE_INTERVAL = 2000;
const unsigned long LED_BLINK_INTERVAL = 200;

// Keep track of timestamps for each event.
unsigned long previous_blink_timestamp;
unsigned long previous_accelerometer_timestamp ;
unsigned long just_once_timestamp;
unsigned long also_just_once_timestamp;

// Flags to indicate completion of "just once" events.
bool just_once = false;
bool also_just_once = false;

// State of blinking LED.
bool led_state = false;

void setup()
{
    Serial.begin(115200);
    Serial.println("\n\nAccelerometer with Servo Test\n");

    // For blink without delay.
    pinMode(LED_BUILTIN, OUTPUT);

    // servo
    servoMini.attach(pinMini);
    servoUp.attach(pinUp);
    servoDown.attach(pinDown);

    // Perform first move.
    servoMini.write(145);
    servoUp.write(180);
    servoDown.write(0);

    // Initialise all timestamps with the same value with a single call to millis().
    previous_blink_timestamp =
    previous_accelerometer_timestamp =
    just_once_timestamp =
    also_just_once_timestamp = millis();
}

void loop()
{
    unsigned long current_timestamp = millis();

    //
    // TASK 1: Read accelerometer.
    //
    if (current_timestamp - previous_accelerometer_timestamp >= READ_ACCELEROMETER_INTERVAL)
    {
        // Read accelerometer.
        Serial.print("Reading accelerometer... ");
        readAcc();
        previous_accelerometer_timestamp += READ_ACCELEROMETER_INTERVAL;
        Serial.println("Done.");
    }

    //
    // TASK 2: Just once.
    //
    if (!just_once && current_timestamp - just_once_timestamp >= JUST_ONCE_INTERVAL)
    {
        // Perform second move.
        Serial.print("Running just once... ");
        servoUp.write(60);
        servoDown.write(120);
        just_once = true;
        Serial.println("Done.");
    }

    //
    // TASK 3: Also just once.
    //
    if (!also_just_once && current_timestamp - also_just_once_timestamp >= ALSO_JUST_ONCE_INTERVAL)
    {
        // Perform third move.
        Serial.print("Running also just once... ");
        servoMini.write(180);
        also_just_once = true;
        Serial.println("Done.");
    }

    //
    // TASK 4: Blink without delay.
    //
    if (current_timestamp - previous_blink_timestamp >= LED_BLINK_INTERVAL)
    {
        // Toggle LED state.
        led_state = !led_state;
        digitalWrite(LED_BUILTIN, led_state);
        previous_blink_timestamp += LED_BLINK_INTERVAL;
    }
}
```

[1]: https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay

body:
Here's the final form of my project.
I've added motor detach function since it still shivers a bit.

```#include <Wire.h>
#include <SoftwareSerial.h>
#include <Servo.h>

const int MPU_addr=0x68;  // MPU-6050 I2C address
int16_t AcX,AcY,AcZ,GyX,GyY,GyZ;

SoftwareSerial BTSerial(3, 2);  // TX, RX

Servo servoMini;
Servo servoUp;
Servo servoDown;

const byte pinMini = 6;
const byte pinUp = 9;
const byte pinDown = 10;

// Timings for each event.
const unsigned long ACC_INTERVAL = 50;
const unsigned long INTERVAL = 1000;
const unsigned long INTERVAL_FIN = 2000;
const unsigned long GRIPPER_INTERVAL = 2000;
const unsigned long GRIPPER_INTERVAL_FIN= 3000;
const unsigned long LED_INTERVAL = 250;

// Keep track of timestamps for each event.
unsigned long prev_led_timestamp;
unsigned long prev_acc_timestamp;
unsigned long servo_timestamp;
unsigned long servo_timestamp_fin;
unsigned long gripper_timestamp;
unsigned long gripper_timestamp_fin;

// Flags to indicate completion of "just once" events.
bool servo = false;
bool servo_fin = false;
bool gripper = false;
bool gripper_fin = false;

// State of blinking LED.
bool led_state = false;

void readAcc(){
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers   // 14bit??

  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  //AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  //AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  //GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  //GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  //GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)

  BTSerial.println(AcX);   // 16bit
  //Serial.println(AcX);
}

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

  // For blink without delay.
  pinMode(LED_BUILTIN, OUTPUT);

  // I2C
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);

  // servo
  servoMini.attach(pinMini);
  servoUp.attach(pinUp);
  servoDown.attach(pinDown);

  // Perform first move.
  servoMini.write(145);
  servoUp.write(180);
  servoDown.write(0);

  // Initialise all timestamps with the same value with a single call to millis().
  prev_led_timestamp =
  prev_acc_timestamp =
  servo_timestamp = servo_timestamp_fin =
  gripper_timestamp = gripper_timestamp_fin = millis();
}

void loop(){
  unsigned long current_timestamp = millis();

  // TASK 1: Read acc.
  if (current_timestamp - prev_acc_timestamp >= ACC_INTERVAL){
    // Read acc.
    readAcc();
    prev_acc_timestamp += ACC_INTERVAL;
  }

  // TASK 2: Just once.
  if (!servo && current_timestamp - servo_timestamp >= INTERVAL)  {
    //Serial.print("Running just once... ");
    servoUp.attach(pinUp);
    servoDown.attach(pinDown);
    servoUp.write(60);
    servoDown.write(120);
    // retract speed control
    servo = true;
    //Serial.println("Done.");
  }
  if (!servo_fin && current_timestamp - servo_timestamp_fin >= INTERVAL_FIN){
    servoUp.detach();
    servoDown.detach();
    servo_fin = true;
  }

  // TASK 3: Also just once.
  if (!gripper && current_timestamp - gripper_timestamp >= GRIPPER_INTERVAL)  {
    // Perform third move.
    //Serial.print("Running also just once... ");
    servoMini.write(180);
    gripper = true;
    //Serial.println("Done.");
  }
  if (!gripper_fin && current_timestamp - gripper_timestamp_fin >= GRIPPER_INTERVAL_FIN){
    servoMini.detach();
    gripper_fin = true;
  }

  // TASK 4: Blink without delay.
  if (current_timestamp - prev_led_timestamp >= LED_INTERVAL){
    // Toggle LED state.
    led_state = !led_state;
    digitalWrite(LED_BUILTIN, led_state);
    prev_led_timestamp += LED_INTERVAL;
  }
}


body:
I am reading a value from an encoder "volume knob" and I have a function called void fn_on were I am having sum int to zero and counting until it reaches the set value of volume. I tried posting to serial but my sum counter does not work. I want my relay to run "volume" number of times until sum > volume in my function "fn_on" I believe I am not storing or updating my volume correctly. Thank you for taking the time to look through this.

```cpp
#include <LiquidCrystal_I2C.h>
#include <Rotary.h>
#include <LCD_I2C.h>

LiquidCrystal_I2C lcd(0x27, 20, 4);

/* Rotary Encoder - Polling Example

The circuit:
  encoder pin A to Arduino pin 2
  encoder pin B to Arduino pin 3
  encoder ground pin to ground (GND)
*/
#define PINA 2
#define PINB 3
#define RelayPin 8

const char PUSHB = 5;
bool pressed = false;
long volume = 0; // this may not set the volumue

Rotary r = Rotary(2, 3);

void setup()
{
 Serial.begin(115200); // setup Pin modes
 pinMode(PUSHB, INPUT);
 r.begin(true);
 lcd.init();
 lcd.backlight();
 lcd.setCursor(0, 3);
 lcd.print(volume);
 digitalWrite(PINA, HIGH); // enable pull-ups
 digitalWrite(PINB, HIGH);
 // digitalWrite (PUSHB, HIGH);
 pinMode(RelayPin, OUTPUT); // Relay Pin ini
}

void loop()
{
 bool currentState = digitalRead(PUSHB);

 if (currentState == pressed)
 {
  Serial.println("Pressed");

  while (digitalRead(PUSHB) == pressed)
  {
   // do nothing
  }
 }

 unsigned char result = r.process();

 if (result)
 {
  // Serial.println(result == DIR_CW ? "Right" : "Left");
  if (result == DIR_CCW)
  {
   volume = volume - 1000; // change ++ to mulpes of 1000
   Serial.println(volume);
   lcd.setCursor(0, 3);
   lcd.print(volume);
   lcd.print("                                ");

   int sum = 0;
   for (sum = 1; sum < volume; sum++ && currentState = true)
   {
    lcd.setCursor(0, 2);
    lcd.print(sum);
    digitalWrite(RelayPin, LOW); // run test
    delay(3000);
    digitalWrite(RelayPin, HIGH); // run test
    delay(3000);
    digitalWrite(RelayPin, LOW); // run test
    delay(3000);
   }
  }
  else
  {
   volume = volume + 1000; // change volume++ to mulpes of 1000
   // initialize display_menu to 1st line
   lcd.setCursor(0, 3);
   lcd.print(volume);
   lcd.print("                                 ");
  }
 }
}
```

title: Relay not triggering from loop function. Variable "volume" not updating after encoder is turned to value?

Answers: 1

body:
I believe the issue is that you're setting your encoder pins high with `digitalWrite()`.  Those pins need to be configured as inputs for the interrupts to work correctly.  This will be handled by the encoder library when you call `r.begin(true)`.  In fact, `true` in that call tells the library to enable the pullups for you.

Removing those lines should fix your issue.