How to change delay by setTimeout in SimpleTimer?

Hello everyone, i’m try change delay(500) in my void by timer.setTimeout, but it doesn’t work, i don’t know what my problem ? I need some help for my project. Thank you very very much !!!


long distance1[17];//So goc quay cua srada
  int dem2 =0;
  int dem1=0;
  int d=10;
  int goc;
  int i;
  srada.write(15);
  robotMover(inR1,inR2,inL1,inL2,0);// Dừng
  for(i = 0; i<17; i+=1){
   delay(500);
   srada.write(10+i*10);
    distance1[i] = getDistance();
    Serial.print("Gia tri: ");
    Serial.println(distance1[i]);
    if(distance1[i]>=4 & distance1[i]<=10){
       d = d+i*10;  
       dem2++;   
       Serial.println(d);
        //phan biet mau 
       color = readColor();
        
    }
   }

define: “it doesn’t work”
what does the code with timer.setTimeout look like?

That is not how it works. What you need to do is decide how often to call the code and add a timer for that function.

for instance
timer.setTimeout(5000L, lockDoor);

sets a timer that calls the function lockdoor() after 5 seconds.

timer.setInterval(500l, scanNfc);

adds a timer event that calls scanNfc() every .5 seconds

In my code, if i use delay(500), app will disconnected. I don’t know use timer.setTimeout because i’m try but cann’t

Dont use delay , get used to using simple timer . Delay will block the blynk.run function so dont use that. plus simple timer is easy.

read this article , @Gunner explains well about the simple timers and basic blynk codes. C++ Blynk - Code Examples for Basic Tasks (Work in Progress)

i know but i don’t know how to change delay(500) by timer.setTimeout ? Let look at my code.Position of delay(500) is in for(). please help me !!!

Sorry friend i am busy and later i will check your code :frowning: . for the time being try to understand the concept of these funtions and i found another link that would be useful for you

Because you are using a for() loop, I am unsure if you can call a timer in it and have the loop “wait” (without blocking) until the timer triggers, before advancing the loop count :thinking:

I think you would need to redesign your preset count loop with a preset count timer… as per my example here using such a timer - C++ Blynk - Code Examples for Basic Tasks (Work in Progress)

Perhaps something like this in Lambda form?

This is completely untested

void SomeLoopFunction) {
i=0;
 timer.setTimer(500, []() {  // Run this timer every 500ms
    i++;  // Count up
    srada.write(10+i*10);
    distance1[i] = getDistance();
    Serial.print("Gia tri: ");
    Serial.println(distance1[i]);
    if(distance1[i]>=4 & distance1[i]<=10){
       d = d+i*10;  
       dem2++;   
       Serial.println(d);
        //phan biet mau 
       color = readColor();
    }
  }, 17); // Run this timer 17 times
}
1 Like

i follow your solution, but error: ‘i’ is not captured
Please help me !!!

Make ‘i’ a global variable outside of the function loop. Even change its name so you don’t get confused later.

That error is to do with lambda functions that capture variables (not currently working in BlynkTimer).

So the workaround is to use a global variable.

my problem is void autorun(). When i select autorun in switch BLYNK_WRITE(V3), app was disconnected. I try more and more but no result. Please help me !!!
This is full code:

#include <Blynk.h>
#include <PS2X_lib.h>
#include <DHT.h>
#include <DHT_U.h>
#include <SPI.h>
#include <ESP8266_Lib.h>
#include <BlynkSimpleShieldEsp8266.h>
#include <SimpleTimer.h>
#include <Servo.h>  

 int ss ;
 long distance1[17];//So goc quay cua srada
  int dem22 =0;
   int dd=10;
//IP blynk
char auth[] = "";
//Name & pass WIFI
char ssid[] = "S2_j6";
char pass[] = "suquynh1601";
// Hardware Serial on Mega
#define EspSerial Serial3
// Your ESP8266 baud rate:
#define ESP8266_BAUD 115200
ESP8266 wifi(&EspSerial);
SimpleTimer timer;
WidgetLCD lcd(V7);
//Cam bien nhiet
#define DHTPIN 52
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
// Servo
Servo s1;  
Servo s2;
Servo s3;
Servo s4;
Servo s5;
Servo srada;
//phan biet mau
#define S0 24
#define S1 25
#define S2 26
#define S3 27
#define sensorOut 28
//rada
#define trig 9 
#define echo 10 
#define TIME_OUT 5000
//Motor
#define inA1 4 //Định nghĩa chân in1 của động cơ A
#define inA2 5 //Định nghĩa chân in2 của động cơ A
#define inB1 6 //Định nghĩa chân in1 của động cơ B
#define inB2 7 //Định nghĩa chân in2 của động cơ B
const byte enA=22;
const byte enB=23;

int pVal = 1;

#define PIN_DO 2
volatile unsigned int pulses = 0;
float rpm =1.00;
unsigned long timeOld;
#define HOLES_DISC 15
int g1=110,g2=100,g3=90,g4=90, g5 =110;// Gia tri ban dau cua cac servo

int frequency = 0;
int color=0;
// Toc do xe di
float v;
float st; // Quang duong di thang
float s = 0.38; //Quang duong quay
//thứ tự màu
int mau1 = 1;
int mau2 = 2;
int mau3 = 3;
//dem so vi tri mau
int dem =0;
//Button
int button = 49;
int buttonState = 0;  
//RF
#define PS2_DAT        A2  //Dữ liệu từ gamepad về vdk
#define PS2_CMD        A3  //Dữ liệu từ vdk về gamepad
#define PS2_SEL        A4  // chip section
#define PS2_CLK        A5  //Xung
#define pwm11 3 
#define pwm22 2
#define pressures   false
#define rumble      false
PS2X ps2x;// tạo PS2 điều khiển lớp
int pwm1=255,pwm2=255;
int error = 0;
byte type = 0;
byte vibrate = 0;
//TOC DO
void counter()
{
  pulses++;
}
//BLYNK
void sendSensor()
{
  float h = dht.readHumidity();
  // or dht.readTemperature(true) for Fahrenheit
  float t = dht.readTemperature(true); 
  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  // You can send any value at any time.
  // Please don't send more that 10 values per second.
  Blynk.virtualWrite(V5, h);
  Blynk.virtualWrite(V6, t);
}


//Toc do dong co
float speedmotor(){
  float vt=1.00;
  if (millis() - timeOld >= 1000)
  {
    detachInterrupt(digitalPinToInterrupt(PIN_DO));
    rpm = rpm * (pulses) / (2*HOLES_DISC);
    Serial.println(rpm);
    vt = vt * rpm*4/100;
    Serial.print("pulses=");
    Serial.println(pulses);
    Serial.print("v=");
    Serial.println(vt);
    timeOld = millis();
    pulses = 0;
    attachInterrupt(digitalPinToInterrupt(PIN_DO), counter, FALLING);  
    rpm = 1.00;
  } 
  return vt;
}
// Khoang cach rada
float getDistance()
{
  long duration, distanceCm;
  digitalWrite(trig, LOW);
  
  digitalWrite(trig, HIGH);
  
  digitalWrite(trig, LOW);
  duration = pulseIn(echo, HIGH, TIME_OUT);
  // convert to distance
  distanceCm = duration / 29.1 / 2;
  return distanceCm;
}
int objectDistance_cm (byte angle)
{
  srada.write(angle);
  timer.setTimeout(500L,objectDistance_cm );
  unsigned long duration;//biến đo thời gian
  int distance;//biến lưu khoảng cách
  /* phát xung từ chân trig */
  digitalWrite(trig,0);//tắt chân trig
  delayMicroseconds(2);
  digitalWrite(trig,1);// phát xung từ chân trig
  delayMicroseconds(5);// xung có độ dài 5 microSeconds
  digitalWrite(trig,0);//tắt chân trig
  /* tính toán thời gian */
  duration = pulseIn(echo,HIGH);//đo độ rộng xung HIGH ở chân echo. ( http://arduino.vn/reference/pulsein )
  distance = int(duration/2/29.412);//tính khoảng cách đến vật.
  /* in kết quả ra Serial monitor */
  //Serial.print(distance);
  //Serial.println("cm");
  //delay(200);
  return distance;

  Serial.println(distance);
}

void ReadColor()
{
  long duration, distance;
  digitalWrite(trig, LOW);  
  delayMicroseconds(2); 
  digitalWrite(trig, HIGH);
  delayMicroseconds(10); 
  digitalWrite(trig, LOW);
  duration = pulseIn(echo, HIGH);
  distance = (duration/2) / 29.1;
  Serial.print(distance);
  lcd.print(0,1,distance);
  digitalWrite(S2,LOW);
  digitalWrite(S3,LOW);
  int redFrequency = pulseIn(sensorOut, LOW);
  int R = redFrequency;
  digitalWrite(S2,HIGH);
  digitalWrite(S3,HIGH);
  int greenFrequency = pulseIn(sensorOut, LOW);
  int G = greenFrequency;
  digitalWrite(S2,LOW);
  digitalWrite(S3,HIGH);
  int blueFrequency = pulseIn(sensorOut, LOW);
  int B = blueFrequency;
    if(R<G & R<B ){
    lcd.clear();
    lcd.print(0,0,"Red");
    lcd.print(0,1,distance);
  }
  else if(G<R & G<B){
    lcd.clear();
    lcd.print(0,0,"Green");
    lcd.print(0,1,distance);
  }
  else if( B<R& B<G){
    lcd.clear();
    lcd.print(0,0,"Blue");
    lcd.print(0,1,distance);
  }
  else
  {
  lcd.clear();
  lcd.print(0,0,"Unknown");
  lcd.print(0,1,distance);
  }
  return ; 
}
// Color
int readColor() {

  // Setting red filtered photodiodes to be read
  digitalWrite(S2, LOW);
  digitalWrite(S3, LOW);
  // Reading the output frequency
  frequency = pulseIn(sensorOut, LOW);
  int R = frequency;
  // Printing the value on the serial monitor
  //Serial.print("R= ");//printing name
  //Serial.print(frequency);//printing RED color frequency
  //Serial.print("  ");
  //delay(50);
  // Setting Green filtered photodiodes to be read
  digitalWrite(S2, HIGH);
  digitalWrite(S3, HIGH);
  // Reading the output frequency
  frequency = pulseIn(sensorOut, LOW);
  int G = frequency;
  // Printing the value on the serial monitor
  //Serial.print("G= ");//printing name
  //Serial.print(frequency);//printing RED color frequency
  //Serial.print("  ");
  //delay(50);
  // Setting Blue filtered photodiodes to be read
  digitalWrite(S2, LOW);
  digitalWrite(S3, HIGH);
  // Reading the output frequency
  frequency = pulseIn(sensorOut, LOW);
  int B = frequency;
  // Printing the value on the serial monitor
  //Serial.print("B= ");//printing name
  //Serial.print(frequency);//printing RED color frequency
  //Serial.print("  ");
  //delay(500);
  if(R<G & R<B){
    color = 1; // Red
  }
  if(G<R & G<B){
    color = 2; // Green
  }
  if(B<R & B<G){
    color = 3; // Blue
  }
  Serial.print("co= ");
  Serial.println(color);
  return color;  
}
//Huong di cua xe
void thang(byte inR1, byte inR2, byte inL1, byte inL2, float st)
{
  int t;
  t = int(1000*(st/v));  
  robotMover(inR1,inR2,inL1,inL2,1);  
  Serial.println("Tiến: ");
  Serial.println(st);
  timer.setTimeout(t, thang); 
}
void lui(byte inR1, byte inR2, byte inL1, byte inL2)
{
  float sl = 0.2;
  int t;
  t = int(1000*(sl/v));  
  robotMover(inR1,inR2,inL1,inL2,2);  
  Serial.println("Lùi: ");
  Serial.println(sl);
  timer.setTimeout(t, lui);
}
void quayphai90(byte inR1, byte inR2, byte inL1, byte inL2)
{
  int t;
  t = int(1000*(s/v));  
  robotMover(inR1,inR2,inL1,inL2,4);  
  Serial.println("Quay phải 90 độ: ");
  Serial.println(s);
  timer.setTimeout(t, quayphai90);
}
void quayphai180(byte inR1, byte inR2, byte inL1, byte inL2)
{
  int t;
  t = int(2000*(s/v));  
  robotMover(inR1,inR2,inL1,inL2,4);  
  Serial.println("Quay phải 180 độ: ");
  Serial.println(s);
  timer.setTimeout(t, quayphai180);
}
void quaytrai90(byte inR1, byte inR2, byte inL1, byte inL2)
{
  int t;
  t = int(1000*(s/v));  
  robotMover(inR1,inR2,inL1,inL2,3);  
  Serial.println("Quay trái 90 độ: ");
  Serial.println(s);
  timer.setTimeout(t, quaytrai90);
}
void robotMover (byte inR1, byte inR2, byte inL1, byte inL2, byte action)
{
  switch (action)
  {
    case 0:// không di chuyển
      motorControlNoSpeed(inR1, inR2, 0);
      motorControlNoSpeed(inL1, inL2, 0);
      break;
    case 1://đi thẳng
      motorControlNoSpeed(inR1, inR2, 1);
      motorControlNoSpeed(inL1, inL2, 1);
      break;
    case 2:// lùi lại
      motorControlNoSpeed(inR1, inR2, 2);
      motorControlNoSpeed(inL1, inL2, 2);
      break;
    case 3:// quay trái
      motorControlNoSpeed(inR1, inR2, 1);
      motorControlNoSpeed(inL1, inL2, 2);
      break;
    case 4:// quay phải
      motorControlNoSpeed(inR1, inR2, 2);
      motorControlNoSpeed(inL1, inL2, 1);
      break;
    case 5:// rẽ trái
      motorControlNoSpeed(inR1, inR2, 1);
      motorControlNoSpeed(inL1, inL2, 0);
      break;
    case 6:// rẽ phải
      motorControlNoSpeed(inR1, inR2, 0);
      motorControlNoSpeed(inL1, inL2, 1);
      break;
    case 7:// rẽ lùi trái
      motorControlNoSpeed(inR1, inR2, 2);
      motorControlNoSpeed(inL1, inL2, 0);
      break;
    case 8:// rẽ lùi phải
      motorControlNoSpeed(inR1, inR2, 0);
      motorControlNoSpeed(inL1, inL2, 2);
      break;
    default:
      action = 0;     
  }
}

void motorControlNoSpeed (byte in1,byte in2, byte direct)
{

  switch (direct) 
  {
    case 0:// Dừng không quay
      digitalWrite(in1,LOW);
      digitalWrite(in2,LOW);
      break;
    case 1:// Quay chiều thứ 1
      digitalWrite(in1,HIGH);
      digitalWrite(in2,LOW);
      break;    
    case 2:// Quay chiều thứ 2
      digitalWrite(in1,LOW);
      digitalWrite(in2,HIGH);
      break;
    //default: 
  }
}
void testthavat(){
  robotMover(inA1,inA2,inB1,inB2,0);
  //Servo 1
  s1.write(g1);
  //Servo 2
  for(g2=100;g2<=170;g2+=1){
    s2.write(g2);
    timer.setTimeout(15L, testthavat);
  }
  //Servo 3
  for(g3=90;g3>=55;g3-=1){
    s3.write(g3);
    timer.setTimeout(15L, testthavat);
  }
  //Servo 4
  s4.write(g4);
  //Servo 5
  for(g5=145;g5>=110;g5-=1){
    s5.write(g5);
    timer.setTimeout(15L, testthavat);
  }
  timer.setTimeout(1000L, testthavat);
  //Sau khi thả robot arm tro lai vi tri cu
  for(g2=170;g2>=100;g2-=1){
    s2.write(g2);
    timer.setTimeout(15L, testthavat);
  }
  for(g3=55;g3<=90;g3+=1){
    s3.write(g3);
    timer.setTimeout(15L, testthavat);
  }
}
void gapvat(){
  for(g2=100;g2<=170;g2+=1){
    s2.write(g2);
    timer.setTimeout(15L, gapvat);
  }
  for(g3=90;g3>=55;g3-=1){
    s3.write(g3);
    timer.setTimeout(15L, gapvat);
  }
  s4.write(g4);
  for(g5=110;g5<=145;g5+=1){
    s5.write(g5);
    timer.setTimeout(15L, gapvat);
  }
  timer.setTimeout(1000L, gapvat);
  for(g2=170;g2>=100;g2-=1){
    s2.write(g2);
    timer.setTimeout(15L, gapvat);
  }
  for(g3=55;g3<=90;g3+=1){
    s3.write(g3); 
    timer.setTimeout(15L, gapvat);
  }
}
/*
void ham1()
  {
    srada.write(10+ii*10);
    distance1[ii] = getDistance();
    Serial.print("Gia tri: ");
    Serial.println(distance1[ii]);
    if(distance1[ii]>=4 & distance1[ii]<=10){
       d = d+ii*10;  
       dem2++;   
       Serial.println(d);
        //phan biet mau   
       color = readColor();
        
    }
    }
    */
void testgapvat(byte inR1, byte inR2, byte inL1, byte inL2, int co)
{
  
  //long distance1[17];//So goc quay cua srada
  //int dem2 =0;
  int dem1=0;
  //int d=10;
  int goc;
  srada.write(15);
  robotMover(inR1,inR2,inL1,inL2,0);// Dừng

  /*
  for(i = 0; i<17; i+=1){
   delay(500);
 //     timer.setTimeout(500L,[i](){srada.write(10 + i*10);});
    srada.write(10+i*10);
    distance1[i] = getDistance();
    Serial.print("Gia tri: ");
    Serial.println(distance1[i]);
    if(distance1[i]>=4 & distance1[i]<=10){
       d = d+i*10;  
       dem2++;   
       Serial.println(d);
        //phan biet mau   
       color = readColor();
        
    }

    //timer.setTimeout(500L,ham1);
    
   }
   */
    ss=0;
   timer.setTimeout(500L, []() {  // Run this timer every 500ms
    ss++;  // Count up
    srada.write(10+ss*10);
    distance1[ss] = getDistance();
    Serial.print("Gia tri: ");
    Serial.println(distance1[ss]);
    if(distance1[ss]>=4 & distance1[ss]<=10){
       dd = dd+ss*10;  
       dem22++;   
       Serial.println(dd);
        //phan biet mau 
       color = readColor();
    }
  }, 17);
   
   dem1=dd/dem22;
   goc = dem1+(120-dem1)/2;
   Serial.println("Goc");
   Serial.println(dem1);
   if(color == co){
    if(dem1>=60&dem1<81)
      {
        //robot arm gap vat
        s1.write(goc+5);
        gapvat();
      }
     else if(dem1>81&dem1<110)
      {
        //robot arm gap vat
        s1.write(goc);
        gapvat();
      }
      else if(dem1>=110&dem1<=120)
      {
        //robot arm gap vat
        s1.write(goc-5);
        gapvat();
      }
      dem22=0;
      dd=10;
      dem1=0;
      lui(inR1, inR2, inL1, inL2);
      if(color == 1){ // Red
          if(dem ==0){
            quayphai90(inR1, inR2, inL1, inL2);
            thang(inR1, inR2, inL1, inL2, 0.7);
            quayphai90(inR1, inR2, inL1, inL2);
            thang(inR1, inR2, inL1, inL2, 0.5);
            testthavat();
            quayphai90(inR1, inR2, inL1, inL2);
            thang(inR1, inR2, inL1, inL2, 0.7);
            quayphai90(inR1, inR2, inL1, inL2);
            robotMover(inR1,inR2,inL1,inL2,0);// Dừng
            timer.setTimeout(1000L, robotMover);
          }
          if(dem == 1){
            quayphai90(inR1, inR2, inL1, inL2);
            thang(inR1, inR2, inL1, inL2, 0.4);
            quayphai90(inR1, inR2, inL1, inL2);
            thang(inR1, inR2, inL1, inL2, 0.5);
            testthavat();
            quayphai90(inR1, inR2, inL1, inL2);
            thang(inR1, inR2, inL1, inL2, 0.7);
            quayphai90(inR1, inR2, inL1, inL2);
            robotMover(inR1,inR2,inL1,inL2,0);// Dừng
            timer.setTimeout(1000L, robotMover);
          }
          if(dem == 2){
            quayphai90(inR1, inR2, inL1, inL2);
            thang(inR1, inR2, inL1, inL2, 0.1);
            quayphai90(inR1, inR2, inL1, inL2);
            thang(inR1, inR2, inL1, inL2, 0.5);
            testthavat();
            quayphai90(inR1, inR2, inL1, inL2);
            thang(inR1, inR2, inL1, inL2, 0.7);
            quayphai90(inR1, inR2, inL1, inL2);
            robotMover(inR1,inR2,inL1,inL2,0);// Dừng
            timer.setTimeout(1000L, robotMover);
          }
        }
        if(color == 2){
          if(dem ==0){
            quayphai90(inR1, inR2, inL1, inL2);
            thang(inR1, inR2, inL1, inL2, 0.6);
            quayphai90(inR1, inR2, inL1, inL2);
            thang(inR1, inR2, inL1, inL2, 0.5);
            testthavat();
            quayphai90(inR1, inR2, inL1, inL2);
            thang(inR1, inR2, inL1, inL2, 0.6);
            quayphai90(inR1, inR2, inL1, inL2);
            robotMover(inR1,inR2,inL1,inL2,0);// Dừng
            timer.setTimeout(1000L, robotMover);
          }
          if(dem == 1){
            quayphai90(inR1, inR2, inL1, inL2);
            thang(inR1, inR2, inL1, inL2, 0.3);
            quayphai90(inR1, inR2, inL1, inL2);
            thang(inR1, inR2, inL1, inL2, 0.5);
            testthavat();
            quayphai90(inR1, inR2, inL1, inL2);
            thang(inR1, inR2, inL1, inL2, 0.6);
            quayphai90(inR1, inR2, inL1, inL2);
            robotMover(inR1,inR2,inL1,inL2,0);// Dừng
            timer.setTimeout(1000L, robotMover);
          }
          if(dem == 2){
            quayphai90(inR1, inR2, inL1, inL2);
            quaytrai90(inR1, inR2, inL1, inL2);
            thang(inR1, inR2, inL1, inL2, 0.5);
            testthavat();
            quayphai90(inR1, inR2, inL1, inL2);
            thang(inR1, inR2, inL1, inL2, 0.6);
            quayphai90(inR1, inR2, inL1, inL2);
            robotMover(inR1,inR2,inL1,inL2,0);// Dừng
            timer.setTimeout(1000L, robotMover);
          }
        }
        if(color == 3){ // Blue
          if(dem ==0){ //vi tri 1
            quayphai90(inR1, inR2, inL1, inL2);
            thang(inR1, inR2, inL1, inL2, 0.5);
            quayphai90(inR1, inR2, inL1, inL2);
            thang(inR1, inR2, inL1, inL2, 0.5);
            testthavat();
            quayphai90(inR1, inR2, inL1, inL2);
            thang(inR1, inR2, inL1, inL2, 0.5);
            quayphai90(inR1, inR2, inL1, inL2);
            robotMover(inR1,inR2,inL1,inL2,0);// Dừng
            timer.setTimeout(1000L, robotMover);
          }
          if(dem == 1){ //vi tri 2
            quayphai90(inR1, inR2, inL1, inL2);
            thang(inR1, inR2, inL1, inL2, 0.2);
            quayphai90(inR1, inR2, inL1, inL2);
            thang(inR1, inR2, inL1, inL2, 0.5);
            testthavat();
            quayphai90(inR1, inR2, inL1, inL2);
            thang(inR1, inR2, inL1, inL2, 0.5);
            quayphai90(inR1, inR2, inL1, inL2);
            robotMover(inR1,inR2,inL1,inL2,0);// Dừng
            timer.setTimeout(1000L, robotMover);
          }
          if(dem == 2){
            quaytrai90(inR1, inR2, inL1, inL2);
            thang(inR1, inR2, inL1, inL2, 0.1);
            quaytrai90(inR1, inR2, inL1, inL2);
            thang(inR1, inR2, inL1, inL2, 0.5);
            testthavat();
            quayphai90(inR1, inR2, inL1, inL2);
            thang(inR1, inR2, inL1, inL2, 0.5);
            quayphai90(inR1, inR2, inL1, inL2);
            robotMover(inR1,inR2,inL1,inL2,0);// Dừng
            timer.setTimeout(1000L, robotMover);
          }
        }
      }
      else {
        lui(inR1, inR2, inL1, inL2);
        quayphai90(inR1, inR2, inL1, inL2);
        thang(inR1, inR2, inL1, inL2,0.3);
        quaytrai90(inR1, inR2, inL1, inL2);
        thang(inR1, inR2, inL1, inL2,0.2);
        testgapvat(inR1, inR2, inL1, inL2, co);
        dem++;
        Serial.print("Dem = ");
        Serial.println(dem);
      }
}
void motorSpeed(int prmA, byte prmA1, byte prmA2, int prmB, byte prmB1, byte prmB2)
{
  analogWrite(enA,prmA);
  analogWrite(enB,prmB);
  
  digitalWrite(inA1,prmA1);
  digitalWrite(inA2,prmA2);
  digitalWrite(inB1,prmB1);
  digitalWrite(inB2,prmB2);
}
BLYNK_WRITE(V0) {
  int x = param[0].asInt();
  int y = param[1].asInt();
// x =  -2 -1 0 1 2 
// Y =  -2 -1 0 1 2 
 if ((x==0) && (y==0)) 
 {
   motorSpeed(0,LOW,LOW,0,LOW,LOW); 
 }
 else if ((x==0) && (y>0))
 {
  if (y==1){ motorSpeed(900,HIGH,LOW,900,HIGH,LOW); }
  else { motorSpeed(1023,HIGH,LOW,1023,HIGH,LOW); }
 }
 else if ((y==0) && (x>0))
  motorSpeed(900,HIGH,LOW,900,LOW,HIGH); 
 else if ((y>0) && (x>0))
  motorSpeed(1023,HIGH,LOW,900,LOW,LOW); 
 else if ((y==0) && (x<0))
  motorSpeed(900,LOW,HIGH,900,HIGH,LOW); 
 else if ((y>0) && (x<0))
   motorSpeed(900,LOW,LOW,1023,HIGH,LOW);   
 if ((y<0) && (x<0))
    motorSpeed(900,LOW,LOW,1023,LOW,HIGH); 
 else if ((y<0) && (x>0))
    motorSpeed(1023,LOW,HIGH,900,LOW,LOW); 
 else if ((y<0) && (x==0))
   motorSpeed(900,LOW,HIGH,900,LOW,HIGH); 
}

BLYNK_WRITE(V1)
{
   s1.write(param.asInt());
}

BLYNK_WRITE(V2)
{
  s2.write(param.asInt());
}
BLYNK_WRITE(V8)
{
   s3.write(param.asInt());
}

BLYNK_WRITE(V9)
{
  s4.write(param.asInt());
}
BLYNK_WRITE(V10)
{
   s5.write(param.asInt());
}


void controlapp(){
  Blynk.run();
  timer.run(); // Initiates BlynkTimer
}
void controlRF(){
  if(error == 1)
    return; 
  if(type == 1)
    ps2x.read_gamepad(false, vibrate); 
  if(ps2x.Button(PSB_START))        
    Serial.println("Start is being held");
  if(ps2x.Button(PSB_SELECT))
    Serial.println("Select is being held");  
  if(ps2x.ButtonPressed(PSB_PAD_UP)) {   
    robotMover(inA1,inA2,inB1,inB2,1);
    Serial.println("Di thang ");
  }
  if(ps2x.ButtonReleased(PSB_PAD_UP)){
     robotMover(inA1,inA2,inB1,inB2,0);
     Serial.println("NGUNG");
   }
   //////////////////////////////
  if(ps2x.ButtonPressed(PSB_PAD_RIGHT)){
    robotMover(inA1,inA2,inB1,inB2,3);
    Serial.println("phai ");
  }
  if(ps2x.ButtonReleased(PSB_PAD_RIGHT)){
    robotMover(inA1,inA2,inB1,inB2,0);
    Serial.println("NGUNG");
  }
    ///////////////////////////////////////////
  if(ps2x.ButtonPressed(PSB_PAD_LEFT)){
      robotMover(inA1,inA2,inB1,inB2,4);
      Serial.println("trai ");
    }
  if(ps2x.ButtonReleased(PSB_PAD_LEFT)){
     robotMover(inA1,inA2,inB1,inB2,0);
     Serial.println("NGUNG");}
    ///////////////////////////////////////////////
   if(ps2x.ButtonPressed(PSB_PAD_DOWN)){
      if(ps2x.Analog(PSAB_PAD_DOWN)==0){
        robotMover(inA1,inA2,inB1,inB2,2);
        Serial.println("nghich");}    
    }   
    if(ps2x.ButtonReleased(PSB_PAD_DOWN)){
      robotMover(inA1,inA2,inB1,inB2,0);
      Serial.println("NGUNG");}
    /////////////////////////////////////////////////
    /* if(ps2x.ButtonPressed(PSB_TRIANGLE)){
      if(ps2x.Analog(PSAB_TRIANGLE)==0){Serial.println("GAP");g4=40;}    
    }   
    if(ps2x.ButtonReleased(PSB_TRIANGLE)){Serial.println("NHA");g4=120;}*/
    /////////////////////////////////////////////////
    
    vibrate = ps2x.Analog(PSAB_CROSS); // nút X  
    if (ps2x.NewButtonState()) {        
      if(ps2x.Button(PSB_L1)){
        Serial.println("L1 pressed");
        pwm1=pwm1+10;
        if(pwm1>=255){pwm1=255;}
        Serial.println(pwm1);
      }  
      if(ps2x.Button(PSB_L2)){
        Serial.println("L2 pressed");
        pwm1=pwm1-10;
        if(pwm1<=0){pwm1=0;}
        Serial.println(pwm1);
      }  
      if(ps2x.Button(PSB_R1))
        {
        Serial.println("R1 pressed");
        pwm2=pwm2+10;
        if(pwm2>=255){pwm2=255;}
        Serial.println(pwm2);
      }  
      if(ps2x.Button(PSB_R2))
        {
        Serial.println("R2 pressed");
        pwm2=pwm2-10;
        if(pwm2<=0){pwm2=0;}
        Serial.println(pwm2);
      }  
    }
 
    if(ps2x.Button(PSB_CIRCLE)) // Nút tròn
    {              
      if(ps2x.Analog(PSS_LX)>200){
        g4+=2;
        if(g4>180)g4=180;
        }
      if(ps2x.Analog(PSS_LX)<50){
        g4-=2;
        if(g4<0)g4=0;
        }}
 //////////////////////////////////////////////////////        
     if(ps2x.Button(PSB_CROSS)) {    
      if(ps2x.Analog(PSS_LX)>200){
        g1+=2;
        if(g1>180)g1=180;
        }
      if(ps2x.Analog(PSS_LX)<50){
        g1-=2;
        if(g1<0)g1=0;
        }        
      if(ps2x.Button(PSB_L1)){
        g2+=2;
        if(g2>180)g2=180;
        }
      if(ps2x.Button(PSB_L2)){
        g2-=2;
        if(g2<0)g2=0;
        } 
      }        
   /////////////////////////////////////////       
       if(ps2x.Button(PSB_SQUARE)) { 
           
      if(ps2x.Button(PSB_L1)){
        g3+=2;
        if(g3>180)g3=180;
        }
      if(ps2x.Button(PSB_L2)){
        g3-=2;
        if(g3<0)g3=0;
        } 
       }
   //////////////////////////////////////////// 
    if(ps2x.Button(PSB_TRIANGLE)) { 
      if(ps2x.Analog(PSS_LX)>200){
        g5+=2;
        if(g5>180)g5=180;
        }
      if(ps2x.Analog(PSS_LX)<50){
        g5-=2;
        if(g5<0)g5=0;
        } }
   ////////////////////////////////////////////     
   
  
  analogWrite(pwm11,pwm1);
  analogWrite(pwm22,pwm2);
  
   s1.write(g1);
   s2.write(g2);
   s3.write(g3);
   s4.write(g4);
   s5.write(g5);
}

void autorun(){
  
  robotMover(inA1,inA2,inB1,inB2,1);
  
  timer.setTimeout(1000L,robotMover);
  Serial.println(" step 1");
  v=speedmotor();
  robotMover(inA1,inA2,inB1,inB2,2);
  Serial.println(" step 2");

  timer.setTimeout(1000L,robotMover);
  thang(inA1, inA2, inB1, inB2, 0.2);// s = 0.2
  Serial.println(" step 3");
  robotMover(inA1,inA2,inB1,inB2,0);  
  Serial.println(" step 4");
  Serial.println("Dừng");
  timer.setTimeout(1000L,robotMover);
  testgapvat(inA1, inA2, inB1, inB2, mau1);
  Serial.println(" step 5");
  dem = 0;
  robotMover(inA1,inA2,inB1,inB2,0);  
  Serial.println(" step 6");
  Serial.println("Dừng");
  timer.setTimeout(1000L,robotMover);
  pulses =0;
  robotMover(inA1,inA2,inB1,inB2,1);
  Serial.println(" step 7");
  timer.setTimeout(2000L,robotMover);
  v=speedmotor();
  robotMover(inA1,inA2,inB1,inB2,2);
  Serial.println(" step 8");
  timer.setTimeout(2000L,robotMover);
  thang(inA1, inA2, inB1, inB2, 0.2);
  Serial.println(" step 9");
   robotMover(inA1,inA2,inB1,inB2,0);  
   Serial.println(" step 10");
  Serial.println("Dừng");
  timer.setTimeout(2000L,robotMover);
  Serial.println(" step 11");
  testgapvat(inA1, inA2, inB1, inB2, mau2);
  Serial.println(" step 12");
  dem = 0;
  v=speedmotor();
  thang(inA1, inA2, inB1, inB2, 0.2);
  Serial.println(" step 13");
  v=speedmotor();
  robotMover(inA1,inA2,inB1,inB2,0);  
  Serial.println(" step 14");
  Serial.println("Dừng");
  timer.setTimeout(1000L,robotMover);
  testgapvat(inA1, inA2, inB1, inB2, mau3);
  Serial.println(" step 15");
  robotMover(inA1,inA2,inB1,inB2,0);
  Serial.println(" step 16"); 
  timer.setTimeout(10000L,robotMover);
  Serial.println("Ket thuc");
  
  

}
void setup(){
  Serial.begin(115200);
//Motor
  pinMode(inA1, OUTPUT);//Set chân in1 của dc A là output
  pinMode(inA2, OUTPUT);//Set chân in2 của dc A là output
  pinMode(inB1, OUTPUT);//Set chân in1 của dc B là output
  pinMode(inB2, OUTPUT);//Set chân in2 của dc B là output
//toc do motor
  pinMode(enA,OUTPUT);
  pinMode(enB,OUTPUT);
  analogWrite(enA,130);
  analogWrite(enB,130);
//rada
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  srada.attach(8);
  srada.write(90);//rada o 90o
//phan biet mau
  pinMode(S0, OUTPUT);
  pinMode(S1, OUTPUT);
  pinMode(S2, OUTPUT);
  pinMode(S3, OUTPUT);
  pinMode(sensorOut, INPUT);
  digitalWrite(S0, HIGH);
  digitalWrite(S1, LOW);
//robot arm  
 s1.attach(30);  
 s2.attach(31);
 s3.attach(32);  
 s4.attach(33);
 s5.attach(34);
//Tinh van toc xe
  pinMode(PIN_DO, INPUT);
  timeOld = 0;
  attachInterrupt(digitalPinToInterrupt(PIN_DO), counter, FALLING);
//Cam bien nhiet
  dht.begin();
  timer.setInterval(1000L, sendSensor);
  timer.setInterval(1000L, ReadColor);
  //timer.setInterval(1000L, app);
  //timer.setInterval(1000L, BLYNK_WRITE(V3));
// Set ESP8266 baud rate
  EspSerial.begin(ESP8266_BAUD);
  delay(10);
//Test connect Blynk
  Serial.println("Connecting to Blynk Server");
  Blynk.begin(auth, wifi, ssid, pass, "192.168.43.249",8080);
  Serial.println("Connection etablished!");
//Button
  pinMode(button, INPUT);
//RF
    error = ps2x.config_gamepad(PS2_CLK, PS2_CMD, PS2_SEL, PS2_DAT, pressures, rumble);
  
  if(error == 0){
    Serial.print("Đã tìm thấy bộ điều khiển ");
    Serial.print("pressures = ");
  if (pressures)
    Serial.println("true ");
  else
    Serial.println("false");
  Serial.print("rumble = ");
  if (rumble)
    Serial.println("true)");
  else
    Serial.println("false");
    Serial.println("Try out all the buttons, X will vibrate the controller, faster as you press harder;");
    Serial.println("giữ L1 hoặc R1 sẽ in ra các giá trị analog");
    Serial.println("Note: Go to www.billporter.info for updates and to report bugs.");
  }  
  else if(error == 1)
    Serial.println("No controller found, check wiring, see readme.txt to enable debug. visit www.billporter.info for troubleshooting tips");
   
  else if(error == 2)
    Serial.println("Controller found but not accepting commands. see readme.txt to enable debug. Visit www.billporter.info for troubleshooting tips");

  else if(error == 3)
    Serial.println("Controller refusing to enter Pressures mode, may not support it. ");
  type = ps2x.readType(); 
  switch(type) {
    case 0:
      Serial.print("Tay điều khiển không phù hợp ");
      break;
    case 1:
      Serial.print("DualShock Controller found ");
      break;
    case 2:
      Serial.print("GuitarHero Controller found ");
      break;
  case 3:
      Serial.print("Wireless Sony DualShock Controller found ");
      break;
   }
  analogWrite(pwm11,255);
  analogWrite(pwm22,255);
}
void loop() 
{ 
 
  Blynk.run();
  timer.run();
}

BLYNK_WRITE(V11){
gapvat();
}

BLYNK_WRITE(V12){
  testthavat();
}


BLYNK_APP_DISCONNECTED() {

Serial.println("Trying connect !");
Blynk.connect();
}

 


  BLYNK_WRITE(V3)
{
  
switch(param.asInt()){
  case 1:
    Serial.println("Auto");
    autorun();
    //timer.setTimeout(1L,autorun);
    
    Serial.println("Auto Finish");
    controlapp();
    Serial.println("Control Finish");
    break;
  case 2:
  
    Serial.println("Manual");
    controlapp();
    break;
  case 3:
  
    Serial.println("RF");
    controlRF();
    timer.setInterval(1/1000000L, controlRF);
    break;

  }
} 

A timer command starts the countdown and lets the the code move onto the next line, and so on.

Meanwhile as the countdown reaches the end, the referenced function is called.

So basically each and every timeout timer is starting countdown at the same time as your code runs that loop, thus all your movement functions are all running at the same time, based on whether they are set for 1, 2 or 10 seconds.

If you want them to work consecutively, you need to look at nesting them… Start one timeout timer, then in that timers function, do the moves and start the next timout timer and so on…

Can you give me an example ? Please !!

Pseudo code style :stuck_out_tongue:

Start Function A…

  • do something then
  • Start a time out timer for 1 second that (when finished) calls Function B

Function B…

  • do something then
  • Start another timeout timer for 1 second that (when finished) calls Function C

Function C…

  • do something then
  • Start another timeout timer for 1 second that (when finished) calls Function D

… And so on, and so on…

You can also play around with the order of the commands in case your “something” takes 1.8 seconds and you want to start “something new” right after, then you do it like this…

Start Function A…

  • Start a time out timer for 2 seconds that (when finished) calls Function B
  • do something that takes 1.8 seconds

Function B…

  • Start a time out timer for 2 seconds that (when finished) calls Function C
  • do something new that takes 1.8 seconds

… Etc.

Thank you very much !! Do you have example code ??

Only if I take my own time to make it and test it… but I will leave that up to you, as it is not Blynk specific and you need to learn yourself a bit of coding anyhow, if you expect to make a functional robot rover (which is what your code seems to be for).

You must know enough to have written or pieced together your existing code, so you shouldn’t need me to write more of it for you.

1 Like