text:
Arduino Uno versus Arduino Nano power consumption
I have both an Arduino Uno and an Arduino Nano but I can't decide which one to use for my project. My aim is to maximize battery lifetime. I have also implemented an 8-second watchdog timer to periodically sleep and wake up the ATMega328P.

Option 1: Arduino Uno R3 + DHT11 sensor: The board is powered on by 4 * 1.25V (2700 mAh) Nickel Metal Hydride batteries and the 3.3V output voltage of the Arduino is supplied to VCC of DHT11. (Arduino Uno specification DC Current per I/O Pin 40 mA, DC Current for 3.3V Pin 50 mA).
Option 2: Arduino Nano + DHT11 sensor. The board is powered on by 4 * 1.25V (2700 mAh) Nickel Metal Hydride batteries and the 3.3V output voltage of the Arduino is supplied to VCC of DHT11. (Arduino Nano specification: DC Current per I/O Pin: 40 mA but NO information for DC current for 3.3V or 5V).

I would like to know which one will be more power-efficient.

DHT11 can work from 5V. Why did you choose 3.3V?

DHT11 works for both. What difference it makes if 5V is used?

Voltage regulator at 3.3 volts dissipates part of the energy. What battery lifetime do you have? What do you want to achieve?

Both these boards draw a lot of extra current due to LEDs, regulators, etc. An alternative solution is to simply turn the board on/off: https://electronics.stackexchange.com/questions/266716/power-off-arduino-via-software

I am currently using Arduino Uno and running overnight successfully. With 2700 mAh batteries, I expect will last more than 3 days but I found in many forums sleeping only ATmega328p with watchdog timer of 8s  will not  save much power. How much do you think battery life time will be? So let's say I power using only battery and deploy in a place where NO power mains is available, it is going to last only 3 to 4 days?? This is a MAJOR issue I am facing.

Please add  code and wiring diagram.

Related: Are there good batteries to power on Arduino? by same person.

A Uno which isn't doing anything useful except being turned on will use about 50 mA of current from the power jack at 9V.
If you use 3 x alkaline AA batteries (giving a nominal voltage of 4.5V) directly into the 5V pin of the Arduino then you might get 2500 mAh which would be 50 hours at 50 mA per hour.
You can save a considerable amount of power by using sleep modes as I describe on my page about power. It also helps to use a bare processor (no voltage regulator, no LEDs).
I made a temperature and humidity sensor which runs from 3 x AA batteries. Using sleep mode, plus various other techniques, that is running for over a year without needing new batteries.

I would like to know which one will be power efficient?

Both the Uno and the Nano use the same Atmega328P processor. Thus the technical considerations would be the same. Both have a voltage regulator and a "power on" LED which alone would use a lot of current, compared to everything else.

It's not that hard to make a minimal board. I have a page about doing that. Example of all you need:

If you use a deep sleep mode, combined with using the watchdog timer to wake every 8 seconds (and check the time, say every 10 times it wakes) you can reduce power consumption right down.
My temperature sensor uses an average of 42 µA which is a lot less than 50 mA. (A thousand times less). Thus your 50 hours run time becomes 50,000 hours which is 2083 days. Your batteries will probably self-discharge sooner. :)

Thank you for your detailed answer. Just a quick question: how do we supply 3.3 v or 5 v to temperature sensor because we will remove the voltage regulator from the chip? Can we use ftdi adapter which gives 3.3v or 5v output?

In that case will FTDI adapter too NOT consume current?

Well, if you are powering the processor you can power the temperature sensor, can't you? Did you read my page about my temperature sensor?

Yes. I read it. It seems you are powering the processor and temperature sensor sensor with FTDI? Correct me if I am wrong. My question is: does FTDI not pull the current from battery like voltage regulator of other arduino boards do?I agree we can get rid of led power consumption.

No, I am powering them from a battery. The FTDI connection is just for reprogramming it.

You are powering from 3.3 V regulated  battery?

You said you read my article about the sensor. The schematic is there. It is powered by 3 x 1.5V Alkaline batteries. There is no voltage regulator. It is marked as 5V on the top left-hand corner of the schematic, but would actually be closer to 4.5V (which is what 3 x 1.5 is). It is quite acceptable to run the processor at 4.5V. If you run at 8 MHz, as I did, then 3V (1V each from 3 batteries) is still OK, as might be expected towards the end of the battery life.

If needed the power LED can just be unsoldered right?

From the Uno board? Yes, but the voltage regulator still takes some power to run.

Don't use either use something with no USB, regulator - e.g. Pro Mini (run from 3.3V)
Just running the Arduino (or indeed most digital circuitry) from a lower voltage will already reduce power consumption - admittedly at a slight cost in processor speed. The Atmega328P will run at 12MHz on 3.3V, although the Pro Mini uses the more conservative 8MHz.

I thought of using pro mini but I found that I have to work on making circuit as pro mini is not much user friendly (in terms of loading code etc) than Arduino nano and uno. Also pro mini does not give output voltage 3.3V or 5V which can be supplied to DHT11 vcc pin easily. So

I found more work to be done from HW side. I am not good at HW making as my background is programming only.

Can we supply Vcc of pro mini to DHT11 vcc?

yes, run it all from 3.3v, using a dc-dc buck (smps) to get 3.3v instead of an LDO

@JyotiRajSharma You miss my point - run the Pro Mini from 3.3V, and use the same source to run your peripherals, avoiding any lossy linear regulators. It really isn't that hard to use a USB-serial dongle to program (which is done when connected to computer) rather than a power hogging on-board converter you aren't using.


text:
Arduino with 2 echo sensors
For a project I'm doing I need the Arduino to be connected to two echo sensors (I have the HC-SR04). Currently I have 4 sensors that I can use, but I will need only 2 or 3.
I have almost no knowledge of coding and the Arduino, but I figured out how to connect it to one echo sensor, and that is working, which is great.
But now I need it to connect to two. I found example code with 3 echo sensors, but whenever I connect them my Arduino shuts down. I guess it is because it takes up too much power, my teacher said something like that. All lights turn off all of the sudden, and it doesn't reset. Only when I remove some the wires for the power, it works again.
So 3 isn't going to work. I figured I'd stick to two. Now the problem: Whenever I try to edit the code to two echo sensors (I basically just removed the trigPin3 and echoPin3 in the first part of the code, and the SonarSensor(trigPin3, echoPin3)), it doesn't work anymore. The monitor doesn't show any values anymore, while it did with the first code. It just shows zeroes now.
So my question is, how can I edit the example code so that it works with 2 echo sensors?
This is the code I found for the 3 echo sensors:
#define trigPin1 3
#define echoPin1 2
#define trigPin2 4
#define echoPin2 5
#define trigPin3 7
#define echoPin3 8

long duration, distance, RightSensor,BackSensor,FrontSensor,LeftSensor;

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

void loop() {
  SonarSensor(trigPin1, echoPin1);
  RightSensor = distance;
  SonarSensor(trigPin2, echoPin2);
  LeftSensor = distance;
  SonarSensor(trigPin3, echoPin3);
  FrontSensor = distance;
  Serial.print(LeftSensor);
  Serial.print(” – “);
  Serial.print(FrontSensor);
  Serial.print(” – “);
  Serial.println(RightSensor);
}

void SonarSensor(int trigPin,int echoPin) {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
}

And this is the one that IS working, but with 1 echo sensor:
#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
#define LEDPin 13 // Onboard LED

int maximumRange = 200;
int minimumRange = 0;
long duration, distance;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  if (distance >= maximumRange || distance <= minimumRange) {
    /* Send a negative number to computer and Turn LED ON
    to indicate "out of range" */
    Serial.println("-1");
    digitalWrite(LEDPin, HIGH);
  } else {
    /* Send the distance to the computer using Serial protocol, and
    turn LED OFF to indicate successful reading. */
    Serial.println(distance);
    digitalWrite(LEDPin, LOW);
  }
  //Delay 50ms before next reading.
  delay(50);
}

I hope someone can help me!
Many thanks, Leah.

Could you update your question to add the code that you've created to work with two sensors, which doesn't work, please? Could you please also elaborate on what you mean by "doesn't respond anymore"? What exactly  does happen?

With "Doesn't respond anymore" I mean, lights turn off completely.

Elaborated some things in my question. I hope it's a little bit more clear now.

We can easily find working code on our own.  What we need is your "not working code".  BTW, instead of listing the working code, most simply provide a link to the working code.  As most get their code from other people's web pages or sources such as github.

There is a magical " delay(50);" that you might have omitted *<:)

Your "SonarSensor" function is quite odd, it probably works, bit it's not really neat. You also seem to start with a capital on some variable's names. The function "SonarSensor" looks like a constructie of a SonarSensor class. You may want to name it like: "getDistance" or "getDistanceFromSonar" and return the distance instead of modifying a global variable.

There is no link to a code, since I got my code from some classmates of mine, and from one of my teachers, that again probably found it somewhere (I don't know the source.) As for the "SonarSensor" function. I will change the name, thank you very much :) About the "Delay(50);", I see that this is indeed in the previous code, that was working. But I don't quite understand what it does exactly.

In the 1 sensor program all the delays added together account for
62ms between samples.
In the 3 sensor program the sample code contains delays which likely
exceed 12ms (delays plus code execution).  So each sensor will not be
sampled faster than once every 36ms.
After you removed 1 sensor from the 3 sensor program, you increased
the sampling rate to about every 23ms.
It is likely a minimum amount of time is necessary between samples in
order for the HC-SR04 to recover.

Try this one. I hope this will work for you.
int trigPin1 = 2;                        //Sensor Trip pin connected to Arduino pin 2
int echoPin1 = 3;                        //Sensor Echo pin connected to Arduino pin 3

int trigPin2 = 4;                        //Sensor Trip pin connected to Arduino pin 4
int echoPin2 = 5;                        //Sensor Echo pin connected to Arduino pin 5

float pingTime1;                         //time for ping to travel from sensor to target and return
float targetDistance1;                   //Distance to Target in centi meters

float pingTime2;                         //time for ping to travel from sensor to target and return
float targetDistance2;                   //Distance to Target in centi meters

float speedOfSound = 760.5583392985;     //Speed of sound in miles per hour.

void setup()
{
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);

  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);
}

void loop()
{
  ultrasonicFun1();
  ultrasonicFun2();
}

void ultrasonicFun1()
{
  digitalWrite(trigPin1, LOW);         //Set trigger pin low
  delayMicroseconds(2000);             //Let signal settle
  digitalWrite(trigPin1, HIGH);        //Set trigPin high
  delayMicroseconds(15);               //Delay in high state
  digitalWrite(trigPin1, LOW);         //ping has now been sent
  delayMicroseconds(10);               //Delay in high state

  pingTime1 = pulseIn(echoPin1, HIGH);             //pingTime is presented in microceconds
  pingTime1 = pingTime1 / 1000000;                 //convert pingTime to seconds by dividing by 1000000 (microseconds in a second)
  pingTime1 = pingTime1 / 3600;                    //convert pingtime to hourse by dividing by 3600 (seconds in an hour)
  targetDistance1 = speedOfSound * pingTime1;      //This will be in miles, since speed of sound was miles per hour
  targetDistance1 = targetDistance1 / 2;           //Remember ping travels to target and back from target, so you must divide by 2 for actual target distance.
  targetDistance1 = targetDistance1 * 160934.4;    //Convert miles to inches by multipling by 160934.4 (centi meters per mile)
}

void ultrasonicFun2()
{
  digitalWrite(trigPin2, LOW);          //Set trigger pin low
  delayMicroseconds(2000);              //Let signal settle
  digitalWrite(trigPin2, HIGH);         //Set trigPin high
  delayMicroseconds(15);                //Delay in high state
  digitalWrite(trigPin2, LOW);          //ping has now been sent
  delayMicroseconds(10);                //Delay in high state

  pingTime2 = pulseIn(echoPin2, HIGH);             //pingTime is presented in microceconds
  pingTime2 = pingTime2 / 1000000;                 //convert pingTime to seconds by dividing by 1000000 (microseconds in a second)
  pingTime2 = pingTime2 / 3600;                    //convert pingtime to hourse by dividing by 3600 (seconds in an hour)
  targetDistance2 = speedOfSound * pingTime2;      //This will be in miles, since speed of sound was miles per hour
  targetDistance2 = targetDistance2 / 2;           //Remember ping travels to target and back from target, so you must divide by 2 for actual target distance.
  targetDistance2 = targetDistance2 * 160934.4;    //Convert miles to inches by multipling by 160934.4 (centi meters per mile)
}

Try this:
void loop() {

RightSensor = SonarSensor(trigPin1, echoPin1);

LeftSensor = SonarSensor(trigPin2, echoPin2);

FrontSensor = SonarSensor(trigPin3, echoPin3);

Serial.print(LeftSensor);

Serial.print(” – “);

Serial.print(FrontSensor);

Serial.print(” – “);

Serial.println(RightSensor);

}

long SonarSensor(int trigPin,int echoPin)
{

digitalWrite(trigPin, LOW);

delayMicroseconds(2);

digitalWrite(trigPin, HIGH);

delayMicroseconds(10);

digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);

distance = (duration/2) / 29.1;

return distance;

}

Some explanation would be great

As far as I understand, your code does not solve the OP problem... Can you just point out what issue this solves and why?

source: Stack Exchange

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

sort: votes


text:
ets Jan 8 2013,rst cause:4, boot mode:(1,7)
I am facing a issue with the ESP8266-01 as the following below:
chksum 0x42
csum 0x42
~ld
ets Jan 8 2013,rst cause:4, boot mode:(1,0)
wdt reset
Anyone has the solution please help!!
#include <LiquidCrystal.h>  //Load liquid Crystal Library
LiquidCrystal LCD(12, 11, 5, 4, 3, 2);  //Create Liquid Crystal Object called LCD
#include <ESP8266WiFi.h>

const char* ssid     = "your-ssid";
const char* password = "your-password";
const char* host = "your-localhost";

#define in 7
#define out 8
#define trigPin 10
#define echoPin 13
#define relay 2
#define led 6            //red color
#define led2 A0           //yellow color
#define led3 9           //green color

int count = 0;

int distanceCm;
long duration;

void IN()
{
    count++;
    LCD.clear();
    LCD.print("Number of Item:");
    LCD.setCursor(0,1);
    LCD.print(count);
    delay(10);
    LCD.setCursor(3,1);
    LCD.print(distanceCm);
    delay(10);
    LCD.setCursor(6,1);
    LCD.print(" cm");
    if(distanceCm <= 3){
     delayMicroseconds(10);
     LCD.setCursor(10,1);
     LCD.print("Full");
     digitalWrite(led, HIGH);
  }else{
    digitalWrite(led, LOW);
  }

  if(distanceCm > 3 && distanceCm <= 5){
     delayMicroseconds(10);
     LCD.setCursor(10,1);
     LCD.print("Enable");
     digitalWrite(led2, HIGH);
  } else{
    digitalWrite(led2, LOW);
  }

  if(distanceCm > 5){
     delayMicroseconds(10);
     LCD.setCursor(10,1);
     LCD.print("Empty");
     digitalWrite(led3, HIGH);
  } else {
    digitalWrite(led3, LOW);
  }
  delay(500);
}

void OUT()
{
  count--;
  LCD.clear();
  LCD.print("Number of Item:");
  LCD.setCursor(0,1);
  LCD.print(count);
  delay(10);
  LCD.setCursor(3,1);
  LCD.print(distanceCm);
  LCD.setCursor(6,1);
  LCD.print(" cm");
   if(distanceCm <= 3){
     delayMicroseconds(10);
     LCD.setCursor(10,1);
     LCD.print("Full");
     digitalWrite(led, HIGH);
  }else{
    digitalWrite(led, LOW);
  }

  if(distanceCm > 3 && distanceCm <= 5){
     delayMicroseconds(10);
     LCD.setCursor(10,1);
     LCD.print("Enable");
     digitalWrite(led2, HIGH);
  } else{
    digitalWrite(led2, LOW);
  }

  if(distanceCm > 5){
     delayMicroseconds(10);
     LCD.setCursor(10,1);
     LCD.print("Empty");
     digitalWrite(led3, HIGH);
  } else {
    digitalWrite(led3, LOW);
  }
  delay(500);
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  delay(10);

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  pinMode(led, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);

  LCD.begin(16,2);
  LCD.print("Item Counter");
  delay(2000);

  pinMode(in, INPUT);
  pinMode(out, INPUT);
  pinMode(relay, OUTPUT);

  LCD.clear();
  LCD.print("Item In Box:");
  LCD.setCursor(0,1);
  LCD.print(count);

  // We start by connecting to a WiFi network

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
     // ESP.wdtFeed();
  }

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

 // ESP.restart();
}

int value = 0;

void loop() {

 delay(0);
 delay(5000);
  ++value;

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

  duration = pulseIn(echoPin, HIGH);
  distanceCm = duration * 0.034/2;

//******************************************************//
//IR Sensor Counting Object
  if(digitalRead(in))
  IN();
  if(digitalRead(out))
  OUT();

  if(count<=0)
  {
    LCD.clear();
    digitalWrite(relay, LOW);
    LCD.clear();
    LCD.print("No Item in box");
    LCD.setCursor(0,1);
    LCD.print("box is empty");
    delay(200);
  }
   else{
    digitalWrite(relay, HIGH);
   }

  Serial.print("connecting to ");
  Serial.println(host);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 8095;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }
  if(WiFi.status() != WL_CONNECTED){
    WiFi.begin(ssid,password);
    while (WiFi.status()!= WL_CONNECTED)
    {
      Serial.println("Waiting for connection");
      delay(0);
    }
  }

  String IRCount, myDistance;
  IRCount = String(count);
  myDistance = String(distanceCm);
  // We now create a URI for the request
  String url = "/Registration/write_data.php";
  url += "?item=";
  url += IRCount;
  url += "&distance=";
  url += myDistance;

  Serial.print("Requesting URL: ");
  Serial.println(url);

  // This will send the request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");
  int timeout = millis() + 5000;
  while (client.available() == 0) {
    if (timeout - millis() < 0) {
      Serial.println(">>> Client Timeout !");
      client.stop();
      return;
    }
  }

  // Read all the lines of the reply from server and print them to Serial
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }

  Serial.println();
  Serial.println("closing connection");
  delay(0);
}

it is a watchdog reset. what is flashed in the esp8266?

@Juraj Flash Size: 1M(512K SPIFFS) flash Node: DIO

i tried all the flash size already but the error still there

that is not what I asked

Sorry... i don't understand what you mean flashed in the esp8266

GPIO 0  pins that i using it in the esp8266-01

what firmware or sketch is flashed? it is a software error the reset, so tell us what did you upload

I not sure what is the error going on... but i use the WiFiClient example to upload the dummy data to the php localhost webpage and it works but when i use the below following text file to upload the data to the webpage and it shows the above error ESP8266_upload.txt

esp-01 has 4 io pins: RX, TX, io 0 and io 2. other pins are not accessible. io 6 to io 11 are wired to on-board flash memory and can't be used.
what are you thinking by using other pins then 0 and 2? how did you wire those sensors and leds to esp-01?

Because for the sensors and leds... I want pass the sensors data to my server. So is it possible to save my sensor data into the MySQL database and display it on my webpage.   I wired those wires on the Arduino UNO board

Do you have any ideas to pass the sensor data to the PHP localhost server webpage? or is it required to change another wifi receiver to pass the data to my localhost webpage?

My issue is the same as this forum before https://arduino.stackexchange.com/questions/48234/getting-error-ets-jan-8-2013-rst-cause4-boot-mode1-6-wdt-reset But i don't see any solution for this

there is no magic that would read Uno pins in connected esp8266. you could use Firmata with Firmata Master esp8266 library but simpler is to write two sketches

but the other sketches connect to the main sketches?

the problem you linked is different. there is no Uno. sensors are wired to esp8266 dev board

i no write the esp8266 connection in the source code... i just write the sensors that connect to the UNO board... i not sure that is correct or not

you need sketch in Uno and sketch or firmware in esp8266

you mean that i need to create two sketch which is uno boards code and the esp01 source code? Sorry... i totally no idea how to do it

step by step. first create and debug a sketch for Uno without networking with output to Serial Monitor.

or buy an esp8266 dev board like Wemos/Lolin or NodeMcu and attach the sensors to it.

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


text:
Sensors are not function with ESP8266 WeMos-D1R2
I attached all sensor into the Wemos-D1 for uploading the sensor data to the server. but when I upload the data to the server, it connects to the server but cannot save the data into the database and after that send the second data to the server, it shows connections failed... besides, the sensor such as ultrasonic sensor and IR sensor cannot function.
here is the source code for connecting the sensor to the wemos. Not sure the connecting those sensors are correct or not to the wemos.
#include <ESP8266WiFi.h>
#include <ESP.h>
#include <LiquidCrystal.h>
//LiquidCrystal LCD(12, 11, 5, 4, 3, 2);
LiquidCrystal LCD(D0,D1, D5, D4, D3, D2);
const char* ssid     = "wifi username";
const char* password = "wifi password";
const char* host = "192.168.1.10";

#define in  D7 //7
#define out D8 //8
#define trigPin D2 //10
#define echoPin D3 //13
#define relay D2 //2
#define led D6 //6            //red color
#define led2 D0           //yellow color
#define led3 D1 //9           //green color

int count = 0;

int distanceCm;
long duration;

void IN()
{
  count++;
  LCD.clear();
  LCD.print("Number of Item:");
  LCD.setCursor(0, 1);
  LCD.print(count);
  delay(10);
  LCD.setCursor(3, 1);
  LCD.print(distanceCm);
  delay(10);
  LCD.setCursor(6, 1);
  LCD.print(" cm");
  if (distanceCm <= 3) {
    delayMicroseconds(10);
    LCD.setCursor(10, 1);
    LCD.print("Full");
    digitalWrite(led, HIGH);
  } else {
    digitalWrite(led, LOW);
  }

  if (distanceCm > 3 && distanceCm <= 5) {
    delayMicroseconds(10);
    LCD.setCursor(10, 1);
    LCD.print("Enable");
    digitalWrite(led2, HIGH);
  } else {
    digitalWrite(led2, LOW);
  }

  if (distanceCm > 5) {
    delayMicroseconds(10);
    LCD.setCursor(10, 1);
    LCD.print("Empty");
//    digitalWrite(led3, HIGH);
  } else {
//    digitalWrite(led3, LOW);
  }
  delay(500);
}

void OUT()
{
  count--;
  LCD.clear();
  LCD.print("Number of Item:");
  LCD.setCursor(0, 1);
  LCD.print(count);
  delay(10);
  LCD.setCursor(3, 1);
  LCD.print(distanceCm);
  LCD.setCursor(6, 1);
  LCD.print(" cm");
  if (distanceCm <= 3) {
    delayMicroseconds(10);
    LCD.setCursor(10, 1);
    LCD.print("Full");
    digitalWrite(led, HIGH);
  } else {
    digitalWrite(led, LOW);
  }

  if (distanceCm > 3 && distanceCm <= 5) {
    delayMicroseconds(10);
    LCD.setCursor(10, 1);
    LCD.print("Enable");
    digitalWrite(led2, HIGH);
  } else {
    digitalWrite(led2, LOW);
  }

  if (distanceCm > 5) {
    delayMicroseconds(10);
    LCD.setCursor(10, 1);
    LCD.print("Empty");
    digitalWrite(led3, HIGH);
  } else {
    digitalWrite(led3, LOW);
  }
  delay(500);
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  delay(10);

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  pinMode(led, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);

  LCD.begin(16, 2);
  LCD.print("Item Counter");
  delay(2000);

  pinMode(in, INPUT);
  pinMode(out, INPUT);
  pinMode(relay, OUTPUT);

  LCD.clear();
  LCD.print("Item In Box:");
  LCD.setCursor(0, 1);
  LCD.print(count);
  // ESP.restart();
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    // ESP.wdtFeed();
  }

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

int value = 0;
void loop() {

  delay(0);
  delay(5000);
  ++value;

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

  duration = pulseIn(echoPin, HIGH);
  distanceCm = duration * 0.034 / 2;

  //******************************************************//
  //IR Sensor Counting Object
  if (digitalRead(in) == HIGH && digitalRead(out) == LOW) {
    IN();
  }

  if (digitalRead(out) == HIGH && digitalRead(in) == LOW) {
    OUT();
  }

  if (count <= 0)
  {
    LCD.clear();
    digitalWrite(relay, LOW);
    LCD.clear();
    LCD.print("No Item in box");
    LCD.setCursor(0, 1);
    LCD.print("box is empty");
    delay(200);
  }
  else {
    digitalWrite(relay, HIGH);
  }

  Serial.print("connecting to ");
  Serial.println(host);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 8095;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }
  if (WiFi.status() != WL_CONNECTED) {
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED)
    {
      Serial.println("Waiting for connection");
      delay(0);
    }
  }

  String IRCount, myDistance;
  IRCount = String(count);
  myDistance = String(distanceCm);
  // We now create a URI for the request
  String url = "/Registration/write_data.php";
  url += "?item=";
  url += IRCount;
  url += "&distance=";
  url += myDistance;

  Serial.print("Requesting URL: ");
  Serial.println(url);

  // This will send the request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");
  int timeout = millis() + 5000;
  while (client.available() == 0) {
    if (timeout - millis() < 0) {
      Serial.println(">>> Client Timeout !");
      client.stop();
      return;
    }
  }

  // Read all the lines of the reply from server and print them to Serial
  while (client.available()) {
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }

  Serial.println();
  Serial.println("closing connection");
}

Anyone has the solutions please help me

is the LCD SPI? you use 4 pins D5/SCK, D6/MISO, D7/MOSI, D8/SS like it would be 10 different pins. how did you wire things?

LCD wire code is LCD(MISO, MOSI,D5, D4, D3, D2) which consists of 6pins for the LCD and then the IN and OUT pins are IR SENSOR PINS AND TRIG AND ECHO for the ultrasonic sensor pins but all of these sensors can’t work.

MISO is D6, MOSI id D7. why do you use SPI pin defines if it is not SPI?

MISO is the Wemos board pins... if I use the arduino board pins it wouldn’t work

Wemos has D0 to D8. MISO and MOSI are aliases to D6 and D7

But for what I attach  the MISO and MOSI pins are representing the D12 and D11

I have edited the pins based on just now u mention there are only D0 to D8 in wemos. So, I have edited the source code as above... but it shows this error: espcomm_upload_mem failed

but you how do you wire it if D2, D3 are for display and for ultrasonic sensor and relay at the same time? pins D3,  D4 and D8 are boot setup pins with pull-ups and pull-down (D8). this state must be preserved at boot. the wired devices must not pull-down D3 and D4 to LOW or set D8 HIGH before they are initialized in setup()

= = I have no idea already because I use the Arduino UNO board logic to wire it

Because i have 2 IR sensor, 1 ultrasonic sensor and LCD which must connect it to the Wemos board

use I2C LCD or don't use LCD but make a web page

make a web page?

you mean that if i dont use LCD then i have enough pins for me to connect ?

or display the data on the webpage that is what i want

I meant a local web page

Ya that what I going to do. Now For what I do is uploading this data into the php file and this php file will save it into the database. After that I use the webpage to read this data from the database and display it on the local webpage

Just for clarification, there are nine pins for me to attach the sensor (D0 -D8) in wemos. So if I attach the sensor to those pins (D0 -D8) so it can function and directly upload the data ?

yes. only test the sensors on different pins to find out what doesn't disturb D3, D4 and D8 at boot. and avoid D0 if you can. it is a little special too

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


text:
Arduino Uno and FastLED WS2812B Glitching
I’m using an Arduino Uno and a fastLed WS2812B.
I have the leds set up correctly. Every 2 seconds, the lights pause of about a second and display seemingly random colors.
Does anyone know what's wrong?
My code:
#include <FastLED.h>

#define LED_PIN   7
#define NUM_LEDS  10

CRGB leds[NUM_LEDS];

void setup() {
  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);

}

void loop() {
  for (int i = 0; i < NUM_LEDS; i++){
    leds[i] = CRGB(0,0,255);
    FastLED.show();
    delay(100);
  }
  for (int i = 0; i < NUM_LEDS; i++){
    leds[i] = CRGB(255,0,0);
    FastLED.show();
    delay(100);
  }
}

Is this on an Arduino or something else like ESP8266?

It is an Arduino Uno

How are you powering the LEDs?

I noted that each example in fastled library, ‘’clear’’ the array, after running ‘’show’’ function. Try with: leds[i]= CRGB::Black; after ‘’show’’.

what happens if you put FastLED.show(); and delay(100); after the for loop

I am powering with three AA batteries

How are you connecting those batteries?

I just connect them in series directly to the lights. Should I also attach them to the 5v and ground on the arduino?

connecting the grounds fixed it =D, does anyone know why?

https://majenko.co.uk/blog/importance-sharing-grounds

I have run the code on the Arduino simulator online. If it is working in the Arduino Simulator chances are less that it has to do something with the code itself.
Hence, also as the root cause was found to be about sharing the ground @Majenko
This is also one example of solving the problem step by step. validating one section after the other. using the simulator you can verify that the code is working fine. later, proceed to verify the hardware. I hope this helps.
You can verify the FastLED code here (you can modify the parameters)

Is this really answering the question? It seems to be saying what the problem isn't.

@NickGammon I too agree ☑. I tried to show how I could deduce the root cause to be hardware and not the library or the code itself. The OP has also found the root cause to be hardware.


text:
How to generate 4 square signals using Arduino Mega 2560 below 30hz using timers
I would like to generate 4 square signals of different frequencies below 30 hz using timers of Arduino Mega.
I was able to generate 30.6hz signals but I have no idea how to generate lower frequencies.
Any help would be appreciated.

Yes, you can use PWM with timer.  Take a look to this guide: https://www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM

How low? lower than 1Hz? Is it without pwm, just a 50% square wave? How accurate should be frequency be? Should the signal be very steady or is a software (with or without interrupt) also possible. I assume there is a library that can use all the timers of the arduino mega, but I could not find it yet. Please also tell us what your project is for.

30.6 Hz is the slowest you can get from an 8 bit timer. For lower frequencies, you will have to use 16 bit timers.


text:
Arduino MySQL Connector Issues with Select only
first question i am doing so hope this is the right place.
I have an issue with an Arduino Uno and an Arduino ESP8266WiFi Shiald by WangTongze using this tutorial (https://www.instructables.com/id/ESP8266-ESP-12E-UART-Wireless-WIFI-Shield-TTL-Conv/) I have been able to connect to the my Wifi and host a small webserver.
Then with the Examples of the MySql Connector Library I have been able to do a simple Insert to a MySQL Database on a NAS Server. However, I want to be able to select a value from my DB and print it on the screen for some reason the Cursor always returns a null. I have been able to select from my PC using the same user. and created the user francis@% so that the host isn't an issue. Please note that this same code with a few tweaks worked to insert a record to the same table. Is there anything I am missing? Below is the code:
//#include <WiFi.h> // Use this for WiFi instead of Ethernet.h
#include <WiFiEsp.h> //use for ESP8266
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

// Emulate Serial1 on pins 2/3 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(2, 3); // RX, TX
#endif

byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server_addr(192,168,x,x); // IP of the MySQL server here
char user[] = "francis";
char password[] = "xxxxxx";

// WiFi card example
char ssid[] = "PintoLoco"; // your network SSID (name)
char pass[] = "xxxxxxxx"; // your network password

//WiFiClient client; // Use this for WiFi instead of EthernetClient
WiFiEspClient client; //Use this for ESP8266
MySQL_Connection conn((Client *)&client);
MySQL_Cursor cur = MySQL_Cursor(&conn);

char query[] = "SELECT Value FROM Peceras.Parameters ";

void setup() {

  Serial.println("Starting....");
  Serial.begin(115200);
  // initialize ESP module
  WiFi.init(&Serial);
  Serial.println("Connecting to WiFi");

  // Begin WiFi section
  int status = WiFi.begin(ssid, pass);
  while(status != WL_CONNECTED){
      status = WiFi.begin(ssid, pass);
    }
  // print out info about the connection:

  Serial.println("Connected to network");
  IPAddress ip = WiFi.localIP();
  Serial.print("My IP address is: ");
  Serial.println(ip);

  // End WiFi section

  Serial.println("Connecting...");
  if (conn.connect(server_addr,3306,user,password)) {
  delay(1000);
  }
  else
  Serial.println("Connection failed.");
}
MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
void loop() {
  row_values *row = NULL;
  long head_count = NULL;
column_names *cols = cur_mem->get_columns();
cur_mem->execute(query);
  // Execute the query
  do {
    row = cur_mem->get_next_row();
    if (row != NULL) {
      for (int f = 0; f < cols->num_fields; f++) {
        head_count = atoi(row->values[f]);
          Serial.print("Ingestelde Temperatuur:  ");
          Serial.println(head_count);
        if (f < cols->num_fields-1) {
          Serial.println(',');

        }
      }
      Serial.println();
    }
  } while (row != NULL);
  // Deleting the cursor also frees up memory used
  delete cur_mem;
  delay(2000);
}

I do not know much about MySQL databases and absolute nothing about the Client you use on your Arduino. So my hints are only wild guesses ;-): You did not end the SQL statement with a semicolon.  Normally that's not a problem because the client lib does it for you, but this client could be an exception. You define a cursor cur you never use. Perhaps the client lib can only handle one active cursor. You select only one field "Value" but iterate over a list of fields. This is not a problem if the field "Value" exists. Perhaps you could try: "SELECT * FROM Peceras.Parameters;"

Thanks Peter, for your response, I have tried your seggestions and I get the same output sadly. The database is just one table with 3 columns and Value is one. I am unsure and thinking it might be to slow to obtain the data when doing the command? out of ideas

Sorry I did not realize that you used the Serial interface for the normal Serial to USB comunication and also for the  connection to the WIFI shield. That will not work. The program defines a Serial1  that you can use to connect to the Shield, but you have to connect the TX and RX pins of the shield with the pins D2 and D3 of the Arduino with wires. (It's been described in the instructables you linked to) I added an answer, For me  it's easier to write code than to write text. ;-) I also did not realize that you close the cursor in the for loop again and again, but you opened it just once.

I have no access to a compiler, so there might be errors.
#include <WiFiEsp.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(2, 3); // RX, TX
#endif

byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server_addr(192,168,x,x);
char user[] = "francis";
char password[] = "xxxxxx";

char ssid[] = "PintoLoco";
char pass[] = "xxxxxxxx";

WiFiEspClient client;
MySQL_Connection conn( (Client *) &client );
MySQL_Cursor *cur_mem = null;

// PPK: some database systems are case sensitive
// so Peceras.Parameters is not the same as peceras.parameters
// check if the tables and fields are named correctly.
char query[] = "SELECT Value FROM Peceras.Parameters";

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

  Serial.println( "Connecting to WiFi" );
  WiFi.init( &Serial1 );
  int status = WiFi.begin( ssid, pass );
  while( status != WL_CONNECTED )
  {
    status = WiFi.begin(ssid, pass);
  }

  Serial.println( "Connected to network" );
  IPAddress ip = WiFi.localIP();
  Serial.print( "My IP address is: " );
  Serial.println( ip );

  Serial.println( "Connecting DB ..." );
  if ( conn.connect( server_addr, 3306, user, password ) )
  {
    Serial.println( "DB connected." );
    cur_mem = new MySQL_Cursor( &conn );
    row_values *row = NULL;
    long head_count = NULL;
    column_names *cols = cur_mem->get_columns();

    cur_mem->execute(query);

    do
    {
      row = cur_mem->get_next_row();
      if ( row != NULL )
      {
        for ( int f = 0; f < cols->num_fields; f++ )
        {
          head_count = atoi( row->values[f] );
          Serial.print( "Ingestelde Temperatuur:  ");
          Serial.println( head_count );
          if ( f < cols->num_fields - 1 )
          {
            Serial.println(',');
          }
        }
        Serial.println();
      }
    } while (row != NULL);

    // Deleting the cursor also frees up memory used
    // PPK: I'm not sure if this is a good idea, I don't know
    delete cur_mem;
  }
  else
  {
    Serial.println( "DB Connection failed." );
  }
}

void loop()
{
  // PPK: I would recommend to do the select in the setup section
  // It looks like you want to run it just once
}

Edit
Please note, that this code only works if you connect the software serial pins D2, D3 to the respective RX and TX pins on the Shield. You have to bend the pins (P0-P3) of the shield to disconnect them from the Arduino. Then you have to connect D2 and D3 to P0 and P1. This is described in step 1 of the instructables you linked to in the question. See the picture at the end of Step 1. https://www.instructables.com/id/ESP8266-ESP-12E-UART-Wireless-WIFI-Shield-TTL-Conv/

Thanks Peter for the response, i tried this code, and now it doesn't start the Esp Module, I get a timeout: [WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] Cannot initialize ESP module


text:
"Manually" generating a PWM signal
I've been trying, just out of curiosity, to write my own function that generates a PWM signal, just like analogWrite(), and to make it light up an LED. Here's my attempt so far:
const int pin = 3;
int cycle = 2; // analogWrite() outputs a 498 Hz signal, so each cycle has approximately 2ms

int duty = 0.5; // for a 50% duty cycle

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

void loop() {
  digitalWrite(pin,HIGH);
  delay(cycle*duty);
  digitalWrite(pin,LOW);
  delay(cycle*(1-duty));
}

The LED does light up, but very dimly, as shown below:

However, when using analogWrite() with a 50% duty cycle to achieve the same result, the LED shines much brighter:

Is there something wrong with my code, or is there a special reason why more power is dissipated with analogWrite()?

have you tried different values in cycle?

I've just tried that, and indeed the brightness increases as the cycle values get smaller. However, I had to use cycle values as low as 2 microseconds in order to get a brightness comparable to the one provided by analogWrite(). I can't really understand why, though, so I'd really appreciate it if you could provide some clarification. :)

i do not know ... i suspect that the signal waveform is not what you and I expect it to be ... only way to check is to put a scope or a logic analyzer on the output

You need to review your code and also the capabilities of the Arduino UNO.

int declares an integer.  So int duty = 0.5; is going to get rounded to either 0 1.
delay(0); also will not work.  The instruction will simply get skipped. Likely the reason why you get a brighter LED. Try to use delayMicroseconds(); if you need shorter time but the minimum delay you can have is 4 us for Arduino UNO.
If you are using times as short as 2 us, then from the above comment the delayMicroseconds(); function is not going to be sufficient.  Also, you should consider the loop overhead, which will be a few microseconds.

All in all this is not a great method.  If you do want to create your own PWM signals, it is much better to use the hardware timers.  For example this tutorial on the Arduino website.  You should also be able to find posts about hardware timers on Arduino SE.


text:
Arduino Nano: HUGE voltage drop on VIN
I am building a small automated indoor greenhouse. I want to use an Arduino Nano to control some LEDs und a fan (both through relays) and a water Grove Water Atomization module. Everything works fine, as long as I power the LEDs and the fan with a 12v supply (3 watts) and the Nano through USB. But I want to power the Nano through the 12v supply, too.
So I built a voltage divider that delivers 7.25v. I measured it with a multimeter. But when I connect it to the VIN of the Nano, the voltage drops to 1.16v. Wich – of course – means that the Nano doesn't start. When I tried it, only the Nano and the relays were connected to the 12v power supply. The relays through voltage divider delivering 5v.
I tried it with an original Arduino and a chinese compatible and got the exact same result both times.
Does anyone have an idea, what I am missing?

Schematic? Voltage dividers are not really regulated power supplies. In fact, not at all.

https://majenko.co.uk/blog/our-blog-1/why-you-can-t-use-resistors-as-a-voltage-regulator-15

You just can't use a couple of resistors to deliver a reliable voltage source like that. The voltage divider effectively works as advertised with zero current. Your Nano will take more than zero current. See here for one discussion.

Ah, okay. So I really missed an important detail. Thanks a lot. I just tried a step-down converter and it works like charm.

If you do not place more than a few mA load on the Nano 5V pin you can wire 'Vin' directly to 12V. Your resistor idea sounds great however when you add the fluctuating current requirement you cannot get a stable output it will change with the load. Note the divider circuit resistance has to be very low in value to stay close making it not practical.

Yes, I know. I tried that first. But the voltage regulator of the Nano got quite hot, I guess the water atomization module draws too much current.

Try it without the atomizator. I have a feeling it will stay much cooler.

The heat wasn't the only problem with the atomizer. Whenever it was attached to the Nano, the Nano froze after some minutes. I added the step-down converter to supply 7 volts to VIN, which helped with the heat, but the Nano still froze. So I added a voltage regulator, to bring the 7 volts to 5 volts for the atomizer. Now everything works fine. And no element gets hotter then 34°C.


text:
Measure audio frequency through pulse duration
Hello dear StackExchange users,
i want to develop an Infrared blaster which i can plug into the headphone jack of a phone or console of choice. In order to communicate what frequency to modulate the diode with and how long to send pulses, i simply generate tones for the Arduino to read and interpret.
My problem is that i can't reliably measure the frequency with it. In order to measure the frequency i use an Analog Comparator Interrupt and trigger at falling edge, thus getting always the interrupt after a full pulse occured. I called micros() at every interrupt in order to get the pulse duration, but it was too imprecise. Then i tried using Timer0 with a prescaler of 8 to measure the frequency, but it only counts to 255.
Now i switched over to Timer1 because of it's bigger TCNT register. However for some reason it already overflows at 255 even though i didn't set the OCR1 registers.
This is my current code. Please note that the actual frequency calculation happens in the main loop to not mess with the measurements gained in the ISR.
const int setFrequencySound = 1000;
const int receiveDataSound = 2000;
const int receiveDataEndSound = 3000;

const int readyMode = 0;
const int setFrequencyMode = 1;
const int receiveDataMode = 2;
const int sendDataMode = 3;

volatile unsigned long timeBefore;
volatile unsigned long timeNow;
volatile unsigned long delta;
volatile float audioFrequencyBefore;
volatile float audioFrequency;

volatile float irFrequency;
volatile int irData[100];
volatile int irDataIndex;

volatile int mode = 0;

ISR (ANALOG_COMP_vect)
{
timeNow = TCNT1;
Serial.print (timeNow);
Serial.println (" TCNT1");
//TCNT1 = 0; //reset timer register
}

void setup ()
{
Serial.begin (115200);
Serial.println ("Started.");
ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
      | bit (ACIE)    // Analog Comparator Interrupt Enable
      | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge)

TCCR1B |= (0 << CS12) | (1 << CS11) | (0 >> CS10); //Activate timer and set prescaler to 8
TCNT1 = 0; //Reset timer register
}  // end of setup

void loop ()
{
//Calculate frequency by using the period duration
//determined through the timestamps captured in
//ISR method.
//delta = timeNow - timeBefore;
audioFrequency = 1000000000.0 / (float(timeNow) * 2.0);

if (millis() % 1000 == 0)
{
  Serial.print (audioFrequency, 5);
  Serial.print (" Hz, ");
  Serial.print (timeNow);
  Serial.println (" TCNT0");
}

//Do not process the same frequency multiple times
if (audioFrequency != audioFrequencyBefore)
{
  switch (mode)
  {
    case readyMode:
      if (audioFrequency == setFrequencySound)
      {
        mode = 1;

        Serial.println ("Start setting IR frequency.");
      }
      else if (audioFrequency == receiveDataSound)
      {
        mode = 2;

        Serial.println ("Start receiving IR data.");
      }
      break;
    case setFrequencyMode:
      irFrequency = audioFrequency + 25000;

      Serial.print ("IR frequency set to ");
      Serial.print (irFrequency, 10);
      Serial.println (" Hz.");

      mode = readyMode;
      break;
    case receiveDataMode:
      if (audioFrequency == receiveDataEndSound)
      {
        Serial.println ("Stop receiving IR data.");

        mode = readyMode;
        irDataIndex = 0;
      }
      else
      {
        irData[irDataIndex] = audioFrequency;

        irDataIndex++;

        Serial.print ("IR pulse received: ");
        Serial.print (irData[irDataIndex]);
        Serial.println (" microsecs.");
      }
      break;
    case sendDataMode:
      Serial.println ("Sending IR data...");
      break;
  }
}

audioFrequencyBefore = audioFrequency;

}  // end of loop

Please show a full compilable code (including the loop function). Serial printing in an ISR is not a good thing. You can very fast fill up the serial buffer that way. What frequency are you trying to measure? Since the signals on a standard headphone jack are often differential (for example in the range of +-1.2V) how are you processing the signal before feeding it into the Arduino?

Of course serial printing in the ISR isn't a good idea, but i gotta get my info somehow. When that issue is fixed, i'll remove this print command. The frequency i'm trying to measure is the audio frequency of a signal that i generate. No song, microphone input or anything, just a simple square tone i generate. Well, multiple tones.

Timer 1 overflows at 255 because that's how it has been configured by
the Arduino core, as it is intended to provide 8-bit PWM. If you want
to use the timer in normal mode, you should undo the Arduino's
initialization by setting TCCR1A to zero.
Two comments on the ISR:
ISR (ANALOG_COMP_vect)
  {
    timeNow = TCNT1;
    Serial.print (timeNow);
    Serial.println (" TCNT1");
    //TCNT1 = 0; //reset timer register
  }

First, as has been stated in a previous comment, you should not print
from within an ISR. Also, if you want consistent timing, you should
never reset the timer. Just keep it freely running and use time
differences to get the signal period. Do not worry about the timer
overflowing: if you do the computation with unsigned 16-bit integers
(uint16_t), you will be immune to the overflows. If you reset the
timer you will likely loose some ticks, as you can not read it and reset
it in the same clock cycle.
Lastly, I recommend you read about the “input capture” capability of
Timer 1. This is a feature of the timer designed for solving the exact
kind of problem you have here: the timer will automatically record a
timestamp on an external event. You can have this triggered by a rising
or falling edge on input pin 8, or by the analog comparator if you
prefer. This method gives you zero jitter, which cannot be achieved with
code, even running within an interrupt.

Edit: Answering an extra question in the comment.

Could i connect the audio wire [...] directly to pin 8 and use the
input capture functionality?

It depends on the shape of the signal that comes out of this wire.
First, you have to make sure the signal always stays between the
electric potentials of GND and Vcc (i.e. 0 – 5 V), otherwise you risk
damaging the Arduino.
Note that if the signal comes from a high impedance source, it can
safely go somewhat beyond this range, as the Arduino has all of its
inputs protected by diodes. You just have to limit the current in the
diodes to less than 1 mA. In other words, for each kΩ of output
impedance, you can extend the (unloaded) acceptable voltage range by 1 V
on each side. If the source is low impedance, you can make it high
impedance simply by adding a 10 kΩ resistor in series.
Second point is, you have to make sure the signal has a large enough
voltage span to make the digital input switch between LOW and HIGH.
According to the datasheet of the ATmega328P, when powered at 5 V the
input thresholds are typically around 2.1 V for switching LOW and 2.6 V
for switching HIGH. The difference between those thresholds provides
some hysteresis, which can help cancelling noise. Note that those are
typical values. If you want guaranteed switching, the signal should go
below 1.5 V to get a guaranteed LOW reading (this is VIL) and
above 3 V to get a guaranteed HIGH reading (VIH).
Note also that, if the input thresholds of the digital pin do not fit
your needs, you can use the analog comparator as a trigger for the input
capture.

Interesting, so the timer-1 tip would work on all 328p based Arduinos right? +1

@Tim_Stewart: Indeed. It's a feature of the ATmega328p (and many other ATmegas), not of the Arduino board that hosts it.

@EdgarBonet Could i connect the audio wire (i have a jumper cable hooked up to the left channel of a headphobne plug) directly to pin 8 and use the input capture functionality?

@MyFairJulie: See amended answer.

@EdgarBonet In fact i already use an analog comparator as seen here. Can just set up the input capture interrupt? Or do i still need the analog comparator interrupt?

@MyFairJulie: If you use the input capture feature of Timer 1, the the input capture interrupt is probably the best place to get the timestamps.


text:
ESP-12e - RX/TX pins flickering on boot when used as GPIO pins
I am using ESP-12e as a controller for my garden lights. I am using pins 1 (TX), 3 (RX) and 5 as an analog output (PWM signal with mosfets) for three separate light sets. ESP is powered on when wall switch is turned on (wall switch turns on power adapter). When I turn the switch on, for short period of time lights connected to pin 1 and 3 work at full power and after that they are set according to PWM signal. Lights on pin 5 works just as expected. I am not using Serial communication, just elegantOTA library for OTA updates and async web server. Is it possible to somehow disable RX/TX functionality at all/before they are set to high, or I am forced to solder lights on pins 1 and 3 to another ones? I tried some software tricks I found online, but without success.

I am not using Serial communication,

You might not be, but the bootloader sure is.

Is it possible to somehow disable RX/TX functionality at all/before they are set to high

No. It's hard coded in ROM. There's nothing you can do.

or I am forced to solder lights on pins 1 and 3 to another ones?

You could use one IO pin to control a buffer the other IO pins. Something like an AND gate (74HC08) would do the job:

simulate this circuit – Schematic created using CircuitLab
Only when CTL is HIGH will the L0-L2 signals be mirrored on the outputs to the LEDs. That way you ignore whatever is going on with those pins until you actively drive the CTL signal high. Choose one pin that has no boot noise for CTL and the other pins then don't matter.
For more detail on what pins do what at boot time read this.

Thanks. I was hoping I could solve this problem only with software because of difficult access to esp-12. I understand the way with AND gate, but probably simpler way for me is to cut off cables from RX/TX and solder to more appropriate pins.

After some digging I realized, that esp-12 has only two pins (4 and 5) which are perfectly suitable for my job (no high state on boot), so as I need three pins, your AND buffer technique is  best option.

This is why most WiFi lights that use the ESP8266 (or ESP8285 most commonly) use a PWM LED driver chip, like the MY9231. Offload the LED control to something else and don't worry about what happens at boot on the ESP8266.

According to this reference, GPIOs 1 and 3 have dedicated behaviour during boot (debug output or pulled high) which can not be disabled in your sketch.
You have to either choose different pins or implement an additional circuitry.

Thanks. I was hoping I could solve this problem only with software because of difficult access to esp-12. I did not give enough time to the selection of pins, but at least, I learned something new.


text:
ST7920 and u8g2 only using some of a 128x64 display
I am trying to use the u8g2 library and an Arduino Mega to control an LCD display. Adapting HelloWorld from the examples included in the library to use the SPI ports of the Mega (50-52), I have the code below.
This gives a bit of a disappointing greeting as in the picture below. It seems that the Arduino is not accessing all the pixels, and only able to change the states of three blocks (the top one with "Hello V", and the two darker regions at the bottom).

The display is a 128X64ZW-10 salvaged from a 3D printer which was working when connected to the printer's motherboard. Pin-out deduced by some kind folk here and here (translation). I briefly saw random Pinyin characters flash across the whole display while I was switching wires. These two facts, and the fact that the regions of pixels that are working are not arranged at random, makes me suspect it is a wiring or coding issue, and that the pixels are not dead.
Here is the code:
#include <Arduino.h>
#include <U8g2lib.h>

#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif

int LCD_CLK_PIN = 52; //Clock (white)
int LCD_RW_PIN = 50; //Read-Write (blue)
int LCD_RS_PIN = 51;  //Register Select (green)
U8G2_ST7920_128X64_F_SW_SPI u8g2(U8G2_R0, LCD_CLK_PIN, LCD_RW_PIN, LCD_RS_PIN,U8X8_PIN_NONE);

void setup(void) {

  /* U8g2 Project: SSD1306 Test Board */
  //pinMode(10, OUTPUT);
  //pinMode(9, OUTPUT);
  //digitalWrite(10, 0);
  //digitalWrite(9, 0);

  /* U8g2 Project: T6963 Test Board */
  //pinMode(18, OUTPUT);
  //digitalWrite(18, 1);

  /* U8g2 Project: KS0108 Test Board */
  //pinMode(16, OUTPUT);
  //digitalWrite(16, 0);

  /* U8g2 Project: LC7981 Test Board, connect RW to GND */
  //pinMode(17, OUTPUT);
  //digitalWrite(17, 0);

  /* U8g2 Project: Pax Instruments Shield: Enable Backlight */
  //pinMode(6, OUTPUT);
  //digitalWrite(6, 0);

  u8g2.begin();
}

void loop(void) {
  u8g2.firstPage();
  do {
    u8g2.setFont(u8g2_font_ncenB10_tr);
    u8g2.drawStr(1,18,"Hello World!");
  } while ( u8g2.nextPage() );
  //delay(1000);
}

I have spent a couple of days on this, but no luck. Any ideas?

Many thanks for your photos.
Test carried out with the motherboard of an Ender3 V1.1.3
PIN configuration: U8g2lib library
#include <U8g2lib.h>

#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif

int LCD_CLK_PIN = 30; //Clock (white)
int LCD_RW_PIN = 17; //Read-Write (blue)
int LCD_RS_PIN = 28;  //Register Select (green)
U8G2_ST7920_128X64_F_SW_SPI u8g2(U8G2_R0, LCD_CLK_PIN, LCD_RW_PIN, LCD_RS_PIN,U8X8_PIN_NONE);

configuration PIN: library U8glib
#include "U8glib.h"
U8GLIB_ST7920_128X64_1X u8g(30, 17, 28);  // SPI Com: SCK = en = 18, MOSI = rw = 16, CS = di = 17

Your program is working properly.

Welcome to Arduino Stack Exchange. In future please post answers in English. I have translated your post for you. Also please format your code in future by selecting it and pressing Ctrl+K.


text:
Can't burn Bootloader on Atmega328P Using Arduino Uno
I'm trying to create an Arduino Uno following the circuit described in the diagram below which I'd based from here.
I'd tried this circuit on an Atmega328 PDIP version (with the correct connections since the PDIP has different pinouts from this TQFP) and I was successful in creating and using my own Arduino.
However, when I've used the TQFP version and had this circuit layout and printed on a pcb, I can't burn the bootloader using an Arduino UNO.
I've double checked the pinouts from the Atmega328P datasheet and they are correct. Using a tester, I've also verified that the connections are there.
By the way, I've used the following connections.
Arduino Digital Pin 13 to SCLK
Arduino Digital Pin 12 to MISO
Arduino Digital Pin 11 to MOSI
Arduino Digital Pin 10 to RESET
Arduino 5V to VCC
Arduino GND to GND

I've also burned the ArduinoISP program on th Arduino UNO, selected Arduino as ISP and chosen Arduino UNO as board.
When I press 'Burn Bootloader', I'm getting this error message.
avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

I've looked at different forums and they are only saying to check the connections which I'd already checked that there is.

I have had this problem in the past and it has always been one of two solutions

The wires were misconfigured, and I only saw it after the Nth time
Wrong chip, I was trying to program a 328 when it expected a 328p

And the secret third option:

Some chip/wire/etc. was busted/burned/bad.

Unfortunately These were the only outcomes to ever come for me when I encountered that particular error.

I've checked the connections a lot of times today and they were correct. Also, I've wrongfully placed an Atmega328PB before. Upon making necessary software changes, I've successfully burned a bootloader. It is also a correct chip now that I'm having this issue. And I've used 3 chips by now and changed a lot of wires so I would want to rule that out?

here is a Link... https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard
If bootloader is burned with arduino uno in atmega328 then code will be uploaded for once and run correctly but next time you tried to burn code in atmega328 then code will not burn in atmega328. I also tried this way but it just work one time for me then I bought usbasp(price 1.5$) to burn bootloader permanently. after burning bootloader with usbasp then its works perfect for me.
Just connect crystall with filtering capacitor thats enough to burn bootloader. above config is just in case you want to use it as MCU.

That's actually the link where I'd based my circuit. Also, I've just bought the chips so I think there are no bootloaders in them. I've tried reburnong the bootloader on the Atmega328p DIP that I've used before. It's working.

The design is missing 0.1uF caps on VCC, AVCC, and Aref.
Aref should not connect to 5V directly. It is connected internally thru a mux and only needs the 0.1uF to Gnd.  If Aref is direct connected and then the sketch selects the internal 1.1V reference, it can/will damage the chip.
Change the 220 ohm resistor on D13/SCK to 1K.  220 ohm puts quite a load on the SCK line for a Programmer. 1K will result in a plenty bright LED.
Do you have a 0.1uF between DTR of a Serial programmer and the Reset pin?  A Programmer needs direct control of the Reset line, a Serial programmer (such as an FTDI Basic module) needs to go thru a cap so a Reset pulse is created.

Actually, I have a cap between VCC, AVCC and GND that I haven't included in the screenshot. Now that you've mentioned it, I'm seeing a small arc (spark) on the AREF pin. What I've done is I'd lifted the pin out to disconnect it from AVCC and VCC, and soldered a 100nF cap to GND. What it did however is create a larger arc on the pin.

Also, before, I'd ordered Atmega328PB instead of Atmega328P. I'm getting an error on device signature then. I've done some modifications based on different forums and was successful on burning a bootloader and uploading a sketch. Now, I've got the correct Atmega328P, installed on the same layout and I'm having this problem.

By arc, you mean you are seeing sparks? That's not good at all. Is your 5v line ok?

Yes, I mean spark. And I can't understand why. The 5V line is ok. Seeing some spikes on oscilloscope whenever a spark forms on the AREF pin though.


text:
How to speed up Due ADC
I'm doing a project where in I'm using Arduino Due to measure the time difference of arrival of signals to four piezoelectric sensors. The piezo sensors where glued on a board and we want to localize the source of taps on the boards based from the TDOA of the vibration to the piezos.
Originally, we are using interrupts to raise flags once we have detected the signals (basically, we've set a threshold on the piezo voltage to say that we've 'detected' a signal) but that seems susceptible to noises especially when the environment has loud noises (music, voices on microphones, etc.).
So what we think as a solution is to perform signal processing. However, to do this, we need to measure the voltage of the incoming signal using the ADC.
So far, my target is to make the performance of this approach comparable to that of the one where we are using interrupts. As of now, the new approach is super sensitive to the difference on the taps giving it a high POE.
As I understand it, the main difference between the two approach is that the interrupt approach has a microsecond difference between counts making the difference of the taps to about 10 to 30 microsecond. However, the Analog approach has a 20 microsecond difference between each sample for each channel, making the count difference 20 second also. Even a count difference would make it 20 us.
Is there anyway to make this time faster? I know the ADC needs time to convert and push the data to the appropriate registers but I'm just trying to find ways to make this faster. I've read on the datasheet of the Due MCU that it has 14 ADC channels plus a temp sensor at the 15th. Maybe a way of doing this could be to reduce the number of channels? I don't know how.
Are there any way to make the ADC conversion of the Arduino Due faster?

Yes, there is a possibility to configure ADC to run faster, as it can handle 1Msps. For four ADC channels it means 250ksps each (with 1us time difference between samples). It's not possible with Arduino wrappers as they are way too slow and also waits for conversion end. You have to configure it directly in MCUs registers, so start with SAM3X8 datasheet.
In short: free running mode, sequenced readings like: 0 1 2 3, with interrupt on 4th sample, interrupt handler and some processing.

Thanks @KIIV! Another question, in the free running mode, would there be any problem on reading the output registers? I mean since the ADC is freely converting and I'm still reading channel 1 (I reckon reading through SPI or I2C is slower than the actual conversion), but the ADC has new set of data, will there be any data collision or anything?

@noobiejp That's why I mentioned sequenced readings. You can configure it to go over ADC inputs in any order. And readings are stored in corresponding data registers.

You can set the ADC in freerun mode to get results as fast as they can be read.
Use adc_configure_trigger for this.
adc_configure_trigger(ADC, ADC_TRIG_SW, ADC_MR_FREERUN_ON);

To enable freerun on the ADC or to configure as needed. No need anymore to set registers.
There was a bug with this function before if called more than once, but it is now fixed.
https://github.com/arduino/Arduino/issues/1819

difference between each sample for each channel,

That's way too slow for any mcu made since the 1980s.
Look into the datasheet and compare it via your code to see where you can pick up the speed. Typically there is a clock prescaler for the adc that you can change.
In general, the fastest would be continuous adc into dma. If you need to add multiple channels turn on scanning.

//Configure ADC
PMC->PMC_WPMR &= ~(PMC_WPMR_WPEN);    //Disable the Write Protect Mode
PMC->PMC_PCER1 |= PMC_PCER1_PID37;    //Enable ADC Peripheral Clock
PIOA->PIO_PDR |= PIO_PDR_P16;         //Disable PIO Controller
ADC->ADC_WPMR &= ~(ADC_WPMR_WPEN);    //Disable the Write Protect Mode
ADC->ADC_CHER |= ADC_CHER_CH7;        //Enable A0 pin
ADC->ADC_MR = 0;
//ADC->ADC_MR = ADC_MR_PRESCAL(2);    //ADC Clock set to 16MHz
ADC->ADC_MR = ADC_MR_PRESCAL(4);      //ADC Clock set to 8MHz
ADC->ADC_MR |= ADC_MR_TRACKTIM(3);
ADC->ADC_MR |= ADC_MR_STARTUP_SUT8;
ADC->ADC_EMR = 0;
//read ADC output
ADC->ADC_CR |= ADC_CR_START;           //Software Trigger
uint32_t adc_read = ADC->ADC_CDR[7];
you can change the parameters of prescaler to get the required speed

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


text:
Purposely create compile error to fail the upload
I would like to create a compile error so sketch does not upload in certain cases.
I have written a library with a function that adds pins being used to an array. If the same pin is used twice I want to fail the compilation (preferably with an error that explains why). Is this possible?
void CheckPinNum(int newPinNum){
  for (int i=0; i <= PinArrayLength; i++){
    if (newPinNum == PinArray[i])
      failCompilation("You entered same pin twice!");
  }
}

@LookAlterno If you vote that way, please be kind enough to explain to me how I should ask the question to get where I want.

@LookAlterno So in that case you can write an answer like "This is not possible because a compiler can't pre-evaluate the variables written in the sketch". Or suggest someway that can work. Thanks anyway.

@LookAlterno Are you not aware that many people using Arduino may have never taken any course and they learn as they go? Anyway, the "Be Kind 101" course is a lot more fundamental.

How could this be done? What fundamental mechanisms are available in C++? Actually there is. It is called static_assert http://en.cppreference.com/w/cpp/language/static_assert. To use it in this case the compiler must be able to evaluate the function at compile-time. This requires the pin number vector to be const but then adding a pin makes no sense (as a compile-time error:). An example of using static_assert can be found here https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Queue.hh#L36

@bets. The question has been answered but I want to point out that C++ is not the hardest language to learn. A major factor in assessing the difficulty of learning a language is the order in which you learn them. For example, If you want to go the C/C++ route then learning assembly first makes learning C easy, especially when dealing with pointers which is the hardest thing for many novices. Secondly, Arduino is a great way to get into programming (and electronics) Just about anything you can think of has been done with them and there is a huge community out there willing to help.

It's impossible to check dynamic behavior compile time.
However, the best 'alternative' I can think of, is during the setup set all pin numbers (if that is possible).
And if something is wrong, let the 'user' or client know something is wrong. In extreme cases, just by putting the Arduino in an endless loop, in best cases, send a serial line, blink a light or whatever feedback.
You can do the same later on (when CheckPinNumber needs to be called in the loop, so not at setup), but the sooner you can do these checks, the better.

To answer the question asked in the title:
#if some_condition
# error Some error message
#endif

But note that this technique only works at compile time, which
probably makes it useless for you.

Thanks! "compile time" is good for me. I'm not sure I totally understand this answer. But I will try to figure out how to check the vars entered in the sketch this way.


text:
How can I use delimiter/split serial input in a loop function?
How can I use delimiter/split serial input in a loop function? I want to use each word from the input and check a database, to check availability.
#include SoftwareSerial.h>
#define MAX_WORD_LENGTH 15

char messageArray[5][MAX_WORD_LENGTH + 1];
SoftwareSerial BT(10, 11);
String command = "";
char message[] = "";

void setup() {
  BT.begin(9600);
  Serial.begin(9600);
  while (BT.available()) {
    delay(10);
    char c = BT.read();
    command += c;
  }

  if (command.length() > 0) {
    Serial.println(command);
    char message[] = {command};
    for (int i = 0; i < 5; i++) {
      // you can 'reset' the array by writing a null to the first element of each
      messageArray[i][0] = '\0';
    }
    sscanf(message, "%s %s %s %s %s", messageArray[0], messageArray[1], messageArray[2], messageArray[3], messageArray[4]);
    for (int i = 0; i < 5; i++) {
      Serial.println(messageArray[i]);
      delay(1000);
    }
  }
}

void loop() {
  for (int i = 0; i < 5; i++) {
    // you can 'reset' the array by writing a null to the first element of each
    messageArray[i][0] = NULL;
  }
  command = "";
}

Exactly how would you like this to work? How does it work now? Any compiler warnings or errors?

You seem to have no clue about arrays on C. Maybe you should read some C array tutorials.

Also your understanding of serial communications is flawed.

You might like this new blog post of mine: https://hackingmajenkoblog.wordpress.com/2017/04/08/splitting-up-text-in-c/


text:
Error compiling: expected unqualified id before token {
#include <LiquidCrystal.h>
#define trigPin 12              // the trig pin to digital pin 12
#define echoPin 13              // the Echo pin to digital pin 13
#define led 8
#include <Servo.h>
Servo servoMain; // Define our Servo

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

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led, OUTPUT);
  Serial.begin(9600); // Starts the serial communication
  lcd.begin(16, 2);
  servoMain.attach(11); // servo on digital pin 11
}

void loop() {
  servoMain.write(5);  // Turn Servo Left to 5 degrees
  delay(1000); // Wait 1 second
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  if (distance < 3) {
    digitalWrite(led, HIGH);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("PLEASE REFILL!");
    lcd.setCursor(0, 1);
  } else {
    digitalWrite(led, LOW);
  }
  if (distance < 6) {
    digitalWrite(led, HIGH);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("U May Refill Now");
    lcd.setCursor(0, 1);
  } else {
    digitalWrite(led, LOW);
  }
  if (distance < 8) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Take it easy");
    lcd.setCursor(0, 1);
  }
  if (distance <= 16) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("FULL!!");
    lcd.setCursor(0, 1);
  }
  if (distance > 16 || distance <= 0) {
    Serial.println("Out of range");
  } else {
    Serial.print(distance);
    Serial.println(" cm");
  }
}
delay(1000);

}
    }

A big chunk of your code isn't contained in a function.

how do i fix that..i am new with arduino

By placing it in a function. I suspect you really wanted to have it inside the loop() function, not after it.

i dont understand...which part should be in the loop() function

i dont understand...which part should be in the loop() function

Everything that comes after the end of the loop function.

i just edited the question (the code) ...is that how we do it

I think you should learn a programming language first. I konw the Arduino IDE is nothing compared to VisualStudio, Xcode or all the other fancy IDEs but knowing your language and reading errors carefully will help.

You should also learn basic formatting rules, or at the very least use the autoformat button in the IDE. It saves many headaches getting your indenting right from the start.

can someone help me to fix the error... i need to have this code run by today

What does it do now you have edited it?

Pressing ctrl-T in Arduino IDE helps. As you can see after reformatting, your code is flawed. Fix that first.

i hv fix the error..but now how do i make the servo to only rotate for 2seconds

At line 82 you have the closing bracket of the loop function. Then after that you have:
  delay(1000);

}
}

Which is invalid.
If you format your code properly it's easy to see. Fix that and it will compile. Will it do what you want is an other question...
#include <LiquidCrystal.h>
#define trigPin 12        // the trig pin to digital pin 12
#define echoPin 13        // the Echo pin to digital pin 13
#define led 8
#include <Servo.h>
Servo servoMain; // Define our Servo

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

void setup()
{
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led, OUTPUT);
  Serial.begin(9600); // Starts the serial communication
  lcd.begin(16, 2);
  servoMain.attach(11); // servo on digital pin 11

}
void loop()
{
  servoMain.write(5); // Turn Servo Left to 5 degrees
  delay(1000);     // Wait 1 second

  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;

  if (distance < 3) {
    digitalWrite(led, HIGH);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("PLEASE REFILL!");
    lcd.setCursor(0, 1);
  }
  else {
    digitalWrite(led, LOW);
  }

  if (distance < 6) {
    digitalWrite(led, HIGH);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("U May Refill Now");
    lcd.setCursor(0, 1);
  }
  else {
    digitalWrite(led, LOW);
  }

  if (distance < 8) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Take it easy");
    lcd.setCursor(0, 1);
  }

  if (distance <= 16) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("FULL!!");
    lcd.setCursor(0, 1);
  }

  if (distance > 16 || distance <= 0) {
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
}
delay(1000);

}
}

I suspect that will always say FULL!! no matter the level.  Think about if distance is 2, that's less than 16 isn't it?  Maybe you need some else if action.


text:
Moving wiring.c functions from timer0 to timer1
I am using an Arduino Leonardo (ATmega32U4) and need to use timer0 for PWM. Since by default in the wiring.c file the functions micros() and millis() use timer0, I decided that, since timer1 isn't being used, I could set up timer1 exactly how timer0 is set up for the micros() and millis() functions and modify their code so that it all uses timer1 instead of timer0.
I think in theory this should work. I read the datasheet and timer1, while being a 16-bit timer, can run in an 8-bit fast PWM mode (which is what timer0 is set up for). So I modified wiring.c to do as above: adjusted the prescaler to match the original for timer0 (f/64) and put timer1 into fast-pwm 8-bit mode.
I modified all functions in wiring.c that used any register from timer0 and changed them to use the corresponding registers in timer1.
However, the problem is that it seems like I did everything right, but when I try to run a simple program that calls Serial.println("hello world"), it is messed up. The output instead shows a repeated 'h' character to the serial console. I'm not really sure what's wrong and wondering if anyone can help.
Here is my re-written wiring.c file that essentially moves all the functionalities from timer0 to timer1:
#include "wiring_private.h"

// the prescaler is set so that timer0 ticks every 64 clock cycles,
// and the overflow handler is called every 256 ticks.
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))
// the whole number of milliseconds per timer0 overflow
#define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000)
// the fractional number of milliseconds per timer0 overflow. we shift right
// by three to fit these numbers into a byte. (for the clock speeds we care
// about - 8 and 16 MHz - this doesn't lose precision.)
#define FRACT_INC ((MICROSECONDS_PER_TIMER0_OVERFLOW % 1000) >> 3)
#define FRACT_MAX (1000 >> 3)

volatile unsigned long timer0_overflow_count = 0;
volatile unsigned long timer0_millis = 0;
static unsigned char timer0_fract = 0;

#if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ISR(TIM0_OVF_vect)
#else
/*************************** Modified wiring.c TIMER1 ISR ***********************/
ISR(TIMER1_OVF_vect)
#endif
{
    // copy these to local variables so they can be stored in registers
    // (volatile variables must be read from memory on every access)
    unsigned long m = timer0_millis;
    unsigned char f = timer0_fract;

    m += MILLIS_INC;
    f += FRACT_INC;
    if (f >= FRACT_MAX) {
        f -= FRACT_MAX;
        m += 1;
    }
    timer0_fract = f;
    timer0_millis = m;
    timer0_overflow_count++;
}
/************************** End TIMER1 ISR **************************************/

unsigned long millis() {
    unsigned long m;
    uint8_t oldSREG = SREG;
    // disable interrupts while we read timer0_millis or we might get
    // an inconsistent value (e.g. in the middle of a write to timer0_millis)
    cli();
    m = timer0_millis;
    SREG = oldSREG;
    return m;
}

/************************ Modified micros() function ****************************/
unsigned long micros() {
    unsigned long m;
    uint8_t oldSREG = SREG, t;
    cli();
    m = timer0_overflow_count;
#if defined(TCNT1)
    t = TCNT1;
#else
    #error TIMER 1 not defined
#endif

#ifdef TIFR1
    if ((TIFR1 & _BV(TOV1)) && (t < 255))
        m++;
#else
    #error TIFR 1 not defined
#endif
    SREG = oldSREG;
    return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
}
/************************ End micros() ******************************************/

void delay(unsigned long ms) {
    uint32_t start = micros();
    while (ms > 0) {
        yield();
        while ( ms > 0 && (micros() - start) >= 1000) {
            ms--;
            start += 1000;
        }
    }
}

/* Delay for the given number of microseconds.  Assumes a 1, 8, 12, 16, 20 or 24 MHz clock. */
void delayMicroseconds(unsigned int us) {
    // call = 4 cycles + 2 to 4 cycles to init us(2 for constant delay, 4 for variable)
    // calling avrlib's delay_us() function with low values (e.g. 1 or
    // 2 microseconds) gives delays longer than desired.
    //delay_us(us);
#if F_CPU >= 24000000L
    // for the 24 MHz clock for the aventurous ones, trying to overclock
    // zero delay fix
    if (!us) return; //  = 3 cycles, (4 when true)
    // the following loop takes a 1/6 of a microsecond (4 cycles)
    // per iteration, so execute it six times for each microsecond of
    // delay requested.
    us *= 6; // x6 us, = 7 cycles

    // account for the time taken in the preceeding commands.
    // we just burned 22 (24) cycles above, remove 5, (5*4=20)
    // us is at least 6 so we can substract 5
    us -= 5; //=2 cycles

#elif F_CPU >= 20000000L
    // for the 20 MHz clock on rare Arduino boards
    // for a one-microsecond delay, simply return.  the overhead
    // of the function call takes 18 (20) cycles, which is 1us
    __asm__ __volatile__ (
        "nop" "\n\t"
        "nop" "\n\t"
        "nop" "\n\t"
        "nop"); //just waiting 4 cycles
    if (us <= 1) return; //  = 3 cycles, (4 when true)

    // the following loop takes a 1/5 of a microsecond (4 cycles)
    // per iteration, so execute it five times for each microsecond of
    // delay requested.
    us = (us << 2) + us; // x5 us, = 7 cycles

    // account for the time taken in the preceeding commands.
    // we just burned 26 (28) cycles above, remove 7, (7*4=28)
    // us is at least 10 so we can substract 7
    us -= 7; // 2 cycles

#elif F_CPU >= 16000000L
    // for the 16 MHz clock on most Arduino boards
    // for a one-microsecond delay, simply return.  the overhead
    // of the function call takes 14 (16) cycles, which is 1us
    if (us <= 1) return; //  = 3 cycles, (4 when true)
    // the following loop takes 1/4 of a microsecond (4 cycles)
    // per iteration, so execute it four times for each microsecond of
    // delay requested.
    us <<= 2; // x4 us, = 4 cycles

    // account for the time taken in the preceding commands.
    // we just burned 19 (21) cycles above, remove 5, (5*4=20)
    // us is at least 8 so we can subtract 5
    us -= 5; // = 2 cycles,
#elif F_CPU >= 12000000L
    // for the 12 MHz clock if somebody is working with USB

    // for a 1 microsecond delay, simply return.  the overhead
    // of the function call takes 14 (16) cycles, which is 1.5us
    if (us <= 1) return; //  = 3 cycles, (4 when true)

    // the following loop takes 1/3 of a microsecond (4 cycles)
    // per iteration, so execute it three times for each microsecond of
    // delay requested.
    us = (us << 1) + us; // x3 us, = 5 cycles

    // account for the time taken in the preceeding commands.
    // we just burned 20 (22) cycles above, remove 5, (5*4=20)
    // us is at least 6 so we can substract 5
    us -= 5; //2 cycles

#elif F_CPU >= 8000000L
    // for the 8 MHz internal clock

    // for a 1 and 2 microsecond delay, simply return.  the overhead
    // of the function call takes 14 (16) cycles, which is 2us
    if (us <= 2) return; //  = 3 cycles, (4 when true)

    // the following loop takes 1/2 of a microsecond (4 cycles)
    // per iteration, so execute it twice for each microsecond of
    // delay requested.
    us <<= 1; //x2 us, = 2 cycles

    // account for the time taken in the preceeding commands.
    // we just burned 17 (19) cycles above, remove 4, (4*4=16)
    // us is at least 6 so we can substract 4
    us -= 4; // = 2 cycles

#else
    // for the 1 MHz internal clock (default settings for common Atmega microcontrollers)

    // the overhead of the function calls is 14 (16) cycles
    if (us <= 16) return; //= 3 cycles, (4 when true)
    if (us <= 25) return; //= 3 cycles, (4 when true), (must be at least 25 if we want to substract 22)

    // compensate for the time taken by the preceeding and next commands (about 22 cycles)
    us -= 22; // = 2 cycles
    // the following loop takes 4 microseconds (4 cycles)
    // per iteration, so execute it us/4 times
    // us is at least 4, divided by 4 gives us 1 (no zero delay bug)
    us >>= 2; // us div 4, = 4 cycles
#endif
    // busy wait
    __asm__ __volatile__ (
        "1: sbiw %0,1" "\n\t" // 2 cycles
        "brne 1b" : "=w" (us) : "0" (us) // 2 cycles
    );
    // return = 4 cycles
}

void init() {
    // this needs to be called before setup() or some functions won't
    // work there
    sei();

    // on the ATmega168, timer 0 is also used for fast hardware pwm
    // (using phase-correct PWM would mean that timer 0 overflowed half as often
    // resulting in different millis() behavior on the ATmega8 and ATmega168)
#if defined(TCCR0A) && defined(WGM01)
    sbi(TCCR0A, WGM01);
    sbi(TCCR0A, WGM00);
#endif

    // set timer 0 prescale factor to 64
#if defined(__AVR_ATmega128__)
    // CPU specific: different values for the ATmega128
    sbi(TCCR0, CS02);
#elif defined(TCCR0) && defined(CS01) && defined(CS00)
    // this combination is for the standard atmega8
    sbi(TCCR0, CS01);
    sbi(TCCR0, CS00);
#elif defined(TCCR0B) && defined(CS01) && defined(CS00)
    // this combination is for the standard 168/328/1280/2560
    sbi(TCCR0B, CS01);
    sbi(TCCR0B, CS00);
#elif defined(TCCR0A) && defined(CS01) && defined(CS00)
    // this combination is for the __AVR_ATmega645__ series
    sbi(TCCR0A, CS01);
    sbi(TCCR0A, CS00);
#else
    #error Timer 0 prescale factor 64 not set correctly
#endif

    // enable timer 0 overflow interrupt
#if defined(TIMSK) && defined(TOIE0)
    sbi(TIMSK, TOIE0);
#elif defined(TIMSK0) && defined(TOIE0)
    sbi(TIMSK0, TOIE0);
#else
    #error  Timer 0 overflow interrupt not set correctly
#endif

    // timers 1 and 2 are used for phase-correct hardware pwm
    // this is better for motors as it ensures an even waveform
    // note, however, that fast pwm mode can achieve a frequency of up
    // 8 MHz (with a 16 MHz clock) at 50% duty cycle

/******************** Modified Code for Timer 1 *********************************/
#if defined(TCCR1B) && defined(CS11) && defined(WGM10)
    // set timer 1 prescale factor to 64
    sbi(TCCR1B, CS11);
    sbi(TCCR1B, CS10);

    // put timer 1 in 8-bit fast pwm mode
    sbi(TCCR1B, WGM12);
    sbi(TCCR1A, WGM10);

    // enable timer 1 overflow interrupt
    sbi(TIMSK1, TOIE1);
#endif
/********************* End Timer 1 **********************************************/

    // set timer 2 prescale factor to 64
#if defined(TCCR2) && defined(CS22)
    sbi(TCCR2, CS22);
#elif defined(TCCR2B) && defined(CS22)
    sbi(TCCR2B, CS22);
//#else
    // Timer 2 not finished (may not be present on this CPU)
#endif

    // configure timer 2 for phase correct pwm (8-bit)
#if defined(TCCR2) && defined(WGM20)
    sbi(TCCR2, WGM20);
#elif defined(TCCR2A) && defined(WGM20)
    sbi(TCCR2A, WGM20);
//#else
    // Timer 2 not finished (may not be present on this CPU)
#endif

/************** Modified Code for Timer 3 ***************************************/
#if defined(TCCR3B) && defined(CS31) && defined(WGM30)
    // set timer 3 prescale factor to 64
    sbi(TCCR3B, CS31);
    sbi(TCCR3B, CS30);

    // put timer 3 in 8-bit fast pwm mode
    sbi(TCCR3B, WGM32);
    sbi(TCCR3A, WGM30);

    // enable timer 3 overflow interrupt
    sbi(TIMSK3, TOIE3);
#endif
/************** End Timer 3 *****************************************************/

#if defined(TCCR4A) && defined(TCCR4B) && defined(TCCR4D) /* beginning of timer4 block for 32U4 and similar */
    sbi(TCCR4B, CS42);      // set timer4 prescale factor to 64
    sbi(TCCR4B, CS41);
    sbi(TCCR4B, CS40);
    sbi(TCCR4D, WGM40);     // put timer 4 in phase- and frequency-correct PWM mode
    sbi(TCCR4A, PWM4A);     // enable PWM mode for comparator OCR4A
    sbi(TCCR4C, PWM4D);     // enable PWM mode for comparator OCR4D
#else /* beginning of timer4 block for ATMEGA1280 and ATMEGA2560 */
#if defined(TCCR4B) && defined(CS41) && defined(WGM40)
    sbi(TCCR4B, CS41);      // set timer 4 prescale factor to 64
    sbi(TCCR4B, CS40);
    sbi(TCCR4A, WGM40);     // put timer 4 in 8-bit phase correct pwm mode
#endif
#endif /* end timer4 block for ATMEGA1280/2560 and similar */

#if defined(TCCR5B) && defined(CS51) && defined(WGM50)
    sbi(TCCR5B, CS51);      // set timer 5 prescale factor to 64
    sbi(TCCR5B, CS50);
    sbi(TCCR5A, WGM50);     // put timer 5 in 8-bit phase correct pwm mode
#endif

#if defined(ADCSRA)
    // set a2d prescaler so we are inside the desired 50-200 KHz range.
    #if F_CPU >= 16000000 // 16 MHz / 128 = 125 KHz
        sbi(ADCSRA, ADPS2);
        sbi(ADCSRA, ADPS1);
        sbi(ADCSRA, ADPS0);
    #elif F_CPU >= 8000000 // 8 MHz / 64 = 125 KHz
        sbi(ADCSRA, ADPS2);
        sbi(ADCSRA, ADPS1);
        cbi(ADCSRA, ADPS0);
    #elif F_CPU >= 4000000 // 4 MHz / 32 = 125 KHz
        sbi(ADCSRA, ADPS2);
        cbi(ADCSRA, ADPS1);
        sbi(ADCSRA, ADPS0);
    #elif F_CPU >= 2000000 // 2 MHz / 16 = 125 KHz
        sbi(ADCSRA, ADPS2);
        cbi(ADCSRA, ADPS1);
        cbi(ADCSRA, ADPS0);
    #elif F_CPU >= 1000000 // 1 MHz / 8 = 125 KHz
        cbi(ADCSRA, ADPS2);
        sbi(ADCSRA, ADPS1);
        sbi(ADCSRA, ADPS0);
    #else // 128 kHz / 2 = 64 KHz -> This is the closest you can get, the prescaler is 2
        cbi(ADCSRA, ADPS2);
        cbi(ADCSRA, ADPS1);
        sbi(ADCSRA, ADPS0);
    #endif
    // enable a2d conversions
    sbi(ADCSRA, ADEN);
#endif

    // the bootloader connects pins 0 and 1 to the USART; disconnect them
    // here so they can be used as normal digital i/o; they will be
    // reconnected in Serial.begin()
#if defined(UCSRB)
    UCSRB = 0;
#elif defined(UCSR0B)
    UCSR0B = 0;
#endif
}

I am not sure I understand why you want to switch from timer0 to timer1, then use timer0 for PWM. Why not keep wiring.c as is and use just timer0 for PWM?

You wrote: “sbi(TIMSK3, TOIE3);  // enable timer 3 overflow interrupt”. Did you implement ISR(TIMER3_OVF_vect) somewhere in your program?

Just for the record, I posted this question before I made an account by mistake, so that is why I cannot select best answer; BUT, I found the solution for anyone wondering.
I had the interrupt enabled for more than one timer (forgot to disable interrupts on the timer0 code). Once, i did that the code worked! I was able to move the millis, micros, delay, and delayMicros functions to the 16-bit timer 1!

My suggestion would be to keep the Arduino code as is and write your own micro() and millis() utilizing timer1.
It should be fairly simple.

Although I am not sure this would completely make all your changes correct, I see a potential issue in one existing line of code, that may be bad due to using a 16bits timer instead of 8bits:
unsigned long micros() {
    unsigned long m;
    uint8_t oldSREG = SREG, t;

    cli();
    m = timer0_overflow_count;
#if defined(TCNT1)
    t = TCNT1;
#else
    #error TIMER 1 not defined
#endif

#ifdef TIFR1
    if ((TIFR1 & _BV(TOV1)) && (t < 255))
        m++;
#else
    #error TIFR 1 not defined
#endif

    SREG = oldSREG;

    return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
}

Here, t is declared as uint8_t and initialized with TCNT1, which is a uint16_t (actually it is a reference to a volatile uint16_t), that may be an issue here.
I'd suggest replacing the line
t = TCNT1

with
t = TCNT1L

where TCNT1L is now a reference to volatile uint8_t accessing the low byte of TCNT1.