Hi Arduino veterans!
I am using an circuit on TinkerCAD to simulate the actual circuit I'm going to run. I thought I had the code down, but I realised that I'm not sure how to offset my workStart back to 0.
Basically, when the ldr is covered for a certain period of time intervalrisk, the led will light up. To switch the led off, the ldr must be uncovered for time intervalrest. Then ideally, workStart can somehow be returned to zero.
Since intervalrisk depends on workStart, which takes current time of the Arduino using millis() in my code, my led will always glow whenever i recover the ldr.
Most of the code I find on the forums will either need me to scrap my 10 hours of coding on the project when I still have homework from other subject to do, aren't what I need or will break the arduino. I have asked my friends who did Arduino before and for much longer than me, and all of them can't figure it out either.
What exact strings of code can I add to my current code, or how can I rework my code such that my workStart starts at 0 whenever the ldr is uncovered?
I have attached the image of the circuit, the code I'm using and the link to the tinkerCAD simulation I'm using. Please help out this sleep-deprived college student :').
tinkercad: Login | Tinkercad
const int ldrPin = 0;//ldr on pin A0
int L;//ldr reading
int led = 3;//led on pin D3
int ledState = LOW;//led is initally off
unsigned long workStart =0;//used to timestamp start of work
unsigned long restStart =0;//used to timestamp start of rest
unsigned long workTime =0;//duration of work
unsigned long restTime =0;//duration of rest
int intervalrest = 1000;//good rest duration
int intervalrisk = 2000;//bad work duration
void setup() {
// put your setup code here, to run once:
pinMode(led,OUTPUT);//motor will output
Serial.begin(9600);//start takin analog measurements
}
void loop() {
// put your main code here, to run repeatedly:
L = analogRead(ldrPin);//P has value of fsr pin
if (L<600){//wrist touch wristbed
workStart=millis();
Serial.println("Contact. Working for ___ ms.");//print Contact on serial monitor
workTime=millis();//take current timestamp of cycle as starting work first time wrist touch
Serial.println(workTime);
if (workTime - workStart > intervalrisk){//if duration of work exceeds risk
Serial.println("Take a break!");
if (ledState==LOW){//if motor off
digitalWrite(led,HIGH);//motor on
}
}
}
if (L>600){//wrist leaves wristbed
Serial.println("No contact. Rested for _____ ms");
restTime=millis()-workTime;//take timestamp of restTime
Serial.println(restTime);
if (restTime - restStart > intervalrest){
Serial.println("Risk avoided! Resume work if needed.");
digitalWrite(led,LOW);
}
else if (restTime - restStart < intervalrest){
Serial.println("Take a longer break.");
}
}
}
}