/*************************************
 *     TIME:2023.3.9
 *     Development Team: Zhiyi Technology Co., Ltd.
 * 
 *  **************************************/

#include <IRremote.h>
#define FORWARD 0xFF02FD    //16712445 --"+" 
#define BACK    0xFF9867    //16750695--"-"
#define LEFT    0xFFE01F    //16769055--<<
#define RIGHT   0xFF906F    //16748655-->>
#define  STOP   0xFFA857    //16754775--">"

//TMI8549电机驱动芯片
#define ENA 5   //使能端，可使用PWM调速
#define INT1 7  //IN1输入端
#define INT2 8  //IN2输入端

#define RECV_PIN  2

IRrecv irrecv(RECV_PIN);
decode_results results;
unsigned long val;
unsigned long preMillis;

void setup() {
  Serial.begin(9600);
  irrecv.enableIRIn();
  pinMode(ENA, OUTPUT);   //引脚设置输出模式
  pinMode(INT1, OUTPUT);  //引脚设置输出模式
  pinMode(INT2, OUTPUT);  //引脚设置输出模式 
}

//INT1,INT2输出控制逻辑
  //INT1   INT2   OUT1    OUT2    OUT3    OUT4
  //0      0      1       0       1       0     前进
  //0      1      1       0       0       1     右转
  //1      0      0       1       1       0     左转
  //1      1      0       1       0       1     后退

void loop() {
  if (irrecv.decode(&results)){ 
    preMillis = millis();
    val = results.value;
    Serial.println(val);
    irrecv.resume();
    switch(val){
      case FORWARD: forward();  break;
      case BACK:    back();     break;
      case LEFT:    left();     break;
      case RIGHT:   right();    break;
      case STOP:    stop();     break;
      default:                  break;
    }
  }
  else{
    if(millis() - preMillis > 500){
      stop();
      preMillis = millis();
    }
  }
}

//前进
void forward(){
  analogWrite(ENA, 150);  //对ENA输入0~255的PWM波进行调速
  digitalWrite(INT1, LOW); 
  digitalWrite(INT2, LOW);  
}

//后退
void back() {
  analogWrite(ENA, 150);  //对ENA输入0~255的PWM波进行调速
  digitalWrite(INT1,HIGH);  //后退
  digitalWrite(INT2,HIGH);  
}

void stop(){
  analogWrite(ENA, 0);  //对ENA输入0~255的PWM波进行调速,设置为0停车
}

//左转
void left() {
  analogWrite(ENA, 150);  //对ENA输入0~255的PWM波进行调速
  digitalWrite(INT1,HIGH);  //左转
  digitalWrite(INT2,LOW);
}

//右转
void right() {
  analogWrite(ENA, 150);  //对ENA输入0~255的PWM波进行调速
  digitalWrite(INT1,LOW);   //右转
  digitalWrite(INT2,HIGH);
}