body:
When using D8 in the code doesn't work, nothing happens, but replacing `D8` with `15` works like a charm. And to test this I created the code below. I know that D8 has worked earlier, but I don't remember which version I was using at that time, but it was a yer or more ago.

Environment:

- Arduino IDE ver. 1.8.13
- ESP8266 board ver. 2.7.4
- Witty Cloud or my add on version to WeMos D1 ([https://oshpark.com/shared_projects/r3NRvNjx][1])
- WeMos D1 R1 chosen in Board manager
---

    // "Witty Cloud" test program

    // A0 - LDR resistor
    // D2 - Button
    // D6 - Green LED
    // D7 - Blue LED
    // D8 - Red LED

    // Constants won't change. They're used here to set pin numbers:
    const int LDR = A0;
    const int BUTTON = D4;
    const int GREEN = D6;
    const int BLUE = D7;
    const int RED = D8;

    void setup()
    {
      Serial.begin(115200);
      pinMode(LDR, INPUT);
      pinMode(RED, OUTPUT);
      pinMode(GREEN, OUTPUT);
      pinMode(BLUE, OUTPUT);
      pinMode(BUTTON, INPUT);
    }

    void loop()
    {

      delay(1000);

      Serial.println("");

      Serial.print("LDR: ");
      Serial.println(analogRead(LDR));

      digitalWrite(RED, HIGH);
      digitalWrite(BLUE, LOW);
      Serial.println("--- Red ---");

      delay(1000);
      digitalWrite(RED, LOW);
      digitalWrite(GREEN, HIGH);
      Serial.println("--- Green ---");

      delay(1000);
      digitalWrite(GREEN, LOW);
      digitalWrite(BLUE, HIGH);
      Serial.println("--- Blue ---");
    }

  [1]: https://oshpark.com/shared_projects/r3NRvNjx

title: Wemos D1 / Witty Cloud D8 doesn't behave as expected

Answers: 0


body:
Trying to read from a voltage divider circuit using two 240 Ohm resistors.  Getting a reading of 6.0, when it should be 1.65.  Circuit is powered by a bench 3.3V and both the Huzzah32 and circuit are grounded.  Using USB for the Huzzah32. Any thoughts?
```
  void setup()
{
  Serial.begin(9600);
}
void loop()
{
  int sensorValue = analogRead(A9);
  float voltage = sensorValue * (3.3 / 1023.0);
  Serial.println(voltage);
  delay(1000);
}
```
[![circuit diagram][1]][1]

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

title: esp32 voltage divider readings off

Answers: 1

body:
First, ESP32 ADC is 12-bit, not 10-bit. therefore the formula should be:

    float voltage = sensorValue * (3.3 / 4096.0);

Secondly, ESP32 ADC is not really linear, and tend to have lower reading than the actual value. You will need to do some calibration if you want to get a more accurate reading. You can take a look at my github on [esp32-adc-calibrate](https://github.com/e-tinkers/esp32-adc-calibrate).


body:
I need to make voltage divider, so I could read a battery voltage up to 14.4 V. Could I use very high resistance resistors for that, so the current would be very low (to not to discharge battery)?

On the Internet there are examples with 500 - 2000 ohm resistors, but could I use hundreds of thousands to reduce the current to minimum? Would Arduino's analog input still read the value?

title: What is the most efficient voltage divider for Arduino?

Answers: 6

body:
I don't see any problem with reasonably high resistors (however see below). You are right that they would discharge the battery less.

> Would Arduino's analog input still read the value?

Of course, if there was a voltage there to read. Why wouldn't it? A *really* high resistance might let the reading be affected by stray voltages.

A possible work-around would be to only take the reading occasionally, say, every 10 seconds. You could do this by making the reading be between a couple of Arduino pins, and leave one "floating" until you are ready to read it.

**However** that is not a good idea for reading a 12V battery. You need the voltage divider to be "active" so you don't have 12V on the Arduino input pin. Majenko's suggestion sounds better in that respect.

I have a [lengthy discussion about the ADC](http://gammon.com.au/adc) on the Atmega328P. [Reply #5](http://gammon.com.au/forum/?id=12779&reply=5#reply5) on that page discusses how it takes its measurements. This is done by charging a "sample and hold" capacitor. With too high an input impedance the capacitor would charge too slowly, and thus the subsequent sampling would give incorrect readings. A source signal impedance of 10k is recommended in the datasheet, so a voltage divider along those lines would be appropriate.

Majenko's suggestion of 20k + 10k would only involve a 0.4 mA constant current flow through the voltage divider, which for a 12V battery is probably not a huge deal (even without all that switching circuitry).

body:
Yes, you can use very high value resistors for your voltage divider.  But the recommended maximum is 10 kohms for the ADC pins.  So the combined resistance of your two resistors should be maximum 10 kohms.

> it is recommended that whatever you connect to the A/D have an output impedance of 10k or less for best accuracy. This is to allow the A/D input capacitor on the sample and hold to charge up in the time allotted to it between switching the input multiplexer over and starting the conversion.

From: *[Input Impedance of A0-A5][1]*

  [1]: https://forum.arduino.cc/index.php?topic=65134.0

body:
The most efficient is not to have a voltage divider at all. Or at least to only have a voltage divider when you actually need one.

My preferred schematic is this:

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

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

<!-- End schematic -->

With this M1 is normally kept turned off by R3. When you want to take a measurement you turn on M2 by setting D3 HIGH (or whatever pin you attached it to) which pulls down the gate of M1 turning it on. This then connects the batter to the voltage divider R1/R2 and allows you to read the voltage at A0.

The voltage divider of 20k / 10k allows you to read up to 15V on the battery, and gives you an output impedance of 6.67kΩ which is within the recommended maximum of 10kΩ for the ATMega's ADC.

During "idle" times when M1 and M2 are both off the only current flowing is the minuscule leakage current through M2 tempered by the large 100kΩ resistor R3 (which itself pales into insignificance compared to the "off" resistance of M2 anyway).

Selecting M1 so that the ON resistance is very small (<0.1Ω) allows you to essentially ignore it in your calculations since that will be swamped by the tolerance of R1 and R2 anyway.  M2 needs to be selected so that it is "logic level" (i.e, with a gate threshold V_GS well below 5V).

This double-FET arrangement should be used rather than just using an N-channel FET in the ground connection of the divider because when that simpler arrangement is turned off the Arduino will be seeing 12V directly connected to A0 which really is not good - you *will* kill the Arduino - so it is important that you switch the "high" side of the network not the "low" side, and to do that requires two FETs.

body:
I was able to implement it with 3 MΩ resistors.
The problem is that the readanalog() function executes 10 reads. So the first one is the right value and then you will not measure the right value anymore.

Solution: A voltage divider with 2.5 MΩ and 500 kΩ with a 470 nF capacitor on the 500 kΩ resistor. The solution with the MOSFET is better. This is easier, and it works (but only for 20 years ).

body:
This is a variation on [Majenko's design above](https://arduino.stackexchange.com/a/78773/47458). It was such a good idea, I couldn't resist submitting this - a *reduced-component-count* version:

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

The [**TPS22810**](https://www.ti.com/product/TPS22810) is a *load switch* that enables or disables Vout (**2.7V ≤ Vin ≤ 18V; Iout ≤ 3A**). The output is determined by the `EN/UVLO` input that may be driven by a 1.8 V, 3.3 V or 5 V GPIO output. This component and the C1 bypass cap replaces 2 FETs and 2 Resistors. The TPS22810 cost is **≈** $0.50 ea. in small quantities.

The TPS22810 will likely find its most useful application as a *high-side switch*, but it seems to serve the purpose of the OP's need for driving a voltage divider also.

body:
Everybody is missing the point here.  The lower limit on the series resistance of the voltage divider is the self-discharge rate of the battery.  For instance, a Li-ion battery loses about 10% of its charge per month.  For a 3000 mAH 18650 cell, that's about 300 mAH per month, meaning about 300/(30X24) = 0.42mA constant drain.  So, for a 8V stack made of 2 18650 cells in series, we get a total series resistance of 8V/0.42 of about 19K-ohms.  IOW, if I put a 19K resistor across an 8V stack, I would get about the same battery drain as the battery would see if I left it completely alone.  As long as the series resistance is much greater than that, it won't affect the battery life at all.  So, if I use 2ea 50K resistors for a total series resistance of 100K, it will have very little effect on battery life.  2ea 50K resistors will present an effective output impedance of about 25K to the ADC input port on a MCU, and that is low enough so there will be little or no distortion of the measured voltage, and any offset can be easily compensated out in software.  Moreover, if you want to go to a higher division ratio (say 4:1 instead of 2:1) the effective output resistance goes DOWN because it's a parallel circuit from the ADC's POV, but still a series circuit from the battery's POV.  If I use a 75/25K divider for a 4:1 ratio, the parallel output impedance is 18.75K.

So, no need for fancy switching circuits - just choose a series divider with a convenient ratio and with a total series resistance in the 100K range, and you are done.


body:
Hi Im very new to coding and I'm struggling to fix a problem. I want the user to input a yes or no answer to a question and based on the answer I want the right text to show on the serial monitor and a LCD as well as the right LED light to light up. However it seems like the if and else if statements are ignored and no matter what the user input is the last else statement is the only thing that shows up.

My second problem is with the switchLead. The LED that shows the condition of the switchLead does not turn off when the switchLead is open.

This is just school work so it has to be basic. Please let me know where I made a mistake! Also this is my first post so let me know how I could make this more clear. Thanks!

```
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

String input;                   // Declate string variable to hold user input

const int whiteLead = 2;
const int switchLED = 13;
const int RED1 = 9;
const int YELLOW1 = 8;
const int GREEN1 = 7;

int switchLead = 0;

void setup() {
  Serial.begin(9600);          // Serial transmission activated baud rate 9600 bits per sec
  lcd.begin(16,2);             // Initialise I2C LCD 16 columns with 2 rows
  lcd.backlight();

pinMode(whiteLead,INPUT);
pinMode(switchLED,OUTPUT);
pinMode(RED1,OUTPUT);
pinMode(YELLOW1,OUTPUT);
pinMode(GREEN1,OUTPUT);

switchLead = digitalRead(whiteLead);       // Read the state of the switchLead value
if (switchLead == HIGH) {                  // Begin if; if whiteLead is open do;
  digitalWrite(switchLED, LOW);
  digitalWrite(RED1,LOW);
  digitalWrite(YELLOW1,LOW);
  digitalWrite(GREEN1,LOW);

}                                          // End if
else {                                     // Begin else; Check if the switchLead is closed, turn LED ON
  digitalWrite(switchLED, HIGH);           // Turn switch LED ON
}                                          // End else
}                                          // End void setup

void loop() {                               // Void loop begins
  Serial.println("Is the room in use? ");   //Prompt user to input answer
  while (Serial.available()==0) {}          // Wait for user input
  input = Serial.readString();              // Read user input and store it in variable input

   if (input == "Yes") {               // Begin if: if user input is yes

    lcd.setCursor(0,0);
    lcd.print("In use");
    Serial.print("The room is ");
    Serial.println("in use");
    digitalWrite(switchLED,HIGH);
    digitalWrite(RED1,HIGH);
    digitalWrite(GREEN1,LOW);
    digitalWrite(YELLOW1,LOW);
  }
  else if (input == "No") {

    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Empty");
    Serial.print("The room is: ");
    Serial.println("empty");
    digitalWrite(switchLED,HIGH);
    digitalWrite(GREEN1,HIGH);
    digitalWrite(RED1,LOW);
    digitalWrite(YELLOW1,LOW);
  }
    else {                                // Begin else

    lcd.clear();                        // Clear LCD display
    lcd.setCursor(0,0);                 // Set LCD cursor to column 0, row 0
    lcd.print("Preparing");             // Print message enclosed in brackets on LCD
    Serial.print("The room is ");       // Print message enclosed in brackets to computer monitor
    Serial.println("being prepared");   // Print message enclosed in brackets to computer monitor
    digitalWrite(YELLOW1,HIGH);         // Turn YELLOW1 ON
    digitalWrite(GREEN1,LOW);           // Turn GREEN1 OFF
    digitalWrite(RED1,LOW);             // Turn RED1 OFF
  }                                     // End else
}                                       // End void loop
 ```

title: Arduino if, else if conditions being overlooked

Answers: 1

body:
Try to use this command

    input = Serial.readStringUntil('\n');

Instead of `input = Serial.readString();`

and also use `while (Serial.available() > 0)`

Instead of `while (Serial.available()==0)`

and where you used `int switchLead = 0;`

Try to use `bool switchLead;`

I hope these changes in the code will help you


body: i am trying to implement the ws2812b with an atmega8,but i didn't understand a thing very well. if i pull low for >50 us, it says it resets, but what does that mean? it resets the current LED all data to 0 and latches the next data to the next led?

title: WS2812B Reset time

Answers: 1

body:
It's the "communication" reset.  You pull the data pin low for 50uS or more to start a new batch of communication.

It's illustrated in the datasheet here:
[![enter image description here][1]][1]

As you can see, between each batch of bits being sent the reset code is set. This is so that the first chip knows to start receiving again and not pass any data on until it's had all 24 of its bits.

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


body:
I have a distance sensor connected to an Arduino DUE and I want to wire its output to an Arduino UNO.

In Arduino DUE, after calculating the distance, I convert a range of distances (0-10cm) to Volts (0-5V), then I map these to 0-255 values and I do AnalogWrite at the DAC pin.

In Arduino UNO, I AnalogRead from an analog pin (A0) which is connected with a jumpwire to the DAC pin of Arduino DUE. I was expecting to get values between 0 (when the distance is 0 cm) and 1023 (when the distance is 10 cm). But instead I get a weird and unstable range between 100 and 548.

The two Arduinos are connected with a jumpwire between grounds and a jumpwire between DAC and A0.

What am I doing wrong? I thought I had understood how to do this, but apparently not :)

Thank you for your help and time in advance!

Konstantina

title: Connect output of Arduino DUE to input of Arduino Uno

Answers: 0


body:
[![enter image description here][1]][1]How can use a separate power source for powering Arduino, and another battery for powering the motors?
How can I make connections through the motor driver module L298N? I know how normally we use one battery to power the Arduino as well as the motors. But I am facing the problem while using different power sources.

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

title: How can I use separate power source for the Arduino and the motors

Answers: 1

body:
That motor driver has an optional on-board 5V regulator. It can be enabled / disabled with a jumper.

With that regulator enabled you just need to connect a ground and your control signals (ENA/IN1/IN2 or ENB/IN3/IN4).

If you disable that regulator (remove the jumper) then you need to provide power from the Arduino's 5V pin to the +5V screw terminal.

The ENx pin(s) (after removing any jumpers that may be on them) connect to any PWM capable pin (this is the speed control pin). IN1/IN2 or IN3/IN4 connect to any IO pin since these are just used to set the direction or control the braking modes.  ENA controls the speed of motor 1, and IN1/IN2 control the direction of motor 1. ENB and IN3/IN4 are likewise for motor 2.


body:
I am new in GPS modules and I need to get the NMEA data from my GPS module but when I execute my code all the NMEA sentences are Invalid.

I am using the same example from instructables Tiny GPS Tracker [https://www.instructables.com/Tiny-GPS-Tracker/][1] and it does not work. So I found other code examples and changed them a little bit.

My code is below. I have the GPS_RX wired with Arduino TX and the same logic for GPS_TX-Arduino RX and Baud is 9600, all these details are inside GPS.h.

If I change the wiring between TX and RX or gps baud the system does not work at all, so I strongly believe that these values are correct.
```
#include "GPS.h"
#include <SD.h>

#if defined (ARDUINO_ARCH_AVR)
#define SerialMonitorInterface Serial
#include <SoftwareSerial.h>
#elif defined(ARDUINO_ARCH_SAMD)
#define SerialMonitorInterface SerialUSB
#include "SoftwareSerialZero.h"
#endif

const int chipSelect = 10;
int cardPresent;

// The GPS connection is attached with a software serial port
SoftwareSerial softSerial(GPS_RXPin, GPS_TXPin);

#define Gps_serial softSerial

void setup()
{
  Gps_serial.begin(GPSBaud);
  SerialMonitorInterface.begin(115200);
  while (!SerialMonitorInterface && millis() < 5000); //On TinyScreen+, this will wait until the Serial Monitor is opened or until 5 seconds has passed

  gpsInitPins();
  delay(100);
  SerialMonitorInterface.print("Attempting to wake GPS module.. ");
  gpsOn();
  SerialMonitorInterface.println("done.");
  delay(200);

  //Enable and set interval or disable, per NMEA sentence type
  Gps_serial.print(gpsConfig(NMEA_GGA_SENTENCE, 0));
  Gps_serial.print(gpsConfig(NMEA_GLL_SENTENCE, 0));
  Gps_serial.print(gpsConfig(NMEA_GSA_SENTENCE, 0));
  Gps_serial.print(gpsConfig(NMEA_GSV_SENTENCE, 0));
  Gps_serial.print(gpsConfig(NMEA_RMC_SENTENCE, 1));
  Gps_serial.print(gpsConfig(NMEA_VTG_SENTENCE, 0));
  Gps_serial.print(gpsConfig(NMEA_GNS_SENTENCE, 0));

  SerialMonitorInterface.print("Initializing SD card...");

  // see if the card is present and can be initialized:
  if (SD.begin(chipSelect)) {
    SerialMonitorInterface.println("card initialized.");
    cardPresent = true;
  } else {
    SerialMonitorInterface.println("Card failed, or not present- continuing with serial output");
    cardPresent = false;
  }
}

void loop() {
  handleGPS();
}

char waitForCharacter() {
  while (!Gps_serial.available());
  return Gps_serial.read();
}

void handleGPS() {
  while (Gps_serial.read() != '$') {
    if(!Gps_serial.available()){
      return;
    }
  }
  int counter = 1;
  char c = 0;
  char buffer[100];
  buffer[0] = '$';
  c = waitForCharacter();
  while (c != '*') {
    buffer[counter++] = c;
    if(c=='$'){//new start
      counter=1;
    }
    c = waitForCharacter();
  }
  buffer[counter++] = c;
  buffer[counter++] = waitForCharacter();
  buffer[counter++] = waitForCharacter();
  buffer[counter++] = '\r';
  buffer[counter++] = '\n';
  buffer[counter] = '\0';

  buffer[1] = 'G';
  buffer[2] = 'P';

  gpsDoChecksum(buffer);

  if (cardPresent) {
    File dataFile = SD.open("gps.txt", FILE_WRITE);
    // if the file is available, write to it:
    if (dataFile) {
      dataFile.write(buffer, counter);
      dataFile.close();
    } else {
      SerialMonitorInterface.println("error opening gps.txt");
      cardPresent = false;
    }
  } else {
    SerialMonitorInterface.print((char *)buffer);
  }
}
```
After I wait aprox. 30 seconds which is the cold start of the gps I still receive invalid NMEA sentences.
(I tested it outdoors and indoors)

$GPRMC,181341.901,V,,,,,,,211020,,,N*4B
$GPRMC,181342.901,V,,,,,,,211020,,,N*48
$GPRMC,181343.901,V,,,,,,,211020,,,N*49
$GPRMC,181344.901,V,,,,,,,211020,,,N*4E
$GPRMC,181345.901,V,,,,,,,211020,,,N*4F

Can someone explain to me what is going on?

  [1]: https://www.instructables.com/Tiny-GPS-Tracker/

title: Invalid data using GPS TinyShield module with Tinyduino

Answers: 0


body:
I'm trying to build a cheap device to measure water level in a tank using HC-SR04 sensor and ESP-01 which send the data to MQTT topic. I used the same code with ESP-E12 which works just fine. As I'm trying to drive the cost down with ESP-01, I faced a problem with I/O pins. I searched the web and found some contradicting info about which pins could be used in this case.

So here is the schematic of my setup:
[![enter image description here][1]][1]

Coming to the ESP-01, I used a USB adapter to program it and the code uploaded successfully. Here I'm just showing the Ultrasonic sensor part which I believe I have issues with.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

    #define echoPin 2 // Echo Pin
    #define trigPin 0 // Trigger Pin

    long duration, distance; // Duration used to calculate distance

    void setup(){
      Serial.begin (115200);
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
    }

    void loop(){
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      distance = duration/58.2;
      Serial.println(distance);
      delay(200);
    }

<!-- end snippet -->

I read somewhere in the internet that GPIO2 can't be used and must be replaced with Rx = GPIO3. However, I tried that and it didn't work too.

**So the question here, am I really using the right pins or is it really possible to do that with esp-01?**

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

title: UltraSonic Sensor with an ESP-01 Standalone

Answers: 2

body:
There are 2 things here.
Ultrasonic sensor works on 5V while ESP on 3.3V. So your sensor is sending 5V signal to ESP. It might fry your board but I believe it has a safety cut off of everything above 3.3V and that's the reason your application is not working.
Cheap solution would be adding voltage divider to your Echo pin:
https://randomnerdtutorials.com/how-to-level-shift-5v-to-3-3v/
but then you will face the issue mentioned by Juraj above.
You may then overpass that issue manually or look for more sophisticated (expensive) solution.

body:
This question is old, but myself had the same problem, so I will answer it.

The problem here seems to be that you have the GPIO0 and GPIO2 connected to the SR04 module when it is powered (this is how should be expected), but the GPIO0 and GPIO2 (also GPIO15, just for mention it), are used by ESP8266 to change the boot mode, with nothing connected to these pins, the ESP will load the program written in the flash, but if these pins change the levels while the ESP is powering up, it could enter in the Flash mode and your code will not execute. If you turn on the ESP-01 first and connect the wires to the SR04 just after, the code works, I know because I had the same problem and have the circuit in my front right now. But this is just for testing, you should not have to do that, the solution for me was to use the GPIO3.

You can use the pin RX as GPIO3 as you mentioned, but you can't use it at the same time that you are using the Serial, because Serial will use the RX and TX pins. If you write a Webserver to display the distance measured, for example, and remove the lines that use the serial, it will work. I used the GPIO3 and GPIO2 with the same code, just disabling serial and changing the pin numbers and worked.


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

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

<!-- End schematic -->

I have 6 AA batteries that I would love to power my Arduino Nano and HCSR04 ultrasonic sensor. However, for my low power application I want to use the bare minimum power required for the components. Since the Nano can run as low as 4.5 volts and the sensor requires 5 volts, I think the best solution would be 4 AA batteries in series to power the hcsr04 and 3 AA batteries in series to power the nano. Since I have 6 batteries I was thinking 3 AA batteries wired in parallel with 3 AA series batteries. I drew the circuit diagram above and realize something is horribly wrong. So I was hoping someone could point me in the right direction.

title: Powering Arduino Components with AA in Parallel and Series

Answers: 1

body:
Wiring 6 batteries up so it gives you both a stack of 3 and a stack of 4 is not easy, and although you can do it you shouldn't do it.  The only arrangement is this:

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

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

<!-- End schematic -->

(The grey link is optional and makes little difference if it's there or not).

The reason you shouldn't really do that arrangement is that you have a mismatch in your capacities, as `[BAT1+BAT2] || [BAT3+BAT4]` has more capacity than `BAT5`, so the current drawn from the 4.5V output will cause BAT5 to go flat far sooner than the others. This will then cause BAT5 to take a reverse charge as current from the other cells flows through it damaging it permanently (especially bad for rechargeable batteries as you will not be able to recharge it, but pretty nasty for alkaline batteries too).

Another consideration when running from different voltages like this is the communication between the different units. If the Arduino is running at a lower voltage the signals it sends out will be of a lower voltage, and it expects to receive signals at a lower voltage. Likewise with the HC-SR04; it will expect to receive higher voltage signals and will send out higher voltage signals. So you will require some logic level translation between the two devices to correct that mismatch in the signal voltages.

As you can see it's all starting to get a little messy now.

A much simpler solution is to keep everything at one voltage. The ideal voltage is 5V since that is the common voltage that all the devices expect to work at.

Since you are running from batteries you want efficiency. To that end you need an efficient solution for generating a stable 5V. The Arduino's built-in regulator is far from efficient, so that can be instantly discounted.

A more efficient solution is a step-down or "buck" switching regulator.  This uses PWM to rapidly turn the power on and off (before then filtering and smoothing it) to effectively convert voltage into current.

You'd run your system off a voltage higher than 5V then use a switching regulator to reduce the voltage down to 5V. Since you have 6 batteries at your disposal the logical voltage would be 6x1.5V = 9V - all 6 batteries in series:

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

![schematic](https://i.stack.imgur.com/4aAGC.png)

<!-- End schematic -->

If you're running non-rechargeable batteries then you don't need to worry about low-voltage cutoff (you shouldn't over-discharge rechargeable batteries), so this arrangement will get the most out of your battery life. Depending on the "drop out" voltage of the regulator (you can get some with a "zero drop-out bypass" mode) your batteries could get down as far as 0.8V each before the system starts to become unstable (even lower if your HC-SR04 is one of the "upgraded" ones that can run from 3V).


body:
When I upload a sketch from Arduino IDE to my Arduino Nano (not yet connected to breakout board) via USB, it works. I can then plug the Nano back to the breakout board and let it do its thing.

However, if the same Nano is already connected to the breakout board (which is in turn connected to some other things), and I try to upload a sketch via USB, it does not work.

The error message is:
```
Arduino: 1.8.13 (Windows 7), Board: "Arduino Nano, ATmega328P (Old Bootloader)"

Sketch uses 3844 bytes (12%) of program storage space. Maximum is 30720 bytes.

Global variables use 204 bytes (9%) of dynamic memory, leaving 1844 bytes for local variables. Maximum is 2048 bytes.

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x1c

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x1c

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x1c

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x1c

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x1c

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x1c

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x1c

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x1c

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x1c

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x1c

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
```
What's wrong? How do I solve it?

title: Fail to upload sketch when Arduino Nano is connected to breakout board

Answers: 0


body:
I've been trying to get my nodemcu working for months and tried countless online references but none worked. I'm using the Arduino IDE to upload sketches and always get the error "Timed out waiting for packer header"

Here's my setup.
I'm trying to upload the example blink code for the nodemcu 1.0 12E.

[![Screenshot of arduino IDE][1]][1]

My board does show up on device manager and here's proof.

[![got the drivers for the board][2]][2]

When i press reset on the nodemcu and have the serial monitor on at 74880 baud the board spits out this.
[![serial monitor output][3]][3]

  [1]: https://i.stack.imgur.com/gZFSl.png
  [2]: https://i.stack.imgur.com/nWniu.png
  [3]: https://i.stack.imgur.com/ZjMOk.png

I have tried pressing the reset and flash buttons while uploading
 in the desired sequence but that didn't work.
I even went as far as reflashing the firmware through the nodemcu flasher but it's always stuck at waiting for MAC and STA address.

Please help me fix the problem and i'm sure not the only one facing this issue. Hoping for help :).

title: Can't upload sketches or flash Nodemcu 1.0 12E (CP2102) but have drivers and responds to RST on Serial monitor

Answers: 1

body:
Turns out it was a board problem. Switched it for an older version of the NodeMCU.

The newer ones are not known for the reliability it seems.


body:
I have a 4KHz 5V pulsed signal connected to Arduino UNO pin2 (ISR).

- When the board is powered, the pulse is attached to ISR rising edge, and is working as intended.

- I don't know the output impedance of the pulsed signal, but when the board is not powered, the pulse drops to 2V.

- The resistance between pin2 and ground is about 500K when not powered. The resistance is infinite when powered.

- The pulsed signal does NOT drop when connected to a 500K resistor.

**Question:**
- What is the cause of the signal drop?
- How to prevent it ? (It's not practical to disconnected the signal from Arduino, but I can make sure Arduino is always powered. How to deal with transient situations like reset ?)

Thanks in advance !

title: Why impedance between I/O pin and ground drops when Arduino is not powered

Answers: 2

body:
The Atmega328p (which is used in the Un[ (and actually all other AVR microcontrollers) has clamping diodes in the input hardware to protect it from overvoltage (above Vcc). When not powered, Vcc is at the same level as ground, so any positive voltage on an input pin is above Vcc. The protection diodes get conductive to protect the input hardware. Note, that the diodes can be fried easily, if a too high current flows through them. You should prevent that.

**How to prevent it?** By not doing it. You should never provide a voltage on an input of an unpowered chip (like any chip). If you really need to unpower the Arduino, you can prevent the voltage from reaching the input pin with a MOSFET.

body: I do that all the time but I also read the data sheet. There is a limit on the amount of current you can inject into a processor pin or in total, that is on the data sheet. Also be aware when you inject current you can cause VCC to go out of specification unless it has enough load to support it. Typically I limit my input current to less than 1mA with a resistor. This also protects me in case I get a negative excursion.  For a 5V system that resistor is 5K or greater, with 10K being very common. The input resistance reading is only good to check if the pin is shorted. It is connected to an active junction of a FET and a few Diodes. The voltage and or polarity of your ohm meter will definitely affect the reading. The resistance that may be there is due to  chip resistance, bonding wire resistance etc. all low in value.


body:
Typical apologies in advance, it's been quite some time since I've tinkered with Arduinos. Using an Arduino Micro Clone (Pro Micro), TF02 LiDAR, and a Adafruit 1.2" 7-segment display, I've been working on a rangefinder that is able to be adjusted up/down by increments of 1. I've hit a wall though. I am unable to adjust the distance value without it returning to the original value. Say the distance is at 6'2". When I push the "up" button, the value is 6'3" but then returns to 6'2". Same applies for the "down" button. Also, when the distance is at, for example, 1'0", and I press the down button, instead of going to 0'11", it displays 0'99". I'm at a wall in terms of what I can do to resolve this.  Any help is appreciated!

    *
    #include <Adafruit_GFX.h>
    #include "Adafruit_LEDBackpack.h"
    Adafruit_7segment matrix = Adafruit_7segment(); //d pin 2, c pin 3
    #include <SoftwareSerial.h>// soft serial port
    #include <Wire.h>

    //button stuff
    int Up_buttonState = 0;
    int Dn_buttonState = 0;
    int Up_lastButtonState = 0;
    int Dn_lastButtonState = 0;
    const int  UpPin = 7;
    const int  DnPin = 8;

    //LiDAR stuff
    int dist;// LiDAR actually measured distance value
    int strength;// LiDAR signal strength
    int check;// check numerical value storage
    int i;
    int uart[9];// store data measured by LiDAR
    const int HEADER=0x59;// data package frame header
    long inches, INCH, feet, ftin;

    SoftwareSerial mySerial(9,10); //rx tx,

    void setup()
    {
    pinMode(UpPin, INPUT);
    pinMode(DnPin, INPUT);
     Serial.begin(9600);

     mySerial.begin(115200);//set the Baud rate of LiDAR and Arduino serial port
      #ifndef __AVR_ATtiny85__

      #endif
      matrix.begin(0x70);
    }
    void loop()
    {

     if (mySerial.available())//check whether the serial port has data input
     {
        if(mySerial.read()==HEADER)// determine data package frame header 0x59
        {

          uart[0]=HEADER;

          if(mySerial.read()==HEADER)//determine data package frame header 0x59
          {
           uart[1]=HEADER;

          for(i=2;i<9;i++)// store data to array
             {
              uart[i]=mySerial.read();
             }
               check=uart[0]+uart[1]+uart[2]+uart[3]+uart[4]+uart[5]+uart[6]+uart[7];
               if(uart[8]==(check&0xff))// check the received data as per protocols //if data received

                 { //start equations
                   dist=uart[2]+uart[3]*256;// calculate distance value

                   //equations for converting mm to ft,in
                   inches = (dist * .3937);
                   INCH = inches% 12;
                   feet = (dist / 2.54) / 12;
                   ftin = feet*100 + INCH;

                   Up_buttonState = digitalRead(UpPin); // add 1 to ftin
                    if (Up_buttonState != Up_lastButtonState)
                    {
                      if (Up_buttonState == HIGH)
                      {
                        ftin++;
                      }
                      delay(500);
                    }
                    Up_lastButtonState = Up_buttonState;

                   Dn_buttonState = digitalRead(DnPin); // subtract 1 from ftin
                    if (Dn_buttonState != Dn_lastButtonState)
                    {
                      if (Dn_buttonState == HIGH)
                      {
                        ftin--;
                      }
                      delay(500);
                    }
                    Dn_lastButtonState = Dn_buttonState;

                   Serial.print(ftin);
                   matrix.print( ftin , DEC );
                   matrix.writeDisplay();

                 }
          }
        }
     }

    }

title: How do I add or subtract to a pre-determined value without having it default back to the original value?

Answers: 1

body:
You wrote:

> ```c++
> ftin = feet*100 + INCH;
> ```

What is this monster? I am not very familiar with imperial units (and I
wonder why anyone would still want to use them), but I believe a foot is
not 100 inches.

Oh, I see. The monster is a kludge to manage the display in feet &
inches. But note that it is computed at every loop iteration as a
function of the measured distance. I doesn't make sense to apply a
correction to the monster as it is going to be recomputed on the next
iteration. That's why the value “returns” to what it is supposed to be.
As to why the down button changes “100” to “99”, I think it is quite
obvious: 100 minus one is 99. It is not a good idea to do arithmetics
with the monster.

If you want the correction to persist, you have to store it in a global
variable (or `static` local), and add that variable to the measured
distance at every loop iteration. For example:

```c++
// In global scope:
int correction = 0;

// In loop():
dist = ...;
inches = dist * 0.3937008 + correction;  // correction added here
ftin = (inches/12) * 100 + (inches);  // only used for display

if (Up_lastButtonState == LOW && Up_buttonState == HIGH) {
    correction++;
    delay(500);
}
if (Dn_lastButtonState == LOW && Dn_buttonState == HIGH) {
    correction--;
    delay(500);
}
```

Note that the monster is used for display **only**. No arithmetics are
performed on it, as that would not make any sense.


body:
As a project I am trying to 'hack' an old E-bike.
The electronic system of the bike consists of:

 - A torque sensor measuring deformation of the rear.
 - A 'spin' sensor measuring if the person is pedeling.
 - A battery pack with BMS
 - A speed controller inside the hub motor.
 - A display to control speed, lights and display distance information etc.

From researching I concluded that the sensors, dislay and speed controller are communicating over LIN because they have a ATA6661 LIN transceiver and they are all connected parallel over the VS, LIN and GND wire.
When I power up the speed controller on its own I can see some LIN communication on my oscilloscope:
[![LIN communication][1]][1]

I do not have a LIN transceiver to log the data but I attached a USB-TTL transceiver to the uart-side of the LINtransceiver. From my oscilloscope a deduced that the baud rate was 9600. I used termite to listen on my serial port and set it to hex view. This is what I got:

[![serial communication][2]][2]

I'm not sure if I should change the amount of bits or parity bits.

My goal is to understand the frames that are send and to deduce which frame holds which sensordata or results in a certain activity.
When I compare this to an CANbus project I was doing it was fairly easy to for example deduce which command was controlling my car's left window because with can-utils (candump) I could see every packet. I could filter unchanged packets and it colorcoded which bit(s) in each packet recently changed.

Any advice/ideas on how to do this for LINbus?

  [1]: https://i.stack.imgur.com/EPlT2.jpg
  [2]: https://i.stack.imgur.com/glyAU.png

title: Reverse engineering LIN bus on E-bike system

Answers: 2

body:
As a starter point I would hookup your rigol ds1054z via usb to sigrok
https://sigrok.org/wiki/PulseView this will enable you to log dump and analyze your lin frames . It has a frame decoder for LIN protocol.
This should give you a great view of what is transiting over the lin bus and which slave PID to call .
From there you may use a macchina.cc  to comunicate over lin or use
https://github.com/macchina/LIN with a arduino due and a lin tranceiver.
Cheerz

body: If you are using "go swissdrive" controller (I'm looking at the picture) the bikebus protocol (bulls green mover) was used and in later, linbus (e-technology, Alber etc.) Display is master, motor and bms as slave .. Good luck :)


body:
I use 485 modules to transmit data serially from one arduino uno to another uno.

If I connect the 2 arduino boards directly without using the rs485 module, the data is sent and received without a problem. But when using the rs485 module, the transmission stops.

Tx code:

```c++
void setup() {
    Serial.begin(9600);
}

void loop() {
    Serial.write(200);
    Serial.flush();
    delay(50);
}
```

Rx code:

```c++
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

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

void loop() {
    if (Serial.available()) {        // If data has come in from Master
        int reply= Serial.read();    // Read the byte
        delay(10);

        lcd.print(reply);
    }
}
```

I can't see what is the problem. I checked every thing wiring and the code is so simple. I'm just sending one number 200 and want to display it on the rx.

Please help. If anyone has an idea about this problem thanks any way.

title: RS-485 Serial communication problem with arduino

Answers: 2

body:
In modbus there are two pins which are as DE and RE which you need to set and reset while transmitting the data. Also you can check [Modbus][1] this library it has some examples which could be useful to you also in arduino Uno don't use software serial for transmitting the data use the hardware serial only I will suggest implement your code on arduino Mega if you have any and then port the code for Uno. Just go through the library you will find some helpful examples and it will solve your issue

  [1]: https://github.com/4-20ma/ModbusMaster

body: I polished my glasses, I did not find the schematic and parts list. It appears you have to enable the transmitter and or receiver to make them work. DE and RE are pins on the Max RSS 485 driver chip and others. They will not transmit or receive if these are wrong. Many connect the DE and RE together to simplify the switching.  In your case you have to enable the transmitter on the transmitting Arduino and the Receive on the receiving Arduino. Do not enable the transmitter on the receive side as it wall cause bus contention and it will probably stop working. The receive can be enabled on the transmitter. This is done is some protocols to validate the message sent. Since you are only sending one way you can hardwire them to the correct logic level. Also you should terminate the buss, it may work without but best to add the resistors.


body:
How can I pass the MAC address to Ethernet shield with leading zeroes?

I change the default MAC address from ```DEADBEEFFEED``` to something like ```DEADBEEFFE01```. So I only change the last number from ```0xED``` to ```0x01```. My board is communicating to a separate server and when I look at the MAC in that server, my board is listed as ```DEADBEEFFE1```.

It's not as simple as printing the MAC address with padded zeroes as the board is actually removing it.

I've looked at the Ethernet library and I saw that the mac is passed as an array of ```uint8_t```. I think that's why, the last number is read as 1 (which is correct) but passed as just that.

Is there a way for the MAC to pass leading zeroes?

title: Leading Zeroes on Arduino Ethernet MAC Address

Answers: 1

body:
Writing this in case someone in the future might be interested.

The values passed in the Ethernet library is correct. The last value, 0x01 must be 1 and is written correctly, ```0x01``` in the registers of the W5500 inside the Ethernet shield.

Where I've got it wrong is how I pass the MAC address to the server. I'm basically creating a string for a json message. In there, I've put ```x``` to make sure that zeroes are padded.


body: in this all the nodemcu are in both mode receiving and transmitting, if i made 6 nodemcu connected with each other as mesh network to control home appliances, using mac address.  suggest how i will start to reach the destination.

title: I want to make mesh network with nodemcu (esp8266)

Answers: 1

body:
there are libraries for this already, i have used [this one,][1] but i have not tested the mesh function yet

  [1]: https://github.com/martin-ger/esp_wifi_repeater


body:
I'm trying to make PWM Signal Generator with Arduino Uno.
I'm trying to control 230V 50hz "[NRG118][1]" combi boiler fan.  The fan powered by AC and have 3pins for PWM control. "vcc,gnd,pwm" Wired them to arduino "5v, GND, 11" pins.

I can control the card on the arduino "0to100% with a simple code below but I can't turn it off.
I tried digitalWrite nothing changed. Tried different pins 5-6-9-11 nothing changed. Tried to wire gnd+vcc to outsource powersuply nothing changed.

Also I have a simple PWM generator ["HW-723 XY-LPWM PWM Signal Generator Module"][2]. The "HW-753" can control the fan without any other component but it may have builtin special component like a NPN but im not sure about it.

In description I found this and maybe its a requirement but I have no idea about electronic components:
"The PWM output pin on the microcontroller drives an NPN MMBT3904 type transistor which in turn drives the PWM output pin of the module.  The transistor has a series 1K resistor tied to VIN+, so the PWM signal will swing between ground and the module supply voltage on the VIN+ pin."

With the HW-753; at startup the fan is not running but when I wire to my arduino it starts with 100% power and when i set "analogWrite(x, 0)" dutycycle reducing but fan still running at %1 speed and I read 0.07volt with multimeter on "PWM+GND" pins.

Most people can not run, I cant stop.... It's killing me people...
What am I doing wrong?

    void setup() {
      pinMode(6, OUTPUT);
    }
    void loop() { //the code only for test. Using loop is dumb.
      //digitalWrite(6, LOW);
       analogWrite(6, 0);
       delay(5000);
    }

  [1]: https://ebmpapst-ventilator.hu/userfiles/webshop/products/resized/2689.jpg
  [2]: https://protosupplies.com/product/xy-lpwm-pwm-signal-generator-module

title: Can't turn off fan using PWM and analogWrite(x, 0)

Answers: 1

body:
If you are working with the AC motor, then it is probably works even PWM cable is not attached. In this case there is no reason to use "analogWrite(PIN, 0)".  It will not work.

"An external resistor divider connected to the VMIN input sets the minimum fan speed by fixing the minimum PWM duty cycle (1.25V to 2.65V = 0% to 100%, typical).  It depends on controler card manufacturer. check datasheet"

If you cant find datasheet like me then check how others do. There is diagram of "HW-753 Signal Generator Module" below. As you can see between VIN+ and PWM there is 1k Resistor and both wired to an NPN, also the mid leg of NPN passing 1k resistor while going to pwm to protect the card. Also 3rd leg is wired to gnd. So it is not the same thing I was doing before. If you work with AC then you must always consider that and just forget what people say. Do not drown like me. I hope it will helps someone.

[![][1]][1]

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


body:
I've been working on a level meter with a neopixel strip (WS2812).

The code is very simple: reading a potentiometer, mapping the input and showing the output in the led strip.

So far, so good. The code I include below is working fine but, obviously, ugly and repetitive.
Since my knowledge of programming is very weak, I wonder if there is any loop way to cut the code short. Please note that the seven led have different colours. Actually this is the confusing point for me to build a loop. Any idea, folks?

Yes, I also know that using so many delays isn't the mos elegant solution, but it does not compromise the device performance and the bar led appearing is quite nice.

```c++
void leveller () {
     int millivolts;
     int level;

     millivolts = analogRead(A3);

     level = map(millivolts, 0, 1024, 0, 7);
     if (level <=0){
       strip.clear();
       strip.setPixelColor(0, 128, 0, 0);
         strip.show ();
      }
      else if ((level > 0)&&(level<1)) {
       strip.clear();
       strip.setPixelColor(0, 128, 0, 0);
          delay(30);
       strip.show ();
       strip.setPixelColor(1, 128, 32, 0);
          delay(30);
         strip.show ();
      }
      else if ((level>= 1)&&(level<2)) {
       strip.clear();
       strip.setPixelColor(0, 128, 0, 0);
          delay(30);
         strip.show ();
       strip.setPixelColor(1, 128, 32, 0);
          delay(30);
         strip.show ();
       strip.setPixelColor(2, 128, 64, 0);
          delay(30);
     strip.show ();
      }
      else if ((level>= 2)&&(level<3)) {
       strip.clear();
       strip.setPixelColor(0, 128, 0, 0);
             delay(30);
         strip.show ();
       strip.setPixelColor(1, 128, 32, 0);
          delay(30);
         strip.show ();
       strip.setPixelColor(2, 128, 64, 0);
          delay(30);
         strip.show ();
       strip.setPixelColor(3, 0, 128, 0);
          delay(30);
     strip.show ();
      }
      else if ((level>= 3)&&(level<4)) {
       strip.clear();
       strip.setPixelColor(0, 128, 0, 0);
          delay(30);
         strip.show ();
       strip.setPixelColor(1, 128, 32, 0);
          delay(30);
         strip.show ();
       strip.setPixelColor(2, 128, 64, 0);
          delay(30);
         strip.show ();
       strip.setPixelColor(3, 0, 128, 0);
          delay(30);
         strip.show ();
       strip.setPixelColor(4, 0, 128, 0);
          delay(30);
         strip.show ();
          }
      else if ((level>= 4)&&(level<5)) {
       strip.clear();
       strip.setPixelColor(0, 128, 0, 0);
          delay(30);
         strip.show ();
       strip.setPixelColor(1, 128, 32, 0);
          delay(30);
         strip.show ();
       strip.setPixelColor(2, 128, 64, 0);
          delay(30);
         strip.show ();
       strip.setPixelColor(3, 0, 128, 0);
          delay(30);
         strip.show ();
       strip.setPixelColor(4, 0, 128, 0);
          delay(30);
         strip.show ();
       strip.setPixelColor(5, 0, 128, 0);
          delay(30);
         strip.show ();
      }
      else if ((level>= 5)&&(level<6)) {
       strip.clear();
       strip.setPixelColor(0, 128, 0, 0);
          delay(30);
         strip.show ();
       strip.setPixelColor(1, 128, 32, 0);
          delay(30);
         strip.show ();
       strip.setPixelColor(2, 128, 64, 0);
          delay(30);
         strip.show ();
       strip.setPixelColor(3, 0, 128, 0);
          delay(30);
         strip.show ();
       strip.setPixelColor(4, 0, 128, 0);
          delay(30);
        strip.show ();
       strip.setPixelColor(5, 0, 128, 0);
          delay(30);
         strip.show ();
       strip.setPixelColor(6, 0, 128, 32);
          delay(30);
         strip.show ();
      }
      else if (level>= 6) {
       strip.clear();
       strip.setPixelColor(0, 128, 0, 0);
          delay(30);
         strip.show ();
       strip.setPixelColor(1, 128, 32, 0);
          delay(30);
         strip.show ();
       strip.setPixelColor(2, 128, 64, 0);
          delay(30);
         strip.show ();
       strip.setPixelColor(3, 0, 128, 0);
          delay(30);
         strip.show ();
       strip.setPixelColor(4, 0, 128, 0);
          delay(30);
         strip.show ();
       strip.setPixelColor(5, 0, 128, 0);
          delay(30);
         strip.show ();
       strip.setPixelColor(6, 0, 128, 32);
          delay(30);
         strip.show ();
       strip.setPixelColor(7, 0, 128, 64);
          delay(30);
       strip.show ();
    }
}
```

title: Cutting neopixel routine code short

Answers: 1

body:
First, a small remark:

> ```c++
> if ((level > 0)&&(level<1))
> ```

`level` is an integer, and there is no integer that is both strictly
larger than zero and smaller than one.

> ```c++
> if ((level>= 1)&&(level<2))
> ```

There is only one integer that verifies this condition. It would be
clearer then to just write

```c++
if (level == 1)
```

Now, for your actual question: one trick that often works to shorten
repetitive code is to turn code into data, store the data in arrays and
run through them with loops. Here the sequence of colors can be stored
in an array:

```c++
const uint8_t colors[8][3] = {
    {128,   0,   0},
    {128,  32,   0},
    {128,  64,   0},
    {  0, 128,   0},
    {  0, 128,   0},
    {  0, 128,   0},
    {  0, 128,  32},
    {  0, 128,  64},
};
```

You can then call `setPixelColor()` within an loop that runs through the
array. As the end point of the loop depends on the measured level, it
could be written like this:

```c++
void leveller() {
    int level = map(analogRead(A3), 0, 1024, 1, 9);
    strip.clear();
    for (int i = 0; i < level; i++) {
        const uint8_t *color = colors[i];
        strip.setPixelColor(i, color[0], color[1], color[2]);
        strip.show();
        delay(30);
    }
}
```

Note that, since the output of `analogRead()` is always smaller than
1024, the variable `level` will always be smaller than 9, i.e. it will
take values between 1 and 8 inclusive. And that is the number of colors
that will be shown.


body:
```c++
#include <Adafruit_NeoPixel.h>
const int PIN = 4;
const int NUMPIXELS = 10;
const int BUTTONPIN = 6;
int buttonState = 0;
int PINState = 0;
int level = 1;
int dt = 100;
Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

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

void loop(void) {
Serial.println(buttonState);
  buttonState = digitalRead(BUTTONPIN);
  if (digitalRead(BUTTONPIN) == HIGH) {
    if (buttonState == 0) {
      buttonState = 1;
    } else {
      buttonState = 0;
    }
  }

  if (buttonState == 1) {
    opdracht(level);
  }
  else {
    if (level >= 10) {
      level++;
    } else {
      level = 1;
    }
    pixels.clear();
  }
}

//level 1
//void opdracht1() {
//  pixels.setPixelColor(0, pixels.Color(150, 0, 0));
//  pixels.setPixelColor(5, pixels.Color(0, 0, 150));
//  pixels.show();
//}

void opdracht(int x) {
  if (x == 1) { //level 1
    pixels.setPixelColor(0, pixels.Color(150, 0, 0));
    pixels.setPixelColor(5, pixels.Color(0, 0, 150));
    pixels.show();
  }

  if (x == 2) { //level 2
pixels.setPixelColor(8, pixels.Color(150, 0, 0));
pixels.setPixelColor(6, pixels.Color(150, 0, 0));
pixels.setPixelColor(1, pixels.Color(0, 0, 150));
pixels.show();
  }
```

title: I want to create 10 levels with one button but this code shows only level 1?

Answers: 1

body:
You forgot to ask a question. So I will assume the intended question is
“Why does this code always show level 1?” and I will try to answer that.

The variable `level` is defined here:

```c++
int level = 1;
```

Its initial value is 1. Then it is updated here:

```c++
if (level >= 10) {
  level++;
} else {
  level = 1;
}
```

The first time this section of code runs, `level` has its initial value,
namely 1. The condition in the `if` evaluates to false, then the
statement

```c++
level = 1;
```

is executed, which assigns the value 1 to `level` (which has no effect,
as that was already its value anyway).

The next time that section of code runs, `level` has still the vale 1,
and the effect is the same as the previous time.


body:
I am not too experienced about the working of arduino but I know that it involves data in computer language  ( 0 and 1)

I have an array of 8 switches plus a few extra. As I am unable to (due to some reasons) program it through my pc, I wanted to know if it is possible to manually use switches to send data and program it? (complexity doesn't matter).

If yes, then could you tell me how I could do it (taking into consideration my limited knowledge).

If no then why?

title: Programming an arduino using only switches to give 0 or 1

Answers: 2

body:
Short answer: If you are unable to program your Arduino using a computer, you are unable to program your Arduino at all.

The Arudino is built to be programmed using a serial interface (usually USB) that interacts with the bootloader, plus an IDE on the other end of the cable. It is not set up to be programmed with switches.

You could conceivably build an Arduino programmer that would let you enter a program using 8 switches plus an enter button. Such a programmer would collect the program into a memory buffer, and then load it into the Arduino using the USB interface but it would take WEEKS of working constantly to enter the simplest of programs, and the odds that you could do it without multiple errors is pretty much zero. Plus, it would probably cost several hundred dollars to build such a programmer. It would be a pointless exercise in masochism.

(Not to mention the fact that you would have to somehow compile your Arduino program into machine code, and convert that into binary in order to enter it.)

Some of the earliest computers required that the operator enter the first few instructions via switches as you describe, and then the computer would read and begin executing the rest of its program from a tape drive. Those computers only had a few thousand bytes of memory, and even then, the instructions the operator had to enter were just enough to start the machine booting from tape.

body:
While not *physically* impossible it would be a really silly thing to attempt.

However, if *I* were to attempt it I'd probably use just 3 switches (or rather 2 switches and one button though you could use a switch instead of the button).

I'd wire it up so that the RESET, MISO and SCK pins were all connected to the switches in such a way that I could hold the whole board in RESET for extended periods (i.e., switch between RESET and GND), set a HIGH or a LOW as needed on the MISO pin, and toggle the SCK pin HIGH and LOW (I'm not sure off hand if you need to idle LOW or HIGH with the clock - the datasheet will tell you).

Then I'd become extremely intimate with the ICSP protocol of the ATMega328P.

That would then allow me, extremely slowly, to act like a hardware programmer and instruct the ATMega328P to program itself with data I sent.

You might also like to attach a shift register to the MOSI and SCK pins with 8 LEDs on it so you can monitor the responses from the Arduino while programming.

It would take forever to upload even the simplest of programs, and the error rate would be far to high, but it *could* be done if you were *really* desperate and had nothing else to do (including eat or sleep) for a number of days.


body:
I am searching for a tiny board to that accepts an usb-c cable and outputs 5v.

To my understanding, for the few hundred milliamps two 5k1 resistors on the board would suffice. PD is not needed.

I already bought [this][1], but sadly it's too big. Also, I don't need any data pins, just 5v and -.

Can anyone recommend such a board to power a tiny circuit?

  [1]: https://www.amazon.de/Pololu-Type-C-Connector-Breakout-Board/dp/B07GZKMPJ8/ref=sr_1_1?__mk_de_DE=ÅMÅŽÕÑ&dchild=1&keywords=usb c diy socket&qid=1603465656&sr=8-1

title: Low power USB C power supply

Answers: 0


body:
Currently I am using a 9 Volt Duracell A one like this:
[![enter image description here][1]][1]

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

I am using it to power a motor driver which contains 2 motors within. I  can see where the main problem is coming and that is to do with that the voltage is not big enough. But I don't understand why this is. I see in the manual for the robot that I am building it is using a smaller voltage battery than what I am using. I tried using another set of batteries but the motors did not move at all then. The 9V Duracell battery that I am currently using has only been used for about a week (so it probably hasn't ran out), its practically brand new.

title: 9 volt battery not being able to power motor driver

Answers: 1

body:
It is likely not a question of the voltage being "big enough". You do need to feed the correct voltage to your robot, but max current and capacity are also very important.

Those "9V transistor batteries" have very low peak current and very low total power capacity (measured in milliamp-hours, or mAh.) They are not up to the job of powering motors. You could easily drain a 9V battery like that in 15 minutes, much less a week.

You should connect 6 D cells in series, and use that instead. That would give you enough peak current and total capacity for your robot.


body:
Am new to Arduino. So permit me if I sound so novice.

I want to create a countdown device (a clock that will countdown or something) that will unlock a box when the time is up.

As an example, let say, I set the clock to start counting down from 2hours, but when it remains 5mins for the countdown to elapse, the box will unlock

What are the things needed for it to work as all examples I see are mostly for opening the door or box when the temperature changes.

title: Using Arduino to create a countdown that unlock a box

Answers: 1

body:
This sounds as an escape room puzzle.
From an electronic point of view you need something to lock/unlock the box like a servo motor, a stepper motor or (best option) a normally closed solenoid. You might need some components to drive such locking mechanism, like a mosfet or transistor (possibly a darlington), depending on which device you choose and what voltage it requires to operate. Simplest solution is a servo motor which doesn’t require anything, but has a low torque, meaning the box can easily be forced. Most robust and reliable solution is a NC solenoid, common ones are 12V so you’ll need a p-channel enhance mosfet and a couple of resistors to drive it from an Arduino.

To display the time you’ll probably want to go for an LCD, common ones are 16 col x 2 rows, most have an integrated chip to drive them using only a few wires.

Apart from that, you need a battery pack (voltage and power depending on your locking circuit choice) and may be a push button (for safety unlock).

From a software perspective you want to create a loop which starts by locking the box and then counts down the time: when the time left is less than 5 mins it activates the unlocking mechanism circuit.

    int current = 0;
    const int max = 2 * 60 * 60; // 2hrs in sec
    const int grant = 5 * 60; // 5mins in sec
    bool unlocked = false;

    void setup() {
        lock();
    }

    // executed once every second
    void loop() {
        // any safety open check should be performed here...
        // if still locked and less than 5 mins to end
        if (!unlocked && current > max - grant) {
            unlock();
        }

        display(current++);
        wait(1000);
    }

    // does what it is needed to unlock and sets the unlocked variable to true
    void unlock() { ... }

    // does what it is needed to lock and sets the unlocked variable to false
    void lock() { ... }

    void display(int secs) {
        int h = secs / (60 * 60);
        int m = (secs / 60) % 60;
        int s = secs % 60;
        // display on LCD the values above with the proper formatting
    }

A couple of notes:

 - if you go for a normally closed solenoid be sure to have a way to get inside the box if something goes wrong with your circuit or if the batteries get drained
 - you might want to have a hidden button or other way to force the unlock, especially for debugging and testing


body: I have an upcoming exam about the codes and stuff. Its about the basics like "blink with delay" and the "millis function". I need to get these things learned but i have no idea how?! Does anybody know a good site or how i can learn this?

title: Help needed!!! I have an upcoming exam

Answers: 1

body:
Learning to write code really takes practice - you learn far more by doing it than by reading about it. Start with the basic Blink example - search for a tutorial online if you want one, there are many - and get that running. Then play with it. Change the blink interval. Try adding a second LED, perhaps it turns off when the other turns on, for instance.

Every time you touch the code you'll have an "opportunity" to make a mistake or a typo. Fixing those will give you some insights you'll never get from reading about coding.

Once you've "squeezed all the juice" out of Blink, move on to Blink Without Delay. Run it, just as it is, at first. Than start tweaking it. Change one or both of the blinking periods. Again, try adding another LED with yet another blink rate.

These hands-on games are the best way to learn this stuff. Having someone (or Arduino Stack Exchange) who can help you when you're stuck is a great resource but the things you discover and the skills you acquire on your own when you fix your own mistakes are the ones that will stick with you (even 50 years later! ;-)


body:
I am new in using Arduino so please forgive me if my question is too simple.

I need to generate a square wave with exactly the same duty cycle and frequency with the trigger pulse. The trigger pulse is 15 Hz with two rising edges in each cycle. Besides, I need to introduce an adjustable delay between them.

Is anyone can tell me how to do it please? Thanks in advance!

title: Arduino UNO generate square wave, which is exactly the same with trigger pulse, but with a time delay

Answers: 0


body: I am trying to connect different types of sensors & motors to the Arduino should I make their grounds and 5v pins on the same connection.

title: Whatever components we connect to the Arduino, their grounds and 5v pin connection must be the same?

Answers: 1

body:
All the grounds must be connected. They don't have to be the same physical pin - the Arduino has multiple GND pins, but they are all connected internally.

The 5V doesn't matter where you get that from, as long as it's regulated and the associated ground is connected to all the others.


body:
As an off-Topic to my main [question][1], regarding Robodyn's Uno+Wifi - it seems that Wifi does not work ( fail to connect and fail find any network ).

Juraj advised to use External Antenna ( did not work ) and try to make an RF calibration as shown [on espressif's site][2]. Which I fail to understand how it is done.

a) Can anyone help with RF Calibration ?

b) Might it be another reason for that ?

Guy

**EDIT_1**
Just to be clear, a sלetch was uploaded and executed successfully to the ESP8266 module (Basic WiFi connect and network scan ).

**Edit_2**
[![close up pic][3]][3]

  [1]: https://arduino.stackexchange.com/questions/78808/robotdyns-unowifi-r3-atmega328pesp8266-32mb-flash-usb-ttl-ch340g-micro-usb?noredirect=1#comment174934_78808
  [2]: https://docs.espressif.com/projects/espressif-esp-faq/en/latest/development-environment/debugging.html?highlight=calibration#how-can-i-modify-the-default-method-of-rf-calibration-in-esp8266
  [3]: https://i.stack.imgur.com/sIedI.jpg

title: ESP8266 RF Calibration

Answers: 1

body:
You can't do anything else with the RF calibration then to clean the flash area where it is stored. There are two reason for doing it:

First is reason to delete the RF calibration area is, if it was written by different version of Espressif SDK, including changing between AT firmware and Arduino. Then it is almost always wrong. I think they changed the data structure so some values are swapped.

Second reason is if the SDK did the calibration in wrong conditions like without antenna.

There is not much information about RF calibration. The [FAQ][1] has "Please erase the RF parameters to trigger overall calibration."

The AT firmware reference has (addresses for 4MB-C1):
* blank.bin 0x3FB000 Initializes RF_CAL parameter area.
* esp_init_data_default.bin 0x3FC000 Stores default RF parameter values, has to be downloaded into flash at least once. If the RF_CAL parameter area is initialized, this bin has to be downloaded too

The esp8266 Arduino core writes the data of esp_init_data_default.bin as part of the sketch's binary.

EDIT: the SDK does the 'digital calibration' at boot. it takes some microseconds. it is not done at every boot, but after some count of resets. this can be configured in the init section

  [1]: https://docs.espressif.com/projects/espressif-esp-faq/en/latest/development-environment/debugging.html?highlight=calibration#how-can-i-modify-the-default-method-of-rf-calibration-in-esp8266


body:
Can I use the Arduino with an External wall-wart and the USB at the same time?  I need to power more LEDs, and the USB on my computer can only supply so much.  But, I didn't want to destroy my computer because I had the USB and the external plugged in.

I saw this,

https://arduino.stackexchange.com/questions/28282/external-power-supply

But I am still unsure.  The reason I want to at all is because when I connected this circuit, the Arduino would cease to be recognized on the USB.  I don't know if it is because there wasn't enough power to the LED, if I short-circuited something, or something else.  I do not wish to break my laptop though.

https://arduino.stackexchange.com/questions/893/what-happens-if-i-power-the-arduino-with-both-the-usb-and-external-power-voltage

These all seem to indicate you don't just "plug in" with both, and you need some other kind of regulator or something.  But in that same answer, one person says,

https://arduino.stackexchange.com/a/896/69706

And that indicates when the power is plugged in the USB is cut off.  Again, my fear is breaking my laptop, and that is the main question.  Especially in light of this,

https://arduino.stackexchange.com/questions/11885/is-supplying-5v-from-both-external-5v-and-usb-harmful

The external power is [this][1],

9 VDC 1000mA regulated switching power adapter

  [1]: https://www.adafruit.com/product/63

title: Can I use and external power supply and USB at the same time on my Arduino?

Answers: 1

body:
Yes, you can simultaneously connect external power supply and USB. As explained in one of the answers, that you linked, the Arduino chooses it's power input through the supplied voltage on Vin/barrel jack. Vin has no direct connection to the VUSB, so the USB port will not get any voltage from the external supply, thus it does not get damaged.

**BUT:** Your thinking is wrong. Clearly your LEDs need more than 500mA. This current should never flow through the Arduino. You can easily fry the protection diode or the voltage regulator (which is an inefficient linear regulator), if you connect all the LEDs to the 5V pin. One GPIO pin can only provide about 20mA (40mA at absolute max, you should stay below 20mA) and only 100mA through all GPIOs together. They are not made to provide power, but for switching.

Instead you should connect the LEDs outside of the Arduino to the power supply. If you want to use the specified 9V power supply, you need to buy a buck switching voltage regulator, which gets the voltage down to 5V for you. Make sure, that this regulator is rated for a current significantly higher, than what you need.

**How to control the LED then?** That depends on your LEDs. If you just have some bare LEDs, you could use a transistor to switch the higher voltage from the Arduino. If you have a plain LED strip you can also use a transistor. Best use a MOSFET for this. If you have an addressable LED strip, just connect the power lines to the 5V output of your new switching regulator and the data line to the Arduino.


body: I want to write a program in which I can select a HEX file recorded on a SD card (via a LED screen, etc.) and run it, i.e. transfer control to it, like launching programs on a PC. Is this possible and if so, how? I only found ways to directly run a sketch from an SD card without that "program"

title: Run HEX program from SD with another program

Answers: 2

body:
Not with an Uno, no, it's not possible. Or it's very very hard and the results would be less than desirable. You need a proper MCU with lots of RAM and the ability to run code from it, which you can't with an Uno.

It would be less work to write your own scripting language to control things from a text file.

body:
The HEX files on SD card would have to be linked for a specific address in flash. Normal program is linked for address zero on ATmega, but the bootloaders are an example on how to link for specific address in flash.

Then you could use the do_sdm() function provided by Optiboot 8 (see [the example][1]) to write the bytes from the HEX file to the right location in flash memory. Next step would be to call the start address as function same way as do_spm() is made accessible with optiboot.h in the example.

```
typedef void (*loaded_function_t)();

const loaded_function_t loaded_function = (loaded_function_t)(ADDRESS_OF_LOADED_FUNCTION);
```
then you can use
```
  Serial.prinln("Execute the loaded code...);
  loaded_function();
  Serial.prinln("Loaded code finished.");
```

  [1]: https://github.com/Optiboot/optiboot/blob/master/optiboot/examples/demo_dospm/demo_dospm.ino


body:
Kunal Gupta:
Guys plss help me .... I am having issues in using stepper motor

I have tried both 28bjy with uln2003 and l293d .. giving it output supply of 5V .
Motor is vibrating but its shaft is not moving.
And even if shaft runs then it is different from what is expected by the logic of code

Similarly tried NEMA 17 stepper motor 4.5 KG using drv8825 driver and L293D driver ... Giving 12 v external supply.

And same results as 28bjy .... motor vibrating but its shaft is mot moving as expected or absolutely not moving

I have read and understood all the concept of driving stepper motor by full step method and hafl step method ....and using at first direct examples from net .. but still not figuring out what is the problem

title: Stepper motor not working as expected

Answers: 1

body: Try  lowering the rpm in the code. I had a similar issue with anything over about 18rpm using certain libraries with certain stepper motors.


body:
Arduino Uno R3, WS2812B, 1 strip of 60 leds, segmented in to 4.

Problem: Only want a single segment/fx_mode to run at any one time.

---

    #include <WS2812FX.h>

    #define LED_COUNT 60

    #define LED_PIN 13

    WS2812FX ws2812fx = WS2812FX(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);

    void setup() {

    ws2812fx.init();

    ws2812fx.setBrightness(85);

    // divide the strip of 60 LEDs in to 4 segments

    ws2812fx.setSegment(0,  0, 14, FX_MODE_COMET, BLUE,  3000, false);

    ws2812fx.setSegment(1, 15, 29, FX_MODE_SCAN, RED, 3000, true);

    ws2812fx.setSegment(2, 30, 44, FX_MODE_SCAN, BLUE,  3000, false);

    ws2812fx.setSegment(3, 45, 60, FX_MODE_SCAN, RED, 3000, true);

    ws2812fx.start();
    }

    void loop() {

    ws2812fx.service();
    }

Answers: 1

body:
The used library doesn't give you the direct possibility to automate the segment changes. So you need to write that code yourself.

Currently you are setting up all segment in `setup()` and starting them together via `start()`. Instead you should add the corresponding segment only, when it should be on, and removing all segments, that should not run. In the following I don't remove and add a segment, but I'm replacing the previous segment (described below)

I propose a code like the following, to light up each element after the other for a specific time each (**not tested**):

    #include <WS2812FX.h>

    #define LED_COUNT 60

    #define LED_PIN 13

    #define SEGMENT_INTERVAL    3000
    unsigned long segment_timestamp;
    uint8_t current_segment = 0;
    #define SEGMENT_N   4

    WS2812FX ws2812fx = WS2812FX(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);

    void setup() {
        ws2812fx.init();
        ws2812fx.setBrightness(85);
        ws2812fx.start();
    }

    void loop() {
        if(millis()-segment_timestamp > SEGMENT_INTERVAL){
            segment_timestamp += SEGMENT_INTERVAL;
            switch(current_segment){
                case 0:
                    ws2812fx.setSegment(0,  0, 14, FX_MODE_COMET, BLUE,  3000, false);
                    break;
                case 1:
                    ws2812fx.setSegment(0, 15, 29, FX_MODE_SCAN, RED, 3000, true);
                    break;
                case 2:
                    ws2812fx.setSegment(0, 30, 44, FX_MODE_SCAN, BLUE,  3000, false);
                    break;
                case 3:
                    ws2812fx.setSegment(0, 45, 60, FX_MODE_SCAN, RED, 3000, true);
                    break;
            }
            current_segment = (current_segment + 1) % SEGMENT_N;
        }
        ws2812fx.service();
    }

**What happens here?** First we use the `millis()` function in the pattern of the `BlinkWithoutDelay` example to time the change of segments to every 3s (3000ms) without blocking the execution of the other code (here the service routine of the LED animation). I will not go into detail here, since this principle is described at numerous places through the web and this site. Just search for something like "Arduino millis" or "Arduino Blink without delay". Now is only important, that the code inside the if statement will be executed every 3s (can be changed with `SEGMENT_INTERVAL`).

In the if statement we use a switch statement to set the corresponding segment, that should be activated at that time. Here we always set the segment 0, since only one segment is active at any time. Instead of removing the previous segment and adding the new one, we just change the previous segment to the data of the new segment.

With the line

    current_segment = (current_segment + 1) % SEGMENT_N;

we increment to the next segment, while wrapping around from segment 3 to segment 1 via the modulo operator `%`. This is needed to loop through the segments.

The call to `ws2812fx.service()` is still needed, since it handles the actual animation of the current segment.

---

Note, that the above code can still be improved. You could save all the segment data in an array of structs and replace the switch statement with one line, using the `current_segment`'th element of the array. I will leave that improvement to you.


body:
****Slave code****

    int arr[10] = {0,1,2,11,4,5,6,7,8,9};
    char id = '1';
    char re[2];
    void setup() {
    // Begin the Serial at 9600 Baud
    Serial.begin(9600);
    }
    int ia;
    void loop() {
    Serial.readBytes(re,2);// slave gets the query
    ia = re[1] - '0';
    if (re[0] == id){
    Serial.println(arr[ia]);// slave print in serial monitor
    }
    delay(500);
    }

**Master Code**

    char mystr[2] = "13";
    void setup() {
    // Begin the Serial at 9600 Baud
    Serial.begin(9600);
    }

    void loop() {
    Serial.write(mystr,2); //sends query to slave
    delay(3000);
    }

title: Communication b/w Arduinos, master(M) and slave(S) via Tx Rx pins. M sends query to S which shows the data in serialmonitor. S fails to send data to M

Answers: 0