text:
Arduino 10bit ADC is not accurate?
I'm reading the voltage with voltage divider:

simulate this circuit – Schematic created using CircuitLab
 | Arduino is connected to both USB and a 9V adapter.
float r1 = 100000;
float r2 = 9980;
float adc, voltage, analog;
void setup() {
  Serial.begin(9600);
  analogReference(EXTERNAL);
  pinMode(A0, INPUT);
}

void loop() {
  for (int i = 0; i < 256; ++i) {
    analog += analogRead(A0);
  }
  analog = analog / 256;
  adc = analog * 1.228 / 1023;
  voltage = adc / (r2 / (r1 + r2));
  Serial.print(analogRead(A0));
  Serial.print(", ");
  Serial.print(analog);
  Serial.print(", ");
  Serial.print(adc);
  Serial.print(", ");
  Serial.print(voltage);
  Serial.println(" ");
  delay(100);
}

Here's the accuracy test result:
Input | Arduino | Difference
 1V      0.89V     -110mV
 2V      1.90V     -100mV
 3V      2.92V     -80mV
 4V      3.93V     -70mV
 5V      4.95V     -50mV
 6V      5.97V     -30mV
 7V      6.98V     -20mV
 8V      8.00      0
 9V      9.01      +10mV
 10V     10.02     +20mV
 11V     11.04     +40mV
 12V     12.06     +60mV

The input voltages measured by DMM and was spot on voltage, like 1.000V.
I didn't test voltages above 12V but it seems the difference is gonna increase by 20mV with each 1V increase, that means at 50V voltage reading is gonna be off by ~1V!
Even with 10bit resolution of Arduino I should have had steady accuracy with some percentage of difference(right?), but as you can see the result shows that the reading is not steady at all!
Why the voltage difference decrease/increase when voltage changes at the input?

As stated by Majenko, the ADC can in principle have all sorts of
errors. However, if you look at your data, you should notice that the
error is essentially linear with the voltage. This means that the
non-linearity error is quite small, and you are mainly seeing the offset
and gain errors. This is fortunate, because these errors are easy to
remove, given good calibration data.
The table you wrote in in your question happens to be a perfectly good
calibration table. By fitting a straight line to it you can get a
calibration function, and then correct the readings simply by adding
this to your code:
voltage = 0.9848815 * voltage + 0.125354;

Or you could instead figure out the correction at the ADC level and
replace
adc = analog * 1.228 / 1023;

by
adc = (analog + offset) / scale;

where offset and scale are computed from the calibration.

Edit: Here is how I extracted the calibration coefficients from the
data.
First, I saved the data in a text file calibration.tsv and cleaned it up
to remove the units and add a comment marker (#) in front of the column
labels:
#Input | Arduino | Difference
 1      0.89     -110e-3
 2      1.90     -100e-3
...

Then I looked at the data with gnuplot. Since I want to know how to
correct the readings, I plot the amount I have to add (minus column 3)
v.s. the Arduino reading (column 2):
plot 'calibration.tsv' using 2:(-$3)

At this point it appears it's linear with what looks like mostly
quantization noise. I model this as a line of equation a*x+b, and
compare the line with the data:
a = -1e-2
b = 0.12
plot 'calibration.tsv' using 2:(-$3), a*x+b

The line is quite off the data, but it's a reasonable first
approximation. Now I ask gnuplot to perform a least squares fit, then
take another look:
fit a*x+b 'calibration.tsv' using 2:(-$3) via a, b
replot

Now the fit looks quite good. When it completed the fit, gnuplot
displayed:
Final set of parameters            Asymptotic Standard Error
=======================            ==========================
a               = -0.0151185       +/- 0.0002953    (1.953%)
b               = 0.125354         +/- 0.002173     (1.734%)

so now I know I can correct the data with:
voltage += -0.0151185 * volatage + 0.125354;

which is equivalent to what I wrote above.

How do you calculate the offset and scale?

@newbie, put the data in Excel/Calc, draw a chart with expected values and function  and then change the offset and scale values for the function until the lines in the chart match

@Juraj Like This?

The voltage = 0.9848815 * voltage + 0.125354; code almost calibrated the reading with ~ -60mV steady difference (it can't measure below 130mV though), where did you get those values? can you please explain more with math included?

@newbie: I am an old timer who likes text-mode programs rather than Excel, Calc and such, so I used gnuplot. See expanded answer.

@newbie, column B should have a function in cells. and the function should use two other cells with the coefficients you want to fine-tune

@Juraj I've never used excel before and have no idea how to do what you want me do to...

@newbie, example https://github.com/jandrassy/Regulator/tree/master/util/Calc

Yes, you are right that the Arduino ADC is not accurate.  If you read the datasheet (ATMega328P section 28.9, ADC Characteristics) you can see a lot of "error" and "non-linearity" characteristics.
These all add up to inaccuracies in your readings.  For example the "Offset error" at your VREF could be as much as ±4.4mV, and the "Gain error" the same. Non-linearity can be as bad as 2mV, etc.
The Arduino ADC is not meant to be accurate. It's meant to be simple and cheap to implement. (It is a "Successive Approximation ADC" - approximation here is the keyword...) If you want a higher accuracy then there are more suitable ADC chips available that give that accuracy.

I was expecting 100mV error to be steady like 1.100V, 2.100V ... Wasted so much time calibrating this ...! beside using external ADC do you think it's good idea to switch to a PIC micro-controller with 12bit ADC. i'm asking this because PIC is cheaper.

I would always say use a PIC over an ATMega, but then I am a PIC junkie- however increased resolution does not equate to increased accuracy. It's still an SAR with the inherent inaccuracies which that gives you. Since the inaccuracy looks to be pretty linear you can use calibration and calculations to remove it. You have a straight line, the formula for which (if you remember school maths classes) is y = mx + c

Re “successive approximation ADC”: any measurement whatsoever is always an approximation. The keyword here is “successive”: it means the ADC works by iteratively refining the approximation.

@EdgarBonet And because the sampled voltage is stored in a tiny capacitor, and it's impossible to read a voltage without drawing some current, each successive comparison will affect the voltage across that capacitor making it less accurate with each bit that is approximated. So it's successively worse approximation. It's a successive approximation that can only ever be approximate.


text:
How to NOT repeat a piece of code again and again?
I have a VERY long code:

Sketch uses 30468 bytes (92%) of program storage space. Maximum is
  32768 bytes.

I've been trying to reduce it's size so i can write more code, one of my main part of code which repeated many times in switch cases or in if statements is related to de-bouncing the buttons.
Here's a piece of my code as an example:
  case 12:
    if ((millis() - millistimer) > BounceD) {
      if (receivedValue == RFb) {
        magnetDistance += 5;
        millistimer = millis();
        receivedValue = 0;
      }
    }
    if ((millis() - millistimer) > BounceD) {
      if (receivedValue == RFd) {
        magnetDistance -= 5;
        millistimer = millis();
        receivedValue = 0;
      }
    }
    break;

The de-bouncing actions happens in each and every case and for each and every button.
There's two buttons which in each case increase/decrease different values.
How to avoid repeating the de-bouncing action for every button?

EDIT:
The recievedValue is updated via RC buttons value once any button is pressed on the remote.

I don't think this is due to long code. You most likely use constructs that are known to have a large footprint like string. Please provide the FULL code to be able to judge the root cause of your high space usage.

Have you heard of functions? That is a cool construct to write a code block once and use it multiple times again.

@Kwasmich i actually have several Strings, i can't just remove them! what do i do with them?

@chrisl so a function for de-bouncing? how do i call it for every button?

Replace C++ ´string´ with C style strings which are arrays of char - char[] and use the corresponding methods for string manipulation.

@Kwasmich can you please provide a link to an article (tutorial) for further reading?

https://majenko.co.uk/blog/evils-arduino-strings

@Juraj Thank you.

http://www.cplusplus.com/doc/tutorial/functions/

There are even libraries for debouncing, like the Bounce 2 library

Could you post all the code, or at least some more? As the code doesn't even do a digitalRead, to read the buttons state. Secondly, the second if statement will never evaluate to true, so can be entirely removed.

@Gerben all cases look like the same as i posted, i just removed the lcd.print() part etc...

@Kwasmich i did changed all strings to char but that only reduced the size by 3%

@chrisl i can't use Bounce 2 library because the buttons are remote RF buttons, i'm using RC-Switch library.

If you don't use physical buttons, why do you want to debounce? Bouncing is a property of physical buttons

@chrisl because the remote that i have sends continuous value to the receiver! and when a value is received it'll do the math and change the receivedValue to zero and cycle continues...

In the short example of above, first find out what is a duplicate (the two outer if statements including their body), than the differences:

Rfb versus Rfd
+5 versus -5

Than make a function for the duplicated code, and turn all differences into a parameter (I don't know the type of Rfd, so I take an int for it).
You will get:
case 12:
  processButton(&Rfb,  5); // Offset magnet distance by +5
  processButton(&RFd, -5); // Offset magnet distance by -5
  break;

  ...

void processButton(int* rf, int diff)
{
  if ((millis() - millistimer) > BounceD) {
    if (receivedValue == *rf) {
      magnetDistance += diff;
      millistimer = millis();
      *rf = 0;
    }
  }
}

Note that if magnetDistance and millistimer are local variables you also have to pass them (as pointer to change the value), if they are globals you can keep the code as is above.
UPDATE
The way parameter works is as follows. E.g.
processButton(Rfb,  5);

Will call the following function:
void processButton(int rf, int diff)

Where value rf will be Rfb, and diff will be 5 (+5).
Thus when magnetDistance += diff; is executed, diff will be +5 and magnetDistance will be increased with +5. In the next call, magnetDistance will be -5 and thus will be subtracted.
UPDATE 2
To change a variable, you have to pass it as pointer, otherwise the (copied) parameter value will be changed and not return its value to the called function. So you have to give the parameter as an address (& operator), and use -> instead of . to get to the value.

can you please comment that code? does it just increase the value of magnetDistance or decrease it too? because RFb and RFd are two different buttons.

Instead of commenting code (which is more or less trivial), I added an explanation how parameters work, I guess that is the information what you miss. It increases or decreases the value, depending on the value passed to the function (first time +5, second time -5).

thanks but what if we press RFb three times? it will just do +5 and -5 three times instead of just do +5 three times.

I'm not sure what you mean ... my code should do exactly like your code but removing the duplicated code parts (which are changed into a function with parameters)... I suggest you add some Serial.prints's, to see what values are passed, so you can see it for yourself.

since it's a remote RC button the receivedValue should be updated with the value it receives via pressing the button on the remote, in your code it seems the receivedValue is not getting any value from the remote and just doing the math part...

receivedValue is only used for a comparison, it is not updated in your code.

Right, sorry my bad, i'll update the question right now.

You only reset receivedValue to zero, so you can do this inside the function as well

@newbie I changed my answer to accommodate for the zero assignment statement (see chrisl's comment too above).

@newbie I will.

source: Stack Exchange

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

sort: votes


text:
Is this the right way to blink a character on LCD?
The code is this:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);

unsigned long blinkTime = 0;
int ValueA = 22;
String placeHolder = "  ";

void setup() {
  lcd.begin();
}

void loop() {
  lcd.setCursor(7, 0);
  if (millis() - blinkTime > 2000) {
    lcd.print(ValueA);
    blinkTime = millis();
  }
  if (millis() - blinkTime > 1000) {
    lcd.print(placeHolder);
  }
}

The I2C LCD library have a lcd.blink() function but it seems that only blinks a "cursor".
The problem with above code is the placeHolder, what if ValueA gets bigger than 2 digits?
Is there a better way to blink a value on LCD?

tip: lcd.setCursor(7, 0); is in both if blocks ... use it before the first if instead

@jsotola Done, thanks.

write a function that accepts three parameters ... boolean show, byte position and int value .... value is the data to display ... position is location of displayed data ... show if true, display data, if false, display spaces ..... show is set by a timer function at the beginning of loop()

@jsotola I've never wrote a function before, can you please post an example of what you just described?

google arduino functions ... https://www.arduino.cc/en/Reference/FunctionDeclaration

The LCD module has this feature built in. There is no need to implement yourself. Call lcd.blink(); and the current cursor position will blink.

it's blinking the cursor, i want to blink the character...!

Instead of redrawing you could periodically turn the display on and off.

@MikaelPatel turning the display on off? what do you mean?

You could use the back-light control instead of rewriting the display to create the illusion of blinking the text (all).

@MikaelPatel but that will blink the whole screen not a 2 or 3 digit character, right? plus i want to keep the backlight ON...

To blink a number (alternate between the number and empty space(s)), you could try the BlinkLCD class in this sketch. It only works with numbers from 0 to 4294967295 or text (char array, 16 characters max). It does not work with floating point numbers.
// 4540 bytes.
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);

class BlinkLCD{

  private:

    byte m_blinkState, m_startPosition, m_dataLength;
    unsigned long m_dataToBlink, m_previousMillis, m_blinkRate;
    char m_text[16 + 1];

  public:

    BlinkLCD(): m_blinkState(0), m_startPosition(0), m_dataLength(0),
                m_dataToBlink(0), m_previousMillis(0), m_blinkRate(500),
                m_text(){}

    void Update(){

      unsigned long m_currentMillis = millis();

      if(m_currentMillis - m_previousMillis >= m_blinkRate){

        byte m_row = 0;
        m_blinkState = !m_blinkState;
        m_previousMillis = m_currentMillis;

        if(m_startPosition > 15){
          m_startPosition -= 16;
          m_row = 1;
        }

        lcd.setCursor(m_startPosition, m_row);

        if(m_blinkState){
          if((unsigned)strlen(m_text) > 0){
            lcd.print(m_text);
          }
          else{
            lcd.print(m_dataToBlink);
          }
        }
        else{
          for(byte i = 0; i < m_dataLength; i++){
            lcd.print(" ");
          }
        }
      }
    }

    void SetBlinkRate(unsigned long blinkRate){
      m_blinkRate = blinkRate;
    }

    void SetNumber(unsigned long dataToBlink){
      m_dataToBlink = dataToBlink;
    }

    void SetLength(byte dataLength){
      m_dataLength = dataLength;
    }

    // LCD top row, columns 0 - 15
    // LCD Bottom row, 16 - 31
    void SetStartPosition(byte startPosition){
      m_startPosition = startPosition;
    }

    void SetText(char text[]){
      strcpy(m_text, text);
    }

};

BlinkLCD TopRowLCD;
BlinkLCD BottomRowLCD;
BlinkLCD BottomRowLCDtext;

void setup(){
  lcd.init();
  lcd.backlight();
  lcd.clear();
  lcd.print("Temperature 35 C");
  lcd.setCursor(0, 1);
  lcd.print("Num = 4294967295");
}

void loop(){

  // Simulate sensor data.
  static byte counter = 35;
  static unsigned long previousMillis = 0;
  unsigned long currentMillis = millis();

  // Update the temperature reading every 2 seconds.
  if(currentMillis - previousMillis >= 2000){
    previousMillis = currentMillis;
    counter++;
    if(counter > 45){counter = 35;}
    lcd.setCursor(12, 0);
    lcd.print(counter);
  }

  // Blink the temperature reading if it's over 40 C.
  if(counter > 40){
    TopRowLCD.SetNumber(counter);
    TopRowLCD.SetStartPosition(12);
    TopRowLCD.SetLength(2);
    TopRowLCD.SetBlinkRate(250);
    TopRowLCD.Update();
  }

  // Blink a number on the second row of the LCD
  // with a default blink rate of 500ms ON, 500ms OFF.
  BottomRowLCD.SetNumber(4294967295);
  BottomRowLCD.SetStartPosition(22);
  BottomRowLCD.SetLength(10);
  BottomRowLCD.Update();

  // Blink some text with at the default blink rate.
  BottomRowLCDtext.SetText("Num");
  BottomRowLCDtext.SetStartPosition(16);
  BottomRowLCDtext.SetLength(3);
  BottomRowLCDtext.Update();

}

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


text:
PWM delay without blocking the code
I want my LED to turn on gradually without using the delay() function and blocking the code.
Here's the code i came up with:
int led_pin = 6;
unsigned long millisTimer = 0;
int PWMdelay = 5000;
int condition = 0;
int i = 0;
void setup() {
    pinMode(led_pin, OUTPUT);
}
void loop() {
    if(condition == 1){
    if ((millis() - millisTimer) > PWMdelay){
        if(i<255){
            i++;
            millisTimer = millis();
        }

    }
        analogWrite(led_pin, i);
    }
}

Is this the "right way" of slowing the PMW duration from 0 to 255 or there are alternative/better/easier ways?

Seems ok for fade in timer. Why are you doing the else with i--? Do you want to fade out the LED after the fade in? That does not work this way, since it will only vary between 254 and 255.

the Fade example in IDE uses delay, but shows how to go up and then down. and put millisTimer = millis(); outside if-else

@chrisl newbie mistakes... thanks for mentioning it.

From my personal definition, the "right way" is a way that works. So, does it work? Your approach is a common way to do tasks without delay (like in the BlinkWithoutDelay example)

@SimSon i'm new to this and i don't know how others write code in "standard way", thought asking may open new doors to learn new things.

see the Fade example and the BlinkWithoutDelay example in IDE Examples menu

@Juraj okay thanks.

That's fine, I do it the same way

all code inside if(condition == 1){ block, except the analogWrite(), should be indented one more level

Here is my take at this - I've followed the example code mentioned by other members and here is "FadeWithoutDelay"

const int ledPin = 11;
unsigned long previousMillis = 0;        // will store last time LED was updated
const long interval = 100;               // fade interval (milliseconds)
int brightness = 0;                      // how bright the LED is
int fadeAmount = 5;                      // how many points to fade the LED by

void setup()
{
  pinMode(ledPin, OUTPUT);  // set the digital pin as output:
}
void loop()
{
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval)
  {
    previousMillis = currentMillis;         // save the last state
    analogWrite(ledPin, brightness);        // Set the brightness
    brightness = brightness + fadeAmount;   // change the brightness for next time through the loop
    // reverse the direction of the fading at the ends of the fade:
    if (brightness <= 0 || brightness >= 255)
    {
      fadeAmount = -fadeAmount;
    }
  }
}


text:
How to connect IRLZ44N to Arduino?

simulate this circuit – Schematic created using CircuitLab
In above schematic;

what value should R1 have? is it even needed?
do we need that pull down resistor(R2)? if yes, 10K is enough or we need higher value like 100K resistor there?

IRLZ44N DATASHEET

It's better with resistor so output driver isn't stressed to its maximum limits. Gate has its capacitance so it's better to limit charge/discharge current for such weak source
As the gate is basically capacitor, it has really big input impedance. Without pull down resistor it'll be catching all kinds of EMI (electro-magnetic interferences). So 10k is fine. The 100k might be less unreliable if the mcu output is not active (boot/reset)

Thanks, but what value should R1 have? 220 ohm is enough?

Ohm law. Output voltage is probably 5V and maximum current on avr pin is less than 30mA. So you shouldn't go under 166R. That 220R sounds fine. Bigger values could cause longer transitions between fully on and closed states and bigger losses. But it's the problem on much higher frequencies than the default analogWrite provides


text:
RTClib library the second, second
I'm using RTClib for my DS3231 module, the problem is the library is displaying the second without zero behind it: 22:1:1 and when i print the time on my 16x2 LCD time is displaying like this:

22:22:59
22:23:19
22:23:29
...
22:23:59
22:23:10
22:23:11

the second number of seconds is not getting cleared.
i know one solution to this is to use lcd.clear() function to update the LCD in each loop but is there any other way to clear that second number or do something so library show zero behind second?

What do leap seconds have to do with anything?

@Majenko sorry there was a misunderstanding, updated the question.

Your problem is that you are printing 1. People don't do that for time. You use 01.

how to use "01"? is there a setting i have to change?

If the seconds are less than ten, then print a 0. Then print the seconds. It's that simple. The library has nothing to do with it. It's what you do with the number in your code that matters.

if you please post that as an aswer i'll pick it as correct answer. lcd.print(now.second());.

It's your responsibility to format the time properly, not the library. The library just gives you a number. If you want a leading zero then it's up to you to provide that leading zero.
For example:
if (now.seconds() < 10) {
    lcd.print("0");
}
lcd.print(now.seconds());

Or:
char timestr[9];
snprintf(timestr, 9, "%02d:%02d:%02d", now.hours(), now.seconds(), now.minutes());
lcd.print(timestr);

what's snprintf? it's giving me this error: expected constructor, destructor, or type conversion before '(' token

@newbie: It's a very standard libc function.

@EdgarBonet i'm sorry but what's the error is about?

Did you use the code inside a function or just dump it into global scope?

i'm guilty of dumping it inside the global scope... i know i'm being a headache right now but can you please explain a bit more? @Majenko

Put it in loop() where you want to display the time.

@Majenko  thank you.


text:
KY-040 rotary encoder skipping steps
Yesterday I asked a question about de-bouncing this rotary encoder and Jsotola suggested that I should use a method like This to detect the previous state and then do the counting. using that method each turn is counting twice in one turn so I came up with my version of de-bouncing the rotary encoder:
int s1, s2;
int count = 0;
boolean right = 0;
boolean left = 0;
int rotary = 0;
unsigned long timer = 0;
unsigned int bounce = 50;

void setup() {
  Serial.begin(9600);
  pinMode(6, INPUT);
  pinMode(7, INPUT);

}

void loop() {

  s1 = digitalRead(6);
  s2 = digitalRead(7);
  if (s1 == 1 && s2 == 1) {
    right = 0;
    left = 0;
    rotary = 0;
  }
  if (s1 == 0 && s2 == 1) {
    left = 1;
  }
  if (left == 1 && (s1 == 0 && s2 == 0)) {
    rotary = 2;
  }
  if (s1 == 1 && s2 == 0) {
    right = 1;
  }
  if (right == 1 && (s1 == 0 && s2 == 0)) {
    rotary = 1;
  }

  if (rotary == 1) {
    if ((millis() - timer) > bounce) {
      count++;
    }
    right = 0;
    left = 0;
    timer = millis();
  }
  if (rotary == 2) {
    if ((millis() - timer) > bounce) {
      count--;
    }
    right = 0;
    left = 0;
    timer = millis();
  }
  Serial.print(s1);
  Serial.print(s2);
  Serial.print(", ");
  Serial.print(count);
  Serial.println(" ");
  delay(15);
}

The code is working just fine. When turning the rotary this are the steps that I get:
10-00-01 < (11) > 10-00-01
problem is if I turn the knob quickly rotary encoder will skip one or two steps like: 01-01-01 < (11) or 10-00-00 < (11).
This problem exist in all methods/libraries (I tested them all), is there anyway to fix this with software/hardware or this rotary encoder is just junk and I should get a better one?

Another method of de-bouncing as Jsotola requested:
 int pinA = 3;  // Connected to CLK on KY-040
 int pinB = 4;  // Connected to DT on KY-040
 int encoderPosCount = 0;
 int pinALast;
 int aVal;
 boolean bCW;

 void setup() {
   pinMode (pinA,INPUT);
   pinMode (pinB,INPUT);
   /* Read Pin A
   Whatever state it's in will reflect the last position
   */
   pinALast = digitalRead(pinA);
   Serial.begin (9600);
 }

 void loop() {
   aVal = digitalRead(pinA);
   if (aVal != pinALast){ // Means the knob is rotating
     // if the knob is rotating, we need to determine direction
     // We do that by reading pin B.
     if (digitalRead(pinB) != aVal) {  // Means pin A Changed first - We're Rotating Clockwise
       encoderPosCount ++;
       bCW = true;
     } else {// Otherwise B changed first and we're moving CCW
       bCW = false;
       encoderPosCount--;
     }
     Serial.print ("Rotated: ");
     if (bCW){
       Serial.println ("clockwise");
     }else{
       Serial.println("counterclockwise");
     }
     Serial.print("Encoder Position: ");
     Serial.println(encoderPosCount);

   }
   pinALast = aVal;
 }

Did you delete your 1st question?  I can not find it.  1) It would be best if you kept a 4 state machine such that you could tell left from right based on the current code and the previous quad-code.  I don't think I see that in your code above. 2) When dealing with firmware sampling one can assume some samples will be missed.   So the software needs to compensate or you need better hardware.  Usually cheap hardware and good software wins out because of cost.  So, I would have the software make up left & right base on history for illegal code sequences.

@st2000 deleted first question because i couldn't explain what the problem actually was and the question was a mess. | How can i detect one step from another when like the example in the question it just skipping all 3 or 2 steps? i need at least the first step...

My guess is the that all those serial.prints are really slowing down your code, making it too slow to detect fast rotary movements. You could for example only print the count, then rotate right fast, and then rotate back slowly, till it reaches the starting position. Then check if count is back to 0.

@Gerben removed delay() and serial prints too, no difference what so ever...

you almost have it  ... the program detects the transition, but you are jumping to trying to determine the direction of rotation .... forget about the direction and focus on consistently detecting either the rising or the falling edge of the signal ... when you see a transition, wait 50 ms and check again ... if a transition is confirmed, then check the signal level .... if it is high, then a rising edge occured ... if it is low, then a falling edge occured .... at this point, do not worry about the direction ... simply increment the counter only on rising edge ... observe the results

@jsotola please if possible post an answer with example.

I applaud you for your tenacity with the "debouncing" idea, but there is an excellent library for this rotary encoder, and the author has also written an article about it: Ben Buxton - rotary encoders done properly. Here is a link to his library: GitHub - buxtronix.
I’ve used an older version of the library before with interrupts, and it worked perfectly for my application. I see the author has updated the library and has 2 example sketches; one uses interrupts, and the other uses polling. I tried both of them today on an Uno and I was very impressed with the polling sketch’s performance. It seemed to equal that of the interrupt method.
If you take the important bits out of the library files, then add them to a sketch, you can see how little code it takes for this "method" of processing the encoder’s output. Here is a test sketch with the library bits in it.

#define R_START 0x0
#define R_CW_FINAL 0x1
#define R_CW_BEGIN 0x2
#define R_CW_NEXT 0x3
#define R_CCW_BEGIN 0x4
#define R_CCW_FINAL 0x5
#define R_CCW_NEXT 0x6
#define DIR_NONE 0x0
#define DIR_CW 0x10
#define DIR_CCW 0x20

const byte pin1 = 5;  // DT
const byte pin2 = 6;  // CLK
int state = R_START;
int counter = 0;

const unsigned char ttable[7][4] = {
  // R_START
  {R_START,    R_CW_BEGIN,  R_CCW_BEGIN, R_START},
  // R_CW_FINAL
  {R_CW_NEXT,  R_START,     R_CW_FINAL,  R_START | DIR_CW},
  // R_CW_BEGIN
  {R_CW_NEXT,  R_CW_BEGIN,  R_START,     R_START},
  // R_CW_NEXT
  {R_CW_NEXT,  R_CW_BEGIN,  R_CW_FINAL,  R_START},
  // R_CCW_BEGIN
  {R_CCW_NEXT, R_START,     R_CCW_BEGIN, R_START},
  // R_CCW_FINAL
  {R_CCW_NEXT, R_CCW_FINAL, R_START,     R_START | DIR_CCW},
  // R_CCW_NEXT
  {R_CCW_NEXT, R_CCW_FINAL, R_CCW_BEGIN, R_START},
};

unsigned char process(){

  // Grab state of input pins.
  unsigned char pinstate = (digitalRead(pin2) << 1) | digitalRead(pin1);

  // Determine new state from the pins and state table.
  state = ttable[state & 0xf][pinstate];

  // Return emit bits, ie the generated event.
  return state & 0x30;
}

void setup(){
  pinMode(pin1, INPUT_PULLUP);
  pinMode(pin2, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop(){
  unsigned char result = process();
  if(result == DIR_CW){
    counter++;
    Serial.println(counter);
  }
  else if(result == DIR_CCW){
    counter--;
    Serial.println(counter);
  }
}

Heres a simplified sketch (It works the same but I didn't like the hex numbers and I don't use define):
const byte pin1 = 5;  // Connected to DT on KY-040
const byte pin2 = 6;  // Connected to CLK on KY-040
int state = 0;
int counter = 0;

const unsigned char ttable[7][4] = {
  {0, 2, 4, 0},
  {3, 0, 1, 0 | 16},
  {3, 2, 0, 0},
  {3, 2, 1, 0},
  {6, 0, 4, 0},
  {6, 5, 0, 0 | 32},
  {6, 5, 4, 0},
};

void setup(){
  pinMode(pin1, INPUT_PULLUP);
  pinMode(pin2, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop(){

  unsigned char result = process();

  // Clockwise rotation.
  if(result == 16){
    counter++;
    Serial.println(counter);
  }

  // Counter clockwise rotation.
  else if(result == 32){
    counter--;
    Serial.println(counter);
  }

}

unsigned char process(){

  // Grab state of input pins.
  unsigned char pinstate = (digitalRead(pin2) << 1) | digitalRead(pin1);

  // Determine new state from the pins and state table.
  state = ttable[state & 0xf][pinstate];

  // Return emit bits, ie the generated event.
  return state & 48;
}

DUDE! it's magic! why i couldn't find this library! Thank you.


text:
Why voltage drop cause changes in analog reading of hall-effect sensor?
The sensor is a hall-effect UGN3503 sensor and I'm using a TL431 shunt regulator as voltage reference for analog readings.
I'm using analogRead() with setting the analog reference to external analogReference(EXTERNAL);.
schematic:

simulate this circuit – Schematic created using CircuitLab
The problem is changes in analog reading of hall-effect sensor. without connecting anything to Arduino but the sensor and TL431 reading is around ~1020, but for example connecting a single LED to any pins of Arduino causes the reading drop by ~2-3 or connecting the an I2C LCD causes the reading to drop to ~1010 etc...
How can i prevent analog read changes to happen when voltage drops?

You should show the Arduino in your circuit diagram, including how you connect the external voltage reference to the Arduino's AREF pin. (or is the AREF indicated in your diagram the connection to the Arduino's AREF pin). You should probably also show the relevant portions of your sketch's code.

@DuncanC the AREF in the diagram connected to the AREF pin of arduino and data pin of hall sensor to the a analog pin, and in the code there's really nothing except analogRead() and analogReference(EXTERNAL); and of course Serial.println()...

It sounds like your +5v supply is only barely adequate and sags as you draw even marginally more current. But even given that, your AREF is the TL431's voltage which 1) won't match the supply voltage (slightly redrawn schematic shows why), and 2) the sensor voltage could possibly exceed the AREF which is out of spec for the Arduino's A/D.
A more stable power supply - able to maintain its voltage despite the expected variation in current draw - would help a lot, but your best solution is to use the supply voltage as your AREF, unless you require the TL431 reference to be your AREF for some reason.

The power supply currently is a USB (Arduino UNO board), before TL431 i had a 3.3V regulator connected to the AREF. i thought changing it to TL431 can solve the problem but it didn't...

You said "A more stable (i.e., capable) would help a lot". Do you mean A more stable (i.e., capable) POWER SUPPLY would help a lot"? As in a higher current regulated power supply?

Yes - thanks for the catch. Fixed.

I suspect the USB 5v supply is rather noisy and sags slightly with load. A hall effect sensor measures TINY signals, so it's probably quite sensitive to changes in supply voltage.
You might try adding a capacitor to the line, but you'd be better off either feeding 7.5-9-VDC into the barrel connector and using the on-board voltage regulator on the Arduino to generate your 5V and 3.3V, or feeding a regulated 5V supply into a cut USB cable (that way you get the power source switching and fuse protection on Arduino boards, but still can use an externally regulated 5V supply.)


text:
RTC timer set point problem
This is the timer part of my code:
int onHourONE = 11;
int onMinuteONE = 00;
int offHourONE = 23;
int offMinuteONE = 00;
byte PWMstatus = 0;

void setup{}

void loop{
    if ((now.hour() >= onHourONE) && (now.minute() >= onMinuteONE)) {
      PWMstatus = 1;
    }
    if ((now.hour() >= offHourONE) && (now.minute() >= offMinuteONE)) {
      PWMstatus = 2;
    }
    if (PWMstatus == 1) {
      // do this
    }
    if (PWMstatus == 2) {
      // do that
}

It's working just fine but the problem is if i set the offhourONE less than onhourONE it will keep the LED OFF.
for example the time is now 14:00
onhourONE and offminuteONE is also set on 14:00
offhourONE and offminuteONE is set on 13:00
So in this case it should keep the LED ON until tomorrow 13:00 but it stays OFF obviously because of this statement:
if ((now.hour() >= offHourONE) && (now.minute() >= offMinuteONE)) {}

I can change that to this:
if ((now.hour() == offHourONE) && (now.minute() == offMinuteONE)) {}

But then it will only turn OFF the LED at that specific time, in this case if i restart the Arduino like 1 minute after it turned OFF it will turn on again while it should stay off until it reaches the set point of turn ON.
I know it sounds simple but seems confusing to me, any guidance appreciated...

i was writing as i was thinking ... 37:00 = 13:00 + 24:00 ... add 24 hours to turn off time

you can figure this out by drawing a diagram ... circle ... 0 at top 12 at bottom ... that is 24 hours ....  add 24 hours to stop time .... then use something like this pseudo code  if (T>=14 && T+24 <=37) then ON else OFF

You need to add more logic to your program.
As mentioned in another answer you really want to be working with just the highest resolution time interval that matters to you - that is minutes in your case.  Convert your hour and minutes of the day into the number of minutes since midnight:
onTime = onHourONE * 60 + onMinuteONE;
offTime = offHourONE * 60 + offHourONE;

And convert the current time to minutes since midnight:
timeNow = now.hour() * 60 + now.minute();

Now comes the tricky bit, but since you are now just working with single numbers it's far easier.  You now need to work out what you are doing.
You have a couple of scenarios:

onTime < offTime - eg: 12:00 to 17:00
onTime > offTime - eg: 21:00 to 03:00

You need to make your decision in a different way depending on which scenario you are in - and comparing a single number with a single number is so much easier than messing with hours and minutes.
So, you can do something like:
if (onTime < offTime) {
    if ((timeNow >= onTime) && (timeNow < offTime)) {
      // On!
    } else {
      // Off!
    }
} else {
    if ((timeNow >= onTime) || (timeNow < offTime)) {
      // On!
    } else {
      // Off!
    }
}

In English:

If the start time is before the end time:

If the time is both greater than the start time and less than the end time, then it's on.
Otherwise it's off.

Otherwise, of the start time is after the end time:

If the time is greater than the start time, or it's less than the end time, then it's on.
Otherwise it's off.

thanks for the detailed answer, that now after first if is timeNow, right?

Yes, that's right. I edited my answer. Well spotted.

I just tested it and it's working. thanks again. quick question; can i combine that if after else together like this else if(){}?

Possibly, but it's more logical laid out the way I have it. You can instantly see the meaning, and it won't make it any more or less efficient to run.

If it overly complicated to use a combination of seconds, minutes and hours for comparisons. For this you can use the time in seconds, as you get it with now.secondstime() or now.unixtime(). If you don't want to look at the seconds (so only values multiple to 60), you can do an integer division to get the minutes now.secondstime()/60.
To calculate the needed limit values from the combination of hour and minutes, just multiply according to the unit. For seconds (hour*60+minutes)*60. For minutes hour*60+minutes.

unixtime for a time in current day? and how does using minutes of day solve the question?


text:
Non-blocking incrementation with single button pressure
I am looking for a way to increment a variable by one each time a button is pressed. Current approach is the following :
    if (redButton.isPressed())
    {
        a++;
        delay(100);
    }

isPressed() just return true if the pin state is HIGH.
delay(100) is used to compensate the small amount of time the button is being pressed. Otherwise a would be incremented multiple times in a single press. But it's blocking behavior, my program can't do anything else during that delay.
In short I'm looking to add a method in my Button class to detect if the button "has just been released".

Have you seen the Bounce2 library? https://github.com/thomasfredericks/Bounce2

In your approach a button press will be detected every 100ms when you just keep the button pressed. So you have to set a flag when the button is pressed. When the button is not pressed while your flag is set, that's the event you're looking for. In this way you can detect both a button press and a release respectively.
As @JRobert mentioned, there still has to be an amount of time between two calls to such a routine to provide some button debouncing.
bool pressed_flag=false;
bool button_timestamp=millis();
uint16_t button_period=100;

if(millis()-button_timestamp>button_period){
  button_timestamp=millis();
  if(redButton.isPressed() && !pressed_flag){
    // button has just been pressed
    // you can do sth. here
    pressed_flag=true;
  }
  else if(!redButton.isPressed() && pressed_flag){
    // button has just been released
    // you can do sth. here
    pressed_flag=false;
  }
}

Also use either a timer library, or hand-code with millis(), to come back and check the button after a time. That interval defends against contact chatter or bounce (multiple inputs for a single press). Using the flag prevents you "detecting" one long button press multiple times. And your code will still not get blocked.

@JRobert theoratically my code is allready non-blocking. But I aggree: it doesn't include any debouncing and my routine should only be called in a specific period.

Agreed - it doesn't block. I just intended to suggest the addition of chatter removal to your already appropriate solution. (And I got caught accidentally submitting a partially-edited comment! ):

@JRobert you're absolutely right, I added what you suggested!


text:
Why does my Arduino 3.3v fluctuate?

For some reason, my 3.3v on my Arduino is fluctuating a lot, and I am not sure why.
The multimeter is measuring dc voltage and is connected between GND and 3.3v of an Arduino Mega.
The multimeter works fine. Connecting between 5v and GND gives 5V on multimeter.

the video is meaningless ... it does not show what you are measuring

Im measuring DC voltage between gnd and 3.3v

@jsotola can you tell me what information I should include?

you have to disconnect everything from the board, upload a blank sketch and measure it again.

Tried that still fluctuated

First check your connections. Otherwise: broken 3.3V regulator or too much load on the 3.3V supply.

Change the batteries in your meter. Try measuring things with your oscilloscope rather than your meter.

What happens if there is a load on the 3.3V rail. It kind of looks like the point you are measuring is floating/not connected. Try adding a 1kOhm resistor between 3.3V and GND, and remeasure. If it's indeed floating you should read 0V. Also try a different GND pin, just in case.

Arduino output voltages may "fluctuate" a few mV but what you showing us in that gif is really unstable.
What you should be doing is:

Disconnect everything from Arduino except the power source
measure the voltage again;

Is it stable? the problem was because of pulling too much current that causing voltage drop and instability .
Is it unstable?

Try checking with another MM and/or change auto-range to manual.

Is it stable when measuring the voltage with another MM? something was wrong with your previous MM.
Still unstable?

Connect the Arduino to a 9V power adapter and disconnect the USB cable.

Measure the voltage again, if it's stable the problem was because of some error in the cable or USB power source.
Voltage is still unstable?

change the 3.3V voltage regulator.

It should fix the problem if not report back to do some more in-depth problem solving.

My voltage Reg was off I should have tested before asking, but thanks!

@SanjitSarda Just for my curiosity, what do you mean with "my voltage reg was off"? Was it broken or did you switched it off. If you switched it off, how did you do that?


text:
Error reading file
What should be done to solve it?
I have edited the board.txt file and none of my codes are getting verified
it shows this error:

"Error reading file (C:\Program Files
  (x86)\Arduino\hardware\arduino\avr\boards.txt:0): Invalid line format,
  should be 'key=value' "

it is obvious that you made a mistake editing the file .... revert the file to its original content

You can either reinstall the Arduino IDE (it will replace the file), or copy the original code back in the file (if you have a copy somewhere).
See the link: https://code.google.com/archive/p/arduino/wikis/Platforms.wiki for more background in case you are interested.
(note: I cannot copy the content of the file in the answer since it is more than 30000 characters.)


text:
I2C Wire.onRequest not detected
I want to know why Wire.onRequest can not detect below massage and what I can do to detect it.(I am not able to change I2C massage)
I was able to read this part of the massage with wire.onReceive:

But I can not read this massage at all, which is requesting:

#include <Wire.h>
byte val = 170;
int sendv;

char c;

byte dataArray[16];

void setup() {
  Wire.begin(0x77);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Wire.onRequest(requestEvent); // register event
  Serial.begin(9600);           // start serial for output
}

void loop() { }

void receiveEvent(int howMany) {
  Serial.println(howMany);

  if (howMany >= 2) {
    for (int i = 0 ; i < howMany; i++) {
      dataArray[i] =  Wire.read();
      Serial.println(dataArray[i], HEX);
    }

  } else {
    c =  Wire.read();
    Serial.println(c, HEX);
  }
}

void requestEvent() {
  Serial.println("REqEVENT");
}

So you mean in your code you are never seeing the REqEVENT in the serial monitor? Normally in the onRequest callback you would write data to the I2C buffer, so that it can be send

Yes, when I run the code I never goes inside of request event and I dont see REqEVENT, which it should becouse 0xEFm or 0xEE is correct address

Are the images from the transmission from your code? That would fit your code, since you don't send any data on request. Maybe sending over serial is not a good test here, since the function get's called from an ISR. Try to light an LED inside the function to test, if the code get's there. Also try to actually send data and see, if this data get's actually send, by watching your logic analyser.

I have tried sending massage which did not work, I just tried Led too and not turning on, Also you can see on logic analyzer is getting 0xFF

I was able to solve the issue with by adding  twi_stop(); to twi.c
base on this website
enter link description here


text:
BLDC motor control
I want to control a BLDC motor with Arduino board and a circuit with some transistors and other elements, the input of this board will be flight control. my question is that is it possible to connect a flight control with an Arduino board? if it is possible do you have any idea?

Yes it is possible

You should also check https://electronics.stackexchange.com/questions/169398/bldc-motor-without-esc and https://electronics.stackexchange.com/questions/355167/how-does-a-hobby-esc-drive-a-bldc-motor . Making your own ESC or " a circuit with some transistors ..." as you have said is no easy task.

You do you even want to build your own ESC? I don't think, that this will be cheaper than simply buying one.

Tnx ,i know uts better to buy a ESC but i wanna  have exprience in building a ESC  for a quad.i will make it with a arduino board and push_pull transistors in this circuit i control the arduino board with two  micro swiths but now l wanna control this with flight controller by giveing the flight control signal to arduino how can i do it?


text:
Interface a mobile phone's finger print scanner with arduino
Is it possible to salvage a fingerprint scanner from an old and dead smartphone and use it with Arduino? I am not talking about writing an android program and send data to Arduino over Bluetooth or WiFi, I am talking about wiring up fingerprint scanner of a mobile phone to Arduino.

any direction you could point me to where i can start digging. Did some basic googling but didnt had any luck.

@Anmol it will be easier if you first identify the finger print sensor (manufacturer, part number etc...).

Long-shot, but if the phone is still functional enough to unlock with a fingerprint, try sensing the overall screen brightness when locked and when unlocked, and use that as the "Fingerprint matched" signal. Obviously this won't work with a truly dead phone.
A lot of processing goes into reading and storing or matching a finger-print. The magic is in the software, not (only in) the sensor. An Arduino (Uno class or similar) is way under-powered for the task. Perhaps one of the Arm- or other high-end Arduinos would have the capability if you had or could write the necessary software.
Short answer: No.

In general: It depends. We can only talk about the general situation, not about details, because we don't know the exact sensor type. You are facing some serious problems when doing this.

Without a part number or something like this, we cannot say, how the sensor communicates with the phones mainboard. It might or might not be a communication interface, that the Arduino has or can be made capable of.
The sensor and it's interface might be proprietary, which would mean, that there is no public documentation about the interface and how it works. Reverse Engineering something like this need mostly a big amount of time and experience with various electronical systems.
As Shyam Singla already pointed out in his/her answer, most (if not all) Arduino compatible fingerprint sensors don't send the actual fingerprint image, but do the difficult image handling and recognition by themselves. The Arduino only get's status information (for example if a previously saved fingerprint was detected). On a phone, this is most likely not the case. The main processor of the phone has way enough power to do the calculation by itself. It doesn't need to offload them to an external chip like the Arduino needs to. (Also this gives the vendor the opportunity to update the recognition software later on with a simple OS update.) That means, that the sensor will most likely only send images and you would need to do the image handling and recognition on the Arduino. AVR based Arduinos (like the Uno or Nano) are totally undersized for this.
The connection pins of the sensor will be very small and difficult to connect, especially if you are a beginner.
You would have to use level shifters and voltage regulators to interface between the 5V devices Uno/Nano and the sensor, which will most likely work with a significantly lower voltage (at max 3.3V, most likely less).

Using FPGAs to tackle some of these problems is possible, but also very challening. If you need to ask this question, this is most likely out of scope. (A friend of mine did program a FPGA for his physics master on university. It can be very difficult.)
All in all I would say, it is not worth the effort to even try this. Instead buy an Arduino compatible fingerprint sensor.

Possible but not directly as the arduino compatible fingerprint sensor contains image formation and saving mechanism which means that those sensors scan a fingerprint form image and send the scan status not the finger print image....
As in case of fingerprint sensor of phones, the sensor directly send the whole image...
so you have to use FPGA (Field Programming Gate Arrays) to make communication between that...
But this is a very expensive way... As FPGA are very expensive but have huge functionality means you can design any circuit any sensor any controller you want using FPGA


text:
How to read voltage using ADS1115
I'm very new to this. I found this tutorial.
But it don't explain how to read voltages higher than Arduino 5V. I have connected a 100K ohm resistor to positive and 10K ohm to negative of my 24V power supply.
I need some guidance for writing the code for this specific ADC, please.

So you want to measure the voltage of your power supply?

Yes i want to measure voltages higher than 5V.

You cannot measure much more than 5V with that device neither. (VDD +0.3V)
You and that "tutorial") use an adafruit library and should get information from them.
If those 2 resistors (100k + 10k) build a voltage divider and negative is connected to GND, 24V is reduced to 24V/11 ~ 2.18V between the two resistors.

i know that Datafiddler but i don't know how can i convert and read that 2,18V to 24V!

It's called "math". For example: Arduino has 10 bit precision and usually 5V reference voltage. That means one step is  5V / 1024 = 0.004883V. And if you divide input voltage by 11, that means you have to multiply previous result by 11 too.

i did what you said: voltage = voltage * 11 but it's showing lower voltage than actual voltage.

If you try something and it doesn't work as expected, please write this information into the question (not the comments). You wrote, that you tried the calculation and got lower voltages. So write in your question: the code that you used for calculation with all relevant values, what voltages are outputted by it and what voltages you measured how externally.

As KIIV mentioned you need to do the math:
Use this online voltage divider calculator to calculate your maximum input.

Keep in mind you shouldn't exceed Arduino 5V.
Use a multimeter to measure the resistors actual resistance.
Do the math for your example assuming R1 is exactly 100K and R2 10K you have to multiple the voltage by 11.
remember any error is going to multiple by 11 too, so make sure the first reading is accurate/stable.

ADS1115 is actually 15bit which will give you resolution of 32768, with default PGA setting you get:
6.144 / 32768 = 0.0001875V per bit.
Voltage = (your ADC reading) * 0.0001875V;
Voltage = Voltage * 11;

Take a look at This question/answer to see how I did reduced Arduino ADC noise, some steps can be done for ADS1115 as well.


text:
I2C Communication with the ICM-20789
I am trying to interface with the ICM-20789 over I2C. DataSheet
I have been successfully able to get all three gyroscope readings and all three accelerometer readings. I am now trying to get the pressure readings from the device, since it has a built-in pressure sensor, but cannot seem to get it working.
In the datasheet, it says to enable Bypass Mode.

Bypass Mode: Set register INT_PIN_CFG (Address: 55 (Decimal); 37 (Hex)) bit 1 to value 1 and I2C_MST_EN bit is ‘0’
  (Address: 106 (Decimal); 6A (Hex). Pressure sensor data can then be accessed using the procedure described in Section 10

In the setup I use this code:
  Wire.beginTransmission(gyro_address);
  Wire.write(0x37);      //INT_PIN_CFG
  Wire.write(0x02);      //00000010
  Wire.endTransmission();

I am having trouble finding I2C_MST_EN in the datasheet as well, as I cannot find it in the 6A Address.
Once I have the bypass bit enabled, I try to request the pressure and temperature data from the sensor using this code:
Wire.beginTransmission(0x63);
Wire.write(0x7866);
Wire.endTransmission();
Wire.requestFrom(0x63, 16);

while (Wire.available() < 16);
pressure = Wire.read() << 16 | Wire.read() << 8 | Wire.read();
temp_2   = Wire.read() << 16 | Wire.read() << 8 | Wire.read();

Unfortunately, the device freezes when I try to run this code. I know I am obviously doing something wrong here, just don't know exactly what yet.

Wire.write(0x7866); will truncate your value to just 0x66. You can only write 8 bits at a time.

There are four things wrong with your code.

You are not sending the "start measurement" command properly. The Wire.write() function can only send 8 bits, but you are passing it a 16-bit value. Instead you should break it apart into 2 separate 8-bit values:
Wire.beginTransmission(0x63);
Wire.write(0x78);
Wire.write(0x66);
Wire.endTransmission();
The data returned is spread over 9 bytes, not 16.  According to the datasheet:

Temperature data is transmitted in two 8-bit words and pressure data is
  transmitted in four 8-bit words.

and:

Two bytes of data are always followed by one byte CRC checksum

That's 2 + 4 = 6 + (6/2) = 9

You aren't waiting for the conversion to complete. According to the datasheet, in "ultra low noise" mode (0x7866) it takes up to 94.5ms to perform the measurement.  So you should add a delay of slightly more than that to allow it to do what it needs to do.
The command you are sending responds with temperature first, not pressure, but you are reading pressure first (and reading the wrong bytes anyway).

In all, your code should look more like:
Wire.beginTransmission(0x63);
Wire.write(0x78);
Wire.write(0x66);
Wire.endTransmission();

delay(100);

Wire.requestFrom(0x63, 9);
uint8_t tmsb = Wire.read(); // Temperature highest byte
uint8_t tlsb = Wire.read(); // Temperature lowest byte
Wire.read();

uint8_t pmmsb = Wire.read(); // Highest pressure byte
uint8_t pmlsb = Wire.read(); // Next highest pressure byte
Wire.read(); // Discard checksum
uint8_t plmsb = Wire.read(); // Next lowest pressure byte
uint8_t pllsb = Wire.read(); // Lowest pressure byte
Wire.read(); // Discard checksum

pressure = (pmmsb << 24) | (pmlsb << 16) | (plmsb << 8) | pllsb;
temp_2   = (tmsb << 8) | (plsb << 8);

Thank you Majenko! That makes more sense. I have added that code to my loop. My code is still freezing though. It happens when I add this code in the setup to enter bypass mode: Wire.beginTransmission(0x63);
Wire.write(0x78);
Wire.write(0x66);
Wire.endTransmission();

That's not the code to enter bypass mode - that's the code to start a pressure conversion.

My apologies, I copied over the wrong code. When I have these lines of code on my setup, the code freezes.
Wire.beginTransmission(gyro_address);
Wire.write(0x37);      //INT_PIN_CFG
Wire.write(0x02);      //00000010
Wire.endTransmission();


text:
Communication between Arduino and Can Bus
Function mcp2515_get_message appears the following instruction:
 uint32_t i1 = (uint32_t) spi_putc(0xff),
          i2 = (uint32_t) spi_putc(0xff),
          i3 = (uint32_t) spi_putc(0xff),
          i4 = (uint32_t) spi_putc(0xff);

This instruction is used to fetch data used for determining the message id. Supposing the 32 bit source data contains
Hex 0xAA3A6060, which values will appear in i1, i2, i3, i4?
Any help will be much appreciated.

Is the "32 bit source" big or little endian?

Is this a school assigment?


text:
How do I code the release of a momentary touch sensor in IDE?
I am a performing musician and quite new to the Arduino community.  Just learning as I go.  I am interested in using a momentary touch sensor with Adafruit's MP3 shield or Wave Shield.  I have successfully connected a touch sensor to the MusicMaker MP3 shield (which is sitting on the Adafruit Metro).  I combined some code from two independently working code sequences: one, to play MP3s and, two, to trigger with the sensor.  This works successfully except that the music starts but does not stop when I lift my finger off the sensor.  I want the music to stop when the touch sensor is not being touched.  When the sensor is touched again, I want the music file to start again from the beginning.  I'm printing the code IDE is running below and attaching an image of the touch sensor I am using.  I appreciate any advice on the code!  Thank you.
/*
  AnalogReadSerial

  Reads an analog input on pin 0, prints the result to the Serial Monitor.
  Graphical representation is available using Serial Plotter (Tools > Serial Plotter menu).
  Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/AnalogReadSerial
*/

// include SPI, MP3 and SD libraries
#include <SPI.h>
#include <Adafruit_VS1053.h>
#include <SD.h>

// define the pins used
//#define CLK 13       // SPI Clock, shared with SD card
//#define MISO 12      // Input data, from VS1053/SD card
//#define MOSI 11      // Output data, to VS1053/SD card
// Connect CLK, MISO and MOSI to hardware SPI pins.
// See http://arduino.cc/en/Reference/SPI "Connections"

// These are the pins used for the breakout example
#define BREAKOUT_RESET  9      // VS1053 reset pin (output)
#define BREAKOUT_CS     10     // VS1053 chip select pin (output)
#define BREAKOUT_DCS    8      // VS1053 Data/command select pin (output)
// These are the pins used for the music maker shield
#define SHIELD_RESET  -1      // VS1053 reset pin (unused!)
#define SHIELD_CS     7      // VS1053 chip select pin (output)
#define SHIELD_DCS    6      // VS1053 Data/command select pin (output)

// These are common pins between breakout and shield
#define CARDCS 4     // Card chip select pin
// DREQ should be an Int pin, see http://arduino.cc/en/Reference/attachInterrupt
#define DREQ 3       // VS1053 Data request, ideally an Interrupt pin

Adafruit_VS1053_FilePlayer musicPlayer =
  // create breakout-example object!
  //Adafruit_VS1053_FilePlayer(BREAKOUT_RESET, BREAKOUT_CS, BREAKOUT_DCS, DREQ, CARDCS);
  // create shield-example object!
  Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  Serial.println("Adafruit VS1053 Simple Test");

  if (! musicPlayer.begin()) { // initialise the music player
     Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
     while (1);
  }
  Serial.println(F("VS1053 found"));

   if (!SD.begin(CARDCS)) {
    Serial.println(F("SD failed, or not present"));
    while (1);  // don't do anything more
  }

  // Set volume for left, right channels. lower numbers == louder volume!
  musicPlayer.setVolume(20,20);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // print out the value you read:
  Serial.println(sensorValue);
  if(sensorValue > 100) {
    Serial.println(F("Playing track 001"));
  musicPlayer.playFullFile("/track001.mp3");
  }
 else(sensorValue < 100); {
    Serial.println(F("Paused"));
  musicPlayer.pausePlaying("/track001.mp3");
 }      }

you do it the same way as when you detect the keypress ... when the value of the pin indicates that the button has been released,  stop the music

I don't know the mp3 lib and its methods, but playFullFile() sounds like it may return after the entire file has been played. In that case the button wouldn't be polled while the file is being played

You have a semicolon that doesn't belong in your code. Your current code (With the indentation cleaned up a little)
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // print out the value you read:
  Serial.println(sensorValue);
  if(sensorValue > 100) {
    Serial.println(F("Playing track 001"));
    musicPlayer.playFullFile("/track001.mp3");
  }
  else(sensorValue < 100); { // <<<--semicolon does not belong here.
    Serial.println(F("Paused"));
    musicPlayer.pausePlaying("/track001.mp3");
  }
}

Should be:
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // print out the value you read:
  Serial.println(sensorValue);
  if(sensorValue > 100) {
    Serial.println(F("Playing track 001"));
    musicPlayer.playFullFile("/track001.mp3");
  }
  else(sensorValue < 100) { // <<<--semicolon removed from this line
    Serial.println(F("Paused"));
    musicPlayer.pausePlaying("/track001.mp3");
  }
}

With the semicolon after the else, your code reads "...else do nothing" and then I would expect it to execute the pause logic no matter what value is in sensorValue.
You should pick an indentation style and then be absolutely consistent with it. Most C/C++ programmers use K&R style, which is what I used in my edit. (Opening braces are on the same line as the if statement/function that begins the scope, code inside braces is indented, and closing brace is at the same indentation level as the line that contains the opening brace.)

As Sim Son have pointed it out, you need to use the proper function.
According to your library's documentation:
boolean playFullFile(char *trackname) - Play the complete file. This function will not return until the playback is complete.
You want to check your touch sensor, so this won't be enough for you.
boolean startPlayingFile(char *trackname) - Begin playing the specified file from the SD card using interrupt-driven playback. This allows your program to perform other tasks as the file is playing.
That documentation missed it, but in the source there is a function that stops your music:
void stopPlaying(void);
You can find this within your Arduino folder: Arduino/libraries/Adafruit_VS1053_Library's Adafruit_VS1053.h and Adafruit_VS1053.cpp files.


text:
FatalError('Invalid head of packet (0x%s)' % hexify(b)) while uploading on ESP8266
I have this error while uploading my code to ESP8266 despite the fact that the code runs without errors. I have the git version of installation for the board.
ERROR:
File"C:/../../AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 1889, in slip_reader
raise FatalError('Invalid head of packet (0x%s)' % hexify(b))
esptool.FatalError: Invalid head of packet (0x46)
esptool.FatalError: Invalid head of packet (0x46)

Any help with this? Thanks.

is the esp8266 in flashing mode?

How do I know If its in flashing mode?

io 0 must be pulled down at boot to start in flashing mode. how did you wire the esp8266 module? how is it connected to PC?

why do you say that the code runs without errors? ... how can the code run if you are unable to load it into the ESP8266?

I press the "verify" button and is running without errors.
My esp8266 module is connected via usb cable.
I didn't understand what you are saying about "io 0 must be pulled down..."


text:
Library compilation error
Need help for this Tutorial. I tried to compile the code, but I'm getting compiling error.
I tried to ask on that forum too but got no answer, the error is:
In file included from C:\Program Files (x86)\Arduino\libraries\SD\src/utility/SdFat.h:32:0,
Multiple libraries were found for "SD.h"from C:\Program Files (x86)\Arduino\libraries\SD\src/SD.h:20,
 Used: C:\Program from D:\FEMV3FKI7YLJVQQ\FEMV3FKI7YLJVQQ.ino:1:
 Not used: C:\Users\IBNUM
C:\Program Files (x86)\Arduino\libraries\SD\src/utility/BlockDriver.h:31:10: fatal error: FatLib/BaseBlockDriver.h: No such file or directory
Multiple libraries were found for "SPI.h"
 #include "FatLib/BaseBlockDriver.h"
 Used: C:\Program
          ^~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.
exit status 1
Error compiling for board Arduino/Genuino Mega or Mega 2560.

How can I fix this Arduino compile error?

you copied parts of the SD library to your sketch folder?

@Juraj no, i use import .Zip file in arduino IDE

@jsotola i'm sorry, i need to edit my question

delete the library from your sketches folder, which you installed with zip. it was already installed with the IDE

1.8.9 working fine for my sketch, but 1.8.10 said compiling error.

I have the same problem since version 1.8.10.
With a good running sketch I don't get any message "Multiple libraries were found" (and no warnings also)
But with every small compiler error I get a whole list of "Multiple libraries were found"
My custom libraries are in a sketchbook location
D:\DATA BACKUPPED\Documenten Albert\Arduino\Sketchbook-and-user-libraries

This answer is really pointing to a really easy but hard to notice reason for getting the duplicate library messages.  Just one compile error and this message can be thrown, however it has nothing to do with the actual problem with the code.


text:
How could i synchronize 2 signals
unsigned long Htime;
unsigned long Ltime;
unsigned long Ttime;
unsigned long f;
int N;

void setup() {
  // put your setup code here, to run once:
cli();
  TCNT2 = 0;
  TCCR2A = 0;
  TCCR2B = 0;
  Serial.begin(9600);
  pinMode(5,INPUT);
  pinMode(3,OUTPUT);
  pinMode(11,OUTPUT);
  TCCR2A = (1 << COM0A1) | (1 << COM0B1) | (1 << WGM21) | (1 << WGM20);
  TCCR2B = (1 << WGM22) | (1 << CS22) | (1 << CS21) | (1 << CS20);
  TIMSK2 = (1 << OCIE2A);
}

void loop() {
  // put your main code here, to run repeatedly:
  Htime = pulseIn(5, HIGH);
  Ltime = pulseIn(5, LOW);
  Ttime = Htime + Ltime;
  f = 1000000 / Ttime;
  Serial.println(f);
  N = (16000000 / 1024 / f ) - 1;
  OCR2A = N;
  OCR2B = N/2;

}

Hi this is what i have written. and i need output a square wave with timer, its frequency is measured from input signal in pin 5. After connecting the oscilloscope, i see the problem, there is phase shift between 2 signals. How could i synchronize this 2 signals?(rising edge to rising edge, falling edge to falling edge) Thank u so much for your help!

You assume a 1:1 HIGH-LOW ratio for your square output, correct? With that assumption you can get rid of the unsure location of the rising edge.

move the println after the OCR settings

The signal at CH1 is an external signal, right?

the top signal has a rising edge of almost 5 ms .... how do you expect to synchronize that?

I haven't fully understood what you want to achieve, but you can clear TCNT2 on a falling edge of the CH1 to synchronize them

Given that only the falling edge of your input is sharp and well
defined, I suggest the following approach:

Use the input-capture feature of Timer 1 to get a timestamp on the
falling edge and trigger an interrupt.
In the ISR, start by toggling the output in order to set it low. Then
compute the period of the signal (timestamp of this falling edge minus
timestamp of the previous one) and program a compare register to
trigger a compare match event after half a period.
The compare match would automatically toggle the output pin again, by
using the “toggle on compare match” timer output mode.

The following program attempts to implement this approach. Note that it
is completely untested. Input is on pin 8 (i.e. PB0 and ICP1). Output is
on pin 9 (i.e. PB1 and OC1A). The timer is set to run at F_CPU/8 in
order to accommodate frequencies as low as about 30.1 Hz. A
different prescaler should be used if lower frequencies are needed. The
program does not rely on the Arduino core, and thus defines its own
main() instead of setup() and loop().
ISR(TIMER1_CAPT_vect)
{
    TCCR1C = _BV(FOC1A);  // force output compare -> toggle output
    static uint16_t last_capture;
    uint16_t capture = ICR1;
    uint16_t period = capture - last_capture;
    last_capture = capture;
    OCR1A = capture + period/2;  // compare match after 1/2 period

    // If output is high, toggle again.
    if (bit_is_set(PINB, PB0))
        TCCR1C = _BV(FOC1A);
}

int main()
{
    // Set OC1A = PB1 = digital 9 as output.
    DDRB = _BV(PB1);

    // Configure Timer 1.
    TCCR1A = _BV(COM1A0);  // toggle OC1A on compare match
    TCCR1B = _BV(CS11);    // clock at F_CPU/8
    TCCR1C = _BV(FOC1A);   // force output compare -> toggle output
    TIFR1  = _BV(ICF1);    // clear capture flag
    TIMSK1 = _BV(ICIE1);   // enable capture interrupt
    sei();

    for (;;) {}
}

thank u so much, this code works perfect. And now i need to transform this square wave to sine wave. I tried set PB2 to change duty cycle and use RC-filter, but when i writte DDRB = _BV(PB2) and OCR1B = ... in programme then can't even get the square wave.why happens that?


text:
How to make an arduino button to forget his past purpose?
For my school project im making an arduino speedometer for a bicycle. I will be using a reed switch sensor to get the speed. There will also be an clock and a termometer, it will be on a 16x2 lcd screen. To get the speed I will need the user to type in his bike size, in zoll. I managed to let the user tap the button until his size and then double tap the button to confirm it. Alright, fine. Now I need the same button to FORGET his last purpose. Because I want to use the same button to change the screen between speed, clock and termometer. SPEED -> tap -> CLOCK -> tap -> TEMPERATURE -> tap -> SPEED ........
I hope you get the idea. After the user picks his size, if he keeps tapping the number it would just keep on growing. So, im trying to make the button forget, or make him go trough that loop only once.
Pick your size tap tap tap double tap, thank you. And stop! I want him to do that only once and never again. I will need the same principle when the user will adjust his clock, he will have to tap to set it, save the number but reset the buttons function.
#include <LiquidCrystal_I2C.h>
#include <LiquidCrystal.h>
LiquidCrystal_I2C lcd(0x27, 16,2);
#define buttonPin 7
int a = 16;
int b = 0;

void setup() {
  lcd.init();
  lcd.backlight();
  lcd.print("RADGROESSE IN");
  lcd.setCursor(0, 1);
  lcd.print("ZOLL EINGEBEN");

   // Set button input pin
   pinMode(buttonPin, INPUT);
   digitalWrite(buttonPin, HIGH );
}
void loop() {
   int b = checkButton();
   if (b == 1) clickEvent();
   if (b == 2) doubleClickEvent();
}
void clickEvent() {

   lcd.setCursor(14, 1);
    lcd.print(a);
    delay(100);
    lcd.print(" ");
    delay(100);
    a++;
    delay(100);
    if(a >= 23){
      a = 16;
      }
}
void doubleClickEvent() {
      b = a - 1;
      Serial.println("Button was idle for one second or more");
      lcd.clear();
      lcd.print("ZOLL = ");
      lcd.setCursor(7, 0);
      lcd.print(b);

}

//=================================================
//  MULTI-CLICK:  One Button, Multiple Events

// Button timing variables
int debounce = 20;          // ms debounce period to prevent flickering when pressing or releasing the button
int DCgap = 420;            // max ms between clicks for a double click event
// Button variables
boolean buttonVal = HIGH;   // value read from button
boolean buttonLast = HIGH;  // buffered value of the button's previous state
boolean DCwaiting = false;  // whether we're waiting for a double click (down)
boolean DConUp = false;     // whether to register a double click on next release, or whether to wait and click
boolean singleOK = true;    // whether it's OK to do a single click
long downTime = -1;         // time the button was pressed down
long upTime = -1;           // time the button was released

int checkButton() {
   int event = 0;
   buttonVal = digitalRead(buttonPin);
   // Button pressed down
   if (buttonVal == LOW && buttonLast == HIGH && (millis() - upTime) > debounce)
   {
       downTime = millis();
       singleOK = true;
       if ((millis()-upTime) < DCgap && DConUp == false && DCwaiting == true)  DConUp = true;
       else  DConUp = false;
       DCwaiting = false;
   }
   // Button released
   else if (buttonVal == HIGH && buttonLast == LOW && (millis() - downTime) > debounce)
   {
           upTime = millis();
           if (DConUp == false) DCwaiting = true;
           else
           {
               event = 2;
               DConUp = false;
               DCwaiting = false;
               singleOK = false;
           }
   }
   // Test for normal click event: DCgap expired
   if ( buttonVal == HIGH && (millis()-upTime) >= DCgap && DCwaiting == true && DConUp == false && singleOK == true && event != 2)
   {
       event = 1;
       DCwaiting = false;
   }

   buttonLast = buttonVal;
   return event;
}

Thank you! I would really appreciate it!

When exactly does the user need to enter the bike size again? After restart / reset of Arduino? Or do you want the user to double click only once?

buttons do not have a memory ... there is nothing to forget ... the program has to respond to a button press depending on the state the program is in

Yes, after the reset. I want the user to tap until his size and double tap to save the size.
After that the bike size part shouldnt come across ever again, well of course if you reset it, but that wont be the case.
After you choose the size the button will now work as a skip function.
I basically want to change the function of a button.

jsotola wrote a very important term in the comments: state.
You should implement your project as a Finite State Machine (FSM), a very important and powerful, yet easy principle. You divide your program into different states. Each state contains code, that only gets executed, when the program is in this state. Depending on input events (like the user pressing the button), you do transitions between the states.
I already wrote a rather detailed answer about FSMs for this question. You can read it to get a better understanding of FSMs.
For your case I would suggest these states: INPUT_SIZE, DISPLAY_SPEED, DISPLAY_CLOCK and DISPLAY_TEMPERATURE. INPUT_SIZE is the initial state (which you might skip after the first power on, after you saved the size in persistent memory like EEPROM). There you execute your current button code. When you sense a double tap on the button, you change to the DISPLAY_SPEED state. From there on a button press to the DISPLAY_CLOCK state and so on.
In my linked answer I used a simple integer variable as state variable, which holds the current state. In fact it is better (easier to read), when you define an enum for the cases (enums are actually only named integer constants):
enum State {INPUT_SIZE, DISPLAY_SPEED, DISPLAY_CLOCK, DISPLAY_TEMPERATURE};

State state = INPUT_SIZE;

void loop(){
    switch(state){
        case INPUT_SIZE:
            // Button code here
            // on double tap use the following line
            state = DISPLAY_SPEED;
            break;
        case DISPLAY_SPEED:
            // code for displaying speed here
        ...
    }
}

That is just a little template for the structure. You need to fill it with life yourself.

Yes, exactly what I needed. Alright, thank you, I will study it, look online and try to implement it
THANK YOU

What you likely need is a state machine. The behavior of the actions depends on the state the program is currently in.
In your case, the state machine might look like this:

What does it mean?

black circle: this is where the system powers on
rectangle: a state
arrow: a transition from one state to another
green text: action

For the problematic double click action, you can see:

it changes the state from "set size" to "speed"
in all other cases, it does not change the state (actually it changes the state to the same state)

I always recommend drawing the state machine before implementing it. It makes mistakes much more obvious.
There are several ways to implement it. The easiest one being a switch/case. More advanced implementations may use object orientation. When using switch/case, I prefer to have one method per state, like so:
void loop()
{
    switch(state):
        case setsize:
             setsize();
             break;
        case speed:
             speed();
             break;
        ...
}

If you know about function pointers, it gets even easier:
enum State {
  setsize = 0,
  speed,
  clock,
  temperature
};

State state;

void setup() {
  state = State::setsize;
}

typedef void (* functionPointer) ();
functionPointer process[] = {do_setsize, do_speed, do_clock, do_temperature};
void loop() {
  process[state]();
}

void do_setsize()
{
  state = State::speed;
}
void do_speed()
{
  state = State::clock;
}
void do_temperature()
{
  state = State::speed;
}
void do_clock()
{
  state = State::temperature;
}

Thank you. I managed to get it to work. Thank you!


text:
Program for counting days
I need a program to count days, from day 1 to day 21 for my project.
I'm making an artificial incubator and I need to show the days on an LCD.

Don't shout, use punctuation to start with. What part you need help with? Counting days in what sense? (with a for loop, or using a real time clock?) Be more precise in your requirements. What do you mean with 'like so' ?

google: "DS3231 Arduino". DS3231 is an Real Time Clock module which allows you to keep track of time and date.

If it doesn't need to be very accurate, you can use millis()

For what it's worth, one day is just 86400000 milliseconds.

You can do that easily using Real Time Clock IC. ds1307/ds3231 ic will do the job. Adafruit has Arduino library for that. easy to interface.
I don't supprt using millis() function. you will lose your time if the system power downs or mcu resets. Using RTC chip is safe option as it has backup battery for time keeping.


text:
Two Reed switch in two way directions
Hi im a student having problem in coding
I  want to set two reed switch in two direction.
Example : 1. Reed switch 1 detect then reed switch 2 detect - led turns to yellow
2.If reed switch 2 detect first then reed switch 1 detect - led turns to red
 It should play in sequentially form. Can help me in coding?
So far i have done this..
const int REED_PIN1 = 2; // Pin connected to reed switch const int REED_PIN2 = 3; // Pin connected to reed switch

const int RED = 9; // LED pin - active-high const int GREEN = 10; // LED pin - active-high const int YELLOW = 11; // LED pin - active-high

int up = 0; int down = 0;

void setup() { Serial.begin(9600); // Since the other end of the reed switch is connected to ground, we need // to pull-up the reed switch pin internally. pinMode(REED_PIN1, INPUT_PULLUP); pinMode(REED_PIN2, INPUT_PULLUP);

pinMode(RED, OUTPUT); pinMode(GREEN, OUTPUT); pinMode(YELLOW, OUTPUT);

digitalWrite(RED, LOW);
digitalWrite(GREEN, HIGH);
digitalWrite(YELLOW, LOW);
}

void loop() { int proximity1 = digitalRead(REED_PIN1); // Read the state of the switch int proximity2 = digitalRead(REED_PIN2); // Read the state of the switch while (proximity1 == LOW) // If the pin reads low, the switch is closed. {

up  = up  + 1;
Serial.print(up);
Serial.print("        ");
Serial.println(down);

if(down < 1){
digitalWrite(RED, LOW);
digitalWrite(GREEN, LOW);
digitalWrite(YELLOW, LOW);

delay(1000);
}

else {
digitalWrite(RED, LOW);
digitalWrite(GREEN, LOW);
digitalWrite(YELLOW, LOW);

delay(1000);
}
} while (proximity2 == LOW) // If the pin reads low, the switch is closed. { up = up - 1; Serial.print(up); Serial.print(" "); Serial.println(down); if(up < 1 && down < 1){ digitalWrite(RED, LOW); digitalWrite(GREEN, LOW); digitalWrite(YELLOW, HIGH);

delay(3000);      }
else{
digitalWrite(RED, LOW);
digitalWrite(GREEN, LOW);
digitalWrite(YELLOW, LOW);

delay(1000);
}
} while (proximity2 == LOW) // If the pin reads low, the switch is closed. { down = down + 1; Serial.print(up); Serial.print(" "); Serial.println(down);

if(up > 1){
digitalWrite(RED, LOW);
digitalWrite(GREEN, LOW);
digitalWrite(YELLOW, HIGH);

delay(1000);
}

else {
digitalWrite(RED, LOW);
digitalWrite(GREEN, LOW);
digitalWrite(YELLOW, LOW);

delay(1000);
}
delay(1000);
}
while (proximity1 == LOW) ;// If the pin reads low, the switch is closed. { down = down - 1; Serial.print(up); Serial.print(" "); Serial.println(down); if(up < 1 && down > 1){ digitalWrite(RED, HIGH); digitalWrite(GREEN, LOW); digitalWrite(YELLOW, LOW);

delay(5000);      }
else{
digitalWrite(RED, LOW);
digitalWrite(GREEN, LOW);
digitalWrite(YELLOW, LOW);
delay(5000);} } }

your code is really badly formatted ... do yourself a favor and format your code so that it is readable ... it will help you immensely with program creation and with debugging

Your code is a mess. Not only is it badly formatted, but because it's badly formatted you've lost all track of your brackets, and now it's all over the place. Half the code isn't even in a function any more.

I think, you don't understand, how while loops are written in C/C++. You can google that, to correct that part of the code. I'm pretty sure, that your current code would throw compilation errors. You can use these to fix the most urgent problems with the code. I started with the pattern "Code something, compile it, correct the errors, compile again, repeat until no errors occur".

Sorry, but your code is complete nonsense. The following code gives you an example. I have no access to a compiler at the moment, so there might be syntax errors and it is completely untested. Also, you gave no complete description of the things you want to do. e.g when to switch on the green LED or what the up and down variables are for.
And there might also be timing problems. In order not to miss a reed state change,
you should avoid adding delays and slow serial print outs.
I'm pretty sure, I did your homework. So my advice is to learn programming and try to understand. Homework was not ( only ;-) ) invented to enjoy the teacher, they help you through tests. ;-)
Your problem is similar to the decoding of a rotary encoder, so information about this subject might help you also.
const int REED_PIN1 = 2;
const int REED_PIN2 = 3;

// LED pins - active-high
const int RED    =  9;
const int GREEN  = 10;
const int YELLOW = 11;

int fixedState1 = HIGH;
int fixedState2 = HIGH;

void setup()
{
   // If the pin reads low, the switch is closed.
   pinMode(REED_PIN1, INPUT_PULLUP);
   pinMode(REED_PIN2, INPUT_PULLUP);

   pinMode(RED, OUTPUT);
   pinMode(GREEN, OUTPUT);
   pinMode(YELLOW, OUTPUT);

   digitalWrite(RED, LOW);
   digitalWrite(GREEN, HIGH);
   digitalWrite(YELLOW, LOW);
}

void loop()
{
  // AS LONG AS BOTH SWITCHES ARE ON AT THE SAME TIME,
  // THE PROGRAM FLIPS OUT ;-)
  int reedState1 = digitalRead( REED_PIN1 );
  int reedState2 = digitalRead( REED_PIN2 );

  if ( readState1 == LOW && fixedState1 == HIGH )
  {
    if ( fixedState2 == LOW )
    {
      digitalWrite( RED,    HIGH );
      digitalWrite( YELLOW, LOW  );
      digitalWrite( GREEN,  LOW  );

      fixedState2 = HIGH;
    }
    else
    {
      // setting the green LED is just a guess
      digitalWrite( RED,    LOW  );
      digitalWrite( YELLOW, LOW  );
      digitalWrite( GREEN,  HIGH );

      fixedState1 = LOW;
    }
  }

  if ( readState2 == LOW && fixedState2 == HIGH )
  {
    if ( fixedState1 == LOW )
    {
      digitalWrite( RED,    LOW  );
      digitalWrite( YELLOW, HIGH );
      digitalWrite( GREEN,  LOW  );

      fixedState1 = HIGH;
    }
    else
    {
      // setting the green LED is just a guess
      digitalWrite( RED,    LOW  );
      digitalWrite( YELLOW, LOW  );
      digitalWrite( GREEN,  HIGH );

      fixedState2 = LOW;
    }
  }
}

Your code is so badly formatted it makes it very difficult to follow.
A couple of things that jump out at me:
You never set REED_PIN1 or REED_PIN2 to INPUT_PULLUP mode. You should do that in setup.
You have the code that deals with REED_PIN2 commented out so that can't possibly work.
I took a first crack at improved code formatting. There result is below:
const int REED_PIN1 = 2; // Pin connected to reed switch const
int REED_PIN2 = 3; // Pin connected to reed switch

const int RED = 9; // LED pin - active-high
const int GREEN = 10; // LED pin - active-high
const int YELLOW = 11; // LED pin - active-high

int up = 0; int down = 0;

void setup() {
    Serial.begin(9600);
    // Since the other end of the reed switch is connected to ground, we need
    // to pull-up the reed switch pin internally.
    pinMode(REED_PIN1, INPUT_PULLUP);
    pinMode(REED_PIN2, INPUT_PULLUP);

    pinMode(RED, OUTPUT); pinMode(GREEN, OUTPUT); pinMode(YELLOW, OUTPUT);

    digitalWrite(RED, LOW);
    digitalWrite(GREEN, HIGH);
    digitalWrite(YELLOW, LOW);
}

void loop() {
    int proximity1 = digitalRead(REED_PIN1); // Read the state of the switch
    int proximity2 = digitalRead(REED_PIN2); // Read the state of the switch while (proximity1 == LOW) // If the pin reads low, the switch is closed.

    up  = up  + 1;
    Serial.print(up);
    Serial.print("        ");
    Serial.println(down);

    if(down < 1) {
        digitalWrite(RED, LOW);
        digitalWrite(GREEN, LOW);
        digitalWrite(YELLOW, LOW);

        delay(1000);
    }

    else {
        digitalWrite(RED, LOW);
        digitalWrite(GREEN, LOW);
        digitalWrite(YELLOW, LOW);

        delay(1000);
    }
} while (proximity2 == LOW) { // If the pin reads low, the switch is closed.
    up = up - 1;
    Serial.print(up);
    Serial.print(" ");
    Serial.println(down);
    if (up < 1 && down < 1) {
        digitalWrite(RED, LOW);
        digitalWrite(GREEN, LOW);
        digitalWrite(YELLOW, HIGH);

        delay(3000);
    }
    else {
        digitalWrite(RED, LOW);
        digitalWrite(GREEN, LOW);
        digitalWrite(YELLOW, LOW);

        delay(1000);
    }
} while (proximity2 == LOW) { // If the pin reads low, the switch is closed.
    down = down + 1;
    Serial.print(up);
    Serial.print(" ");
    Serial.println(down);

    if(up > 1) {
        digitalWrite(RED, LOW);
        digitalWrite(GREEN, LOW);
        digitalWrite(YELLOW, HIGH);

        delay(1000);
    }

    else {
        digitalWrite(RED, LOW);
        digitalWrite(GREEN, LOW);
        digitalWrite(YELLOW, LOW);

        delay(1000);
    }
    delay(1000);
}
while (proximity1 == LOW) { // If the pin reads low, the switch is closed.
    down = down - 1;
    Serial.print(up);
    Serial.print(" ");
    Serial.println(down);
    if (up < 1 && down > 1) {
        digitalWrite(RED, HIGH);
        digitalWrite(GREEN, LOW);
        digitalWrite(YELLOW, LOW);
        delay(5000);      }
    else{
        digitalWrite(RED, LOW);
        digitalWrite(GREEN, LOW);
        digitalWrite(YELLOW, LOW);
        delay(5000);

    }
}

EDIT:
After a first pass at code formatting I found the lines that are supposed to set up your REED_PIN1 and REED_PIN2 as inputs. That code got swallowed into a comment, so I didn't see it.
(Everything after a // until the end of the line is a comment. You can't put the opening curly brace for a while or an if statement after a comment.)
Don't put statements on the same line as an opening brace. Don't put multiple statements on a line. Every time you enter a new level of scope (inside another set of curly braces) increase your indentation level)
These are pretty firm conventions for code formatting. There's some debate on the margins for things like where to put your braces and how many blank lines to use, but your code violates the basics of readability all over the place.

I have tried the coding and readjust it but i dont get the output

I need the output like this Example : 1. Reed switch 1 detect then reed switch 2 detect - led turns to yellow 2.If reed switch 2 detect first then reed switch 1 detect - led turns to red It should play in sequentially form

Is like car goes in one way road and what happend if the car enter in the one way from opposite site

I can't make much sense of your twisted syntax.


text:
MAX30003 using Arduino
I am doing project on Single-lead ECG & Heart rate Variability using MAX30003 using Arduino.  I have added the code for this project also. Can anyone please tell me how to include Timer.h library. I am getting following error:

F:\TRACKER WAVE\MAX INT\max
  ard\Protocentral-protocentral_max30003-v0.1-12-ge141d22
  (1)\Protocentral-protocentral_max30003-e141d22\software\protocentral_max30003_arduino\protocentral_max30003\protocentral_max30003.ino:34:22:
  fatal error: TimerOne.h: No such file or directory
#include
compilation terminated.
exit status 1 Error compiling for board Arduino/Genuino Uno.

The code is here:
#include<SPI.h>
#include <TimerOne.h>
#include "MAX30003.h"

#define MAX30003_CS_PIN   7
#define CLK_PIN          6

volatile char SPI_RX_Buff[5] ;
volatile char *SPI_RX_Buff_Ptr;
int i=0;
unsigned long uintECGraw = 0;
signed long intECGraw=0;
uint8_t DataPacketHeader[20];
uint8_t data_len = 8;
signed long ecgdata;
unsigned long data;

char SPI_temp_32b[4];
char SPI_temp_Burst[100];

// 32KHz clock using timer1
void timerIsr()
{
    digitalWrite( CLK_PIN, digitalRead(CLK_PIN ) ^ 1 ); // toggle Digital6 attached to FCLK  of MAX30003
}

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

    pinMode(MAX30003_CS_PIN,OUTPUT);
    digitalWrite(MAX30003_CS_PIN,HIGH); //disable device

    SPI.begin();
    SPI.setBitOrder(MSBFIRST);
    SPI.setDataMode(SPI_MODE0);

  //please enable the below lines if you are using older version of Protocentral_max30003 board without 32k f-clock generator
    /*SPI.setClockDivider(SPI_CLOCK_DIV4);
    pinMode(CLK_PIN,OUTPUT);

     //Start CLK timer
    Timer1.initialize(16);              // set a timer of length 100000 microseconds (or 0.1 sec - or 10Hz => the led will blink 5 times, 5 cycles of on-and-off, per second)
    Timer1.attachInterrupt( timerIsr ); // attach the service routine here
*/
    MAX30003_begin();   // initialize MAX30003
}

void loop()
{
    MAX30003_Reg_Read(ECG_FIFO);

    unsigned long data0 = (unsigned long) (SPI_temp_32b[0]);
    data0 = data0 <<24;
    unsigned long data1 = (unsigned long) (SPI_temp_32b[1]);
    data1 = data1 <<16;
    unsigned long data2 = (unsigned long) (SPI_temp_32b[2]);
    data2 = data2 >>6;
    data2 = data2 & 0x03;

    data = (unsigned long) (data0 | data1 | data2);
    ecgdata = (signed long) (data);

    MAX30003_Reg_Read(RTOR);
    unsigned long RTOR_msb = (unsigned long) (SPI_temp_32b[0]);
   // RTOR_msb = RTOR_msb <<8;
    unsigned char RTOR_lsb = (unsigned char) (SPI_temp_32b[1]);

    unsigned long rtor = (RTOR_msb<<8 | RTOR_lsb);
    rtor = ((rtor >>2) & 0x3fff) ;

    float hr =  60 /((float)rtor*0.008);
    unsigned int HR = (unsigned int)hr;  // type cast to int

    unsigned int RR = (unsigned int)rtor*8 ;  //8ms

     /*Serial.print(RTOR_msb);
     Serial.print(",");
     Serial.print(RTOR_lsb);
     Serial.print(",");
     Serial.print(rtor);
     Serial.print(",");
     Serial.print(rr);
     Serial.print(",");
     Serial.println(hr);      */

      DataPacketHeader[0] = 0x0A;
      DataPacketHeader[1] = 0xFA;
      DataPacketHeader[2] = 0x0C;
      DataPacketHeader[3] = 0;
      DataPacketHeader[4] = 0x02;

      DataPacketHeader[5] = ecgdata;
      DataPacketHeader[6] = ecgdata>>8;
      DataPacketHeader[7] = ecgdata>>16;
      DataPacketHeader[8] = ecgdata>>24;

      DataPacketHeader[9] =  RR ;
      DataPacketHeader[10] = RR >>8;
      DataPacketHeader[11] = 0x00;
      DataPacketHeader[12] = 0x00;

      DataPacketHeader[13] = HR ;
      DataPacketHeader[14] = HR >>8;
      DataPacketHeader[15] = 0x00;
      DataPacketHeader[16] = 0x00;

      DataPacketHeader[17] = 0x00;
      DataPacketHeader[18] = 0x0b;

      for(i=0; i<19; i++) // transmit the data
      {
        Serial.write(DataPacketHeader[i]);

       }

    delay(8);
}

void MAX30003_Reg_Write (unsigned char WRITE_ADDRESS, unsigned long data)
{

    // now combine the register address and the command into one byte:
     byte dataToSend = (WRITE_ADDRESS<<1) | WREG;

     // take the chip select low to select the device:
     digitalWrite(MAX30003_CS_PIN, LOW);

     delay(2);
     SPI.transfer(dataToSend);   //Send register location
     SPI.transfer(data>>16);     //number of register to wr
     SPI.transfer(data>>8);      //number of register to wr
     SPI.transfer(data);      //Send value to record into register
     delay(2);

     // take the chip select high to de-select:
     digitalWrite(MAX30003_CS_PIN, HIGH);
}

void max30003_sw_reset(void)
{
    MAX30003_Reg_Write(SW_RST,0x000000);
    delay(100);
}

void max30003_synch(void)
{
    MAX30003_Reg_Write(SYNCH,0x000000);
}

void MAX30003_Reg_Read(uint8_t Reg_address)
{
    uint8_t SPI_TX_Buff;

    digitalWrite(MAX30003_CS_PIN, LOW);

    SPI_TX_Buff = (Reg_address<<1 ) | RREG;
    SPI.transfer(SPI_TX_Buff); //Send register location

    for ( i = 0; i < 3; i++)
    {
       SPI_temp_32b[i] = SPI.transfer(0xff);
    }

    digitalWrite(MAX30003_CS_PIN, HIGH);
}

void MAX30003_Read_Data(int num_samples)
{
    uint8_t SPI_TX_Buff;

    digitalWrite(MAX30003_CS_PIN, LOW);

    SPI_TX_Buff = (ECG_FIFO_BURST<<1 ) | RREG;
    SPI.transfer(SPI_TX_Buff); //Send register location

    for ( i = 0; i < num_samples*3; ++i)
    {
      SPI_temp_Burst[i] = SPI.transfer(0x00);
    }

    digitalWrite(MAX30003_CS_PIN, HIGH);
}

void MAX30003_begin()
{
    max30003_sw_reset();
    delay(100);
    MAX30003_Reg_Write(CNFG_GEN, 0x081007);
    delay(100);
    MAX30003_Reg_Write(CNFG_CAL, 0x720000);  // 0x700000
    delay(100);
    MAX30003_Reg_Write(CNFG_EMUX,0x0B0000);
    delay(100);
    MAX30003_Reg_Write(CNFG_ECG, 0x805000);  // d23 - d22 : 10 for 250sps , 00:500 sps
    delay(100);

    MAX30003_Reg_Write(CNFG_RTOR1,0x3fc600);
    max30003_synch();
    delay(100);
}

some parts of your code are properly formatted ..  the rest is not ... why are you not asking how to format the code?

Nowadays, the Arduino IDE has a Library Manager helping to properly install and add libraries to projects. Perhaps you remove TimerOne manually and add it again using that tool. (Manager, then Sketch -> include Library )