text:
fastLED help - special reinforcements needed
Hello help needed trying to get fastLED to start and stop at specific points on the strip, i have this nice fade animation but need to split the strip intov about 3 sections and have it run at different times.
here is the mess i have made any help welcome...
#include <FastLED.h>
#define NUM_LEDS 60
#define DATA_PIN 6 //How boring and obvious!
#define COLOR_ORDER GRB //Green (G), Red (R), Blue (B)
#define CHIPSET WS2812B
#define BRIGHTNESS 60
#define VOLTS 5
#define MAX_AMPS 500 //value in milliamps

//ENOUGH NONSENSE!

CRGB leds[NUM_LEDS];

void setup() {
  FastLED.addLeds<CHIPSET,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS);
  FastLED.setMaxPowerInVoltsAndMilliamps(VOLTS, MAX_AMPS);
  FastLED.setBrightness(BRIGHTNESS);
  FastLED.clear();
  FastLED.show();
}

void loop() {
  fadeToBlackBy(leds, NUM_LEDS, 4);      // Smaller value = longer tail
  int i = (millis()/40) % NUM_LEDS;      // How fast it goes.
  leds[i] = CRGB::White;
  FastLED.show();
}

Cheers
Rob

Any idea how i can set a start led and end led position that is not the full lengh of the strip?
my micky mouse version ...
for(int i=40; i<strip.numPixels() -43; i++) { // For each pixel in strip...
i edit the "i=40" bit then the "-43;"

do you realize that you can write code like this? ... for(int i=start; i<end; i++)

Ok very sorry first time on here ill edit the question.

how about something like this https://wokwi.com/projects/362275278547275777

Here is an example sketch that shows how to manipulate data in a sub-section of an array.
https://wokwi.com/projects/362275278547275777
The important thing to understand, is that the FastLED.show(); is the function that does the sending of the leds[] array contents to the physical LED strip.
That means that you can do anything you want to the leds[] array, and the changes will not be visible until the show() function is called.
You can make changes in bits and pieces, without seeing the change increments.
This sketch also shows how to use timers to synchronize actions

#include <FastLED.h>

#define CHIPSET     WS2812B
#define COLOR_ORDER     GRB         // Green (G), Red (R), Blue (B)
#define NUM_LEDS         95
#define DATA_PIN          3
#define BRIGHTNESS      255
#define VOLTS             5
#define MAX_AMPS        500         // value in milliamps

CRGB leds[NUM_LEDS];                // main LED array
CRGB test[10];                      // set up separate array for merging with main LED array
                                    // kind of a sprite
int indx = 0;

boolean tick[4] = {false, false, false, false};    // countdown timers flags

unsigned long timeInterval  [4] = {10, 20, 1, 2};  // timers load with these values
unsigned long timeCounter   [4];                   // these are the actual timers

unsigned long previousMicros = 0;

void setup() {

  Serial.begin(115200);

  FastLED.addLeds<CHIPSET,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS);
  FastLED.setMaxPowerInVoltsAndMilliamps(VOLTS, MAX_AMPS);
  FastLED.setBrightness(BRIGHTNESS);
  FastLED.clear();

  memcpy(timeCounter, timeInterval, 4 * sizeof(long));  // preload timers
}

void loop() {

  unsigned long currentMicros = micros();

  if (currentMicros - previousMicros >= 1000) {   // 1 ms tick
    for (int i = 0; i < 4; i++) {
      previousMicros = currentMicros;

      timeCounter[i]-- ;                          // keep track of 4 time intervals
      if (timeCounter[i] == 0) {
        timeCounter[i] = timeInterval[i];         // reached zero, reload counter and emit a "tick"
        tick[i] = true;
      }
    }

    // fade sections of leds[] array at different rates
    // NOTE: "&leds[0]" and "leds" both point to the beginning of the array
    fadeToBlackBy(&leds [0], 30,  3);               //  long tail
    fadeToBlackBy(&leds[30], 30, 10);               //   mid tail
    fadeToBlackBy(&leds[60], 30, 20);               // short tail
    fadeToBlackBy(&leds[90],  5,  1);               // really long tail

    if (tick[0]) {    // 10 ms tick
      tick[0] = false;
      leds[indx] = CRGB::White;                   // add the "running dot" after fades are applied
      indx++;
      if (indx > (NUM_LEDS-1)) indx = 0;
    }

    if (tick[1]) {    // 20 ms tick
      tick[1] = false;

//    the &test[0] points to the array element directly
//    it allows the choice of a starting point for the fade function

//    fadeToBlackBy( test,    3, 16);               // these two lines are the same
      fadeToBlackBy(&test[0], 3, 16);               // fade only first three elements in the array
      fadeToBlackBy(&test[3], 1, 20);               // fade only the third element in the array

      if(test[0].r < 64){                           // pixels faded enough
        test[0]= CRGB(248, 11, 130);                // reload pixels
        test[1]= CRGB(221, 245, 6);
        test[2]= CRGB(112, 16, 236);
        test[3]= CRGB(16, 236, 53);
      }
    }
    memcpy(&leds[10], test,     4 * sizeof(CRGB));    // apply 4 pixels to leds[] array
    memcpy(&leds[50], &test[0], 4 * sizeof(CRGB));    // apply 4 pixels to leds[] array
    memcpy(&leds[80], &test[1], 3 * sizeof(CRGB));    // apply 3 pixels to leds[] array

    FastLED.show();                                   // send pixel data to the LED strip
  }
}


text:
Running Arduino with 2 outputs and 2 inputs
Totally new to Arduino, 3 weeks old!
I am doing a project with 2 inputs (2 x ultrasonic sensors) and 2 outputs (buzzer and send SMS)
The code to run the buzzer and sms works perfectly individually. For the buzzer, it will stop buzzing after approx 5 seconds.
I would love them to run concurrently but it didn't work as planned when I upload the code on the board.
I've read on forums to use millis / blinkwithoutdelay but am unsure how I can incorporate those functions on my mode as the examples posted online are different from my project.
The following is the code I have created.
Would appreciate if I can get some help from the experienced folks here.
#define TRIG A0 //Module pins
#define ECHO A1
#define TRIG1 A2 //Module pins
#define ECHO1 A3
#define Buzzerpin 13

int ctn = 0;

void setup() {
  Serial.begin(9600); // Serial monitoring
  pinMode(TRIG, OUTPUT); // Initializing Trigger Output and Echo Input
  pinMode(ECHO, INPUT_PULLUP);
  pinMode(TRIG1, OUTPUT); // Initializing Trigger Output and Echo Input
  pinMode(ECHO1, INPUT_PULLUP);
  pinMode(Buzzerpin, OUTPUT);
}

void loop() {

  digitalWrite(TRIG, LOW); // Set the trigger pin to low for 2uS
  delayMicroseconds(2);

  digitalWrite(TRIG, HIGH); // Send a 10uS high to trigger ranging according to specs
  delayMicroseconds(20);

  digitalWrite(TRIG, LOW); // Send pin low again
  delayMicroseconds(2);

  digitalWrite(TRIG1, LOW); // Set the trigger pin to low for 2uS. Give a short LOW pulse beforehand to ensure a clean HIGH pulse
  delayMicroseconds(2);

  digitalWrite(TRIG1, HIGH); // Send a 10uS high to trigger ranging according to specs
  delayMicroseconds(20);

  digitalWrite(TRIG1, LOW); // Send pin low again
  delayMicroseconds(2);

  int distance = pulseIn(ECHO, HIGH, 26000); // Read in times pulse
  int distance1 = pulseIn(ECHO1, HIGH, 26000); // Read in times pulse
  distance = distance/58;
  distance1 = distance1/58;

  if (distance < 25) {
    Serial.print("\r");
    delay(1000);
    Serial.print("AT+CMGF=1\r");
    delay(1000);
    /*Replace XXXXXXXXXX to 10 digit mobile number & ZZ to 2 digit country code*/
    Serial.print("AT+CMGS=\"+YYXXXX\"\r"); // YY is the country code XXX is the number
    delay(1000); //
    //The text of the message to be sent.
    Serial.print("HELLO There");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);
  }
  else {}

  if (distance1 < 25 && ctn < 150) {
    ctn += 1;
    digitalWrite(Buzzerpin, HIGH);
  }
  else {
    digitalWrite(Buzzerpin, LOW);
  }

  if (distance1 > 25 && ctn >= 150) {
    ctn = 0;
    digitalWrite(Buzzerpin, HIGH);
  }
}

First thing: you should call pulseIn() right after sending the TRIG
pulse. If you wait too much, you will miss the start of the echo pulse.
For instance, here:
int distance = pulseIn(ECHO, HIGH, 26000);
int distance1 = pulseIn(ECHO1, HIGH, 26000);

the second pulseIn() is starting too late, because of the time taken
by the first one.
Next, the general approach for doing things is a non-blocking fashion
(and thus being able to handle concurrent tasks) is to program each task
in the form of a finite state machine. Combine this with the
timing technique used in the “Blink without delay” Arduino tutorial if
you need time-triggered actions.
Here I would use one state machine for sending the SMS and another one
for the buzzer. The first one is the most complex:
Edit: I expanded on how I designed this state machine.
In a canonical finite state machine implementation, each action is
associated with a state transition. We then have a transition for each
command sent to the GSM module, and we can label the states according to
which commands have already been sent, like this:
SENT_NOTHING → SENT_CR → SENT_CMGF → SENT_CMGS → SENT_MSG →
SENT_ALL.
All of the above transitions send a string to the GSM module. The first
one (SENT_NOTHING → SENT_CR) is triggered by the distance detected
being less than 25 cm. The following ones are time-triggered one
second after the previous one. We have to add one final transition
(SENT_ALL → SENT_NOTHING) that performs no action but lets the system
“forget” it has sent an SMS and thus makes it ready to send a new one.
This transition would also be time-triggered, after a potentially long
delay (how often would the user like to receive those reminders?). In
the code below, this last delay is one second, which I believe is too
short, but matches the last delay(1000) in the code you posted. The
implementation would be like this:
static enum {
  SENT_NOTHING, SENT_CR, SENT_CMGF, SENT_CMGS, SENT_MSG, SENT_ALL
} sms_state = SENT_NOTHING;
static uint32_t time_last_command_sent;
uint32_t now = millis();
switch (sms_state) {
  case SENT_NOTHING:
    if (distance < 25) {
      Serial.print("\r");
      time_last_command_sent = now;
      sms_state = SENT_CR;
    }
    break;
  case SENT_CR:
    if (now - time_last_command_sent >= 1000) {
      Serial.print("AT+CMGF=1\r");
      time_last_command_sent = now;
      sms_state = SENT_CMGF;
    }
    break;
  case SENT_CMGF:
    if (now - time_last_command_sent >= 1000) {
      Serial.print("AT+CMGS=\"+YYXXXX\"\r");
      time_last_command_sent = now;
      sms_state = SENT_CMGS;
    }
    break;
  // and so on for the cases SENT_CMGS and SENT_MSG...
  case SENT_ALL:
    if (now - time_last_command_sent >= 1000) {
      sms_state = SENT_NOTHING;  // forget we sent an SMS
    }
    break;
}

I have an issue with this implementation though: it is overly
repetitive, as the cases SENT_CR, SENT_CMGF, SENT_CMGS and SENT_MSG
are essentially copies of the same code. In order to make the code
dryer, I prefer merging them into a single state, and splitting
the state information into two variables: sms_state and
commands_sent. The new possible values for sms_state are now:

SMS_READY: the code is ready to send the message as soon as it is
required by the detected distance.
SMS_SENDING: it has started to send the commands to the GSM module,
but is not done yet.
SMS_DONE: the SMS has been sent, but no other one will be sent until
some time has elapsed, after which it will transition to SMS_READY.

The mapping to the “full” machine states is then:
 full state    │ sms_state   commands_sent
───────────────┼───────────────────────────
 SENT_NOTHING  │ SMS_READY         0
 SENT_CR       │ SMS_SENDING       1
 SENT_CMGF     │ SMS_SENDING       2
 SENT_CMGS     │ SMS_SENDING       3
 SENT_MSG      │ SMS_SENDING       4
 SENT_ALL      │ SMS_DONE          5

It could be argued that sms_state is redundant, as all the state
information is contained in commands_sent. I still wanted to keep
sms_state in order to easily switch on it. This is not the only
possible approach though, and it would be perfectly sensible to write
something like
if (commands_sent == 0) {
  // handle the case SMS_READY
} else if (commands_sent < command_count) {
  // handle the case SMS_SENDING
} else {
  // handle the case SMS_DONE
}

For the buzzer, there are only two states: BUZZER_OFF and BUZZER_ON.
The transitions are conditioned by the measured distance and, for the ON
→ OFF transition, also by the time it has been ON.
Here is my tentative, untested implementation of this approach:
#define TRIG A0 //Module pins
#define ECHO A1
#define TRIG1 A2 //Module pins
#define ECHO1 A3
#define Buzzerpin 13

// Commands to be sent to the GSM module.
const int command_count = 5;
const char * const commands[command_count] = {
  "\r",
  "AT+CMGF=1\r",
  "AT+CMGS=\"+YYXXXX\"\r",
  "HELLO There",
  "\x1a"
};

void setup() {
  Serial.begin(9600);
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT_PULLUP);
  pinMode(TRIG1, OUTPUT);
  pinMode(ECHO1, INPUT_PULLUP);
  pinMode(Buzzerpin, OUTPUT);
}

void loop() {
  // Measure both distances.
  digitalWrite(TRIG, LOW);
  digitalWrite(TRIG, HIGH);
  delayMicroseconds(20);
  digitalWrite(TRIG, LOW);
  int distance = pulseIn(ECHO, HIGH, 26000) / 58;
  digitalWrite(TRIG1, HIGH);
  delayMicroseconds(20);
  digitalWrite(TRIG1, LOW);
  int distance1 = pulseIn(ECHO1, HIGH, 26000) / 58;

  // Timing for both state machines.
  uint32_t now = millis();

  // Send the SMS.
  static enum {SMS_READY, SMS_SENDING, SMS_DONE} sms_state;
  static uint32_t time_last_command_sent;
  static int commands_sent = 0;
  switch (sms_state) {
    case SMS_READY:
      if (distance < 25) {
        Serial.print(commands[commands_sent++]);
        time_last_command_sent = now;
        sms_state = SMS_SENDING;
      }
      break;
    case SMS_SENDING:
      if (now - time_last_command_sent >= 1000) {
        Serial.print(commands[commands_sent++]);
        time_last_command_sent = now;
        if (commands_sent >= command_count) {
          sms_state = SMS_DONE;
        }
      }
      break;
    case SMS_DONE:
      if (now - time_last_command_sent >= 1000) {
        commands_sent = 0;
        sms_state = SMS_READY;
      }
      break;
  }

  // Drive the buzzer.
  static enum {BUZZER_OFF, BUZZER_ON} buzzer_state;
  static uint32_t time_buzzer_started;
  if (buzzer_state == BUZZER_OFF && distance1 < 25) {
    digitalWrite(Buzzerpin, HIGH);
    buzzer_state = BUZZER_ON;
    time_buzzer_started = now;
  } else if (buzzer_state == BUZZER_ON && distance1 >= 25
             && now - time_buzzer_started >= 2000) {
    digitalWrite(Buzzerpin, LOW);
    buzzer_state = BUZZER_OFF;
  }
}

Wow. You did a major rewrite of the OPs code. I decided to treat this as a "give a man a fish/teach a man to fish" situation, and instead offer general guidance.

@DuncanC, more important is that this is a nice example of the technique

Agreed, it's is an elegant reworking of the OPs code.

Hi Edgar, thank you so much for the code. Can I check, can I change the time in 'if (now - time_last_command_sent >= 1000) {' for both SMS_SENDING and SMS_DONE? Will it disrupt the flow of the circuit?

@Zac: I encourage you to study this code (start with the “finite state machine” link I provided), understand it (ask questions if needed) and then change anything you want. Actually I believe you really have to play with it in order to fully comprehend its working.

Using the blinkwithoutdelay approach is not incorporating functions, it is a coding style.
The idea is that you write your loop code to pass through without any delays, or with only very tiny delays. On each pass through the loop, you see how much time has passed, and if it's been 5 seconds since you started the buzzer, you turn off the buzzer.
You can probably get away with the microsecond delays that you use in your ultrasonic sensor code. Those delays are so small that they will only cause very short pauses in your app.
The delay(1000) calls in your loop are not going to work. Each one of those causes EVERYTHING to stop for a full second. You won't check the ultrasonic sensor, you won't change the buzzer state, you won't do ANYTHING, for 5 seconds, once you enter the body of that if statement. Those delay calls have to go.

source: Stack Exchange

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

sort: votes


text:
what will be the sampling frequecy of my arduino Mega 2560 code. How would I calculate it?

void setup() {
    // initialize the serial communication:
    Serial.begin(9600);
    pinMode(10, INPUT); // Setup for leads off detection LO +
    pinMode(11, INPUT); // Setup for leads off detection LO -
}

void loop() {
    if ((digitalRead(10) == 1) || (digitalRead(11) == 1)) {
        Serial.println('!');
    }
    else {
        // send the value of analog input 0:
        Serial.println(analogRead(A0));
    }
    //Wait for a bit to keep serial data from saturating
    delay(1);
}

EDIT
This sketch is for plotting raw ECG signal having a baud rate of 9600. but when I use these data for calculating heart rate then I want sampling rate for calculation but I don't get the value by this sketch. How will I calculate the frequency from the coming raw data? As it does not show a clear picture.

On the Arduino Mega, the ADC is clocked at F_CPU/128 =
125 kHz (period = 8 µs). Except for the very first one,
each ADC conversion takes 13 ADC clock cycles, i.e. 104 µs. If
you run analogRead() in a tight loop, like
for (;;)
    analogRead(A0);

the CPU has to do some work in between the conversions, and since the
ADC always starts by waiting for a rising edge of the ADC clock, you
loose at least one full ADC cycle in between the conversions. You then
get one conversion every 14 ADC cycles, which results in a sampling
period of 112 µs, and the corresponding sampling frequency of about
8.93 kHz.
The code you showed does a little bit more than an analogRead() per
iteration: two digitalRead(), a test, and a Serial.println() that
involves a binary to decimal conversion. I am not sure the CPU will be
able to handle all that in a mere 8 µs. You might end up using
15 ADC clock cycles per iteration (13 for the conversion,
2 for the computation), which would result in 120 µs
(8.33 kHz) sampling period. Maybe even more. You will have to test
if you want to know for sure. The sampling period is not even guaranteed
to be constant: the code will take longer to run whenever it's
interrupted by the timer interrupt, which the Arduino core uses for
timekeeping purposes...
All this applies as long as the serial output buffer is not full. Once
you have 64 bytes waiting to be sent, the buffer will be full, and
Serial.println() will start delaying the output, effectively
throttling down your loop to the speed of the serial connection. C.f.
the busybee's answer for the details. Note that the sampling period is
still not constant, as sending a 1-to-4-digit number through the serial
port can take anywhere between 3.125 and 6.25 ms.
If you want a constant sampling period, you have to take control over
the timing yourself. A straightforward example would be:
const uint32_t SAMPLING_PERIOD = 6500;  // 6.5 ms

void loop() {
    static uint32_t last_sample;
    if (micros() - last_sample >= SAMPLING_PERIOD) {
        last_sample += SAMPLING_PERIOD;
        Serial.println(analogRead(A0));
    }
}

You could go faster with a higher baud rate, but you have to always keep
SAMPLING_PERIOD consistent with your chosen baud rate. The code above
will still produce some jitter in the sampling, mostly due to the timer
interrupt. If this is not acceptable for your application, you will have
to read the datasheet of the microcontroller and learn how to set the
ADC to be “auto-triggered” from a timer.

The sampling frequency is calculated by the number of samples per time. I think you need to know how fast you're able to do this in your loop().
For this you could fetch the start time, do a number of sampling, fetch the end time, and calculate the frequency.
This is the straight forward and simple way.
Please be aware the the turn-arund time for your sketch will include the transmission time for the result. This will be much longer than the time for the "pure" analog conversion.

Alternatively you can lookup the source code of Arduino's library function for analogRead(), get the data sheet, learn how the conversion works, and calculate the time.
But this is not at all easy.

BTW, delay(1) is by far not enough to "saturate" the serial transmission you do. You are using 9600 baud which gives about 960 characters per second. The biggest number you send is "1023" and the sequence "\r\n" is appended due to println(). So you are transmitting 6 characters which need 6 characters / 960 characters/s = 0.00625 s. These are a bit more than 6 ms, so you would delay(7) at least.
If you don't, the call to println() will do the delay if the transmitter's buffer gets full. Therefore your sketch will wait anyway. So you might consider to remove the delay.

And please, use the correct formatting the next time. ;-)

THANKS...But still, I didn't get my answer. I want to calculate sampling frequency by calculation method not by just rough idea. So if you have any better method please share with me. Thanku

Well, my answer targets real-world aspects. For the detailed alternative see @EdgarBonet's answer. My hint in the second part is just a pointer to start with. -- It is not clear, for which situation you need to know the frequency. You should elaborate on this issue in your question. As your sketch is written, the frequency is by far determined by the serial transmission, not by the sampling itself.

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


text:
Stuck in a loop using IR Receiver
I am new to Arduino Programming and I have bought an Arduino UNO , Ultrasonic Sensor (HC-SR04), A Piezo Buzzer, IR Receiver (VS1838B) and a RGB LED....
I wrote a program to Calculate Distance form the Ultrasonic Sensor to an object and a Processing Sketch to Display the results.
Now I want to use the IR Receiver to increase the Distance Threshold which makes the buzzer beep...I mean I want to press 1 in my remote to keep the distance about 5 cm after which the buzzer beeps, and when I press 2 the distance becomes 10 cm and so on...I want to stop everything when I press 0 in my remote...
I have already found out the hex codes of my remote buttons but the program makes the task harder...
Please help me with the program that I have already written :-
#include <NewTone.h>
#include <IRremote.h>

const int rec = 9;
IRrecv irrecv(rec);
decode_results results;

#define BUTTON_0 0xFF6897
#define BUTTON_1 0xFF30CF
#define BUTTON_2 0xFF18E7
#define BUTTON_3 0xFF7A85
#define BUTTON_EQ 0xFF906F
#define BUTTON_4 0xFF10EF

const int redPin = 5;
const int greenPin = 6;
const int bluePin = 10;
const int trigPin = 12;
const int echoPin = 11;
const int buzPin = 3;
double duration;
double distanceCm, distanceInch;
double dur;

void setup() {

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
  pinMode(buzPin, OUTPUT);
  irrecv.enableIRIn();
  Serial.begin(9600);
}

void loop()
{
  if (irrecv.decode(&results))
  {
    if (results.value != BUTTON_0)
    {

      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);

      duration = pulseIn(echoPin, HIGH);
      distanceCm = duration * 0.034 / 2;
      distanceInch = duration * 0.0133 / 2;
      dur = duration / 10000;

      Serial.print(distanceCm);
      Serial.print("  cm ");
      Serial.print("                         ");
      Serial.print(distanceInch);
      Serial.print(" Inch ");
      Serial.print("                         ");
      Serial.print(dur);
      Serial.print(" Seconds");
      Serial.print("\n");
    }

    if (results.value == BUTTON_0)
    {

      noNewTone(buzPin);
      analogWrite(redPin, 0);
      analogWrite(greenPin, 0);
      analogWrite(bluePin, 0);
    }

    if (results.value == BUTTON_1)
    {

      if (distanceCm <= 5)
      {
        NewTone(buzPin, 2000);
        analogWrite(redPin, 255);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 0);
      }
      else if (distanceCm <= 10 && distanceCm > 5)
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 255);
      }
      else
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 255);
        analogWrite(bluePin, 0);
      }

    }

    if (results.value == BUTTON_2)
    {

      if (distanceCm <= 10)
      {
        NewTone(buzPin, 2000);
        analogWrite(redPin, 255);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 0);
      }
      else if (distanceCm <= 20 && distanceCm > 10)
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 255);
      }
      else
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 255);
        analogWrite(bluePin, 0);
      }

    }

    if (results.value == BUTTON_3)
    {

      if (distanceCm <= 30)
      {
        NewTone(buzPin, 2000);
        analogWrite(redPin, 255);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 0);
      }
      else if (distanceCm <= 50 && distanceCm > 30)
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 255);
      }
      else
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 255);
        analogWrite(bluePin, 0);
      }

    }

    if (results.value == BUTTON_4)
    {

      if (distanceCm <= 100)
      {
        NewTone(buzPin, 2000);
        analogWrite(redPin, 255);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 0);
      }
      else if (distanceCm <= 200 && distanceCm > 100)
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 255);
      }
      else
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 255);
        analogWrite(bluePin, 0);
      }

    }
    irrecv.resume();
  }
}

I am using the "IRremote.h" and "NewTone.h" Libraries....
The main problem is that the "irrecv.resume();" pauses the program and waits for the IR input but I want the program to run continuously till I give an IR Input...
I request you to help me with the program.

I edited my program to this and this worked:-
#include <NewTone.h>
#include <IRremote.h>

const int rec = 2;
IRrecv irrecv(rec);
decode_results results;

#define BUTTON_0 0xFF6897
#define BUTTON_1 0xFF30CF
#define BUTTON_2 0xFF18E7
#define BUTTON_3 0xFF7A85
#define BUTTON_EQ 0xFF906F
#define BUTTON_4 0xFF10EF

const int redPin = 5;
const int greenPin = 6;
const int bluePin = 10;
const int trigPin = 12;
const int echoPin = 11;
const int buzPin = 3;
double duration;
double distanceCm, distanceInch;
double dur;

void setup() {

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
  pinMode(buzPin, OUTPUT);
  Serial.begin(9600);
  irrecv.enableIRIn();
}

void loop()
{
  if (irrecv.decode(&results))
  {

    do
    {
      if (results.value == BUTTON_0)

      {

        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 0);
      }

      if (results.value == BUTTON_1)
      {
        sonic();

        if (distanceCm <= 5)
        {
          red();
        }
        else if (distanceCm <= 10 && distanceCm > 5)
        {
          blue();
        }
        else
        {
          green();
        }

      }

      if (results.value == BUTTON_2)
      {
        sonic();
        if (distanceCm <= 10)
        {
          red();
        }
        else if (distanceCm <= 20 && distanceCm > 10)
        {
          blue();
        }
        else
        {
          green();
        }
      }

      if (results.value == BUTTON_3)
      {
        sonic();
        if (distanceCm <= 30)
        {
          red();
        }
        else if (distanceCm <= 50 && distanceCm > 30)
        {
          blue();
        }
        else
        {
          green();
        }
      }

      if (results.value == BUTTON_4)
      {
        sonic();
        if (distanceCm <= 100)
        {
          red();
        }
        else if (distanceCm <= 200 && distanceCm > 100)
        {
          blue();
        }
        else
        {
          green();
        }

      }
    }
    while (digitalRead(rec) == 1);

    irrecv.resume();
  }
}

void sonic()
{
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distanceCm = duration * 0.034 / 2;
  distanceInch = duration * 0.0133 / 2;
  dur = duration / 10000;

  Serial.print(distanceCm);
  Serial.print("  cm ");
  Serial.print("                         ");
  Serial.print(distanceInch);
  Serial.print(" Inch ");
  Serial.print("                         ");
  Serial.print(dur);
  Serial.print(" Seconds");
  Serial.print("\n");
}

void green()
{
  noNewTone(buzPin);
  analogWrite(redPin, 0);
  analogWrite(greenPin, 255);
  analogWrite(bluePin, 0);
}

void blue()
{
  noNewTone(buzPin);
  analogWrite(redPin, 0);
  analogWrite(greenPin, 0);
  analogWrite(bluePin, 255);
}

void red()
{
  NewTone(buzPin, 2000);
  analogWrite(redPin, 255);
  analogWrite(greenPin, 0);
  analogWrite(bluePin, 0);
}

But now the problem is I need to press the IR Remote button two times because when I press once the program moves to the irrecv.resume(); command and waits for another IR Input and I need to press the button again.
Can this be solved (with only one press)?

The call to irrecv.resume() should not block. The IR detection runs on a timer interrupt. Maybe you have 2 parts of code, that both try to use one timer. Can you try, if the IR code is working, when you comment out all NewTone code or all analogWrite code? (Both also use timers)

Your code becomes more readable, if you use functions with return values.
For example, something like this structure
unsigned int limit; // 0 = off, else limit in cm  ...
void loop() {
  if (irrecv.decode(&results)) {
      byte key = getIRKey(results.value); // 0 , 1, 2, etc.,  0xFF for unknown
      irrecv.resume();
      switch (key) {
         case 0: limit = 0; break;
         case 1: limit = 5; break;
         ...
         default: break; // wrong key does not change limit
      }
  }
  if (limit) {
     unsigned int dist = sonic(); // returns the measured distance or 0
     if (dist && dist < limit) NewTone(buzPin, 2000);
     else noNewTone(buzPin); // off: too far
  } else noNewTone(buzPin); // off: no check
}

This code should not block. Have fun modifying sonic() and creating the other helper function.

You really should use switch-case.
irrecv.resume() does not halt the code.

Your program is running fine. It seems like you want to make sensor readings continuously and act only when you press the button. Am I right?

Yes, You are Right... I want to do a loop till another button is pressed and when it is pressed it should go into another loop.


text:
Getting error invalid conversion from 'const char*' to 'const uint8_t*
I have written this sketch, and I am trying to populate the array of wifi hotspots to  set the value in html select using javascript dynamically.
#include <Arduino.h>
#include <Hash.h>
#include "ESP8266WiFi.h"
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>

const char* ap_ssid     = "ESP8266";
const char* ap_password = "0123456789";

// Create AsyncWebServer object on port 8080
AsyncWebServer ap_server(8080);

const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML>

  <meta name="viewport" content="width=device-width, initial-scale=1">

)rawliteral";

void setup() {
  Serial.print("Setting AP (Access Point)…");
  // Remove the password parameter, if you want the AP (Access Point) to be open
  WiFi.softAP(ap_ssid, ap_password);

  IPAddress IP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(IP);

  // Print ESP8266 Local IP Address
  Serial.println(WiFi.localIP());

  // Route for root / web page
  ap_server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) {
    request->send_P(200, "text/html", index_html, getWifiHotspots());
  });

  // Start server
  ap_server.begin();
}

void loop() {
  // put your main code here, to run repeatedly:

}

But I am geting this error
    /Arduino/libraries/ESPAsyncWebServer/src/ESPAsyncWebServer.h:243:10: error:   initializing argument 4 of 'void AsyncWebServerRequest::send_P(int, const String&, const uint8_t*, size_t, AwsTemplateProcessor)' [-fpermissive]

     void send_P(int code, const String& contentType, const uint8_t * content, size_t len,
AwsTemplateProcessor callback=nullptr);
          ^

exit status 1
invalid conversion from 'const char*' to 'const uint8_t* {aka const unsigned char*}' [-fpermissive]

Try to force the conversion in the function parameter: send_P(200, "text/html", (uint8_t *)index_html, getWifiHotspots());.

In the library ESPAsyncWebServer.h are these two possible function variants defined
  void send_P(int code, const String& contentType, const uint8_t * content, size_t len, AwsTemplateProcessor callback=nullptr);
   void send_P(int code, const String& contentType, PGM_P content, AwsTemplateProcessor callback=nullptr);

So  when using
const char index_html[] PROGMEM = R"rawliteral(<YOUR HTML here>)rawliteral";

give the compiler the explicit instruction
ap_server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) {
  request->send_P(200, "text/html", (const uint8_t*) index_html, getWifiHotspots());
 });

The code compiles error free on ArduinoIDE 1.8.12/ESP8266 2.71/ NodeMCUv1 (as not having your definition of getWifiHotspots() I defined it as char)

I see, I am getting error because index_html is of char type and the getWifiHotspots returns array of Strings?

@Ciastopiekarz No, as the error message clearly states, the argument is a const char *, and the function expects a const uint8_t *. -- BTW, actually you are programming C++, and the right cast is static_cast<const uint8_t *>(...).


text:
Is there a more elegant way to check highest / lowest sample data?
N00b question,
Is there a better way for readability / elegance / DRY etc to check various sensor values for high/low record value?  This code works, but looks like the long way round.
  void checkRecord() {

if ( temp.current > temp.high) {
  temp.high = temp.current;
}

if ( temp.current < temp.low) {
  temp.low = temp.current;
}

if ( pressure.current > pressure.high) {
  pressure.high = pressure.current;
}

if ( pressure.current < pressure.low) {
  pressure.low = pressure.current;
}
if ( humidity.current > humidity.high) {
  humidity.high = humidity.current;
}

if ( humidity.current < humidity.low) {
  humidity.low = humidity.current;
}

if ( rainfall.current > rainfall.high) {
  rainfall.high = rainfall.current;
}

if ( rainfall.current < rainfall.low) {
  rainfall.low = rainfall.current;
}
if ( altitude.current > altitude.high) {
  altitude.high = altitude.current;
}

if ( altitude.current < altitude.low) {
  altitude.low = altitude.current;
}
}

Thanks!

If it works and is clear, what else do you need?  if statements execute quickly and I doubt you are calling the function quickly enough for execution time to matter.  Alternatively you could consider storing the data in an array rather than each variable separately - could make export easier.

nothing wrong with the code ..... formatting is incorrect .... the whole checkRecord() block should be indented  ..... it is only a readability issue ..... you could single-line all the if statements .... if ( temp.current > temp.high)   temp.high = temp.current; ..... then you could neatly line up everything in a column .... put all the equal signs under each other

This is a variation on the struct idea with an object-oriented flavor.
If you put the current, low and high values of any sensor inside a
struct, you could also morph this struct into a class and give it
an update() method that, in addition to updating the current value,
keeps the low and high updated:
class LowHigh
{
public:
    LowHigh() : current(0), low(INFINITY), high(-INFINITY) {}
    void update(float value) {
        current = value;
        if (current < low)
            low = current;
        if (current > high)
            high = current;
    }
    float get_low() { return low; }
    float get_high() { return high; }
private:
    float current, low, high;
};

I am assuming float data here, you may have to adapt to whatever type
is appropriate for your sensors.
You would use the class as this:
LowHigh temp, pressure, humidity, rainfall, altitude;

void loop()
{
    temp.update(temp_sensor.get_reading());
    pressure.update(pressure_sensor.get_reading());
    humidity.update(humidity_sensor.get_reading());
    // ...
}

I like this, it may require a bit of rework to my code, but a Sensor class is exactly how I should go about it to learn OOP and not think so procedural about things.  Thanks for your example!  I like the INFINITY for setting initial high/low, I had used  large and small values out of range.

I edited your answer to make the argument of the update method a float instead of int. Good explanation.

Thanks @MichelKeijzers, that was an oversight of mine.

You could write something like:
temp.high = (temp.current > temp.high) ? temp.current : temp.high;
temp.low  = (temp.current < temp.low) ? temp.current : temp.low;
...

Most of the time there are min/max macros defined already like:
#define MAX(a, b)   ((a > b) ? a : b)
#define MIN(a, b)   ((a < b) ? a : b)

So you can then simply write:
temp.high = MAX(temp.current, temp.high);
temp.low  = MIN(temp.current, temp.low);
...

Which expands to the exact code as given above.

I achieves the goal of looking a bit more tidy... Thank you!

Jeff Wahaus, you can go one step further. Can you make a macro for that with float numbers?

Unfortunately this way is slower, because every loop it updates the values of temp.high and temp.low. The original code updated that value only when conditions where true.

@FilipFranik actually, it is exactly as fast as the if-statements. The compiler seems to be able to optimize it.

Yes, the optimizer sees 'a=a' and optimizes it out unless you declare 'a' volatile.

These macros are already defined in Arduino.h, but they are spelled in lowercase: min() and max().

If the temperature, pressure, humidity, rainfall, and altitude structs were elements of an array of structs, you could iterate over those elements setting each one's high and low values with only two handwritten 'if-then' statements. If you also used an enum to name the indices of the structs, then in other parts of your code you could address each of them by a descriptive name:
// Declare a data struct and define an array of them.
struct {
   int16_t current;
   int16_t high;
   int16_t low;
} data[5] = {0, 0, 0, 0, 0};

// Name the structs by index
enum kind {
   temperature = 0,
   pressure,
   humidity,
   rainfall,
   altitude
};

// Assign one kind of data:
data[temperature].current = getTermperature();

// Set maxes & mins for all of the kinds of data:
for( i = 0; i < sizeof(data)/sizeof(data[0])); ++i ){
   if ( data[i].current > data.high) {
      data[i].high = data[i].current;
   }

   if ( data[i].current < data[i].low) {
      data[i].low = data[i].current;
   }
}

Update:

I'm strugling with the data[5] {0,0...} part in struct.

I can't see your whole sketch but you probably have allocated 5 separate structs named "temp", "pressure", ... , etc. I'm suggesting you allocate an array of 5 structs (which I collectively called "data"), one for each of your individual ones. I included an initializer ( '= {0,0,0,0,0}') to set everything to zero before the start of the run.

all of enum kind{} and how it becomes data[pressure] etc.,

The enum is a quick way to make 5 symbols that stand for consecutive integers, in this case, the index into the array of each struct, using a descriptive name for that struct's data. So 'data[pressure]' is the same as data[1] (in this case) but is more understandable.

the sizeof(data)/sizeof(data[0]) in the loop

That expression gives the number of structs in the array (the total byte-size of the array divided by the byte-size of one struct). We could write '5' instead, but when you someday add another member or two (wind_direction, wind_speed, perhaps?), you'd have to remember to also fix your for() loop. By using this calculation, the compiler will do it for you, leaving you one less opportunity to make a mistake you'd then need to debug.

and finally I think
  altitude.high in the if statement is a paste typo? should be
  data[i].high?

Absolutely right! Fixed now.
Update:

For defining initial values can you just assign an initial value in
  the struct such as int16_t low = INFINITY; and so on instead of
  {0,0,0,0,0}?

Yes - Without knowing your data and application, I chose the simplest initializer. The full syntax to do what you want would look like this:
// Declare a data struct and define an array of them.
struct {
   int16_t current;
   int16_t high;
   int16_t low;
} data[5] = {
  {0, 0, INFINITY},
  {0, 0, INFINITY},
  {0, 0, INFINITY},
  {0, 0, INFINITY},
  {0, 0, INFINITY}
};

You don't need (and may not) specify each data type and name; the struct declaration already provides that information. The initializers are positional and each one must be compatible with the data-type it matches up to.

Thanks, I don't understand a few things because n00b. I'm strugling with the data[5] {0,0...} part in struct.  all of enum kind{} and how it becomes data[pressure] etc., the  sizeof(data)/sizeof(data[0]) in the loop and finally I think altitude.high in the if statement is a paste typo?  should be data[i].high?

Thank you so much, the explanation of enum kind{}, and the expression in the loop was very helpful in understanding how it all fit together.  For defining initial values can you just assign an initial value in the struct such as int16_t low = INFINITY; and so on instead of {0,0,0,0,0}?  Since a default value of 0 for low will not work properly if the temp is above freezing.


text:
Button for Delay Select
My target is to make an Arduino system that is able to change modes with different delays by pushing a button. For example, if I pressed the button, it will go into mode 1 with loop 1 that has a 30s delay. If I pressed it one more time, it will go to mode 2 with with loop 2 that has a 1 min delay, etc. The important thing is that mode 1 should be breaked when the push button pressed.
The code below solved part of the problem. However, LEDs are only constant ON, they are not blinking for a certain time then it turned either on-off within the mode when the push button pressed.
int b =3;int rl= 5;int gl=6;
int yl=7; int s=0; int o=0;
 int bp =0;

void setup() {
  // put your setup code here, to run once:
pinMode(b,INPUT);
pinMode(rl,OUTPUT);
pinMode(gl,OUTPUT);
pinMode(yl,OUTPUT);

 digitalWrite(rl,LOW);
digitalWrite(gl,LOW);
digitalWrite(yl,LOW);
}

void loop() {
  // put your main code here, to run repeatedly:

bp=digitalRead(b);
if (bp==1){
  delay(50);
  bp=digitalRead(b);
  if (bp==0){
    s=o+1;}}
    else{
      delay(100);}
      switch(s){
        case 1:
        digitalWrite(rl,HIGH);
digitalWrite(gl,LOW);
digitalWrite(yl,LOW);
o=s;
break;

case 2 :
digitalWrite(rl,LOW);
digitalWrite(gl,HIGH);
digitalWrite(yl,LOW);
o=s;
break;

case 3:

digitalWrite(rl,LOW);
digitalWrite(gl,LOW);
digitalWrite(yl,HIGH);
o=s;
break;
default:

digitalWrite(rl,LOW);
digitalWrite(gl,LOW);
digitalWrite(yl,LOW);
o=0;
break;}}

S1 is responsible to activate D12 to be constant ON (when it’s pressed once) which lead UNO2 to be powered then blink the right LED ON (1min) OFF(4Hr), (pressing it twice should turn D12 OFF (optional)). The same thing with S2, when it’s pressed once it should first disable D12 and activate D11 instead, powering UNO3, blinking the left LED ON(30S), OFF (4Hr).
In addition, blinking on() off() repeatedly is needed (unless action break/occur, ex: pressing S1 or S2).
About S1 and S2. The LED on D12 will flash ON for 1 minute then turn off for 4 hours. After the 4 hours, the LED on D12 will flash ON again for 1 min then turn off for 4 hours again & again...as an infinite loop. With S2 The LED on D11 will flash ON for 30 seconds then turn off for 4 hours. After the 4 hours, the LED On D11 will flash ON again for 30 s then turn off for 4 hours again and again as an infinite loop.

I got tired with no result>< what does this even mean? What have you tried so far? Have you written ANY code at all?

state machine triggered by interrputs

In response to your comment on Matej's answer @Ibrahim.M: "I wish I can abbreviate it with only one UNO that able to do the same task by using programming.". You can do this with just one Uno.
I would start by detecting the button presses and debouncing them. This is easy to do using the Bounce2 library. You can use the button presses to start timers which will turn the LEDs On and Off.
EDIT
To make an LED flash on and off, and to keep time, you can use the millis() function. I started with the BlinkWithoutDelay tutorial, and came up with the following sketch. It only has one timer / LED flasher, but there is enough information in the sketch to figure out how to make the second timer / LED flasher.
#include <Bounce2.h>

byte led1State = LOW;
byte timer1Active = 0;
const byte led1Pin = LED_BUILTIN;
const byte buttonPin1 = 6;
const byte buttonPin2 = 7;
unsigned int timer1Counter = 0;
const unsigned long debouncerInterval = 50;
const unsigned long oneSecond = 1000;
unsigned long previousMillis = 0;

Bounce debouncer = Bounce();
Bounce debouncer2 = Bounce();

void setup(){
  Serial.begin(9600);
  debouncer.attach(buttonPin1, INPUT_PULLUP);
  debouncer.interval(debouncerInterval);
  debouncer2.attach(buttonPin2, INPUT_PULLUP);
  debouncer2.interval(debouncerInterval);
  pinMode(led1Pin, OUTPUT);
}

void loop(){

  unsigned long currentMillis = millis();

  // 4 hour, 30 second timer.
  if((currentMillis - previousMillis >= oneSecond) && (timer1Active == 1)){
    previousMillis = currentMillis;
    timer1Counter++;
    if(timer1Counter < 31){
      //if(led1State == LOW){
        led1State = HIGH;
      //}
      //else{
        //led1State = LOW;
      //}
      digitalWrite(led1Pin, led1State);
    }
    else if(timer1Counter == 31){
      digitalWrite(led1Pin, LOW);
    }

    // 60 sec X 60 min X 4 hours + 30 seconds.
    if(timer1Counter > 14430){
      timer1Counter = 0;
    }
  }

  // Button 1
  if(debouncer.update()){
    if(debouncer.read() == 0){
      Serial.println("Start 30 second ON, 4 hour OFF timer.");
      timer1Active = 1;
      timer1Counter = 0;
    }
  }

  // Button 2
  if(debouncer2.update()){
    if(debouncer2.read() == 0){
      Serial.println("Start 1 minute ON, 4 hour OFF timer.");
      timer1Active = 0;
      digitalWrite(led1Pin, LOW);
    }
  }

}

Based on this part of your last comment "I’ve a trick! ‘const unsigned long oneSecond = 1000;’ should be edited to ‘const unsigned long oneSecond = 10;’ this make the led be as a constant ON.", it sounds like you want the LED to remain ON constantly for the 30 or 60 seconds. I have "commented out" 5 lines of the above sketch that will make this happen.

Matej and VE7JRO you are a great persons, thank you so much.

Do not use delay but millis().
Example:
#define BTN 2
#define MAX_MODE 1   //2 modes

const unsigned int times[] = {1000, 2000};

unsigned int time = times[0];

unsigned long btn_tm = 0;
unsigned long l_time = 0;

byte mode = 0;

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

void loop(){
  if(digitalRead(BTN) == 1 && millis() - btn_tm > 200){
    btn_tm = millis();
    mode ++
    if(mode > MAX_MODE) mode = 0;
    time = times[mode];
 }
  if(millis() - l_time >= time){
    l_time = millis();
    if(mode == 0) Serial.println("mode 0");
    if(mode == 1) Serial.println("mode 1");
 }
}

Read it and try it.

Thank you Matej. The code has an error related to this part: ' if(mode > MAX_MODES) mode = 0; ' , kindly, how can I add LEDs as an output for each mode pls?

Is it possible to make the code inside the link take place each case mentioned in my topic code? where then  each case will has its own time [https://www.arduino.cc/en/tutorial/BlinkWithoutDelay]

@Ibrahim.M I fixed this error, it was wrong name of variable. If you want to use code from the link, remove this part from code if(millis() - l_time >= time){ l_time = millis(); if(mode == 0) Serial.println("mode 0"); if(mode == 1) Serial.println("mode 1"); }  and instead of it, put inside if(mode == 0){  } code which is in the loop() from your link.

@Ibrahim.M And for your first comment, simply put pinMode() to the setup() above setup put bool state = 0; and into a if(mode == 0){ }  put digitalWrite(LED, state); state = !state;

Thank you Matej, I appreciate it. Unfortunately, my problem is still not solved. I assume that uno’s IC cannot do what I want ( ex; yellow button activates pin9 1min each 6 hr wherase blue button activate pin10 30 sec each 6hr ).

I’ve just uploaded a picture has a long tail circuit diagram at this link: https://i.sstatic.net/Cg3k0.jpg . I wish I can abbreviate it with only one UNO that able to do the same task by using programming.

@Ibrahim.M Write 3 codes for 3 unos and I will help you to merge these codes.


text:
How to use Honeywell NBP Series Sensor with Arduino
I am trying to use a HONEYWELL NBPDANN100PAUNV Pressure Sensor.
I found an example here http://www.circuitstoday.com/interfacing-pressure-sensor-arduino

As this example says as instrumentation amplifier based on quad op-amp LM324 is used for conditioning the output voltage from the pressure sensor.

int sensor=A0;
int dig_out;
void setup(){
  Serial.begin(9600);
  pinMode(sensor,INPUT);
  pinMode(2, INPUT_PULLUP);
}

void loop(){
  if (digitalRead(2) == LOW) {
      dig_out=analogRead(sensor); // reads the input voltage
    Serial.print("Pressure Sensor "); // prints "Pressure Sensor"
    Serial.print(dig_out);
    Serial.print("\n");
    delay(1000);
  }
}

But when I make this circuit and connect to Arduino it just give output about 5, I give the external air pressure but value not change.
Can any one help me Interfacing this type of sensor to Arduino.


text:
How do I connect Arduino directly to MySQL server using the URL?
I started a project with my Arduino Mega 2560 that gets some values from sensors. I'm using MySQL Connector, https://launchpad.net/mysql-arduino, and this library allows me to connect to a server using the IP address, and it worked on localhost.
This is the code:
/* Setup for all libraries */
#include <SPI.h>
#include <Ethernet.h>
#include <sha1.h>
#include <mysql.h>
#include <OneWire.h>

/* Setup for Ethernet Library */
byte mac_addr[] = { 0x90, 0xA2, 0xDA, 0x0E, 0xB3, 0x05 }; // MAC address must be unique; this is the Ethernet shield address
IPAddress server_addr( 177, 156, 122, 113 ); // Server addr

/* Setup for all others variables */
int DS18S20_Pin = 2; // Temperature sensor
float temperature;
float placasTensao;
float placasCorrente;
float geradorEolicoTensao;
float geradorEolicoCorrente;
float bateriaTensao;
float bateriaTemp;
float correnteSaidaControlador;
float correnteSaidaConsumo;

OneWire ds(DS18S20_Pin);  // On digital pin 2

/* Setup for the Connector/Arduino */
Connector my_conn; // The Connector/Arduino reference

/* Setup for connection and all variables of the database */
char user[] = "";
char password[] = "";
char INSERT_SQL[1000];
char temperature_convt[10], placasTensao_convt[10], placasCorrente_convt[10], geradorEolicoTensao_convt[10],
     geradorEolicoCorrente_convt[10], bateriaTensao_convt[10], bateriaTemp_convt[10], correnteSaidaControlador_convt[10],
     correnteSaidaConsumo_convt[10];

void setup(){
  Ethernet.begin(mac_addr);
  Serial.begin(9600);
  delay(1000);
}

void loop(){
  temperature = getTemp();
  convert(temperature, temperature_convt);
  snprintf(INSERT_SQL, "INSERT INTO data.data VALUES (%s, 1, 1, 1, 1, 1, 1, 1, NULL)", temperature_convt);
  sendData();
  delay(20000);
}

// Convert a float variable to string
void convert(float data, char *value){
  dtostrf(data, 7, 3, value);
}

// Saves all data on database
void sendData(){
  Serial.println("Connecting...");
  if (my_conn.mysql_connect(server_addr, 3306, user, password)){
    delay(500);
    Serial.println("Starting SQL!");
    Serial.println(INSERT_SQL);
    my_conn.cmd_query(INSERT_SQL);
    Serial.println("Query Success!");
    my_conn.disconnect();
    Serial.println("\n");
  } else {
    Serial.println("Connection failed!");
    Serial.println("Make sure all cables are properly connected!\nIf they are, restart the Arduino!\n");
  }
}

// Returns the temperature from one DS18S20 in degree Celsius
float getTemp(){
  byte data[12];
  byte addr[8];
  if (!ds.search(addr)) {
      // No more sensors on chain, reset search
      ds.reset_search();
      return -1000;
  }

  if ( OneWire::crc8( addr, 7) != addr[7]) {
      Serial.println("CRC is not valid!");
      return -1000;
  }

  if ( addr[0] != 0x10 && addr[0] != 0x28) {
      Serial.print("Device is not recognized");
      return -1000;
  }
  ds.reset();
  ds.select(addr);
  ds.write(0x44,1);
  // Start conversion, with parasite power on at the end
  byte present = ds.reset();
  ds.select(addr);
  ds.write(0xBE); // Read Scratchpad
  for (int i = 0; i < 9; i++) { // We need 9 bytes
    data[i] = ds.read();
  }
  ds.reset_search();
  byte MSB = data[1];
  byte LSB = data[0];
  float tempRead = ((MSB << 8) | LSB); // Using two's complement
  float TemperatureSum = tempRead / 16;
  return TemperatureSum;
}

Now, how can I connect to a server using the URL? Is there a library like MySQL Connector that allows me to use the URL instead of the IP address?
All I want is to do exactly the same thing that I'm doing with MySQL Connector, but using the URL of the server instead of the IP address.

The easiest, just git 'er done, way would be to do an nslookup on the domain, get the IP address and just hard code that into your source. It's not the most robust solution, as it's possible for the IP address to change over time. However, it's highly likely the IP address won't change frequently.
> nslookup google.ca
Server:     64.59.144.93
Address:    64.59.144.93#53

Non-authoritative answer:
Name:   google.ca
Address: 216.58.193.67

If you need it to be more robust, you would need the Arduino to perform the dns lookup to resolve the IP address. This looks like it would do the job:
https://github.com/esp8266/Arduino/blob/master/libraries/Ethernet/src/Dns.h

You are using DHCP, so this step might be optional.
Specify your network addresses (actually we want to specify DNS only but have to specify IP in 2nd argument, so likely have to specify gateway and subnet too):
IPAddress dns_addr( 8, 8, 8, 8); // GOOGLE DNS server, could be any DNS
IPAddress gateway_addr( , , , );   // put your gateway addr
IPAddress ip_addr( , , , );   // put your IP addr
IPAddress subnet( , , , );   // put your subnet mask

void setup(){
                  Ethernet.begin(mac_addr, ip_addr, dns_addr, gateway_addr, subnet);...

Now you could modify Connector::mysql_connect method (or create new method) as follows (only function declaration is changed, body is not):
boolean Connector::mysql_connect(/*IPAddress server*/const char *server, int port, char *user, char *password)
{
  int connected = 0;
  int i = -1;

  // Retry up to MAX_CONNECT_ATTEMPTS times 1 second apart.
  do {
    delay(1000);
    connected = client.connect(server, port);
    i++;
  } while (i < MAX_CONNECT_ATTEMPTS && !connected);

  if (connected) {
    read_packet();
    parse_handshake_packet();
    send_authentication_packet(user, password);
    read_packet();
    if (check_ok_packet() != 0) {
      parse_error_packet();
      return false;
    }
    print_message(CONNECTED);
    Serial.println(server_version);
    free(server_version); // don't need it anymore
    return true;
  }
  return false;
}

Modify the header file also:
boolean mysql_connect(/*IPAddress server*/const char *server, int port,
                                 char *user, char *password)

Now you can supply URL:
if (my_conn.mysql_connect("http:\\www.mysqlserver.com", 3306, user, password))...

I did everything. Modified the Connector::mysql_connect method and also the header. But it doesn't work @Flanker. Do you know what could be causing this? When the program call the my_conn.mysql_connect(), it just stop there, without any answer, appear just my message "Connecting...". Thank you for the answer.

Do you have "http://" protocol part in your URL? Please try without it, like "www.domain...". The Ethernet client have same connect function with URL parameter instead IP (and port), the idea is to use it. Also maybe DNS is not working, maybe test the network address configuration with another DNS sample sketch?

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


text:
Error in IR receiver project
I'm trying to receive remote information with an IR receiver and this is my code:
#include <IRremote.h>

int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;

void setup() {
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value
  }
  delay(100);
}

I tried to upload this to Arduino and it says:
exit status 1
redefinition of 'int RECV_PIN'

How can I fix this?

I can see no reason for it unless you didn't install the library properly, or the code you show isn't actually the code you are compiling.

I compiled your code. There is no compilation error. Probably, library problem. Install it properly.

Apparently the name RECV_PIN is used somewhere else, presumably in IRRemote.h -- although not in any version of it I can find.  Anyway, just change the name of RECV_PIN to something which doesn't conflict.
For example:
int MY_RECV_PIN = 11;
IRrecv irrecv(MY_RECV_PIN);

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


text:
Assigning float to 10 decimal place for longitude,latitude
I'm quite a novice in arduino programming. I am doing a small home project and I am using sim808 to obtain GPS data.
My question is quite simple but i can't find any solution online.
Serial.print("latitude :");
Serial.println(sim808.GPSdata.lat, 10);
Serial.print("longitude :");
Serial.println(sim808.GPSdata.lon, 10;

This code display Longitude and Latitude data on serial monitor to 10 decimal place perfectly.
But when after setting the Longitude and Latitude to float.When I use this code, I don't get a valid gps data.
Longitude = (sim808.GPSdata.lon, 10 );
Latitude = (sim808.GPSdata.lat, 10 );

Please help, Thanks.
(edited)
I understand my error in coding for the above.
In fact, I am using a DF robot shield sim 808 for vehicle tracking. I am uploading my GPS data, longitude, latitude and speed to Ubidots. The only difficulty is in saving accurate data.
I am using this codes
Longitude = sim808.GPSdata.lon;
Latitude = sim808.GPSdata.lat;
Speedperkm = sim808.GPSdata.speed_kph;

client.add("Longitude", Longitude);
client.add("Latitude", Latitude);
client.add("Speed per Km", Speedperkm);

The code is working fine but only GPS data of 2 decimal place is being uploaded. If data of up to 6 decimal place is uploaded then the system will more accurate.
That my problem that I am trying to solve.

A float has roughly 7-digit resolution. Printing it with 10 decimal places is ludicrous.

Please add the library (source) for "client.add()". Impossible to guess what you are using. Also you should start a new issue if the original question has been answered even though the issue has evolved. How could others find information if the question changes?

does using double instead of float help?

@dandavis: It might help on an ARM-based Arduino, like the Due. On AVR (most Arduinos), double is the same as float.

But when after setting the Longitude and Latitude to float.When I use
  this code, I don't get a valid gps data.

Some statements in C/C++ are not what they might seem. The value of the statements:
Longitude = (sim808.GPSdata.lon, 10 );
Latitude = (sim808.GPSdata.lat, 10 );

Are actually the same as:
sim808.GPSdata.lon;
Longitude = 10;
sim808.GPSdata.lat;
Latitude = 10;

Which is then optimized to:
Longitude = 10.0;
Latitude = 10.0;

That is, when using list notation, the value of the expression is the same as the value of last expression in the list.
The other answers have covered the fact that float and double on Arduino (AVR-GCC) are only 32-bit, and that gives 6 to 9 significant decimal digits precision.
Cheers!

i get your point completely

You always should calculate with the maximum resolution (not rounding to 10 digits), so use:
Longitude = sim808.GPSdata.lon;
Latitude = sim808.GPSdata.lat;

For printing you can use the code you have.
Serial.print("latitude :");
Serial.println(sim808.GPSdata.lat, 10);
Serial.print("longitude :");
Serial.println(sim808.GPSdata.lon, 10);

Floats are always exact numbers, and 10.0 will always be 10, never 9.9999999999. You get rounding errors only when trying to represent as a float a number that cannot be exactly representable as a float.

@EdgarBonet not according https://technet.microsoft.com/en-us/library/ms187912(v=sql.105).aspx ... I mean a float as type (probably you mean a 'mathematical float' ?

Every float represents a number, in the mathematical sense of the word “number”, i.e. defined with infinite precision. Most numbers are not representable as floats, and can thus only be approximated by floats. Every single integer in the range ±16777216 (and this include the number 10) is an exact float.

@EdgarBonet Yes you are completely right about the integers ... I will update the answer. Thanks.


text:
Turning an LED on when an error occurs, then turn it off after 2 seconds
I am currently working on making some test equipment for µUSB cables. The code is supposed to recoqnise when an error in the cable occurs. Most of it works as expected, but I have some trouble understanding the use of millis() timers.
I, therefore want to ask, in the code below, how can I make my program pick up on an missing connection in the cable and make sure it turns on the LED always? And secondly, how can I make it stay on for 2 seconds, even if the cable has "fixed" itself again (i.e. the connection has returned)?
Update
It seems that I have misunderstood the assignment. The program should turn on a LED, when an error is present and keeps this on while the error is present (already fixed this in the code). When the connection has been regained a timer should start, which turns off the LED after two seconds. (Here's the trouble I'm having, I can't seem to pinpoint where and how this timer should start)
case microUSB:
  if (Vcc_Ext_val > 50)
  {
    digitalWrite(ActivateLoad, HIGH);
    LoadActivated = true;

  }
  else if (Vcc_Ext_val < 30)
  {
    digitalWrite(ActivateLoad, LOW);
    LoadActivated = false;
  }
  if ((Vcc_Ext_val < 50) || (USB_DP_VAL < 10)|| (USB_DM_VAL < 10))
  {
    PulseCurrentMillis = millis();
    if (FirstPulse == true)
    {
    digitalWrite(RedIntLED, StateLEDON);
    FirstPulse = false;
    }
    if (PulseCurrentMillis - PulseLastMillis >= PulseInterval)
    {
      PulseLastMillis = PulseCurrentMillis;
      if (LEDState == StateLEDON)
      {
        LEDState = StateLEDOFF;
      }
      else
      {
        LEDState = StateLEDON;
      }
    }
    digitalWrite(GreenIntLED, StateLEDOFF);
    digitalWrite(RedIntLED, LEDState);
  }
  else
  {
    digitalWrite(GreenIntLED, StateLEDON);
  }
  break;

When you turn on the led, record the time.
After that, turn off the led if

The led is on and
Sufficient time has passed.

edit: this is what I would do.
//detect if sufficient time has passed
//1. turn on the led on button high -> low transition
//2. turn off the led after certain time (LED_DLY)
uint8_t led_ctrl(void) {
    static uint32_t led_timeoff=0;                              //time to turn the led off
    uint32_t time_now = millis();                               //take time now

    //if sufficient delay has passed, turn the led off
    if (isLED_ON() && (time_now >= led_timeoff)) {              //if led is already on
        LED_OFF();                                              //turn off the led
    }

    //if the button has experienced a the falling edge, turn on the led and set up the time to turn the led off
    if (btn_pressed()) {
        LED_ON();                                               //turn on the led
        led_timeoff = time_now + LED_DLY;                       //set up the time to turn off the led
    }

}

it is almost a literal implementation of what I wrote above.
here is the code in action, responding to button's falling edge with a 150ms delay turn off for the led: the button is on D12 and the led on D8.

fairly straight forward, isn't it?

It would seem that this is what I should accomplish, but I have some trouble understanding how to do this.

You have trouble implementing it or understanding it? Potential solutions for the first and no solution for the latter.

I have trouble understanding how to implement this in a way so that the program recognizes that the connection has been reestablished and then turn off the LED after 2s

I have made it work now.
The working code is as following, if anyone else gets the same issue.
case microUSB:
  if ((Vcc_Ext_val > 50) && (USB_DP_VAL > 10) && (USB_DM_VAL > 10) && (digitalRead(RedIntLED) == StateLEDON))
  {
    if (FirstStart == true)
    {
      StartMillis = millis();
      FirstStart = false;
    }
    PulseCurrentMillis = millis();
    if ((PulseCurrentMillis - StartMillis >= PulseInterval) && (digitalRead(RedIntLED) == StateLEDON))
      {
        PulseLastMillis = PulseCurrentMillis;
        digitalWrite(RedIntLED, StateLEDOFF);
      }
  }
  if (Vcc_Ext_val > 50)
  {
    digitalWrite(ActivateLoad, HIGH);
    LoadActivated = true;

  }
  else if (Vcc_Ext_val < 30)
  {
    digitalWrite(ActivateLoad, LOW);
    LoadActivated = false;
  }
   if ((Vcc_Ext_val < 50) || (USB_DP_VAL < 10) || (USB_DM_VAL < 10))
    {
      FirstStart = true;
      digitalWrite(GreenIntLED, StateLEDOFF);
      digitalWrite(RedIntLED, StateLEDON);
    }
    else
    {
      digitalWrite(GreenIntLED, StateLEDON);
    }
  break;

Look at one of the timer libraries such as SimpleTimer. It handles the timing for you and calls a routine you specify at the appropriate time. Your code just has to call its run() function frequently - once in every loop() iteration is typical.
Update:
Either library should work for you; neither should disturb the hardware timers or millis(), which depends on them. Try one of the timer example programs, blinking two leds at different rates for example, and expand or adapt from there.

I initially used the timer.h library, but since I have a timer elsewhere in the code that uses the millis() function (Couldn't find an appropriate function for this in the library), the behavior of the digital pins became quite odd (They started to oscillate at a very low voltage, causing the LED's to blink, when they should be turned off)


text:
SPI or A0/A1: what is the best solution for pin allocation on an Arduino shield?
When you design an Arduino shield you want to make it compatible with a maximum number of shields that may be stacked with it on an Arduino (UNO). Considering the following two possible tradeoffs, which one would you consider the best:

Option A: A shield that uses pins A0 and A1, where no other stacked shield can use those pins.
Option B: A shield that uses SPI, where other stacked shields can only use pins 11, 12 and 13 in SPI mode.

Note: I'm asking this question for a project I'm designing called Omzlo one. It's an Arduino compatible board with builtin CAN bus networking. I'm hesitating between two prototype designs.

Why not support both options with a set of switches (or jumpers) on the shield? The your Arduino library would have an input argument to indicate which option to use.

I would guess that a shield wanting to use SPI is more likely to do so as a slave...

@Edgar Bonet - I incorrectly said "SPI master mode"in the question. Corrected that.

it probably depends on the shield, and what other shields you expect it to combine with.


text:
Can I connect my Arduino Uno to a power source and a battery at the same time?
My aim is to be able to power my Arduino while there is a power supply and if there isn't the Arduino automatically switches over to the battery. The components connected to the Arduino are pir sensor, smoke sensor, SIM 800L, temperature sensor, 6v relay.

Yes, to my knowledge this is done automatically, and there is no harm when connecting the Arduino to two power sources. When I power my Arduino I have it connected to my computer and the wall. So theoretically, if the electricity in the wall stopped coming, it would start taking power from the computer. Same works for battery.

Most mainstream and reputable Arduino variants (the UNO or Pro, for example) have protection circuitry that allows it to basically ignore where its power is coming from, as long as the voltage isn't above 20v. This is because almost every Arduino device funnels its power through an appropriate regulator, ensuring there is no problem with the voltages or available current suddenly changing (switching power feeds). However, you should account for what happens when you plug an external power source in the same loop as a battery that might be a different voltage. If you're going to try to have them manually switch then you'll need an external circuit (perhaps using a transistor that shuts off the battery when the power supply is active, with capacitors for a buffer), else you could have problems with popping batteries. But be warned, if you plug your battery into the PWR (5V/3V3) pin(s) of the Arduino, then you'll need to provide your own protection.


text:
How to get code to respond to a certain time from the DS3231 RTC?
I am trying to make a program that runs when it gets to five in the afternoon, so 17:00:00.
I am using this DS3231 library, but I can't figure out a way to get it to send "Woooopp" to the serial monitor at the specified time.
On the DS3231, the pin labeled SCL is connected to A5 on the Arduino and the pin labeled SDA is connected to A4 on the Arduino.
SCL -> A5
SDA -> A4
My code:
#include <DS3231.h>

// Init the DS3231 using the hardware interface
DS3231  rtc (SDA, SCL);

void setup() {
  // Setup Serial connection
  Serial.begin(115200);
  // Uncomment the next line if you are using an Arduino Leonardo
  //while (!Serial) {}

  // Initialize the rtc object
  rtc.begin();

  // The following lines can be uncommented to set the date and time
  // rtc.setDOW(SATURDAY);     // Set Day-of-Week to SUNDAY
  // rtc.setTime(19, 48, 50);     // Set the time to 12:00:00 (24hr format)
  // rtc.setDate(3, 6, 2017);   // Set the date to January 1st, 2014
}

void loop() {
  // Send Day-of-Week
  Serial.print(rtc.getDOWStr());
  Serial.print(" ");

  // Send date
  Serial.print(rtc.getDateStr());
  Serial.print(" -- ");

  // Send time
  Serial.println(rtc.getTimeStr());

  // Wait one second before repeating :)

  if (rtc.getTimeStr() == "19:58:12") {
    Serial.println("Woooopp");
  }
  delay (1000);
}

No errors are thrown, however, the code simply does not work.
Any help would be greatly appreciated!

Which RTC library do you use ? It seems to be this one: http://www.rinkydinkelectronics.com/library.php?id=73

Yes, I used that one. Sorry I forgot to link it, I will edit the question now.

Try using a shorter delay. All the other stuff also takes time to run, so you are checking slightly less than once per second. So certain seconds will be skipped.

Thanks for your answer, I tried that and it worked along with me also declaring the time in a variable beforehand and then comparing that instead. Have a great day!

When you look at the serial output, is the string you are getting from getTimeStr the same as what you expect?

You could use the DS3231 RTC built-in alarm function(s) to power-on the Arduino Uno.

@Delta_G I managed to find out that the problem lay with not declaring a variable to store the current time. Before, I was directly comparing the output from the function to the desired time. Thank you for your help though!

@MikaelPatel Thank you, I will try to use this as well, to see if it will work more efficiently than the method I found in the end.

How to get code to respond to a certain time from the DS3231 RTC?

the easiest is to set up the alarm in rtc.
alternatively, keep reading the rtc until the desired time has passed. not terribly efficient.


text:
How to flash hex files from a micro SD card to an Arduino Nano using an SD card module?
I want to flash a hex file stored in a micro SD card into an Arduino [Uno/Nano]. So far I can read and write to the SD card using Arduino.
Without modifying the bootloader, is it possible to flash the Arduino using micro SD card module?

Do you have two user accounts? You appear to be suggesting edits from an account that differs from the account that you originally posted your question from. If you contact the moderators, then they can merge the two accounts for you.

I have rejected the edit as it changes the focus of the question. What you asked in your edit was a good question - I highly suggest that you ask it as another question (if it hasn't been asked already).

No. Only the bootloader is allowed to write to the program flash.

can you show us where this is explained?  The boot loader is just a program and so is the sketch.  I do not see why a sketch can not do what the OP asked.  That said, the knowledge to read the SDCard and modify the non-volatile program memory goes way beyond common Arduino programming knowledge.   One would have to be very familiar the the particular micro processor being used.  Even then it would be a challenge.  To put it another way, this task is easily on par with that of creating the Arduino boot loader in the first place.

@st2000 the bootloader has this extra privilege that a regular sketch hasn't.

Yes, but I am not sure it can work from the smaller Arduino models. Have a look at the Phoenard project. The platform, based on a 2560, flashes .hex files on demand, which are stored on the SD card.
It's an open-source project, so it should be possible to go through the code and see how they do it.


text:
Running multiple programs with one Arduino
Is it a problem to use multiple softwares to read the data that came from the same USB port simultaneously?
I have a board connected to a PC by USB, which is read by an application developed in C#. I display the data from the board in a table form.
Now I have to plot the data. The problem is that both the board and the software are deployed and can't be modified. So I have to create another program to do that, but the user should be able to run both softwares simultaneously.
Thank you!

If you are running Linux you can do this in a few lines of shell script; https://stackoverflow.com/questions/38361531/how-to-duplicate-dev-ttyusb0-stream

The question is not so much about Arduino, but about PC serial ports. There are programs/drivers out there that allow a user to "split" a serial port into two or more virtual serial ports, each of which can be opened by separate Windows applications, such as your C# programs.
Some of these programs or drivers are commercial and not free, and some are free.
https://www.fabulatech.com/serial-port-splitter-help/serial-port-splitting.html
http://www.eterlogic.com/help/vspe/UsageSplitPage.html
http://www.aggsoft.com/tcp-com/tcp-com-com-splitting.htm


text:
I need help with code for two 74HC595
I created and learned this code myself from many examples. I tried to add another chip to it, but I have no idea. Do I need to rewrite all of it? Just some simple code is needed.
int latchPin = 2;
int dataPin = 3;
int clockPin = 4;
const int analogPin = A0;
const int ledPin = 13;
const int EmptyEn = 0;
const int GreenOne = 100;
const int GreenTwo = 200;
const int GreenThree = 300;
const int GreenFour = 400;
const int YellowOne = 500;
const int YellowTwo = 600;
const int RedOne = 750;
const int RedTwo = 900;
const int MaxHold = 1000;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
}

void loop() {
  int analogValue = analogRead(analogPin);
  if (analogValue > GreenOne) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B00000000);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }
  if (analogValue > GreenOne) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B10000000);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }
  if (analogValue > GreenTwo) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B11000000);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }
  if (analogValue > GreenThree) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B11100000);
    digitalWrite(latchPin, LOW);
    delay(1);
  }
  if (analogValue > GreenFour) {
    digitalWrite(latchPin, HIGH);
    shiftOut(dataPin, clockPin, MSBFIRST, B11110000);
    digitalWrite(latchPin, LOW);
    delay(1);
  }
  if (analogValue > YellowOne) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B11111000);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }
  if (analogValue > YellowTwo) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B11111100);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }
  if (analogValue > RedOne) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B11111110);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }
  if (analogValue > RedTwo) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B11111111);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }
  if (analogValue > MaxHold) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B00000000);
    digitalWrite(latchPin, HIGH);
    delay(100);
  }
  Serial.println(analogValue);
  delay(1);
}

Can you give more guidance, such as stating what is wrong, posting any compile errors, and then asking a specific question?

Look for a repetition in your code.
  //Repeating code..
  if (analogValue > GreenOne) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B00000000 );
    digitalWrite(latchPin, HIGH);
    delay(1);
  }

  if (analogValue > GreenTwo) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B10000000 );
    digitalWrite(latchPin, HIGH);
    delay(1);
  }

You will notice that you have a lot of repetition of the general structure of a if-comparison (always with a different value) and then a shiftOut with a different value to be shifted out.
  //General code structure
  //Only things to change is someComparisonValue and someDataValue
  //the rest is the same.
  if (analogValue > someComparisonValue) {
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, someDataValue);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }

You can generalize and simplify the code by storing those different comparison values and data values in a look-up table (LUT). Now you could use two arrays to hold these values but you could also further condense it in a C struct, a "data structure".
Let's define a data structure which holds a threshold value and then the data to be shifted out as  struct.
/* Defines a LUT entry */
struct LutEntry {
    int treshhold;  /* threshhold value */
    byte data;      /* data to be shifted out */
};

We can then pack the actual data into a single variable. Because this is constant data, it will take up flash memory instead of RAM.
static const LutEntry lutTable[] = {
    { GreenOne, B00000000},
    { GreenOne, B10000000},
    { GreenTwo, B11000000},
    { GreenThree, B11100000},
    { GreenFour, B11110000},
    { YellowOne, B11111000},
    { YellowTwo, B11111100},
    { RedOne, B11111110},
    { RedTwo, B11111111},
    { MaxHold, B00000000}
};

From there we can also see that there is a computable relationship between the index of the treshhold value and the data to be shifted out - an entry at index i will be associated with the data bitstring in which all bits from the MSB up to i inclusive are 1, the rest being 0. Except for MaxHold as special value. We could exploit this property to get rid of that data member entirely, but that is an exercise left to you.
Now we can re-write the loop code by simply taking a analogRead sample and then iterating through the entires of the LUT to shift out the corresponding data.
void loop() {
    int analogValue = analogRead(analogPin);
    int numLutEntries = (int)(sizeof(lutTable) / sizeof(lutTable[0]));

    for(int i=0; i < numLutEntries; i++) {
        if (analogValue > lutTable[i].treshhold) {
            digitalWrite(latchPin, LOW);
            shiftOut(dataPin, clockPin, MSBFIRST, lutTable[i].data);
            digitalWrite(latchPin, HIGH);
            delay(1);
        }
    }
    Serial.println(analogValue);
    delay(1);
}

Which transforms 69 lines of repeating code into 12 lines of non-repeating code.
After this general code cleanup it becomes easier to add another shift register: You can define a new look up table, or modify the structure of the old one, to hold the information you need (treshholds, data to be shifted out, the clock, data and latch pin for the register, ...). What logic needs to be there is something only you know, because the description "add another chip [to this code]" is quite broad.
In short:

DRY: Don't repeat yourself. If you use a piece of code over and over again with only slight variances in used values, make it a function
recognize the differences of the used data values in used code pieces and try to group them neatly together. Use the language feature of structs or class to express the meaning of this data
exploit certain properties / relationships of your data to save even more memory / computing time.


text:
Turn infrared LED on and off in order to simulate an infrared signal
Note I am able to send and recieve IR signals. This question is only for purposes of learning.
When using the existing library #include <IRremote.h> it is very simple to read and transmit infrared signals. However I will like to send the signals myself with digitalWrite(pin, HIGH);
1) Receive an infrared signal from a remote control in order to clone it and send it later with Arduino.
For this to work I have purchased an infrared LED.
I connect the left leg of the IR LED to pin 11, the middle leg to the ground and the right leg to 5 volts.
Then I upload the following sketch to arduino:

#include <IRremote.h>

int receiverpin = 11; // left leg of IR receiver is connected to this pin

IRrecv irrecv(receiverpin);
decode_results results;

void setup() {
  pinMode(receiverpin, INPUT);
  Serial.begin(9600);
  irrecv.enableIRIn();
}

void loop() {
  if (irrecv.decode(&results))
  {
    Serial.println(results.value, HEX);
    irrecv.resume();
    delay(150);
  }
}

When I run that and press the power button of my samsung remote control this is what I capture through serial:
Encoding  : SAMSUNG
Code      : E0E040BF (32 bits)
Timing[67]:
 +4500, -4500     + 550, -1650     + 550, -1700     + 550, -1700
 + 550, - 600     + 500, - 550     + 550, - 550     + 550, - 600
 + 550, - 550     + 550, -1700     + 550, -1650     + 550, -1700
 + 550, - 550     + 550, - 550     + 550, - 600     + 550, - 550
 + 550, - 550     + 550, - 600     + 550, -1650     + 550, - 600
 + 550, - 550     + 550, - 550     + 550, - 550     + 550, - 600
 + 550, - 550     + 550, -1700     + 550, - 550     + 550, -1700
 + 500, -1700     + 550, -1700     + 550, -1650     + 550, -1750
 + 500, -1650     + 550
unsigned int  rawData[67] = {4500,4500, 550,1650, 550,1700, 550,1700, 550,600, 500,550, 550,550, 550,600, 550,550, 550,1700, 550,1650, 550,1700, 550,550, 550,550, 550,600, 550,550, 550,550, 550,600, 550,1650, 550,600, 550,550, 550,550, 550,550, 550,600, 550,550, 550,1700, 550,550, 550,1700, 500,1700, 550,1700, 550,1650, 550,1750, 500,1650, 550};  // SAMSUNG E0E040BF
unsigned int  data = 0xE0E040BF;

What is this supposed to mean. How can I conver this to 0s and 1s?
2) Sending cloned signal from arduino.
Now if I want to power on my TV with arduino I will need a Infrared LED. I will connect pin 3 to the long leg of my LED and ground to the short leg. Once I pefrom that connection I will run this sketch:
#include <IRremote.h>

IRsend irsend;

void setup() {}

void loop() {

  irsend.sendSAMSUNG(0xE0E040BF, 32); //Power Code
  delay(1000); // try again in 1 second

}

Note this code works and my TV powers on with my Arduino!
3) Now my question
It was very simple to read and transmit infrared signals using IRremote.h header.The only thing I had to do was capture 0xE0E040BF that I got when reading the infrared signal and use that hex code on part 2. From reading on the internet I have researched that sending an IR signal is just turning and IR LED on and off very fast (38khz). How can I tranlate what I read:
 rawData[67] = {4500,4500, 550,1650, 550,1700, 550,1700, 550,600, 500,550, 550,550, 550,600, 550,550, 550,1700, 550,1650, 550,1700, 550,550, 550,550, 550,600, 550,550, 550,550, 550,600, 550,1650, 550,600, 550,550, 550,550, 550,550, 550,600, 550,550, 550,1700, 550,550, 550,1700, 500,1700, 550,1700, 550,1650, 550,1750, 500,1650, 550};

To 0s and 1s and then send that hard coded for puposes of learning.
Acording to this link: http://www.remotecentral.com/cgi-bin/codes/samsung/tv_functions/
The infrared code to power on a samsung tv is:
0000 006d 0022 0003 00a9 00a8 0015 003f 0015 003f 0015 003f 0015 0015 0015
0015 0015 0015 0015 0015 0015 0015 0015 003f 0015 003f 0015 003f 0015 0015
0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 003f 0015 0015 0015
0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0040 0015 0015 0015 003f
0015 003f 0015 003f 0015 003f 0015 003f 0015 003f 0015 0702 00a9 00a8 0015
0015 0015 0e6e

I have converted that to binary and it comes to be:
000000000000000000000000011011010000000000100010000000000000001100000000101010010000000010101000000000000001010100000000001111110000000000010101000000000011111100000000000101010000000000111111000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000111111000000000001010100000000001111110000000000010101000000000011111100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000111111000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000010000000000000000010101000000000001010100000000000101010000000000111111000000000001010100000000001111110000000000010101000000000011111100000000000101010000000000111111000000000001010100000000001111110000000000010101000000000011111100000000000101010000011100000010000000001010100100000000101010000000000000010101000000000001010100000000000101010000111001101110

Now every time I see a 0 I will power off the LED and every time I see a 1 I will power on the LED waiting about 10 microseconds in order to have a frequency of 38khz This is how my sketch looks like:
int pinSend=3;
char data[1248] = "000000000000000000000000011011010000000000100010000000000000001100000000101010010000000010101000000000000001010100000000001111110000000000010101000000000011111100000000000101010000000000111111000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000111111000000000001010100000000001111110000000000010101000000000011111100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000111111000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000010000000000000000010101000000000001010100000000000101010000000000111111000000000001010100000000001111110000000000010101000000000011111100000000000101010000000000111111000000000001010100000000001111110000000000010101000000000011111100000000000101010000011100000010000000001010100100000000101010000000000000010101000000000001010100000000000101010000111001101110";
int waitTimeInMicroseconds = 5; // counter to try with different wait times in order to see what frequency works best

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

void loop() {

  Serial.print("Starting sending IR signal waiting ");
  Serial.print(waitTimeInMicroseconds);
  Serial.println(" microseconds");

  int len = sizeof(data);

  for(int i=0; i<len; i++)
  {
    if( data[i] == '0') // if 0 turn off LED
    {
      digitalWrite(pinSend,LOW);
    }
    else // else turn ON LED
    {
      digitalWrite(pinSend,HIGH);
    }

    delayMicroseconds(waitTimeInMicroseconds); // wait in microseconds
  }

  Serial.println("Done! Is TV on??????");
  delay(1000); // wait 1 second for next atempt

  waitTimeInMicroseconds++; // next time try with different wait time

}

When I run that code the TV does not turn on why? How can I hard code the 0s and 1s for purposes of learning?

Honestly, I almost always go to the web to find the exact codes for the different remote controls and devices I have.  Getting an approximate code is fine.  But if it is at the edge of being correct - who knows - maybe that will create times when the Ardunio appears not to work as well as the original remote control.

The embedded delay in your code waits 150ms each iteration.  But you are also executing code which takes its own time.  The error will accumulate as time goes on.  Causing any attempt at recreating the signal to be more off the longer the signal is.  It would be better to execute the sampling based on a hardware timer interrupt.

The receiver is more than just a photo diode.  The receiver demodulates the 38KHz signal.  To recreate the signal you need to turn the IR LED on and off at 38KHz and turn that signal on and off using the pattern you recorded at the output of the receiver.

To recreate the 38KHz signal, you would have to complete a loop of your code ever 13.158us.  That needs to include the time it takes to execute the code.  Likely the real driver does not bother with this.  Instead, code can configure the PWM hardware to generate a continuous 38KHz.  Then the code would only be tasked with modulating the 38KHz code.

Glad I came across your post.Hoe you can help me out:
how the hex data (0xE0E040BF) corresponds to the rawData? Is the raw data time of high and low? or rather difference?
Do you have a way to convert the hex to rawData ?
Thanks

@Pixelowsky, do not ask questions in comments. You wIll not get answers. Ask a new question instead.

Finally managed to figure it out without using any library. This is how I turn on my TV:
int pinSend=3;
int waitTimeInMicroseconds = 33; // counter to try with different wait times in order to see what frequency works best
unsigned int  rawData[67] = {4500,4500, 550,1650, 550,1700, 550,1700, 550,600, 500,550, 550,550, 550,600, 550,550, 550,1700, 550,1650, 550,1700, 550,550, 550,550, 550,600, 550,550, 550,550, 550,600, 550,1650, 550,600, 550,550, 550,550, 550,550, 550,600, 550,550, 550,1700, 550,550, 550,1700, 500,1700, 550,1700, 550,1650, 550,1750, 500,1650, 550};

int isOn =1;

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

void loop() {

    Serial.print("starting with ");
    Serial.println(waitTimeInMicroseconds);

    for(int jj=0; jj<16; jj++)
    {
    for(int i=0; i<67; i++)
    {
        if(isOn==0)    {
          isOn=1;

          int x=0;

          while(true)
          {
            digitalWrite(pinSend,HIGH);
            delayMicroseconds(waitTimeInMicroseconds); // wait in microseconds
            digitalWrite(pinSend,LOW);
            delayMicroseconds(waitTimeInMicroseconds); // wait in microseconds

            x=x+waitTimeInMicroseconds+waitTimeInMicroseconds;

            if(x > rawData[i])
            {
              break;
            }
          }

        }
        else{
          isOn=0;
          delayMicroseconds(rawData[i]);
        }

    }
    }

    delay(2500);
    //waitTimeInMicroseconds++;

}


text:
Arduino ultrasonic sensor project
I'm a newbie at Arduino, and I'm trying to make a project with ultrasonic sensor, I'm using the grove ultrasonic ranger, not the HC-SR04, and I already did test with distance and it worked very well, but now I need help with the code.
I need to create a vector that save the values of the distance to after calculate the speed using distance/time calculus, but the case of my project its to use in open places, so will be times that the distance will be "max" because there's nobody in the range, so I need a condition to exclude those values of the array (the maximum distance printed when the sensor can't feel nothing is 516 cm)
I'm not experienced with Arduino coding, so please help me, in anex is my code for basic scanning.
#include "Ultrasonic.h"

Ultrasonic ultrasonic(7);
void setup()
{
    Serial.begin(9600);
}
void loop()
{
    long RangeInCentimeters;
    Serial.println("The distance to obstacles in front is: ");

    // two measurements should keep an interval
    RangeInCentimeters = ultrasonic.MeasureInCentimeters();
    if(RangeInCentimeters > 400)
    Serial.print ("distancia nula");
    else
    Serial.print(RangeInCentimeters);//0~400cm
    Serial.println(" cm");
    delay(1000);
}

the question is how can i do this, create a vector that save the distances above 400cm and exclude the rest

Do you need the distance up to 400 cm and ignore the rest, or over 400cm and ignore all values below 400cm?

If you don't know how many data points will be recorded, look into vectors or an external storage device. Alternatively you could use a circular array if you don't mind losing recorded data after a while.
If you know how many data points will be recorded, a basic array will suffice.
As for excluding invalid values:
// Keep trying to get a valid data point
While (RangeInCentimeters > 512 && RangeInCentimeters < 400)
{
 delay(200);  // The minimum value of this delay depends on the sample rate of your sensor
 RangeInCentimeters = ultrasonic.MeasureInCentimeters();
}

//... Store data to array/linked list/etc

I changed your max range to 512 because this is likely the max real value (2^9 = 512).

while?.......

why not let the loop() loop?

its for track athletes, so i did a calculus, and it will print around 10 moves every lap, my think about the memory trouble its to every lap the array placing the values, them calculating the speed and putting in another array, then reset the array, so with 2 arrays, 1 for speed and 1 for data, reseting the data array will not solute the memory trouble?

Having the while loop would let you reduce the delay value inside and pick up the next valid measurement as soon as possible, instead of waiting the full 1000ms. Other than than it's not needed.

@rokazz For only 10 data points just use an array. However I would suggest changing your delay value because in 10 seconds (the time it takes to make 10 measurements) the runner will have gone much farther than 512cm

yes, the delay time will be 100 or 200, it depends from the results of precision

i was thinking in another solution, initially i was thinking about  the sensor pointing in to the athlete running in the straight line of the field and with the data calculate the speed, but i also can make it stand by all the lap, when the runner pass it starts a time and when pass again stop and make a calculus of the distance of the field and time, giving the speed, what do you guys think about it?

@rokazz That would work as well, but if they manage to pass through the detecting range of the sensor in less than 100/200ms it won't detect them. Look at the data sheet and determine the sample rate to figure out how low you can get that delay value. The lower it is the less likely you are to miss them.