Hi guys !
I'm a beginner and I recently wrote a code using millis. This program supposedly needs to print the signal " cut tape" only when the result of the ultrasonic sensor is less than 30 cm for 5 seconds. However, once I ran the program, it stills prints " Cut tape" even though it the period haven't reach 5 secs.
Can anyone help me to solve the issue ?
This is my code. Ignore the codes for servo for now as it is in development mode. Thank you.
const unsigned long period= 5000;// init period=5000.
int trigPin = 13; // Trigger
int echoPin = 12; // Echo
long duration, cm, inches;
unsigned long startMillis; //some global variables available anywhere in the program
unsigned long currentMillis;
#include <Servo.h>
Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards
int pos = 0; // variable to store the servo position
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
//Serial Port begin
Serial.begin(9600);
//Define inputs and outputs
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
startMillis= millis();
}
void loop() {
// The sensor is triggered by a HIGH pulse of 10 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
//pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(10);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the signal from the sensor: a HIGH pulse whose
// duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
// Convert the time into a distance
cm = (duration/2) / 29.1; // Divide by 29.1 or multiply by 0.0343
Serial.print(cm);
Serial.print("cm");
while( cm < 30)
{ here: currentMillis= millis();
if((currentMillis-startMillis)<period )
{ goto here;}// less than 5s jump to 'here'.
else if(( currentMillis-startMillis )== period)
{ Serial.print(" Cut tape"); }
startMillis = currentMillis;// to save the latest time so can get the diff when looping again.
//delay(50);
break;
}
delay(150);
}