text:
Arduino read PWM duty cycle value with input (analog / digital)
I am working on comparing autopilots like Ardupilot, CC3D, KK2.1.5. The comparision is about system reactions/behaviors that it gives during flight. For this purpose, I need to read the PWM duty cycle (like osilascopes - the PWM frequency can be vary from 50 to 430 Hz) values from autopilot card. There are 4 command input PWMs and 4 esc control PWMs for a typical quadrotor. I have to read 8 duty cycle values with digital/analog input pins. How do I measure duty cycle of 8 PWM signals?  Also, is digital or analogue measurement precise and faster?
Note about attachInterrupt command: According to arduino.cc AtMega328 series have 2 interrupts, Arduino ATmega 2560 series have 7 interrupts.

The code shown in my answer to question 18183, “Read RC receiver channels using Interrupt instead of PulseIn”. That answer has code to read four channels of RC PWM.  It can easily be adapted to work with eight channels.  It has an ISR that runs when selected pins change.  It sorts out which channel(s) changed, and stores the value of micros() at each change.
Also see my answer to question 19106, “Can external interrupts be OR'd together on the '328 (Uno)?”  That answer includes a sketch for generating appropriate ISR code.  My answer to question 32572, “How to detect the direction of a rotary encoder?”, shows another instance.
Digital input, as used in the code mentioned above, takes under  a microsecond ten microseconds in the ISR.  As noted in dannyf's comment, unrolling the for loop and (where possible) using constants instead of variables can reduce the in-ISR time to 3.4 μs.  Note, ISR entry and exit still add several microseconds.
10-bit analog input, on the other hand, will take around 104 microseconds per reading, a time comparable to some of the pulse widths you'll be measuring.  So it isn't fast enough.  If degraded ADC accuracy is acceptable, decreasing the ADC-clock scale factor as explained in a webpage at microsmart.co.za can get AD conversion time down to 20 μs.  This is around three times as long as digital input takes, so rather slow.

takes under a microsecond in the ISR, I find that unlikely. Obviously, I'm not sure which code pieces you were talking about - as they are three of them. but a causal look on them would suggest that it will take more than 16 ticks to execute the body of the ISR - not counting the overhead. As a matter of fact, a little birdie of mine said that it would take close to 8us to execute them on an Uno, :)

@dannyf, I was looking at one of the simpler ISRs (single encoder counting) when I wrote that, so will need to edit answer with correct time.  Sorry!

not a problem. two suggestions: 1) unroll the while loop; 2) use constants rather than variables. and I would also make rcOld a static inside the ISR so the code is more modular. with that, I got the execution time down to 3.4us.

Can you share your code instead of links. Also, AtMega328 series have 2 interrupts, Arduino ATmega 2560 series have 7 interrupts. So how can I measure 8 simultaneus PWM signals? https://www.arduino.cc/en/Reference/attachInterrupt

@acs, ATmega328's have 26 different interrupt vectors.  The vectors used in the referenced code are for pin change interrupts, or PCINTs, which use 3 of those vectors.   PCINTs are available on 22 of the  ATmega328-based-Nano pins, and a similar number on Uno's.  Please refer to the code shown in the previous questions -- at the moment I have work deadlines to meet.

@jwpat7 This link says there are only 3 interrupt vector ==> http://playground.arduino.cc/Main/PinChangeInterrupt  So, how did you do this possible? I couldn't find any solution. Please share your code.

@acs, Are you unable to follow the links and look at other questions on Arduino stackexchange?  In particular, see my answer to question 18183, linked in first line of answer above.  That code handles 4 RC inputs and can be adapted for as many as there are pins for.  ¶  Note, each of the 3 PCI vectors has 8 pins assigned to it.   ISRs can read ports and figure out which bits changed.  ¶   I have some 8-RC-inputs code (adaptation of that shown in answer to 18183) that I can post after some more  work deadlines; a couple of days from now.

if done in analog, run the pwm through a lpf and perform an adc on the output;
if done in digital, use a timer's capture function, or use external interrupt / pin change interrupt to capture the timing off a time base.


text:
Programming standalone Atmega328p-PU with NE555N timer IC
I know I may sound a little idiotic to ask, but as I have seen in the internet that to program a standalone Atmel chip like that from of the Arduino's, you need 2 22pF ceramic capacitors and a 16mhz oscillator. As the oscillator is needed is clock the frequency of the chip, so a timer IC should work just fine, isn't it? or do I have wrong information?

You can provide an external clock on pin PB6, but you'd need to set the correct fuses to select the External Clock option. But if you need to change the fuses, you might as well set the fuses to use the internal 8MHz RC oscillator, and negate the need for a 555 or crystal.

No, you won't be able to build a 16 MHz clock signal using a 555 timer. That's far beyond the 555 capabilities (see N.B.).
If you could squeeze out of the 555 a mere 1 MHz (which I seriously doubt), the clock stability and jitter would be so bad that it won't be usable but for simple sketches not requiring any timing accuracy. At that point, you would be far better off using the internal 1 MHz RC network of the ATmega328P as Majenko says, because you would at least save the 555 and its associated components.
Also, a 555-based clock would consume much more power than any of the alternatives already available to you (internal oscillator, external crystal...). Even the CMOS version.
My recommendation: forget about it, it's not worth it.
NOTE BELOW:
NE555N is a BJT version of the 555. BJTs suffer from what's called "storage time", a charge accumulation in the base that severely limits switching time. The NE555N datasheet states a storage time of about 10 microseconds (p.10), which limits the switching frequency to about 100 kHz.
TLC555 is a CMOS version of the 555. Because it uses FETs, its maximum switching frequency is much higher. The TLC555 datasheet (p.6) states that a typical value for the maximum switching frequency is 2.1 MHz (and at least > 1.2 MHz).

Yes, you could use a 555. You can also go even simpler and use an RC network. Even simpler still is to use the 1MHz RC network built in to the chip.
The main drawback of these methods, and the 555 particularly, is that of stability. Using a crystal and capacitors you can get very accurate timing at high frequencies. Using a 555 you can get ballpark timing at low frequencies. Fine if all you want to do is blink an LED, but as soon as you need to do anything that requires good timing it all falls apart. That includes things like using the UART for which accurate timing is at the heart of its operation.
The internal oscillator is better in this respect since it can be calibrated using the OSCCAL register. However changes in ambient temperature can cause unacceptable drifting of the clock frequency.

The default configuration of these chips, as they come from the factory,
is to use their internal 8 MHz RC oscillator downscaled at 1 MHz. So you
do not need any extra oscillator to program them.
Once you program the chip the first time, if you configure it to use
an external resonator/oscillator, then you do need to have that
attached in order to reprogram the chip.
A 555 may be able to run the chip, but if you want to reprogram it, the
programmer may not cope well with the extra-low frequency the chip would
be running at.

It depends on how you're programming it.
If you're using a bootloader to accept programming commands via a serial connection then you will need to use the clock method specified by the fuses currently programmed, since the chip at that point will actually be running code programmed on it.
If you're using ISP to program the chip out-of-band then you can apply a clock source directly to the XTAL1 pin as shown in the "Serial Downloading" subsection of the "Memory Programming" section of the datasheet. In this case you will need to adhere to the timing information given at the end of the subsection.

source: Stack Exchange

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

sort: votes


text:
Arduino LED Dimmer Proportionate to Ambient Light
I am trying to get an LED dimming reversely proportionate to natural light level in a room.
So as the sun rises, the LED dims and vice-versa.
I am using the standard LDR+ 10k Ohm resistor divider, an LED, and an Arduino Leonardo Clone.
The issue is, regardless of the values I adjust in map(), it does not change the flickering rate or brightness of the LED.
What range of map shuold I be using?
The LED ought to shut off while the LDR takes a reading.
I have two variations of the code; one uses PWM, the other simulates PWM using delay()
Here are my sketches:
/set pin numbers
//const won't change
const int ledPin = 1;   //D1 the number of the LED pin (OR to MOSFET input wire for controlling high power LED
const int ldrPin = A0;  // A0 the number of the LDR pin
//10K ohm resistor as voltage reference.

void setup() {

  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);  //initialize the LED pin as an output
  pinMode(ldrPin, INPUT);   //initialize the LDR pin as an input
}

void loop() {
  digitalWrite(ledPin, LOW); //Shutoff LED invisibly rapid to get a reading of the ambient light without the LED on
  int ldrStatus = analogRead(ldrPin);   //read the status of the light sensor value
  // KEEP LED OFF TIME BASED ON AMBIENT LIGHT LEVEL...
  int dim2 = map(ldrStatus, 0, 1023, 500, 0); //OFF FOR UP TO 0.50 seconds.
  digitalWrite(ledPin, HIGH);
  delay(dim2);

   }

Sketch two:
//set pin numbers
//const won't change
const int ledPin = 1;   //D1 the number of the LED pin (OR to MOSFET input wire for controlling high power LED
const int ldrPin = A0;  // A0 the number of the LDR pin
//10K OHM resistor as voltage reference.

void setup() {

  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);  //initialize the LED pin as an output
  pinMode(ldrPin, INPUT);   //initialize the LDR pin as an input
}

void loop() {
  digitalWrite(ledPin, LOW); //Shutoff LED invisibly rapid to get a reading of the ambient light without the LED on
  int ldrStatus = analogRead(ldrPin);   //read the status of the light sensor value
  int dim = map(ldrStatus, 0, 1023, 255, 0);     // scale it to use it with the LED (value between 0 and 255)
  digitalWrite(ledPin, dim);               //Flash LED at that rate to adjust brightness.

   }

Why do you think you should be using digitalWrite()?

I was mistaken. I switched it to analogWrite() , but no changes happened.

You need to use PWM pin, like pin 3, but  different sets for different Arduinos.

For certain Arduino models, the PWM pins are different. For the iteaduino lite, a usable PWM pin is pin D5.
Here is the code updated to use D5 instead of D1, which lacks PWM abilities:
//set pin numbers
//const won't change
const int ledPin = 5;   //D5 PWM the number of the LED pin (OR to MOSFET input wire for controlling high power LED
const int ldrPin = A0;  // A0 the number of the LDR pin
//10K OHM resistor as voltage reference.

void setup() {

  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);  //initialize the LED pin as an output
  pinMode(ldrPin, INPUT);   //initialize the LDR pin as an input
}

void loop() {
  digitalWrite(ledPin, LOW); //Shutoff LED invisibly rapid to get a reading of the ambient light without the LED on
  int ldrStatus = analogRead(ldrPin);   //read the status of the light sensor value
  int dim = map(ldrStatus, 0, 1023, 0, 255);     // scale it to use it with the LED (value between 0 and 255)
  analogWrite(ledPin, dim);               //Flash LED at that rate to adjust brightness.
  Serial.println(dim);
   }

There is still flickering, but that is to be expected. map() ranges can be adjusted to set when the LED will be fully off or on.
It is still unclear how to allow the light sensor to take a reading while the LED is OFF, then power back on rapidly enough to not have a visible flicker.
If anyone has thoughts on that, it would be appreciated!
Thanks everyone for helping.

analogRead() is slow. You should consider using the ADC at a lower level if you need improved speed.

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


text:
How can I make motor vibrate using arduino depending on the ultrasonic distance?
I want to make the vibration motor vibrate depending on the distance to an obstacle, for example if the distance is too short it should vibrate quickly and vice versa.
How can i make motor vibrate using arduino depending on the distance?
Can you explain for me how can I use the delay in the vibration code?
I found this code in the internet for vibration:
digitalWrite(y, HIGH);
delay(50);
digitalWrite(y, LOW);
delay(50);

I know that I can change the delay, but how can we do it depending on our purpose?
Please help me .. I don't know the use of the delay :(

You could just replace the "50" in the first delay with the ultrasonic distance variable, I'll explain a bit more below.
Let's assume your ultrasonic sensor outputs an analogue value between 0V and 5V. The output is connected to analog pin A0. Then you just set pinMode(A0, INPUT) and analogRead the value from the pin and store it in the variable X or whatever. Then you just use the variable X as a delay and it will do what you want. The higher the value gets the longer it will vibrate. Something like this:
[...]
val = analogRead(A0);
digitalWrite(5, HIGH);
delay(val);
digitalWrite(5, LOW);
[...]

Second option, if you only wish to turn it on if it is above or under a certain limit, would be using an if condition.
For example:
if(variable > 50){
  // if the variable named variable is over 50 this code is going to be executed
} else {
  // If the variable is below 50 this is executed
}

If you are unfamiliar with if conditions then I suggest reading this too.

I know that I can change the delay, but how can we do it depending on our purpose?

Are you asking how to use a variable? An example:
const int LED = 13;

void setup()
  {
  pinMode (LED, OUTPUT);
  }

void loop()
  {
  int amount = analogRead (A0);   // get a reading
  digitalWrite(LED, HIGH);
  delay(amount);
  digitalWrite(LED, LOW);
  delay(amount);
  }

That code reads some analog device, and adjusts the delay based on the figure it read.

I want to show you my thinking, and tell me please if it is right or wrong:
I build an relationship between the distance and the speed.
I know that (speed = distance/time) and if the obstacle is too close to the ultrasonic sensor the speed of the motor should be maximum, so I have decrease the time which is the delay, right?
I make the code according what i said above and it is shown below:
    if(distance <= 60 && distance >= 45)// the distance is too large
    {
    digitalWrite(motorPin, HIGH);

    delay(200);// I increase the delay to make the motor vibrate slowly

    digitalWrite(motorPin, LOW);

    delay(200);

    }

    else if(distance < 45 && distance >= 30)
    {
    digitalWrite(motorPin, HIGH);

    delay(100);

    digitalWrite(motorPin, LOW);

    delay(100);

   }
    else if(distance < 30){

    digitalWrite(motorPin, HIGH);

    delay(50);

    digitalWrite(motorPin, LOW);

    delay(50);

  }
  else
  {
    digitalWrite(motorPin, LOW);// If the distance is too large the motor will be off
  }

The code is okay, but one of the comments are wrong. Using a longer delay makes the motor spin longer, delay after turning the motor off increases the time between that and the next reading so keep that in mind.

Thanks a lot for replying, but u didn't tell me if my thinking is right or not according to the equation that i wrote above.. Also, which comment is wrong ?
Can u explain the idea for me more, cuz i got confuse little bit ... :(
Also.. can u give me ur email that will make the communication easier ??
plz reply as soon as u can ...

The first comment and the logic is wrong. You can not change the speed of a motor with a delay, you can change the duration of it being on or off. See my answer below for more details.


text:
anti-theft system
I'm trying to create an anti-theft system, I use a Pir sensor for motion detection and a esp8266 to send a variable (1 or 0) to a local server with tcp protocol and at command . when I turn on the arduino it sends a 0 (no movement) but after it sends only 1 (there is a movement),
she doesn't return to the initial state.
 I tested the sensor alone, it works very well .
Any help please ?
#include<SoftwareSerial.h>
SoftwareSerial Serial1(1,0); //RX, TX
#define DEBUG true
void setup() {
   Serial1.begin(115200);
   pinMode(A0, INPUT);
   pinMode(8, OUTPUT);
}

void loop(void) {
   if(digitalRead(A0) == HIGH)
   {
      tone(8, 50);
      Serial.println("hight");
      send(1);
   }
   else
   {
      noTone(8);
      Serial.println("low");
      send(0);
   }
}

void send(int val)
{

   String rest1 = "AT+CIPMUX=1";
   rest1 += "\r\n";
   sendData(rest1, 2000, 0);

   char inv = '"';
   String add = "AT+CIPSTART";
   add += "=1,";
   add += inv;
   add += "TCP";
   add += inv;
   add += ",";
   add += inv;
   add += "192.168.46.102";  // Host_server_name
   add += inv;
   add += ",";
   add += "80";
   add += "\r\n";
   sendData(add, 3000, 0);  // Establishing a TCP Connection. ( AT+CIPSTART = "TCP","Host_server_name",80 )

   String rest = "AT+CIPSEND=1,87";
   rest += "\r\n";
   sendData(rest, 2000, 0); //Number of characters to send. ( "AT+CIPSEND=90" )

   String hostt = "GET /sp_notification/upload.php?value=";
   hostt += val;
   hostt +=" HTTP/1.1";
   hostt += "\r\n";
   hostt += "HOST:192.168.46.102";
   hostt += "\r\n\r\n\r\n\r\n\r\n";
   String views = sendData(hostt, 2000, 0);  // GET request ( GET /apps/thinghttp/send_request?api_key=XXXXXXXXXXXXXXXX
                                             //               Host: Host_server_name )
}

String sendData(String command, const int Goldout, boolean debug)
{
   String response = "";

   Serial1.print(command); // send the read character to the Serial1

   long int Gold = millis();

   while ( (Gold + Goldout) > millis())
   {
      while (Serial1.available())
      {

         // The esp has data so display its output to the serial window
         char c = Serial1.read(); // read the next character.
         response += c;
      }
   }

   if (debug)
   {
      Serial.print(response);
   }
   return response;
}

Did you try other pins? Why using an analog pin? And I assume you see never the text 'low' except during startup?

yes , i don"t see the text   , i just started using arduino i don"t know difference between pins

Does the tone stop? PS you can use \" to add a " inside a string. So for example add = "AT+CIPSTART=1,\"TCP\", ...";

A0 to A7 are analog (only) pins, the others are digital, you can try to use another pin (except 0 and 1 which are used for RX/TX UART communication), but 2 or 3 should be ok, reconnect your sensor to pin 2 or 3 too, and check if that changes.

yes , bro it s worked , but sometimes even if buzzer run he don't send (1) any suggestion ?

Gerben , when i used analogic port the tone didn"t stop

Michel Keijzers , the sensor find a great difficulty to detect my movement

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


text:
Mechanical requirements for Arduino compatibility
If I want to design an Arduino-compatible board I guess I'll have to use the same outline, and connector positions to fit existing enclosures. (Beats me why they didn't choose a simple rectangular board, which would have been cheaper.) But I wonder if the ICSP header's position is standardized. Some enclosures have a hole above it, but many don't. Can I move the ICSP header to another position?

(Can somebody add a "compatibility" tag? Thanks. Also, neither "mechanical" nor "board" nor "layout" seem to exist as tags. Feel free to improve my generic tagging.)
The "shield" tag was suggested, but this isn't about shields, it's about the ICSP header.

Ah, I misread the question, I seem unable to remove my "shields" tag.

You can move the ICSP header.
Your board will be compatible with everything that does not use the ICSP header.
The casing will still "work", but you would be unable to reach the ICSP header if the casing is on it.

Look at the Uno board and the Mega board for example. Both seem to have the ISP header at the same position. Some shields require it. The only reason for a fixed location would be shield, so that tag is pretty applicable. Also note that if you move it, it might interfere with components placed on the bottom of some shield.

@Gerben: I find your "seem" interesting :-). Does a hard source for it exist? Not to my knowledge. Is there a drawing with the required clearances for the bottom of shields? I seriously doubt it.

Depends on what you define as "Arduino compatible".
My "Arduino Nano" is 'Compatible' but a whole other design.
Or well, it already separates here.
"Software compatible" working with the Arduino IDE and/or Libraries. In general, any board with ATMega 328P / USB or ICSP / Bootloader could be considered compatible.
But, however, for an "Arduino clone" being "Hardware compatible" you could also look at:

Pin placement (Thus being compatible with shields).
Using the same FTDI chip, thus being directly compatible with arduino
drivers (not sure)
Using "exactly" same electronic specifications.
Size and/or shape or even weight of the board.

Strictly, moving the ICSP header will make it 'incompatible' for some shields.
But, well, for most shields it won't be a problem. For casings that have an opening for the ICSP header it'll mostly just look funny.
By replacing the ICSP header it might touch components of other shields/casings and thus be not compatible with it.

(update)
The website and file below are from the arduino site and could thus be considered to be the 'standard' as it's set by arduino. You can however make your board how you want it and compatible with what you want. But changes will often make it incompatible with (some) shields/adapters.
The arduino website with specifications on the board:
http://www.arduino.cc/en/Main/ArduinoBoardUno
EAGLE files:
http://arduino.cc/en/uploads/Main/arduino_Uno_Rev3-02-TH.zip

There are several areas of compatibility. I mention mechanical in particular. I know there are different board designs, like the Nano, which are software compatible, but it should be obvious that I'm not asking about mechanical compatibility between Nano and Uno, for instance. The question is: does there exist an official drawing with PCB outline and the positions of mounting holes and connectors/headers? I couldn't find it.

Hmm, not that I know off, though arduino is open source and they do have design documentation on their website https://www.google.nl/url?sa=t&source=web&rct=j&ei=8HM-VbjmE5blao3OgcgI&url=http://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf&ved=0CEIQFjAI&usg=AFQjCNGzCio-NUQNITccf4-akL0T_cyi1Q&sig2=OlSWYdqsNnjl8Axk0vD5rQ

Yes, that's an (outdated) schematic, thanks. But have you ever seen an official mechanical drawing?

I have searched on my laptop (which is easier as on my phone) and found the following: http://arduino.cc/en/uploads/Main/arduino_Uno_Rev3-02-TH.zip , These are the eagle SCHEMATIC and BOARD files. Found on this page: http://www.arduino.cc/en/Main/ArduinoBoardUno
I believe this would be the standard set by arduino, it's from Rev 3 so I think it's quite up to date?

A board file is (probably) a PCB layout. I can't read that because I don't have Eagle. That's not a mechanical documentation file (which preferably should be a PDF). I appreciate that you want to find an answer, but I still don't think it exists. I've also Googled the Internetverse for a long time for it. I found drawings which are the initiative of individuals to fill in the gap in documentation, but those drawings either are incomplete, wrong or contradicting.

I agree, Arduino is made for hobbyists and this does also only have basic documentation in this field. Not to much technical info. You should consider downloading eagle, it's free (I believe) and you can use measurement tools in eagle to get the exact placing/dimensions.

If you get good at it you'll be able to create custom pcb's for specific projects. Like an RFID reader with wireless connection, as 'small' as an arduino. Your arduino copy should basically be as much te same. Unless you have beter ideas, like using a beter chip and double the rows of pins or something!

"you can use measurement tools in eagle to get the exact placing/dimensions." I'm not a mechanical engineer, but I've worked enough with them to know that measuring on a drawing is a cardinal sin. Never measure on a mechanical drawing. All measurements should be there. If some measurements are missing, send the drawing back to the engineer who made it. But again, a PCB layout is not a mechanical drawing. If you want to know what I mean by good mechanical drawing, take a look at the drawings near the end of any electronic component's datasheet.

I actually agree on that. Though I haven't seen an mechanical drawing from arduino yet. You might want to request it at their forums?


text:
Serial Communication Not Receiving Entire String
I have an Arduino connected to a pico motor driver that is supposed to take a number of steps for a specific number of triggers that gets from a source (i.e. waveform generator). I've setup the code so that it would ask the user to input number of steps and number of triggers. For example, if I want the motor to take 10 steps once it got 60 triggers, I should input s10; and t60; separately into Serial Monitor.
In addition, I want to be able to change the number of steps and triggers any time that I want. However the problem is that sometimes Arduino doesn't receive the input string entirely for the first time. Sometimes it works on the second try. Or even not at all. I really appreciate if someone can give a hint on why this is happening.
This is a simple version of the code (without the parts that move the motor):
#include<String.h>

long int steps;
long int num_triggers;
long int newtrigger;
long int newstep;
long int oldtrigger;
long int oldstep;

const int main_control = 0;
int triggers_count;
bool motor_trigger = true;

void setup() {

 Serial.begin(19200);
 Serial.println("Please enter chosen number of steps and triggers.");
 Serial.println("Example: \n If you want the pico-motor to take 10 steps per 40 triggers,");
 Serial.println(" write 's10;' and press enter then do the same for 't45;'(Order doesn't matter).");
}

void loop() {

  while (num_triggers == 0 || steps == 0) {

    getcommand(&steps, &num_triggers);

  }

  attachInterrupt(main_control, trigger, RISING);  // it starts looking for trigger

  if (motor_trigger == false) {

    getcommand(&steps, &num_triggers);
  }

  else if (motor_trigger == true) {

    motor_trigger = false;
    detachInterrupt(main_control);

    if (triggers_count <= (num_triggers - 1)) {

      getcommand(&steps, &num_triggers);

    }

    else {

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

        oldstep = steps;
        oldtrigger = num_triggers;
        getcommand(&steps, &num_triggers);

        if (  num_triggers != oldtrigger || steps != oldstep) {
          break;
        }
      }
    }
  }
}

void trigger(void) {

  motor_trigger = true;
  triggers_count++;
}

void getcommand (long int *newstep, long int *newtrigger) {

    char   char_input;
    String string_input;
    String output_1;
    String output_2;

  while (Serial.available()) {

    char_input = Serial.read();
      if (char_input == ';'){
    Serial.println("done");

      }
      else{
    string_input += char_input;
    delay(500);
    }
  }

  Serial.println("Getting input...");
  Serial.println(string_input);
  Serial.println("Input printed.");

  int inputlen = string_input.length();
  output_1 = string_input[0];

    for ( int i = 1; i < inputlen; i++ ) {
      output_2 += string_input[i];
    }

      if ( output_2.toInt()<=0 && inputlen>0 ){   // check if there's an error

        Serial.println("Error with input number");
        delay(5000);
        Serial.println("Reading the input string");
        Serial.println(Serial.readString());
        Serial.println("Done reading the input string");
        }

    if (output_1 == "s") {

      *newstep = output_2.toInt();

    }

    else if (output_1 == "t") {

      *newtrigger = output_2.toInt();
    }

  }

Edits must not change literal details of command codes which the program is looking for; also, editing just to insert a comma or optional definite article is merely a waste of everyone's time and attention.

I can see several issues:

If the Serial buffer contains more than one command already, you'll read it too. For example serial buffer contains "s43;t25;" and  the input_string would be something like "s43t25". This is highly to happen if you send those characters in less than 3seconds (as you have delay(500) for each appended character). You have to stop reading from buffer if you detect ';'.
Parsing of commands is also pretty weird. You are blocking for some time, so you can detect 's'/'t' and then use Serial.parseInt(); with Serial.setTimeout(1000); to do similar but much faster get command.
Variables set inside of ISR (function trigger is called from ISR) must be volatile. Otherwise it might be optimized out or into register by compiler.

Anyway, if you want to read whole commands try the serialEvent() example. Just change checking for '\n' to ';' and then you can parse that command in your way when it's complete.


text:
Read Audio Data in Real-time over 3.5mm Stereo Cable
My Goal
Have Arduino read audio output from a TRS stereo audio cable (coming from a computer, smartphone, etc.). As motivation for this use-case, once some audio data (depending on the sample rate) have been stored in a buffer, the Arduino will perform an FFT on the buffered data. The power contained in the FFT is mapped to the red, green, and blue frequency-bands of visible light to determine the color of an LED strip.
My Set-up
The obvious first step was to connect a Right-Angle 3.5mm Stereo Plug to Pigtail Cable to the Arduino. As is commonplace, this cable has a Tip, Ring, and Sleeve connector; Adafruit labels the black wire as ground (sleeve). They further label the red wire as "left channel live" (tip) and the white wire as "right channel live" (ring), if I can trust Wikipedia:

Stereo sockets commonly provide two such NC contacts, one for the tip (left channel live) and one for the ring or collar (right channel live).

My Question
So, I've plugged the red wire into the A0 pin and the white wire into the A1 pin. However, I'm unsure of how to sample the actual audio signal from these analog pins.
I don't believe the analogRead() function solves the whole problem - it only converts a voltage reading at the pin into a value between 0 and 1023. Presumably, if I knew the bit rate (i.e., sample rate) & of each packet in the transmitted audio signal, I'd be able to construct signal from that. Is it possible to extract the original audio's waveform from a simple voltage signal? If not, what approach would enable the Arduino to read audio data from an audio cable?
Note: For those wondering, I have indeed heeded the advice from this Electronics SE answer to attach a DC-blocking/DC-bias circuit to the signal source before driving it into an analog pin on the Arduino.

While not impossible, an ATmega based Arduino is a relatively non-optimal choice for this project.  With three output colors, you can probably do more optimal mapping than an FFT - it sort of sounds like you're trying to imitate an old op-amp "color organ"

@ChrisStratton I've never heard of an op-amp color organ. Three output channels*, so that could be any number of colors depending on the intensity of each channel. Could expand on what makes the Arduino non-optimal (what should I do to make it better)? Processing power / resource constraints are hard to fix for any microcontroller.

The ATmega has a very slow, limited resolution ADC, little memory, and slow processing compared to even cheaper modern alternative MCUs.  You really should spend some time researching color organs.  You have only 3 color controls, so if you are going to do color mixing, you are going to need to define some algorithm to map frequency components to color mixes.  It will probably be easiest to play with that on a PC, reading audio files and running it through your evolving algorithm until you are showing satisfactorily pretty colors on the screen.  Only then worry about the MCU.

@ChrisStratton I see where you're going with color organs. It seems like a color organ takes the average the power over three selected frequency sub-bands in the acoustic range & dim a red, blue, or green light based on those average powers. I'm doing the same thing, except for an RGB LED strip has a R, G, and B channel. So simply, if I supply three PWM signals generated according to those average powers, the R, G, and B channels mix at the LED and produce some other color (for instance, bright white if all channels are provided with the same PWM signal).

@dda - please don't make edits which decrease the quality of a post.  The original version was superior to yours, and so has been restored.

The middle path
Build the simple op-amp (or whatever) 70s-era color organ, but without all the LEDs. Then basically feed the organ's LED-driving lines into the Arduino's ADCs. Sampling that pre-processed/summarized data, you can define a wide variety of RGB interactions without complicated math or an EE background. The timing requirements will be well-within the Arduino's reach, unlike computing FFTs or other "difficult" processes. Besides, old/new hybrids are cool!

Simply, YES: it is possible to reconstruct the waveform from the sampled signal. There are entire 400 level college courses on this subject, in fact, but it is rather simple to implement. However, you should study the FFT algorithm you plan to use a little more closely, as it actually requires a discreet time (sampled) input.
Some background: The audio signal you are getting from the TRS cable is continuous, but was recreated from discreet samples (unless your using a tape deck) by using reconstruction theory. The basic idea is this: you take a continuous train of discreet values (the sample points of the sound you want to make), then you multiply each one by a sinusoidal rectangle function (called a sinc, if you want to look it up), which basically takes your discrete values and makes them analog. The frequencies of the sampled signal will probably be 44.1 or 96kHz, although the signal you actually get is analog.
Now, the FFT!
The FFT itself is a discrete time function, meaning that it is designed to use sampled data (for instance, of vector of values read from analogread() once every T seconds, where T=1/f, f being your sampling frequency). I should warn you, unless you're planning on using a library someone else already made, the FFT is a complicated beast! It's not impossible to use--in fact once you understand it, it's really quite beautiful--just be aware there is a lot of circle-based math and opaque optimization.
So, again in short, yes, you can reconstruct a signal from its sample, but you don't need to!
Note: there may be more information on what you're trying to do on the Signal processing SE as well.
Hope that helps!
EDIT ADDITION:
In response to the comments, I very much agree that most lower level arduinos (assuming uno or similar) is not the ideal chip. However, there is a way around your sampling problem. Whether your processor can handle the higher sampling rate is questionable, but we'll address that momentarily.
Q: How to get a higher sample rate out a 10kHz max ADC.
A: Double up. Or triple up, or quadrupile up, etc.
The basic idea is, if you have one ADC reading channel 1 of a signal nT seconds (T being period = 1/10kHz and n being a discrete set of integers = 0,1,2,3...), then you can have a second ADC reading the signal every nT+(T/2) seconds. Then, you populate your data vector as DATA=[ADC1(0*T),ADC2(0*T+T/2),ADC1(1*T),ADC2(1*T+T/2),...] and so on. This effectively doubles your sampling rate. If you want to sample at ~40Hz, you use 4 ADC channels. The real question is how high do you need to go. By Nyqist's Theorem, you need a sampling freequency >= to twice of the highest frequency you expect to be present in your signal. In most recorded sounds this never above 18kHz. So, you do this with 4 ADC channels offset from each other by a quarter period, and you have a high enough sample rate.
Q: What if I can't process the data with an FFT that fast?
A: Never fear! Discrete time filters and power integration are here! (okay, that was a bit corny).
A much less processor intensive method of frequency band power estimation would be to implement band-pass filters in your software (which can work with very little overhead processor-wise) and then average the power output of each filter.
Again, hope this addition helps! But as another commenter pointed out, what you want to due may be much easier with a different chip. And as I will point out, moving the filtering and power integration to external op-amp circuits would be an equally simpler option, eliminating the entire sampling problem!

The real problem at hand is: how do I sample the analog audio signal at the analog pin at 44.1 or 96 kHz? Because the ADC has a maximum sampling frequency of 10 kHz. At the moment, the key seems to be something called an "interrupt call" on a timer (this page seems to explain that, but I haven't wrapped my head around what it's doing yet). I'm having trouble identifying where the sample rate is being scaled up, though...

@VladislavMartin - you can do slightly better, but an ATmega is neither intended nor able to sample high fidelity audio.  You'll have to pick a different part if you really want to do that.

No.  The ATmega's ADC is multiplexed.  Using multiple channels doesn't make it faster, because it's not 4 ADC's, it's 1 ADC dividing its capabilities to cover 4 inputs in turn.  That idea only works on parts that have multiple ADC's - but many of those are already fast enough for Audio when using just one.

@ChrisStratton Are you sure it's not able to sample audio? I'm writing up an answer that uses Timer1 for interrupt handling to effectively increase the ADC's sample rate. According to Atmel doc, this is perfectly acceptable: "Recommended maximum ADC clock frequency
is limited by the internal DAC in the conversion circuitry. For optimum performance, the ADC clock should not exceed 200kHz. However, frequencies up to 1MHz do not reduce the ADC resolution significantly."


text:
HCSR04 Sensor without delay
I've made a code to make a stepper work together with a HCSR04 sensor. The problem here is that the sensor has to use a delay in order to work. This delay messes with the smootness of the stepper.
If I remove the code for the sensor the stepper runs verry smooth, adding the sensor code causes the stepper to run 'shaky'.
The code:
int trigPin = 11;
int echoPin = 10;

void setup()
{
pinMode(trigPin, OUTPUT); //Sensor
pinMode(echoPin, INPUT); //Sensor
pinMode(6,OUTPUT); // Enable
pinMode(13,OUTPUT); // Step
pinMode(12,OUTPUT); // Dir
digitalWrite(6,LOW); // Set Enable low
digitalWrite(5,LOW); // Set Step low
Serial.begin(9600);
}

void loop()
{
//rotateleft();
//Serial.println("ik draai nu exact een rotatie linksom");
//delay(1000);
//rotateright();
//Serial.println("ik draai nu exact een rotatie rechtsom");
//delay(1000);
//velocity();

 //sensor
 long duration, distance;
 digitalWrite(trigPin, LOW);
 delayMicroseconds(2); //**problem**
 digitalWrite(trigPin, HIGH);
 delayMicroseconds(5); //**problem**
 digitalWrite(trigPin, LOW);
 duration = pulseIn(echoPin, HIGH);
 distance = (duration/2) / 29.1;
 Serial.print ("cm:");
 Serial.print (distance);

//eigen creatie
if (distance > 20 && distance < 30)
{
  digitalWrite(13,HIGH); // Output high
  delayMicroseconds(1000); // Wait
  digitalWrite(13,LOW); // Output low
  delayMicroseconds(1000); // Wait
}

if (distance > 10 && distance < 20)
{
  digitalWrite(13,HIGH); // Output high
  delayMicroseconds(3000); // Wait
  digitalWrite(13,LOW); // Output low
  delayMicroseconds(3000); // Wait
}

if (distance > 1 && distance < 10)
{
  //digitalWrite(13,HIGH); // Output high
  //delayMicroseconds(1000); // Wait
  digitalWrite(13,LOW); // Output low
}

else
{
 velocity();
}

}

void velocity()
{
 digitalWrite(13,HIGH); // Output high
 delayMicroseconds(500); // Wait
 digitalWrite(13,LOW); // Output low
 delayMicroseconds(500); // Wait
}
 }

Have you searched for other libraries or example code for this particular sensor?
I found this NewPing library that claims to have been developed to fix poor performance of such modules due to poor timing methods.

Yes, the https://bitbucket.org/teckel12/arduino-new-ping/wiki/Home#!event-timer-sketch has a non-blocking timer-interrupt based example.

I have been looking into the newPin library but I cannot find a function that resolves the problem. Still, I am going to look into the NewPin library. It seems to promising. But I quess it is not going to completly fix my delay problem.

You only have a single thread of execution of an Arduino.  So you have limited options:

Live with it.
Use two Arduinos.
Use a microcontroller with 2 cores.
Interrupts

2 Is possible, you could have a slave mcu to drive the motor and control it over I2C.  You will still have contention when you are driving the I2C bus, but you can time that so it is not when you are scanning.
3 Is a very similar solution to 2, but is all in one chip.

You MIGHT be able to use interrupts which will let processing continue whilst you are waiting for something to occur.  I can't remember if the Arduino has timer interrupts, if it doesn't an external source could generate the interrupts and changes the state of the lines.,

Hi Matt, Interesting options. I do have a second Arduino Uno laying around for this project. Haven't heard of I2C but I will look into it.

You could also use Serial to talk between the two devices, but you can't use the main serial port on an Uno, because that will make debugging difficult and people keep reporting issues with software serial.


text:
why am I losing data over serial communication between arduino and pc
I'm working on a project for school. I'm trying to rotate a servo by writing the letter that identify the servo and then the angle.
the problem is that sometimes the last number of the angle is lost or the whole angle all together. for example i want to rotate servo "a" 50 degrees. i enter a50 this works most of the time but sometimes i only get a 5 without the zero and sometimes i just get a zero. can anyone help, thanks.
please keep in mind i only did computer science in high school and intro to c++ in college. go easy on me please.
attached is the code and an image illustrating my problem.
#include <Servo.h>

Servo servo1;
Servo servo2;
Servo servo3;

String angle1="";
String angle2="";

char serialbuffer[4];
int index=0;
int charcount=0;

int lastangle;
int dif;

void setup() {
  servo3.attach(3);  // attaches the servo on pin 9 to the servo object

  Serial.begin(9600);

  serialbuffer[0]='0';
  serialbuffer[1]='0';
  serialbuffer[2]='0';
  serialbuffer[3]='0';
}

void loop() {

       charcount=0;
       index=0;
       serialbuffer[0]=99;

   while (Serial.available() > 0) {

      char charbuffer = Serial.read();
       if(charbuffer=='\n'){
          index=0;
        }
        else{

           serialbuffer[index]=charbuffer;
           index++;
           charcount++;
          }

      }

  angle1="";
  if(serialbuffer[0]=='a'){

      for(int i=1;i<charcount;i++){
         angle1+=serialbuffer[i];
      }
      move_servo3(angle1);
      index=0;
      serialbuffer[0]=99;
    }
  delay(15);
}

void move_servo3(String angle2){

   Serial.println(angle2.toInt());
   servo3.write(angle2.toInt());

  }

Are you hand-typing the commands? It is pretty difficult to do that consistently. I ask because your code collects data from the serial buffer until the buffer is empty - i.e. when you pause even slightly in your typing - and tries to act on whatever it has collected so far. That may be (probably will be!) an incomplete command. Even if your terminal uses line-by-line entry, there is still the risk that your code could notice an empty buffer between characters within a line.
Try collecting characters until it sees a newline, instead. That is probably what you intended, and it will be immune to your typing speed. You'll still need to test for .available, but that should only allow the code to collect more characters. Keep collecting until it sees a newline.
What (I think) is happening now is called a race-condition. That means that the program's behavior is dependent on which of two (or more) events happens first, and the order of their occurrence is indeterminate. Race conditions are especially hard to find when the order of two events is almost always the one you expected. Notice the "gotcha" word in that sentence? :)

thanks for your answer. for future viewers, i ended up adding a last latter to determine the end of the message and then sending the whole thing to the servo.

I don't understand why the problem is being caused, your code looks OK, but this is too big for a comment.

I think it would be better if you initialised you serialbuffer with NULL rather than '0'.  This way angle2.ToInt() will just read the number you have typed, rather than what was in there last time.  Try entering a111 and then a2.  You will get a211 second time.  NULL is the end of a string.
In loop() change your while loop to this:
char charBuffer = Serial.read();
while (charBuffer != '\n' && index < 4) // Index < 4 stops a buffer overflow.
{
  serialbuffer[index++] = charBuffer;
  charCount++;
  charBuffer = Serial.read();
}

This will keep reading until it sees a new line, which I think is what you want.

You don't need the delay statement now, the speed is controlled by
how fast you can type.
The for statement could be changed to:
for (int i = 0; i < 4 && serialbuffer[i] != NULL; ++i)

If you make these changes I think it might help see the problem.  Also printing the number that has been typed in before the for loop might help, it will print now because you have initialised it to NULL.


text:
Change RF Receiver Frequency by Antenna Length
This may be a very stupid question, but I have got me one of those cheap 433 MHz RF modules for the Arduino.
I'm wondering if I can vary the receiver's frequency by simply changing the length of the antenna? Or does the circuit limit the frequency band to 433 MHz?
Thanks in advance.

No, changing the antenna length will only change the resonant frequency of the antenna circuit. That is, it will affect the sensitivity of the receiver, but won't actually change the frequency that the receiver "listens" to.


text:
How to attempt connection to WiFi only once?
I am working on a garden timer project, I connect to WiFi once and if its successful show time from NTPClient or else show time from RTC.
I have been done the above, and it works in the sense that if I turn off the WiFi while the program is running, it switches to the RTC and back to NTPClient when  WiFi is available again.
PROBLEM- If the WiFi is not available when the board boots, the program just waits for WiFi where I want it to use RTC.
Hardware-ESP8266 based NodeMCU, I2C RTC, I2C 16x2 LCD.
Software-Blynk
My code:-
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <DS3231.h>
#include <Wire.h>
#include "DHT.h"
#include "LiquidCrystal_PCF8574.h"

#define BLYNK_PRINT Serial
#define DHT_PIN_DATA  12
// LCD definitions
#define LCD_ADDRESS 0x27
#define LCD_ROWS 2
#define LCD_COLUMNS 16
#define SCROLL_DELAY 150
#define BACKLIGHT 25
#define DHTTYPE DHT22

// Auth code and wifi credentials here
char auth[] = "ymri80lFL9_xjZppphf6WIRHtQ1kqEWOt9zBy";
char ssid[] = "Hotspot-82DB";
char pass[] = "qqnbkbbbk";
int autoSch;
int waterNow;
int morTime;
int afterTime;
int postNoon;
int eveTime;
int schTime;
int minStep;
int interval;
int count;
int flag = 0;
int soilHum = A0;
int waterItr;
int checkRun;
int waterItr1;
int oneTime;
bool h12Flag;
bool pmFlag;

unsigned long previousMillis = 0;
byte wifi[] = {
  B00001,
  B00001,
  B00101,
  B00101,
  B00101,
  B10101,
  B10101,
  B10101,

};

DHT dht(DHT_PIN_DATA, DHTTYPE);
LiquidCrystal_PCF8574 lcdI2C;
WiFiUDP ntpUDP;
DS3231 Clock;
NTPClient timeClient(ntpUDP, "in.pool.ntp.org", 19800, 600000);

BLYNK_CONNECTED() {
  Blynk.syncAll();
}

BLYNK_WRITE(V0)
{
  autoSch = param.asInt(); // assigning incoming value from pin V1 to a variable
}

BLYNK_WRITE(V1)
{
  morTime = param.asInt(); // assigning incoming value from pin V1 to a variable
}

BLYNK_WRITE(V2)
{
  afterTime = param.asInt(); // assigning incoming value from pin V1 to a variable
}

BLYNK_WRITE(V6)
{
  postNoon = param.asInt(); // assigning incoming value from pin V1 to a variable
}

BLYNK_WRITE(V3)
{
  eveTime = param.asInt(); // assigning incoming value from pin V1 to a variable
}

BLYNK_WRITE(V10)
{
  waterNow = param.asInt(); // assigning incoming value from pin V1 to a variable
}

BLYNK_WRITE(V4)
{
  schTime = param.asInt(); // assigning incoming value from pin V1 to a variable
}

BLYNK_WRITE(V7)
{
  minStep = param.asInt(); // assigning incoming value from pin V1 to a variable
}

void setup()
{
  Wire.begin();
  dht.begin();
  lcdI2C.begin(LCD_COLUMNS, LCD_ROWS, LCD_ADDRESS, BACKLIGHT);
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);
  pinMode(14, OUTPUT);
  pinMode(15, OUTPUT);
  digitalWrite(14, LOW);
  digitalWrite(15, LOW);
  Blynk.virtualWrite(V5, 0);
  Blynk.virtualWrite(V8, 0);
  pinMode(0, INPUT_PULLUP);
  Serial.begin(9600);
  Blynk.begin(auth, ssid, pass);
      timeClient.begin();
  /*
    while ( WiFi.status() != WL_CONNECTED ) {
      delay ( 500 );
      Serial.print ( "." );
    }
  */

  Blynk.syncAll();
  lcdI2C.createChar(0, wifi);
}

void loop()
{
  Blynk.run();
  time_run();
  lcd();
  butPress();
  butCheck();
  /*if (waterNow != 1) {
    Blynk.virtualWrite(V10, 0);
    digitalWrite(14, LOW);
    Blynk.virtualWrite(V5, 0);
    Blynk.virtualWrite(V8, minStep * 60);
    }*/
  if (waterNow == 1) {
    if (waterItr < minStep * 60) {
      waterOn();
      waterItr++;
      delay(500);
    }
    else {
      waterOff();
    }

  } else if (autoSch == 0) {
    auto_run1();
    waterItr = 0;
  } else if (autoSch == 1) {
    sch_run2();
    waterItr = 0;
  } else {
    //Blynk.virtualWrite(V10, 0);
    waterItr = 0;
    digitalWrite(14, LOW);
    Blynk.virtualWrite(V5, 0);
  }
  Blynk.syncAll();

}

void butPress() {
  if (digitalRead(0) == LOW) {
    delay (100);
    if (flag == 0) {
      flag = 1;
    }
    else if (flag == 1) {
      flag = 0;
      waterItr1 = 0;
      digitalWrite(15, LOW);
      Blynk.virtualWrite(V5, 0);
    }
  }
}

void butCheck() {
  if (flag == 1) {
    digitalWrite(15, HIGH);
    Blynk.virtualWrite(V5, 255);
    lcdI2C.selectLine(2);
    lcdI2C.print("Wtr B Now :  ");
    lcdI2C.print(600 - waterItr1);
    if (waterItr1 < 600) {
      waterItr1++;
      delay(500);
    }
    else {
      waterItr1 = 0;
      flag = 0;
      digitalWrite(15, LOW);
      Blynk.virtualWrite(V5, 0);
    }
  }
}

void lcd() {
  if (oneTime == 0){

    oneTime=0;
    }
  //lcdI2C.clear();
  lcdI2C.setCursor(0, 0);

  if (WiFi.status() == WL_CONNECTED) {
    timeClient.update();
    lcdI2C.print("T:");
    lcdI2C.print(timeClient.getFormattedTime());
    Clock.setHour(timeClient.getHours());
    Clock.setMinute(timeClient.getMinutes());
    Clock.setSecond(timeClient.getSeconds());
  } else {
lcdI2C.print("R:");
lcdI2C.print(Clock.getHour(h12Flag, pmFlag)); lcdI2C.print(":"); lcdI2C.print(Clock.getMinute()); lcdI2C.print(":"); lcdI2C.print(Clock.getSecond());
  }
  if (autoSch == 0) {
    lcdI2C.setCursor(10, 0);
    lcdI2C.print(" Auto   ");
  } else {
    lcdI2C.print(" Sch   ");
  }

  if (WiFi.status() == WL_CONNECTED) {
    lcdI2C.setCursor(15, 0);
    lcdI2C.write(0);
  }

  if (digitalRead(14) == 1) {
    lcdI2C.selectLine(2);
    lcdI2C.print("Wtr Now           ");
  }
  else
  {
    if (int(timeClient.getHours()) < 6 && morTime == 1 && autoSch == 0) {
      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at: 6a ");
    } else if (int(timeClient.getHours()) < 12 && afterTime == 1 && autoSch == 0) {
      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at: 12n ");
    } else if (int(timeClient.getHours()) < 14 && postNoon == 1 && autoSch == 0) {
      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at:14pn ");
    } else if (int(timeClient.getHours()) < 18 && eveTime == 1 && autoSch == 0) {
      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at: 18e ");
    } else if (int(timeClient.getHours()) >= 18 && morTime == 1 && autoSch == 0) {
      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at: 6a ");
    } else if (int(timeClient.getHours()) >= 6 && morTime == 1 && autoSch == 0) {
      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at: 6a ");
    } else if (int(timeClient.getHours()) >= 12 && afterTime == 1 && autoSch == 0) {
      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at: 12a ");
    }   else if (int(timeClient.getHours()) >= 14 && postNoon == 1 && autoSch == 0) {
      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at: 14a ");
    }  else if (int(timeClient.getHours()) >= 18 && eveTime == 1 && autoSch == 0) {
      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at: 18a ");
    } else {
      if (autoSch == 0) {
        lcdI2C.selectLine(2);
        lcdI2C.print("  Switch to Sch  ");
      } else {
        lcdI2C.selectLine(2);
        lcdI2C.print("  Schedule mode ");
      }
    }
  }
}

void waterOn() {
  lcdI2C.setCursor(0, 0);
  digitalWrite(14, HIGH);
  Blynk.virtualWrite(V5, 255);
  lcdI2C.selectLine(2);
  lcdI2C.print("Wtr Now :");
  lcdI2C.print((minStep * 60)  - waterItr);
  Blynk.virtualWrite(V8, (minStep * 60)  - waterItr);
  Blynk.syncAll();
}

void waterOff() {
  Blynk.virtualWrite(V10, 0);
  digitalWrite(14, LOW);
  Blynk.virtualWrite(V5, 0);
  Blynk.virtualWrite(V8, 0);
  waterItr = 0;
  Blynk.syncAll();
}

void sch_run2() {
  if (schTime == 1) {
    digitalWrite(14, HIGH);
    Blynk.virtualWrite(V5, 255);
    checkRun = 1;
    Blynk.syncAll();
  } else if (schTime == 0) {
    checkRun = 0;
    if (checkRun == 0) {
      digitalWrite(14, LOW);
      Blynk.virtualWrite(V5, 0);
      Blynk.syncAll();
    }
  }
}

void time_run() {
  Blynk.virtualWrite(V11, int(timeClient.getHours()));
  Blynk.virtualWrite(V12, int(timeClient.getMinutes()));
  Blynk.virtualWrite(V13, float(dht.readTempC()));
  Blynk.virtualWrite(V14, float(dht.readHumidity()));
}

void auto_run1() {
  if (morTime == 1 && String(timeClient.getFormattedTime()) > "06:00:00" && String(timeClient.getFormattedTime()) < "06:20:00") {
    digitalWrite(14, HIGH);
    Blynk.virtualWrite(V5, 255);
    checkRun = 1;
  }
  else if (afterTime == 1 && String(timeClient.getFormattedTime()) > "12:00:00" && String(timeClient.getFormattedTime()) < "12:20:00") {
    digitalWrite(14, HIGH);
    Blynk.virtualWrite(V5, 255);
    checkRun = 1;
  }
  else if (postNoon == 1 && String(timeClient.getFormattedTime()) > "14:00:00" && String(timeClient.getFormattedTime()) < "14:20:00") {
    digitalWrite(14, HIGH);
    Blynk.virtualWrite(V5, 255);
    checkRun = 1;
  }
  else if (eveTime == 1 && String(timeClient.getFormattedTime()) > "11:49:00" && String(timeClient.getFormattedTime()) < "11:50:00") {
    digitalWrite(14, HIGH);
    Blynk.virtualWrite(V5, 255);
    checkRun = 1;
  }
  else  {
    //(String(timeClient.getFormattedTime() == "06:20:00" || "12:20:00" || "14:20:00" || "13:48:00"))
    //waterNowrun();
    checkRun = 0;
    if (checkRun == 0) {
      //Blynk.virtualWrite(V10, 0);
      digitalWrite(14, LOW);
      Blynk.virtualWrite(V5, 0);
      Blynk.virtualWrite(V8, 0);
      Blynk.syncAll();
    }
  }
}

Blynk.begin waits for the WiFi connection. is that what you ask? then it has nothing to do with RTC or NTP. is that your real Blynk token? the esp8266 SDK has NTP, don't use NTPClient library on esp8266.

@juraj No its not the real one, still would like to use NTPClient

@juraj What's the problem with NTP, Blynk.begin waits for the WiFi connection. How to prevent it?

your question is all about NTP and RTC, but you ask about WiFi connection. so I don't know what do you ask. Blynk.begin() calls Blynk.config() and then waits for WiFi. you can use Blynk.config only

@juraj Forget about NTP and RTC, the code does not execute until its connected to wifi, how do I prevent it?

replace Blynk.begin with Blynk.config(key) and handle the WiFi connection as usual without Blynk

@Coder9390 For details see the Blynk docs.

Instead of using blynk.begin() use WiFi.begin() and blynk.config() to achieve non-blocking code
void setup(){
//  Blynk.begin(auth, ssid, pass); don't use this
  WiFi.begin(ssid, pass);
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }
  Blynk.config(auth);
}

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


text:
Servo wont work with LED code!
I'm basically trying to combine my servo code and my LED code but whenever I add my servo code the LED refuses to turn on at all.
I am super new to arduino sorry if this doesn't make any sense!

Servo myservo;

const int pushbutton_PIN = 2;
const int POT_PIN = A0;
const int LED_PIN = 3;

int pos = 0;
int buttonState = 0;
int lastbuttonState = 0;
int analogValue = 0;
int lightState = false;
int brightness = 0;

void setup() {
  myservo.attach(9);
  pinMode(pushbutton_PIN, INPUT);
  pinMode(POT_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);
  Serial.begin(9600);
}

void loop(){
  light();
  servo();
  }

void servo(){
        for (pos = 0; pos <= 180; pos += 1) {
    // in steps of 1 degree
    myservo.write(pos);
    delay(15);
  }
  for (pos = 180; pos >= 0; pos -= 1) {
    myservo.write(pos);
    delay(15);
  }
}

void light() {
      buttonState = digitalRead(pushbutton_PIN);
  if (buttonState != lastbuttonState) {
    if (buttonState == HIGH) {
      delay(300);
      lightState = true;
      light_on();
    }
  }
  lastbuttonState = buttonState;
}

void light_on() {
  while (lightState == true) {
    analogValue = analogRead(POT_PIN);
    brightness = map(analogValue, 0, 1023, 0, 255);
    analogWrite(LED_PIN, brightness);
    buttonState = digitalRead(pushbutton_PIN);
    if (buttonState != lastbuttonState) {
      if (buttonState == HIGH) {
        lightState = false;
        delay(300);
        analogWrite(LED_PIN, LOW);
        loop();
      }
    }
    lastbuttonState = buttonState;
  }
}

I think your problem is the blocking code. While your servo code run, the LED isn't handled in any way. To do multiple this at the same time (like controlling a servo, checking a button and controlling an LED, you actually need to do these this sequentially in very fast succession, basically only doing something, when it is time to do so, otherwise going further to the next thing. No delay calls (thats just busy waiting). Please look at tutorials about millis()and the BlinkWithoutDelay example, that comes with the Arduino IDE. It is very important coding principle for microcontrollers.

Common issue with PWM and Servo when it doesn't work is that used PWM pin is on the same Timer taken over by Servo library. But it's usualy using Timer1 and pin 3 is on timer 2, so it might not be issue in this case

Each call to your servo() function takes well over 5 seconds (5.4s, for the delay() calls alone!), during which nothing else - testing the button, f/ex - is being done. Seconding @chrisl 's suggestion to review the BlinkWithoutDelay example. Also search Arduino StackExchange for "non-blocking".

To add on to Chris's comment there is a really good sticky post on the arduino forum in the project guidance section which deals with this exact issue for newbies. I think it's called: doing several things at the same time

is there any reason why you are moving the servo in small steps?

@chrisl I've looked into what you suggested and I think I've figured it out, so thank you! However if I removed my delays for the servo I'm worried my servo will move too fast for what I need it for. Is there a way to slow my servo down without any delay calls?

Exactly as I wrote: With millis() and the principle in the BlinkWithoutDelay example. That requires a restructuring of your code.


text:
Why do I see error in this code
NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

AF_DCMotor motor1(1, MOTOR12_1KHZ);
AF_DCMotor motor2(2, MOTOR12_1KHZ);
AF_DCMotor motor3(3, MOTOR34_1KHZ);
AF_DCMotor motor4(4, MOTOR34_1KHZ);
Servo myservo;

boolean goesForward=false;
int distance = 100;
int speedSet = 0;

void setup() {

  myservo.attach(10);
  myservo.write(115);
  delay(2000);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
}

void loop() {
 int distanceR = 0;
 int distanceL =  0;
 delay(40);

 if(distance<=15)
 {
  moveStop();
  delay(100);
  moveBackward();
  delay(300);
  moveStop();
  delay(200);
  distanceR = lookRight();
  delay(200);
  distanceL = lookLeft();
  delay(200);

  if(distanceR>=distanceL)
  {
    turnRight();
    moveStop();
  }else
  {
    turnLeft();
    moveStop();
  }
 }else
 {
  moveForward();
 }
 distance = readPing();
}

int lookRight()
{
    myservo.write(50);
    delay(500);
    int distance = readPing();
    delay(100);
    myservo.write(115);
    return distance;
}

int lookLeft()
{
    myservo.write(170);
    delay(500);
    int distance = readPing();
    delay(100);
    myservo.write(115);
    return distance;
    delay(100);
}

int readPing() {
  delay(70);
  int cm = sonar.ping_cm();
  if(cm==0)
  {
    cm = 250;
  }
  return cm;
}

void moveStop() {
  motor1.run(RELEASE);
  motor2.run(RELEASE);
  motor3.run(RELEASE);
  motor4.run(RELEASE);
  }

void moveForward() {

 if(!goesForward)
  {
    goesForward=true;
    motor1.run(FORWARD);
    motor2.run(FORWARD);
    motor3.run(FORWARD);
    motor4.run(FORWARD);
   for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2) // slowly bring the speed up to avoid loading down the batteries too quickly
   {
    motor1.setSpeed(speedSet);
    motor2.setSpeed(speedSet);
    motor3.setSpeed(speedSet);
    motor4.setSpeed(speedSet);
    delay(5);
   }
  }
}

void moveBackward() {
    goesForward=false;
    motor1.run(BACKWARD);
    motor2.run(BACKWARD);
    motor3.run(BACKWARD);
    motor4.run(BACKWARD);
  for (speedSet = 0; speedSet < MAX_SPEED; speedSet +=2) // slowly bring the speed up to avoid loading down the batteries too quickly
  {
    motor1.setSpeed(speedSet);
    motor2.setSpeed(speedSet);
    motor3.setSpeed(speedSet);
    motor4.setSpeed(speedSet);
    delay(5);
  }
}

void turnRight() {
  motor1.run(FORWARD);
  motor2.run(FORWARD);
  motor3.run(BACKWARD);
  motor4.run(BACKWARD);
  delay(500);
  motor1.run(FORWARD);
  motor2.run(FORWARD);
  motor3.run(FORWARD);
  motor4.run(FORWARD);
}

void turnLeft() {
  motor1.run(BACKWARD);
  motor2.run(BACKWARD);
  motor3.run(FORWARD);
  motor4.run(FORWARD);
  delay(500);
  motor1.run(FORWARD);
  motor2.run(FORWARD);
  motor3.run(FORWARD);
  motor4.run(FORWARD);
}

Because you didn't include the libraries maybe? What is the error you see?

You asked about "this error", but you didn't include the actual error message

All of the errors I got were "NewPing does not name a type", "AF_DCMOtor does not name a type" and "motor<> was not declared in this scope". I don't see library includes; at least one for NewPing is needed. I don't know where AF_DCMotor is supposed to be declared but, as it is not declared as a type, it leaves all of the motor undefined. Those are the bulk (if not all) of the errors as the code stands now. Add the missing NewPing library do whatever you need to to define AF_DCMotor.

AF_DCMotor is also a library.

Makes perfect sense...

It probably needs a library. Looks like you have some kind of AFDC library and did not use it.


text:
Can Arduino libraries be compiled for ARM MCU's?
I am looking for a very low power Micro-controller to interface with the RockBlock Iridium modem. The MCU I am thinking of purchasing is the Gecko Zero by Silicon Labs.
I want to know if it is possible to compile the Rockblock-IridiumSBD Arduino library for the Gecko Zero. The Gecko Zero is a 32 bit ARM MCU.
IridiumSBD Library
Gecko Zero MCU

If you have the full source of the library and all its dependencies you should be able to port it.  The issue is not so much the CPU core, but rather the mechanics of peripheral interface.  There are already a number of supported ARM targets, both Atmel-based boards from Arduino.cc and others, as well as those with other vendor's ARM parts like the teensy series.  Note however that making a true low power design atop the Arduino framework may require extra work - at a certain point you may just want to create well designed firmware from scratch.  If you are new to this, buy a board not a chip.

It uses serial to communicate, so looking at it, the only thing you need to port is the IridiumSBD::send function (as far as I can see).

Depending on the rest of your application, you might find the easiest path is to use the Gecko with the mbed.org tools. There already seem to be mbed Gecko development boards so the task is, to port the Rockblock-IridiumSBD Arduino library.
The benefit of using mbed with the Gecko is it looks like mbed have all of the libraries, including low-power control implemented.
The Rockblock-IridiumSBD Arduino library won't compile 'out of the packet' on mbed.
However, the Rockblock-IridiumSBD Arduino library appears to be a serial interface over a few wires. They recommend 'soft serial' which uses digitalWrite, under program control, and no deep access to Arduino peripherals. That should be relatively straightforward to port to mbed. Mbed has equivalent library calls for digitalWrite, so a first attempt might be a few global search and replace edits.
The alternative would be to use Gecko with an Open Source or commercial development system. However, mbed would provide a faster start, if you have good internet access and are not too paranoid about security, because the tools are 'cloud based', saving you time to set up the tools, and their is an mbed community who might help you over the initial hurdles.

You can often (but not always) export an mbed project as a Makefile to drive gcc offline.  It can be a decent way to setup such an arm project, though the results often need some detailed adjustment.

@ChrisStratton - yes, agreed. Still, IMHO, having a working, tested tool chain, repo, and supportive community with little more effort than signing up has quite a lot to recommend it. It is not unusual for quite small obstacles at the beginning to waste quite a lot of energy Easy to install IDEs like Arduino, or zero-install systems like mbed can help. They can reduce the initial hurdles, leaving lots of time, energy and enthusiasm for later refinements like a local build system.


text:
Switching between SPI Devices when one is an SD card
I'm using a USB Barcode scanner connected via a USB shield, I'm able to get the readings from the barcode using this example, After getting this readings, I'd like to save it to an SD card but the SD card won't initialize since the barcode also uses SPI, how can I deactivate the ICSP in order to activate the SD card? Or how to switch between multiple SPI slaves?

@LookAlterno If someone can answers how to tristate a buffer or use a multiplexer to circumvent the SD problem, it might be a useful addition and not fully a duplicate.

with SPI there is an implicit slave select pin on each device that must be pulled low to enable the device.
Connect each slave select pin of the SPI device to their own unused digital pin on your arduino and keep it pulled high until you want to talk to the slave.
However not all SPI devices will properly put the MISO pin into high impedance when SS is pulled high so you may need to use a tristate buffer on that pin or use a multiplexer.
When adding your own tristate buffer (for example a HS125) you need to connect each MISO pin of the SPI device to the input of a buffer, the slave select is then connected to the output enable pin of the tristate. The outputs of the buffers can be connected together along with the MISO pins of the devices that do properly go high impedance to the MISO of the master.
When using multiplexers there are 2 options:

You can daisy chain 2:1 multiplexers by connecting the MISO of the device to the 0-input of the mux and the Slave select to the select input pin of the mux.
you can use a >2 multiplexer to select the correct MISO line based on the address of a set of S lines. Then with a decoder you can provide the actual SS signal to the SPI device. This way you only need 2 SS pins for 4 SPI devices.

SD cards are notoriously bad at playing nicely with other devices on the same bus. Especially with some adaptors with poor logic level shifting circuits.

I can confirm this ... I had so many problems using a (cheap) SD break card and (SPI) SRAM together, that I eventually bought a separate SD logging card. But I wonder how to implement that 'buffer' or what multiplexer (and how to use it) ... Can you explain this a bit plase?

Refer to the schematic below for a visual explanation of what is explained in this thread regarding a tri-state buffer.  I have used this circuit successfully on a PCB.
I got this schematic from:
© 2017 Vishnu M Aiea. www.vishnumaiea.in


text:
Arduino Clone - A request for the USB device descriptor failed
I was working with my arduino clone and that was working well till last night.
I was trying to add l298p motor shield and after a few times of testing without any achievement, my PC suddenly did not recognize the arduino.
The device status in device manager is :
Windows has stopped this device because it has reported problems. (Code 43)
A request for the USB device descriptor failed.

What should I do now??
My OS is windows 8.1

Is it a real genuine Arduino Uno or a cheap Chinese clone?

it is a cheap chinese one

Then most likely the USB interface chip has died. Buy a real Arduino next time.

how can i repair it??

By replacing the USB interface chip with one that works. Until the next time it dies. Cheap Chinese clones are false economy. You can probably still use it using an external USB to TTL UART adapter through pins 0/1.

I can  program the AVR 328p via ICSP but i can not program it via USB which is on the board. so the avr is working. there is an IC named ch340t ... is it the IC used for programming

I guessed there probably would be... that kind of chip is the absolute cheapest USB interface chip available. Cough in its direction and it dies. Look at it and it dies. Enter the same room as it and it dies. They are about as useful as a chocolate teapot.

I've got the same problem with a genuine Arduino Uno WiFi Developer Edition, probably because of a damaged USB cable. So you can fry the original too ...

You have a cheap Chinese clone with a CH340T USB interface chip.
These are notoriously bad chips. It will have died.
You can fix it (temporarily) by replacing the CH340T with another - though it's anyone's guess how long that'll last.
You can also continue using your board as it is now by either programming the chip directly through ICSP or keep using the bootloader but via an external USB to TTL Serial adapter connected to pins 0/1 + RESET (via a capacitor to DTR) as if it were a "breadboard" Arduino.
That's the price you pay for buying cheap Chinese clones. They may seem like a good idea at the time, but unless you are willing to treat them very much as a throw-away item they are not always the value they appear.
Next time buy a genuine Arduino or an Arduino compatible from a reputable manufacturer.

Solution for semi-bricked Pro Micro/mini-Leonardo clones:
The OP's question is ambiguous to as the exact Arduino device in question. My answer applies to the "Pro Micro" or "mini-Leonardo" since these Clones usually use the default Leonardo boot loader, not the modified Sparkfun version.
Note the the Pro Micro doesn't use an external serial to USB chip at all. So the "CH340T USB" argument doesn't apply here. The USB is directly wired to the ATMEGA chip in this case as it has built-in USB 2.0 support.
I've made two projects with these: I gutted an old keypad replaced with a Pro Micro Clone and turned it into a extended keyboard so I could get F13 to F24 keys plus some others, then a custom game foot controller (to 'Q' and 'E' lean in FPS shooters).
Problem, I went to update my Foot controller sketch and after over a year later I forgot my Arduino IDE settings. This time I must have used the wrong setting like "Sparkfun Pro Micro" 3.3.v 8Mhz when your clone is probably like mine a 5v 16Mhz model.
When I uploaded the sketch it failed and apparently corrupted the program Flash header or something.
The original code was still running (on pedal press my LED lit up) but the device now showed up as "..missing USB device descriptor.." type message in the Windows device manager.
Fear not, it's probably recoverable like it was for me.
First of all realize you DON'T set in the Arduino IDE the board to "Spark Fun Pro Micro", simply set it to the default "Arduino Leonardo".
That's the right board setting for these clones. The Sparkfun bootloader IS different, as it says on their site. If you uploaded their bootloader then it might work but that's an experiment for another time.
Now you will need to add a reset button to the right hand side of your board (with the micro USB plug pointing up). The pins are next to each other and are clearly labeled.
I found a mini-switch just right to fit into the header pins from my parts box. In a pinch you can probably solder two small insulated stripped wires as a makeshift switch, but it might make the following step harder which is timing related.
If you plug your Clone Micro back in, notice if you press the switch the Clone Micro will show back up as a Arduino Leonardo on a COM port for about 8 seconds, then fall back to the bad USB ID thing again.
Now in your Arduino IDE create a NEW sketch. Which will create a minimal program that you'll need to restore your Clone back to working order.
Hit the reset switch again and quickly in your IDE preset the "port" to the COM port that shows up. Don't worry it will remember it after the device falls back again.
Now comes the hard part. Unlike a real Sparkfun Micro you can't double tap the reset button for extra time, you only get the 8 seconds period.
In the IDE click the "Upload" button, wait about a second, then hit your reset button.
If all goes well, you will see the typical flashing programming LED success lights and you will have restored your Clone Micro! This might take a few tries depending on your timing.
The thing is to press your reset button slightly after you click the Upload button (or CTRL-U) else you will miss the time frame of the special bootloader reset phase.
Basically this is the directions given here, with a little more details:
https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide#troubleshooting-and-faq

The OP got some opinionated and pretty toxic responses for an open-source hardware device. Some common sense notes on the morality and ethics of buying Chinese clone devices:
First of all, at least this is not nearly as bad a situation of the Chinese fake chips, arguably the real scourge of the Electronics parts world.
Without spending too much time on the legal ramifications and not being a lawyer, it looks like most of the Sparkfun stuff is CC licensed. Although doubtful the license if for their original or modified software/firmware.
From the Arduino site:
"Arduino is an open-source hardware and software company". So the clones are apparently not illegal to buy in the USA (if this is the country of contention).
The reason a lot of people buy the clones is you can buy around three or more of them for the same price of just one Sparkfun Micro.
I've been an electronic hobbyist since the late 70's and part of the equation for me is getting a few extras because there is always that chance I'll fry something despite double if not triple checking my wiring.
I can make a project plus have some spares for the next time.
I wouldn't use it in anything mission critical, but so far the Clone has been working fine for me as a hobbyist.
These things being said, I'm a big fan of Sparkfun. They are a relatively small USA company that makes fun innovative products with helpful Youtube "how too" videos, etc. I'm all for supporting them.

Whilst your answer is interesting, I'm not sure where the Pro Micro is mentioned in the OP's question. They state that they are trying to add a shield so that implies an Uno/Mega, or something similar and they even state that their Arduino has a CH340T.

True, my mistake. It still does come up on top search results for "Arduino" + "request for the USB device descriptor failed", so I made some edits and will leave it here in hopes it helps someone with Pro Micro or Leonardo clone devices.


text:
CH340 Nano avrdude: stk500_getsync() not in sync resp=0xa4
I'm trying to upload some code to an non-arduino nano with the CH340G chip, and the avrdude refuses to let me upload. The error I'm getting is:
Using Port                    : COM4
Using Programmer              : arduino
Overriding Baud Rate          : 115200

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xf6
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xf6

avrdude done.  Thank you.

I've tried installing the drivers for the CH340 chip following this guide but have had no luck. I've also tried uploading to my arduino uno and my arduino micro (both are arduino brand) with no problems. I'm running Windows 10, Arduino IDE 1.8.5
Any ideas?

Thanks, this was my issue as well, Arduino Nano from side manufacturer.

Possible duplicate of Arduino Nano uploading gives error: avrdude: stk500_recv(): programmer is not responding

@scruss. it is not a duplicate. read the answer, check the dates

it sure is: it's an older question having the same problem. Sure, the accepted answer isn't any good, but this one is spot on

@scruss, the 'Old Bootloader' problem didn't exist 5 years ago when the other question was asked.

Arduino has recently changed to using a different bootloader on their official Nano boards that communicates at 115200 baud rather than the previous 57600 baud. Support for these new boards was added in Arduino AVR Boards 1.6.21. The new Nano board definition is not compatible with old Nanos and likely most 3rd party Nanos so backwards compatibility is provided via the Tools > Processor > ATmega328P (Old Bootloader) menu selection.


text:
Code for activating a led after 2 minutes and will blink after 30 seconds interval
Can anyone help me to build a code which will activate a LED after 2 minutes when the power supply is cut off and blink that LED after a time interval of 30 seconds.
I want to import the code on Arduino-Uno.
I will power the Arduino with cell and assign two pins as sensor if they are connected to each other than every this is fine if they are cut the Arduino will blink the LED after 2 minutes and will keep blinking at 30 seconds interval

How do you expect to do anything if the power has been removed?!

I will power the Arduino with cell and assign two pins as sensor if they are connected to each other than every this is fine if they are cut the  Arduino will blink the led after 2 minutes and will keep blinking at 30 seconds interval.

Can any one help me with a code that can switch ON a pump for 5secs and then switch on a blower for 3secs and the operation continues like that.

Use a commonly available USB power pack re-charging from mains and powering the Arduino.  Use a light source directly powered by main and optically couple that to an Arduino.  There are plenty of examples on the web where an Arduino is used to detect light.  Once triggered, write some additional code to blink the led.  Since you are not doing anything other than timing, you can use the delay Arduino library to time events.

I have edited it now can you please help me

I think it would be easier to use a rechargeable USB power pack.  They are very common.  I added a let-me-google-that-for-you link so you can see what I am talking about.  I still think optically isolating mains power from the Arduino is a good idea.  So I am sticking with what the answer says.  Read the pages the links take you to.  Then ask your questions.  It is always best if you make an attempt at programming then ask your questions posting your code with your question.

I have a code edited by me
int pinButton = 8; //the pin where we connect the button
int LED = 2; //the pin we connect the LED

void setup() {
 pinMode(pinButton, INPUT); //set the button pin as INPUT
 pinMode(LED, OUTPUT); //set the LED pin as OUTPUT
}

void loop() {
 start:delay(120000);
 check:int stateButton = digitalRead(pinButton); //read the state of the button
 if(stateButton == 0) { //if not pressed

   digitalWrite(LED, HIGH);
   delay(250);
   digitalWrite(LED, LOW);
   delay(30000);
   goto check;
 }
 else { //if  pressed
  digitalWrite(LED, LOW);
  goto start;
 }
}

The goto start is completely redundant, because at the end of loop it goes back to the start of it anyway. Please avoid using goto - your other one can be replaced by a while loop

DISCLAIMER: This is just a suggestion. No hate for this anwser please.
You could use a capacitor. A super capacitor (high capacity) with a proper joule theft circuit for your project could power the arduino for propably another 5min even if main power is cut off, plus you do not need any extra power source once the main source is cut off. It can be useful if you need to change the battery or move it to an other location but you do not want the module to be turned off.
const int led = 13;    //led pin
const int sensor = A0; //connect this your power supply, use a voltage divider if necessary
                       //this will act like a volt meter

void setup()
{
  pinMode(led, OUTPUT);
  pinMode(sensor, INPUT);
}

void loop()
{
  int V = analogRead(sensor);
  V = map(V,0,1023,0,5); // the 5 is replaced with the ammount of voltage that you supply the arduino

  if(V < 1) // when the power is below a point or simply disconnected, the capacitor
            //will kick in by itself because the Arduino will draw its power
    {
    delay(120000)
    while(V < 1)
    {
      V = analogRead(sensor);
      V = map(V,0,1023,0,5);

      digitalWrite(led, HIGH);
      delay(500);
      digitalWrite(led, LOW);
      delay(29500);
    }
  }
}

The Blink example will tell you how to blink an LED, you just need to change the times in the delay statements.
You want to detect the failure of a power supply.  You Arduino has a backup battery (cell) to power it when the power fails.  Correct?
There are voltage sensor kits available that can monitor mains voltage, just search for "Arduino Voltage sensor".  However there is a risk to you working with main voltages.  So using optical isolation (as ST2000 says) is probably safer for you.  There may be some optical isolator IC that can manage mains and 5V, they are usually white in colour.


text:
Data not updated in real time
In my recent project, working with JSON and Arduino. Till now, I am getting proper JSON data and add this one into Arduino data. But here I face one problem. My data are not updated in real time.
For example, my JSON string is:
{"TPS_Json":"0.40"}

And below is my Arduino code:
#include<LiquidCrystal.h>
#include <ArduinoJson.h>

LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

String response = "";
bool begin = false, finished;

//------------------------------ Variable ---------------------------------//

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

  lcd.begin(16, 2);
}

void loop()
{
  //----------------------------TPS----------------------------//

  float TPS = analogRead(A0) * (5.0 / 1023.0);

  //-----------------------JASON DATA--------------------------//

  StaticJsonBuffer<100> jsonBuffer;

  while (finished == false)
  {
    if (Serial.available())
    {
      const char in = Serial.read();
      if (in == '{')
      {
        response = "";  // Blank the string
        begin = true;
      }
      if (begin)
      {
        response += (in); // Only write if within the {}
      }
      if (in == '}')
      {
        begin = false;   // Prevent any chars between } and { leaking through.
        break;
      }
    }
    delay(1);
  }

  JsonObject& root = jsonBuffer.parseObject(response);

  float TPS_Json = root["TPS_Json"];

  float TPS_Final = TPS + TPS_Json;

  lcd.setCursor(0, 0);
  lcd.print("      ");
  lcd.setCursor(0, 0);
  lcd.print(TPS);
  lcd.setCursor(8, 0);
  lcd.print("      ");
  lcd.setCursor(8, 0);
  lcd.print(TPS_Json);
  lcd.setCursor(0, 1);
  lcd.print("      ");
  lcd.setCursor(0, 1);
  lcd.print(TPS_Final);
}

So, now I add TPS_Json with TPS. Where TPS_Json is JSON data and TPS is an analog value from A0. And TPS_Final is the addition of TPS_Json and TPS. I displayed all this on LCD.
Suppose, TPS_Json = 0.40, TPS = 2.40... So addition is 2.80 means TPS_Final = 2.80...
And this all data displayed on LCD successfully.
But when I changed my analog value means TPS value then it is not updated and I'm not getting the correct result.
Suppose, I change the value of TPS means makes it 3.00 from 2.40 than my TPS_Final must be 3.40.But nothing updated. It updated when I send JSON data again. I don't know why this happens. I want to change it in real time means When I changed TPS then TPS_Final must be changed in real time.

The reasons it's not updating is because your code is sitting in the loop while (finished == false) {...} waiting for more json to arrive.
Try replacing the while loop with something along these lines:
  while ((finished == false) || Serial.available()) {
   if (Serial.available()) {
    const char in = Serial.read();
    if (in == '{')  {
        response = "";  // Blank the string
        begin = true;
        finished = false;
    }
    if (begin)
        response += (in); // Only write if within the {}
    if (in == '}') {
        begin = false;   // Prevent any chars between } and { leaking through.
        finished = true;
    }
   }
  }

and change the initial variable declarations at the start of the code to set finished to false:
// personally I always put each variables on a separate lines when setting initial values.
bool begin = false;
bool finished = false;

This will block until it's received at least 1 json string. After that it will check if there is new data on the serial port, if there is it will block until it's received the whole string, it there isn't any data waiting it will exit.
Oh and your response string is currently including the { } characters at the start and end, this contradicts your comments which imply that it doesn't.

Thank you for your effort. I tried out your code. Now my data is updated but I'm not getting JSON Data...It's displayed 0.00 instead of 0.40...

Code updated. If finished was false (not had any JSON or in the middle of a string) but there was no serial data waiting then invalid data would get added to the response string. I've added an if(serial.avalible()) to the code which should fix that.

Thank you. Now, it's working fine. Can you explain what is the fault in previous code?

I though I had explained it. When finished was false but there was no data waiting on the serial port it would still attempt to read the serial port. If this happened to be between the { and } characters junk would get inserted into the middle of the json string. Ultimately this is caused by serial ports being painfully slow in comparison to processors and so you end up having to wait for the message to finish.

Your code reads data from the serial interface and once it has read the input it re-evaluates the value of TPS_Final.  I've found it difficult to understand your question but I think you are saying this:
If you enter {"TPS_Json":"0.40"} in the serial monitor and A0 has a value that equates to 2.4 then you expect TPS = 2.80 on your LCD.  So do I.
Now if you change what ever is feeding A0 so that the value equates to 3.00 I think you are saying you expect you LCD to update to say TPS = 3.40, but it doesn't and you don't understand why.
IF that is the case then the answer is simple.  When you change the value for A0 you code is waiting for you to enter the serial data again, because it is a 'blocking function call' well a 'blocking' bit of code at any rate.  And until you enter a value in the serial monitor you code won't evaluate TPS again.
You need to change/remove the while loop so it your code will update the LCD even when the data is being entered by the serial interface.