text:
MPU 6050 only reads 0 in output
I am new to using MPU 6050. I am stuck at a basic code of getting readings from the sensor. The code I used is attached below. Its the one with GY 521 breakout board. Concluding that my sensor is broken I have changed sensor and now using the third one. Still no luck. FYI I have run the i2c scanner code to check whether arduino(nano) can detect the sensor. The code responds to all the sensors I tried. I have no clue what I am doing wrong. If someone could provide some suggestions it would be helpful
    MPU6050 Triple Axis Gyroscope & Accelerometer. Simple Gyroscope Example.
    Read more: http://www.jarzebski.pl/arduino/czujniki-i-sensory/3-osiowy-zyroskop-i-akcelerometr-mpu6050.html
    GIT: https://github.com/jarzebski/Arduino-MPU6050
    Web: http://www.jarzebski.pl
    (c) 2014 by Korneliusz Jarzebski
*/

#include <Wire.h>
#include <MPU6050.h>

MPU6050 mpu;

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

  // Initialize MPU6050
  Serial.println("Initialize MPU6050");
  while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
  {
    Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
    delay(500);
  }

  // If you want, you can set gyroscope offsets
  // mpu.setGyroOffsetX(155);
  // mpu.setGyroOffsetY(15);
  // mpu.setGyroOffsetZ(15);

  // Calibrate gyroscope. The calibration must be at rest.
  // If you don't want calibrate, comment this line.
  mpu.calibrateGyro();

  // Set threshold sensivty. Default 3.
  // If you don't want use threshold, comment this line or set 0.
  mpu.setThreshold(3);

  // Check settings
  checkSettings();
}

void checkSettings()
{
  Serial.println();

  Serial.print(" * Sleep Mode:        ");
  Serial.println(mpu.getSleepEnabled() ? "Enabled" : "Disabled");

  Serial.print(" * Clock Source:      ");
  switch(mpu.getClockSource())
  {
    case MPU6050_CLOCK_KEEP_RESET:     Serial.println("Stops the clock and keeps the timing generator in reset"); break;
    case MPU6050_CLOCK_EXTERNAL_19MHZ: Serial.println("PLL with external 19.2MHz reference"); break;
    case MPU6050_CLOCK_EXTERNAL_32KHZ: Serial.println("PLL with external 32.768kHz reference"); break;
    case MPU6050_CLOCK_PLL_ZGYRO:      Serial.println("PLL with Z axis gyroscope reference"); break;
    case MPU6050_CLOCK_PLL_YGYRO:      Serial.println("PLL with Y axis gyroscope reference"); break;
    case MPU6050_CLOCK_PLL_XGYRO:      Serial.println("PLL with X axis gyroscope reference"); break;
    case MPU6050_CLOCK_INTERNAL_8MHZ:  Serial.println("Internal 8MHz oscillator"); break;
  }

  Serial.print(" * Gyroscope:         ");
  switch(mpu.getScale())
  {
    case MPU6050_SCALE_2000DPS:        Serial.println("2000 dps"); break;
    case MPU6050_SCALE_1000DPS:        Serial.println("1000 dps"); break;
    case MPU6050_SCALE_500DPS:         Serial.println("500 dps"); break;
    case MPU6050_SCALE_250DPS:         Serial.println("250 dps"); break;
  }

  Serial.print(" * Gyroscope offsets: ");
  Serial.print(mpu.getGyroOffsetX());
  Serial.print(" / ");
  Serial.print(mpu.getGyroOffsetY());
  Serial.print(" / ");
  Serial.println(mpu.getGyroOffsetZ());

  Serial.println();
}

void loop()
{
  Vector rawGyro = mpu.readRawGyro();
  Vector normGyro = mpu.readNormalizeGyro();

  Serial.print(" Xraw = ");
  Serial.print(rawGyro.XAxis);
  Serial.print(" Yraw = ");
  Serial.print(rawGyro.YAxis);
  Serial.print(" Zraw = ");
  Serial.println(rawGyro.ZAxis);

  Serial.print(" Xnorm = ");
  Serial.print(normGyro.XAxis);
  Serial.print(" Ynorm = ");
  Serial.print(normGyro.YAxis);
  Serial.print(" Znorm = ");
  Serial.println(normGyro.ZAxis);

  delay(10);
}

Could you provide a schematic of how you connected everything together? The MPU-6050 is a 3.3 V device while the Arduino is 5 V. Also the GY 521 has an onboard 3.3 V regulator that should be supplied with 5 V rather than 3.3 V. More info on Arduino Plaground and schematic diagram

I hope it is useful for debugging ...
Only a sketch I found (here), not remembering if I have tested ...
// MPU-6050 Short Example Sketch
// By Arduino User JohnChi
// August 17, 2014
// Public Domain
#include<Wire.h>
const int MPU_addr=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
void setup(){
  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);
  Serial.begin(9600);
}
void loop(){
  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
  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)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_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)
  Serial.print("AcX = "); Serial.print(AcX);
  Serial.print(" | AcY = "); Serial.print(AcY);
  Serial.print(" | AcZ = "); Serial.print(AcZ);
  Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
  Serial.print(" | GyX = "); Serial.print(GyX);
  Serial.print(" | GyY = "); Serial.print(GyY);
  Serial.print(" | GyZ = "); Serial.println(GyZ);
  delay(333);
}

There is also a long example sketch ...

You do not tell us what is the problem so my guess is address or level.
If you get "Could not find a valid MPU6050 sensor, check wiring!" this is an address problem. By default MP6050 uses x068 as I2C address. If you have something else connected to the bus, there might be a conflict. If so, connect AD0 to 3.3V (pull-up with a 2.2kOhms resistor) to set address to 0x69 (use I2C scanner in /example/wire to make sure).
If you see zeros, this might be a logic level problem:
To elaborate on the previous answer, the MP6050 is a 3.3V device. The GY 521 circuit has a voltage regulator (5V->3.3V) bUt on output it still uses 3.3V TTL logic level. With some noise, bad contacts or long wires, the Arduino may fail to read the I2C properly. Had similar problems, solved using a bidirectional logic level shifter between a Uno and the MPU6050. You can get pre-assembled 4-channels board (same size as GY521 board) for ~ 1US$. I hope this helps


text:
STM32 "blue pill" st-flash error
I am trying to flash STM32 "blue pill" using arduino IDE as mentioned in the link https://www.onetransistor.eu/2017/11/stm32-bluepill-arduino-ide.html#no-bootloader
Basically using MX linux as OS.
The following is the response
user@mx:~/.arduino15/packages/stm32duino/tools/stm32tools/2021.5.31/linux/stlink
$ ./st-flash --reset write ~/Desktop/generic_boot20_pc13.bin 0x8000000
2021-07-27T09:20:21 INFO src/common.c: Loading device parameters....
2021-07-27T09:20:21 INFO src/common.c: Device connected is: F1 Medium-density device, id 0x20036410
2021-07-27T09:20:21 INFO src/common.c: SRAM size: 0x5000 bytes (20 KiB), Flash: 0x20000 bytes (128 KiB) in pages of 1024 bytes
2021-07-27T09:20:21 INFO src/common.c: Attempting to write 22268 (0x56fc) bytes to stm32 address: 134217728 (0x8000000)
Flash page at addr: 0x08005400 erased
2021-07-27T09:20:21 INFO src/common.c: Finished erasing 22 pages of 1024 (0x400) bytes
2021-07-27T09:20:21 INFO src/common.c: Starting Flash write for VL/F0/F3 core id
2021-07-27T09:20:21 ERROR src/common.c: unknown coreid, not sure what flash loader to use, aborting!: 2ba01477
2021-07-27T09:20:21 WARN src/common.c: Failed to write flash loader to sram!
2021-07-27T09:20:21 ERROR src/common.c: init_flash_loader() == -1
stlink_fwrite_flash() == -1
user@mx:~/.arduino15/packages/stm32duino/tools/stm32tools/2021.5.31/linux/stlink
$

I am not finding any src/common.c program in any of the subfolders, hence unable to dwell into details of the unknown core ID error
STlink V2 is providing proper response for st-info --probe as below
user@mx:~/.arduino15/packages/stm32duino/tools/stm32tools/2021.5.31/linux/stlink
$ ./st-info --probe
Found 1 stlink programmers
 serial: 4a3307000e144c37514d4e00
openocd: "\x4a\x33\x07\x00\x0e\x14\x4c\x37\x51\x4d\x4e\x00"
  flash: 131072 (pagesize: 1024)
   sram: 20480
 chipid: 0x0410
  descr: F1 Medium-density device
user@mx:~/.arduino15/packages/stm32duino/tools/stm32tools/2021.5.31/linux/stlink

Please let me know if you can find any method resolve this error

I recommend you https://www.stm32duino.com

Sure. Thanks for the website.

source: Stack Exchange

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

sort: votes


text:
Arduino Pull-Down Resistors
I'm building what I thought was a simple Arduino Nano project... right up until it caught fire!
I am a long-time reader of stack exchange and I always find the answers to my questions somewhere on Google, but this seems to be a bit of a head scratcher.
The project is a 4 pin 7 segment LED screen with a timer that counts when Analog pin 0 receives a voltage signal of ~2.5-5v.
Testing the project worked as expected, but when I soldered everything together, I was getting static or white noise from the Analog pin with no voltage being supplied.
I figured I needed a Pull-Down resistor to keep the Analog pin grounded until it received a voltage signal to get rid of any interference.
I connected a 220ohm resistor DIRECTLY from GND and DIRECTLY to Analog Pin 0 and connected the voltage signal wire to Pin 0 as well.
When I actually tested the hardware while connected to the car battery, that's when it shorted out and caused a mini fire.
I was able to read the voltage with my multimeter before the chip burnt out, I was reading ~15.5v total. I'm guessing it's the car battery plus the input voltage on Pin 0.
I only do clean and precise soldering, so there were no unaccounted for connections.
I'm unsure if the issue was too many volts running through the Nano altogether or because I don't really understand how the Pull-Down resistor works and messed that up.
Please help me understand what the issue is and what I can do for a solution.
Thank you.

Arduino Nano accept up to 12V.
On which pin have you connected the battery? What voltage are you measuring now on the battery? Have you connected the grounds of the car battery with the ground of the input signal?

Could you manage to draw a schematic? That will make things a lot clearer probably! Did you connect the battery minus to the Arduino Vcc (as that is the only way the voltages could “add up” as you said)? And how did you come up with a value of 220 Ohms (which is quite a low value for a pull down resistor)?

I've added a schematic. For some reason one line of text didn't save. The pink wire is CLK, but I don't think that's relevant to my original question. The 220ohm was a suggestion someone made to me, but I have no idea. I haven't dealt with resistors before.

What is that external 5V signal? Did you connect it with just one wire? And what exactly did burn? Something on the Arduino? If yes, how much current does the LED display draw? You might overload the voltage regulator. And a pulldown resistor as small as 1 to 4kOhm is already considered very strong. Normally you would use something like 10kOhm

The external 5v is a device which is also connected to the vehicle battery, so it's on the same circuit. Whenever it's powered on, it gets 5v which is my signal. What the LED actually draws, I'm not sure, but the specs say 5v@220mA. The part of the Arduino that burnt was whatever that chip is on the flip side of the processor. I'll try with a 10K resistor and see if it works.

the +5 V and GND on the device can easily be +12 V and +7 V when referenced to the vehicle battery negative

What are the brown lines on your drawing?

@Eli So you get 7V x 220mA = 1.4W of power as heat in the linear voltage regulator for the display alone. I currently don't have the real numbers, but I think this is too much. You need to switching voltage regulator, which is way more efficient. The linear voltage regulator on the Arduino just dissipates the excess voltage as heat.

Are you able to post a photo of the burnt out results?  Our describe exactly what smoked?

You violated the voltage input specification of A0 by a lot. What happened is what I would expect. The input protection diode on A0 conducted the battery voltage (- the protection diode drop) into the VCC of the Nano, this overvoltage fried just about all semiconductors and possibly several of the passive components on the board. It sounds like they do what they do when abused and they let the smoke out destroying the Nano and possible several other components. Hopefully this explains what happened. If you had connected the resistor between A0 and the battery it might have survived.

Input power
Car power systems operate between 13 and 15 volts when the car is running. Might be too high for the voltage regulator on the Nano. Mine is a AMS1117 which goes up to 15v. Sounds like that's what fried based on your description. Some fail closed circuit, so may have exposed the ATMega to 14v. There's some alternative voltage regulators with the same footprint that will go up to 20v or more input, look for one of those. SOT-223 footprint.
Button
The Nano/ATMegs has internal pullups. I'd use those; connect the one side of your button to ground rather than 5v, and the other to the Nano digital input. In your code, activate on LOW rather than HIGH. Then you can skip your external pullup.
Pullups
220 ohms is a very strong pulldown for the 5v signal. It will be seeing .11 watts of power dissipation. Use something higher like 10K or 100K. Put a 1K resistor on the 5v signal to limit it's current. You're Arduino is only sensing the voltage, so with a 10K to GND and 1K from 5v signal, the resistor divider will signal 4.5v, plenty for your Nano to detect "HIGH".

What do you do when you get a double battery jump. How about load dump?

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


text:
I am trying to automate my sun shade on my back porch with a Nema17 Stepper motor
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.

    // 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;
    }

  }
}

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.
...

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!

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.


text:
Save Watchdog ISR Return Address in EEPROM
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?

What architrcture?

AVR… Arduino Pro Mini atmega328p

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:
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

Well, that was easy… thanks! Next exercise is to figure out where that is in the code.

I didn't articulate that very well… next exercise is to find out where that return address is in the code (or in space) to get a clue what went wrong.

@EricNelson: Disassemble the .elf file using avr-objdump -SC.

@EdgarBonet YES!! Oh, man, does this ever take me back to the 90s.  Poring over disassembled code, counting cycles, rearranging code to see if we can eke out a few more whatevers per second to win a benchmark.

"addr2line" might be a handy tool, too.


text:
Can Arduino UNO be used to emulate a PS4 joystick?
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

I have just edited it. I want to know if there is a library that i can use to emulate a PS4 joystock using an Arduino UNO

Tie a string to the joystick and the sides of the steering wheel. So that when you turn the wheel, it pulls the thumbstick to left/right? Best case you can use an Arduino to replace the actual thumbsticks on a controller, by taking it apart.

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:

Implementing the USB code properly with custom drivers defined by Sony.
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.


text:
How to send data from esp-01 Wi-Fi module to arduino
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);
  }
}

see the basic examples in IDE examples menu

Which one should I see?

all of them .... think about this in your code what will be the state of the LED when value1 is not equal to 1?

if the value not equal to 1, LED will be off

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

Thank you for your help.

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.


text:
Serial communication problems
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;
}

You're turning your heap into swiss cheese with all that String abuse.

And here is the obligatory Majenko blog entry about the Evils of Arduino Strings.

add the serial output to your question.


text:
Global Variable not updating…
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;
  }
}

Had you tried to print and test to output of map function?

And why is it a float if its value can only be an integer from 1-8?

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:

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:
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:

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.

Thanks Edgar… I will rewrite this after lunch and feedback…

Fabian… at first I did when I was getting the led routing working. Then I stopped monitoring that function… probably why I may have missed it.

Dave, because I was grasping at straws rather doing what I doing now, asking for help, which is way more rational… I’ll fix that code asap. :-)


text:
Can I get the hex file from an Arduino without the .ino code
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.)

cool story bro, show me.

the hex file is the code. your MCU runs. if I had the hex file, I wouldnt need the source code, I could upload it to the MCU. I can do that with avrdude, or whatever, Im sure arduno code can do it too.

here is some talk about it https://electronics.stackexchange.com/questions/61079/is-it-possible-to-extract-code-from-an-arduino-board

lol nice. Here is some talk about it, no solution, and a link to a 404d page. I think I almost have it figured out one my own, though. ... I think I can get avrdude to do it.

yes, avrdude is the program ... there should be command line help that may include an example

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

I just thought of another way to do it, using an ardunio as an ISP, (in circiut programmer? wut?) but Im not sure it would work right using this board, and my other authentic Ardunio boards. and it wouldnt give you a file, you would simply make a clone.

You might also need to read the mcu's eeprom using the same command, but with eeprom:r:eeprom.eep:i (I believe).


text:
Push button unexpected increment/decrement. I'm using attachInterrupt
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.

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.

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.

Thank you for the solution.


text:
How can I get a holding torque on dc motor if I am using an H-bridge?
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.

While you can break the motor by essentially connecting both ends of the coil through the driver, that breaking might not be enough. It might need active driving of the motor to keep the position. So how are you currently moving to a set position? A common way of achieving such things would be implementing PID control in your software. Please show us your current code.

Correct me (anyone) if this is over simplistic, but I always assumed robots were driven by either stepper motors or motors with feedback (servos). For steppers it is unnecessary to know the torque as long as you exceed it.  For servos I would think you need to constantly monitor if the motor is in the desired position and use the H-Bridge to return to the desired position if necessary. I have not seen a situation where you can remove power with out a mechanical break system to hold the position.

@st2000 I understand your point and that is the reason why I said I am using potentiometer to get the position feedback.

@chrisl I had tried the breaking mechanism by short circuiting the wires of the motors but the force was of more intensity.
Should I consider a gearbox for further reduction, I have an option to 3d print the mechanism.

Dynamic breaking is likely not going to stop a motor as it only generates a stopping force when objects are in motion.  This is the reason a lone locomotive is more dangerous (only or mostly relies on dynamic breaking) then an entire train (now the engineer has air breaks on all the cars attached to the train).  So, if you are going to cut the power, you likely need a mechanical break.  Posting in this forum usually indicates a low budget project.  So I would consider a small amount of friction applied to the motor shaft so that you can take advantage of the gear box multiplication effect.

Do you really need to cut power? Then you definitely need mechanical braking. Otherwise just keep driving the motor actively. Please show your code


text:
HC-05 bluetooth module stops working when blinking
I'm using this 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);
}


text:
Error After running Arduino code on Windows 10
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.

did you connect the Arduino to PC?

So you're saying there's nothing displayed under "Tools->Ports"?

Yes I connected to PC.  Under tools drop down box, Ports icon is greyed out

Can you check in device manager that when you plug the arduino if any COM ports are available or shown there

I have just done that now and it displayed: Device type- Unknown, Location-Port_#0002.Hub_#0002. Thanks

That means, that Windows has no appropriate driver for it. Do you have a cheap Uno clone? Then you need to install the ch340 driver (which is the USB interface chip on mist cheap Uno/Nano clones). Please try and report if that helps

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

CH341 serial driver (e.g. for Vendor ID 1A86, Product ID 7523)
Holtek UART bridge (e.g. for Vendor ID 04D9, Product ID B534)
FTDI Drivers (e.g. for Vendor ID 0403, Product ID 60xx)
CP210x Drivers (e.g. for Vendor ID 10C4, Product ID EAxx)
Prolific PL2303 (e.g. for Vendor ID 067B, Product ID 23xx and AAxx)
Microchip MCP2221 (for Vendor ID 04D8, Product IDs 00xx and 020x)
Cypress CDC (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.


text:
How to stop Single Analog Pin Keypad Matrix (Using Resistors) from receiving Interference from Livewire/other Sensors?
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.

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!

you do not have a common ground connection between the arduino and the breadboard

Lower the resistance, that will reduce the coupled noise after you make sure all grounds are connected. There are other possibilities but the frizzy picture is useless to me.

Your key values are:
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 is:
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 is:

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

...which is different to your key values.
Have I misunderstood your circuit setup? Are you doing something different?

Thanks you for your detailed response Tim! It consisted of two errors: the one was my ground not being connected between the Arduino and the breadboard, which reduced jumping. Your recommendation of adding the 1 kOhm resistance between the ground and the keypad resistor setup was the finishing touch!


text:
Mega2560 programming megacore avrdude: Device signature = 0x000000
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.

How did you connect the Mega2560 to the Mega2560 (as the link you provided does not show that)? The Mega2560 uses different pins (50, 51 and 52) for programming the bootloader than the Uno. Have you mounted a 10µF capacitor between the Reset and GND line of the "programmer" Mega2560?

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. -- That sounds very wrong. I suggest finding a reliable tutorial to follow.

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.


text:
How to hook up a HC-06 to Arduino Nano
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?

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.

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.

After closer inspection it did say 3.3v I should've paid more attention. Thank you for your help :)

You are welcome. Thanks for letting us know.

@PeterDragomirov If you think one of the answers is correct, you can mark it as such. That way everyone knows, that that is the correct one and that the question was successfully answered


text:
Control 4 Grove - RGB LED (WS2813 Mini) color and brightness
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

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:
#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:

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

Thanks but the simulation is wrong as I have  4 Grove - RGB LED (WS2813 Mini) (https://www.seeedstudio.com/Grove-RGB-LED-WS2813-Mini-p-4269.html ) connected to D2,D3,D4,D5 and I wish to control each one of them separately.

@alirazi And why would you need 4 pins for that? As I see it the WS2813 is just like the standard Neopixels (WS2811 or 12 I think). You can daisy chain them. That way you only need one pin, but you can still control each LED individually.

@chrisl You are right, but I wish to avoid soldering and extra wires.

https://github.com/FastLED/FastLED/wiki/Multiple-Controller-Examples you have a few examples for controlling multiple addressable LEDs


text:
Can’t send string from arduino to processing via hc05
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’)
[1]: https://i.stack.imgur.com/V3Jqn.jpg![enter image description here](https://i.stack.imgur.com/usvad.jpg)

Start by using something other than processing to try and receive your data. That way you can confirm which is the culprit: the Arduino setup or the Processing code.

I’ve done that. I first used the arduino ide, set the Port to COM8(Bluetooth )  and it didn’t work. I then used putty, also the same.

Ok, so next replace your firmware with a very simple one that just prints the value of millis() every second.

It works only on arduino serial monitor port not bluetooth Here’s the code I used.                                                     Void setup(){
Serial.begin(115200):
}
Void loop(){
float timer= millis();
Serial.println(timer);
Delay(1000);
}

Then it sounds like your problem is either hardware related or related to the bluetooth connection / configuration itself.

I removed both the hc05 and the nano from the circuit and made a new connection with voltage divide on a breadboard, still same result. Laptop can send data to bluetooth(arduino), but arduino can’t send back.   I also change the baud rate to 115200(formally 9600) using AT mode

Let us continue this discussion in chat.

Remove the HC05 from the Arduino. Connect the HC05 TX pin to the HC05 RX pin and power it from the Arduino. Try sending data from the PC and see if it gets echoed back.

Does the stop bit or parity bit of the Hc05 have anything to do with the transmission?

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


text:
Back EMF from Relay causing trigger on INPUT pin
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

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.

I don't see how the "relay for light 1" relay can interfere with the Arduino, other that the change in load generating some noise on the 12V DC. I think the real problem is running 8 relays from the 5V created by the UNOs voltage regulator. Especially with a noisy 12V input. I don't think the UNOs power supply circuit is made for automotive. I'd get get one of those phone chargers for cars, and use that to power the UNO and relay board.

I have one of those, was running it off of a 5v USB connection initially, read an article saying that you should not power them from the USB connector. So I even tried from a 9v battery to try and isolate the problem. For now I am just trying with 1 relay until I get it working.

@Gerben Seems I should widen the net slightly for full disclosure. I've narrowed it down to something else... I have a 4 button RF Remote Control, the receiver is in the blue box, one of the buttons fires another relay that has an interrupt input into the Arduino, and does an _Init(). Seems this is being fired when "relay for light 1" is disengaged. I will update the question and the diagram.

Since the problem is with the Arduino post a schematic, not a frizzy thing showing how it is connected showing all connections and power.

@Gil I'm not sure what you are asking of me... Are you saying that there is not enough detail in my circuit diagram? I'm open to suggestion on how I can make this question better.

You show the Arduino + connected to the vehicle electrical system, Is that Vin? What other protection if any have you added to that feed? Most if not all of the electromechanical devices such as relays will generate noise when cycled, that typically appears on the 12V system. You show three different grounds, they should all be the same. Have you taken any precautions for the alternator noise?

No, it's as is, connected to the battery, other than fuses, though I've got a 5v USB adapter, like the cigarette lighter ones. The earth like symbol is for the chassis of the car, all connecting back to the car battery. The issue i see is some interference from the back emf of the Light 1 Relay some how sending a positive signal to the Arduino digital in pin 2 with the interupt enabled.

Are you using an internal pullup resistor on Pin 2? The internal pullup is about 20K to 50K, but there is also a 10K external pulldown on that pin. It should be either pullup or pulldown, but not both. Also consider using a 1K resistor instead of the 10K to provide a stronger pulldown and greater noise immunity. And you could replace all the relays with MOSFETs.

@tim thanks for the info, to be honest my knowledge on this is a little rusty from my Electronics A Level 30 years ago. I need to do some reading on pullup and pulldown, and MOSFETs. With that 30 years in IT, I naively thought running an Arduino with relays was like computer logic, I remember now that it's not, feels like it's back to basics for me :).

That 10K resistor should be removed completely. It's not achieving anything useful, and is in fact causing the input to be far too sensitive to noise. You should use a pullup resistor of 10K or less instead of the internal (very weak) pullup.

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:

That looks like a good plan, I'll give it a shot. I have actually been trying a few things and got it to work. First I removed the resistor, removed the 5v wire to the same relay, left as INPUT_PULLUP. Then I added a Diode from ground to the top side of the Module Relay for flyback. That seems to work, strobe and everything, but I may have a ticking timebomb!!

Added an updated circuit with my changes. Thoughts?

@MattD I would still recommend adding the smaller pullup resistor on the input pin. It will help it be more immune to noise. Snubbers are still a good idea to add, although the diode you added is doing most of the job of the snubber for the inductive load of the second relay. You should consider adding one to the second relay's contacts though, if only to increase their lifetime.

Thanks for your help, it's all working now, got 4 inputs and 8 outputs to do the same, that's a fair bit of wiring, I think I'll need to put together a strip board to tidy it all up.

The internal pullup was ok when the car wasn't running, but was not enough with the engine on. Putting in the 1K external pullup resistor worked a treat, even when running. Thanks!

Here is a general idea of a MOSFET alternative for switching the light on and off.
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.
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.

I like the idea of this (still getting my head around it tbh)... but I can't get around the wiring in the engine bay, that needs to be the existing relay. I think it's too much of a change for me at the moment, though I will consider parts of this if I end up taking it further. Thanks


text:
Connecting Arduino Uno's TX pin directly to Esp8266 esp-01
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 ?

There is still no definitive answer to this from Espressif. Anecdotal evidence says that the ESP8266 is 5V tolerant. The (current) datasheet does not say if it is or not. An early version may have said that it is. No one really knows.

https://hackaday.com/2016/07/28/ask-hackaday-is-the-esp8266-5v-tolerant/

Do it the correct way, use a logic level converter, they are inexpensive and you generally have less connections by the time everything is finished..

Esp01 is not 5v tolerant so it could corrupt it at any time so don't do this and use voltage divider.


text:
Stuck In While Loop

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?
#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;
    }
}

Please post schematics and code here directly. Linking to a site where you have to sign up to access your code / schematic is not particularly friendly to us.

48 is the ASCII code for the text character 0

We cannot see your code at tinkercad. It is not publicly available. Please put your code directly into your question. Then we surely can give you a good answer

Thanks for the tips! I edited the question a bit because I deleted the while loops.

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.

That last one sounds really good, sooo how exactly should I implement it? Could you write the lines of code for me? Would be awesome!

Good sir, you are a LIFE SAVER!

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:
// 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.


text:
Program a mega2560 from a different Serial port
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.

download from where over HC-05? what format? hex or bin? or you want to make a Serial upload with avrdude over HC-05 on Serial3? then you need the bootloader to listen at that Serial

@Juraj What format should I use? I was planning on bin, but what format to write to the flash? Download from a tablet in the field that has the internet connection. That's kind of what I'm asking. How do I get the bootloader to listen to Serial3?

you want to use InternalStorage of my ArduinoOTA library to store and apply the updated sketch binary?

@Juraj That would be great! Will that let me read from the Serial port?

the transport of the binary is on you. the only transport available in the library is receiving upload from the IDE. see the Advanced examples on how to use InternalStorage with alternative transport of the binary

@Juraj The example in ArduinoOTA?

yes, the examples in the Advanced section

@Juraj And I should be converting the hex file to bytes at two characters per byte, and then writing that directly to flash. Is that correct?

let the avr tools create the binary. https://github.com/jandrassy/ArduinoOTA/blob/master/extras/avr/platform.local.txt#L4

Let us continue this discussion in chat.

you could write an answer

@Juraj Don't really have one yet. I'm currently using OTA libraries.


text:
Level shifter with diode - not pulling to zero
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:

simulate this circuit – Schematic created using CircuitLab
I don't have the GPS Module 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 ...

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.

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?

This is pretty much OK and as expected.

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.

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.