message:
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!!

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


sender: user

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

sender: assistant

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

1. You are not putting a binary zero to end the input string.
2. That's not the way to read serial input.
3. 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:

[![enter image description here][1]][1]

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

  [1]: https://i.stack.imgur.com/CzJcQ.png


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

[![circuit schematic][1]][1]

  [1]: https://i.stack.imgur.com/iveUk.png

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


body:
"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."


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


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

<!-- language: lang-c++ -->

    #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

body:
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](http://www.ohmslawcalculator.com/voltage-divider-calculator).

    Vout = Vin * R2 / (R1 + R2)
    13.8 * 10 / (200 + 10) = 0.657

As suggested on [my page about the ADC](http://www.gammon.com.au/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.


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

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


message:
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!

body:
> 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](http://www.gammon.com.au/switches).

---

It sounds like you have wired your switch like this:

[![Floating input][1]][1]

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:

[![Pull-down resistor][2]][2]

---

Or a pull-up resistor:

[![Pull-up resistor][3]][3]

---

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.

  [1]: https://i.stack.imgur.com/7Mxzd.png
  [2]: https://i.stack.imgur.com/iv3SB.png
  [3]: https://i.stack.imgur.com/8k6s8.png


message:
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][1].

  [1]: https://www.sparkfun.com/products/709

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


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

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


message:
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**".

[![Builtin LED is ON][1]][1]
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.

  [1]: https://i.stack.imgur.com/YHpfv.jpg

body:
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() {
    }
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/LwiwZ.jpg


message:
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;

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

1. 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
2. Turn on an LED, apparently from your comment the yellow one
3. 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**.


message:
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"

    }

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

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/fBwAB.png)

<!-- End schematic -->

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


body:
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*.


body:
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][1].

It would use much of the same logic you are working on now, but would use the IR sensors rather then wires (buttons)

  [1]: http://www.instructables.com/id/Arduino-IR-Sensor-Timer/


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


message:
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 ?

body:
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/:

[![enter image description here][1]][1]

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][2] and this [other][3] 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.

  [1]: https://i.stack.imgur.com/XVCT2.jpg
  [2]: http://www.gammon.com.au/forum/?id=11608
  [3]: https://github.com/smaffer/vgax


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

body:
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;
    }


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


message:
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?

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


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

1. Is this happens with dimmer circuit normally while load connected [TABLE FAN] or I am doing something wrong?

2. 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][1]

here i am using inductive load (TABLE FAN).

[![this is circuit which is referred for dimmer][2]][2]

`

      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

    }`

  [1]: http://www.instructables.com/id/Arduino-controlled-light-dimmer-The-circuit/
  [2]: https://i.stack.imgur.com/K8xlU.jpg

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


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

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

[![enter image description here][1]][1]

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

  [1]: https://i.stack.imgur.com/pBTuL.png


message:
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!

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


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

[![enter image description here][1]][1]

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.

  [1]: https://i.stack.imgur.com/FWAXF.jpg


body: Just modify your UBS cable to not provide power.


message:
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?

body:
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");

    }


message:
ArduinoJson buffer gets overwritten

I have not that much experience with native languages like c/c++ and I'm facing a strange issue, which drives me crazy. So I'm using an Wemos D1 mini (ESP8266) which uses a class calles `ConfigManager` to read a configuration file from eeprom. The config file is formatted as json, so I'm using [ArduinoJson][1] to parse the content. I have declared a `StaticJsonBuffer` and pointer to a `JsonObject` in the header, like you can see in the code example:

    //FILE: ConfigManager.h
    #ifndef ConfigManager_H
    #define ConfigManager_H

    #include <Arduino.h>
    #include <ArduinoJson.h>
    #include <FS.h>
    #include "Logger.h"

    class ConfigManager {
    public:

        Settings *settings;

        ConfigManager();

        void read_from_eeprom();

    private:

        File configFile;
        JsonObject *json;
        StaticJsonBuffer<200> jsonBuffer;

        void open_file(const char *permission);

        void read_json();

        void recreate_file();

        void create_json();

        void check_success();

        void populate_settings();

        void clean_up();
    };

    #endif

When the function `read_from_eeprom` is invoked, it opens the file and invokes the function`read_json`:

    void ConfigManager::read_json() {
        size_t size = configFile.size();
        Log.verbose("[ConfigManager] Config file size: %d", size);

        std::unique_ptr<char[]> buf(new char[size]);
        configFile.readBytes(buf.get(), size);
        Log.verbose("[ConfigManager] File content: %s", buf.get());

        Log.verbose("[ConfigManager] Parsing json");
        json = &jsonBuffer.parseObject(buf.get());

        Log.notice("[ConfigManager] Json is:");
        json->printTo(Serial);
        Serial.println();
    }

Which is followed by a call to `check_success()`

    void ConfigManager::check_success() {
        Log.notice("[ConfigManager] Json is:");
        json->printTo(Serial);
        Serial.println();

        bool should_recreate = true;
        if (json->success()) {
            Log.notice("[ConfigManager] Parsed json successfully");

            auto version = json->get<const char*>("version");
            if (version) {
                if (strcmp(version, Settings::current_version) == 0) {
                    Log.notice("[ConfigManager] Config version is up2date");
                    should_recreate = false;
                } else {
                    Log.warning("[ConfigManager] Config version outdated");
                }
            } else {
                Log.warning("[ConfigManager] Invalid config file");
            }
        } else {
            Log.warning("[ConfigManager] Config file is not valid json");
        }

        if (should_recreate) {
            Log.notice("[ConfigManager] Recreating config file");
            recreate_file();
            create_json();
        }

        Log.notice("JSON IS: ");
        json->prettyPrintTo(Serial);

        Log.notice("[ConfigManager] Sucessfully read json");
    }

So what I noticed is that the file content is fine. E.g. `{"version":"0.2","led_count":"64"}`.

Then the json is parsed, which succeeds and logs the json object, which is again `{"version":"0.2","led_count":"64"}`.

Afterwards the function returns, and calls `check_success`, which again prints the content of the json object to the log, but this time it seems that something has overwritten the JsonBuffer, which causes the json object to be corrupted. This time the logged content is `{"v␂":"0.2","led_count":"64"}` (with some strange unicorn characters that change as the source code changes). I'm trying to figure out whats going on for many hours now, but I'm stuck. Can someone please point me in the right direction to solve this problem? Thank you!

  [1]: https://github.com/bblanchon/ArduinoJson

body:
the [ArduinoJson library][1] doesn't copy the strings, it only stores pointers and writes terminating zeros into input buffer. And your buffer buf is disposed by [std::unique_ptr][2] at the end of read_json() function

  [1]: https://arduinojson.org/api/jsonbuffer/parseobject/
  [2]: http://en.cppreference.com/w/cpp/memory/unique_ptr


message:
Can I change this code to use a potentiometer instead of a push button

The following code is for a pyrograph power supply that uses an ATtiny85. I want to change it, so instead of a push button I have a potentiometer being the control of the temperature. Can anyone guide me on how to accomplish this with this code?

    //Written by Tyler Gerritsen
    //2017-10-21
    //Pyrography Pen Power Supply Controller
    //Written for ATTiny85 w/ Internal 1MHZ Clock

    const byte btn = 2;
    const byte led = 1;
    const byte pwr = 0;
    byte rate = 0;
    unsigned long nextChange = 0;
    boolean onOff = false;
    unsigned long blinkyCount = 2000000000;
    unsigned long nextBlink = 0;
    unsigned long debounceTimer = 2000000000;
    const unsigned int debounceDelay = 400;
    const unsigned int onDelay[5] = {6800, 6300, 5800, 6300, 4800};
    const unsigned int offDelay = 5000;

    void setup() {
      pinMode(btn, INPUT_PULLUP);
      digitalWrite(btn, HIGH);
      pinMode(led, OUTPUT);
      pinMode(pwr, OUTPUT);
      digitalWrite(pwr, LOW);
      debounceTimer = 60000000;
      while (digitalRead(btn)) {
        checkButton();
      }
      analogWrite(led, 0);
      nextChange = micros();
      debounceTimer = millis() + debounceDelay;
      blinkyCount = 1;

    }

    void loop() {
      runBurner();
      checkButton();
    }

    void runBurner() {
      if (micros() > nextChange) {
        if (onOff) {
          digitalWrite(pwr, LOW);
          onOff = false;
          nextChange += onDelay[rate];
        } else {
          digitalWrite(pwr, HIGH);
          onOff = true;
          nextChange += offDelay;
        }
      }
    }

    void checkButton() {
      if (!digitalRead(btn) && millis() > debounceTimer) {
        debounceTimer = millis() + debounceDelay;
        rate++;
        rate %= 5;
        blinkyCount = (rate) * 2 + 5;
        nextBlink = millis();
      }
      if (blinkyCount > 1 && millis() > nextBlink) {
        if (blinkyCount % 2) {
          digitalWrite(led, LOW);
          blinkyCount--;
          nextBlink += 150;
        } else {
          analogWrite(led, 10);
          nextBlink += 150;
          blinkyCount--;
        }
      } else if (blinkyCount == 1) {
        analogWrite(led, 10);
        blinkyCount = 0;
      }
    }

body:
This is a simple sketch that shows how to read a potentiometer and do something with the value, namely, adjust the delay of the blinking led.

[Source: https://www.arduino.cc/en/tutorial/potentiometer]

    /* Analog Read to LED
     * ------------------
     *
     * turns on and off a light emitting diode(LED) connected to digital
     * pin 13. The amount of time the LED will be on and off depends on
     * the value obtained by analogRead(). In the easiest case we connect
     * a potentiometer to analog pin 2.
     *
     * Created 1 December 2005
     * copyleft 2005 DojoDave <http://www.0j0.org>
     * http://arduino.berlios.de
     *
     */

    int potPin = 2;    // select the input pin for the potentiometer
    int ledPin = 13;   // select the pin for the LED
    int val = 0;       // variable to store the value coming from the sensor

    void setup() {
      pinMode(ledPin, OUTPUT);  // declare the ledPin as an OUTPUT
    }

    void loop() {
      val = analogRead(potPin);    // read the value from the sensor
      digitalWrite(ledPin, HIGH);  // turn the ledPin on
      delay(val);                  // stop the program for some time
      digitalWrite(ledPin, LOW);   // turn the ledPin off
      delay(val);                  // stop the program for some time
    }

So, in every loop iteration you read the potPin and using that value for delay.

AnalogRead gives you a value between 0-1023, which you have to adjust to give the desired value for temperature control. That is all you need.

Use `map` function to adjust the value. Look at https://www.arduino.cc/reference/en/language/functions/math/map/


body:
This bit of code from you is the key part:

    if (!digitalRead(btn) && millis() > debounceTimer) {
      debounceTimer = millis() + debounceDelay;
      rate++;
      rate %= 5;
      blinkyCount = (rate)*2+5;
      nextBlink = millis();
    }

Specifically, the `rate++` and `rate %= 5` lines.

You have a 5-step temp setting. The `analogRead()` function returns a value from 0 to 1023, which you have to map to 0 to 4 (5 steps). Also, you can read the Potentiometer without worry about debouncing; thus:

    if (true) {
      rate = map(analogRead(A0), 0, 1023, 0, 4);
      blinkyCount = (rate)*2+5;
      nextBlink = millis();
    }

If you desire to have more than 5 "settings" for temperature, you could get a continuous range by eliminating the table `onDelay[]` and mapping the analog value between the high and low range of the acceptable `onDelay` values, so you get a finer control of the "on" delay time.

    // No longer needs to be an array or a const
    unsigned int onDelay = 6800;

Within `checkButton()`:

    if (true) {

      // Key Change here
      onDelay = map(analogRead(A0), 0, 1023, 6800, 4800);

      blinkyCount = (rate)*2+5;
      nextBlink = millis();
    }

Update to `runBurner()`:

    void runBurner(){
      if (micros() > nextChange){
        if (onOff){
          digitalWrite(pwr, LOW);
          onOff = false;

          // Key Change here:
          nextChange += onDelay;

        }
        else {
          digitalWrite(pwr, HIGH);
          onOff = true;
          nextChange += offDelay;
        }
      }
    }


message:
ATtiny84 vs ATtiny85 consumption

I'm doing a comparative study between ATtiny84 and ATtiny85, and I found from the datasheet that ATtiny84 consumes less current, is that normal even if it is bigger in terms of size and number of pins? Am i wrong?

body:
There are wide differences in power usage in AVR parts. Typically the "P" variants (for "picopower") are more optimized for low power usage, but there are also differences between different revs of the same part (for example the ATMEGA168PB uses slightly more power than the ATMEGA168PA during sleep) presumably becuase of different processes used to make the chips.

If you are looking for the lowest power possible, it will depend on how your application.  Do you spend most time running at full speed? Power down? Do you need a realtime-clock?

Don't forget about the ATXMEGA parts- they have some that have very low power when running a real-time clock from the internal "ultra-low power" oscillator.


message:
ATtiny85 serial communication, bootloader and setting up fuses

I have been reading some articles about ATtiny and how to burn the bootloader. And I have two questions which I can't figure out.

1. Do I need to manually setup fuses to run 8 MHz on my ATtiny when I'm using my Arduino board as my ISP (there we can select the internal clock and that confuses me)?

2. For the SoftwareSerial.h library, do I need to setup my ATtiny to 8 Mhz in order to work?

body:
1. If you search the internet, you mostly find statements, that the fuses will be set right, if you burn the bootloader from the IDE. However I had to set the fuses in an extra call to avr-dude, because the clock divider was still active, setting the clock effectivly to 1MHz, instead of the intended 8MHz. With a command like

    avrdude -P /dev/ttyUSB1 -b 19200 -c avrisp -p attiny85 -v

you can read the current fuses. Note that you have to set the parameters according to your setup (I used an ArduinoAsISP on the serial port ttyUSB1). You can write the fuses with a command like this:

    avrdude -P /dev/ttyUSB1 -b 19200 -c avrisp -p attiny85 -v -U lfuse:w:0xE2:m

depending on which fuse you want to set, you have to replace `lfuse` with `hfuse` or `efuse`.

2. SoftwareSerial should also work with other clock frequencies, but I don't know the limitations. Keep in mind, that lower clock frequency means you can only reach lower baudrates. It is crucial, that the fuses are set correctly for the intended speed, because the library takes the speed defined in the IDE. In my case this was 8MHz, but the ATTiny still run at 1MHz, which confused the serial communication.


body:
If you load this into the IDE
<https://github.com/SpenceKonde/ATTinyCore>
the fuses will be set correctly for the different selectable clock speeds.


message:
Sending over a number from Arduino to Attiny85

I recently started my first arduino project, displaying a number on a 4x 7 segment display. I want to keep this code and use the display in other projects to display 4 digit numbers (creating a library and using segmentdisplay.write(number) maybe?).

Just displaying the number went really well, but I wanted to drive it with less I/O pins. Then I discovered shift registers, which reduced the number of necessary I/O pins to 3. But, the code needs to execute constantly to keep the 4 digits on the display via multiplexing. My solution to this was to run the sketch on attiny85, on which I programmed the code below. The only thing left to do is to change the value of 'getal' to a value that I read or calculate on the arduino. But I have no idea on how to achieve this, can I shift out data from the arduino to attiny85, which then updates 'getal's value? Any help is appreciated!

    const int dataPin = 0;
    const int latchPin = 1;
    const int clockPin = 2;

    const int Db = B00001111;
    const int D1 = B00000111;
    const int D2 = B00001011;
    const int D3 = B00001101;
    const int D4 = B00001110;
    const int num0 = B11111100;
    const int num1 = B01100000;
    const int num2 = B11011010;
    const int num3 = B11110010;
    const int num4 = B01100110;
    const int num5 = B10110110;
    const int num6 = B10111110;
    const int num7 = B11100000;
    const int num8 = B11111110;
    const int num9 = B11110110;

    int D_4[4] = {D1, D2, D3, D4};
    int D_3[4] = {Db, D2, D3, D4};
    int D_2[4] = {Db, Db, D3, D4};
    int D_1[4] = {Db, Db, Db, D4};
    const int num[10] = {num0, num1, num2, num3, num4, num5, num6, num7, num8, num9};

    const int tallen[4] = {1000, 100, 10, 1};

    int getal = 185;

    void setup() {
      pinMode(latchPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
    }

    void loop() {
      int lengte = findn(getal);
      switch (lengte) {
        case 1:
          displaynum(D_1);
          break;
        case 2:
          displaynum(D_2);
          break;
        case 3:
          displaynum(D_3);
          break;
        case 4:
          displaynum(D_4);
          break;
      }
    }

    int findn(int num) {
      int n = 0;
      while (num) {
        num /= 10;
        n++;
      }
      return n;
    }

    void displaynum(int *D_x) {
      for (int i = 0; i <= 3; i++) {

        digitalWrite(clockPin, LOW);
        digitalWrite(latchPin, LOW);

        shiftOut(dataPin, clockPin, LSBFIRST, D_x[i]);
        shiftOut(dataPin, clockPin, LSBFIRST, num[(getal / tallen[i]) % 10]);
        digitalWrite(latchPin, HIGH);
        delay(1);
      }
    }

body:
As Look Alterno stated it would be easier to directly use an LCD display. But if you really want to use the 7 segment display and the ATTiny85 you can use I2C to send the number to the ATTiny. There are libraries, that can use the USI hardware ot emulate a (nearly) full I2C bus. For example my [TinyWire library][1], that I composed from the previous TinyWireM and TinyWireS libraries. I2C needs only 2 pins (pin 0 as SDA and pin 2 as SCL I think), so you still have your 3 pins left for the display.

Then you would make the Arduino master and the ATTiny slave. Use the examples, that come with the library to learn it's usage. Note, that currently you can use the `write()` function only with one byte, so if you need bigger datatypes you need to split them to byte-level on your own.

  [1]: https://github.com/lucullusTheOnly/TinyWire


body: Could also use a chip with better resources, such as Attiny2313. 20 Pins, so a little larger than the '85, but you get a real serial port and SPI port.


message:
Is it possible to add an additional board on Arduino Web Editor (create.arduino.cc)?

I'm using a board that can be programmed via Arduino IDE (a NodeMCU with ESP8266) and I've configured the Windows client successfully. I've added an additional board through "Preferences" menu by specifying [its configuration url][1], following manufacturer's directions.

Now, I'm quite happy with the web editor, the one at [create.arduino.cc][2], and I'd like to use it with this board too. Is there any way to configure additional boards?

  [1]: http://arduino.esp8266.com/versions/2.4.0/package_esp8266com_index.json
  [2]: https://create.arduino.cc

body:
No, there isn't.

The web editor is completely closed. It's a service run by Arduino, and as such it will only support Arduino's own boards.

Two reasons:

1. Why should they spend the time, effort and money adding support for other people's products?
2. It adds value to their products to encourage you to use real Ardiuno hardware.

Business is business, after all.


message:
Two-wire Conductivity Sensor and Arduino Hook-up?

For the conductivity meter shown in the photo below, it is a non-NPN sensor for measuring conductivity / impedance.

I am trying to figure out the best method for measuring the output of the sensor using an Arduino.

I am told from the supplier that there is no polarity.  I was planning to connect one of the leads through a 10k resistor to an analog input (A0) on my Arduino; and the other lead to 5V?

Without much other information on the sensor, is a 10k resistor a good place to start?

 [![enter image description here][1]][1]

[![enter image description here][2]][2]

[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/Qzm8T.png
  [2]: https://i.stack.imgur.com/9O9Qz.jpg
  [3]: https://i.stack.imgur.com/ymrN2.jpg

body:
It depends on the conductivity of the liquid which it is going to be placed/submerged to. For example if the liquid is highly conductive(ex. saltwater), then a 10k Ohms resistor should be fine. But if the liquid conductivity is low(ex. tap water), then its best to measure the output voltage of one lead with respect to the Arduino's ground to be sure what value of resistor to apply to or if there is no resistor needed at all.

But generally if you are going to supply it with 5 Volts, it should be fine to connect it with the Arduino's Analog inputs directly as the operating voltage of the Arduino itself is also 5 Volts.

Cheers!


message:
Enroll more than one finger on Unique Id in R305 FingerPrint Module Working With Arduino

I am working on a project when I have to enroll and Submit the attendance of the fingerprints.

What I have : I am able to enroll single fingerprint on a different unique ID. Using AdaFruit FingerPrint Sensor Library.
I have :

> R305 FingerPrint Sensor having 1000 fingerPrint storage and
> Arduino Uno

What I want : I want to enroll more than one finger Prints on same Unique Id.
How to do it, Please anyone Help me with  this.
Help will be appreciated. Thanks

body:
Each fingerprint must have a unique ID that refers to that fingerprint.

What you need next is a table to associate multiple fingerprint IDs with "persons" so that you can find out which person belongs to a particular print scan.

You didn't say if you were holding fingerprint and person data within the Arduino or on some network-based storage system, but if we assume that this is entirely self-contained in the Arduino you would need to write the association table to some kind of storage that won't reset when the Arduino loses power, such as an EEPROM. The Uno has a "built in" EEPROM on the ATMega328p chip, but it only holds 1024 bytes. There are external EEPROMs that communicate via SPI or I2C that can hold more data.

As to the actual data structure -- it can be as simple as a 2-dimensional array, with one dimension holding the fingerprint ID, and the other holding a person ID. For multiple fingerprints of the same person, the table would have multiple rows with the same person ID, but different fingerprint IDs.

You could also make an array of `struct` datatypes, or create class, etc. But the point is that the "Unique ID" matching only ONE print from the fingerprint sensor is a limitation you have to work with.


message:
Why my ISR is giving impossible values?

I have a very simple ISR:

<!-- language: c++ -->

    const uint32_t PATTERN_A = 0xFF00FF00;
    const uint32_t PATTERN_B = 0x00FF00FF;
    volatile uint32_t count = 0;
    volatile uint32_t toggle = PATTERN_A;

    // My ISR
    void callback()
    {
     count++;
     toggle = (count % 2) ? PATTERN_A : PATTERN_B;
    }

The idea is that the `toggle` variable takes values 0xFF00FF00 or 0xFF00FF00 depending on the evenness of the `count` variable. This is the only place where `toggle` is changed, but it's used (read-only) in the sketch.

I don't know why, but `toggle` gets all sort of random values during execution.

What is happening here?

body:
The problem is a combination of several causes.

**Assignments are not atomic**

An *atomic* operation is something that is completely done or not. The opposite is some operation that can be disrupted while executing, leaving thing in a inconsistent state.

This is how the `count++` works at machine level in Arduino:

    void callback()
    {
     count++;
      fa: 80 91 0a 02  lds r24, 0x020A
      fe: 90 91 0b 02  lds r25, 0x020B
     102: a0 91 0c 02  lds r26, 0x020C
     106: b0 91 0d 02  lds r27, 0x020D
     10a: 01 96        adiw r24, 0x01 ; 1
     10c: a1 1d        adc r26, r1
     10e: b1 1d        adc r27, r1
     110: 80 93 0a 02  sts 0x020A, r24
     114: 90 93 0b 02  sts 0x020B, r25
     118: a0 93 0c 02  sts 0x020C, r26
     11c: b0 93 0d 02  sts 0x020D, r27

The first four instruction loads the four `count` bytes into four separate register, the laboriously increment it by one and then store it back in RAM.

Now, `toggle` is a variable of interest and you want to use it inside `loop`, like this:

    void loop()
    {
     uint32_t x = toggle;
        ...
    }

And at machine level you get

     uint32_t x = toggle;
     414: 60 91 04 01  lds r22, 0x0104
     418: 70 91 05 01  lds r23, 0x0105
     41c: 80 91 06 01  lds r24, 0x0106
     420: 90 91 07 01  lds r25, 0x0107

Here we are simply copying the `toggle` variable into our `x` variable. As you can see, the copy takes four machine instructions to get completed.

Now, what happens if an interrupt comes while you are copying (or using) `toggle`?

An interrupt suspend the assignment, go to the ISR (`callback` in this case and change `toggle` value. Upon return, copying continues, mixing bytes from the old and new value.

**You must use volatile**

Any global variable used inside an ISR must be declared `volatile`. This is an hint to the compiler that the variable could change unexpectedly. Therefore, the volatile variable must be always read afresh, discarding any cached value.

**Critical section**

The rule for using values changed by ISR is simple:

 1. Always copy the ISR's global variables to your own temporary variable.
 2. Before coping, disable interrupts and reenable it after the copy is done. This prevent the ISR from executing while your are copy the values.

**Demo**

This little demo shows you all of this in action.

The sketch collect all the values from `toggle` (not disabling interrupts) during one minute and after that print a table showing what it got.

    /*
     * This sketch show how to deal with variables shared between ISR and main thread.
     *
     * By Look Alterno 2018
     */

    #include "TimerOne.h"

    volatile uint32_t count = 0;
    const uint32_t PATTERN_A = 0xFF00FF00;
    const uint32_t PATTERN_B = 0x00FF00FF;

    volatile uint32_t toggle = PATTERN_A;

    #define MAX_CASES 16
    struct {
     unsigned long value;
     int count;
    } found[MAX_CASES];
    int freeFound = 0;

    #define PRINT_INTERVAL 60000L

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

     while(!Serial);

     Serial.println("");
     Serial.println("Test assignment under interrupts");
     Serial.println("");

     Serial.print("Value A=");
     Serial.println(PATTERN_A, HEX);
     Serial.print("Value B=");
     Serial.println(PATTERN_B, HEX);

     Timer1.initialize(500);
     Timer1.pwm(9, 512);
     Timer1.attachInterrupt(callback);

     pinMode(A0, INPUT);
     randomSeed(analogRead(A0));
    }

    void callback()
    {
     count++;
     toggle = (count % 2) ? PATTERN_A : PATTERN_B;
    }

    void loop()
    {
      static unsigned long prev = 0;

      //  A random delay to simulate some real, variable work being done.
     delayMicroseconds(random(250));

      // This is the critical section.
    //  noInterrupts();
     uint32_t x = toggle;
    //  interrupts();

      // Now, let's see what value we got.
     if(x != PATTERN_A && x != PATTERN_B) {
      insert(x);
     }

      // Print values found
      unsigned long now = millis();
      if (now - prev > PRINT_INTERVAL) {
        printFound();
        prev = now;
      }
    }

    /*
     * Add a value to a table for counting.
     */
    void insert(unsigned long x)
    {
     int index = 0;

     while(index < freeFound && found[index].value != x) {
      index++;
     }

     if(index < MAX_CASES) {
      if(index == freeFound) {
       found[index].value = x;
       found[index].count = 1;
       freeFound++;
          Serial.print(freeFound);
          Serial.print(". Add=");
          Serial.println(x, HEX);
      } else {
       found[index].count++;
      }
     } else {
      Serial.print("*** Table overflow. value=");
      Serial.print(x, HEX);
      Serial.println(" ***");
     }
    }

    /*
     * Print the table of found values so far.
     */
    void printFound() {
      Serial.println("");
      Serial.println("Values found");
      Serial.println("");
      Serial.println("Value - Count");
      for (int i=0; i < freeFound; i++) {
        Serial.print(found[i].value, HEX); Serial.print(" - "); Serial.println(found[i].count);
      }
    }

If you uncomment `noInterrupts` and `interrupts`, every thing works just fine.

**Other CPU**

More powerful CPUs have atomic assignments, but following this practices makes your code portable across platforms, no matter what. Think of *defensive programming*


message:
Is an Arduino Uno required to send any sort of command to a NodeMCU?

I have an Amica ESP8266 NodeMCU I want to send some commands to. I have tried sending some commands like 'AT' and 'AT+CWLAP' but I do not get any sort of output for any command I send to it.

Actually I did not send commands the first time I bought it. I flashed it with a `deauther` program made by spacehuhn then I erased the chip using the `esptool.py --port /dev/tty.SLAB_USBtoUART erase_flash` command multiple times. Then I heard that you can send commands to the NodeMCU using the Serial Monitor using Arduino. So I tried it but no output. So my question is whether I need an Arduino Uno or has the command which I used to erase the factory code of the NodeMCU broken something?

PS. I am a newbie so I don't know much of this stuff.

body:
With erase_flash you deleted the AT firmware from flash. You can load it back with esptool or with [Flash Download Tool (Windows only)][1].

[AT firmware download page][2]

Addresses for 4 megabyte flash (more in readme.md of AT firmware):

    esptool.py -p /dev/tty.SLAB_USBtoUART write_flash 0x0 boot_v1.7.bin 0x01000 at/512+512/user1.1024.new.2.bin 0x3fc000 esp_init_data_default.bin 0xfe000 blank.bin 0x3fe000 blank.bin

  [1]: http://espressif.com/en/support/download/other-tools
  [2]: http://espressif.com/en/support/download/at?keys=&field_type_tid[]=14


message:
Arduino MQTT Bluetooth

Is there a library to use MQTT with a bluetooth module (HC-06) instead of WiFi? If not is there a similar ready for use implementation of a publisher subscriber pattern available?

body:
MQTT is TCP/IP native. If you want to access it via Bluetooth, you need a gateway; a device that translate protocols. You need one for the specific protocols involved: MQTT, TCP/IP and Bluetooth.

Google "MQTT Bluetooth gateway" to find alternatives like this one:

[![enter image description here][1]][1]

> The iGS01 gateway listens for beacons, gets their advertising data and
> forwards it on to your server or an IoT server via TCP, HTTP(S) or
> MQTT. It can be used to feed back-end systems that report on the
> presence or absence of iBeacon or Eddystone beacons or act on beacon
> sensor (e.g. accelerometer, temperature, light, humidity) data.

[![enter image description here][2]][2]

> The gateway connects to your local 2.4GHz frequency band WiFi access
> point and is managed via a web browser interface. It can  be connected
> via WPS (press button on both the gateway and the WiFi access point).
> It can also be managed via Telnet commands from other hardware (or a
> human).
>
> For MQTT/MQTTS, the host, port, username, password and a root CA cert
> can be provided.

There are also software only solutions available, but I didn't found a generic one, only specific for certain vendors.

  [1]: https://i.stack.imgur.com/zTSX3.jpg
  [2]: https://i.stack.imgur.com/zCduc.png


message:
Can I support all these sensors?

I'm new to arduino's and am currently working on a project which requires a lot of different sensors. I was just wondering if its possible to use all the following sensors on a single Arduino Uno:

- 2 Separate Load sensors (i.e giving different readings) controlled with an load cell amplifier
- a Gyro Sensor
- an Accelerometer
- and an ESC

If its not possible, could someone please tell me what hardware I would need to run all these sensors together. Thanks :).

body:
It really depends on how many pins each sensor uses. The signal pins of all the sensors used would have to be equal to or less than the total number of I/O pins on the arduino, which would be 20. So you can control 20 sensors if they each have one signal pin.

However, to control more sensors (or use a lower pin count on arduino) you can use multiplexing. See [Two sensors on one input][1] or [MULTIPLEXING WITH ARDUINO AND THE 74HC595][2].

Theoretically, you can control an infinite number of sensors with the use of multiplexing.

  [1]: https://arduino.stackexchange.com/questions/14489/two-sensors-on-one-input
  [2]: http://www.instructables.com/id/Multiplexing-with-Arduino-and-the-74HC595/


body:
Yes, it should work. The HX711 need two pins each (one for clock and one for shifting out the data). The MPU6050 seems to have an I2C interface, which needs two lines (SCL and SDA). And lastly an ESC uses a PWM pin.

All in all this needs 7 pins, way less than an Arduino UNO has.

Note that having enough pins doesn't mean, that you can usw all the sensors at the same time. You might habe to disable one for a short time to do something else.


message:
Failed to initialise SD card on Leonardo

I'm trying to connect SD card reader to my Arduino. For testing i'm running [CardInfo][1] example.

It seems like it runs ok when I'm running it on my Arduino UNO, but it fails to initialise SD Card while i'm running it on any Arduino with Atmega32U4 chip. I tried on two Leonardo's and Micro Pro.

This is my pinout:

    CardReader       Arduino

    CS          <->     4
    SCK         <->    13
    MISO        <->    12
    MOSI        <->    11
    VCC         <->    5V
    GND         <->    GND

I'm using Library in version 1.2.1 if that's make difference.

Does anyone have any suggestions?

  [1]: https://www.arduino.cc/en/Tutorial/CardInfo

body:
A Leonardo has the SPI pins on the ICSP header, not on pins 11, 12, 13.

[![Leonardo pinout][img_l]][link_l]

And a Pro Micro has the SPI pins on 14, 15, 16.

[![Pro Micro pinout][img_pm]][link_pm]

  [img_l]: https://i.stack.imgur.com/c9i7U.png
  [link_l]: http://www.pighixxx.com/test/portfolio-items/leonardo/
  [img_pm]: https://i.stack.imgur.com/uAqD5.png
  [link_pm]: http://www.pighixxx.com/test/2016/07/pro-micro-pinout/
  [pin_def]: https://github.com/arduino/Arduino/blob/1.8.5/hardware/arduino/avr/variants/leonardo/pins_arduino.h#L111-L114