text:
Switch Statement stuck in loop
I am writing a code for a user to enter a 4 digit pin, then use this pin later to unlock a box. The loop is stuck between the "ready to unlock box" and "enter pin" it just keeps flipping between values but i want both to be displayed, just at different times.

#include <Keypad.h> //install keypad library
#include <LiquidCrystal.h> //install LCD screen library

const byte ROWS = 4; //include four rows of keypad
const byte COLS = 4; //indclude four cols of keypad

char keys[ROWS][COLS] = { //set keypad array equal to numbers on keypad
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};

int pin1, pin2, pin3, pin4, pin5, pin6, pin7, pin8;
int code[] = {pin1, pin2, pin3, pin4};

byte rowPins[ROWS] = {45,43,41,39}; //connect to the row pins of keypad
byte colPins[COLS] = {37,35,33,31}; //connent to the column pins of keypad

LiquidCrystal lcd(7, 8, 9, 10, 11, 12); //set up pins lcd will be connected to
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS ); //set keypad up to use as variable

int solenoidPin = 1; //connect motor pin to code

bool in_press = false;
void setup() {
   Serial.begin(9600); //start code
   lcd.begin(16,2); //start screen with dimensions
}

void loop() //loop of functions to run through
{
  int key; //initialize key as integer

  lcd.setCursor(0,0);
  lcd.print("Press # to lock,");//welcome screen
  lcd.setCursor(0,1);
  lcd.print("or * to unlock.");

  key = keypad.getKey(); //let arduino know it is waiting for a value

    while (in_press && key == NO_KEY) //check if they want to begin
    {
      in_press = false; //if no key was clicked
      return; //exit the loop and restart
    }

    while (key != NO_KEY){ //if a key was clicked
      switch(key){
      case '#':
        lcd.clear();
        lcd.setCursor(0,0);
        *lcd.print("Ready to lock"); //let user know ready for next step of process
        lcd.setCursor(0,1);
        lcd.print("keys!");
        delay(1000);
        EnterPin1();
        break;*

      case '*':
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Ready to unlock"); //let user know ready for next step of process
        lcd.setCursor(0,1);
        lcd.print("keys!");
        delay(1000);
        EnterPin5();
        break;

       default:
       lcd.clear();
       lcd.setCursor(0,0);
       lcd.print("No input");
       lcd.setCursor(0,1);
       lcd.print("detected.");
       break;
  }
 }
}

void EnterPin1()
{
  Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
  bool in_press = false;
  int pin1;

  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Enter your pin.");//let user know you are waiting for input
  delay(1000);

  pin1 = keypad.getKey(); //let arduino know it is waiting for a value

    while (in_press && pin1 == NO_KEY) //check if they want to begin
    {
      in_press = false; //if no key was clicked
      return; //exit the loop and restart
    }

    while (pin1 != NO_KEY) //if a key was clicked
    {
      switch(pin1){
      case '1':
        pin1 = 1;
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("*"); //let user know ready for next step of process
        EnterPin2(); //go to enter pin function
        break;

      case'2':
        pin1 = 2;
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("*"); //let user know ready for next step of process
        delay(1000);
        EnterPin2();
        break;

      case '3':
        pin1 = 3;
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("*");
        EnterPin2();
        break;

      case '4':
        pin1 = 4;
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("*");
        EnterPin2();
        break;

      case '5':
        pin1 = 5;
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("*");
        EnterPin2();
        break;

      case '6':
        pin1 = 6;
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("*");
        EnterPin2();
        break;

      case '7':
        pin1 = 7;
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("*");
        EnterPin2();
        break;

      case '8':
        pin1 = 8;
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("*");
        EnterPin2();
        break;

      case '9':
        pin1 = 9;
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("*");
        EnterPin2();
        break;
   }
  }
 }

The logic may be incorrect.  Also try to make a https://en.wikipedia.org/wiki/Finite-state_machine which may avoid needing to define multiple functions EnterPin1, EnterPin2 3 etc.

Your primary loop code sets key, and then has a while (key != nokey) {} loop after, but the value of key never changes inside the while loop. Thus, if key is not equal to noKey, the while loop will never exit.
key = keypad.getKey();

while (key != noKey) {
  //code that does not change key
}

That is an endless loop. The fact that there’s a switch statement inside the while loop is immaterial. None of that code changes the value of key, so the loop will never exit.
Write it like this instead:
EDIT
key = keypad.getKey();
while (key != noKey) {
  //Your current code
  key = keypad.getKey();
}

You have the same logic problem in your enterPin1 function. You don’t provide the code for your enterPin2 function, but I would guess it also has the same logic problem.

That gives me error "expected ')' before ';' token", is there another part i should add in there?

Ok, I wasn’t sure if that syntax was legal or not. Apparently not. I’m at a tablet where I don’t have access to a C compiler. You could use your code, but add a final  key = kaypad.getKey() as the last statement in your while loop to fetch another value for key before looping back again.

See the edit to my answer. There’s a more elegant way to do this but I don’t have access to a compiler at the moment to get it right for you.


text:
1st LED turn ON when 1st button is pressed and other LEDs remaining OFF
I have 2 LEDs and 2 buttons. What I want to code is when first button pressed the 1st LED turn on (stay on for 5 seconds) and 2nd LED remain off, and same if 2nd button pressed the 2nd LED turn on and 1st LED remain off. I want the processing reset after 5 seconds.
Here is my work, what it does now is 1st LED turn on when I press 1st button, but the 2nd button and 2nd LED still can press and light up right after. I want the 2nd button deactivate when 1st button pressed for 5 seconds.
Please give me basic program because I am new to this.
int pinButton_1 = 8; //the pin where we connect the button
int pinButton_2 = 9;
int LED_1 = 1; //the pin we connect the LED
int LED_2 = 2;
void setup() {
  pinMode(pinButton_1, INPUT); //set the button pin as INPUT
  pinMode(pinButton_2, INPUT);
  pinMode(LED_1, OUTPUT); //set the LED pin as OUTPUT
  pinMode(LED_2, OUTPUT);
}

void loop() {
  int stateButton_1 = digitalRead(pinButton_1); //read the state of the button
  int stateButton_2 = digitalRead(pinButton_2); //read the state of the button
  if(stateButton_1 == 1) { //if is pressed
     digitalWrite(LED_1, HIGH); //LED_1 on
     digitalWrite(LED_2, LOW); //LED_2 off
     delay(50);
  }
     if (stateButton_2 == 1) {
      digitalWrite(LED_1, LOW);
      digitalWrite(LED_2, HIGH);
      delay(50);
     }
  }

First of all you have not implemented a stay on time of 5seconds delay(5000); but only 50ms delay(50);.
Second, you are not really switching of your LED's if no further button is pressed.
Change your loop() to the following, I guess this will help you to start your next steps into getting familiar with your code:
    void loop() {
      int stateButton_1 = digitalRead(pinButton_1); //read the state of the Button_1
      if(stateButton_1 == 1) {      //if Button_1 is pressed
         digitalWrite(LED_1, HIGH); //LED_1 on
         digitalWrite(LED_2, LOW);  //LED_2 off
         delay(5000);
      }
      digitalWrite(LED_1, LOW); //Switch off LED_1

      int stateButton_2 = digitalRead(pinButton_2); //read the state of the button 2
      if (stateButton_2 == 1) {
         digitalWrite(LED_1, LOW);
         digitalWrite(LED_2, HIGH);
         delay(5000);
      }
      digitalWrite(LED_2, LOW); //Switch off LED_2
    }

Hint: Using delay() is often not a good construct, better to do it with millis(), but this means some more changes. For the start in your case delay() will do, but check out what here in different Questions/answers is already written about delay() vs. millis()

thank you for your help, I really appreciated

source: Stack Exchange

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

sort: votes


text:
http.POST is not sending data to local web page
I am using a nodeMCU to send data to my local web page developed using Spring boot but when I run the code I don't get an error the esp8266 connects to WiFi but I don't get anything on my spring boot app or any responses.
Here is the rest controller used from spring boot

@RestController
@RequestMapping("/getallcadres")
public class cadreController {
    @Autowired
    cadreRepository cadre;

@PostMapping("/getnbpassage")
    public String getnbrpassage(@RequestBody String nb){
        System.out.println("nombre de passage = "+nb);
        return "received";

    }
}

and the Arduino code
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>

void setup() {

  Serial.begin(9600);//Serial connection
  WiFi.disconnect();
  WiFi.begin("Iphone de elaa", "27343550");   //WiFi connection

  while (WiFi.status() != WL_CONNECTED) {  //Wait for the WiFI connection completion

    delay(500);
    Serial.println("Waiting for connection");

  }
  Serial.println("Wifi is connected");
  Serial.println(WiFi.localIP());

}

void loop() {

 if(WiFi.status()== WL_CONNECTED){   //Check WiFi connection status
 Serial.println("here we start");
   HTTPClient http;    //Declare object of class HTTPClient

   http.begin("http://localhost:8080/getallcadres/getnbpassage");      //Specify request destination
   http.addHeader("Content-Type", "text/plain");  //Specify content-type header

   int httpCode = http.POST("5");   //Send the request
   String payload = http.getString();//Get the response payload

   Serial.println("return code"+httpCode);   //Print HTTP return code
   Serial.println(payload);    //Print request response payload

   http.end();  //Close connection

 }else{

    Serial.println("Error in WiFi connection");

 }

  delay(30000);  //Send a request every 30 seconds

}

I am using Arduino IDE 1.6.5 here is what I get

Your URL has localhost as the host name. That cannot work. localhost means “self”, the computer initiating the request. In this case it would mean the ESP8266, if it even understood it. You need to use the name or the IP address of the computer running your spring boot app, not localhost.

thank you that worked for me

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


text:
Trying to use Tap Detection solution using ADXL345 with Arduino
I am using ADXL345 sensor connecting with Arduino via I2C interface, I am able to test the data at tri-axial axis but as there are some other features also, which I am going to try with Tap detection method as I didn't use TAP THRESH register and instead of that I am using the registers (in decimal) of Tap latency - 33, Tap Duration - 34, Tap Window - 35.
For which I just started with raw code,
#include <Wire.h>

// ADXL345 I2C address is 0x53(83)
#define Addr 0x53

void setup()
{
  // Initialise I2C communication as MASTER
  Wire.begin();
  // Initialise serial communication, set baud rate = 9600
  Serial.begin(9600);

  // Start I2C Transmission
  Wire.beginTransmission(Addr);
  // Select bandwidth rate register
  Wire.write(0x2C);
  // Normal mode, Output data rate = 100 Hz
  Wire.write(0x0A);
  // Stop I2C transmission
  Wire.endTransmission();

  // Start I2C Transmission
  Wire.beginTransmission(Addr);
  // Select power control register
  Wire.write(0x2D);
  // Auto-sleep disable
  Wire.write(0x08);
  // Stop I2C transmission
  Wire.endTransmission();

  // Start I2C Transmission
  Wire.beginTransmission(Addr);
  // Select data format register
  Wire.write(0x31);
  // Self test disabled, 4-wire interface, Full resolution, Range = +/-2g
  Wire.write(0x08);
  // Stop I2C transmission
  Wire.endTransmission();
  delay(300);
 }

 void loop()
 {
   unsigned int data[3];
   for(int i = 0; i < 3; i++)
   {
    // Start I2C Transmission
    Wire.beginTransmission(Addr);
    // Select data register
    Wire.write((33 + i));
    // Stop I2C transmission
    Wire.endTransmission();

    // Request 1 byte of data
    Wire.requestFrom(Addr, 1);

    //Read Three Bytes
    if(Wire.available() == 1)
    {
      data[i] = Wire.read();
    }
 }
   int TAP_DUR = data[1];
   int TAP_LAT = data[2];
   int TAP_WIN = data[3];

   Serial.print("TAP DURATION: ");
   Serial.println(TAP_DUR);
   Serial.print("TAP Latency: ");
   Serial.println(TAP_LAT);
   Serial.print("Tap Window : ");
   Serial.println(TAP_WIN);
   delay(3000);
   }

which is not working properly, and giving the result like this
TAP DURATION: 0
TAP Latency: 0
Tap Window : 22272
TAP DURATION: 0
TAP Latency: 0
Tap Window : 22272
TAP DURATION: 0
TAP Latency: 0
Tap Window : 22272

The main aim is to test the no of tap count and duration between single tap and double tap rather than using any library I need to work with the code I have been making.
Suggestion and bits of advice to make it work will be welcome.

the arrays are indexed from 0 but you assign to TAP_ variables array values indexed 1,2,3.
Are you sure the sensor is wired ok? Did it work with a library example?


text:
Arduino yes! and after?
I am new to electronics and am currently working with an Arduino UNO. I know the basics of PCB manufacturing (Besides, I'm fiddling with mine, very basic of course) Anytime I'm curious about how to get from Arduino to a finished PCB with the same result only on my Arduino prototype?
For example, my project has several components such as leds, An RFID module, a TFT LCD Shield 3.5 ", another 240x320 OLED screen ... How to put all this on a printed circuit board?
Do I need to solder the same components to my PCB?
-Do I need to run my Arduino code on my PCB once it is assembled?
-.......................................

put it all in a box

No, I want my own PCB without Arduino inside! Arduino just serves me for prototyping and see how it all works. I just wanted to know about my program for example my RFID module on an Arduino and then I want to wear it on my PCB how to do it without Arduino is integrated into the device I want to create!

A printed PCB can be used to place your components on (typically resistors, ICs, capacitors etc).
However, if you want to connect an LCD or big components, it would be a waste of space for your PCB. So in that case, I guess the best way is to create an enclosure where your displays fit in (and your RFID module if it is big too), and create some kind of connector from the PCB (e.g. using a terminal block or other way) and connect it to your displays.
On your PCB also an Arduino needs to be added, I guess the best solution is to use the Arduino chip (AtMega328P probably), and some external circuitry needed. Optionally using an IC socket in case you want to change the program later on.
On some Arduinos you can take out the AtMega328 DIP28 IC from your Arduino Uno board. Program it, than place it in the socket on your PCB board.
Update
Maybe you can use an Arduino Micro or Nano and place that directly onto your PCB (with headers preferably). Than you get something like below:

is there any way to make my own 100% PCB without component but that works exactly like my prototype on Arduino?

What do you mean without component? Without components like resistors/capacitors/etc? Or without an AtMega IC? For the first, I doubt, for the second, that depends if you can convert your software code into hardware components; if your code is using a library or has some formulas or using a communication protocol, it will be very hard. There are very many transistors in your AtMega and you don't want to copy those with separate components... What is the problem using an AtMega on your PCB?

Did you think about using e.g. an Arduino Nano or Micro instead? Than you can place one of those directly on your PCB (with a socket preferably).

I have no problem inserting an AtMega chip on my PCB it's just that I thought I could program my own microcontroller! I do not think the PCBs we have (those of our old electronic devices do not have arduino micro or nano inside). So I told myself that I could program everything myself but my concern is that it will work as well as my prototype or I will have things changed!

I doubt it will be easy to make your own microcontroller .... if you post your sketch someone can check if it is feasible.

Ok thank for all!

" Optionally using an IC socket in case you want to change the program later on."
No need, put an FTDI header on for serial programming, or put an ICSP header on and use a Programmer to program via the SPI pins.
Making your own PCB is very straightforward. I use EAGLE CAD software and design boards all the time. To duplicate a Promini for example, one only needs a '328P, 16 MHz xtal, two 22pF caps, 4 0.1uF caps, and a 10K resistor.  Then the 2 headers for convenient bootloading and/or programming.  Bootload and program it just like it was an Uno.

Thanks for this very good alternative, upvoted.


text:
X and Y axis on Arduino Serial Plotter?
I am trying to plot my counter vs. time on the serial plotter, but the values on the y axis are so big there is no way that it's displaying the counter values.
I have printed both values:
  Serial.print("counter: ");
  Serial.println(counter);
  time = millis();
  Serial.print("Time: ");
  Serial.println(time);

I expected time to show up in the x-axis, but I think it's displaying on the y-axis and I'm not sure how to change this.
The plot should just be an increasing line as the counter and time get bigger...
what am I missing?
Thanks.
Slashing out the Serial.print("Time:") does not correct anything.

Inorder to plot multiple variables or waveforms simultaneously a 'space' is printed between the two print statements.
Serial.print(counter);
Serial.print(" ");
time = millis();
Serial.println(time);

OR
Serial.print(counter);
Serial.print("\t");
time = millis();
Serial.println(time);

The X-axis is fixed and nothing gets plotted on the X-axis. It has its own divisions and they are automatically set by the Arduino IDE. The Arduino IDE still has to do some improvements to its software so that the X- axis can be adjusted and plotted too! This is my experience so far and corrections are welcome!

Comment out the Serial.print("Time: "); line. The Arduino serial plotter wants only numbers.

To plot multiple values over time you need to output just the numbers on a single line per iteration, and delimit with a space or tab:
Serial.print(counter);
Serial.print("\t"); // delimit with tab
time = millis();
Serial.print(time);
Serial.println();

It's worth noting however, the time (x axis) is implied by each line. In essence each line of output advances "time" by 1 unit. So I suspect you'll want to remove the time variable output and just output the count variable by it self.

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


text:
Unsigned long overflow? Or something else?
I have been looking at this for hours and can't figure it out... Take the following code I ran on an Arduino Mega:
#define MINUTES 0
#define SECONDS 1
#define MILLIS  2
#define DEFAULT_SELECTED_TURN_DELAY 0, 45, 0

unsigned long calculate_ms(int , int , int );

int selected_turn_delay[3] = { DEFAULT_SELECTED_TURN_DELAY };

void setup() {
  Serial.begin(115200);
  delay(1000);
  Serial.println("Values of selected_turn_delay:");
  Serial.print("minutes: ");
  Serial.println(selected_turn_delay[MINUTES]);
  Serial.print("seconds: ");
  Serial.println(selected_turn_delay[SECONDS]);
  Serial.print("milliseconds: ");
  Serial.println(selected_turn_delay[MILLIS]);

  unsigned long result = calculate_ms(selected_turn_delay[MINUTES], selected_turn_delay[SECONDS], selected_turn_delay[MILLIS]);
  unsigned long result1 = calculate_ms(selected_turn_delay[MINUTES], selected_turn_delay[SECONDS], selected_turn_delay[MILLIS]);
  unsigned long result2 = calculate_ms(0,45,0);
  unsigned long result3 = calculate_ms(0,30,0);
  unsigned long result4 = calculate_ms(0,31,0);
  unsigned long result5 = calculate_ms(0,32,0);
  unsigned long result6 = calculate_ms(0,33,0);
  unsigned long result7 = calculate_ms(0,34,0);
}

void loop() {
}

unsigned long calculate_ms(int minutes, int seconds, int milliseconds) {
  Serial.println("------------");
  Serial.println("In calculate_ms");
  Serial.println("------------");
  unsigned long calculated_total_milliseconds = 0;
  unsigned long minute_to_seconds = 0;
  unsigned long seconds_to_ms = 0;

  Serial.println("Input:");
  Serial.print("minutes: ");
  Serial.println(minutes);
  Serial.print("seconds: ");
  Serial.println(seconds);
  Serial.print("milliseconds: ");
  Serial.println(milliseconds);

  calculated_total_milliseconds = (milliseconds + (seconds * 1000) + ((minutes * 60) * 1000));

  Serial.print("Calculates ms:");
  Serial.println(calculated_total_milliseconds);
  return(calculated_total_milliseconds);
}

It gives me the following results:
Values of selected_turn_delay:
minutes: 0
seconds: 45
milliseconds: 0
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 45
milliseconds: 0
Calculates ms:4294946760
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 45
milliseconds: 0
Calculates ms:4294946760
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 45
milliseconds: 0
Calculates ms:4294946760
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 30
milliseconds: 0
Calculates ms:30000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 31
milliseconds: 0
Calculates ms:31000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 32
milliseconds: 0
Calculates ms:32000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 33
milliseconds: 0
Calculates ms:4294934760
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 34
milliseconds: 0
Calculates ms:4294935760

What am I missing why is the calculation for values above 32s out of wack ?
Tried the same code adapted for gcc:
#include <stdio.h>

#define MINUTES 0
#define SECONDS 1
#define MILLIS  2
#define DEFAULT_SELECTED_TURN_DELAY 0, 45, 0

unsigned long calculate_ms(int , int , int );

int selected_turn_delay[3] = { DEFAULT_SELECTED_TURN_DELAY };

int main(void) {
  printf("Values of selected_turn_delay:\n");
  printf("minutes: ");
  printf("%d\n",selected_turn_delay[MINUTES]);
  printf("seconds: ");
  printf("%d\n",selected_turn_delay[SECONDS]);
  printf("milliseconds: ");
  printf("%d\n",selected_turn_delay[MILLIS]);

  unsigned long result = calculate_ms(selected_turn_delay[MINUTES], selected_turn_delay[SECONDS], selected_turn_delay[MILLIS]);
  unsigned long result1 = calculate_ms(selected_turn_delay[MINUTES], selected_turn_delay[SECONDS], selected_turn_delay[MILLIS]);
  unsigned long result2 = calculate_ms(0,45,0);
  unsigned long result3 = calculate_ms(0,30,0);
  unsigned long result4 = calculate_ms(0,31,0);
  unsigned long result5 = calculate_ms(0,32,0);
  unsigned long result6 = calculate_ms(0,33,0);
  unsigned long result7 = calculate_ms(0,34,0);
}

unsigned long calculate_ms(int minutes, int seconds, int milliseconds) {
  printf("------------\n");
  printf("In calculate_ms\n");
  printf("------------\n");
  unsigned long calculated_total_milliseconds = 0;
  unsigned long minute_to_seconds = 0;
  unsigned long seconds_to_ms = 0;

  printf("Input:\n");
  printf("minutes: ");
  printf("%d\n",minutes);
  printf("seconds: ");
  printf("%d\n",seconds);
  printf("milliseconds: ");
  printf("%d\n",milliseconds);

  calculated_total_milliseconds = (milliseconds + (seconds * 1000) + ((minutes * 60) * 1000));

  printf("Calculates ms:");
  printf("%lu\n",calculated_total_milliseconds);
  return(calculated_total_milliseconds);
}

And it works great:
Values of selected_turn_delay:
minutes: 0
seconds: 45
milliseconds: 0
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 45
milliseconds: 0
Calculates ms:45000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 45
milliseconds: 0
Calculates ms:45000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 45
milliseconds: 0
Calculates ms:45000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 30
milliseconds: 0
Calculates ms:30000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 31
milliseconds: 0
Calculates ms:31000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 32
milliseconds: 0
Calculates ms:32000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 33
milliseconds: 0
Calculates ms:33000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 34
milliseconds: 0
Calculates ms:34000

It has to be something obvious, but I can't find it...

Ok well, 'before bed illumination'...
Changing:
calculated_total_milliseconds = (milliseconds + (seconds * 1000) + ((minutes * 60) * 1000));

for
calculated_total_milliseconds = (milliseconds + (seconds * 1000UL) + ((minutes * 60) * 1000UL));

Make it work:
Values of selected_turn_delay:
minutes: 0
seconds: 45
milliseconds: 0
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 45
milliseconds: 0
Calculates ms:45000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 45
milliseconds: 0
Calculates ms:45000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 45
milliseconds: 0
Calculates ms:45000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 30
milliseconds: 0
Calculates ms:30000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 31
milliseconds: 0
Calculates ms:31000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 32
milliseconds: 0
Calculates ms:32000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 33
milliseconds: 0
Calculates ms:33000
------------
In calculate_ms
------------
Input:
minutes: 0
seconds: 34
milliseconds: 0
Calculates ms:34000

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


text:
Controlling TFT LCD with Arduino
I bought this LCD module. How many pins does this LCD module uses? They have written in the product description that this LCD module uses 8 bit communication, but the LCD module has 16 bit pinout (DB0-DB15). What is the right pin number?
Is there any Arduino LCD library that supports this LCD module, which uses the OTM4001A LCD driver? Usually for LCD the UTFT library works, but it does not support the OTM4001A LCD driver.
Thanks for your help!

Trust what is on the board, not what the eBay seller says. They invariably can't tell the difference between a TFT screen and a doll, and they sell everything in between. They just regurgitate Chinglish nonsense. If the board says DB0-DB15 then DB0-DB15 is what you need to use.
Plus it says in the description:

Support 16 bit RGB565 format , can connect any 16 bit data bus.

At least this one has told you what the driver chip is (OTM4001A) - many times they can't even do that and don't even understand what you are asking when you request that information.
Mind, it's a driver chip I have never come across before, so maybe I should get one on order to support it in DisplayCore...


text:
Barebones Arduino Zero with ATSAMD21G18
I have been using the ATmega328P TQFP32 chip for quite a while and I would like to try something new. I came across the ATSAMD21G18 used by Arduino Zero and M0. However, there aren't any information online regarding how to develop a standalone, very basic setup of it.
Previously, I have used...

ATmega328P TQFP32
For the crystal: 16Mhz and 22pF caps
For bootloading: 10 11 12 13 for Arduino ISP
For uploading programs: TX and RX of an Arduino Uno with its chip removed.

For the ATSAMD21G18, I am also looking for a similar setup. I checked out the Sparkfun Mini breakout schematics, but I am not good at reading them and there seems to be a lot of components just for protection and to make it more stable, which I don't need as you can probably know from the setup I used for the 328.
https://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/sparkfun-samd21-mini-breakout-v10.pdf
What are the basic required components for it to work properly?
For bootloading, am I required to use the Atmel Ice? If so, what are the pins and components needed for burning the Arduino Zero bootloader?
For uploading a program, am I required to use the USB functionality built in? How can I use it (components pins and connections)? Can I use Arduino ISP using an Arduino Zero?
Finally, what should I bear in mind when switching from an ATmega328P to an ATSAMD21G18?
Thanks in advance!

Datasheet says?

Google Samd21 xplained pro. It's got a similar chip but with more features. It also has an on board debugger/programmer.

This seems to be the simples form of the Arduino M0 I could find.
From this tutorial site
The ICE programmmer makes it very easy to program and all you need is the SWD pins to program the bootloader.
ISP is for AVR chips where as with ARM chips like SAMD21 you will need to use JTAG/SWD to program it.
I am also try to make a home brew Zero but I am getting stuck after the bootloader where the board just does not want to expose a Serial port.


text:
Arduino Nano 3.0 and Arduino Uno Benchmarks
What are the benchmarks (MIPS) of an Arduino Uno (ATmega32P) and Arduino Nano 3.0 (Atmega328) @ 1.6MHz?

ATmega16U4/ATmega32U4, ATmega48A/PA/88A/PA/168A/PA/328/P, ATmega2560, and numerous other Atmel AVR 8-Bit microcontrollers have an instruction set typically with “135 Powerful Instructions – Most Single Clock Cycle Execution” per datasheets.
That is, many of the AVR instructions, including almost all of the logic and arithmetic instructions, execute in 1 cycle.  A fair number of memory access instructions take 2 cycles.  A few instructions (eg JMP) take 3 cycles, and some (RCALL, CALL, RET, RETI, et al) take 4 or 5 cycles.  Others (eg SBRC) take 1, 2, or 3 cycles, depending on operand values and whether a branch occurs that disrupts the pipeline, which is shallow.  For an overview, see the instruction set summary in any AVR-part datasheet. For details, see Atmel's AVR Instruction Set Manual, doc0856 at atmel.com.
Overall, the average instructions per second in a typical compiled C program probably is between 1.5 and 2, so a 16 MHz system might do 8 to 11 MIPS on average, while carefully tailored do-nothing code can easily achieve 16 MIPS.

Do you mean 16MzHz?
Benchmarks are here.

I checked the page out, but It did not answer my questions. I want to know how many instructions per second (IPS) can the microcontrollers preocess  at their 16MHz clock speed.


text:
Implementing AT commands with Arduino and ESP8266
Being a newbie to Arduino, I'm trying to implement AT commands in the serial monitor, though in vain. After connecting the ESP8266 (01) module to an Arduino Uno, I tried to scan for the nearest network present [code link: https://github.com/esp8266/Arduino/blob/master/doc/esp8266wifi/scan-examples.md#simple-scan] and it worked perfectly.
But the moment I am trying to connect to send AT commands (even manually), it shows nothing. In addition, if(Serial.available()) and if(esp8266.available())< both are giving false value.
What am I doing wrong?

Show your code, since maybe the problem lies with Softserial + native serial

You don't give a circuit diagram or very much detail about what you've done, but if I guess correctly...
You have flashed the code in your link to the ESP-01 (perhaps using the Arduino as a serial port adapter). That code is now running on the ESP itself - it's not running on the Arduino and controlling the ESP.
Flashing the ESP erases the stock firmware, so the ESP can no longer respond to AT commands.
I don't know of a way to reprogram the 'AT' firmware into the ESP but perhaps Google will help.
If I've guessed incorrectly, please explain exactly what you have done - with circuit diagram, setup steps and code.

This is exactly what has happened. I reprogram the 'AT' firmware into the ESP then AT was working perfectly. The moment I tried to access ESP programmatically [sendData("AT+CWMODE=2\r\n",1000,DEBUG)] it again showed the same problem. I think Program Address Offset [Hex] value for firmware and my *.ino are same. I am trying another range with no result. Can you tell me how to change the Program Offset for Aurduino [0x000000]. Any able comment is solicited.

If my answer answers your original question, please feel free to accept it, and optionally up-vote it. That will encourage people to answer further questions. If you have a new question, please read http://stackoverflow.com/help/how-to-ask and ask a new question.

created a new thread, please assist there as well. [ref: http://arduino.stackexchange.com/questions/32899/esp8266-firmware-update-problem]

Anyone who is new to using ESP8266 module should consider following before interfacing it with Arduino

Try connecting ESP Module directly with your computer and test out all the AT Commands you will be implementing with Arduino. This approach is better because (a) this will give you confidence that your communication works perfectly (b) you will figure out all the problems that people face when sending AT commands and receive reply (c) this is a more visual approach so you will know what is going on and where you are going wrong.
Use Computer based communication tools and make a simple power adaptor to solve communication and wiring problems once and for all.

authors: الكترونيات صفوان


text:
Wait for serial input otherwise start with preconfigured options
I need to input config parameters from serial input. After a period (1 min) with no input I would like the program to start with preconfigured parameters.
Currently in the loop() section I use Serial.available, which stops until it receives new data.
How can I implement that?
void loop() {
  // read serial input
  if (Serial.available() > 0) {
    inChar = (char)Serial.read();
    inputString += inChar;

The Serial.available function does NOT block execution. If you want to try, upload this
unsigned long lastTime;
#define LED1 5
#define LED2 13

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

void loop() {
  if (Serial.available() > 0)
  {
    Serial.read();
    digitalWrite(LED1, !digitalRead(LED1));
  }
  if ((millis() - lastTime) > 500)
  {
    lastTime = millis();
    digitalWrite(LED2, !digitalRead(LED2));
  }
}

You will see led on pin 13 to turn on and off even if the serial port buffer is empty.
Maybe your problem is somewhere else. Anyway what you want can be solved this way:
void setup()
{
    Serial.begin(9600);

    // Wait for one minute - millis is started at 0, so there's no
    // need to store the initial value of the waiting time
    boolean receivedConfiguration = false;
    while ((!receivedConfiguration) && (millis() < 60000))
    {
        if (Serial.available() > 0)
        {
            // There's some data; parse it

            if (__receivedDataIsComplete)
            {
                __myConfiguration = __configurationFromSerial;

                receivedConfiguration = true;
            }
        }
    }
    if (!receivedConfiguration)
    {
        __myConfiguration = __defaultConfiguration;
    }
}

In this setup function, the microcontroller waits for one minute. If it receives the data it ends the waiting time and uses that configuration, otherwise restores the default one and goes on. In your loop you can then use the configuration.
Please note that the variables starting with a double underscore (__) are false variables, you will have to fill with the proper code and/or variables


text:
Serial clock for SPI
I'm trying to configure my ADC(LM98725) registers through Arduino UNO via SPI but I'm facing a small problem, it would be great if somebody help me out. I have to configure my 16 bit ADC registers which needs 25+ clocks but right now I'm getting 16 SCLK with my 16 bit data output on MOSI pin, there is no SCLK signal without data output. How can I increase the number of SCLK for my ADC?
To write to the serial registers, the timing diagram shown in a diagram. First, SEN is toggled low. The LM98725 assumes control of the SDO pin during the first eight clocks of the command. During this period, data is clocked out of the device at the rising edge of SCLK. At the rising edge of ninth clock,the LM98725 releases control of the SDO pin. At the falling edge of the ninth clock period, the master should assume control of the SDI pin and begin issuing the new command. SDI is clocked into the LM98725 at the rising edge of SCLK. The remaining bits are composed of the "write" command bit (a zero), two device addressbits (00, 01 or 10 for the LM98725), five bit register address to be written, and the eight bit register value to be written.
#include <SPI.h>

int ss=10;
int DATAOUT=11;
int DATAIN=12;
int SCLK=13;

void setup()
{
    SPI.begin();
    pinMode(DATAOUT, OUTPUT);
    pinMode(DATAIN, INPUT);
    pinMode(SCLK, OUTPUT);
    pinMode(ss, OUTPUT);
    digitalWrite(ss, HIGH);
    SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE0));
}

void loop()
{
    digitalWrite(ss, LOW);
    SPI.transfer16(0x02c6);
    digitalWrite(ss, HIGH);
}

Did you try a dummy write? Can you show us your code?

Its a simple code I just want to send 16 bit data to my ADC but I only have 16 SCLK pulses and I need 25 pulses.

You are transferring only 16 bits. You should transfer at least 25, or rather 32 since it must be a multiple of 8.

on the first 8 clocks my ADC sends data on MISO pin and then it starts receiving data from the 10th clock. If I sends 32 bit data the first 9 bits would be dummy and then my 16bits for the register configuration and then again the last 7 bits have to be dummy. That's what you are saying?

No. According to the graph, all the dummy bits (bits marked "x") should be sent before the register configuration.

Yeah but how? As its written in the description that  from the rising edge of ninth clock,the LM98725 releases control of the SDO pin and at the falling edge of the ninth clock period, the master should assume control of the SDI pin and begin issuing the new command. SDI is clocked into the LM98725 at the rising edge of SCLK.

So according to this it will start taking bits from the 10th clock for writing register that's what I understand.


text:
Altering code to run a timer while checking for a data input
I am rather new to the Arduino world and am looking for a way to create my own tipping rain gauge with only one Arduino(micro).
I have had some help from a friend to get a loop that checks for when a switch is closed, which signals that the bucket has tipped and thus "x units" of rain have fallen. The code I have for sensing this is:
void loop()
{
  /*
    digitalWrite(4, HIGH);
    delay(500);
    digitalWrite(4, LOW);
    delay(6500);
  */
  int analogValue = digitalRead(8);

  if (analogValue==HIGH)
  {
    Serial.println(count);
    count++;
    delay(250);
  }
}

Then I developed a code to count up in 0.5 second intervals so that I could essentially time stamp when the switch from the first loop was closed/activated. The code for the timer is as follows:
void loop()
{
  while (ssec < 10)
  {
    Serial.print(hour);
    Serial.print(":");
    Serial.print(minute);
    Serial.print(":");
    Serial.print(sec);
    Serial.print(".");
    Serial.print(ssec);
    //Serial.print(" s");
    //Serial.println();
    ssec += 5;
    delay(500);
    Serial.println();
  }
  if (ssec == 10);
  {
    sec++;
    ssec = 0;
    //Serial.print(sec);
    //Serial.print(".");
    //Serial.print(ssec);
  }
  if (sec == 60)
  {
    minute++;
    sec = 0;
  }
  if (minute == 60)
  {
    hour++;
    minute = 0;
  }
  if (hour == 24)
  {
    Serial.println();
    Serial.print("DAY ");
    Serial.print(day);
    Serial.print(" COMPLETED!");
    Serial.print("Data Points: ");
    //Serial.print(count);
    Serial.println();
    Serial.println();
    hour = 0;
    day++;
  }
}

I understand that it is very hard to run these together at the same time due to the fact that I am using a delay function to run the timer.
Are there any ways to essentially run these side by side? Or a library I can use that will run the timer while i have the arduino looking for the switch to close, and I can simply call the timer when I need it?
Thank you for any and all help! :)

What's with the double-spacing? It makes it hard to read.
if(ssec==10);

That is wrong.
Arduino programming traps, tips and style guide

I understand that it is very hard to run these together at the same time due to the fact that I am using a delay function to run the timer.

I know StackExchange doesn't like link-only answers, but it is this or copy-and-paste:
How to do multiple things at once ... like cook bacon and eggs

I couldn't understand how to format the code and it was just coming up as a big chunk of text, so i just spaced it out.

This site does explain how to do that (and I edited it for you). Basically you select the code and click on the "code" button which indents it all 4 spaces. The indentation is what is needed, not lots of new lines.

If you do not need to know the timing when the event occurs with a high resolution, and do not have anything else you need to do, you can simply delay in short intervals and check the condition in between them.  Of course you will not know when the event occurred more precisely than knowing it happened sometime in the interval since the previous check.
Another approach is to not use the delay mechanism, but rather continually check the input in a loop, and also check the elapsed time so that you can accomplish your periodic events when intervals of time have elapsed.  Do be aware of the millis() overflow eventuality if taking this approach.
If you had important work to do while waiting, you could accomplish the check with a pin change interrupt, and record a timestamp in the interrupt service routine, but if all you would be doing in the foreground is running a delay, this is inferior to the previous approach.  Using an interrupt service routine (or any more elaborate form of threading) also requires care to ensure consistency of data shared between the main and interrupt or alternate thread context.
Ultimately the best solution for an actual real-world embedded application like this is typical to try to have the processor in a low powered sleep mode most of the time.  Typically you would have a low power real time clock running, but the processor's high speed clock and associated logic stopped.  Your tilt sensor would be wired as an interrupt that the MCU is configured to wake up to normal operation in response to.  On wakeup, it would read the clock to accomplish a timestamp, then go back to sleep.  You can also use various mechanisms in the real time clock or in the MCU to wake up periodically to announce the passing of time intervals.  Wakeup on a small MCU is typically a fairly efficient process - it can be beneficial in terms of net power consumption to go (at least partially) to sleep even for a fraction of a second.

Just in case the OP goes looking for it, there is no RTC on 8-bit AVRs (UNO, Mega2560 et al) nor the Arduino 101.  There is an RTC on the 32-bit SAM-based boards (Due et al).

Yes, you can run the two loop() function side-by-side with a Multi-tasking Scheduler.
Please see https://github.com/mikaelpatel/Arduino-Scheduler. There are plenty of examples to get you started but basically you call Scheduler.start() with loop() functions. You will have to give them different names.
The Scheduler will context switch between the loop() functions on yield() or delay().
Cheers!

You can find some 3rd party library that does software emulation of threads.
For example: ArduinoThread.
With the use of such library I successfully developed an app that was switching LEDs on and off and at the same time listened to any data coming from Bluetooth (serial port). It is worth a try.

No, this is really not a problem that calls for threads.  Jumping right to that for a problem of this simplicity is skipping over some of the key basics of embedded development, and not something that should be encouraged.


text:
POST data from Arduino to website
I am working on a project where I am trying to send data using HTTP and POST method from my Arduino Mega2560 to a website which I host on localhost. I am living to a students' accommodation and thus, I do not have access to the router. However, I have bought a router and have connected it to the wall via the WAN. Also, the Arduino is connected to one of the ethernet plugs of the router via an Ethernet shield and my laptop to another ethernet plug. I am trying to retrieve the data from the website, but I cannot seem to load them.
Arduino Code
#include <dht.h>
#include <SPI.h>
#include <Ethernet.h>

dht DHT1;
int temperatureSensorPin1 = 25;

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
EthernetClient client;
EthernetServer server(80);

long previousMillis = 0;
unsigned long currentMillis = 0;
long interval = 250000;
String data;

long lastUpdate = 0;

void setup() {

  Serial.begin(9600);
  if(Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
  }

  data = "";

  pinMode(temperatureSensorPin1, INPUT);
}

void loop() {

int temp1 = DHT1.read11(temperatureSensorPin1);

switch (temp1)
  {
    case DHTLIB_OK:
        Serial.print("OK,\t");
        break;
    case DHTLIB_ERROR_CHECKSUM:
        Serial.print("Checksum error,\t");
        break;
    case DHTLIB_ERROR_TIMEOUT:
        Serial.print("Time out error,\t");
        break;
    case DHTLIB_ERROR_CONNECT:
        Serial.print("Connect error,\t");
        break;
    case DHTLIB_ERROR_ACK_L:
        Serial.print("Ack Low error,\t");
        break;
    case DHTLIB_ERROR_ACK_H:
        Serial.print("Ack High error,\t");
        break;
    default:
        Serial.print("Unknown error,\t");
        break;
  }

  currentMillis = millis();
  if(currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;
  }
  String data="temp1="+String(DHT1.temperature, 0)+"&temp2="+String(DHT2.temperature, 0)+"&temp3="+String(DHT3.temperature, 0)+"&temp4="+String(DHT4.temperature, 0)+"&temp5="+String(DHT5.temperature, 0)
                  +"&hum1="+String(DHT1.humidity, 0)+"&hum2="+String(DHT2.humidity, 0)+"&hum3="+String(DHT3.humidity, 0)+"&hum4="+String(DHT4.humidity, 0)+"&hum5="+String(DHT5.humidity, 0)+"&gas="+gasValue;

  Serial.println(Ethernet.localIP());
  if(client.connect("192.168.0.1", 80)) {
    client.println("POST /home/visualisation.php HTTP/1.1");
    client.println("Host:  192.168.0.1");
    //client.println("User-Agent: Arduino/1.0");
    //client.println("Connection: close");
    client.println("Content-Type: application/x-www-form-urlencoded;");
    client.print("Content-Length: ");
    client.println(data.length());
    client.println();
    client.print(data);
    //Serial.println(data);
    Serial.println("We have connection");
  }

  if(client.connected()) {
    Serial.println("We have abc");
    client.stop();
  }

  delay(4000);
}

PHP Code
<?php
$temp1 = "";
if(isset($_POST['temp1'])) {
    $temp1 = $_POST['temp1'];
}
echo $temp1;
?>

Windows ip configuration
[Router ip configuration][2]
Is the connection that I have made the appropriate one? How should I do it in order to work?
P.S.: I would like to clarify that I do not have an extended knowledge regarding networking.
Router ip configuration
LAN
MAC Address: 60-E3-27-E7-70-7A
IP Address: 192.168.0.1
Subnet Mask: 255.255.255.0
Wireless
Wireless Radio: Enable
Name (SSID): TP-LINK_707A
Mode: 11bgn mixed
Channel Width: Automatic
Channel: Auto (Current channel 3)
MAC Address: 60-E3-27-E7-70-7A
WDS Status: Disable
WAN
MAC Address: 60-E3-27-E7-70-7B
IP Address: 100.66.166.2    Dynamic IP
Subnet Mask: 255.255.255.192
Default Gateway: 100.66.166.1
DNS Server: 77.244.128.44 , 77.244.128.45

Since the php script isn't doing anything you can detect it might already be working. Could you post the serial output of the Arduino? Can you check the access log of the web server you are running on your PC?

It is working! I had to make a PHP script to store the values to a database. One change that I needed to do is to make the Arduino send the values to 192.168.0.100

If you have found a solution to your question, then please answer the question and accept it.

Great to hear. Best of luck.

The ip that I have Arduino send data to is the router's and thus, I should have used the 192.168.0.100 ip which is the one of my computer.
I also needed to save the value to a database to notice the changes because echo $temp1; did not seem to work, probably I should have it included into HTML label tags. Anyway, I just loaded the value from the database into a PHP variable and I was able to accomplish the task.


text:
Perform function after a period of time
I am working on a project that I am supplying with voltage an LED through a digital pin (26) and I want the LED to be switched off after 4 seconds.
I am using Arduino Mega2560 and I am programming it using Arduino's IDE version 1.6.10. I have installed the SimpleTimer library .zip method but it does not seem to function.
Code
#include <SimpleTimer.h>

SimpleTimer timer;

void setup() {
pinMode(26, OUTPUT);
digitalWrite(26, HIGH);

timerId = timer.setTimeout(4000, switchOff);
}

void switchOff() {
  digitalWrite(26, LOW);
}

void loop() {
}

The problem is that the LED stays just on (digitalWrite(26, HIGH);) instead of going to the switchOff function and turning off (digitalWrite(26, LOW);). I have also tried using Timer1 and Timer libraries but they also do not work. Can someone who has made any of the libraries work, provide me with some guidance?

You have to call timer.run() inside loop function.

It worked! Answer the question and I will choose your answer as the best one.

You have to call timer.run() inside loop function.
The SimpleTimer library is more like a scheduler. You call at every so often, and it checks if there is any event that has expired.


text:
No power_usi_disable() on Arduino Uno
we have an error after compiling the code in arduinouno that is displayed as
error: 'power_usi_disable' was not declared in this scope   in Board: "Arduino/Genuino Uno".how to rectify this error. please reply us fast

The Arduino Uno does not have a USI peripheral. Thus, you cannot disable
the power of the (non-existent) USI, and there is no
power_usi_disable() function.
Solution: remove the call to power_usi_disable() from your code.
Update: To answer your new question in the comment, WDTCR is the
Watchdog Timer Control Register on some AVR chips. On the Uno it is
called WDTCSR, because it is a control and status register.
Looks to me like you have downloaded from somewhere a program you do not
understand. That program was written for an ATtiny chip and you are
trying to compile it as-is for an Arduino Uno, which is based on an
(incompatible) ATmega328P. That's not the way to do it: you have to
understand the program and rewrite all the ATtiny specific stuff to fit
the Uno.

Thank you ,but we have an other error exit status 1
'WDTCR' was not declared in this scope. plz help us

Check the board selection in the Arduino IDE Tools menu. Also please post source code and compiler warnings/errors.

@ppsrc: Se amended answer.


text:
using string to display text on serial monitor
After using int to display text in serial monitor, now i am trying to use string but there is something wrong.
The expected reslut is "Led1 is on" in serial monitor but what i get is "285".
This is the code involving strings.
String(ledPin1="Led1 is on");
Serial.println(ledPin1);

while this is the full code
int numledPin1Blinks=5;
int ledPin1Blinks=2;
int i;
int j;
int waiTtimeoff2=1000;
int waitTimeOn2=1000;
int ledPin2=10;
int ledPin1=13;
int waiTtimeOn1=1000;
int waiTtimeOff1=1000;
void setup()
{pinMode(10,OUTPUT);
pinMode(13,OUTPUT);
Serial.begin(9600);
String(ledPin1="Led1 is on");

}

void loop()
{Serial.println(ledPin1);
for (i=1;i<=3;i=i+1){
Serial.print("   You are on blink
no#:  ");
Serial.println(i);
digitalWrite(ledPin1,HIGH);
delay(waiTtimeOn1);
digitalWrite(ledPin1,LOW);
delay(waiTtimeOff1);}
Serial.println(" ");

Serial.println("Led 2 is on!");
for (j=1;j<=4;j=j+1){
Serial.print(" You are on blink no
#:");
Serial.println(j);
digitalWrite (ledPin2,HIGH);
delay(waitTimeOn2);
digitalWrite (ledPin2,LOW);
delay(waiTtimeoff2);}
Serial.println(" ");

}

What do you think that code is supposed to do?

Display ' led 1 is blinking ' in serial monitor.

Why would it do that? ledPin1 is just a number and can never be anything else. It's an int. All you are doing is assigning the address of a static string to it, turning that number also into a String, and then throwing that string away.

As an aside: don't try and learn how to use String in the first place. It will lead you down a dark and dismal path that will end in unstable code and tears before bedtime. Don't taint your knowledge with them.  Start straight off with C strings (NULL-terminated character arrays).

I am learning aurdino from a website ( toptechboy) . The instructor did the same thing as he introduced the concept of string but I'm unable to perform it

I just perused that site (lesson 5 is it?) There's nothing like that there. The closest is: String redMessage="The Red LED is Blinking"; which is nothing like you have.

Yes I think it's lesson 5. I am not copying his code as I want to learn to code that's why my code seems to be different but it has the same structure as on the website

Please stop answering and use comments instead.

Maybe you should start with his code and modify it instead of trying to run before you can walk.

Sorry for not using comments.

For this case(string) ,  I even copied his code but the problem still persists.

note: your code is very poorly formatted ... that makes it difficult to read and to spot errors .... proper code formatting should be one of the first things that you learn .... it will help you a lot in the future .... note: your code has errors that prevent it from compiling

Your syntax is incorrect. You are assigning the address of a static string literal to an integer, then using the results of that assignment (the address of the string literal, as it "falls through" to the left) to create a new String object. That String object is then being thrown away.
You need to create a new String variable (not re-use one that you actively use for another part of your program) and assign a string literal to it:
String led1Message = "LED 1 is on";

Then you can print that variable instead:
Serial.println(led1Message);

HOWEVER String objects are very very fragile on the Arduino and should be avoided. Forget trying to learn to use them, since you will only have to un-learn them at a later date.  Skip them and start straight away with C-strings (NULL-terminated char arrays).  Also learn about PROGMEM.
For instance, the above could be written as:
const char led1Message[] PROGMEM = "LED 1 is on";

And then use a casting to get println to grab it from flash:
Serial.println((__FlashStringHelper*)led1Message);

This uses pretty much zero RAM, which on an Arduino is very important. Even more important it doesn't cause heap fragmentation which can cause your program to crash randomly.

Thank you very much,  I had no idea about demerits of using strings. I'll just try using const char instead.

Can print/println really differentiate between in memory const char and flash one? The F macro was using reinterpret cast into FlashStringHelper pointer so function overloading can be used.

Actually, I'm not sure: I never actively use Arduino... ;)  You may want to cast it to (__FlashStringHelper*).


text:
lcd.clear doesn't work with Serial.begin(9600) on Arduino Mega 2560
So I have a standard 16x2 LCD display with 16 pins. The LCD display works fine with every other aspect, however, the "lcd.clear" function doesn't work with "Serial.begin(ANY BAUD)". I have tried changing bauds and downgrading the board software but it still doesn't work.
Basically, instead of clearing the display like it should do, it displays a weird character with 4 horizontal lines (in one character space) and then continues to write stuff after it.
Here is my code:

#include <LiquidCrystal.h>
LiquidCrystal lcd(1, 2, 4, 5, 6, 7);

void setup() {
 pinMode(8, INPUT);
 lcd.begin(16,2);
 Serial.begin(9600);
}

void loop() {
 lcd.print("incorrect");
 delay(3000);
 lcd.clear();
 delay(100);
}

Whenever I delete the Serial.begin everything works fine, but when I add it the clear function doesn't work anymore.
So in this case, what happens is that the Arduino prints "incorrect", then instead of clearing the display, it prints out four horizontal lines, and then continues to print out "incorrect" infinitely.

You seem to use UART pins to connect your LCD.

Pins 0 and 1 are the hardware serial pins on the Mega.  If you're going to use Serial, then you can't connect your LCD to those pins or it won't work.  Even if you are only connected to Serial through the USB, pins 0 and 1 are still acting as Tx and Rx.

Right thank you so much!

Can you please mark the answer as accepted.

Buddy you are using those pins which are used for communication purpose that is pin No. 0 and 1 is for RXD and TXD


text:
How to read distance of passing object?
Ok, guys this is my first post and I am new to Arduino but somewhat familiar with programming so I hope you guys can assist me. If any of this is confusing, I apologize in advance! :)
I want to be able to utilize a TOF sensor that will be stationary to capture the distance of a passing object at a certain moment after it is first detected, because it is round. So I wanted to use a photoelectric switch, so when the object would pass, it would send the signal to the TOF sensor to read the distance 17ms after that moment.(I've done the math, and the delay to be in the center(closest edge to the sensor of solid ball) of the object passing would take 17ms) Then I would like to have that distance be displayed onto a LCD screen, until the next object passes and the process repeats....Think of a conveyor belt with a basketball on it. The basketball would be moving and pass the sensor, but the distance to the center(closest edge to the sensor)of the ball would be measured at a certain moment and displayed until the next ball passes.
The next problem is that the distance needs to be converted to a "zone" So like between 10-12cm, it would = 2. 12.1-14 would be 3 etc... The last part is probably the easiest but, I have no idea where to start...I appreciate all who helps!
I was needing help with the code to make this work with the Arduino uno. The tof sensor is VL53L1X and E-931-S35RRQ photoelectric sensor. And the LCD will be a 7 segment display so as long as it’s programmed for that I can change out sizes later..

@velocitygraphix - I've removed the "financial reward" part of your question because the Stack Exchange community frowns on monetary bounties for questions: https://meta.stackoverflow.com/questions/316137/what-to-do-when-op-offers-payment-for-solution

Yes all the balls are the same size. I’m not trying to find the size of the ball, only the distance to each one as it passes and then display it. Thanks!

Distance to the middle of the ball?...I’m not sure how you would word to say the middle of the ball..(halfway on the surface of the circumference?)...it’s a solid ball so the time of flight sensor would need to measure the closest edge of the ball-on the surface...

Not sure what you mean by closest approach but I want it measured to the part of the ball that is closest to the sensor which will fall halfway from front to back when passing. Picture if you pointed your finger out horizontally at a height exactly half the diameter of the ball...your finger is the sensor. Now if a ball rolls by and grazes your finger, that is the closest edge to the finger (sensor) that should be measured...

The ball part may be confusing you, as the shape doesn’t matter as long as the sensor takes a distance reading 17ms after the beam is broken...as long as the sensor takes a reading at that exact time, it’ll automatically be measuring to the correct part of the object.

i understand now ... you do not have it in your mind clearly ... as a result, your post is just a mess of irrelevant information ... all you want is for the TOF sensor to take a distance reading 17ms after a trigger signal ... you only need one sentence to ask that, not several paragraphs

Well sort of. I wanted to explain in detail. It also needs to hold the reading on a display until the next object passes...as well as convert the distance to “zones”...

Is there any specific question about this project? And do you already have the TOF sensor? Or at least have chosen one?

The sensor has a 50Hz ranging frequency; depending on the speed of the balls passing the measuring section, you may only need to wait for ranges of less than (whatever passes for inifinity in your setup) and then track the ranges until they hit a minimum, save that value, and there's your first answer. This saves a detector and has the additional virtue of being independent of the speed of the traveling ball (up to a resolution limited by the sensor's measuring frequency & your precision requirements).
The second part just needs a few ifs, such as:
if( range < 10.0 ){
  zone = 1;   // or whatever else you need to do here
}
else if( range < 12.0 ){
  zone = 2;
}
else {
  zone = 3;   // anywhere else
}

So break this into parts and solve each part separately. First, figure out how to interface the photoelectric sensor. First just write a loop() that waits for the state change when the sensor trips.
To get accurate timing you'll probably want to respond to the photoelectric sensor with an interrupt service routine that starts a timer. Get that working next.
Then figure out how to interface with your ToF sensor. When I googled it I found the bare sensor as well as versions on PC boards with an I2C interface. You may be able to find somebody's library that interfaces with the sensor. Get that working so you can take readings from the TOF sensor.
Then figure out how to drive the 7-segment display. Just write code that displays the values from 0-9 for 1 second each using a delay.
Once you've got all the pieces working separately, it's time to map out the logic if your program and make it work. Take a look at the "arduino blink without delay" example for how to write code that handles timed responses without using the delay() function.


text:
Clock cycle count count for the same command is not equal in ESP32
I am using ESP32 Pico Kit with Arduino Ide. I want to measure operation cycle for a few commands.
The code is so simple as below:

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

void loop() {
  unsigned long count = 10000;
  unsigned long i = 0;
  unsigned long _start;
  unsigned long _end;
  _start = ESP.getCycleCount();
  while(i < count)
  {
    i++;
  }
  _end = ESP.getCycleCount();
  Serial.println(_end - _start);
}

When I run the code, the result is 13.
Then, I changed the counter variable to different values and ran it again (values: 10, 100, 1000, 10000, ...).
The result is always 13!
Why the execution cycle does not change and it seems that the code is compiled as just one loop and the loop count is not important?
Am I missing something?

I think the compiler sees what you are doing, and just replace the while loop with i=count. The compiler tries to optimize your code.

try using the volatile keyword in the i variable declaration  ....  volatile unsigned long i = 0;

Not only does the compiler remove the loop, it also removed the variables i and count altogether. Or at least any decent optimizing compiler would do so.

Thank you all. I did it an it is working perfect. How should I mark it as answered?! :)


text:
If else statement not mutually exclusive?
When I'm running some test on my encoder motors using the following provided code by Makeblock, it appears that the if..else.. statement is not mutually exclusive ie. I can control Encoder_1 and Encoder_2 at the same time. How come?
case ENCODER_BOARD:
      if(port == 0)
      {
        uint8_t slot = readBuffer(7);
        int16_t speed_value = readShort(8);
        speed_value = -speed_value;`

        if(slot == SLOT_1)
        {
          Encoder_1.setTarPWM(speed_value);
        }
        else if(slot == SLOT_2)
        {
          Encoder_2.setTarPWM(speed_value);
        }
        else if(slot == SLOT_3)
        {
          Encoder_3.setTarPWM(speed_value);
        }
        else if(slot == SLOT_4)
        {
          Encoder_4.setTarPWM(speed_value);
        }
      }

int16_t readShort(int16_t idx)
{
  valShort.byteVal[0] = readBuffer(idx);
  valShort.byteVal[1] = readBuffer(idx+1);
  return valShort.shortVal;
}

uint8_t readBuffer(int16_t index)
{
  if(BluetoothSource == DATA_SERIAL)
  {
    return buffer[index];
  }
  else if(BluetoothSource == DATA_SERIAL2)
  {
    return bufferBt1[index];
  }
  else if(BluetoothSource == DATA_SERIAL3)
  {
    return bufferBt2[index];
  }
}

All the code are taken from here and I am not the owner. I myself still studying how these whole code works. I am hoping someone out there who have experience with these kind of implementations be able to help me out.

if and else if clauses are mutually exclusive. If the if is true then the else if cannot run.
Therefore it must be the case that the code you posted is being executed twice (at least) - once for SLOT_1 and once for SLOT_2.  Just so fast that you think it's happening at the same time.

Exactly one of the blocks in if{..} else {...} will be executed.  Your misunderstanding is elsewhere.

Yes they are mutually exclusive.
Note that the following construct is more appropriate:
switch (slot)
{
case SLOT_1:
     Encoder_1.setTarPWM(speed_value);
     break;

case SLOT_2:
     Encoder_2.setTarPWM(speed_value);
     break;

case SLOT_3:
     Encoder_3.setTarPWM(speed_value);
     break;

case SLOT_4:
     Encoder_4.setTarPWM(speed_value);
     break;

default: // other cases/error
     // Handle error situation
     break;
}

You can do the same with BluetoothSource.
Also you can do multiple commands within one case statement, like:
case SLOT_4:
     Encoder_4.setTarPWM(speed_value);
     Encoder_Extra.setTarPWM(speed_value);
     break;

Note that the switch/case only works where you compare one variable/expression.

am hoping someone out there who have experience with these kind of implementations be able to help me out.

Match out the brackets (to your logic) and the issue will be clear.
Your inadvertently created a duffs machine

I see no Duff’s device in his snippets.


text:
Parsing serial port data
Hello I found an Arduino project that works with serial port parsing and it had very interesting parsing code. I am trying to use it in my project but I still don't understand some lines and what is going there. (I marked them with ???).
char inData[82]; //create 82 char array
byte index = 0; //index byte (0 - 255)
String string_convert; //String
int PCdata[20]; //int array

void setup() {
  Serial.begin(9600); //init port
}

void loop() {
  parsing(); //loop the function
}

void parsing() {
  while (Serial.available() > 0) {
    //while there is data in serial buffer (128 bytes)
    char aChar = Serial.read(); //aChar - current symbol in buffer
    if (aChar != 'E') {
      //if aChar isnt the 'E' (End) symbol do:
      inData[index] = aChar;
      //(inData - array, index - loop № counter) write all Buffer to the array
      index++; //index + 1 - loop count
      inData[index] = '\0';
      //set the next position to '\0' or null symbol
    } else {
      //if aChar or current buffer symbol is 'E' (End) do:
      char *p = inData; //create inData address pointer
      char *str; //create pointer
      index = 0; //set counter to 0
      String value = ""; //create string
      while ((str = strtok_r(p, ";", &p)) != NULL) { //???
        string_convert = str; //???
        PCdata[index] = string_convert.toInt(); //???
        index++; //counter + 1 - loop count
      }
      index = 0; //counter to 0
    }
  }
}

Thank you for help!


text:
How do I have this audio and LED activate ONLY when a button is held using an Arduino?
I have this code that I am using to play a sound effect where I used a program called wav2c to convert a .wav file to number values that I put into a header file that I use in the code to generate the sound. I currently have it programmed to play the audio upon uploading it to the Arduino with an LED being activated along with it and staying lit for just the duration of the sound effect. I am trying to program it so that the sound and LED only activate when I am pressing a button. I have the pin the button is plugged into already programmed in but I'm not sure how to have it control the audio and LED as stated above. I don't have much experience with programming or Arduino so any help is much appreciated! I am using an Arduino Mega 2560.
The code

#include <stdint.h>
#include <avr/interrupt.h>
#include <avr/io.h>
#include <avr/pgmspace.h>

#define SAMPLE_RATE 20000
#include "Test.h"

int ledPin = 2;
int speakerPin = 9; // Can be either 3 or 11, two PWM outputs connected to Timer 2
const byte pinSwitch1 = 3;
volatile uint16_t sample;
byte lastSample;

void stopPlayback()
{
    digitalWrite(ledPin, LOW);
    // Disable playback per-sample interrupt.
    TIMSK1 &= ~_BV(OCIE1A);

    // Disable the per-sample timer completely.
    TCCR1B &= ~_BV(CS10);

    // Disable the PWM timer.
    TCCR2B &= ~_BV(CS10);

    digitalWrite(speakerPin, LOW);
}

// This is called at 8000 Hz to load the next sample.
ISR(TIMER1_COMPA_vect) {
    if (sample >= sounddata_length) {
        if (sample == sounddata_length + lastSample) {
            stopPlayback();
        }
        else {
            if(speakerPin==11){
                // Ramp down to zero to reduce the click at the end of playback.
                OCR2A = sounddata_length + lastSample - sample;
            } else {
                OCR2B = sounddata_length + lastSample - sample;
            }
        }
    }
    else {
        if(speakerPin==11){
            OCR2A = pgm_read_byte(&sounddata_data[sample]);
        } else {
            OCR2B = pgm_read_byte(&sounddata_data[sample]);
        }
    }

    ++sample;
}

void startPlayback()
{
    pinMode(speakerPin, OUTPUT);

    // Set up Timer 2 to do pulse width modulation on the speaker
    // pin.

    // Use internal clock (datasheet p.160)
    ASSR &= ~(_BV(EXCLK) | _BV(AS2));

    // Set fast PWM mode  (p.157)
    TCCR2A |= _BV(WGM21) | _BV(WGM20);
    TCCR2B &= ~_BV(WGM22);

    if(speakerPin==11){
        // Do non-inverting PWM on pin OC2A (p.155)
        // On the Arduino this is pin 11.
        TCCR2A = (TCCR2A | _BV(COM2A1)) & ~_BV(COM2A0);
        TCCR2A &= ~(_BV(COM2B1) | _BV(COM2B0));
        // No prescaler (p.158)
        TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

        // Set initial pulse width to the first sample.
        OCR2A = pgm_read_byte(&sounddata_data[0]);
    } else {
        // Do non-inverting PWM on pin OC2B (p.155)
        // On the Arduino this is pin 3.
        TCCR2A = (TCCR2A | _BV(COM2B1)) & ~_BV(COM2B0);
        TCCR2A &= ~(_BV(COM2A1) | _BV(COM2A0));
        // No prescaler (p.158)
        TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

        // Set initial pulse width to the first sample.
        OCR2B = pgm_read_byte(&sounddata_data[0]);
    }

    // Set up Timer 1 to send a sample every interrupt.

    cli();

    // Set CTC mode (Clear Timer on Compare Match) (p.133)
    // Have to set OCR1A *after*, otherwise it gets reset to 0!
    TCCR1B = (TCCR1B & ~_BV(WGM13)) | _BV(WGM12);
    TCCR1A = TCCR1A & ~(_BV(WGM11) | _BV(WGM10));

    // No prescaler (p.134)
    TCCR1B = (TCCR1B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

    // Set the compare register (OCR1A).
    // OCR1A is a 16-bit register, so we have to do this with
    // interrupts disabled to be safe.
    OCR1A = F_CPU / SAMPLE_RATE;    // 16e6 / 8000 = 2000

    // Enable interrupt when TCNT1 == OCR1A (p.136)
    TIMSK1 |= _BV(OCIE1A);

    lastSample = pgm_read_byte(&sounddata_data[sounddata_length-1]);
    sample = 0;
    sei();

}

void setup()
{
    pinMode( pinSwitch1, INPUT );
    pinMode(ledPin, OUTPUT);
    digitalWrite(ledPin, HIGH);
    startPlayback();
}

void loop()
{
    while (true);
}

The header file referenced in the code with the numeric values to create the audio.
#ifndef _HEADERFILE_H    // Put these two lines at the top of your file.
#define _HEADERFILE_H    // (Use a suitable name, usually based on the file name.)

const int sounddata_length=32000;
//const int sounddata_sampleRate=20000;

const unsigned char sounddata_data[] PROGMEM = {
  15,1,49,0,150,0,138,0,219,255,133,0,176,0,15,1,210,

//There are many lines of more numbers in between that I cut out to save space

};

#endif // _HEADERFILE_H    // Put this line at the end of your file.

remove startPlayback() from setup() ... place it in loop() so that it is called only when the switch is moved from released to pressed .... when the switch is moved from pressed to released then call stopPlayback()

I moved the 'startPlayback()' to setup() and added                                   //buttonState = digitalRead(pinSwitch1);
//while (buttonState == LOW) {
//stopPlayback();  }  And the same for stopPlayback, but it doesn't seem to be working, any suggestions?

read my first comment carefully ... the changes you made are not same as what i suggested

ok, I will reread. The audio does not play when I changed the location of 'startPlayback()' and the button doesn't affect anything.

also looks like you added comments, not code

don't forget that loop() repeats many times per second .... any code that runs when the button is in the released state (or in pressed state) will run at each iteration of loop() .... you want your code to run only once when there is a change in switch state

your best course of action is to test intermediate code ... in loop(), call startPlayback(), pause for 5 seconds, call stopPlayback(), pause for 5 seconds .... that will tell you if you can start and stop playback from within loop()

note: there is no reason to have while (true); inside loop() if it is empty ... loop() is while(true); already


text:
How can I adapt this code for the ATTiny85?
So I set up an Arduino circuit that while a button was pressed, a sound effect would play and an LED would activate until I stopped pressing the button. Since I didn't use a micro sd card module, I had to use wav2c to convert the audio to numeric values that I then used the code here to implement the audio. The numeric values for the audio were placed in a header file that was referenced in the code. The code and my circuit work but I want to see if I can use one of my new ATTiny85's to run the code and perform the same operations as the Arduino did. I have set up my Arduino Mega 2560 to program the ATTiny85. I have tested it with Blink and it works. However, after I had moved the pins of the speaker, LED, and button to those of the ATTin85 and edited the appropriate code, it will not upload to the ATTiny85. It gives error messages that certain variables have not been declared in this scope. One such is "TCCR1B" and when I comment it out, it claims another variable has not been declared in this scope. Any idea how I can overcome this and if it's even possible to use the ATTiny in this capacity?
The Code I tried uploading to the ATTiny85

#include <stdint.h>
#include <avr/interrupt.h>
#include <avr/io.h>
#include <avr/pgmspace.h>

#define SAMPLE_RATE 20000
#include "Test.h"

int ledPin = 0;
int speakerPin = 1; // Can be either 3 or 11, two PWM outputs connected to Timer 2
const byte pinSwitch1 = 2;
volatile uint16_t sample;
byte lastSample;
int buttonState = 0;
const byte interruptPin = 2;
volatile byte state = LOW;

void stopPlayback()
{
    digitalWrite(ledPin, LOW);
    // Disable playback per-sample interrupt.
    TIMSK1 &= ~_BV(OCIE1A);

    // Disable the per-sample timer completely.
    TCCR1B &= ~_BV(CS10);

    // Disable the PWM timer.
    TCCR2B &= ~_BV(CS10);

    digitalWrite(speakerPin, LOW);
}

// This is called at 8000 Hz to load the next sample.
ISR(TIMER1_COMPA_vect) {
    if (sample >= sounddata_length) {
        if (sample == sounddata_length + lastSample) {
            stopPlayback();
        }
        else {
            if(speakerPin==11){
                // Ramp down to zero to reduce the click at the end of playback.
                OCR2A = sounddata_length + lastSample - sample;
            } else {
                OCR2B = sounddata_length + lastSample - sample;
            }
        }
    }
    else {
        if(speakerPin==11){
            OCR2A = pgm_read_byte(&sounddata_data[sample]);
        } else {
            OCR2B = pgm_read_byte(&sounddata_data[sample]);
        }
    }

    ++sample;
}

void startPlayback()
{
    digitalWrite(ledPin, HIGH);
    pinMode(speakerPin, OUTPUT);

    // Set up Timer 2 to do pulse width modulation on the speaker
    // pin.

    // Use internal clock (datasheet p.160)
    ASSR &= ~(_BV(EXCLK) | _BV(AS2));

    // Set fast PWM mode  (p.157)
    TCCR2A |= _BV(WGM21) | _BV(WGM20);
    TCCR2B &= ~_BV(WGM22);

    if(speakerPin==11){
        // Do non-inverting PWM on pin OC2A (p.155)
        // On the Arduino this is pin 11.
        TCCR2A = (TCCR2A | _BV(COM2A1)) & ~_BV(COM2A0);
        TCCR2A &= ~(_BV(COM2B1) | _BV(COM2B0));
        // No prescaler (p.158)
        TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

        // Set initial pulse width to the first sample.
        OCR2A = pgm_read_byte(&sounddata_data[0]);
    } else {
        // Do non-inverting PWM on pin OC2B (p.155)
        // On the Arduino this is pin 3.
        TCCR2A = (TCCR2A | _BV(COM2B1)) & ~_BV(COM2B0);
        TCCR2A &= ~(_BV(COM2A1) | _BV(COM2A0));
        // No prescaler (p.158)
        TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

        // Set initial pulse width to the first sample.
        OCR2B = pgm_read_byte(&sounddata_data[0]);
    }

    // Set up Timer 1 to send a sample every interrupt.

    cli();

    // Set CTC mode (Clear Timer on Compare Match) (p.133)
    // Have to set OCR1A *after*, otherwise it gets reset to 0!
    TCCR1B = (TCCR1B & ~_BV(WGM13)) | _BV(WGM12);
    TCCR1A = TCCR1A & ~(_BV(WGM11) | _BV(WGM10));

    // No prescaler (p.134)
    TCCR1B = (TCCR1B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

    // Set the compare register (OCR1A).
    // OCR1A is a 16-bit register, so we have to do this with
    // interrupts disabled to be safe.
    OCR1A = F_CPU / SAMPLE_RATE;    // 16e6 / 8000 = 2000

    // Enable interrupt when TCNT1 == OCR1A (p.136)
    TIMSK1 |= _BV(OCIE1A);

    lastSample = pgm_read_byte(&sounddata_data[sounddata_length-1]);
    sample = 0;
    sei();
        //digitalWrite(ledPin, HIGH);
        //delay(1000);
        //digitalWrite(ledPin, LOW);
}

void setup()
{
    pinMode( pinSwitch1, INPUT );
    pinMode(ledPin, OUTPUT);
    pinMode(interruptPin, INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(interruptPin), stopPlayback, CHANGE);

}

void loop()
{
//startPlayback();
//delay(5000);
//stopPlayback();
buttonState = digitalRead(pinSwitch1);

stopPlayback();

if (buttonState == LOW) {
    startPlayback();
    delay(1150);

}

}

The header file with the audio
#ifndef _HEADERFILE_H    // Put these two lines at the top of your file.
#define _HEADERFILE_H    // (Use a suitable name, usually based on the file name.)

const int sounddata_length=32000;
//const int sounddata_sampleRate=20000;

const unsigned char sounddata_data[] PROGMEM = {
  15,1,49,0,150,0,138,0,219,255,133,0,176,0,15,1,210,

//There are a lot more numbers in here to generate the audio but I cut most out to save space

};

#endif // _HEADERFILE_H    // Put this line at the end of your file.

The ATTINY85 doesn't have the same set of timers as the board this was written for.    That looks like code for an UNO (ATMEGA328) or a Mega (ATMEGA2560).  The ATTINY85 doesn't have a corresponding timer to the 16 bit Timer1 on those chips.  You really can't use this on an 85.

As @delta_G pointed out, this code is written specifically to access the timer hardware on the chip, and the ATTINY85 has different timer hardware.
It would not be hard to change this code to work with your just need to output the next step in the list of audio values 8000 timer per second.
There are two ways you could do this...

You could figure out the corresponding settings for the ATTINY85 timer hardware and use those instead. The timer registers are documented in the ATTINY85 datasheets and you can google lots of info on how to set those registers, but it is complicated.
You can bit-bang the audio data out though a digital pin. Bing banging means you write code that manually sets the pin high or low at the appropriate times.

Since it does not look like you need to do anything else while the sound is playing, I think bit banging is the simpler approach here.
Do do bit banging, you get rid of the start and end playback functions and instal have a playSound() function that looks something like this...
void playSound() {
    pinMode(speakerPin, OUTPUT);  // This really belongs in setup()
    for(unsigned sample=0; sample<sounddata_length; sample++) {      // step though the audio samples
        sample_value=pgm_read_byte(&sounddata_data[sample])/2;    // grab next value from array in flash

        // Note that we divide the value by 2. This is because our target rate is
        // 8000 samples per second, which is 125us per sample. Each sample value is 0-255, so /2 gives us
        // a value 0-127. If we spend about 127us on each sample then we are in the right ballpark
        // for playback speed (ok, a bit slow).

        digitalWrite( speakerPin , 1);     // poor man's single cycle bitbang PWM
        _delay_us( sample_value );
        digitalWrite( speakerPin , 0);
        _delay_us( 127-sample_value );

     }

    }
}

This is just pseudo code and I have not checked to see if this even compiles, but you should get the idea.
This is also a hack, so it does not take into account how long the digitalWrite() takes
or the overhead of the loop. It also explicitly stretches the sample time from 125us to 127us for math simplicity and speed (dividing the 0-255 by 2 is very fast). All these will likely make the playback sound slow and low, but i'm not sure how much.
I also do not take into account that the playback can get interrupted which would cause audio glitches. You can fix this by putting cli()/sei() around the playSound() code.
Finally, each sample only gets a single PWM cycle so I don't expect audio to be CD quality, but maybe good enough. If you need more PWM cycles then there are ways to do this, but then probably better to use the hardware timer.
LMK if you can get this working (post a video!) or have any questions!


text:
Sending code for error detection facing problem with error not able to compile code
MY PROJECT CODE:

#include ESP8266WiFi.h
#include LiquidCrystal.h
#include FirebaseArduino.h>
#include HX711.h>
#define FIREBASE_HOST "iot-based-smart-dustbin.firebaseio.com"
#define FIREBASE_AUTH "ljIbV03K07rLwoHRKSaAxWzJNCb3Lh6buc76dkvb"
#define WIFI_SSID "AndroidAP"
#define WIFI_PASSWORD "ashu1234"
char c; //ESP
String data   = "";  //ESP
#define DOUT  15
#define CLK  13
#define IR1 14
#define IR2 12
HX711 scale(DOUT, CLK); // Init of library
float calibration_factor = -96650; //-106600 worked for 3-40Kg max scale setup
const int rs = 16, en = 5, d4 = 4, d5 = 0, d6 = 2, d7 = 10;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
void setup()
{
   Serial.begin(9600);
   pinMode(IR1,INPUT);
  pinMode(IR2, INPUT);
  pinMode(DOUT, INPUT);
  pinMode(CLK, OUTPUT);
  lcd.begin(16, 2);     // Print a message to the LCD.
  lcd.print("WELCOME");
  delay(2000);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
//  Serial.print("connecting");
  while (WiFi.status() != WL_CONNECTED)
    {
  //    Serial.print(".");
      delay(500);
    }
//  Serial.println();
//  Serial.print("connected: ");
//  Serial.println(WiFi.localIP());
  scale.set_scale();
  scale.tare(); //Reset the scale to
}
void loop()
{
  scale.set_scale(calibration_factor); //Adjust to this calibration factor
  float a=scale.get_units();   // a Variable to take weight values at input
  lcd.clear();
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.setFloat("Weight", a);  //to set value in firebase // value on a sent to weight variable
  if (digitalRead(IR1)==HIGH)
  {
    Firebase.setFloat("IR1", HIGH);
    lcd.setCursor(0, 0);
    lcd.print("Location 1:High");
  }
   if (digitalRead(IR1)==LOW)
  {
    Firebase.setFloat("IR1", LOW);
    lcd.setCursor(0, 0);   //column, Row
    lcd.print("Location 1: Low");
  }
   if (digitalRead(IR2)==HIGH)
  {
    Firebase.setFloat("IR2", HIGH);
    lcd.setCursor(0, 1);
    lcd.print("Location 2:High");
  }
   if (digitalRead(IR2)==LOW)
  {
    Firebase.setFloat("IR2", LOW);
    lcd.setCursor(0, 1);
    lcd.print("Location 2: Low");
  }
  delay(2000);
  lcd.clear();
  if (a>=4)
  {
    lcd.setCursor(0, 0);
    lcd.print("Weight: High");
  }
   if (a<4)
  {
    lcd.setCursor(0, 0);
    lcd.print("Weight: Low");
  }
 delay(2000);
}
void send_msg_1()
{
  Serial.println("AT+CMGF=1");// for GSM module in TEXT mode
  delay(1000);
  Serial.println("AT+CMGS=\"+9921526975\"\r");// Phone number (change)
  delay(1000);
  Serial.println("Dustbin at Location 1 is full");// Message body (change as per requirement)
  delay(1000);
  Serial.println((char)26);// send message
  delay(1000);
}

ERRORS I am Getting while compiling as follows:
sketch_jul18a:34:22: error: no matching function for call to 'HX711::HX711(int, int)'
 HX711 scale(DOUT, CLK); // Init of library
                      ^
C:\Users\Admin\Desktop\Neha\sketch_jul18a\sketch_jul18a.ino:34:22: note: candidates are:
In file included from C:\Users\Admin\Desktop\Neha\sketch_jul18a\sketch_jul18a.ino:23:0:
C:\Users\Admin\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:30:3: note: HX711::HX711()
   HX711();
   ^
C:\Users\Admin\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:30:3: note:   candidate expects 0 arguments, 2 provided
C:\Users\Admin\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:19:7: note: constexpr HX711::HX711(const HX711&)
 class HX711
       ^
C:\Users\Admin\Documents\Arduino\libraries\HX711_Arduino_Library\src/HX711.h:19:7: note:   candidate expects 1 argument, 2 provided
exit status 1
no matching function for call to 'HX711::HX711(int, int)'

Please help me to solve this problem. Too much struggling...

Probably the main problem is already in the first lines:
#include ESP8266WiFi.h
#include LiquidCrystal.h
#include FirebaseArduino.h>
#include HX711.h>

You should use the correct formatting:
#include "ESP8266WiFi.h"
#include "LiquidCrystal.h"
#include "FirebaseArduino.h"
#include "HX711.h"

Also, HX711 does not have a constructor with arguments, so instead of
HX711 scale(DOUT, CLK);

uese
HX711 scale;

and in Setup:
scale.begin(DOUT, CLK);

You probably have the code meant for a different library.
See HX711_full_example. Or use the code belonging to your used HX711 library.

Thank you so much for your precious Help sir. from last many days struggling with errors. Not much familiar with Arduino IDE.. Thank you very much for help. Really grateful.

You are welcome, success with your project. If the answer solves your problem, please accept the answer (by pressing the button near the answer).


text:
HTTP myphp request error RFID
This program is a program which readings of rfid are saved to myphp database. I have a problem when running the code The wifi is connected but when the code doesn't save im assuming that the problem is in this part of the code client.print("GET /rfid/nodemcu_rfid/rfid_read.php?allow="); Since i have done a wire shark capture and notice a Bad Request error 400 as shown in the screen shot.
IP Addresses: 192.168.0.14 Is the php server , 192.168.0.19 is the nodemcu
ALL THE CODE :

#include<SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <SPI.h>
#include <MFRC522.h>

const char* ssid = "ARRIS-84AB";
const char* password = "your SSID password ";
//WiFiClient client;
char server[] = "192.168.0.14";   //eg: 192.168.0.222
#define SS_PIN 2 //FOR RFID SS PIN BECASUSE WE ARE USING BOTH ETHERNET SHIELD AND RS-522
#define RST_PIN 15
#define No_Of_Card 3

 WiFiClient client;

//WiFiServer server(80);
SoftwareSerial mySerial(8,9);
MFRC522 rfid(SS_PIN,RST_PIN);
MFRC522::MIFARE_Key key;
byte id[No_Of_Card][4]={
  {44,153,22,219},             //RFID NO-1
  {112,224,72,84},             //RFID NO-2
  {151,94,80,84}              //RFID NO-3
};
byte id_temp[3][3];
byte i;
int j=0;
void setup()
{
 Serial.begin(115200);
  delay(10);
  mySerial.begin(115200);
  SPI.begin();
  rfid.PCD_Init();

    for(byte i=0;i<6;i++)
  {
    key.keyByte[i]=0xFF;
  }

  // Connect to 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(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
//  server.begin();
  Serial.println("Server started");
  Serial.print(WiFi.localIP());
  delay(1000);
  Serial.println("connecting...");
 }
void loop()
{  // Check if a client has connected
  int m=0;
  if(!rfid.PICC_IsNewCardPresent())
  return;
  if(!rfid.PICC_ReadCardSerial())
  return;
  for(i=0;i<4;i++)
  {
   id_temp[0][i]=rfid.uid.uidByte[i];
             delay(50);
  }

   for(i=0;i<No_Of_Card;i++)
  {
          if(id[i][0]==id_temp[0][0])
          {
            if(id[i][1]==id_temp[0][1])
            {
              if(id[i][2]==id_temp[0][2])
              {
                if(id[i][3]==id_temp[0][3])
                {
                  Serial.print("your card no :");
                  for(int s=0;s<4;s++)
                  {
                    Serial.print(rfid.uid.uidByte[s]);
                    Serial.print(" ");

                  }
                  Serial.println("\nVALID");
                  Sending_To_DB();
                  j=0;

                            rfid.PICC_HaltA(); rfid.PCD_StopCrypto1();   return;
                }
              }
            }
          }
   else
   {j++;
    if(j==No_Of_Card)
    {
      Serial.println("inVALID");
      Sending_To_DB();
      j=0;
    }
   }
  }

     // Halt PICC
  rfid.PICC_HaltA();

  // Stop encryption on PCD
  rfid.PCD_StopCrypto1();
 }

 void Sending_To_DB()   //CONNECTING WITH MYSQL
 {
   if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
    Serial.println("GET /rfid/rfidread.php?allow=");     //YOUR URL /rfid/rfidread.php?allow
    client.print("GET /rfid/nodemcurfid/rfidread.php?allow=");     //YOUR URL /rfid/rfidread.php?allow  /var/www/html/rfid/rfid_read.php
    if(j!=No_Of_Card)
    {
      Serial.println('1');
      client.print('1');
    }
    else
    {
      Serial.println('0');
      client.print('0');
    }
    Serial.println("&id=");
    client.print("&id=");
    for(int s=0;s<4;s++)
                  {
                    Serial.println(rfid.uid.uidByte[s]);
                    client.print(rfid.uid.uidByte[s]);

                  }
    client.print(" ");      //SPACE BEFORE HTTP/1.1
    client.print("HTTP/1.1");
    client.print("Host: ");
     client.println(server);
    client.println("Host: 192.168.0.14");//eg: 192.168.0.222
    client.println("Connection: close");
    client.println();
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
  client.stop();
 }

client.println("Host: YOUR SERVER IP");//eg: 192.168.0.222 -- Is that really what you have in your running code?

no my that is a sample my code is client.println("Host: 192.168.0.14");

Please show us your real code. We can't tell you what is wrong with your code if you show us something that is not your code.

Edited with all configs (the real code)

Your problem is here:
client.print(" ");      //SPACE BEFORE HTTP/1.1
client.print("HTTP/1.1");
client.print("Host: ");
 client.println(server);
client.println("Host: 192.168.0.14");//eg: 192.168.0.222
client.println("Connection: close");
client.println();

That ends up with:
....(your request)... HTTP/1.1Host: 192.168.0.14
Host: 193.168.0.14
Connection: close

Not only are you sending the Host header twice, but you're not adding the line ending after the HTTP version.
Instead it should look more like:
client.print(" ");      //SPACE BEFORE HTTP/1.1
client.println("HTTP/1.1"); // <-- Note the use of println not print
client.print("Host: ");
client.println(server);
client.println("Connection: close");
client.println();

I have fixed the code like this but still no luck
client.print(" ");      //SPACE BEFORE HTTP/1.1     client.print("HTTP/1.1");     client.println(" Host: 192.168.0.14");//eg: 192.168.0.222     client.println("Connection: close");     client.println();
What is a line ending after HTTP version please ?

See my edit....

Thanks it worked !!!


text:
Arduino code for turning an led on by one clap and then off by one clap
I want my Arduino to turn on a LED when sound sensor detects a clap (noise) and keeps the LED on until the sound sensor detects another clap (noise) which turns the LED off.
int Sensor = A0;
boolean status_lights = false;

void setup() {
  pinMode(Sensor, INPUT);
  pinMode(13, OUTPUT);
}

void loop() {
  int status_sensor = digitalRead(Sensor);
  if (status_sensor == 0)
  {
    if (status_lights == true)
    {
      status_lights = false;
      digitalWrite(13, LOW);
    }
    else {
      status_lights = true;
      digitalWrite(13, HIGH);
    }
  }
}

My sound sensor has 3 pins.
sound sensor details
EDIT: My code only turns on the led but dosen't turn it off when I clap.

you have no code that is used for debugging... at least print the value of status_sensor to see what it actually is

If the sound level is below the threshold, the DO pin of the sensor signals a high value. If the sound level exceeds the threshold, i.e you clap you hands, the DO is pulled to GND and the signal gets LOW for a short while. After this short while the signals gets HIGH again.
Now look at you loop:
void loop()
{
  int status_sensor = digitalRead(Sensor);

  if (status_sensor == 0)
  {
    // you enter this block if you clap your hands and the
    // mcu is fast enough to capture the signal / DO pin (LOW)
    // within the short time interval
    // I'm sure it is fast enough to enter this block multiple
    // times in the interval the clap is active.
    if (status_lights == true)
    {
      status_lights = false;
      digitalWrite(13, LOW);
    }
    else
    {
      status_lights = true;
      digitalWrite(13, HIGH);
    }
  }
}

You see, the LED is toggled as long as the LOW interval of the sensor is active (DO=LOW).
I interpret you statement "My code only turns on the led but dosen't turn it off when I clap." so, that the LED is on, when the program starts without a clap. That means that the environmental noise is loud enough to activate the sensor. Then the loop above is iterated permanently and you switch on and off the LED at a very fast speed. That's like you would apply a PWM waveform on the LED pin. The LED is on but dimmed to about 50%.
To find out if I'm right, just add a delay in the loop. My assumption seems to be correct, if the LED blinks with one herz (one time per second).  The you can adjust the sound threshold until the LED stops blinking.
void loop()
{
  int status_sensor = digitalRead(Sensor);

  // Add the delay here ..........
  delay(500);

  if (status_sensor == 0)
  {

If you have calibrated the sensor, remove the delay from the code and add a new delay after changing the LED states. That should be much shorter, because it's only there to ensure that you don't toggle the LED while the sensor is active.
    if (status_lights == true)
    {
      status_lights = false;
      digitalWrite(13, LOW);
    }
    else
    {
      status_lights = true;
      digitalWrite(13, HIGH);
    }
    // wait until the clap is over
    delay(100);

+1 for this code comment: "I’m sure it is fast enough to enter this block multiple times in the interval the clap is active." When you clap, it toggles the DO pin high and low multiple times, and it looks something like this: https://arduino.stackexchange.com/a/54495/37523

@VE7JRO The documentation of the sensor is not really helpful, so thank you for giving an example. I was not really sure whether the  use something like a  smoothing condenser. But obviously that's not the case. (73 Peter, DF4VB)