text:
Why my loop stop working
i have an arduino, an RTC (time), a DHT (humidity and temp sensor), oled screen (128x32 ; microoled 1306) and 4 relais ;
all seems to work perfectly for hours, but sometime (1 or 2 per day..) everything stop working ;

screen i frozen on last info displayed
relais stay stuck in a random position (somtimes turning everythings ON (on=LOW with thoses relay.))

i obviously made a mistake, but don t know what...
what can cause a loop to stay stuck randomly ???
plz save me :)
EDIT => A REWORK OF THAT TERRIBLE CODE AVAILABLE IN ANSWER, THE PROBLEM IS STILL THERE
// GND GND
// A4 SCL
// A5 SDA
// VCC  5V

// for DHT11,
//      VCC: 5V or 3V
//      GND: GND
//      DATA: A7+

// YL-39 + YL-69 humidity sensor
const byte humidity_sensor_pin = A1;
const byte humidity_sensor_vcc = 6;

// ecran SDA / SDL
// RELAIS Pin D8
// RELAIS2 Pin D9
// RELAIS3 Pin D10
// RELAIS4 Pin D11

// Relais reboot D5 ?

#include <SimpleDHT.h>
#include <Wire.h>
#include "U8glib.h"
#include "RTClib.h"

const int pinDHT11 = 7;
 SimpleDHT11 dht11;

RTC_DS1307 RTC;
U8GLIB_SSD1306_128X32 u8g(U8G_I2C_OPT_NONE);

const int relay = 8; // Light
const int relay2 = 9; // Wind
const int relay3 = 10; // Heat
const int relay4 = 11; // Humidity

// Time Variable
DateTime InitTime ;
int InitHour;

const int startHour = 20;
const int startMin = 01;
const int startTime = startHour *100 + startMin;
const int endHour = 8;
const int endMin = 01;
const int endTime= endHour *100 + endMin;
const int maxWind = 5;
const int startWind = 05;
int lastWind ;

const int dayMinTemp = 18;
const int dayMaxTemp = 20;
const int nightMinTemp = 16;
const int nightMaxTemp = 19;

const int minhum = 50;

void drawInit(DateTime InitD){
String text = String(InitD.day());
  text += " ";
text += String(InitD.month());

String text2 = String(InitD.hour());
  text2 += ":";
text2 += String(InitD.minute());
text2 += ":";
text2 += String(InitD.second());

 u8g.setFont(u8g_font_unifont);
  u8g.setPrintPos(0,16);
  u8g.print(text);
  u8g.setPrintPos(0,32);
  u8g.print(text2);

}
void drawTemp(float temp, int hum, int nowT){
String text = "Temp: ";
  text += temp;
    text += "*C";
String text2 = "Hum: ";
  text2 += hum;
    text2 += "% :";
    text2 += nowT;

 u8g.setFont(u8g_font_unifont);
  u8g.setPrintPos(0,16);
  u8g.print(text);
  u8g.setPrintPos(0,32);
  u8g.print(text2);
}

void draw(String staT, String endT, String nowT){
String iotxt;
if (digitalRead(relay) == LOW){iotxt="On";}else{iotxt="Off";}

String text = "S: ";
  text += staT;
  text += " E: ";
  text += endT;
String text2 = "H: ";
  text2 += nowT;
//  text2 += " L: ";
//  text2 += iotxt;

  u8g.setFont(u8g_font_unifont);
  u8g.setPrintPos(0,16);
  u8g.print(text);
  u8g.setPrintPos(0,32);
  u8g.print(text2);
}

void drawerror(String error){
  String text = "err mod: ";
  text += error;

  u8g.setFont(u8g_font_unifont);
  u8g.setPrintPos(0,16);
  u8g.print(text);

}

void draw2(int nowTime){
  String iotxt;
  String hottxt;
  String lumtxt;
    String humtxt;

if (digitalRead(relay) == LOW){lumtxt="On";}else{lumtxt="Off";}
if (digitalRead(relay2) == LOW){iotxt="On";}else{iotxt="Off";}
if (digitalRead(relay3) == LOW){hottxt="On";}else{hottxt="Off";}
if (digitalRead(relay4) == LOW){humtxt="On";}else{humtxt="Off";}

String text = "Hot: ";
  text += hottxt;
  text += " Lum: ";
  text += lumtxt;

String text2 = "Hum: ";
  text2 += humtxt;
  text2 += " Win: ";
  text2 += iotxt;

  u8g.setFont(u8g_font_unifont);
  u8g.setPrintPos(0,16);
  u8g.print(text);
  u8g.setPrintPos(0,32);
  u8g.print(text2);
}

void setup () {

 pinMode(relay, OUTPUT);
 pinMode(relay2, OUTPUT);
 pinMode(relay3, OUTPUT);
 pinMode(relay4, OUTPUT);
 digitalWrite(relay, HIGH);
 digitalWrite(relay2,HIGH);
 digitalWrite(relay3,HIGH);
 digitalWrite(relay4,HIGH);

    Serial.begin(9600);
    Wire.begin();

    if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }
  RTC.begin();

   DateTime now = RTC.now();
 InitTime = now ;
InitHour =  now.hour()*100 + now.minute();
}

void loop () {

 byte temperature = 0;
  byte humidity = 0;

int err = SimpleDHTErrSuccess;
  if ((err = dht11.read(pinDHT11, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
//    Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);

    u8g.firstPage();
  do {
    drawerror("DHT");
  } while( u8g.nextPage() );
delay(3000);

    return;
  }else{

  // Serial.print("Sample OK: ");
 // Serial.print((int)temperature); Serial.print(" *, ");
 // Serial.print((int)humidity); Serial.println(" H");

// Relay Chaleur
if (digitalRead(relay)==LOW){
if((int)temperature < dayMinTemp){
   digitalWrite(relay3,LOW);
   //  Serial.print("HEAT : On");

  }else{digitalWrite(relay3,HIGH);
     //  Serial.print("HEAT : Off");
}
  }else{
    if((int)temperature < nightMinTemp){
   digitalWrite(relay3,LOW);
     //   Serial.print("HEAT : On");

}else{
      digitalWrite(relay3,HIGH);
   //  Serial.print("HEAT : Off");

      }
    }
// fin relay chaleur

  if (! RTC.isrunning()) {
    drawerror("RTC");}else{

   DateTime now = RTC.now();

int nowTime= now.hour()*100 + now.minute();

// § WIND
if(now.minute() >= startWind && now.minute() <= startWind+maxWind ){
      digitalWrite(relay2,LOW);
     // Serial.println("Wind ON");
      lastWind = nowTime;

  }else if(now.minute()>startWind+5 || now.minute()<startWind){
          digitalWrite(relay2,HIGH);
    //  Serial.println("Wind OFF");
      }

// § END WIND

// START humidity
if(int(humidity)<minhum){
      digitalWrite(relay4,LOW);

  }else{    digitalWrite(relay4,HIGH);
  }
//
// § LIGHT START

if(startTime<endTime){
  if(startTime <= nowTime && endTime >= nowTime){
      digitalWrite(relay,LOW);
    //  Serial.println("Light ON");
  }else{
      digitalWrite(relay,HIGH);
//      Serial.println("Light OFF");
}}else{
  if(endTime <= nowTime && startTime >= nowTime){

      digitalWrite(relay,HIGH);
  //    Serial.println("Light OFF");
  }else{
          digitalWrite(relay,LOW);
    //  Serial.println("Light ON");
    }}

//  if(nowTime >= startTime && nowTime <= 2359){
//            digitalWrite(relay, LOW);
//            Serial.println("Light ON");
//            }
//       else if(nowTime  < endTime ){
//            digitalWrite(relay, LOW);
//            Serial.println("LIGHT ON");}
//       else if(nowTime  >= endTime && nowTime  < startTime){
//            digitalWrite(relay, HIGH);
//            Serial.println("Light OFF");}
//      }
      // § LIGHT END

u8g.firstPage();
  do {
    draw(String(startTime),String(endTime),String(nowTime));
  } while( u8g.nextPage() );
delay(3000);

u8g.firstPage();
  do {
    drawInit(InitTime);
  } while( u8g.nextPage() );
 delay(3000);

u8g.firstPage();
  do {
    draw2(nowTime);
  } while( u8g.nextPage() );
 delay(3000);
u8g.firstPage();
  do {
    drawTemp(float(temperature), int(humidity),int(NowT));
  } while( u8g.nextPage() );
 delay(3000);
    }}}

you may want to fix your identation, that will help clarify the logic flow of each function

I present you the "?:" operator: lumtxt = digitalRead(relay) ? "On" : "Off";

At a quick guess I'd say your heap is swiss cheese. Ditch String.

i will rework that to made it more digest xD sry, let me few min :)

@Look Alterno  : thx i will check this and implement it :)

your code is horribly formatted ... it is a mess ... it is very difficult to determine how all the parts interact

@jsotola : u are totaly alright, i rewrite it totaly, hoping the same hlp, don t hesitate to bring me comments on the new one, :) (if problem there is, try to give me some tips :) i m a nooby amateur dev. )

While it makes logical sense to use the String type to hold strings of text, it's really a very poor choice for a low-RAM device like an Arduino.
You are using the string concatenation operator (+) a lot. The String type handles this by grabbing a new block of RAM that is equal to the sum of the 2 strings you are concatenating, puts the new string in that RAM, and marks the previous block of RAM that held one of the strings as empty and available for re-use.
The problem is that when you keep concatenating bits to the same string variable, it has to keep finding longer and longer continuous blocks of RAM into which to put the new string. All the previous blocks that are "available" for use, are also too short, as they are all the length of previous strings prior to your new, longer string requirement.
As @Majenko noted, this means your RAM is "swiss cheese" -- full of holes that can't be used by the program for more strings.
One solution is to avoid the String variable type and instead use what are called C-Style Strings - arrays of char type. It's a whole new, old world of doing things, and can be more challenging than the String type, but it has a distinct advantage of not shredding the device's RAM.
The C-style string world is ruled by monsters like strnlen() and strncpy(), and making sure you have remembered to allocate enough RAM at the start of your program, and making sure you null-terminate your array.
Of the myriad tutorials and descriptions on using C-style strings, one is at https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

Are you saying that Arduino doesn't merge back contiguous RAM blocks?

No, but often some other action takes place that puts another block on the heap.

That s seem s realy logical ! i will dig this and apply the change :)

arf, till a small problem, i don t achieve to concat in any way my char[] and my INT :/
char screen[16] ;
char text[3] = "abc" ;
int i = 12 ;
screen[16] = text + i ;

You can't use + to concat c-style strings. Use strncat().

Also, you'll need to convert your int to a char[] (C-style string) using something like itoa()

@jose can u c : yep, the conversion put me in mess few hours :) but i think i deal with it, it probably can be improve anw, but sadly, the problem remains...

after rewrite all code, rewire all relay, bypass the relay card (using another relay), the problem is still there, but i finally found other people with the same problem, and the solution seem to be adding a "snubber" on each relay, i m waiting for it and will give u a return if it work :
link to arduino forum for a common problem


text:
Strange discrete errors when reading HC-SR04 sonar sensor
I'm experimenting with an HC-SR04 sonar sensor. Basically I'm measuring the distance to a cardboard box twice a second with these lines of code running on an ESP32:
unsigned long sonarMeasure() {
    digitalWrite(TRIGGER, HIGH);
    delayMicroseconds(10);
    digitalWrite(TRIGGER, LOW);
    return pulseIn(ECHO, HIGH);
}

double distance = duration * 0.03455;

The results are a bit strange. I know, that I can't expect millimeter accuracy. But why are there rather discrete jumps of about 4 mm? And when looking closer, there is another frequent jump of <1mm:

(As far as I can tell, the jumps increase at larger distances.)
Is this an issue of how I read the sensor on the ESP32, or is it something happening internally on the HC-SR04?
I'd love to understand the reason for this effect to be able to improve the accuracy of my measurements.

And how exactly are you calculating the distance?

@gre_gor: double distance = duration * 0.03455 (I'll add it to my question.)

I think it's from the HC-SR04... it uses echos and it seems your bad readings are some kind of echo reflections.
What you should do is either remove the bad readings, or take the average/most common value of the last x readings.
Or throw away values too far off some default (like the last average) and average the rest.

Sure, I could implement some kind of filter. But actually I want to use it on a moving platform, so I can't repeat any measurement.

No, the spacing is much to small to be multiple reflections.  For that to occur, you'd be seeing multiples of the base reading, rather than a distribution around a basic value.

source: Stack Exchange

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

sort: votes


text:
RPM measurement using quadrature encoder
I am trying to build a RPM controller for my project. I am using a quadrature encoder (ppr=400) and Arduino Uno for this purpose. I am using the code given below inorder to caluculate the RPM of the DC motor. I get a reading on my serial Monitor. However, this RPM doesn't match with my manual calculation (i.e when I calculate the RPM Manually using a stop watch- for lower speeds).
EDIT-> Eg- Manually I get around 10 RPM, but my program shows 60 and more.
I have used one interrupt pin on my Arduino UNO.
#define encoder0PinA  2
#define encoder0PinB  3
int power=6; // to power up the encoder
int gnd=4;  // to provide ground to the encoder
int motor=11; //motor PWM pin
int dir=10;
volatile unsigned int encoder0Pos = 0;

void setup() {
  pinMode(encoder0PinA, INPUT);
  digitalWrite(encoder0PinA, HIGH);       // turn on pull-up resistor
  pinMode(encoder0PinB, INPUT);
  digitalWrite(encoder0PinB, HIGH);       // turn on pull-up resistor
  pinMode(power,OUTPUT);
  pinMode(gnd,OUTPUT);
  digitalWrite(power,HIGH);
  digitalWrite(gnd,LOW);
  pinMode(motor,OUTPUT);
  pinMode(dir,OUTPUT);
  digitalWrite(dir,LOW);

  attachInterrupt(0, doEncoder, RISING);  // encoder pin on interrupt 0 - pin 2
  Serial.begin (9600);
  Serial.println("start");    // a personal quirk
  analogWrite(motor,120); // to set a particular test RPM to the motor.
}

void loop() {
  encoder0Pos=0;
  delay(1000);
  float rpm=encoder0Pos/(400);
  Serial.println(rpm);
}

void doEncoder() {

  encoder0Pos++;
  }

Also I tried the very first code on the following link "https://playground.arduino.cc/Main/RotaryEncoders".. In this case my Arduino stops transmitting completely. I tried the same code on one of my friend's setup.. surprisingly it works there.
Can't understand where I am going wrong... Is my coding approach correct?? Please enlighten me...
Thank you.

When you say your calculation doesn't match -- please describe the values each produces. There are many ways in which something can "not work"

sure sir, I will edit it ASAP.

Is your quadrature encoder optical or mechanical?

It's an optical quadrature encoder

Encoder link- https://m.aliexpress.com/item/32816515228.html

Ensure the encoder outputs 400 pulses on each phase. It could be 200 on each phase for one rotation
Rather then clearing your pulseCount, figure out the time it take to make one rotation (as close as you can tell) and turn the motor on for only that amount of time, and then off again. This will allow you a more controlled environment to test your code in, and it will be the same(almost) every time.
You are calculating revolutions per second with your code, not per min
number of pulses/400(if this is correct number)=Revolutions     which you are clearing ever 1000ms
Ensure good connections on your wiring as it does not take much to allow the interrupt to fire twice when it should have only fired once.
Use the second phase of the encoder, this is what gives the ability to decipher bad signals and change of dirrection,   ie- multiple A pulses in a row(without any B pulse) does not equal movement, it means either the motor is hanging out right on a phase line, or something is causing the interrupt to fire more often then it should.

Why is the code from Arduino playground not working?

Getting direction is not an issue for me... Getting Rpm or RPS is my main concern..

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


text:
avr/io.h No such file or directory error when compiling using avr-gcc
I am trying to use the atmega328p as standalone microchip and program it. I ama using an Arduino Uno as ISP. I have written a simple program to test it however when I try to compile it using
avr-gcc -mmcu=atmega328p -o main.out main.c

I get the error:
main.c:1:20: fatal error: avr/io.h: No such file or directory
compilation terminated.

I am running OpenSUSE Leap 42.3 and i have installed avr-gcc, avr-libc.
My code:
#include <avr/io.h>

int main() {
    DDRB = 1;
    PORTB = 1;
}

Thank you in advance!

Have you installed avr-libc?

You can use the Arduino IDE to compile such programs. What is the objection to doing that?

@NickGammon there are lots of reasons to avoid the IDE. https://christopherjmcclellan.wordpress.com/2018/02/16/test-driving-arduino/

OK., Arduino IDE is subpar, but the main goal, e.g. producing Arduino executables is flawless. Did you tried UECIDE (uecide.org)? Eclipse plugin? Netbeans plugins?

[Opinion piece] If you want a (IMHO, a million times) better dev environment than Arduino IDE then start using PlatformIO. Automatically generates project files for every possible IDE out there, downloads the compilers and frameworks you need, 'just works' without worries.

@RubberDuck - well ... the complaint about "the IDE" that SoftwareSerial disables interrupts is hardly the IDE's fault. And the IDE supports using a different editor. It's not the greatest IDE I've seen but it easily produces .hex files ready for uploading (and indeed uploads them if you want it to).

@NickGammon I’ll admit that’s more a complaint about Arduino than the Arduino IDE and yes, it’s pretty good at uploading, but you still can’t write & run tests unless you compile it yourself.

I’m guessing you started with the toolchain Arduino put on your machine.
Try explicitly including the header files on the include path with the -I switch.
avr-gcc -mmcu=atmega328p -I /path/to/avr/include -o main.out main.c

Just search for the io.h file. It should be somewhere close by to where you found the compiler.


text:
Error while uploading the sketch for Arduino Mini
I'm having a problem while uploading the program.
Arduino: 1.8.4 (Windows 10), Board: "Arduino Mini, ATmega328P"

Archiving built core (caching) in: C:\Users\UMME-K~1\AppData\Local\Temp\arduino_cache_566019\core\core_arduino_avr_mini_cpu_atmega328_3f323efdab4276426e9d8710d5d73f64.a
Sketch uses 3932 bytes (13%) of program storage space. Maximum is 28672 bytes.
Global variables use 250 bytes (12%) of dynamic memory, leaving 1798 bytes for local variables. Maximum is 2048 bytes.
D:\Amna\arduino-1.8.4\hardware\tools\avr/bin/avrdude -CD:\Amna\arduino-1.8.4\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\UMME-K~1\AppData\Local\Temp\arduino_build_808790/buzzer.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "D:\Amna\arduino-1.8.4\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

avrdude done.  Thank you.

An error occurred while uploading the sketch

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

What should I do?

how is the Mini connected to USB? (or serial port?)

has it ever worked?

Google "avrdude: stk500_getsync() attempt 1 of 10: not in sync" and the Truth will be revelated.

@Juraj through USB cable , serial port

doing it for the first time @jsotola...

connects the cable to Reset pin?

https://www.google.com.pk/search?biw=1366&bih=662&tbm=isch&sa=1&ei=guaHWq25IsG1gQbTuZnIDg&q=arduino+mini+program+upload&oq=arduino+mini+program+upload&gs_l=psy-ab.3...23636.28787.0.29006.15.15.0.0.0.0.330.1716.2-5j1.6.0....0...1c.1.64.psy-ab..9.6.1711...0j0i67k1j0i8i30k1j0i30k1.0.5aM_FwHjjdM#imgrc=p97hfh3t5iS8aM: @Juraj This is the arduino mini that im using and i have connected the data cable to it.. I am having issues while uploading the program. I think there is an issue with some driver or something if u know please let me know ....

On Uno and other boards with USB on board, for flashing the IDE resets the Atmega to bootloader, sending signal over USB. Mini has not an build in USB and you connected it with an USB to TTL cable. Has this cable a Reset signal line? If yes, did you connect this line to Reset pin?
If not, then you need to do a manual reset in the right moment when avrdude sends the hex file. I count to 9 after the first attempt and then I push the reset button.

Well Thanks for your answer...Highly appreciated ... Anyhow the issue is solved  ...

"If not, then you need to do a manual reset in the right moment when avrdude sends the hex file. I count to 9 after the first attempt and then I push the reset button."
In the IDE, if you select File:Preferences and turn on Verbose outputs, you can see when the IDE is about to download, there will appear "compiled xxx of 32xxx bytes), then3 attempts to download. If you press Reset when you see that message, or press & hold reset then release when you see that message, it is much easier to get the bootloader started at the right time (assuming one is actually loaded and there is nothing interfering with the signals on the D0/D1 pins).


text:
SOMETHING WRONG IN DHT22 PROGRAM showing error as expected unqualified id before'. ' token
I am using a arduino and dht22 sensor for my project purpose annd gettting error as expecte before unqualified '.' token
MY CODE IS :
#include <DHT.h>

#include <LiquidCrystal.h>
#include <SoftwareSerial.h>
#include <Wire.h>

#define DHTPIN 8
#define DHTTYPE DHT22

LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

int ldrpin=A0;
int ldr=0;

DHT dht(DHTPIN, DHTTYPE);

//
//
//
//
//
//
//
//

void setup()
    {

   lcd.begin(16, 2);
   Serial.begin (9600);
   DHT .begin();
     pinMode(ldrpin,INPUT);

}

//
//
//
//
//
//
//

void loop()
    {

  lcd.setCursor(0,0);

 //ldr
  ldr=analogRead(ldrpin);

//LDR DISPLAY
  Serial.println("LIGHT INTENSITY");
  Serial.println(ldr);
  Serial.print(" lx\t");
  delay(2000);

   lcd.clear();
    lcd.setCursor(0, 0);

   lcd.print("LIGHT INTENSITY");
    delay(200);
    lcd.print(ldr);
      delay(2000);

//dht22
delay(2000);

   int chk = DHT.read(DHTPIN);
    float humidity = DHT.humidity;
    float temperature = DHT.temperature;

//dht22 display
1.  Serial.println("Humidity: ");
2.    Serial.print(h);
3.    Serial.print(" %\t");
4.    Serial.println("Temperature: ");
5.    Serial.print(t);
  Serial.println(" *C ");

my error message is
Arduino: 1.6.4 (Windows 8.1), Board: "Arduino Uno"

LCD.ino: In function 'void setup()':
LCD:38: error: expected unqualified-id before '.' token
LCD.ino: In function 'void loop()':
LCD:80: error: expected primary-expression before '.' token
LCD:81: error: expected primary-expression before '.' token
LCD:82: error: expected primary-expression before '.' token
LCD:87: error: expected ';' before 'Serial'
LCD:88: error: expected ';' before 'Serial'
LCD:89: error: expected ';' before 'Serial'
LCD:90: error: expected ';' before 'Serial'
LCD:91: error: expected ';' before 'Serial'
expected unqualified-id before '.' token

This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.
some one help me please!!

Don’t shout. No need for an ALLCAPS title

Line 38, 80, 81, 82: DHT is a class name, dht is an instance of that class (an object, a variable), so write:
   dht.begin();

And all those call to DHT.something? Wrong too. Reemplaza DHT with dht.
All others errors: Why are you written "1. ", "2. ", before statements? Delete those numbers:
Serial.println("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.println("Temperature: ");
Serial.print(t);
Serial.println(" *C ");

Also, you are missing a "}" to end loop().
When you correct this errors, others will surface.


text:
arduino rfid with led, code is compiling but not working as expected!
code is compiling, what I want is that when rfid tag kept led should get on but instead its getting to the else loop.
int count = 0;
char input[12]; // rfid input
int led = 3; // led pin
char first[20] = {"270059204B15"}; //rfid tag no
char a[24];

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(led, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (Serial.available() > 0) // code for rfid input
  { count = 0;
    while (Serial.available() && count < 12)
    {
      input[count] = Serial.read();
      count++;
      delay(10);
    }
    Serial.print(input);
  }

  if (strcmp(input, first) == 0) /*comparing two string rfid tag no and input
   if matches led is on*/
  {
    digitalWrite(led, LOW); /* as the board which we are using is in sink
    mode low is taken as 1 or on*/
    delay(500);
    Serial.print("led is on\n");
  }

  else
  { digitalWrite(led, HIGH);
    delay(500);
    Serial.print("led is off\n");
  }
}

Could you clarify your question, provide step by step explanation on how you want it to work(or how you expected it as per title)? Something like a program flow.

Your unespecified problems are consecuence of a collection of small details.

You are not putting a binary zero to end the input string.
That's not the way to read serial input.
Code doesn't filter out control caracteres (LF, CR).

Here is your code cleaned up:
#define ID_SIZE 12

int count=0;
char input[ID_SIZE + 1]; // rfid input
int led=3; // led pin
char first[ID_SIZE + 1]= {"270059204B15"}; //rfid tag no

void setup()
{
    // put your setup code here, to run once:
    Serial.begin(9600);
    pinMode(led,OUTPUT);
}

void loop()
{

    // put your main code here, to run repeatedly:
    while(Serial.available() > 0 && count < 12) {  // code for rfid input
       char c = Serial.read();
       if (isAlphaNumeric(c)) {
          input[count++]=c;
          }
      }

    input[count] = 0;
    if(count >= 12) {
        Serial.print(input);
    }

    if(strcmp(input,first)==0) /*comparing two string rfid tag no and input
   if matches led is on*/
    {
        digitalWrite(led,LOW); /* as the board which we are using is in sink
    mode low is taken as 1 or on*/
        delay(500);
        Serial.println("led is on\n");
        input[0] = count = 0;
    }

    else {
        digitalWrite(led,HIGH);
        delay(500);
        Serial.println("led is off\n");
    }
}

And here is the result:

Edit:
The C strings are char arrays of undefined lenght. To signal the end of the string, put a binary zero next to the (effective) last element. Then, if you want to store a 10 chars string, you need an 11 elements arrays (10 for the string itself, 1 for the binary zero).
Failure to put a binary zero at the end of a string is a very common cause of program failure.
Control characters. In general, when you type "TEST" in the Serial Monitor and press SEND, what Arduino receive is the word TEST itself, plus a Line Feed/Carriage Return pair (LF/CR) to mark the end of the line.
In real world, your serial input can be contaminated with tabs, spaces, LF/CR and other valid chars. You need to discard them (unless they are valid for your app).

coding service? :-)

Programming School. The OP, while a beginner, looks in the right path. At least he doesn't use String and know about arrays. Posting the original code and the improved version help others to learn better coding practices. Coding Service is coding from scratch on specs. Not this case, the guy did his homework.

Thank you for your answer alterno, could you please explain your second and third point.

@NikhilNaidu. I edited my answer.


text:
How many transistors can be connected to Arduino pins?
How many TIP122 transistors can I connect to the Arduino digital pins? The Atmega328p datasheet states that the pins can source a total of 200 mA, while other documents state 40 mA per pin.
In the following circuit layout, I connected six TIP122 transistors with 2.2  kΩ  base resistors. I used an LM338 regulator to power the Arduino IC and other functions.

I would use a N-channel MOSFET instead of the TIPwhatever.
AOD514 from Digikey has really low Rds, somewhere around 0.01 ohm, and can be driven from an Arduino pin, say thru a  150 ohm resistor to protect against the gate input capacitance of the MOSFET. A 10K pulldown resistor on the gate will hold the MOSFET off until the Arduino sketch starts up and controls the pin.
AOD514 is surface mount, but tab and pins are pretty good size and can be manually soldered.
AOD508 and AOD510 are even lower Rds, but cost a bit more at Digikey.

The TIP122 is a 100V, 5A, Hfe at least 1000, darlington NPN transistor. With the base resistor of 2k2, that is about 1 or 2 mA per pin. You don't have to worry about a few mA.
To answer your question: "How many transistor can be connected to arduino pins?", that will be about 100.
Why do you use TIP122 ? They have a voltage drop. Logic level mosfets have a very little voltage drop and thus they stay a lot cooler.
Mosfets leak at a higher voltage. If you need to operate near 100V, there are IGBT transistors for that.
Make sure that the high current through the TIP122 at the emitter does not disturb the GND of the ATmega chip. You have to design your circuit board to avoid such troubles.

Thank for your answers,in my design i want to switch 24v 200mA fans only. I think thisll not disturb gnd of atmega, is it right?? Or not..and what to do if ive to switch large current thru transistor?? Do you have any notes or web link of this,,plz share..

@NikhilP, I don't know a website. As far as I know, that is a common design rule. If you use a single power connector for both the atmega chip and the transistors, then you could keep those ground paths seperatated and only connect them at the connector.

Can you plz recheck my circuit diagram ,and suggest me where i can seperate ground line with atmega(highlighted line is ground line is GND line for mosfet as well as microcontroller)..Also plz check for other errors.  I am new in this field dont know desiging rules.i ve uploded complete circuit diagram above.

The emitter/ground current of the TIP122 can raise the ground level, and that will directly influence the working of the Atmega chip. The ground path of the Atmega chip is not going to the connector, but connects to the ground path which has the large currents from the TIP122 transistors. It will probably work. A grounding problem is more serious with high frequences. Just to be sure, I would split the ground from the connector into two paths, one for the Atmega chip and one for the TIP122 transistors.

"In datasheet atmega 328p total arduino pin can source 200 ma of current or some saying 40ma current per pin."
Datasheet says 200mA per VCC and GND pin.  I personally confirmed that with Atmel Tech Support (before they were bought by MicroChip).
Absolute max per IO pin is 40mA, more than that and you risk damaging the pin.
Further, above 20mA a High output will begin outputting lower voltage, and a Low output will begin outputting a higher voltage. See Section 32 of the latest datasheet:
"Note: Stresses beyond those listed under “Absolute Maximum Ratings” may cause permanent damage
to the device. This is a stress rating only and functional operation of the device at these or other
conditions beyond those indicated in the operational sections of this specification is not implied. Exposure
to absolute maximum rating conditions for extended periods may affect device reliability."
and notes 3 and 4 under table 32.2:
"If IIOH exceeds the test condition (20mA at VCC = 5V, 10mA at VCC =
3V), VOH may exceed the related specification. Pins are not
guaranteed to source current greater than the listed test condition."
"If IOL exceeds the test condition (20mA at VCC = 5V, 10mA at VCC =
3V), VOL may exceed the related specification. Pins are not guaranteed
to sink current greater than the listed test condition."

Did you mean "outputting a a higher current"? Lower?

I meant what I said. A higher load (more than 20mA) and a low output will start rising, and a high output will start dropping. Pretty sure that is caused by voltage created from current x Rds of the output transistors.


text:
UNO: AnalogRead results not as expected
I'm new to Arduino, and trying to build a project that will measure the voltage and current from two, unconnected, 12v batteries. The present test environment comprises:-

a 13.8v power supply (run from the mains (240v)) which is powering two separate voltage dividers;
a take-off from one voltage divider going to A0, the take-off to the second going to A3;
a connection from Arduino GND to the -ve rail on the bread-board;

The voltage dividers are identical - both comprising 10kOhm and 200kOhm resistors - so I am expecting that an analogRead of A0 and A3 would return similar results, which they don't. A0 is up around the 344 mark, A3 is down around 133. So, the problem is that identical voltage dividers are not giving the same readings from the same input voltage.
Code and results follow, and I would be grateful for any hints, tips and further education!
Code follows
#define NUMBER_OF_SAMPLES 10
int looped = 0;

void setup()
{
  Serial.begin(57600);  Serial.println("Test sketch starting");
}

void loop()
{
  int temp1=0;
  int temp2=0;
  int temp3=0;

  looped++;

  for(int count=0; count<NUMBER_OF_SAMPLES; count++)
  {
    temp1 = analogRead(A0);
    temp3 += temp1;

    Serial.print("temp1 = ");
    Serial.print(temp1);    Serial.print(",");
    delay(200);
  }
  Serial.println(temp3);
  temp3 = 0;
  for(int count=0; count<NUMBER_OF_SAMPLES; count++)
  {

    temp2 = analogRead(A2);
    temp3 += temp2;
    Serial.print("temp2 = ");
    Serial.print(temp2);    Serial.print(",");
    delay(200);
  }
  Serial.println(temp3);
  Serial.println("");

  if(looped>NUMBER_OF_SAMPLES)
  {
    delay(500000);
  }
}

And this is the output.
Test sketch starting
temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,3450
temp2 = 129,temp2 = 125,temp2 = 137,temp2 = 137,temp2 = 126,temp2 = 136,temp2 = 134,temp2 = 136,temp2 = 132,temp2 = 132,1324

temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,3450
temp2 = 132,temp2 = 133,temp2 = 136,temp2 = 137,temp2 = 135,temp2 = 129,temp2 = 132,temp2 = 137,temp2 = 131,temp2 = 130,1332

temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 344,temp1 = 344,3448
temp2 = 133,temp2 = 134,temp2 = 132,temp2 = 128,temp2 = 133,temp2 = 134,temp2 = 131,temp2 = 125,temp2 = 130,temp2 = 129,1309

temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 345,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 345,3442
temp2 = 132,temp2 = 133,temp2 = 135,temp2 = 132,temp2 = 131,temp2 = 133,temp2 = 134,temp2 = 133,temp2 = 131,temp2 = 130,1324

temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,3440
temp2 = 133,temp2 = 133,temp2 = 131,temp2 = 133,temp2 = 132,temp2 = 133,temp2 = 133,temp2 = 130,temp2 = 133,temp2 = 138,1329

temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,3440
temp2 = 133,temp2 = 135,temp2 = 133,temp2 = 133,temp2 = 131,temp2 = 133,temp2 = 133,temp2 = 133,temp2 = 133,temp2 = 133,1330

temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,3440
temp2 = 131,temp2 = 134,temp2 = 128,temp2 = 134,temp2 = 134,temp2 = 132,temp2 = 132,temp2 = 132,temp2 = 132,temp2 = 133,1322

temp1 = 344,temp1 = 343,temp1 = 344,temp1 = 344,temp1 = 343,temp1 = 344,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 344,3435
temp2 = 142,temp2 = 141,temp2 = 135,temp2 = 135,temp2 = 135,temp2 = 133,temp2 = 134,temp2 = 133,temp2 = 133,temp2 = 132,1353

temp1 = 343,temp1 = 344,temp1 = 344,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,3432
temp2 = 135,temp2 = 130,temp2 = 136,temp2 = 135,temp2 = 141,temp2 = 130,temp2 = 135,temp2 = 133,temp2 = 134,temp2 = 131,1340

temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,3430
temp2 = 129,temp2 = 133,temp2 = 129,temp2 = 131,temp2 = 133,temp2 = 130,temp2 = 131,temp2 = 135,temp2 = 134,temp2 = 133,1318

temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,3430
temp2 = 131,temp2 = 135,temp2 = 130,temp2 = 128,temp2 = 137,temp2 = 136,temp2 = 136,temp2 = 131,temp2 = 134,temp2 = 134,1332

You are reading A2 instead of A3.

Well that's a schoolboy error! Thanks for that, and reformatting the original question. Now I've fixed the code I see that the result returned by A0 starts at 345 and drops to 341, while that for A3 starts at 324 and drops to 289 - both over 20 iterations. A0 returns 320 six times consecutively, while A3 just drops consistently and the gap between the two widens. Any ideas how I might correct this?

What resistors are you using?

The divider on A0 is 9840 and 200000, that on A3 is 9770 and 199800 - both measured on a UT203 digital multimeter, so nothing particularly special but, hopefully, not garbage either. The resistors were from Maplins, so probably 5%, but would that make the difference?

I'm new to electronics as well as Arduino, I have assumed that the tolerance would only apply to initial manufacture e.g. that a 5% 200kOhm resistor would actually be + or -  10kOhms, but that it would be stable in operation rather than having an allowable drift of + or - 5%?

Quote from: CtrlAltElite: you could try each time you do an analogRead, do two reads of each pin, but throw away the first one, and don't use it.

Try swapping the divider pin assignments and see if the difference goes with the pins or the resistors.

@CtrlAltElite - thanks for this. Could you explain why this might help resolve the problem that readings from both pins are falling, and why A3 is falling faster than A0 as that makes no sense to me.

@ChrisStratton - I've altered the code so that A2 is read before A0 e.g. swapped them around. That seems to have stopped both of them falling - are you able to explain why that might be. However, that has not resolved the problem that A2 is giving readings around 341 and A0 is giving readings around 135 - any ideas?

Again, try swapping the wires between A2 and A0 and see if the values follow the port pins or the external dividers.

Which Arduino? Please add the appropriate tag to the question. Also please edit the question to make absolutely clear what port you are using. As it stands the question says you are using A3 but the code says A2.

and why A3 is falling faster than A0 - what do you mean by that? And do you mean A2?

Can you please use your meter to actually measure the voltage at the mid-point of the voltage dividers? On the figures you give you should be getting around 0.657 volts there. On that basis the analog reading of 134 looks like the correct one. 134.5 / 1024 * 5 = 0.657

move this to just before the for loop ... Serial.print("temp1 = "); ... for narrower printout

Assuming you are using an Arduino Uno, I set up your test situation on my bench.
I modified the prints as jsotola suggested to move the "temp1 = " out of the loop.
I measured 0.670V on the A0 port and 0.666 on the A2 port.
We would expect 0.657V as per the Voltage Divider Calculator.
Vout = Vin * R2 / (R1 + R2)
13.8 * 10 / (200 + 10) = 0.657

As suggested on my page about the ADC the formula for converting a reading into a voltage is:
float voltage = ((float) rawADC  + 0.5 ) / 1024.0 * Vref;

Therefore a reading of 134 gives the correct results:
(134 + 0.5) / 1024 * 5 = 0.657

My results were:
Test sketch starting
temp1 = 133,134,133,134,134,134,134,134,134,134,1338
temp2 = 133,132,133,134,132,133,133,134,133,133,1330

temp1 = 134,134,134,134,133,134,134,134,134,134,1339
temp2 = 134,133,133,132,133,133,133,134,133,133,1331

temp1 = 134,134,134,133,134,134,134,133,134,134,1338
temp2 = 133,133,133,134,133,133,133,133,133,132,1330

temp1 = 134,134,133,135,134,134,134,134,134,134,1340
temp2 = 133,133,133,133,133,133,132,133,133,134,1330

temp1 = 134,134,134,134,134,134,134,134,134,134,1340
temp2 = 133,133,132,133,133,134,133,133,134,133,1331

temp1 = 134,133,133,134,134,133,134,134,134,134,1337
temp2 = 132,133,133,133,134,133,133,133,133,133,1330

temp1 = 134,134,134,135,134,133,134,134,134,134,1340
temp2 = 133,133,133,134,133,133,133,133,133,132,1330

This therefore shows that your sketch is working properly, and that there must be some electrical issue in your voltage divider or your connections.

The slight differences would be accounted for by noise in the voltage divider circuitry.

Excellent, thanks Nick, that gives me the confidence to try this again with soldered connections, rather than on a breadboard.


text:
uno timer0 prescale
I have a project where I need to get a low frequency to get a pwm suited from my project. The problem is that after I modify the frequency of timer0 the millis() becomes slower or faster depending on prescalar. So a fix as stated here is to change prescalar in wiring.c. But I don't know for what reason when I set it to 256 or 1024 the millis return 0. For 1-64 works fine.
Timer 0 uses a prescale factor which is set to 64 by default
To set the prescale factor use this line in the setup function

Setting                          Prescale_factor
TCCR0B = _BV(CS00);              1
TCCR0B = _BV(CS01);              8
TCCR0B = _BV(CS00) | _BV(CS01);  64
TCCR0B = _BV(CS02);              256
TCCR0B = _BV(CS00) | _BV(CS02);  1024

To use Fast PWM on Timer 0
Write this line in the setup function
TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM01) | _BV(WGM00);
And to calculate the PWM frequency, use
Fast_PWM_frequency = (16 000 000)/(Prescale_factor*256);

To use Phase-correct PWM on Timer 0 (half the frequency of Fast PWM)
Write this line in the setup function
TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM00);
And to calculate the PWM frequency, use
Phase_correct_PWM_frequency = (16 000 000)/(Prescale_factor*510);

Changing the prescale factor on Timer0 will affect functions
millis(), micros(), delay(),...

To adjust millis(), micros(), delay(),... accordingly,
You can modify a line in the wiring.c function in the Arduino program files
hardware\arduino\cores\arduino\wiring.c

In the beginning of wiring.c you can find:
// the prescaler is set so that timer0 ticks every 64 clock cycles, and the
// the overflow handler is called every 256 ticks.
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))

You need to modify the prescale factor in this function to the corresponding line

For fast PWM (default):
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(PRESCALE_FACTOR* 256))
For phase-correct PWM :
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(PRESCALE_FACTOR * 510))

try setting it to 257 or 1025

Integer math in C is done in an int or unsigned int by default. int is 16-bit on AVR. 256 * 256 overflows to 0, as does 1024 * 256. You will need to tell the compiler to perform the math in a longer type.
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(256 * 256L))

The value is stored in an unsigned long not an int, which is 32 bits.

Amended, assuming you are correct.


text:
Buttons, LOW vs no connection
I'm working with a very simple circuit to understand push buttons. The code in the tutorial uses the INPUT_PULLUP pinmode. I understand the idea of the pinmode, but I have two questions:
There must be a difference between a LOW reading and no connection, correct? How does the arduino differentiate between the two?
I tried to experiment with this idea. So my thought was that you could create a circuit where the LED only stays lit when you hold the button down. In this setup, I used just normal INPUT for pinmode. So the logic was: if LOW then turn light on, else light off. The turnout was the light was almost always on and just really finicky when i moved the board. Why?
Thanks!

To us to fully answer this question you need to post your schematic and your code.

Upvoted for the good question which I learnt from by the comments and answer of Nick.

There must be a difference between a LOW reading and no connection, correct?

No, the input circuitry measures a voltage. The exact details are in the datasheet, but how could it know there is nothing connected? There is not some sort of sensor that detects the insertion of a wire into the input. Therefore it is trying to read a voltage all the time.
With nothing connected then stray voltages from nearby circuitry will influence the reading.

... and just really finicky when i moved the board ...

Yep, you are influencing the voltage by capacitance from your hand.
You need to have a definite voltage for "no switch pressed" which can be a resistor to ground (eg. 10k) or a resistor to +5V.
I have a tutorial on this.

It sounds like you have wired your switch like this:

Because you don't have a definite voltage there, the input could "randomly" switch between LOW and HIGH.

You could add a pull-down resistor:

Or a pull-up resistor:

Or use the INPUT_PULLUP mode to create a pull-up resistor in the processor hardware. (There is no INPUT_PULLDOWN mode).
Then you will get consistent results.

Upvoted ... thanks Nick for this great answer... I learnt a lot from it (and thought the Arduino also had an INPUT_PULLDOWN mode.


text:
LCD Lifespans Constantly Running
I am creating an arduino alarm clock/light sculpture, but I can't for the life of me find any information about the lifespans of LCDs that are running 24/7 for a very long time. If anyone has any information on them, please tell me. Specifically, I am using this one.

Let me turn the question around for you. How long do you want it to last, realistically? A year? 10 years? 100 years?

it should be years and years; i have several going for years now.

The lifespan of the LCD and the electronics is just like any electronics part. When it is bad quality it will last a few years, when it is good quality it is more than 10 years.
A LCD watch from the 1970s might still work today. That is a few decades.
The backlight might get dim. That depends on the quality of the led and how bright it is set. The cheapest leds have only 50% brightness left after a few months. I suppose they didn't put the cheapest led in that display. I expect it to be okay for many years. Don't set it to the highest brightness. A resistor for the backlight of 220 Ω is common, you could start with 470 Ω and see if that is bright enough.
I see sometimes that the backlight display is directly connected to 5V, without resistor. If you have done that, then you have reduced its lifespan.
There are a few weak parts: The potentiometer for the contrast, the large capacitors on the Arduino board (if there are any), and the power supply.
If the display is more or less at the same room temperature, you could replace the potentiometer with a single resistor of 100Ω to 10kΩ from the LCD contrast pin to GND.


text:
How to replace the delay() function in my code?
I'm new to Arduino and I currently have a project that involves the control of an LED via ultrasonic sensor. Basically, if an object passes through the ultrasonic sensor, the LED will be ON for 5 seconds but adding another set of LED and ultrasonic sensor with the same function gives a problem because the other LED won't light up if the other one is ON and vice versa because of the delay whereas what I want is to be able to make them both light up and stay lit for 5 seconds after their respective ultrasonic sensors detect an object. I've tried using the "Blink without delay" example but I can't understand it nor make it work. Please help me guys and thanks for reading. Here is my current code:
int trigPin1=2;
int echoPin1=3;

int trigPin2=4;
int echoPin2=5;

int led1=10;
int led2=11;

void setup() {
  Serial.begin(9600);
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);

  pinMode(led1,OUTPUT);
  pinMode(led2,OUTPUT);
}

void loop() {
  long duration1, distance1;
  digitalWrite(trigPin1, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(trigPin1, HIGH);
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin1, LOW);
  duration1 = pulseIn(echoPin1, HIGH);
  distance1 = (duration1/2) / 29.1;

   if (distance1 >= 500 || distance1 <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print ( "Sensor1  ");
    Serial.print ( distance1);
    Serial.println("cm");
       }

  long duration2, distance2;
  digitalWrite(trigPin2, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(trigPin2, HIGH);
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin2, LOW);
  duration2 = pulseIn(echoPin2, HIGH);
  distance2= (duration2/2) / 29.1;

  if (distance2 >= 500 || distance2 <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print("Sensor2  ");
    Serial.print(distance2);
    Serial.println("cm");
       }

  if(distance1>20 || distance2>20){
    digitalWrite(led1,LOW);
    digitalWrite(led2,LOW);
  }
  else if(distance1<20){
    digitalWrite(led1,HIGH);
    delay(5000);
  }

  else if(distance2<20){
    digitalWrite(led2,HIGH);
    delay(5000);
  }
}

The first set of delaymicroseconds for measuring is fine.
you'll want to replace the delay(5000) when switching the leds.
  if(distance1>20 || distance2>20){
    digitalWrite(led1,LOW);
    digitalWrite(led2,LOW);
  }
  else if(distance1<20){
    digitalWrite(led1,HIGH);
    delay(5000);
  }

  else if(distance2<20){
    digitalWrite(led2,HIGH);
    delay(5000);
  }

you can do that by using a timestamp of when the distance was last high:
  if(distance1<20){
    digitalWrite(led1,HIGH);
    timestamp1 = millis();
  }

  if(distance2<20){
    digitalWrite(led2,HIGH);
    timestamp2 = millis();
  }

if(millis() - timestamp1 > 5000){
  digitalWrite(led1,LOW);
}

if(millis() - timestamp2 > 5000){
  digitalWrite(led2,LOW);
}

timestamp1 and timestamp2 should be globals (or static locals). This code will delay turning off the led to 5 seconds after the sensor last detected something close.

Thank you very much! I managed to do it using your hints but I believe the code after if(millis()-timestamp1>5000) should be digitalWrite(led1,LOW);

@LelouchLamperouge indeed they should be set to low there. copy paste errors...


text:
Problem with LED (Builtin) connected to pin 13
This is Aakash. Student of Electrical Engineering in a University.
I want to ask some information. Today I Purchased Arduino UNO R3 board. and facing some problem which are :
          "**Builtin LED at pin#13 is always ON on my board**".

Is there any problem with the board ?
I tried to upload these sketches and got these results::
1)...with empty setup(){} and empty loop(){}, Still LED is ON.
2)...When I uploaded these command "pinMode(LED_BUILTIN,OUTPUT);" in setup() and "digitalWrite(LED_BUILTIN,LOW);" in loop(), LED turned OFF
3)...If i touch pin13 and Ground both by a wet finger at back of board, LED turns OFF.
4)...but on uploading empty or any other code, BUILTIN_LED turns ON again and do not turns OFF.
Kindly reply me ASAP! So that if i have got faulty Board then i might go for claim.

Possible duplicate of Uno pin 13 LED mysteriously always ON at 0.14V unless pinMode OUTPUT, also see https://arduino.stackexchange.com/questions/18263/arduino-in-built-led-is-not-turning-off

This is a normal thing. All my arduino boards do the same. The reason for this is that the micro controller don't care about the pins that aren't defined in the code. When they aren't defined they all have a HIGH on them. Here is my board with this code:
void setup() {
}
void loop() {
}


text:
yellow LED not turning off in traffic light simulation
I wanted to make a simulation of a traffic light, and since I don't have any sensors I used a button to change between the different states (red/stop and green/drive). When the states are changing I wanted to have a short yellow blink-
 just like normal traffic lights work. But in the first state(green), yellow doesn't turn off. In the second the same problem occurs, but if I press the button, that I connected to GPIO pin 2, the LED turns off. It makes no sense to me, as the switch sentence turn off the yellow LED before powering the others (in both cases). In addition, I can't wrap my head around the fact that the yellow LED turns off after I press the button once more, as I only have two cases in the switch sentence, but it now seems like there is three.
void loop() {
// Turn the green led on (GPIO PIN 11) if button pressed once. If button is pressed again switch to yellow then to red.

if(switchLedBtn.pressed()) {
colour = colour + 1;
if(colour > 3) {
  colour = 1;
 }
}

switch(colour) {

// Turn off red, turn on yellow in half a second, then power green (green(0), yellow(1) and red(2))
case 1: digitalWrite(ledPins[2], LOW); digitalWrite(ledPins[1], HIGH); delay(500); digitalWrite(ledPins[1], LOW); digitalWrite(ledPins[0], HIGH);
        break;

// Turn green off, turn yellow on for a second, then power red
case 2: digitalWrite(ledPins[0], LOW); digitalWrite(ledPins[1], HIGH); delay(1000); digitalWrite(ledPins[1], LOW); digitalWrite(ledPins[2], HIGH);
        break;

Please add some line breaks! Cramming multiple statements onto one line makes them very hard to read. And also post your complete code which I suspect is not much longer than what you posted already.

Got it, next time i ask i will include the whole code and try to make it easier to read

Your program runs in a tight loop - an extremely tight one which does all but nothing in any state but 1 or 2.  However what happens in these states is interesting.
Essentially what you have is

Quickly check for input - which won't be detected unless the bottom is being held down at this precise narrow slice of time between long delays
Turn on an LED, apparently from your comment the yellow one
Change the LEDs but recycle so quickly that this fact is generally invisible.

The result of this is that instead of a brief pulse of yellow, you will be seeing near constant yellow, because that is the only part of your loop which takes any time.
Probably what you want to do is to advance the state when you are done with your brief yellow flash.  But it's not possible to say what you should advance the state to, since it's unclear how you want this light to work.  If it is purely timer-based, then you don't need any input at all; while if the button is supposed to do something but a timer should also be used, then you have a more complicated problem.
Essentially, before you can write any code you must write in words or diagrams a comprehensive set of "rules" for what the system is supposed to do.


text:
Build a timer that starts and stops timing when 2 wires are broken
I need to build a timer that uses the breaking of copper strips to trigger its starting and stopping. The intention is to measure the speed of a rocket with this - it will break the first wire, starting the timer, and then break the second, stopping it.
I am using an Arduino Uno, and a couple of lengths of wire for now.
I can plug one wire into the 1st 5V power supply on the board, and the other end into one of the analog pins (AO), (and then the second wire into the 2nd 5v supply and A1) so that when it is pulled out of the pin socket, it is 'broken'. Is this the correct method to go about this, and if so, how do I tell the Arduino to look for those signals as its 'start' and 'stop' and then record the time difference accordingly?
So far, I have managed to read a signal from the wire using the Analog Read Signal tutorial on Arduino.cc (https://www.arduino.cc/en/Tutorial/AnalogReadSerial). I noted whilst watching the printed data that once the wire is removed from the pin, the voltage value slowly decreased, and held at around 290 (starting at 1023, as per the tutorial). Is this simply a side effect of not using a grounded potentiometer, but a wire?
void setup() {
  // set up comms:
  Serial.begin(9600);
}

void loop() {
  // check and read value of input:
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  delay(1);
}

I am new to Arduino, so please explain in detail, or point me to a thread that will! Thanks in advance for help!
UPDATE
Having played around with analogWrite some more, I have managed to get a situation where I can output the relative value from both A0 and A1. However, I am still struggling to make it operate as a timer.
// declare variables
unsigned long startTime, stopTime;
unsigned long totalTime = (stopTime - startTime);

void setup() {
  Serial.begin(9600);   // set up comms
}

void loop() {
  // check and read value of input:
  int sensorValue1 = analogRead(A0);
  int sensorValue2 = analogRead(A1);

  if (sensorValue1 < 1023) {
    startTime = micros();
    Serial.println(sensorValue1);
  }
  if (sensorValue2 < 1023) {
    stopTime = micros();
    Serial.println(sensorValue2);
  }

  Serial.println("Time: ");   // prints "Time: "
  Serial.println(totalTime);  // prints time value
    delay(1000);
}

I have also tried to convert this to use digitalRead rather than analogRead but have not had much success - I am still failing to get a time. I know my method is wrong, but have struggled to find guidance on how to correct it.
    // declare variables
boolean timingFinished = false;
unsigned long startTime, stopTime;

String strTime = "Time:";

void setup() {
  Serial.begin(9600);   // set up comms
  pinMode(7, INPUT);   // set up pin 7
  pinMode(6, INPUT);   // set up pin 6
}

void loop() {
  // check and read value of input:
  int sensorValue1 = digitalRead(7);
  int sensorValue2 = digitalRead(6);
  Serial.println(sensorValue1);
  Serial.println(sensorValue2);

  if (sensorValue1 = HIGH) {
    startTime = micros();
    Serial.println(sensorValue1);
  }
  if (sensorValue2 = HIGH) {
    stopTime = micros();
    Serial.println(sensorValue2);
  }
  unsigned long totalTime = (sensorValue1 - sensorValue2);
  String strPrint = strTime + totalTime;
  Serial.println(strPrint);      // prints "Time"

}

You have a number of problems in your code. For one thing, you are doing a lot of printing:
void loop() {
  // check and read value of input:
  int sensorValue1 = digitalRead(7);
  int sensorValue2 = digitalRead(6);
  Serial.println(sensorValue1);
  Serial.println(sensorValue2);

  if (sensorValue1 = HIGH) {
    startTime = micros();
    Serial.println(sensorValue1);
  }
  if (sensorValue2 = HIGH) {
    stopTime = micros();
    Serial.println(sensorValue2);
  }
  unsigned long totalTime = (sensorValue1 - sensorValue2);
  String strPrint = strTime + totalTime;
  Serial.println(strPrint);      // prints "Time"

}

At 9600 baud each byte output takes 1/960 seconds (about 1 ms). A println adds a carriage-return/linefeed to what you are printing so I estimate:
3 + 3 + 7 + 7 = 20 bytes (20 ms)

That is every time around the loop! You will soon find the output buffer filling up, and thus are limiting the rate at which you can test times to be the nearest 20 ms which makes using micros() a bit redundant. You won't get that accuracy.

Plus, the String class does dynamic memory allocation which will slow things down. Why use String at all? For example, you can print "Time" like this:
Serial.println ("Time:");

Next, this assigns not compares:
  if (sensorValue1 = HIGH) {

That statement makes sensorValue1 HIGH (always) and then tests if it is true, which it always will be. You want:
  if (sensorValue1 == HIGH) {

Finally, as mentioned by Majenko, make the inputs INPUT_PULLUP and wire the other end to ground, like this:
  pinMode(7, INPUT_PULLUP);   // set up pin 7
  pinMode(6, INPUT_PULLUP);   // set up pin 6

Edit - after amended question.
// declare variables
unsigned long startTime, stopTime;
unsigned long totalTime = (stopTime - startTime);

You don't declare totalTime like that. It appears you want totalTime to eventually subtract startTime from stopTime.
Just declare totalTime without any calculations, and do the calculation when it is needed. eg.
// declare variables
unsigned long startTime, stopTime;
unsigned long totalTime;

...

  if (sensorValue2 == HIGH) {
    stopTime = micros();
    totalTime = stopTime - startTime;
    Serial.print ("Time: ");
    Serial.println (totalTime);
    }  // end of second sensor tripped

Note the "==" there, without it the code thinks both sensors tripped immediately.

A broken wire is just a button that's held in until you release it.  Just treat it like any other button.

simulate this circuit – Schematic created using CircuitLab
Just like a button, when it's all connected (button is pressed), it reads LOW, and when it's disconnected / broken (button is released) it reads HIGH. No need for messing around with analog inputs - you only care about two states, OPEN (HIGH) and CLOSED (LOW).
You can even use interrupts to make it respond even faster.
Here is an example using a simple state machine for how you could code it (untested):
const uint8_t startPin = 4;
const uint8_t stopPin = 5;

uint32_t startTime;
uint32_t stopTime;

#define ARMED = 0
#define STARTED = 1
#define STOPPED = 2

uint8_t state = ARMED;

void setup() {
    Serial.begin(115200);
    pinMode(startPin, INPUT_PULLUP);
    pinMode(stopPin, INPUT_PULLUP);
}

void loop() {

    switch (state) {
        case ARMED:  // If first wire disconnects then start.
            if (digitalRead(startPin) == HIGH) {
                startTime = micros();
                state = STARTED;
            }
            break;

        case STARTED:  // If second wire disconnects then stop
            if (digitalRead(stopPin) == HIGH) {
                stopTime = micros();
                state = STOPPED;
                Serial.print(F("Duration: "));
                Serial.print(stopTime - startTime);
                Serial.println("us");
            }
            break;

        case STOPPED:  // If both wires reconnected then start over
            if ((digitalRead(startPin) == LOW) &&
                (digitalRead(stopPin) == LOW)) {
                    state = ARMED;
            }
            break;

        default:
            break;
    }
}

Thanks, but could you go into more detail please? How would I write such a code? I had previously tried using digitalWrite, but could not work out how to get a time out of it.

As I said above: Think buttons. How would you read the state of a button? How could you use that to start or stop a timer (or more properly, record two times and then subtract one from another)?

If you have a chance to glance over my updated code, I would appreciate it. I haven't managed to get a time value other than 0 (suggesting that it is recording the startTime and stopTime at the same time.

The problem with your code is you are constantly setting your timestamps all the time the inputs are HIGH, not just at the moment they go HIGH. You only want to set them once, and once only. Simplest way: first set them to 0, then only set them to micros() if they are currently 0.

A better approach for your problem which was to measure the speed of a rocket (i am assuming at launch) would be to use non touch style sensors. Rather then the rocket having to hit two wires which would interrupt the flight path. You could use IR sensors Like in this article.
It would use much of the same logic you are working on now, but would use the IR sensors rather then wires (buttons)

Regardless of what you use as the sensors, wires or photo detectors, you should use interrupts.  Each sensor should go to an interrupt and that interrupt routine should be as short as possible, basically just saving the processor time micros(), into a storage location and returning.  Your main loop can then look at the storage and see if a calculation or printout is necessary.  That way your result will not be dependent on where in your loop the event was detected. The inputs should be digital, high or low as described above.  If you are using photo detectors that are analog, build some external circuits to turn their outputs into digital signals.  I would say this isn't rocket science, but apparently it is. I just hope I am not helping a terrorists :-)


text:
can I design a User Interface to run on the arduino and display it with VGA?
I know you can design a user-interface in any language you choose and Link it with a Arduino via serial Port, but I am asking if I can design user-interface to run on the Arduino WITHOUT the need for an external laptop/desktop and display the user interface on a screen (like via VGA) ? and HOW ?

Only in the most crude and blocky manner.  There are a few game systems which come close.  realistically you should use something else; today small LCD or OLED displays are all of cheaper, more compact, and far easier to drive; if you really want VGA use a small FPGA or fast MCU for that.  But your question is far too broad to be a fit here - stack exchange sites are about specifics.

What are you asking? Can you connect a LCD? An OLED display? A 8x8 LED module (or a string of them)? There are lots of ways of doing user interface. And VGA is possible.

Forget VGA. Arduino is not capable of that.
For display you can use a 16x2 LCD (only chars, not graphics) or an OLED display, which have graphic capabilities. There are in size from 0.96". There BW, but alse color models and touch sensitive ones. For input you use push buttons, or keypad.
Today best option for display is some model with I2C or SPI interfaces (to minimize wiring).
There thousand of projects in Internet. Search "Arduino OLED keypad" and you will find projects like http://www.instructables.com/id/Arduino-OLED-Calculator/:

This hardware impose some limits in the UI (thank god). What you have is a tradicional menu system: you present a menu, user choose an option, Arduino execute it. No help, no dropbox, no autocompletion, nothing, only the most basic "Press 1 for ..."
EDIT:
As Nick Gammon stated, it's possible to drive a VGA display from an Arduino, like this post and this other shows. The resolution are  20 characters wide by 30 characters deep (160 x 480 pixels) for the monochrome version and 120 x 60 pixels for the four colors version.
However, that capabilities doesn't match any of the standard VGA capabilities:

The VGA supports both All Points Addressable graphics modes, and
  alphanumeric text modes. Standard graphics modes are:
640×480 in 16 colors or monochrome[2] (the latter matching IBM's lesser Multi-Color Graphics Array standard)
640×350 or 640×200 in 16 colors or monochrome (EGA compatibility mode)
320×200 in 4 or 16 colors
320×200 in 256 colors (Mode 13h)

The proposed alternatives achieves less resolution than a 1981 Sinclair ZX-81 (24 lines of 32 chars), takes two timers and half of Arduino RAM minimum (the color example left you with 200 bytes RAM and takes a third timer with it).
So, in practical terms, VGA is not an option.

so I can't simply create a GUI (like the u create with java/swing or qt/c++) and run it on the Arduino ?

@MekacherAnis. Thank god not! So many hours wasted ajusting the graphic UI in a PC. Think more in the line of old cell phones, very simple, shallow menu. You have to think in screens of 4 lines x 20-40 chars (tipically with OLED). Arduino is not a PC; you don't sit in front of it all day long; you just need a UI for a quick check or simple action. You don't do data entry on Arduino; if you need to input a great amount of date, better downlad it from a PC, tablet or smartphone.

@MekacherAnis. If UI is a issue, I will choose a NodeMCU instead of Arduino, and use MQTT to control NodeMCU with a GUI running in a smartphone, table or desktop PC. Have a look at MQTT.

thaaaank u for this clarification, my problem is that I considered the Arduino a PC while it's simply a programmable microcontroller, I think I'll get back to the idea of designing with java or c++ as I have experience with those languages

@MekacherAnis. If you want to control devices in real time, it have to be Arduino (or similar). If you just want a small format PC, look at  Raspberry Pi. Or combine both: Raspberry for UI, Arduino for device control.

Forget VGA. Arduino is not capable of that. - Yes it is

@NickGammon. Well, you can display something in a VGA monitor, but monochrome output and 20 characters wide by 30 characters deep (160 x 480 pixels) is not the same VGA that the OP is looking for. VGA means at least 640x480 with 256 colors. Less than that you have CGA (or Hercules even).

S/he said "like via VGA". If you want to display "cooling on" or "cooling off" that would be adequate.

@NickGammon. While driven a VGA display from an Arduino is posible, devoting half of Arduino RAM and two timers just achieve less resolution than a Sinclair ZX81 doesn't sound appealing.

It's something I wouldn't do, because a LCD display would be more logical. :)

@NickGammon no what I really meant by VGA is a beautiful graphical interactive interface that looks appealing not a an MS DOS kinda of thing, anyway thank u both for this clarification

@MekacherAnis If you wan't a fancy GUI with Arduino, look up Nextion displays.

@gre_gor that's really good, cool idea, I'll keep that in mind, but it's a bit small for my taste, I'm looking to control a computer monitor, and as explained it seems out of reach with the use of just an arduino

@MekacherAnis You will need a Raspberry Pi for that.

@gre_gor yes it seems like I need one... thank you for your help


text:
Passing the result of the variable to another variable
Hello everyone i'm figuring if this variable can be passed to another variable. I'm using RFID RC522
Here is the code:
 #include <SPI.h>
    #include <MFRC522.h>
    #define RST_PIN         5           // Configurable, see typical pin layout
    above
    #define SS_PIN          53          // Configurable, see typical pin layout
    above
    MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
    int result = 0;
    // Number of known default keys (hard-coded)
    // NOTE: Synchronize the NR_KNOWN_KEYS define with the defaultKeys[] array
    #define NR_KNOWN_KEYS   8
    // Known keys, see:
    https://code.google.com/p/mfcuk/wiki/MifareClassicDefaultKeys
    byte knownKeys[NR_KNOWN_KEYS][MFRC522::MF_KEY_SIZE] =  {
    {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, // FF FF FF FF FF FF = factory default
    {0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5}, // A0 A1 A2 A3 A4 A5
    {0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5}, // B0 B1 B2 B3 B4 B5
    {0x4d, 0x3a, 0x99, 0xc3, 0x51, 0xdd}, // 4D 3A 99 C3 51 DD
    {0x1a, 0x98, 0x2c, 0x7e, 0x45, 0x9a}, // 1A 98 2C 7E 45 9A
    {0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7}, // D3 F7 D3 F7 D3 F7
    {0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}, // AA BB CC DD EE FF
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}  // 00 00 00 00 00 00
    };
    /*
    * Initialize.
    */
    void setup() {
    Serial.begin(9600);         // Initialize serial communications with the PC
    while (!Serial);            // Do nothing if no serial port is opened (added
    for Arduinos based on ATMEGA32U4)
    SPI.begin();                // Init SPI bus
    mfrc522.PCD_Init();         // Init MFRC522 card
    // Serial.println(F("Try the most used default keys to print block 0 of a
    MIFARE PICC."));
    }
    /*
    * Helper routine to dump a byte array as hex values to Serial.
    */
    void dump_byte_array(byte *buffer, byte bufferSize) {
    for (byte i = 0; i < bufferSize; i++) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
        Serial.print(buffer[i], HEX);
    }
}

/*
 * Try using the PICC (the tag/card) with the given key to access block 0.
 * On success, it will show the key details, and dump the block data on Serial.
 *
 * @return true when the given key worked, false otherwise.
 */
boolean try_key(MFRC522::MIFARE_Key *key)
{
    boolean result = false;
    byte buffer[18];
    byte block = 0;
    byte status;

    // Serial.println(F("Authenticating using key A..."));
    status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, key, &(mfrc522.uid));
    if (status != MFRC522::STATUS_OK) {
        // Serial.print(F("PCD_Authenticate() failed: "));
        // Serial.println(mfrc522.GetStatusCodeName(status));
        return false;
    }

    // Read block
    byte byteCount = sizeof(buffer);
    status = mfrc522.MIFARE_Read(block, buffer, &byteCount);
    if (status != MFRC522::STATUS_OK) {
        // Serial.print(F("MIFARE_Read() failed: "));
        // Serial.println(mfrc522.GetStatusCodeName(status));
    }
    else {
        // Successful read
        result = true;
        //Serial.print(F("Success with key:"));
        dump_byte_array((*key).keyByte, MFRC522::MF_KEY_SIZE);
        //Serial.println();
        // Dump block data
       // Serial.print(F("Block ")); Serial.print(block); Serial.print(F(":"));
        dump_byte_array(buffer, 16);
        //Serial.println();
    }
  //  Serial.println();

    mfrc522.PICC_HaltA();       // Halt PICC
    mfrc522.PCD_StopCrypto1();  // Stop encryption on PCD
    return result;
}

/*
 * Main loop.
 */
void loop() {
  // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent())
        return;
// Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial())
    return;
    // Show some details of the PICC (that is: the tag/card)
   // Serial.print(F("Card UID:"));
    dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
delay(3000);
// Serial.print(F("PICC type: "));
  //  byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
    //Serial.println(mfrc522.PICC_GetTypeName(piccType));

    // Try the known default keys

      }

I list all of my card's value and i want to create a conditional statement if the result of dump_byte_array is the same with my card's value i list.
Sample:
if ( dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size) && "D4 39 F8 BE" ==
  true ){
        Serial.print("Card 1 Detected");

That's what i want to happen but i know that is wrong.
Please help me with this.
Thank you in advance.

Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets. Minimal means you've stripped away irrelevant stuff, just leaving what's needed to show the problem. Complete means all the library names are shown, all the variable declarations, and all the function definitions – so people don't have to waste time guessing what you did or what you meant. Verifiable means it can be compiled and tested, allowing other people to test their theories about the problem

Ok sir , i will edit my post.

looks similar to this question - anyway, since the function (which you wrote) i.e. void dump_byte_array doesn't return anything, then, no, you can't possibly compare the result of calling that function with anything ... perhaps create a new function, to which you pass mfrc522.uid.uidByte, mfrc522.uid.size, [0xD4, 0x39, 0xf8, oxbe] which can return true/false

I tried to add this code and it works fine but no result if its, Card 1 is correct.

Well, dump_byte_array is a void function, so you can't compare it to anything.
And this line
if (dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size) && "D4 39 F8 BE" == true)

is both ilegal and illogical. Ilegal, because you are comparing a pointer ("
("D4 39 F8 BE") against an integer (the true value is a int in disguise).
It's illogical, because you are "&&" is the logical and operator, not the bitwise and.
What you need is a string comparison:
if (strncmp(mfrc522.uid.uidByte, "D4 39 F8 BE", mfrc522.uid.size) == 0) {
   Serial.println("Card found");
}

That's assuming that uidByte contains the ID.
The strncmp function
int strncmp ( const char * str1, const char * str2, size_t num );

Compare characters of two strings
Compares up to num characters of the C string str1 to those of the C string str2.
This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ, until a terminating null-character is reached, or until num characters match in both strings, whichever happens first.
Parameters
str1     C string to be compared.
str2     C string to be compared.
num      Maximum number of characters to compare. size_t is an unsigned integral type.
Return Value
Returns an integral value indicating the relationship between the strings:

<0   the first character that does not match has a lower value in str1
than in str2
0    the contents of both strings are equal
>0  the first character that does not match has a greater value in str1 than in str2

But you really need to learn C.

Judging by the (rather confusing) question the array in question is "binary" (not a string) so strncmp might easily fail if there was 0x00 in the array. Probably memcmp would be more suitable.

Simply rewrite your dump_byte_array function as follows
bool matchID(byte *buffer, byte bufferSize, byte * match, byte matchSize) {
    if (bufferSize != matchSize) return false;
    for (byte i = 0; i < bufferSize; i++)
        if (buffer[i] != match[i])
            return false;
    return true;
}

and call this new function like
if ( matchID(mfrc522.uid.uidByte, mfrc522.uid.size, [0xD4, 0x39, 0xF8, 0xBE], 4)) {
    Serial.print("Card 1 Detected");
}

As suggested in the comments, what's wrong with memcmp ...
bool matchID(byte *buffer, byte bufferSize, byte * match, byte matchSize) {
    if (bufferSize != matchSize) return false;
    return memcmp(buffer, match, bufferSize) == 0;
}

I tried to rewrite this:
void dump_byte_array(byte *buffer, byte bufferSize) {
for (byte i = 0; i < bufferSize; i++) {
Serial.print(buffer[i] < 0x10 ? " 0" : " ");
Serial.print(buffer[i], HEX);

to this:
[code]
bool matchID(byte *buffer, byte bufferSize, byte * match, byte matchSize) {
if (bufferSize <> matchSize) return false;
for (byte i = 0; i < bufferSize; i++)
if (buffer[i] <> match[i])
return falsbool matchID(byte *buffer, byte bufferSize, byte * match, byte matchSize) {
if (bufferSize <> matchSize) return false;
for (byte i = 0; i < bufferSize; i++)
if (buffer[i] <> match[i])
return false;
return true;
};
return true;
}
[/code]

And it gives me:
exit status 1
expected primary-expression before '>' token

That's not valid code. Sorry was in vb mode

But it can convert it to C++ ?

answer edited, check now - my code had one flaw ... <> instead of != - so, yes, it can be converted!

It gives me another error:expected primary-expression before '>' token

see ... there were two places I used <> instead of != - that's the problem with blindly copying code from an answer without understanding it - try now - I'm beginning to suspect the code in the question is not written by you, rather it is an exact copy of someone elses efforts

I didn't copy paste the code, i'm typing it and trying to understand what's the code mean.

What's wrong with using memcmp?

absolutely nothing - just made the simplest change possible with the view that it'd be easier to learn :p added it to the answer


text:
Resistor pull-ups for ESP8266
I'm using 4.7kOhm resistor as pullups for GPIOs 2,0,2,16, CH_PD and RESET, and also 4.7kOhm pulldown for GPIO 15. The ESP8266 boots and works fine. Would it be okay for a long shot? Should I use 10kOhm instead of 4.7kOhm?

I use 10k and have never had an issue - Note: I don't use any pullup for RESET (I think it's reset, it's one of CH_PD or RESET in any case), as all my ESP modules (07/12E/12F based) have "on board" pullup. I've also never had a pullup for GPIO16 because I've never used it for anything, and it's state at power on is irrelevant - only reset and ch_pd (obviously) and 0/2/15 are "important" at power on

Would it be okay for a long shot? - what is a "long shot" in this instance?

@NickGammon "in the future"

@JFetz2191, that should be "long haul"  ... as in "Would it be ok in the long haul?"...... "long shot" means "something that is most likely to fail"

Oh, OK, I thought it might have meant "over a long distance".

In general it makes little or no difference what the value of resistor you use is.
The only things it can affect are:

The current consumption while a button is pressed - a lower value resistor will cause more current to flow while for the time the button is pressed (it makes no difference at other times).
The LOW voltage (VIL) read at the IO pin if the button has a high resistance (for example if it's on the end of a 500m length of cable).
Noise immunity - a lower value resistor will pull the pin up "harder" making it more difficult for noise induced in a long wire (see the previous point, too) from causing a false button press (although this is less of a concern with modern digital inputs that tend to all have Schmitt triggers).

10k is often chosen not because it's "better" than any other value, but purely because it's more common that many other values, and it's in the right kind of ball-park for most setups.  It's low enough to give good noise immunity while being high enough to not cause undue current flow while the button is pressed. But more importantly, it's a resistor that everyone has in their kit, and is most likely the most common resistor used in a number of other places in the circuit as well. It's a good all-rounder as far as resistors go.
To take a closer look at the current flow aspect - if you are running (as with an ESP8266) at 3.3V and you have a 10k resistor the current flow, when the button is pressed and the resistor connected directly to ground, though the resistor would be (I=V/R) 3.3/10,000 = 330uA. If you used a 4.7k resistor (as you are doing at the moment) the current rises to 3.3/4,700 = 702uA. Yes, that's just over double the current, but twice peantus is still peanuts. So 4.7k, under most general circumstances, is perfectly fine.
However if power consumption is a real concern and you want to keep all consumption to an absolute minimum switching to 100k (as you often see in low-power circuits) would be beneficial, since 3.3/100,000 is 33uA.
If your input is connected to a momentary button which will be pressed for fractions of a second at a time it's not that much of an issue. But if the input is connected to a switch that could be activated for days or weeks at a time it obviously becomes of greater interest.
So in short: when running on batteries higher value pullup resistors are better, but when running off a power supply it really makes no difference.

If you need pull-up just for buttons and similar inputs, 100k is pretty fine. But if you use open-drain bus (e.g. I2C), then resistor values have to be calculated properly. If you want to achive 400kHz speed on I2C, even 4k7 might not work and you may need 3k6 or even lower. It depends on the total capacitance of all traces and devices attached.


text:
At dimming = 128, suddenly voltage goes up to 240 volt and then back to 0 volt
While using dimmer circuit with esp8266, at dimming = 128, suddenly voltage goes up to 240 volt and then back to 0 volt. at the output inductive load is connected like TABLE FAN , it has not any type of adapter, its AC line device.
where, the dimming range is 0-128 .
0=ON (no power clipping) means load should be ON.
128=OFF means load should be OFF.

Is this happens with dimmer circuit normally while load connected [TABLE FAN] or I am doing something wrong?
Also , can we use this value(128) for switching purpose? --means whenever we put the dimming=128 the load will be stay OFF,and power consumption stops towards load, as switch works.

i am newbie and trying esp8266 dimmer for first time.
here , the line voltage is 230-240 volts AC, 50Hz power supply .
I am referring this circuit as it is and code also, only the change is dimming value taken using serial communication
here i am using inductive load (TABLE FAN).

`
  const int interruptPin = 14;
int AC_LOAD = 4;    // Output to Opto Triac pin
int dimming = 128;  // Dimming level (0-128)  0 = ON, 128 = OFF

void setup()
{
  Serial.begin(115200);
  pinMode(AC_LOAD, OUTPUT);// Set AC Load pin as output
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), zero_crosss_int, RISING);  // Choose the zero cross interrupt # from the table above
}

//the interrupt function must take no parameters and return nothing
void zero_crosss_int()  //function to be fired at the zero crossing to dim the light
{
  // Firing angle calculation : 1 full 50Hz wave =1/50=20ms
  // Every zerocrossing thus: (50Hz)-> 10ms (1/2 Cycle)
  // 10ms=10000us
  // (10000us - 10us) / 128 = 75 (Approx)

  int dimtime = (75 * dimming);  // For 60Hz =>65
  delayMicroseconds(dimtime);    // Wait till firing the TRIAC
  digitalWrite(AC_LOAD, HIGH);   // Fire the TRIAC
  delayMicroseconds(10);         // triac On propogation delay
  // (for 60Hz use 8.33) Some Triacs need a longer period
  digitalWrite(AC_LOAD, LOW);    // No longer trigger the TRIAC (the next zero crossing will swith it off) TRIAC
}

void loop()  {

   dimming = Serial.read(); // dimming value is taken from serial for
                               dimming the load

}`

is it a 240 V fan or it has a AC/DC adapter working from 60 to 240 V?

Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets. Minimal means you've stripped away irrelevant stuff, just leaving what's needed to show the problem. Complete means all the library names are shown, all the variable declarations, and all the function definitions – so people don't have to waste time guessing what you did or what you meant. Verifiable means it can be compiled and tested, allowing other people to test their theories about the problem

It is 240 v ac fan has not any adaptor

int dimming = 128;  // Dimming level (0-128)  0 = ON, 128 = OFF

The code comments explicitly tell you that the range is 0-128; while non-trivial to do safely, digging out a scope to understand what exactly happens on overflow could be interesting (for example, it may skip alternate half cycles), but the obvious solution is to never command values outside that range, and clamp any out-of-range values which might be requested over the serial port to the limits.
Given that the timing is done unreliably in software, the precise phase behavior of your zero cross detector may be different than the original author's and the line frequency and pulse width constants may or may not be correct for your location, it's not really surprising that you are seeing 128 fall outside the limit of proper behavior rather than just within it.  Likely you want to be conservative in what you allow.
To avoid inconcistency, even better than clamping the maximum value, you may simply want to treat everything above a chosen delay limit as an absolute "off" by simply finishing the ISR immediately without firing the triac at all.  This may prove a lot simpler than trying to reliably find a delay limit that is "almost entirely" off without sometimes slipping over to firing right at the start of the next half cycle - and who really uses the "barely even on" range anyway?
Technically, depending on what the actual memory access width and alignment rules of the ESP8266 are, the sharing of a potentially non-atomic variable between the main and interrupt contexts could cause a one time glitch when it is changed (though even that is unlikely for your expected range of values, especially if you do the limiting before assignment to the shared variable). However, the atomicity concern can be simply remedied by using a volatile unsigned char (or more portably including stdint.h and using a volatile uint8_t) as the shared variable. The volatile keyword is used to require that the compiler actually calculate a variable that may not appear to be used, and actually store it in memory rather than merely cache it in a register.
It's worth noting that the software timed dimming, while somewhat portable is not particularly reliable, and may at high degrees of delay mean the processor spends almost all of its time in the ISR.  For this reason it is generally better to use a hardware timer for this purpose, however that then becomes more chip-specific.  If you are hoping to have things life WiFi running on your ESP8266 at the same time, you'll almost certainly want to move to a hardware timer to avoid glitching.
Ultimately it seems that the tutorial your are following is a poor one, such that doing a complete from-scratch reimplementation would be wise.  Additionally, mains-powered dimming circuits present many safety and reliability concerns even when driving a lightbulb - and it is by no means clear that your triac and snubber circuit are safe to use with an inductive load.  This is a challenging project, and not necessarily an appropriate one to attempt without deep experience.  You might want to consider using a DC fan PWM-controlled from a well-engineered low-voltage power supply instead.

While volatile is appicable in this particular case and MCU, it doesn't works if you are using an Arduino or if you need to change two or more related global variables in your ISR.

Untrue.  8-bit variables with a single writer as suggested here are atomic almost everywhere, including on ATmegas.  There are no linked variables here - the topic is already complex enough without getting sidetracked into situations that do not occur in it.

Due to amateur nature of most visitors to this site, it's much better to give an answer that cover the general case, even if not needed in this particular case and MCU. Others will read you answers and apply it blindly to other problems, with disastrous results. Better yet, post a sketch showing the OP the right way to do it.

Again, there is nothing specific to a given MCU here.  The poster got into their predicament by following a poorly written tutorial; getting out of it will require real thought to apply the explanations here.  This is not a project which can safely be approached by beginners - so the last thing it needs is untested code for someone to copy and paste to other situations where they do not understand that it does not apply.


text:
Read from serial monitor till timeout
Is is possible to read from serial window till timeout?
Actually, what I am looking for is a function that reads from serial monitor, and if no data is available in serial monitor, then it should wait for some time and if still no data is arrived it should return.
Something like,
Serial.read(int timeout);

That's nearly what Serial.readString() does, only you have to set the timeout in advance.  However, such an approach may or may not be what is best for your ultimate goals.

Use this:
byte x;
if (Serial.available() > 0) {
  x = Serial.read();
  }

This doesn't block, because you only read when there is something available in the input buffer.
Now, if you want to read an integer with time-out the serial input, this is a short demo:
#define TIME_OUT 10000L
void setup()
{
    Serial.begin(9600);

    while(!Serial);

    Serial.println();

    Serial.println("Input an int (waiting for 60 seconds");
}

void loop()
{
    static unsigned long timeLastInput = 0;
    unsigned long now = millis();
    static char buffer[10];
    static int index = 0;
    int value;

    if(Serial.available() > 0) {
        char x = Serial.read();
        timeLastInput = now;

        if(isDigit(x)) {
            buffer[index++] = x;
        } else {
            if(index > 0) {
                buffer[index] = 0;
                value = atoi(buffer);
                Serial.print("Integer=");
                Serial.println(value);
                index = 0;
            }
        }
    }

    if(now - timeLastInput > TIME_OUT) {
        Serial.println("Time out");
        index = 0;
        timeLastInput = now;
    }
}

It works by reading all digits into buffer. A non digit input signal the end of the integer. We use atoi to convert the integer ascii representation in his binary value. The result you wants is stored in the value variable.
Note that we read only one char at the time in each loop pass.
And this how the output looks:

And remember: code doesn't manage any error condition; is up to you.

and the Stream.parseInt() function? it uses Stream.setTimeout() setting

@Juraj, to keep the sketch going and use non-blocking is far more important.

@Juraj. I want to do other things beside sitting waiting for an integer to come. The generic problem with setTimeout() is that if too short, doesn't work, and if it is too long, you missed other events and maybe even get a watchdog reset. The proposed solution can wait for hours without blocking. setTimeout is like delay

true. parse and waitUntil functions can't be used with user input.


text:
Can I force Arduino not to be powered by USB?
I'm building a 3D printer and I'm using an ATmega2560 + RAMPS board.
The whole thing is powered by an ATX PSU (12v for motors and stuff, 5v for the Arduino), but when I plug in my USB cable, I can't shut the printer down, as it switches over to USB power.
Is there a way to make the Arduino never use the USB power, only the external power source?
Thanks!

Or create a USB adapter that does not connect the power line.

The best way of doing this, if you want your USB connection to still work, is to remove the P-channel MOSFET T1 from the board.

You can't just disconnect the power from the USB port since that power connection goes directly to UVCC on the ATMega16U2 chip. That is used to power the internal USB peripheral (it goes to a 3.3V regulator inside the chip) and without it the USB interface won't have power.
The USB power is connected to the main 5V rail through that transistor, so if you remove that transistor the 5V from the USB remains connected to the ATMega16U2, but is no longer connected to the rest of the circuit.

Or the big fuse next to it :)

No. That would be the same as cutting the power from the USB.  The USB socket goes first to the fuse, then to both the transistor and the ATMega16U2.

you could do this if you cut the trace for the 5V line from the USB connector to the rest of the board. if you place the mega underside up on a bench in front of you, with the USB facing towards you, i believe it should be the top left pin of the 4 USB pins, but you should double check that first.

you probably can't see it but your answer has 1 down and 1 up vote.  I didn't down vote you - but suspect the person who did may not have liked that your answer requires "double checking".  Perhaps if you verify your answer is correct and re-word it, the person who down voted it may remove the down vote.

Personally I don't like the idea of a permanent modification such as cutting a trace. Once it's done you are pretty much out of options and alternatives. I'm not the down voter either, just throwing my two cents into this post.

Well, it's what I looked for, if I want a non permanent thing I'd put in a switch but this is what I want. Thanks!

This method may be counter-productive. You need the power from the USB port to run the ATMega16U2's USB hardware. Without that you won't get a USB connection...

@Valmond the answer posted by Majenko is what you want, mine is incorrect.

Just modify your UBS cable to not provide power.

read the accepted answer. the USB chip would not be powered

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


text:
RX/TX not working as intended
I am currently working on a project with a HC-06 module. I hooked it up accordingly like so:
Arduino -> HC-06
5V -> VCC
GND -> GND
TX -> RX
RX -> TX

and I ran this code:
void setup() {
  Serial.begin(9600);
}

void loop() {
   Serial.print("test");
   Serial.print("\n");

}

Strangely enough that does not work at all. When I am using neither with or without PC as the power source. When I am using SoftwareSerial like this it works like a charm:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(0, 1); // RX, TX

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

void loop() {

   mySerial.print("test");
   mySerial.print("\n");

}

Can someone please explain why and of course how to fix that?

assuming you have double checked that the wiring (tx/rx) is the same between the two.   Also are you sure your upload completes when you use the hardware serial?  Many times if another device is attached to the hardware serial port, the programing will fail

You are using a Leonardo. Pins 0/1 aren't Serial, they're Serial1.  Serial is the built-in USB connection.
void setup() {
  Serial1.begin(9600);
}

void loop() {
   Serial1.print("test");
   Serial1.print("\n");

}