title: LCD Clock Millis Code Issue

text:
# Question
Title: LCD Clock Millis Code Issue
I am trying to create a clock on an LCD when I upload the code below, all it displays is a very rapidly flashing 0:00 PM. Please help. This is my first time using Millis.

```
#include <LiquidCrystal.h>   //includes LCD display library in sketch
LiquidCrystal lcd(27,26,25,24,23,22);   //determines pins of the LCD display
int seconds = 0;    //generates integer storing seconds
int minutes = 0;    //generates integer storing and showing minutes
int hours = 12;      //generates integer storing hours in 24 hour mode
int displayHours;      //generates integer displaying hours in 12 hour mode
unsigned long previousMillis = 0;   //creates a variable to store the amount of milliseconds since last update
const long interval = 1000;    //generates integer to find 1 second interval

void setup()
{
  lcd.begin(16,2);  //determines size of the LCD display
}

void loop()   //runs code repeatedly
{
  updateSeconds();   //runs the updateSeconds function
  clockShown();   //runs the clockShown function
  clockConversion();    //runs the clockConversion function
}

void updateSeconds()   //check to see if it's time to update the seconds integer
{
  unsigned long currentMillis = millis();  //generates the number of milliseconds program has been running
  if (currentMillis - previousMillis >= interval)
    {
      previousMillis = currentMillis; //updates the last time seconds was updated
      seconds = seconds ++;   //adds a second to the counter
   }
}

void clockShown()   //displays the time on an LCD display
{
  lcd.clear();   //resets screen on LCD
  lcd.setCursor(0,0);    //sets the place to start writing at the top left corner of the LCD
  lcd.print(displayHours);  //displays hours
  lcd.print(":");   //displays colon
  if(minutes <= 9)  //if the minute is 1 digit
  {
    lcd.print("0"); //displays 0
  }
  lcd.print(minutes);  //displays minutes
  if(hours < 12)lcd.print(" AM");  //displays AM in the morning
  if(hours >= 12)lcd.print(" PM");   //displays PM at night
}

void clockConversion()  //runs math to convert seconds minutes and hours
{
  if(seconds == 60) //when seconds is 60
  {
    seconds = 0;  //set seconds back to 0
    minutes = minutes ++;  //and add a minute
  }
  if(minutes == 60) //when minutes is 60
  {
    minutes = 0; //set minutes back to 0
    displayHours = displayHours ++; //and add an hour
    hours = hours ++; //and keep track of AM PM
  }
  if(displayHours == 13)  //if the hour being displayed is 13
  {
    displayHours = 1; //make it 1 instead
  }
}

```

# Answer
**Problem 1**

```
seconds = seconds ++;   //adds a second to the counter

```

This command grabs the value of `seconds`, increments the value of `seconds`, and then assigns the previously grabbed value to `seconds`. Or rather, it does nothing to change the value of `seconds`.

This mistake is repeated for `minutes`, `hours`, and `displayHours` in the `clockConversion()` function.

*Instead*

```
seconds++;

```

That was the main problem. The other problems described below are just for efficiency.

**Problem 2**

```
void loop()   //runs code repeatedly
{
  updateSeconds();   //runs the updateSeconds function
  clockShown();   //runs the clockShown function
  clockConversion();    //runs the clockConversion function
}

```

Why would you display the clock with `clockShown()` *before* you run `clockConversion()` to nice-up the minute and hour carry-over? Since you are running both `clockShown()` and `clockConversion()` at a high frequency, it doesn't matter much, but from a program flow point of view, I think it makes more sense to do the conversion before you display the values.

**Problem 3**

You are only updating `seconds` every 1000 milliseconds, using the `millis()` function. This is good.

However, nothing at all changes during the 1000 milliseconds between the incrementing of `seconds`. Why not pull the `millis()` parts into `loop()` and call all 3 functions only once per second?

```
void loop()   //runs code repeatedly
{
  unsigned long currentMillis = millis();  //generates the number of milliseconds program has been running
  if (currentMillis - previousMillis >= waittime)
  {
    previousMillis = currentMillis; //updates the last time seconds was updated

    updateSeconds();   //runs the updateSeconds function
    clockConversion();    //runs the clockConversion function
    clockShown();   //runs the clockShown function
  }
}

```
> 2 votes

---
Tags: lcd, millis
---


# Question
Title: The code fails to generate the values I want, when both trigger pins 2, 3 are high or low. Why?
```
/*aim of the program is to generate 2 different varying frequency from the
same output which is controlled by 2 triggers*/
void setup()
{
    pinMode(2,INPUT); //setting the trigger pins 2,3
    pinMode(3,INPUT);
    pinMode(6,OUTPUT); //output pin
}

void loop()
{
    if(digitalRead(2)==HIGH && digitalRead(3)==LOW) { //trigger conditions
        infra();
    }
    else if(digitalRead(2)==LOW && digitalRead(3)==HIGH) {
        red();
    }
    else if((digitalRead(2)==HIGH && digitalRead(3)==HIGH) || (digitalRead(2)==LOW && digitalRead(3)==LOW)) {
        Serial.println('help');
    }
}

void infra() //function varies sinosoidaly (working)
{
    float f;

    for(f=16000; f<=20525; f+=4.525) {
        tone(6,f);
    }

    for(f=20525; f>=16000; f=f-4.525) {
        tone(6,f);
    }
}

void red() //function varies sinosoidaly (working)
{
    float p;

    for(p=25000; p<=32071; p+=7.071) {
        tone(6,p);
    }

    for(p=32071; p>=25000; p=p-7.071) {
        tone(6,p);
    }
}

```

# Answer
> 2 votes
To send anything to serial you need to initialize it first with:

```
void setup()
{
    Serial.begin(115200);
    //other code
}

```

And you are using wrong quotes for the string.
They should be double quotes `"` not single ones `'`.

Also you could simplify your code, if you removed the third `if`, since it's just checking the already known state at that point.

You should also read the button state only once, save them into a variable and then just compare those variables.

```
bool button1_state = digitalRead(2);
bool button2_state = digitalRead(3);
if (button1_state && !button2_state) {
    infra();
}
else if (!button1_state && button2_state) {
    red();
}
else {
    Serial.println("help");
}

```

---
Tags: signal-processing
---


# Question
Title: Does the tone() generates unwanted signal?
I was trying to use the tone function for another project but I found that it also generates an undesired frequency (not the harmonics above of square wave it generates) but a lower frq square wave. Is this normal or somethings wrong with my implementation? the code is pretty simple:

```
void setup()
{
    pinMode(7,OUTPUT); //set the pin as output
    tone(7,10000); //start a 10KHz tone
    while(true); //stay here
}

void loop()
{ }

```

hardware was an Uno also tried different pins above but same results. first I tried a 470R and an 8R speaker. then guess maybe the inductance, or something else causing it so I used a piezo buzzer as seen below:

```
Pin(x)--->10KR--->piezo--->GND

```

however it was the same. I measured the lower frequency as 19.55Hz for a tone(10000) and 39.05Hz for tone(40000); both are pretty annoying. what causes this and whats the workaround?

# Answer
I could reproduce the problem with the posted code. This will be caused by the fact that the tone library uses interrupts and has to manually toggle pins, which will always have a bit of jitter. You are better off setting up a hardware timer to generate the tones, this does not require interrupts.

For example:

```
#include <TonePlayer.h>

TonePlayer tone1 (TCCR1A, TCCR1B, OCR1AH, OCR1AL, TCNT1H, TCNT1L);  // pin D9 (Uno), D11 (Mega)

void setup()
  {
  pinMode (9, OUTPUT);  // output pin is fixed (OC1A)

  tone1.tone (10000);  // 10 kHz
  }

void loop() { }

```

This uses a fairly small library I wrote, which you can download from http://www.gammon.com.au/Arduino/TonePlayer.zip

---

# Library code

If you don't want to trust some zip file from a random web site, here is TonePlayer.h:

```
/*
 Play tones with hardware timers
 Author: Nick Gammon
 Date:   1 April 2013
*/

#include <Arduino.h>

class TonePlayer
  {
  // addresses of output ports - NULL if not applicable
  volatile byte * const timerRegA_;
  volatile byte * const timerRegB_;
  volatile byte * const timerOCRH_;
  volatile byte * const timerOCRL_;
  volatile byte * const timerTCNTH_;
  volatile byte * const timerTCNTL_;

  public:
    // constructor
    TonePlayer (
          // ports
          volatile byte & timerRegA,
          volatile byte & timerRegB,
          volatile byte & timerOCRH,
          volatile byte & timerOCRL,
          volatile byte & timerTCNTH,
          volatile byte & timerTCNTL)
       :
         timerRegA_  (&timerRegA),
         timerRegB_  (&timerRegB),
         timerOCRH_  (&timerOCRH),
         timerOCRL_  (&timerOCRL),
         timerTCNTH_ (&timerTCNTH),
         timerTCNTL_ (&timerTCNTH)
  { }

    void tone (const unsigned int Hz);
    void noTone ();

  };  // end of TonePlayer

/*

 PERMISSION TO DISTRIBUTE

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software
 and associated documentation files (the "Software"), to deal in the Software without restriction,
 including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
 and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
 subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 LIMITATION OF LIABILITY

 The software is provided "as is", without warranty of any kind, express or implied,
 including but not limited to the warranties of merchantability, fitness for a particular
 purpose and noninfringement. In no event shall the authors or copyright holders be liable
 for any claim, damages or other liability, whether in an action of contract,
 tort or otherwise, arising from, out of or in connection with the software
 or the use or other dealings in the software.

 */

```

And here is TonePlayer.cpp:

```
/*
 Play tones with hardware timers
 Author: Nick Gammon
 Date:   1 April 2013
 */

#include <TonePlayer.h>

void TonePlayer::tone (const unsigned int Hz)
{
  // it takes two toggles for one "cycle"
  unsigned long ocr = F_CPU / Hz / 2;
  byte prescaler = _BV (CS10);  // start with prescaler of 1  (bits are the same for all timers)

  // too large? prescale it
  if (ocr > 0xFFFF)
    {
    prescaler |= _BV (CS11);    // now prescaler of 64
    ocr /= 64;
    }

  // stop timer
  *timerRegA_ = 0;
  *timerRegB_ = 0;

  // reset counter
  *timerTCNTH_ = 0;
  *timerTCNTL_ = 0;

  // what to count up to
  *timerOCRH_ = highByte (ocr);
  *timerOCRL_ = lowByte (ocr);

  *timerRegA_ = _BV (COM1A0);             // toggle output pin
  *timerRegB_ = _BV (WGM12) | prescaler;  // CTC
  }  // end of TonePlayer::tone

void TonePlayer::noTone ()
  {
  // stop timer
  *timerRegA_ = 0;
  *timerRegB_ = 0;
  } // end of TonePlayer::noTone

/*
 PERMISSION TO DISTRIBUTE

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software
 and associated documentation files (the "Software"), to deal in the Software without restriction,
 including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
 and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
 subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 LIMITATION OF LIABILITY

 The software is provided "as is", without warranty of any kind, express or implied,
 including but not limited to the warranties of merchantability, fitness for a particular
 purpose and noninfringement. In no event shall the authors or copyright holders be liable
 for any claim, damages or other liability, whether in an action of contract,
 tort or otherwise, arising from, out of or in connection with the software
 or the use or other dealings in the software.

 Example of use:

 #include <TonePlayer.h>

 ...

 TonePlayer tone1 (TCCR1A, TCCR1B, OCR1AH, OCR1AL, TCNT1H, TCNT1L);  // pin D9 (Uno), D11 (Mega)

 or, on the Mega 2560:

 TonePlayer tone3 (TCCR3A, TCCR3B, OCR3AH, OCR3AL, TCNT3H, TCNT3L);  // pin D5
 TonePlayer tone4 (TCCR4A, TCCR4B, OCR4AH, OCR4AL, TCNT4H, TCNT4L);  // pin D6
 TonePlayer tone5 (TCCR5A, TCCR5B, OCR5AH, OCR5AL, TCNT5H, TCNT5L);  // pin D46

 ...

 pinMode (9, OUTPUT);  // D9 on Uno, D11 on Mega 2560
 tone1.tone (440);     // play 440 Hz
 delay (500);          // wait half a second
 tone1.noTone ();      // stop playing

 or, on the Mega 2560:

 pinMode (46, OUTPUT);
 tone5.tone (440);

*/

```

Just put those two files inside a folder "TonePlayer" inside the `libraries` folder inside your sketches folder, and it should all work.

The library is written for the **16-bit timers**, and supports Timer 1 on the Atmega328, and Timers 1, 3, 4, 5 on the Atmega2560. Comments inside the library show how to set up the other timers.
> 5 votes

# Answer
Did you measure it with good equipment? How much dB is the lower frequency? Can you show a spectrum plot?

It could be the software pin toggle. The tone selects a hardware timer, which is used to generate an interrupt. The output pin is toggled in that interrupt. It is in the file Tone.cpp. That interrupt could be delayed by a timer0 interrupt (for millis).
The timer0 runs at 16MHz/(64\*256). With those numbers I can not get to the interference frequency that you mentioned.
You could try to use the output of a hardware timer. For example the toneAC library generates a tone at pin 9 and 10. That is as steady as the 16 MHz crystal (very steady).

It could be the equipment that you use to test.

It could be the speaker. Some speakers generate other tones. I had a ultrasound speaker which I could hear squeeking at a much lower frequency. After a search on the internet, I found that such a speaker is known to create lower frequency whistling noises.

It could be the 5V voltage is changed somehow by the circuit.
> 0 votes

---
Tags: arduino-uno, sound
---


# Question
Title: Unable to connect ESP8266 to WPA2+Enterprise network
I am trying to connect ESP8266 module to WPA2+Enterprise network with my ssid, username and password and the latest version supports such connection. I followed this link, and the code:

```
#include "ESP8266WiFi.h"
extern "C" {
  #include "user_interface.h"
  #include "wpa2_enterprise.h"
}

static const char* ssid = "ssid";
static const char* username = "username";
static const char* password = "password";
const char* host = "host_ip";

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

  Serial.print("Connecting to ");
  Serial.println(ssid);
   // Setting ESP into STATION mode only (no AP mode or dual mode)
  wifi_set_opmode(0x01);

  struct station_config wifi_config;

  memset(&wifi_config, 0, sizeof(wifi_config));
  strcpy((char*)wifi_config.ssid, ssid);

  wifi_station_set_config(&wifi_config);

  wifi_station_clear_cert_key();
  wifi_station_clear_enterprise_ca_cert();

  wifi_station_set_wpa2_enterprise_auth(1);
  wifi_station_set_enterprise_username((uint8*)username, strlen(username));
  wifi_station_set_enterprise_password((uint8*)password, strlen(password));

  wifi_station_connect();
  Serial.print("Wifi station connect status:");
  Serial.println(wifi_station_get_connect_status());

  // Wait for connection AND IP address from DHCP
  while (WiFi.status() != WL_CONNECTED) {
    Serial.println(WiFi.status());
    delay(2000);
    Serial.println("Not connected");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop()
{
  delay(2000);
}

```

**OUTPUT:**

```
Connecting to ssid
Wifi station connect status:1
6
Not connected
6
Not connected
.....

```

Status 6 is WL\_DISCONNECTED,i.e., module is not configured in station mode. I am not able to figure out what is causing the problem.

# Answer
> 1 votes
The clear commands are not useful until after you have connected.
I use these commands just before setting user ID and password:

```
wifi_station_set_enterprise_identity((uint8*)username1, strlen(username));
wifi_station_set_enterprise_ca_cert(ca_cert, sizeof(ca_cert));

```

It is necessary that the radius server have `default_eap_type` set to TTLS or PEAP for username/password authentication. Perhaps there is another possibility, but there is a bug in ESP8266 so it does not properly search for supported EAP types.

```
const char* username1 = "anonymous"; //works for me

u8 ca_cert[] = "-----BEGIN CERTIFICATE-----\n"
"MIIFETCCA/mgAwIBAgIJAO0ntD34r/+QMA0GCSqGSIb3DQEBCwUAMIGiMQswCQYD\n"
"VQQGEwJVUzEXMBUGA1UECAwOTm9ydGggQ2Fyb2xpbmExDzANBgNVBAcMBkR1cmhh\n"
"bTEeMBwGA1UECgwVTWl0Y2hlbGwvVHJhbXBlciBJbmMuMR8wHQYJKoZIhvcNAQkB\n"
"FhBidXJ0bXNAZ21haWwuY29tMSgwJgYDVQQDDB9CdXJ0IFNlbGYgQ2VydGlmaWNh\n"
"dGUgQXV0aG9yaXR5MB4XDTE4MDEyMzE1NTgxOFoXDTE4MDMyNDE1NTgxOFowgaIx\n"
"CzAJBgNVBAYTAlVTMRcwFQYDVQQIDA5Ob3J0aCBDYXJvbGluYTEPMA0GA1UEBwwG\n"
"RHVyaGFtMR4wHAYDVQQKDBVNaXRjaGVsbC9UcmFtcGVyIEluYy4xHzAdBgkqhkiG\n"
"9w0BCQEWEGJ1cnRtc0BnbWFpbC5jb20xKDAmBgNVBAMMH0J1cnQgU2VsZiBDZXJ0\n"
"aWZpY2F0ZSBBdXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB\n"
"AQC2O2m4JCmqimeztaZ8JasIuZqksrxvCjyWpkykoGzoR6v1/kDSuLgdp7EmtLKN\n"
"vOJPQ2ea0yVvkFf0dQYcgDhNdAsXcqskMOprS+jefzlLQUbU1jTk+AOSiOcmxWT1\n"
"H8uYhSp/1TkkWDM8dVO9RRIQyigVinsJNhdPyUVsTaQh3s29AL8CboixUNZWngOo\n"
"d1+66lwy4N+3hXACJWlurgvc0q7RfqSqfJY/+lugfID0ANpGQqqu1Dq2IXZbLyx9\n"
"roOPpC+fqX2wn5g9+RuA18OY/GPtkHc6clAoiJDGXsTRpffgsI5spdJ26WknbhO/\n"
"3Q2vQJ2Q5m/QvSp55qOM5nevAgMBAAGjggFGMIIBQjAdBgNVHQ4EFgQUT3hChU84\n"
"EEXHesDdKOtPqfhrg68wgdcGA1UdIwSBzzCBzIAUT3hChU84EEXHesDdKOtPqfhr\n"
"g6+hgaikgaUwgaIxCzAJBgNVBAYTAlVTMRcwFQYDVQQIDA5Ob3J0aCBDYXJvbGlu\n"
"YTEPMA0GA1UEBwwGRHVyaGFtMR4wHAYDVQQKDBVNaXRjaGVsbC9UcmFtcGVyIElu\n"
"Yy4xHzAdBgkqhkiG9w0BCQEWEGJ1cnRtc0BnbWFpbC5jb20xKDAmBgNVBAMMH0J1\n"
"cnQgU2VsZiBDZXJ0aWZpY2F0ZSBBdXRob3JpdHmCCQDtJ7Q9+K//kDAPBgNVHRMB\n"
"Af8EBTADAQH/MDYGA1UdHwQvMC0wK6ApoCeGJWh0dHA6Ly93d3cuZXhhbXBsZS5v\n"
"cmcvZXhhbXBsZV9jYS5jcmwwDQYJKoZIhvcNAQELBQADggEBADNmDxddEh1XSo8J\n"
"fanCRuYqngpVFtKCzRNCtQ7aOAPrj6gRMtMAqQhlYmcbxjaVOCboAvJ8evY8x5We\n"
"YU6eIAmg95PlDws8EvcVQhO2ZYcuOHTvdu5Q4Ior0oXaCfqdS35YcPW7pRGprY/x\n"
"w7kbG84FFatpXPuDGQB65haqQ2KXPrILiE/jAKpTu9EBLEEN4uIAuxbB6unARovX\n"
"YoXIQHFc32bZAjihquvs4J7FNkcSr3lJpuv03dryqMB+Qn3G8yM7PFLNL2QyS0Zu\n"
"UbS5kDO7UqbTjtrUDolp5sUNvyrkX5ILYfZeEeaHqAlA20SFqNG7BcTY222NsCft\n"
"yNXqX1c=\n"
"-----END CERTIFICATE-----";

```

works for me. I have to go back and check whether those `\n`'s are needed.

I think I found the enterprise\_identity command important for both TTLS and PEAP, and I found I needed a `ca_cert` to do PEAP but not necessary for TTLS. I am not certain why.

---
Tags: esp8266, wifi, wireless
---


# Question
Title: running a dc motor with a small L298N module and an arduino and the L298N library
I have a small L298N module which I would like to use to run a couple of dc motors. The module I have is smaller than most of the ones you see on eBay, it looks like this...  I am trying to use the following library : https://github.com/AndreaLombardo/L298N

I have managed to get the motor going forwards and backwards, but the problem is, this module doesn't have a pin for enable ( EN for PWM from the Arduino) and the library seems to require this; therefore I can't control the speed of the motors.

Does anyone have any experience with these modules? Is there a different technique I should be using? Is there another library that works with these kind of modules?

All help appreciated.

# Answer
PWM is used to control the duty cycle and not the voltage directly so your PWM will work directly on the input pins of motor driver and you will be able to control the speed. just use analogWrite on the input pin which was held HIGH and HOLD the other pin to LOW. If you desire to change the direction while simultaneously controlling the speed. just analogWrite both the pins. Just keep in mind that the duty cycle of both the pins should not be tweaked simultaneously. while the speed is being controlled in one direction the other pin should be at analogWrite(other,0).
> 1 votes

# Answer
you can use this snippet in your code if you want

```
void Loop()
{
   //this is basically to demostrate how you can control the speed
   // and direction simultaneously
   for(i=0;i<256;i+=51)
   {
      analogWrite(motorForwardPin,i);
      analogWrite(motorBackwardPin,0);
      delay(2000);
   }
   for(i=0;i<256;i+=51)
   {
      analogWrite(motorForwardPin,0);
      analogWrite(motorBackwardPin,i);
      delay(2000);
   }
}

```
> 0 votes

---
Tags: esp8266, motor, l298n
---


# Question
Title: bit_is_clear(ACSR, ACO) Instead of digital_read(1)==LOW
I am attempting to create a program for the atmega328P which will enable the aux input of a Toyota Corolla stereo. In order to do this, I'm bitbanging AVC LAN. Nearly all of my research comes from this site: https://github.com/halleysfifthinc/Toyota-AVC-LAN

In this example, Frigon has wired his Atmega8 in a peculiar way. Instead of connecting the + terminal directly to a single pin of his Atmega8, he's connected it to a pulldown resistor, resisted it to the - terminal (presumably for bus termination) and a digital pin as well as an analog pin. The - terminal has been given similar strange treatment.

In his function ReadBits(), he waits for a physical 1, then sets a timer and waits for a physical 0 to measure the length of the pulse. But when he does this, he uses the equivalent of

```
while ( bit_is_clear( ACSR, ACO ) );

```

That's completely Greek to me. Does this have something to do with something called in Internal Analog Comparator?

I attempted to create something similar using

```
while( digitalRead( 2 ) );

```

but I'm reading static as well as honest-to-goodness pulses. I assume that, anyways, because I'm getting pulses of length 2-7 ticks when many are closer to 20-40 ticks (measured using TCNT0 with no custom prescaler).

So... what exactly is he doing with ACSR and ACO? Why is his + and - terminals connected to more than one pin? Why are his diodes there?

=========================EDIT=======================

Following Edgar's advice, I've reworked my schematic and code to closely match Frigon's work. Below is my code:

```
#include <avr/wdt.h>

#define fwVer       "v0.1"
#define fwDt        __DATE__
#define DATAPIN     2

//====================================================================================COPYPASTED
#define DATAIN_PIN              ACSR
#define DATAIN                  ACO

#define INPUT_IS_SET            ( bit_is_set( DATAIN_PIN, DATAIN ) )
#define INPUT_IS_CLEAR          ( bit_is_clear( DATAIN_PIN, DATAIN ) )
//===================================================================================WHAT DOES THIS MEAN

byte data[255];

void setup() {
  LedOff();

  Serial.begin(9600);

  pinMode(3,OUTPUT);
  pinMode(2,OUTPUT);
  digitalWrite(3,HIGH); //"leave the pins tri-stated" according to Frigon
  digitalWrite(2,LOW);
  pinMode(LED_BUILTIN,OUTPUT);

  //two second watchdog
  wdt_enable( WDTO_2S );

  Serial.println("Firmware "+String(fwVer)+", compiled on "+fwDt);
  LedOff();
}

void LedOff() {
  digitalWrite(LED_BUILTIN, LOW);
}
void LedOn() {
  digitalWrite(LED_BUILTIN, HIGH);
}

void loop() {
  wdt_reset();
  if (INPUT_IS_CLEAR) LedOff();
  else LedOn();
}

```

Schematic: https://i.stack.imgur.com/0UNzF.jpg (mistake on the schematic - I connected 5v to vcc and ground to ground) If it matters, I'm powering the head unit and the arduino from the 12v and 5v rails of an ATX power supply. They both take the same ground.

My code should theoretically only turn on my led whenever the head unit broadcasts bits, but it's just sort of erratically blipping on and off or fading gently at random. I've triple checked my wiring (breadboard if that matters). Why is this happening? Is there something about bit\_is\_clear(ACSR,ACO) that I don't understand?

# Answer
> Does \[`bit_is_clear(ACSR, ACO)`\] have something to do with something called in Internal Analog Comparator?

Exactly. `ACSR` is the “Analog Comparator Control and Status Register”. `ACO`, the “Analog Comparator Output” is one bit of this register. The ATmega328P has the same comparator, with the same register and bit names as the ATmega8. C.f. the datasheet. You should be able to use this part of the code as is.

> Frigon has wired his Atmega8 in a peculiar way. \[...\]

It seems to me that is termination is intended to ensure that, in the “floating level”, the line AVC− is at a potential higher than AVC+. In the “driving level”, the opposite should be true, with a difference of at least 120 mV.

> I attempted to create something similar using `while(digitalRead(2)) ;`

It's not surprising that it doesn't work. This is a differential bus. The information is carried by the potential difference between AVC+ and AVC−, not by the potential of a single wire. A difference higher than 120 mV should be interpreted and a high state. Your digital input instead reads a single wire and compares its potential to ground. The thresholds to switch between `LOW` and `HIGH` are typically around 2.1 and 2.6 V, with some hysteresis. This is far from being compatible with the signaling of the bus.

I recommend you follow Frigon's steps and use the analog comparator just as he does. The comparator will tell you which of AVC+ or AVC− has a higher potential, and it will not be bothered by the low level of the differential signaling.
> 0 votes

---
Tags: analogread, avr, can-bus
---


# Question
Title: avrdude: stk500_recv(): programmer is not responding after all tries
After months of good use, both my boards Mega 2560 and Uno became unavailable for uploading sketch or burning bootloader.

```
Sketch uses 444 bytes (1%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
C:\[...]bin/avrdude -CC:[...]avrdude\6.3.0-arduino9/etc/avrdude.conf -v -patmega328p -cstk500v1 -PCOM5 -Uflash:w:C:\Users\GREGOR~1\AppData\Local\Temp\arduino_build_242793/BareMinimum.ino.hex:i

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

         System wide configuration file is "C:[...]\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : stk500v1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03

```

**Facts :**

* v1.6.20 of the boards
* v1.8.5 of the IDE
* Windows 8.1 64bits
* Programmer: "AVR ISP"
* Drivers are fine (the boards are well recognized)
* Serial monitor works
* I'm trying to upload the "Bare minimum" exemple sketch
* Nothing in pin 0 and 1, nothing at all is plugged actually
* Get Board info:
* Uno : VID 2A03
* Mega2560 : VID 2A03
* From instructions here, every instruction is "echoed back"

**What i tried :**

Nothing works. If you have any idea.....

Thank you all !

# Answer
> 2 votes
It eventually worked by using **upload** / ctrl+U (what I *didn't try*... smh) instead of **upload using programmer** / ctrl+shift+U.

So i know now where it comes from, though I don't know what's wrong with AVR ISP.

---
Tags: uploading
---


# Question
Title: Why Commenting Serial.print() gives me a different value?
I am working on with `Cypress` and `Arduino`.I am trying to transfer the data from `cypress` and printing it to the `Serial Monitor` or Arduino. but the thing is when I am using `Serial.print(j)` it is showing the right value of i (See in the code about what is `i and j`), but when I comment or remove `Serial.print(j)` it is showing the wrong value of `i` For example, suppose cypress is sending data `00001934a` and then I am reading this value using

```
int j = mySerial.read()-'0';
// -'0' is for chaging ascii data to normal integer
//for example ascii value of `0` is 48
//so mySerial will read 48
// and exprerssion value will become `48-48 = 0`

```

My code

```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX
void setup() {
Serial.begin(57600);
 while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

mySerial.begin(4800);
}

int  i = 0;
int j = 0;
void loop() {
if (mySerial.available()) {

        while(j!=49){
        i = i*10 + j;
        j = mySerial.read()-'0';
         //49 is the ascii value of a, I am using this for acting like
         //a flag, so that i can see the break in data

        Serial.println(j);//commeting this line is causing the problem
      }
   Serial.print(i);
   }
}

```

when the line is not commented the output was

```
0
0
0
0
1
9
3
4
49
193 //this is the value of i which is correct one

```

but when I comment the line `Serial.println(j)` the output was

```
   14569 // I don't know what the hack is this.

```

Hopefully the problem is understandable, but still, you can comment for more detail. BTW I am using SoftwareSerial.

# Answer
Your serial reading is completely flawed:

```
if (mySerial.available()) {

    while(j!=49){
    i = i*10 + j;
    j = mySerial.read()-'0';

```

What you are saying there is:

* If there is *at least one* character available:
* Read as many characters as can until I get 49.

The main thing wrong with that is that you try and read characters that just don't exist. Serial comes in a byte a time and you *must* wait for those characters to arrive before attempting to read them. By adding the serial print into your loop you are slowing it down and, by chance, giving the characters time to arrive.
> 1 votes

# Answer
Majenko has correctly diagnosed your problem, and the blog post he linked to is definitely a must-read. The suggested solution, namely buffering the input until you can read a complete message, is presumably the most standard way of dealing with an input stream.

It is, however, not the only option. Your idea of building the number digit by digit can work, if implemented properly, and it can save you the memory cost of the buffer. The key is to only read bytes when they are available.

Below is a *non-blocking* implementation of a number reader that works along the lines of your own code. This function only reads positive numbers. It returns the number it just parsed upon reading a non-digit character. In every other case it returns `-1` to tell you there is no input number available:

```
// Read an positive integer from a stream.
// Returns -1 if a complete integer is not available.
int readInt(Stream &link)
{
    static bool got_a_digit = false;  // did we get a digit so far?
    static int i = 0;                 // the integer we are building
    if (link.available()) {
        char c = link.read();
        if (isdigit(c)) {
            i = 10 * i + (c - '0');
            got_a_digit = true;
        } else if (got_a_digit) {  // non-digit: return the number
            int i_copy = i;
            got_a_digit = false;   // reset for next reading
            i = 0;                 // ditto
            return i_copy;
        }
    }
    return -1;
}

```

And here is how you would use it:

```
void loop() {
    int i = readInt(mySerial);
    if (i != -1)
        Serial.println(i);
}

```
> 1 votes

# Answer
Please, explain this to me

```
   while(j!=49){
        i = i*10 + j;

        Serial.println(j);//commeting this line is causing the problem
      }
   Serial.print(i);

```

The variable `j` never change inside the `while`.

You print the same `j` time and time again inside the `while`.

The variable `i` keep incrementing inside the `while`. It never stop.

I don't think you posted your real code.
> 0 votes

---
Tags: arduino-uno, softwareserial, robotics
---


# Question
Title: Trying to compile code on UNO using ccs811 and LCD
Complete newbie here. I'm really hoping to get something like this to work, and then learn from it. I have a generic UNO board and an LCD/CCS811 on order. I'm trying to do exactly this: (https://create.arduino.cc/projecthub/partsoven/air-quality-monitor-live-display-ad028a) but I'm receiving the following error upon compiling the code. I believe I have all the libraries installed, etc.. but for some reason, I can't get this sketch to upload.. sorry for the crap formatting on this, the {} never works for me and I can't space or indent past a certain point for some reason.... sorry for the long post.

```
Arduino: 1.8.1 (Windows 7), Board: "Arduino/Genuino Uno"

C:\Users\Guy\Documents\Arduino\sketch_jan25a\sketch_jan25a.ino:9:32:
warning: invalid conversion from 'int' to 't_backlighPol' [-fpermissive]

LiquidCrystal_I2C lcd(0x3F,16,2);  // set the LCD address to 0x3F for a 16 chars and 2 line display

                                ^

 In file included from
 C:\Users\Guy\Documents\Arduino\sketch_jan25a\sketch_jan25a.ino:5:0:
 C:\Users\Guy\Documents\Arduino\libraries\jm_LiquidCrystal_I2C/LiquidCrystal_I2C.h:55:2: note: initializing argument 3 of 'LiquidCrystal_I2C::LiquidCrystal_I2C(uint8_t, uint8_t, t_backlighPol)'

  LiquidCrystal_I2C (uint8_t lcd_Addr, uint8_t backlighPin, t_backlighPol pol);

  ^

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::available()'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::rxBufferLength'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::rxBufferIndex'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::read()'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::rxBuffer'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::peek()'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::flush()'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::onReceiveService(unsigned char*, int)'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::user_onReceive'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::onRequestService()'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::user_onRequest'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::txBufferIndex'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::txBufferLength'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::write(unsigned char const*, unsigned int)'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::transmitting'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::write(unsigned char)'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::txBuffer'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::TwoWire()'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::TwoWire()'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `Wire'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::begin()'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::begin(unsigned char)'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::begin(int)'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::end()'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::setClock(unsigned long)'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::beginTransmission(unsigned char)'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::txAddress'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::beginTransmission(int)'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::endTransmission(unsigned char)'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::requestFrom(unsigned char, unsigned char, unsigned long, unsigned char, unsigned char)'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::requestFrom(unsigned char, unsigned char, unsigned char)'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::requestFrom(unsigned char, unsigned char)'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::requestFrom(int, int)'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::requestFrom(int, int, int)'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::endTransmission()'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::onReceive(void (*)(int))'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

(.text+0x0): multiple definition of `TwoWire::onRequest(void (*)())'

libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\utility\jm_twi.c.o (symbol from plugin): In function `twi_readFrom':

(.text+0x0): multiple definition of `twi_readFrom'

libraries\Wire\utility\twi.c.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\utility\jm_twi.c.o (symbol from plugin): In function `twi_readFrom':

(.text+0x0): multiple definition of `twi_writeTo'

libraries\Wire\utility\twi.c.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\utility\jm_twi.c.o (symbol from plugin): In function `twi_readFrom':

(.text+0x0): multiple definition of `twi_transmit'

libraries\Wire\utility\twi.c.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\utility\jm_twi.c.o (symbol from plugin): In function `twi_readFrom':

(.text+0x0): multiple definition of `twi_init'

libraries\Wire\utility\twi.c.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\utility\jm_twi.c.o (symbol from plugin): In function `twi_readFrom':

(.text+0x0): multiple definition of `twi_disable'

libraries\Wire\utility\twi.c.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\utility\jm_twi.c.o (symbol from plugin): In function `twi_readFrom':

(.text+0x0): multiple definition of `twi_setAddress'

libraries\Wire\utility\twi.c.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\utility\jm_twi.c.o (symbol from plugin): In function `twi_readFrom':

(.text+0x0): multiple definition of `twi_setFrequency'

libraries\Wire\utility\twi.c.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\utility\jm_twi.c.o (symbol from plugin): In function `twi_readFrom':

(.text+0x0): multiple definition of `twi_attachSlaveRxEvent'

libraries\Wire\utility\twi.c.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\utility\jm_twi.c.o (symbol from plugin): In function `twi_readFrom':

(.text+0x0): multiple definition of `twi_attachSlaveTxEvent'

libraries\Wire\utility\twi.c.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\utility\jm_twi.c.o (symbol from plugin): In function `twi_readFrom':

(.text+0x0): multiple definition of `twi_reply'

libraries\Wire\utility\twi.c.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\utility\jm_twi.c.o (symbol from plugin): In function `twi_readFrom':

(.text+0x0): multiple definition of `twi_stop'

libraries\Wire\utility\twi.c.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\utility\jm_twi.c.o (symbol from plugin): In function `twi_readFrom':

(.text+0x0): multiple definition of `twi_releaseBus'

libraries\Wire\utility\twi.c.o (symbol from plugin):(.text+0x0): first defined here

libraries\jm_Wire\utility\jm_twi.c.o (symbol from plugin): In function `twi_readFrom':

(.text+0x0): multiple definition of `__vector_24'

libraries\Wire\utility\twi.c.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Arduino/Genuino Uno.

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

```

Below is the sketch I'm attempting to upload:

```
/*
 * Displays Sparkfun CCS811 data on a Serial enabled LCD sent over I2C.
 */
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

#define I2C_ADDR 0x3F
LiquidCrystal_I2C lcd(0x3F,16,2);  // set the LCD address to 0x3F for a 16 chars and 2 line display

#include "SparkFunCCS811.h"

#define CCS811_ADDR 0x5B // CCS811 Default I2C Address
//#define CCS811_ADDR 0x5A //Alternate I2C Address

CCS811 mySensor(CCS811_ADDR);

void setup()
{
  lcd.init();                      // initialize the lcd
  lcd.backlight();                //turn on backlight
  Serial.begin(9600);

}

void loop()
{
  //Check to see if data is ready with .dataAvailable()
  if (mySensor.dataAvailable())
  {
    //If so, have the sensor read and calculate the results.
    //Get them later
    mySensor.readAlgorithmResults();

  }

  delay(100); //Don't spam the I2C bus

    // clear the screen
    lcd.clear();
    // go to first row and send CO2 data to the display
    lcd.setCursor(0,0);
    lcd.print("CO2 [");
    lcd.print(mySensor.getCO2());
    lcd.print("] ppb");
      // go to second row and send tVOC data to the display
    lcd.setCursor(0,1);
    lcd.print("tVOC [");
    lcd.print(mySensor.getTVOC());
    lcd.print("] ppm");

}

```

# Answer
I am assuming you are using this library, which is the only one I can find using that `t_backlighPol` datatype

You need to set the I2C address when you instantiate the object:

```
LiquidCrystal_I2C lcd(0x38);  // Set the LCD I2C address

```

And define the LCD size when you call the `begin()` function. Note that `init()` is a private function of the object:

```
lcd.begin(16,2);               // initialize the lcd

```
> 0 votes

---
Tags: arduino-uno, arduino-ide
---


title: Atmega328P Prescaler to Microseconds

text:
# Question
Title: Atmega328P Prescaler to Microseconds
For a bitbanging project I'm working on, I need to measure microseconds as accurately as possible. The function micros() won't work for me here because of the unpredictable times at which it might roll over. I have been using this project by Louis Frigon as an example:

https://web.archive.org/web/20140627135927/http://www.sigmaobjects.com/toyota/

In this document he sets his Atmega8's prescaler value:

```
// Timer 0 prescaler = 8 ( 1 count / us )
TCCR0 = _BV(CS01);

```

Do I understand that after these instructions, TCNT0 counts up by nearly precise microseconds? If so, what math could I use to set my prescaler for measuring microseconds? The 328P has a higher clock speed, does that mean I won't be able to do this?

# Answer
> The 328P has a higher clock speed

The 328P will run at whatever speed you clock it, up to a maximum that depends on the supply voltage. Most 328P-based Arduinos are clocked at 16 MHz though.

> what math could I use to set my prescaler for measuring microseconds?

You can't. You would have to set the prescaler to 16 if you want the timer to count microseconds. You can set it to 8 or to 64, but there is no intermediate setting in between.

Maybe you could leave the prescaler at 8 and count half-microseconds instead?

---

**Edit**: On the 328P, Timer 0 has *two* control registers, named `TCCR0A` and `TCCR0B`. To set it to normal counting mode at `F_CPU`/8, you have to:

```
TCCR0A = 0;
TCCR0B = _BV(CS01);

```

If you are programming in plain C, the first line is not needed (but it won't hurt either), as the initial value of `TCCR0A` is zero on reset. If you are using the Arduino core library (and you write `setup()` and `loop()` instead of `main()`), then you do need this first line, as the Arduino core configures Timer 0 for PWM at 977 Hz. But note that the Arduino core also uses Timer 0 for timekeeping (`millis()`, `micros()` and `delay()`). Thus you may want to use another timer.

You could switch to Timer 2 by replacing every “0” with a “2” on the register and bit names of the two lines above. Then you would also replace every occurrence of `TCNT0` in the code with `TCNT2`.
> 0 votes

---
Tags: timing
---


# Question
Title: Can I use relays with 10A125V~ for my 220V~ applications, safely?
I am using the TinkerKit Relay Module and recently they changed the relay mounted on the board from a white one with `10A250V~` to a black one with `10A125V~`.

In my country the voltage is `220V~`. Can I use the black relay in my application, safely? May be there problems that I have to be careful?

# Answer
> 1 votes
The part is obsolete now according to Mouser. The simple answer is no, you cannot use a 120 volt part at 220 volts. The higher voltage can breakdown the lower voltage rated parts. It really has nothing to do with the "power" rating as there will be very little power actually dissipated in the relay. The current handling of the contacts is one issue and that seemingly didn't change but the voltage rating change is basically saying that this part cannot work at 220volts.

---
Tags: voltage-level, relay, current, safety, electricity
---


# Question
Title: How can I record a push button sequence and store it in an array
I have 3 push buttons and I want to record the sequence in which they are pressed in array of size 10,i.e, I want to record 10 values for example {1,1,2,2,3,3,1,1,1,3}. I want to blink an array of 3 LED in the same pattern in which the buttons were pressed. I have two extra push buttons for putting the arduino in record and play modes respectively. If any one can suggest how I can store the values in the array I will really be very thankful. I am also facing the problem because it's very difficult to manage the bouncing of the buttons simultaneously.

# Answer
You can create an array like this, make it global to easy access it:

```
int states[10];

```

And the current index:

```
int index_state = 0;

```

And initialize the array (in setup):

```
for (int n = 0; n < 10; n++)
{
    states[n] = 0; // Unpressed
}

```

When a new button press should be stored:

```
states[index_state] = state;

```

And add one to the index state, if 10 is reached, start over (this means the last 10 are stored).

```
index_state = (index_state + 1) % 10;

```

And to check the states you just iterate from index\_state.

Hope this helps you get going.

Note this is called a ring buffer.
> 3 votes

# Answer
this is my code that stores the button sequence but it will be great if someone can help me blink the LED sequence an put the micro-controller in play or record mode when desired. Also this code faces some issue as some times it fails to take inputs or takes two inputs at a time:

```
int arr[10];
boolean previous = LOW;
unsigned long time1 = 0;
int debounce = 200;
unsigned long time2 = 0;
int index_state = 0;
void setup()
{
 for(int i = 3;i<6 ;i++)
  pinMode(i,INPUT);
 for(int n=0;n<10;n++) arr[n] = 0;//initialisition
 Serial.begin(9600);
}

void loop(){
 boolean mode = digitalRead(3) || digitalRead(4) || digitalRead(5);
 while(mode == LOW) mode = digitalRead(3) || digitalRead(4) || digitalRead(5);//wait here till one of the pushbutton goes high;
 //Serial.println("value");
 if( mode == HIGH && previous == LOW && millis() - time1 > debounce){
 //find out which one is high and store that value in array;
 if(digitalRead(3)) arr[index_state] = 3;
 else if(digitalRead(4)) arr[index_state] = 4;
 else if(digitalRead(5)) arr[index_state] = 5;
 else ;
 //print the value and the index;
 Serial.print(arr[index_state]);
 Serial.print(" Stored in index: ");
 Serial.println(index_state);
 index_state = (index_state + 1) % 10;
 //update value of time1 for button debouncing
 time1 =  millis();
}

  //update the value of previous button state
  previous = digitalRead(3) || digitalRead(4) || digitalRead(5);

  }

```
> 1 votes

---
Tags: arduino-uno, array
---


# Question
Title: Problem with action that should happen in loop(continuously)
I’m using WeMos D1 R2 and latest Blynk library and app. I am also using Arduino IDE 1.6.13. I am trying to read a button from the app, which works fine, but i want to read it continuously. Through the Serial Monitor I can see that the board changes modes as it should. However, even if sensors read values when we get through the first “if” states, the values do not continue to show up in Serial Monitor. I believe that’s happening because it is not working as a loop. Also, the relays are not working(they start as open as they should, but their state never changes), as I believe program freezes at some point.

Here is the code:

```
//Start of program
#include <dht11.h>
#define BLYNK_PRINT Serial//
#include <ESP8266WiFi.h>
#include <Blynk.h>
#include <BlynkSimpleEsp8266.h>
#include <NewPing.h>
#include <SimpleTimer.h>

#define TRIGGER_PIN2 D4 // Arduino pin tied to trigger pin on the ultrasonic sensor 2.
#define ECHO_PIN2 D5     // Arduino pin tied to echo pin on the ultrasonic sensor 2.
#define MAX_DISTANCE2  23// Height of the Water Tank 2 (in centimeters).
#define DHT11_PIN D6

char auth[] = "****";
char ssid[] = "8888";
char pass[] = "psw";

int Relay1 = D1;
int Relay2 = D2;
int val2 = 0;
int tankwater1 = 0; //water in tank 1 in liters
int tankwater2 = 0; //water in tank 2 in liters
int fieldsize1 = 0; //size of field1 in m^2
int fieldsize2 = 0; //size of field2 in m^2
int sensor_pin = D7;
SimpleTimer timer;
//NewPing sonar1(TRIGGER_PIN1, ECHO_PIN1, MAX_DISTANCE1); // NewPing setup
of pins and maximum distance.
NewPing sonar2(TRIGGER_PIN2, ECHO_PIN2, MAX_DISTANCE2); // NewPing setup of
pins and maximum distance.

void setup()
{
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
  Blynk.begin(auth, ssid, pass);
  pinMode(Relay1, OUTPUT); //Setup Relay pin as output pin
  pinMode(Relay2, OUTPUT); //Setup Relay pin as output pin
  //pinMode(led_pin, OUTPUT);
  pinMode(sensor_pin, INPUT);
  digitalWrite(Relay1, LOW);
  digitalWrite(Relay2, LOW);
}

void loop()
{
  Blynk.run();
  timer.run();
}

BLYNK_READ(V8)
{
  Blynk.virtualWrite(8, 23 - val2); // virtualpin 8 distance
}

BLYNK_WRITE(V1) {
  int pinValue = param.asInt();

  if (pinValue == 0)
  {
    val2 = sonar2.convert_cm(sonar2.ping_median());
    Serial.println("Irrigation mode is active");
    Serial.println("Water level is at:");
    Serial.println(23 - val2);

    if (digitalRead(sensor_pin) == HIGH)
    {
      if (val2 <= 15) //Water level reaches the Top of the Tank2
      {
        digitalWrite(Relay2, HIGH); //Pump2 off
        delay(500);
      }
      else if (val2 > 15) // Water is empty on the Tank2
      {
        digitalWrite(Relay2, LOW); // Pump2 ON
        delay(500);
        //delay(86400000); one day delay. not suitable for experiment
      }
      else if (digitalRead(sensor_pin) == LOW)
      {
        digitalWrite(Relay1, LOW);
      }
    }
  }
  else {
    Serial.println("Fertilize mode is active. This does nothing now");
    //val3 = sonar2.convert_cm(sonar2.ping_median());
    //tankwater2 = (10-val3)*fieldsize2; //calculation of water in tank2
  }
}
//End of program

```

# Answer
The `BLYNK_WRITE(V1)` function is only called when a Blynk app widget sends data to your hardware. It does not run in a loop. If you want something to run in a loop, put it in `loop()`.

The `WRITE` aspect is from the point of view of the App, not of your hardware, so your hardware uses `BLYNK_WRITE()` to **receive** information from the app. And it's only called when the app chooses to send that information. For example, when a button in the Blynk smartphone app is pushed.
> 1 votes

---
Tags: arduino-uno, esp8266, loop, blynk
---


# Question
Title: Why was the Atmega16U2 used on the Arduino UNO as a USB to Serial converter?
This is the first time that I realized that extra SMD IC near the USB port of the Arduino UNO is actually a fully fledged microcontroller, I thought that it was just a USB to Serial converter. Further research into this chip left me with more questions than answers.

First of all, why did Arduino decide to use the Atmega16U2 as a USB to Serial converter? Couldn't they have gone with an FTDI chip instead? I came across this phrase on Quora "The best part is that you can also program and create your own applications on the 16u2 if you have an In-circuit Serial Programmer". How exactly does this work?

What about the two other set of connectors on the board? (other than the two main rows of headers) The ones labeled ICSP and JP2? Is the JP2 for the 16U2? I read that these could be used for burning the code onto the Atmega328P so that it can be modified, but not overwritten. What are any other uses for the 16U2 on the Arduino UNO?

# Answer
> 10 votes
First reason I'd guess is price:

They can probably get much better deals considering that the Atmega328 is also from Atmel (now Microchip).

About the programming:

There are some projects which make the Atmega16U2 into a MIDI device over USB or HID, for example some repos: , , . I've used the second one I think, and it works fine.

You can program it with an ISP/ICSP programmer such as Atmel ICE(below) or Arduino ISP.

Use the ISP pins by the Atmega16U2:

---
Tags: isp
---


# Question
Title: Power consumption in Arithmetic Operation in Arduino UNO
I would like to know how much current is consumed by multiplication operation in Arduino (ATMega328P) microcontroller. As per ATMega328p datasheet, multiplication operation takes 2 cycles. I have to now convert it to current.

Please let me know how to calculate it. Attached is ATMega328p datasheet for frequency versus current graph.

# Answer
The power consumed by the chip won't change much by multiplying (compared to, say, adding). The chip is always fetching and executing instructions, unless you have put it into one of its sleep modes.

The only power consumption change would be if the instruction had a side-effect on a peripheral. For example, turning on the ADC unit (for analog reading), or by setting an output pin high or low.

Having said that, I set up a couple of tests and measured the power consumption. I didn't use a Uno because the power used by the "power on" LED and the voltage regulator tend to swamp the power consumption of the chip itself. However it was tested on an Atmega328P.

---

## Addition

### Test sketch

```
volatile int foo = 100;
int main (void)
  {
  DDRB = 0b00111111;  // all ports to output
  DDRC = 0b00111111;
  DDRD = 0b11111111;
  PORTB = 0;          // write LOW
  PORTC = 0;
  PORTD = 0;

  while (true)
    foo += 42;
  }

```

### Generated code

```
  a6:   80 91 00 01     lds r24, 0x0100
  aa:   90 91 01 01     lds r25, 0x0101
  ae:   8a 96           adiw    r24, 0x2a   ; 42
  b0:   90 93 01 01     sts 0x0101, r25
  b4:   80 93 00 01     sts 0x0100, r24
  b8:   f6 cf           rjmp    .-20        ; 0xa6 <main+0x10>

```

### Measured consumption

I measured an average of 7.00 mA.

---

## Multiplication

### Test sketch

```
volatile int foo = 100;
int main (void)
  {
  DDRB = 0b00111111;  // all ports to output
  DDRC = 0b00111111;
  DDRD = 0b11111111;
  PORTB = 0;          // write LOW
  PORTC = 0;
  PORTD = 0;

  while (true)
    foo *= 42;
  }

```

### Generated code

```
  a6:   4a e2           ldi r20, 0x2A   ; 42
  a8:   20 91 00 01     lds r18, 0x0100
  ac:   30 91 01 01     lds r19, 0x0101
  b0:   42 9f           mul r20, r18
  b2:   c0 01           movw    r24, r0
  b4:   43 9f           mul r20, r19
  b6:   90 0d           add r25, r0
  b8:   11 24           eor r1, r1
  ba:   90 93 01 01     sts 0x0101, r25
  be:   80 93 00 01     sts 0x0100, r24
  c2:   f2 cf           rjmp    .-28        ; 0xa8 <main+0x12>

```

### Measured consumption

I measured an average of 6.32 mA.

---

## Conclusion

I found this rather surprising, that it used less power doing a multiplication compared to an addition. Setting all ports to output and low was intended to remove any side-effects from spurious inputs on the input ports.

Still, as you can see from the generated code, most of the instructions are "helper" instructions (like loading from registers, storing to registers, looping etc.).

I'm still not sure I believe the results, perhaps someone else would like to try to reproduce them?

## Update

As Edgar Bonet pointed out, the multiplication test became zero after 14 iterations and thus it gave the processor the simpler task of multiplying by zero. I changed the multiplier to 41 which does not become zero. This time the average consumption was 7.34 mA which was higher than the addition test.
> 1 votes

# Answer
Why not just measure the current drawn by the board and an empty loop vs. a loop that does some multiplication? (other than 1,2,4,8..)
> 0 votes

---
Tags: arduino-uno, atmega328
---


# Question
Title: Measuring Lithium ion cell voltage used to power Arduino via a boost module
Can I measure lithium ion cell voltage with Arduino ADC which is used to power the same Arduino through a boost module (XL6009)? The output voltage of boost module is 9 volts.

# Answer
I'm the author of a library called BatterySense and you can use it to achieve your goal. In the repository Readme you can also find wiring diagrams and usage examples, but to give you a rough idea...

1. Verify the negative side of your battery has continuity to the GND pin of your Arduino: you need to identify if the boost module is messing the common ground, but if you have continuity then you are fine
2. Add a connection from the battery positive terminal going into one of the Arduino analog pins
3. Use the BatterySense library to get the battery voltage and percentage level
> 2 votes

---
Tags: arduino-nano, battery, adc
---


# Question
Title: Arduino uno audio output quality improvement
I am new to electronics. I am going to play a sound truck from SD card when user push a button, Well This is very easy and there are lots of methods and codes to play it. the problem is with sound quality. I want to output sound into an speaker using 2.5 mm jack. here the problem appears. Is there any module which outputs Arduinos to speakers?

To me more clear in this tutorial https://www.instructables.com/id/Audio-Player-Using-Arduino-With-Micro-SD-Card/ we can play sound using simple speakers, is it possible to connect it to a higher quality speaker? like those pc speakers using 2.5 mm jack? In fact I want to get better sound quality than the above tutorial using adrino. thanks

# Answer
> 2 votes
If a beginner, it is always better to copy then invent. That said, I would recommend using this arduino.cc Simple Audio Player tutorial. There are many different types of Arduino boards. The Arduino Due uses a Microchip/Atmel SAM3X8E ARM Cortex-M3 CPU which contains at least one DAC. It is assumed this will produce better sound than the PWM output of the slower ATmega328P processor found on an Arduino Uno.

---
Tags: sound
---


title: Running python script using Arduino

text:
# Question
Title: Running python script using Arduino
I am trying to use Process.h library to run a shell command. Here is my code. I am using Arduino Uno.

```
#include <Process.h>
#include <Bridge.h>

void setup() {
  // Initialize Bridge
  //Bridge.begin(115200);

  // Initialize Serial
  Serial.begin(115200);

  // Wait until a Serial Monitor is connected.
  while (!Serial);

  // run various example processes
  runPythonFunction();
}

void loop() {
  // Do nothing here.
}

void runPythonFunction() {

  Process p;        // Create a process and call it "p"
  //p.begin("/usr/bin/python /home/kairos/Arduino/codes/sketch_jan26a/tweet.py");
  p.runShellCommandAsynchronously("/usr/bin/python -U /path/to/tweet.py");      // Run the process and wait for its termination
  //p.run();
  // Print command output on the SerialUSB.
  // A process output can be read with the stream methods
  while(p.available() > 0) {
     char c = p.read();
    Serial.print(c);
  }
  // Ensure the last bit of data is sent.
  Serial.flush();
  delay(300000);
}

```

If I do not comment the `Bridge.begin()` line, then in monitor display reverse question marks are displayed. And after commenting that, I am getting some garbage on the serial monitor. Also, my python script makes a new file in the same directory, which runs fine if I run it using a terminal. But if I run it using Arduino code, I am not able to see that new file being generated.

Even using `p.begin()` and `p.run()`it does not run. Nor using `p.runShellCommandAsynchronously()`.

So how can I run that python script?

# Answer
The Uno cannot run python.

The Bridge library is intended for communication either between the two MCUs of the Yun, or between an Arduino board and the MCU on a Yun shield.

It is literally a Bridge between the two systems - Arduino and the Linux system in the Yun.
> 3 votes

---
Tags: arduino-uno
---


title: ATMEGA AVcc pin - low pass filter

text:
# Question
Title: ATMEGA AVcc pin - low pass filter
I am a newby to the world of electronics and IC chips, and am looking to make an ATMEGA328 based board to monitor 12v batteries. The board will be powered from the batteries being monitored, with a regulated power supply taking 12v input and outputting 5v to the board. The data sheet for the ATMEGA328 chip says that AVcc should be connected externally to Vcc via a low-pass filter. A bit of internetting tells me the low-pass filter will filter out noise above a specific frequency, and provides links to calculators that show the affect of different resistor / capacitor pairs.

My problem is that, I have no idea what frequencies I need to filter! All / any advice much appreciated.

Further info: voltage measurements will be via voltage divider circuits, amp hour consumption will be via sensors, all of which will be connected to analog pins for ADC conversion.

# Answer
The filter is only needed if low noise is important to your application. For monitoring batteries, you probably don't need the accuracy level at which you would want the filter. For what it's worth, the Arduino Uno doesn't have such filter: it's AVCC is connected straight to VCC.

If you really want the filter, the exact characteristics are not critical. The datasheet suggests 10 µH + 100 nF, so this should be a safe choice.

---

**Edit**: To answer the question in the comment, yes, it is generally advised to use decoupling capacitors, usually something like 100 nF, even when powered from a voltage regulator.

Notice that both the VCC and the AVCC pins are very close to a ground pin. Best practice is to use one decoupling cap for each (A)VCC/GND pair, and to place that cap as close as possible to the pins.
> 2 votes

---
Tags: atmega328
---


# Question
Title: Arduino controlled relay for certain duration of time
I am using a relay on my Arduino Uno and i want it to be on LOW for a calculated interval of time, let's say ftime=7 seconds, and after that i need it to be set as HIGH (no power through relay). My code below makes no changes to the relay state. How would that be possible? I tried to use "delay()" too (which i know that is generally a bad idea), but had no success.

```
 unsigned int interval = ftime*1000; //ftime in ms
do
  {
  digitalWrite(Relay1, LOW);
  }
  while(timeElapsed < interval);
digitalWrite(Relay1, HIGH);

```

Also, if i try without:

```
digitalWrite(Relay1, HIGH);

```

relay is LOW (motor running) but it never returns to HIGH obviously.

# Answer
you need to update the timeElapsed variable inside the while loop:

```
 unsigned int interval = ftime*1000; //ftime in ms
 unsigned long startTime = millis();
do
  {
      digitalWrite(Relay1, LOW);
      timeElapsed = millis() - startTime;
  }
  while(timeElapsed < interval);
digitalWrite(Relay1, HIGH);

```

Another way is to create a state machine make `startTime` a global and update the logical state (and the pin) when the time is elapsed.

```
unsigned long startTime;
bool relayLOW = false;

void loop(){

    if(relayLOW && millis() - startTime > interval){
        digitalWrite(Relay1, HIGH);
        relayLOW = false;
    }
    if(!relayLOW){
        bool closeRelay= //decide if relay needs to be triggered
        if(closeRelay){
            startTime = millis();
            digitalWrite(Relay1, LOW);
            relayLOW = true;
        }
    }
}

```
> 2 votes

---
Tags: arduino-uno, relay
---


# Question
Title: Update button state in Blynk app through the code
I'm using Blynk along with a WeMos D1 R2 and i can change modes through an ON/OFF button.

I can succesfully change mode and make my application go from mode 1 (irrigation) to mode 2 (Fertilization), but through the code i manage to switch from mode 2 to mode 1(after my code does what it is meant to do).

However, i cannot make the button show up as being in mode 1 again, if the application is working properly in mode 1. Any ideas on how to update button condition?

My code follows(below the code you can see the app and the button Using the V1 virtual pin):

```
void setup()
{
  Serial.begin(9600);             // opens serial port, sets data rate to 9600 bps
  Blynk.begin(auth, ssid, pass);
  pinMode(Relay1, OUTPUT);        // Setup Relay pin as output pin
  pinMode(Relay2, OUTPUT);        // Setup Relay pin as output pin
//pinMode(led_pin, OUTPUT);
  pinMode(sensor_pin, INPUT);
  digitalWrite(Relay1, LOW);
  digitalWrite(Relay2, LOW);
  digitalWrite(Relay1,HIGH);
  digitalWrite(Relay2,HIGH);

}

BLYNK_READ(V8)
{
  Blynk.virtualWrite(8,level);    // virtualpin 8 distance
}

BLYNK_WRITE(V1)
{
  pinValue = param.asInt();
}

BLYNK_READ(V5)
{
  Blynk.virtualWrite(5,RH);       // virtualpin 8 distance
}

BLYNK_READ(V6)
{
  Blynk.virtualWrite(6,temp);     // virtualpin 8 distance
}

void loop()
{
  Blynk.run();
  timer.run();
  if (pinValue==0)
  {
    // some code here
  }
  else //(digitalRead(sensor_pin) == 1)
  {
    // some other code
  }}

else {
  // a lot of code here
  pinValue=0;                     // here i set pinValue to 0 again in order to return to mode1
}
}
BLYNK_READ(V1)
{
  Blynk.virtualWrite(1,pinValue); // virtualpin 1 state
}

//End of program

```

# Answer
`BLYNK_READ()` is documented as:

> BLYNK\_READ(vPIN)
>
> BLYNK\_READ defines a function that is called when device is requested to send it’s current value of Virtual Pin to the server.

That means it is called when the app or the Blynk server requests a state from the hardware/sketch, such as when the app first connects or reconnects to the Blynk server, or when the hardware reconnects to the Blynk server due to some network problem.

But if you just want to update the virtual pin `V1` at an arbitrary time in your sketch, just call:

```
Blynk.virtualWrite(V1, pinValue);

```

at the point in your code where you want to "change" the button's current state. Not in the `BLYNK_READ()` function, but in your main code, such as:

```
[...]
else {
  // a lot of code here
  pinValue=0; //here i set pinValue to 0 again in order to return to mode1
  Blynk.virtualWrite(V1, pinMode);
}
[...]

```
> 2 votes

---
Tags: arduino-uno, blynk
---


# Question
Title: Increasing number of iterations not increasing time
I am using Arduino Uno with Atmel Atmega328. I am using `micros()` function in Arduino IDE to measure time taken for execution. Here is my code:

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

void loop() {
    unsigned long a = micros();
    for (unsigned long j = 0; j < 100; ++j);
    Serial.println ((micros() - a));
    delay(1000);
}

```

The output comes as `4`. But if I increase the number of iterations in the for loop to say around `1000000000` it still shows that for loop takes same time of `4`. Is there a function which I can use to measure time properly in arduino?

# Answer
> 6 votes
The compiler has realized that your loop doesn't do anything useful and therefore optimized the whole thing away. Thus you are just timing how long it takes to do nothing. (You didn't get a result of zero, because calling `micros` will itself take time).

BTW, the granularity of `micros` is 4 µs, so you won't get a reading of 1 or 2. The code actually probably only took a couple of microseconds.

You need to do something that the compiler thinks "does something", like this:

```
void setup() {
    Serial.begin(115200);
}

volatile byte b;

void loop() {
    unsigned long a = micros();
    for (unsigned long j = 0; j < 100; ++j)
      b++;
    Serial.println ((micros() - a));
    delay(1000);
}

```

By making `b` volatile the compiler cannot decide that `b` isn't doing anything useful, so now the timings make sense.

I got 72 for 100 iterations and 144 for 200 iterations.

---

> Is there a function which I can use to measure time properly in arduino?

Your time measurement is fine. Your interpretation of the results indicates you didn't realize how smart the compiler is. :)

---

You can see what the compiler did if you examine the generated code:

```
    unsigned long a = micros();
  d8:   0e 94 d2 00     call    0x1a4   ; 0x1a4 <micros>
  dc:   6b 01           movw    r12, r22
  de:   7c 01           movw    r14, r24
    for (unsigned long j = 0; j < 100; ++j);
    Serial.println ((micros() - a));
  e0:   0e 94 d2 00     call    0x1a4   ; 0x1a4 <micros>
  e4:   ab 01           movw    r20, r22
  e6:   bc 01           movw    r22, r24

```

As you can see, between the two calls to `micros` there isn't any sort of loop.

To find the assembled code you can follow the steps documented here.

Basically, turn on "verbose compiling" which will show near the end of the verbose output the full pathname of the ".elf" file. Then use a command (terminal) window to enter this command:

```
avr-objdump -S xxx.elf

```

You may want to redirect the output to a file:

```
avr-objdump -S xxx.elf > myfile.txt

```

Depending on how the Arduino IDE was installed you may have to find the pull pathname of `avr-objdump` and use that instead of just the program name.

---
Tags: arduino-uno, arduino-ide, atmega328, time
---


# Question
Title: Constants within array of structs causes strange compiler errors?
In my sketch I have the following:

```
#define HU_ADDR                 0x190;
#define ALL_AUDIO_ADDR          0x1FF;
#define MY_ADDR                 0x360;
#define UNKNOWN_ADDR            0xFFF;

typedef byte MessageID;
enum {
  ACT_UNKNOWN,
  ACT_POWERON,
  ACT_POWEROFF,
  ACT_PASSIVEOFF_0,
  ACT_PASSIVEOFFRARE_0,
  ACT_PASSIVEON_0,
  ACT_KEYTURN,
  ACT_PRESSDISC
};

struct MessageDef {
  MessageID ID;
  word MasterAddr;
  word SlaveAddr;
  byte PayloadLength;
  byte Payload[20];
  char Description[20];
};

MessageDef MessageTable[] = {
  {ACT_POWERON,           HU_ADDR, UNKNOWN_ADDR, 13,  {0x00, 0x60, 0x31, 0xF1, 0x01, 0x01, 0x81, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00},                   "On call"},
  {ACT_POWEROFF,          HU_ADDR, UNKNOWN_ADDR, 13,  {0x00, 0x60, 0x31, 0xF1, 0x00, 0x00, 0x81, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00},                   "off?"},
  {ACT_PASSIVEOFF_0,      HU_ADDR, UNKNOWN_ADDR, 3,   {0x00, 0x11, 0x01},                                                                               "Passive: Weak"},
  {ACT_PASSIVEOFFRARE_0,  HU_ADDR, UNKNOWN_ADDR, 4,   {0x00, 0x11, 0x01, 0x20},                                                                         "Passive: Strong"},
  {ACT_PASSIVEON_0,       HU_ADDR, UNKNOWN_ADDR, 16,  {0x00, 0x74, 0x31, 0xF1, 0x80, 0x13, 0x10, 0x10, 0x10, 0x10, 0x10, 0x00, 0x00, 0x00, 0x03, 0x03}, "On response"},
  {ACT_KEYTURN,           HU_ADDR, UNKNOWN_ADDR, 11,  {0x31, 0x62, 0x31, 0xF1, 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x00},                               "Key turned"},
  {ACT_PRESSDISC,         HU_ADDR, UNKNOWN_ADDR, 4,   {0x00, 0x62, 0x31, 0x9F},                                                                         "DISC pressed"}
};

```

When I compile this, for some reason the Arduino IDE points at the first line and says "expected '}' before ';' token". If I replace the text like so:

```
#define HU_ADDR                 0x190;
#define ALL_AUDIO_ADDR          0x1FF;
#define MY_ADDR                 0x360;
#define UNKNOWN_ADDR            0xFFF;

typedef byte MessageID;
enum {
  ACT_UNKNOWN,
  ACT_POWERON,
  ACT_POWEROFF,
  ACT_PASSIVEOFF_0,
  ACT_PASSIVEOFFRARE_0,
  ACT_PASSIVEON_0,
  ACT_KEYTURN,
  ACT_PRESSDISC
};

struct MessageDef {
  MessageID ID;
  word MasterAddr;
  word SlaveAddr;
  byte PayloadLength;
  byte Payload[20];
  char Description[20];
};

MessageDef MessageTable[] = {
  {ACT_POWERON,           0x190, 0xFFF, 13,  {0x00, 0x60, 0x31, 0xF1, 0x01, 0x01, 0x81, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00},                   "On call"},
  {ACT_POWEROFF,          0x190, 0xFFF, 13,  {0x00, 0x60, 0x31, 0xF1, 0x00, 0x00, 0x81, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00},                   "off?"},
  {ACT_PASSIVEOFF_0,      0x190, 0xFFF, 3,   {0x00, 0x11, 0x01},                                                                               "Passive: Weak"},
  {ACT_PASSIVEOFFRARE_0,  0x190, 0xFFF, 4,   {0x00, 0x11, 0x01, 0x20},                                                                         "Passive: Strong"},
  {ACT_PASSIVEON_0,       0x190, 0xFFF, 16,  {0x00, 0x74, 0x31, 0xF1, 0x80, 0x13, 0x10, 0x10, 0x10, 0x10, 0x10, 0x00, 0x00, 0x00, 0x03, 0x03}, "On response"},
  {ACT_KEYTURN,           0x190, 0xFFF, 11,  {0x31, 0x62, 0x31, 0xF1, 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x00},                               "Key turned"},
  {ACT_PRESSDISC,         0x190, 0xFFF, 4,   {0x00, 0x62, 0x31, 0x9F},                                                                         "DISC pressed"}
};

```

Then it compiles with no complaints. ....what? Why? Aren't these functionally identical? Why does the compiler care if I use HU\_ADDR instead of 0x190?

# Answer
Don't put a semi-colon at the end of #define.

Whatever comes after `#define NAME` will be used to replace NAME across the source code.
> 6 votes

---
Tags: arduino-ide, array, compilation-errors, struct, constants
---


# Question
Title: Does the Arduino Yun have to be powered exactly at 5V?
I'm working on a senior project and I am using a ATX PSU to supply power to the Arduino Yun and other components. If I'm not mistaken, its powered through the usb. I took a usb cord, strip the sheath and put the proper connections on the breadboard and connected the red wire from the PSU to the breadboard as well. When I measure it, the voltage is 5.1V max. I'm scared to hook it up to the Arduino since I read that if its above 5, it will fry it. Is this voltage fine? If not, will I have to put resistors on it to get it down?

# Answer
It is fine. That is only 2% too high. The microcontroller is the ATmega32U4 and it can have 5.5V. The wifi module runs at 3.3V, and it has a voltage regulator. Some voltage is also lost in the cable. If the voltage is 6V, then you are in the danger zone, but not with 5.1V.

There are clones and shields of the Arduino Yún. Each has its own power supply demands. You should read what the specifications are for your board. The official Yún board requires 5V from the USB cable or 5V at the VIN pin.
> 5 votes

# Answer
I would avoid directly powering any micro without voltage regulation. Things like zener diodes and dedicated regulators adds complexity. But you can pretty much power it off any positive rail at or above 5v DC.(Use nothing greater than the specs) They can also be had and implemented for very little, that and they are used on the UNO board.
> 1 votes

---
Tags: voltage-level, arduino-yun
---


# Question
Title: IR sensor not incrementing or decrementing inside the loop
My project is automatic room light controller with visitor counter using Arduino.

My project was running correct upto this, but the problem started when we connected GSM module to our project because we have given a limit to the room, so when after limit exceeded using GSM a msg must be sent to the admin.

Actual problem is when a limit exceeds,code is not coming out of loop and when we are trying to increment or decrement no. of persons using IR sensor but its not happening.

Help me which loop i sholud use to send msg automatically

```
#include<LiquidCrystal.h>
#include <SoftwareSerial.h>
SoftwareSerial mySerial(3, 5);
char msg;
LiquidCrystal lcd(13, 12, 11, 10, 9, 8);
#define in 14
#define out 19
#define relay 2
int count = 0;
void IN()
{
  count++;
  lcd.clear();
  lcd.print("Person In Room:");
  lcd.setCursor(0, 1);
  lcd.print(count);
  delay(1000);
}
void OUT()
{
  count--;
  lcd.clear();
  lcd.print("Person In Room:");
  lcd.setCursor(0, 1);
  lcd.print(count);
  delay(1000);
}
void setup()
{
  lcd.begin(16, 2);
  lcd.print("Visitor Counter");
  delay(2000);
  pinMode(in, INPUT);
  pinMode(out, INPUT);
  pinMode(relay, OUTPUT);
  lcd.clear();
  lcd.print("Person In Room:");
  lcd.setCursor(0, 1);
  lcd.print(count);

  mySerial.begin(9600);   // Setting the baud rate of GSM Module
  Serial.begin(9600);    // Setting the baud rate of Serial Monitor (Arduino)
  Serial.println("GSM SIM900A BEGIN");
  Serial.println("Enter character for control option:");
  Serial.println("s : to send message");
  Serial.println();
  delay(100);
}

void loop()
{
  if (digitalRead(in))
    IN();
  if (digitalRead(out))
    OUT();

  if (count <= 0)
  {
    lcd.clear();
    digitalWrite(relay, LOW);
    lcd.clear();
    lcd.print("Nobody In Room");
    lcd.setCursor(0, 1);
    lcd.print("Light Is Off");
    delay(200);
  }
  else
    digitalWrite(relay, HIGH);

  if (count >= 3)
  {
    SendMessage();

    digitalWrite(relay, HIGH);
    delay(100);
    lcd.clear();
    lcd.print("Limit exceeded");
    lcd.setCursor(0, 1);
    lcd.print(count);
    return;
  }
  //else
  //  digitalWrite(relay, LOW);

  if (Serial.available() > 0)
    switch (Serial.read())
    {
      case 's':
        SendMessage();
        break;
      case 'r':
        ReceiveMessage();
        break;
    }
  if (mySerial.available() > 0)
    Serial.write(mySerial.read());
}

void SendMessage()
{
  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"+918419906897\"\r"); // Replace x with mobile number
  delay(1000);
  mySerial.println("GSM TEST:Limit of the room exceeded");// The SMS text you want to send
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  //Serial.end();
}

void ReceiveMessage()
{
  mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to recieve a live SMS
  delay(1000);
  if (mySerial.available() > 0)
  {
    msg = mySerial.read();
    Serial.print(msg);
  }
}

void Response()
{
  int count = 0;
  Serial.println();
  while (1)
  {
    if (Serial.available())
    {
      char data = Serial.read();
      if (data == 'K') {
        Serial.println("OK");
        break;
      }
      if (data == 'R') {
        Serial.println("GSM Not Working");
        break;
      }
    }
    count++;
    delay(10);
    if (count == 1000) {
      Serial.println("GSM not Found");
      break;
    }
  }
}

```

# Answer
Check that the GSM module is wired correctly, is setup correctly and that you get a ringing tone when you call that number from a different number. If that is all okay, write / copy a sketch from one of the many online tutorials that sends an SMS taking all input from the serial monitor of the Arduino IDE. When that is working, transfer that code into the sketch above. The *return* statement in your code will exit the loop() function within the sketch, but the C code running your sketch will just invoke your sketch again. Also, good practise says it's best not to include a function that is not actually used in the sketch - examples being the ReceiveMessage() and Response() functions.
> 0 votes

---
Tags: arduino-uno, gsm, ir
---


title: Relay active low and ESP8266 GPIO pins

text:
# Question
Title: Relay active low and ESP8266 GPIO pins
I am using a ESP8266, specifically the ESP-12-E :

I have a Relay, SRD-05VDC-SL-C connected to GPIO pin 4.

It is wired in Normally Open(with my device to be powered wired into the top and middle pins counting from the top to the bottom of the picture below):

In my arduino code when I issue:

```
  pinMode(4, OUTPUT);

```

This seems to pull the pin LOW, which is the active state of the relay, powering it, which turns my device on before my control code has even had chance to run. I want to get the pin for output but keep it floating.

How do I setup my pin for output, but leave it 'floating' from code, or keep it high / floating, so that I have to explicitly issue:

```
digitalWrite(4, LOW);

```

Before low is sent to activate my relay?

Hope this makes sense!

# Answer
The answer thanks to Trevor\_G was:

use digitalWrite(4, HIGH); before pinMode(4, OUTPUT);
> 2 votes

---
Tags: relay, pins, esp8266
---


# Question
Title: Decreasing Arduino pro micro power consumption
I'm working on a project that involves sending GPS coordinates wirelessly from an arduino board to another one. I was thinking of using an arduino micro for this task. The problem is that I want it to last as long as possible on a lithium battery. I searched and found too many tutorials on how to decrease arduino pro mini power consumption, but I didn't find anything related to the arduino pro micro. So I was thinking, does the same procedure used to decrease the arduino pro mini consumption apply for the arduino pri micro? Also, what microcontroller do you suggest for this project? (PIC, Arduino mini, micro, nano...)

# Answer
> 0 votes
> **Bringing Down power consumption by taking the LED out and lowering the clock ?**

Yes, you can do that! And you are okay with Arduino unless you want to complicate things more...If you want to check out other methods then you can check out the Microcontrollers Schematics and also the datasheets of their Components...

---
Tags: power, arduino-micro, arduino-mini
---


title: Can't display any number using 74HC595

text:
# Question
Title: Can't display any number using 74HC595
I just started using elegoo UNO R3 and I have the problem displaying different numbers on the segment display using the 74Hc595. I have no problem with the uploads and the circuits are working fine. However, the segment doesn't display any numbers besides 8. Is there a problem with the code or the wiring? any suggestion?

```
byte seven_seg_digits[10] = { B11111100,  // = 0
                          B01100000,  // = 1
                          B11011010,  // = 2
                          B11110010,  // = 3
                          B01100110,  // = 4
                          B10110110,  // = 5
                          B10111110,  // = 6
                          B11100000,  // = 7
                          B11111110,  // = 8
                          B11100110   // = 9
                         };
// connect to the ST_CP of 74HC595 (pin 3,latch pin)
int latchPin = 3;
// connect to the SH_CP of 74HC595 (pin 4, clock pin)
int clockPin = 4;
// connect to the DS of 74HC595 (pin 2)
int dataPin = 2;

 void setup() {
  // Set latchPin, clockPin, dataPin as output
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
}

// display a number on the digital segment display
void sevenSegWrite(byte digit) {
  // set the latchPin to low potential, before sending data
  digitalWrite(latchPin, LOW);

  // the original data (bit pattern)
  shiftOut(dataPin, clockPin, LSBFIRST, seven_seg_digits[digit]);

  // set the latchPin to high potential, after sending data
  digitalWrite(latchPin, HIGH);
}
   }

void loop() {
  // count from 9 to 0
  for (byte digit = 10; digit > 0; --digit) {
    delay(0);
    sevenSegWrite(digit - 1);
  }

  // suspend 4 seconds
  delay(0);
}

```

here is my circuit and the tutorial diagram:

# Answer
You're not giving your eyes time to see the numbers change. If you were a pigeon you might just see some numbers flicker past very rapidly, but we mere humans don't have a hope of seeing them - not without introducing some delay.

```
void loop() {
  // count from 9 to 0
  for (byte digit = 10; digit > 0; --digit) {
    delay(0);  // <--- Number of ms to wait between each digit
    sevenSegWrite(digit - 1);
  }

  // suspend 4 seconds
  delay(0);  // <--- Number of ms to wait between counts.
}

```
> 3 votes

---
Tags: arduino-uno, arduino-mega, programming
---


# Question
Title: Printing char array from array of structs in progmem to serial
(I apologize if this is a c++ question, I'm too green to know if this is unique to the Arduino IDE)

I've moved an array of structs into my PROGMEM because I was running into memory issues:

```
#define HU_ADDR                 0x190
#define ALL_AUDIO_ADDR          0x1FF
#define MY_ADDR                 0x360
#define UNKNOWN_ADDR            0xFFF

typedef byte MessageID;
enum {
  ACT_UNKNOWN,
  ACT_POWERON,
  ACT_POWEROFF,
  ACT_PASSIVEOFF_0,
  ACT_PASSIVEOFFRARE_0,
  ACT_PASSIVEONRARE,
  ACT_PASSIVEON_0,
  ACT_KEYTURN,
  ACT_PRESSDISC,
  ACT_PRESSAM,
  ACT_CD,
  ACT_STATIONFOUND,
  ACT_ENABLECD,
  ACT_CD2
};

struct MessageDef {
  MessageID ID;
  word MasterAddr;
  word SlaveAddr;
  byte PayloadLength;
  word Payload[24];
  char Description[20];
};

const MessageDef MessageTable[] PROGMEM = {
  {ACT_POWERON,           HU_ADDR, ALL_AUDIO_ADDR, 13,  {0x00, 0x00, 0x00, 0x00, 0x100, 0x100, 0x00, 0x81, 0x100, 0x01, 0xF1, 0x31, 0x60},                    "Tune Knob"},
  {ACT_POWEROFF,          HU_ADDR, UNKNOWN_ADDR, 13,    {0x00, 0x60, 0x31, 0xF1, 0x00, 0x00, 0x81, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00},                       "off?"},
  {ACT_PASSIVEOFF_0,      HU_ADDR, UNKNOWN_ADDR, 3,     {0x46, 0x01, 0x11},                                                                                "Passive: Weak"},
  {ACT_PASSIVEOFFRARE_0,  HU_ADDR, UNKNOWN_ADDR, 4,     {0x60, 0x45, 0x01, 0x11},                                                                             "Passive: Strong"},
  {ACT_PASSIVEONRARE,     HU_ADDR, UNKNOWN_ADDR, 4,     {0x100, 0x20, 0x01, 0x11},                                                                            "Passive: Fierce"},
  {ACT_PASSIVEON_0,       HU_ADDR, ALL_AUDIO_ADDR, 16,  {0x00, 0x03, 0x03, 0x00, 0x00, 0x00, 0x10, 0x10, 0x10, 0x10, 0x10, 0x100, 0x80, 0xF1, 0x31, 0x74},    "Vol Knob"},
  {ACT_KEYTURN,           HU_ADDR, UNKNOWN_ADDR, 11,    {0x31, 0x62, 0x31, 0xF1, 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x00},                                   "Key turned"},
  {ACT_PRESSDISC,         HU_ADDR, ALL_AUDIO_ADDR, 4,   {0x00, 0x9F, 0x31, 0x62},                                                                             "No DISC available"},
  {ACT_PRESSAM,           HU_ADDR, ALL_AUDIO_ADDR, 24,  {0x00, 0x60, 0x31, 0xF3, 0x01, 0x00, 0x01, 0x00, 0x08, 0x00, 0x30, 0x00, 0x58, 0x00, 0x6C, 0x00, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, "AM/FM Switch"},
  {ACT_CD,                HU_ADDR, ALL_AUDIO_ADDR, 11,  {0x31, 0x62, 0x31, 0xF1, 0x01, 0x30, 0x01, 0xFF, 0xFF, 0xFF, 0x00},                                   "CD switch?"},
  {ACT_STATIONFOUND,      HU_ADDR, ALL_AUDIO_ADDR, 13,  {0x00, 0x00, 0x00, 0x04, 0x00, 0x100, 0x00, 0x81, 0x100, 0x01, 0xF1, 0x31, 0x60},                     "FM station found"},
  {ACT_ENABLECD,          HU_ADDR, ALL_AUDIO_ADDR, 13,  {0x00, 0x00, 0x00, 0x04, 0x00, 0x77, 0x00, 0x81, 0x00, 0x00, 0xF1, 0x31, 0x60},                       "Enter CD mode"},
  {ACT_CD2,               HU_ADDR, ALL_AUDIO_ADDR, 4,   {0x62, 0x45, 0x01, 0x11},                                                                             "CD message 2?"}
};

const byte MessageTableSize = sizeof(MessageTable)/sizeof(MessageDef);

```

I've adjusted accordingly in my code segments that reference this data using pgm\_read\_byte\_near() for example. However, I'm not really sure how to get the Description field anymore. When MessageTable was in dynamic memory I could just use:

```
Serial.println(pgm_read_word(MessageTable[msgid].Description))

```

But now that seems to be printing... maybe the addresses of the data? Instead of printing out the character array I need to see. How do I parse this more correctly?

# Answer
> 0 votes
You can use the `strncpy_P(char* dest, const char* src, size_t maxLen);` function which will copy a zero-terminated string of at max `maxLen` bytes from PROGMEM into RAM. Then print the string from RAM.

Example code:

```
//We have global buffer in RAM. +1 for 0 termination
char descBuf[20 + 1];

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

    //Copy the description string of the first message in the buffer
    strncpy_P(descBuf, MessageTable[0].Description, 20);
    //Print it
    Serial.print("Description: ");
    Serial.println(descBuf);
}

```

Together with your code above, that prints on my Arduino Nano as:

```
Description: Tune Knob

```

If you don't want to have a 21 byte big buffer in RAM (or there are larger strings you wish to print), you can also use the `pgm_read_byte` function to read and print the string characters byte-wise. Example:

```
Serial.print("Description: ");
char c = 0;
for(size_t i=0; i < strlen_P(MessageTable[0].Description); i++) {
    c = pgm_read_byte(MessageTable[0].Description + i);
    Serial.print(c);
}
Serial.println();

```

For further reference, see the Arduino documentation on PROGMEM: https://www.arduino.cc/reference/en/language/variables/utilities/progmem/

---
Tags: arduino-ide, string, array, progmem, struct
---


# Question
Title: Hooking up LCD screens reclaimed from old camcorders to Arduino
Has anyone had any luck using LCD screens reclaimed from old electronics with Arduino, such as camcorders etc?

My 8 yr old has an old sony handycam (dcr-trv103) in bits and now wants to use the LCD screen with the arduino. I'm not even sure how I would go about this. Any tips? How do I figure out 'what does what' in terms of the inputs? How would I drive this thing / what do I need to do to send visual images to it via an Arduino?

Here's the front and back panels of the LCD screen, and their hookups.

The Screen

Screen hookup

I'm assuming this is the backlight

backlight hookup

Note: someone identified this as a duplicate of another question about reusing a cellphone LCD screen. This question is specifically about reusing an older camcorder LCD screen. Also that other question has very little answers. I found the answers below useful and educational. Thanks all.

# Answer
This is likely a type of TTL LCD interface. But it is nearly impossible to describe more as there are so many variations both in hardware and in timing. Likely a steady stream of Red Green & Blue binary data way faster than an Arduino Uno could possibly manage is required to create an image. For the necessary processing power, you would have to utilize one of the top end Arduino boards. Even then, software to create the steady stream of binary data for this particular LCD is still required. Also, there are hardly no standards beyond saying the LCD is a TTL or LVDS. Which means hours spent on developing software for this LCD will likely only work for this LCD.

It would be far easier to just buy an LCD and interface board known to work together. If you are using an Arduino Uno, there is not much processing power beyond saying "I want a circle here" or "I want a line there". Fortunately, there are such COTS parts available. Here is a tutorial describing such a device connected to an Arduino Uno.
> 7 votes

---
Tags: arduino-uno, lcd
---