Using mills instead of delay for small pizeo project

Hi guys

Essentially what I've done so far is use a light sensor to make a pizeo buzzer make beeping noises depending on the level of light. When there is less light, it beeps faster, and when there is more light, is beeps slower.

In addition, I've put in a an LED and it flashes with the pizeo buzzer beeps.

Essentially they both use the the sensorValue time to do their thing.

My question is how i can incorporate mills() into it rather than using the delay. Me using the delay means the LED flash and buzzer don't quite line up.

I have done the mills example within the program but i don't really know how i can apply it in this situation.

The code is

/*

Light sensor, Piezo and LED project

*/

int piezoPin = 8; // Declaring Piezo Buzzer on Pin 8
int lightsensorPin = 0; // Declaring light sensor on Analog Pin 0
int sensorValue = 0; // Reading different values from the sensor
int ledPin = 3; // PWM pin
//long int previousMillis =0;
//const long interval = 25;

void setup()
{
  pinMode(lightsensorPin, INPUT);
  pinMode(ledPin, OUTPUT);
}

void loop()
{// Starting the cycle functions below


sensorValue = analogRead(lightsensorPin); // read the value from the light sensor
tone(piezoPin, 500); // Play a 1000Hz tone from the piezo (beep)
delay(30); // wait a bit, change the delay for fast response.
noTone(piezoPin); // stop the tone
delay(sensorValue); // wait the amount of milliseconds (sensorValue is a number);
digitalWrite(ledPin,HIGH);
delay(sensorValue);
digitalWrite(ledPin,LOW);
delay(sensorValue);

}

Thanks in advance

Why not simply rearrange the sketch so that things do line up?

How..? If I'm using delays, that means that the other thing can't possibly occur at the same time. There will always a be a slight gap between the piezo beep and LED flash - you can't really notice it when its flashing/beeping fast, but when it slows down significantly, its very noticeable.

Unless I'm being dumb about the problem I'm having, please show me.

tone(piezoPin, 500);
digitalWrite(ledPin,HIGH);
delay(30); // wait a bit, change the delay for fast response.
noTone(piezoPin); // stop the tone

etc?

The demo several things at a time which illustrates how to use millis() to manage time.

...R

Thanks guys,

@Robin2 your thread is very useful but in this case it turns out that I can just do what AWOL suggested. Ill be sure to refer to your thread in the future when I need it.