text:
Arduino if, else if conditions being overlooked
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

because readString returns "Yes\n"

tip:  lcd.setCursor(0,0); is always executed ... it should be placed before the first if statement .... same with the Serial.print("The room is ");

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


text:
WS2812B Reset time
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?

welcome, it helps if you add a reference to 'it' in 'it says', probably a datasheet of the WS2812B you are using (and add the page/fragment or copy it).

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:

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.

so, the reset code needs to be sent between each 24 bits, right?

No. Between each 24 * NUM_LEDS bits.

aaah, got it, so it's for when the all the data is sent, so i can send new data again. thanks!

@SoxxZ_ Btw, it is sometimes used to stretch comunication. The data for single led are sent and then MCU can do something else for short time (as far as it's not longer than reset pulse).

source: Stack Exchange

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

sort: votes


text:
Connect output of Arduino DUE to input of Arduino Uno
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

why do you want to do this? Due is 3.3 V and Uno ADC reads 1023 at 5 V

I'm not too sure what you're end goal is but it sounds like your using this as a means of communication. If that's the case, use a level shifter and communicate via UART through the arduino. Here's a link for the level shifter https://www.adafruit.com/product/757

As said by @Juraj it is 3.3V, so it is normal to have a value from 0 to 550. Add a 1k resistor to ground if you want a better and stable output. Isn't there a better way to transmit the value? You will never be able to transmit the real value if you convert it to an analog signal.

Thank you very much guys! The reason I want to do this, is that the Arduino UNO is already part of a larger system that I cannot modify.  This Arduino UNO normally reads the analog signal from a potentiometer. I need to replace this potentiometer with a distance sensor. So I bought the ultrasonic HS sensor and I reasoned that I could do it through an Arduino DUE that does AnalogWrite to the Arduino UNO that does its AnalogRead. Do you think I could do it in a smarter way?   I am not super good with these so any help/suggestions are greatly appreciated!

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


text:
How can I use separate power source for the Arduino and the motors
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.

make sure all ground pins are connected together. And please edit your answer and insert a photo of your setup so others can spot your problem

I added the Image and want to know how the pins are connected when separate power source are used

please edit the image so it's clearly visible which cable goes to which terminal, especially on the arduino and the L298 module

That's what I want to know

seems correctly connected ... two control signals and ground connected between the arduino and the motor driver

Read the documentation of the motor driver module. If it doesn't seem to answer your question, update the question with a link to that documentation.

You already are powering the motor with a separate power source - the 9V battery (poor choice, btw). The Arduino is powered by the 5V from the Pi.

@Majenko Ya I know it's already connected but I want to know the actual connections of the pins, The connections made in the diagram are not properly visible

@AmitNikhade your post only asks about separate power supplies ... if you want to ask about control lines, then you should open a new post ... document exactly what module you have and how it is connected (pin numbers, signal names) ... give details about what you are trying to do

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.

You mean to say that do not remove the jumper of the 5v regulator and then connect the ENA/IN1/IN2  And It's ready.

PLus ground, but yes. That's right.

And the battery connections

Well, yes, of course. Without those there will be no power...

So I will be able to power the arduino with a separate battery or through USB. And what about the motor driver connections with the other battery for motors.

What about them? You connect them. You connect the battery to the connections for the battery.

It worked, Thank's

I completed the circuit as you said but my raspberry pi suddenly start booting and Now only showing a red light

Maybe your Pi's power supply is not good enough to power the Arduino as well as the Pi. They can be very picky.

It's working now. My god everything working well now


text:
Invalid data using GPS TinyShield module with Tinyduino
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/ 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,,,N4B
$GPRMC,181342.901,V,,,,,,,211020,,,N48
$GPRMC,181343.901,V,,,,,,,211020,,,N49
$GPRMC,181344.901,V,,,,,,,211020,,,N4E
$GPRMC,181345.901,V,,,,,,,211020,,,N*4F
Can someone explain to me what is going on?

V stands for invalid sentence, I can't find a way to generate valid sentences

looks like the module is not able to determine location .... maybe not enough satellites are being received .... perhaps the GPS module has a setting for sensitivity level ... maybe the antenna is bad, or badly connected ... this does not appear to be an Arduino problem .... just a note: your code is overly complicated for debugging ... all that is required, is to copy the received characters to SerialMonitor .... see the SoftwareSerial example in the Arduino IDE

I tried similar code that only prints the sentences and the validity, but all of them were invalid. I tried the same code outdoors but same results.   Could it be faulty antenna??

think about it logically ... the module is generating valid sentences ... that means that the serial communication is good ... the module itself is saying that the data in the sentences is invalid, probably because the lat/lon info is missing ... so the problem is either configuration, or the module hardware on the satellite receiver side

Do you know if there is a way to print the number of satellites connected to the GPS module?

Using example sketches give invalid results also haha

looks like you may want either GGA, or GSA sentence .... https://web.archive.org/web/20200131031033/www.gpsinformation.org/dale/nmea.htm

So you say that i need to check those sentences in order to understand if the gps is fixed or not..

all I am saying is, look at the type of information that can be obtained from these various sentences  .... it is up to you to to decide if the information is useful to you .... personally, i would print out as many different sentences as possible and look at them  .... i would also try to find out if there is a command available that dumps multiple different sentences at once ..... here is a similar web page that is still alive http://aprs.gids.nl/nmea/  ..... note: GSV lists satellites in view


text:
UltraSonic Sensor with an ESP-01 Standalone
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:

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.
#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);
}

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?

I think logic requires 5V, but there is a hack to make it work with 3.3 v : https://www.instructables.com/Modify-Ultrasonic-Sensors-for-3-Volts-Logic-prepar/

you use the right pins. but this pins must be pulled up at boot. if the sensor pulls them LOW, then the esp8266 will not boot. same appiies for ESP-12

You need a Logic Level Converter Module
Because esp8266 01 support 3v and ultrasonic sensor support 5v

And ESP8266 IO pin is 5v tolerant ! https://www.facebook.com/groups/1499045113679103/permalink/1731855033731442

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.

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.

ESP is 5v tolerant. https://www.facebook.com/groups/1499045113679103/permalink/1731855033731442

full size ESP is but ESP-01 is not

What? The CHIP is 5v tolerant!


text:
Powering Arduino Components with AA in Parallel and Series

simulate this circuit – Schematic created using CircuitLab
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.

You've got yourself in a right muddle there. You can't make 3 and 4 or of 6. You need 7. Also there are other factors you need to consider. I'll write a pepper answer when I get to my computer later.

According to specs, HC-SR04 uses 15mA. I think it is safe to power it through Nano 5V pin. And then you need just to power only your Nano.

Newer HC-SR04's will run off 3-5V, which makes things easier.

Yeah, don't try to get cute with "lowballing" the input to the Nano. The built-in linear regulator is a big power waster. As Majenko says in his excellent answer, you're much better off using an external buck regulator to power both devices at a full 5V. Those are a LOT more efficient than linear regulators (which convert excess voltage to heat)

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:

simulate this circuit – Schematic created using CircuitLab
(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:

simulate this circuit
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).

Thanks, why will only the 4.5V outupt drain BATT5? The upgraded hcsr04 is intriguing since I need my battery capacity to last longer than AA batteries in series.

Not only the 4.5V output. But batt5 will be the first to go flat. It has less capacity than the 1/3 or 2/4 pairs, and it is being used by both outputs. It's the one battery that is weakest in the chain. One of the smallest batteries with the most current being drawn from it. Batt6 has the same capacity as batt5 but only a tiny current being drawn from it for the 6V output.


text:
Fail to upload sketch when Arduino Nano is connected to breakout board
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?

What breakout board do you have? Does it use the serial interface? Upload is done via serial. So if you block the serial interface with some other device, you cannot upload

Thanks chrisl
I think it's this one: https://www.jvzdigitalsourcing.com/products/arduino-nano-breakout-board
I think it's supposed to work with serial interface though, because the school provided all the hardware I'm using (it's for a course), and one of the things we need to do in this course is to control some motors via serial interface.

Have you pins 0 and 1 connected to anything?

Nope, 0 and 1 not connected to anything

!!!! I realised the RXN and TXN pins connecting to the bluetooth module are 0 and 1 pins! Oh god!

I unplugged them and now it's okay :) Thanks!


text:
Can't upload sketches or flash Nodemcu 1.0 12E (CP2102) but have drivers and responds to RST on Serial monitor
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.

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

When i press reset on the nodemcu and have the serial monitor on at 74880 baud the board spits out this.

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

You must not have the serial monitor open while programming the board. The response from the board ends up going to the serial monitor instead of to the esptool.py process that's doing the programming.

no lol i never have the serial monitor open while i try to upload. i put the screen grab just to show the nodemcu can talk back .

Ok. Try selecting a different "Upload Speed" in the Tools menu.

um tried all , still nothing unfortunatley

did you try to put the mcu in bootloader mode manually? holding the flash button while resetting with the reset button?

yes i did and it doesn't fix the problem :( and even tried putting a 10uF capacitor between EN and ground.

did you solve it? what is printed in Serial Monitor at 74880 when you reset while holding the FLASH button?

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.


text:
Why impedance between I/O pin and ground drops when Arduino is not powered
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 !

you prevent it by not sending a signal into an unpowered arduino ... you should not be doing that in the first place because you can blow out the input protection diodes

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.

I can make sure Arduino is always powered, but Arduino will briefly reset when programming or initiating serial com.

@7E10FC9A reset is not unpowered

Adding a resistor (for example 10kΩ) between the signal and the Arduino pin is a reasonable compromise.

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.


text:
How do I add or subtract to a pre-determined value without having it default back to the original value?
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();

             }
      }
    }
 }

}

Using a 'long' and dividing by 2.54 might not get the result you want, use a float.

You wrote:

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:
// In global scope:
int correction = 0;

// In loop():
dist = ...;
inches = dist * 0.3937008 + correction;  // correction added here
ftin = (inches/12) * 100 + (inches%12);  // 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.

Monster it sure is haha. I'm making a rangefinder for focus pulling on Cinema Lenses. Our lenses are imperial so rather fork out money for metric lenses, in comes the monster. Can't thank you enough for the clear explanation, it worked!


text:
Reverse engineering LIN bus on E-bike system
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:

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:

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?

I know nothing about LIN, but the datasheet of the transceiver should tell you, how it communicates over Serial. Then you should be able to extract the LIN packages from the serial stream.

please post the captured serial communication as text, not as a picture

Where is the Arduino in this?

this may help you ... at 1:32  ... https://m.youtube.com/watch?feature=youtu.be&t=92&v=tu8Ow6fJm1g

@chrisl Well a transceiver is just like a translator, it translates uart into LIN and vice versa. I doesn't understand the conversation nor does it choose how fast the communication is (baudrate). Apart from that I did check the datasheet (http://www.farnell.com/datasheets/1678261.pdf). Thanks anyway for putting effort to helping me!

@jsotola Yes you are right, that would be more helpfull. I didn't succeed in termite logging the hex values of the traffic though (It always seems to log the ascii values) But I will copy it from to program tomorrow and change it here :)

@Majenko Indeed, I get that this is not yet an 'Arduino' project. My goal is to attach an Arduino in the end to send certain LIN commands to spoof my sensors.

@jsotola Yes thank you, I've seen the video. To bad I do not have acces to an oscilliscope with does LIN decoding. But its a good video to become aware of what mathers (LIN version, baudrate, ...)

my comment is about the signal trace on the oscilloscope screen, not about the oscilloscope itself

@SvenOnderbeke Mhh, from what I read just now, LIN is at least similar to UART with different voltage levels and a protocol imposed on the data stream. I would try to find individual packages in the data stream, that you captured. Looking at the captured data, the bytes 0xfdfe seem suspicious to me.

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

Thanks Bernard! This seems like the exact kind of answer I was hoping for! I will go and try those out. Thanks for your help!

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


text:
RS-485 Serial communication problem with arduino
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:
void setup() {
    Serial.begin(9600);
}

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

Rx code:
#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.

your code is not really legible as presented ... please format it properly

What if you print to the serial terminal of the receiver, instead of trying to display it on the LCD?

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

There is no mention of 'modbus' in the question, this is basic RS485. In two-wire, half duplex RS485, the 'transceiver' usually has a pin that should be pulled high or low. (Yes, modbus uses this as a physical/electrical layer in some cases)

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.


text:
Leading Zeroes on Arduino Ethernet MAC Address
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?

0x01 is 1. the server prints it wrong

Yep, apparently, found out that it is the server that has a problem.

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 %02x to make sure that zeroes are padded.


text:
I want to make mesh network with nodemcu (esp8266)
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.

How will your nodes find / connect to each other? Basically, keep a table of which nodes connect directly to which other nodes, distribute updates to this table among all devices (for example when devices join, leave or links break) and use this table to find the shortest path to the destination node.

Can you provide some details (i.e. code) as to what you have done so far and what the problem is that you have encountered?

till now i only tested nodemcu range and communication from master to slave. but i wanted to extend more to communicate all the node mcu's with each other.

i got some ways to broadcast the data using MAC address of receivers. but the problem is how i connect all the nodemcu as STATION and AP mode at the same time. in mesh network in which all the nodemcu are communicating each other.

there are libraries for this already, i have used this one, but i have not tested the mesh function yet

im using painless mesh


text:
Can't turn off fan using PWM and analogWrite(x, 0)
I'm trying to make PWM Signal Generator with Arduino Uno.
I'm trying to control 230V 50hz "NRG118" 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". 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);
}

Can you look at the PWM signal with a scope when driven by the HW-753 and when driven by the Arduino? What happens when you wire PWM and GND together?

I can't. I'm just a developer who has nothing about electronics. I have only a Multimeter.:)
I didn't wire PWM and GND together. What is the logic behind this?

If you short PWM and GND (remove PWM from any Arduino pin!), you make sure that you have the lowest possible value. Now check how your fan is doing.

Thanks I will try that. Also I figured out that if the PWM pin is not using it means 0 volt but the fan works with highest speed. So PWM pin shouldn't be 0volt. Maybe I need to give a special voltage to stop it? In this diagram it looks 0.8-2volt. https://www.allaboutcircuits.com/uploads/articles/voltage-tolerance-of-ttl-gate-inputs.jpg

So to stop the motor I need to give special PWM voltage. I think analogWrite(6, X);  the X should be between 50-100. How can I learn what PWM output needs the fan to turn-off?

Looking at some datasheets, I think, anything less than 20% duty cycle means OFF. Which would X < 50 (and X>0).

Considering a common 4-pin PC fan (I know, that's not what you have) it is not possible to switch off. All my 4-pin fans are running at ficed rpm when PWM is below ~20%. To make it stop I need to cut Vcc. Posdibly your fab behaves the same way

If I wire 5V to FAN controller card,  PWM+GND fan can stop the fan. But if I directly wire Fan's "5V, GND" to a adapter then PWM has no effect on arduino. If I wire "5V, GND" to arduino then PWM can drive the fan between %10-70 DutyCycle with "analogWrite(PWM_PIN, 0-255);" but can not stop the fan. What should I do?

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.

Am I missing something, AC motors are typically controlled with phase control, not PWM.  Just a SWAG as the AC portion circuit is not posted. Typically on AC the motor will be driven with a Triac or SCR. Timing for firing is from the zero cross, once for each 1/2 cycle.


text:
Cutting neopixel routine code short
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.
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 ();
    }
}

simplest reduction .... do not repeat code unnecessarily .... you have if a>0 do x ... else if a>1 do x,y ... else if a>2 do x,y,z ......... instead do if a>0 do x ... if a>1 do y ... if a>2 do z

First, a small remark:

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.

if ((level>= 1)&&(level<2))

There is only one integer that verifies this condition. It would be
clearer then to just write
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:
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:
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.

Brilliant! It worked fine at the first try. Thank you so much for your programming lessons. Best regards from Spain.


text:
I want to create 10 levels with one button but this code shows only level 1?
#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();
  }

I think if (level >= 10) { should be if (level < 10) {?

Your button reading code doesn't work. It only registers a button press if the button is pressed, when the code is exactly between the two digitalRead lines. Which is very unlikely. Try adding a few more variables, instead of trying to use the buttonState for three different purposes. Hint: use buttonState for the current state of the button; use something like oldButtonState for the state of the button in the last loop; and use something like buttonPressed to indicate when the button is first pressed down (which you then use to increment the level)

thank you! I will try to use the oldButtonState and buttonPressed.

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:
int level = 1;

Its initial value is 1. Then it is updated here:
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
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.

oow i understand it thank you!! what do i have to change to change the value?

@louisemoons: Under what condition do you want level to be incremented? Can you complete the sentence “level should be incremented if ...”?

Another, stronger hint. Your current code says "if level is greater than or equal to 10, increment it." It starts at 1, and no other code changes it, so that if statement will never be true. Don't you want to increment it if it is less than 10?

@EdgarBonet level should be incremented if pressing buttonpin


text:
Programming an arduino using only switches to give 0 or 1
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?

Welcome. I'm not understanding your question. What is 'it'  you want to program? For programming an Arduino you need a PC. You can use switches without an Arduino, but I also don't understand what you  mean with 'send data' (to what?).

Ok, that sparks the question, why you cannot use a computer. As you are able to get an Arduino, I guess you could also buy other electronic components. If a PC is just too expensive, you could go with a Single Board Computer like the Raspberry Pi. Depending on which Pi board you buy, it costs 10 or 35$. 1 standard USB charger (with over 1.5A), an SD card (which can be bought with an OS on them), cheap USB Keyboard/Mouse combination and any HDMI capable display. And a USB cable for the Arduino of course. Then you are good to go. It is like a full fletched PC, just smaller and not that fast.

@chris Thanks for the suggestion!Well I have been having serious problems with my pc currently such that it won't compile nor interpret any code. That's why I had been looking for an alternative

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.

The First Arduino had a "serial" port and the more recent have a serial USB interface. So to be correct, the Arduino is programmed with a serial interface.

@MatsKarlsson, thanks for the correction. I edited my answer accordingly.

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.

Oh..thanks a lot!Atleast now I am getting to know the internal workings of the arduino a bit...But of course I won't attempt it

Oh wow. That's going really primitive. You'd need debounced switches though. I wonder how many KB of data you'd need to send through the serial interface in order to enter a trivial program like "blink"? Not to mention the work to hand-compile the code, and then map the program into the data-stream needed to program it.

@DuncanC Yep. Physically possible. Emotionally possible? Nah. You would need to be really really desperate for something to occupy your time, plus a coffee IV and colostomy bag...

@DuncanC: You can write “blink” in assembly in less than ten 16-bit instructions. It wouldn't take too long to assemble it by hand. But then, the overhead of the ICSP protocol may be a lot larger than the program itself...

but if you construct a punch card reader to switch the switches ... :-)

This projects sounds a lot like trying to program in the Brainf*ck language (google it if not familiar. It's a real thing.)

@DuncanC I remember it well... I once did write an actual program in it...

Oh this is bringing me back 45-50 years when I did this with a Z80 CPU, it was tedious and fun.... I would choose another processor than the Atmel AVR family.

@MatsKarlsson, did what? Programmed a Z80 with shift registers and switches? Or do you mean writing machine code by hand and entering it in hex? I've done a fair amount of that myself, but mostly on the 6502. (I've done a little Z80, but with an assembler)

It was writing assembler on paper, convert it to binary and then with dip switches or was it toggle switches, enter the code and then step to next address location for the next row. After that I did a hex keyboard and 7-segment led display.


text:
Low power USB C power supply
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, 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?

If you can't find one, design your own.

I would, I just  don't have the equipment to assemble it. Also, the project is really not that important...

Cut the end off a USB C extension cable and wire it in directly.

takes too much space, sadly...

More space than the cable you'd be plugging in anyway?

by extension cable you mean a type c with male on one end and female on the other?

Yes. Have the socket "remote" from your space constrained device.

I see. Sadly, that defeats the purpose in my case. I could just aswell cut a male-male cable and hardwire that. Although it's quite creative.

Have you considered not using USB C? There are plenty of other small connectors.

Sure. Seems like I am falling back to usb micro. I thought that if I am already building a device, it could be C aswell..

It would make sense from a future-proofing PoV. It's still not common in the arduinosphere though - there's not many boards that use it. I think I only have 2 USB C cables in my possession, and one of those is for a Pi 4.

I'd cut that board. Solder some wires to the GND and VCC planes. I don't think those resistors are needed if you use less than 100mA. Though I'm not that familiar with USB C. You might be able to move them with some creative soldering.

sadly, usb c doesn't provide 5v just like that, so some sort of configuration is needed...


text:
9 volt battery not being able to power motor driver
Currently I am using a 9 Volt Duracell A one like this:

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.

Voltage is not the be all and end all. Power density and current delivery are more important, and PP3 batteries fail at both.

that battery contains six AAAA cells ... think about the difference between AA and AAA

This question has been asked several times on this site. A quick search gave me  this question and this question. Both explain, that 9V block cells are not up to the job of driving motors

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.

Does this mean that I have destroyed my 9V battery

Used it up, more likely. If you have a volt meter, measure the output voltage. If it's much less than 9 volts, the 9V battery is too weak to be useful. Those are disposable, and don't have much "juice" even when they're new. Toss it and get a bigger battery.

Oh dear........


text:
Using Arduino to create a countdown that unlock a box
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.

see the BlinkWithoutDelay example.

Some kind of display to show the remaining time. Either an LCD display, or a 4-digit 7-segment display. For the latter, there there are breakout boards that already have the needed circuitry to driver them. For the latch, you could use a servo. Or alternatively a solenoid.

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

You should probably have current = (millis() - startMillis) / 1000; in loop(), and no current++.

I tried to make it simpler to understand, but you are right: I’m not taking into consideration any time spent while looping. Also consider that the loss will almost always be in the order of 10-20ms... but you are definitely right: my “clock” implementation will drift for sure


text:
Help needed!!! I have an upcoming exam
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?

Why don't you use the material your teacher provided you with? Or aren't there any sources? The ardiuno.cc site teaches you some basics https://www.arduino.cc/en/Tutorial/HomePage . But that's lot of stuff, so i would prefer the material from school. If you have an Arduino to use it, you can install the Arduino IDE and try some of the examples and learn from it.

Don't you mean "blink without delay"? The point is that the delay() function is to be avoided.

You should get an Arduino, a couple of LEDs, properly sized current limiting resistors, and spend a couple of days figuring out how to write a sketch that blinks the 2 LEDs at the same time on different intervals (Say you blink the first LED on and off every 3 seconds and the 2nd LED every 2 seconds.) If you figure that out, you will understand using millis() to manage timed events well enough for an exam.

There are tons of tutorials on the web about this (if you search for terms like "arduino blink without delay" or "arduino millis"). Even on this site the principle has been described numerous times. You should read some tutorials about it. If you don't have the actual Arduino hardware, you can use a simulator like from tinkercad. Try, what you have read in the tutorials and you will be able to figure this out fast.

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! ;-)


text:
Arduino UNO generate square wave, which is exactly the same with trigger pulse, but with a time delay
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!

I'd forget the idea of "generating a square wave". Instead I'd just watch the incoming signal and replicate it x time in the future. If you see a rising edge then think "I need to generate a rising edge in x ms" - and the same with a falling edge.

thank you but the rising edges in triggering pulses  are not importatnt. It is for reminding when using interrupts as it will be trigger twice in one cycle.

@chris I don't understand your comment. If the triggering pulse is not important, then why should the output be exactly the same? Majenko suggested just writing code, that reads the pin (maybe through interrupts, maybe without), delaying and then outputting that value onto the output pin

how can you have two rising edges in a cycle?

I mean exactly the same in terms of duty cycle and frequency. I tried but the phase between two pulses are not stable.

Here are the main codes:
void loop() {
InputState = digitalRead(interruptPin);
if (InputState == HIGH){
delay (DelayTime);
digitalWrite (OutPin, HIGH);
delay (TriggerPeakDuration);
digitalWrite (OutPin, LOW);
delay (T - TriggerPeakDuration - DelayTime);
}

please put the explanation and the code into your question .... format the code properly

digitalWrite() and digitalRead() are extremely slow. Plus the loop() function is called in a loop, so the CPU has overhead when the function returns and is called again (jumps). This all introduces delay in the execution if your check-and-set-pin logic, thus the result you see is totally expected. See https://www.youtube.com/watch?v=D0Hr24QDD-s.

You may just want to rewrite it to use interrupts and a timer. As in, interrupt fires, you set the output, arm a timer with some expiry time, the timer interrupt fires, you unset the output. CPU can mostly sleep then, too.. If that's not possible, at least use digitalWriteFast() and friends, and unrolled loops..


text:
Whatever components we connect to the Arduino, their grounds and 5v pin connection must be the same?
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.

If u didn't understand I can explain you

I understood it now, by the way thanks for asking

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.


text:
ESP8266 RF Calibration
As an off-Topic to my main question, 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. 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

Every ESP8266 schematic I can find has a 5.6pF capacitor between the LNA pin and the antenna. Robotdyn's doesn't - it has a resistor. Looks like they aren't that great at designing RF circuits...

@Majenko - So by definition it has no WiFi ? Can it be fixed ?

I'm not so sure. I'm going by the schematics here, but they don't seem to match what I am seeing in the product image. What I think is R13 looks to actually be a capacitor... It looks like there's no real relation between the published schematics and what is really on the board.

@Majenko - See Edit1 please ( to be sure )

Yeah, I had been following your original question.

I think the schematics were drawn by a child. They haven't even got any component values on them...! They're useless.

@Majenko - it could have been funnier if I hadn't purchased it :).
Do you know what might be the drivers for ? under "Documents" tab on their site

They'll be for the CH340G.

Have you closely inspected the soldering of the ESP8266 chip on your board?

I'm using linux - that I could find ( that it belong to CH340 ). But under Windows, it actually have an exe file

@Majenko see pic. Don’t see anything suspicious

Ok, looking at that I can tell you that there is a capacitor fitted to connect the LNA to the u.FL connector. What value that capacitor is I can't say. There is no capacitor fitted to use the PCB antenna. So you must use an external antenna (make sure it's a 2.45GHz one) or modify the board.

Looking at the colour of that capacitor for the u.FL it looks way higher than 5.6pF. More like 1nF.

@Majenko - I took it from Wemos D1 mini Pro I guess it is what needed. As said - with or without  the antenna, I get nothing.

I'd be inclined to removed the u.FL capacitor and solder in a known 5.6pF into the PCB antenna capacitor footprint.

I would try to upload AT firmware. forum users reported QOUT setting for flash

@Juraj - how can I do that ?

https://blog.gabrielcsapo.com/arduino-web-server-mega-2560-r3-built-in-esp8266/

@Juraj - Excellent reference!!

it has some problems, the author didn't want to change. he wrote it based on a forum session with me. you can download the AT firmware 1.7.4 here https://www.espressif.com/en/support/download/at?keys=&field_type_tid%5B%5D=14

@Juraj UPDATE: using the blog, each step was done successfuly, incl. downloading the firmware as you pointed, yielded the same result ( using ext. antenna ). :(((((  - while my basic check is network scan ( no networks found ). what can I do more. ??

so return the board or you could try the hardware fix recommended by Majenko

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

Thank you again. From FAQ, I don't have any operative steps what to do.

flash blank.bin to 0x3FB000  or erase the entire flash.

Erasing using esptool.py ? since erasing using Arduino IDE did not solve it

Arduino IDE uses esptool.py. btw. what are your Tools menu settings?

Right... silly me. I'm setting Generic ESP8266 Module... now when I'm thinkg of it - the default is 1MB. Is that what you ment ?

set 4 MB end try to erase the flash again. but I think the esptool.py is not fooled with the setting when it executes the erase

Nope - setting to 4MB, nor to Wifi Arduino under ESP8266 didn't make it :(


text:
Can I use and external power supply and USB at the same time on my Arduino?
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,
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.
What happens if I power the Arduino with both the USB and external power voltage simultaneously?
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,
Is supplying 5V from both external 5V and USB harmful?
The external power is this,
9 VDC 1000mA regulated switching power adapter

don't use the arduino as a power supply for the LEDs

Don't I power the Arduino and run the wires through the GPIO?

you do if you want to use the arduino as an expensive fuse .... GPIO pins have a limited current source/sink capacity .... the internet has many examples of controlling high current devices with a microcontroller

Besides the limits of the signal pins, the 5V pin on the arduino cannot supply as much current as your 9V 1A wall wart. Question is, how you power more LEDs ?

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.


text:
Run HEX program from SD with another program
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"

this may work ... https://arduino-forth.com/

Bootloaders like Optiboot accept a program via UART and burn it into the flash of the MCU. That code is openly available: https://github.com/Optiboot/optiboot/blob/master/optiboot/bootloaders/optiboot/optiboot.c. With lots of effort, you too can write a bootloader which loads a compiled (or intel hex format) sketch from an SD card via SPI. The nearest project to that that aI could find is https://github.com/zevero/avr_boot which looks for a FIRMWARE.BIN on the SD card, programs the internal flash and runs it. You might want to modify that.. or, do it on another MCU with less restrictions

@MaximilianGerhardt, burn SD bootloader and then you use SD library to copy the selected file to firmware.bin and reset. the new firmware should have the same capability of selecting a firmware

@MaximilianGerhardt If you wish to answer the question, please post an answer.

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) 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.");

Sorry, but I don't understand how to link HEX files from SD card for a specific address in flash. How to do it?
I've not found do_sdm() function in Optiboot. What did you mean?

there is a link in the answer 1) see how bootloaders are compiled and linked for specific address

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.


text:
Stepper motor not working as expected
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

Can you please show your code and your wiring? A vibrating stepper motor suggests, that the phases of the motor are not driven in the right order. I already wrote an answer to a question about the 28BYJ-48 stepper and the ULN2003 once. Maybe it helps you: https://arduino.stackexchange.com/questions/57089/stepper-motor-wont-reverse-turn-ccw/57095#57095

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


text:
Arduino Uno R3, WS2812B, 1 strip of 60 leds, segmented in to 4
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();
}

and doesn't it? ... what is your question?

aren't they individually addressable LEDs?

look at example code in the arduino IDE

your post doesn't say much of anything about what you are trying to do  ... the example code is right there in the Arduino IDE on your computer

Please let me explain this more.  I have 1 strip of 60 leds, segmented in to 4 parts with 4 different FX_MODES and colours. I only want 1 segment or FX_MODE to be ON at any one time...  Segment(0, to be ON and the rest are OFF.  Next Segment(1, is ON and the rest are OFF. Next Segment(2, is ON and the rest are OFF. Next Segment(3, ON and all the rest are OFF.

You can help by putting the additional information in the question by editing it. As it is now, your question only consists of unformatted code with no descrtiption of what's wrong with it or what you're trying to accomplish. It's unlikely to be answered like this.

You have to look at the ws2812fx library to see what the code is doing. I think it is described pretty well here, including how the setSegment function works. You can leave out the ws2812fx.setSegment(1, ...) to (3, ...) to stop using that segment. You can change the amount of LEDs in a segment with the second and third parameters, i.e. ws2812fx.setSegment(0, 0, 4, ...) will only light the first 5 LEDs (0..4). Just experiment a bit with the parameters.

I'm just an unpaid volunteer trying to help you in my free time, which I will stop doing after your comment. I can't read your mind. You need to put all of this information in the question. What about "pause/delay/time/count"? It's not in your question. How was I supposed to know that you already changed the amount of LEDs in each segment? You did not mention it anywhere.

I've tried to read everything I could on here and in library examples, on youtube and google.  Finally post a question here at 3am as I thought the problem would be obvious to a pro.  It's now 5am and way past bed time lol good night

Your question reads like: "Problem: I want to bake a cake. Here is the recipe". You don't say what actually happens when you follow the recipe. Even a pro can't answer that.

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.


text:
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
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);
}

check the result value of readBytes. before readBytes check available(). readBytes waits a second for a byte, the it returns count of bytes read. so it could be 0

Is Slave's Serial connected to Master or to SerialMonitor? Serial is not a bus.