I have an error in the times of my code, it receives a value from 0 to 100 of the serial port, and then it converts to seconds, example: if the value is 25, it should be 15 seconds off and 45 seconds on but the times are not accurate , for this example it is 20 seconds off and 51 on and sometimes varies
#include "Wire.h"
int ledState = LOW;
const int ledPin = 9;
unsigned long tempo = 0; // variável para tratar valores do millis()
int temporizador = 0; // variável de status
unsigned short int timerx=0;
unsigned short int timery=0;
void setup() {
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
}
void loop() {
unsigned long currentMillis = millis();
while (Serial.available()) {
int received= Serial.parseInt();
Serial.println(received);
timerx=(((received*60)/100)*1000);
timery=(60000-timerx);
if(received==0)
{
digitalWrite(ledPin, LOW);
}
if(received==100){
digitalWrite(ledPin, HIGH);
}
if (temporizador == 0) {
digitalWrite(ledPin, HIGH);
temporizador = 1;
tempo = millis();
}
if (millis() - tempo >= timery && temporizador == 1){
digitalWrite(ledPin, LOW);
temporizador = 2;
tempo = millis();
}
if (millis() - tempo >= timerx && temporizador == 2){
digitalWrite(ledPin, HIGH);
temporizador = 1;
tempo = millis();
digitalWrite(ledPin, HIGH);
}
}
}