/**
*    文件: 电机驱动.ino      by 零知实验室(www.lingzhilab.com)
*    -^^- 零知开源，让电子制作变得更简单！ -^^-
*    时间: 2018/10/13 15:01
*    说明: 
**/





//控制命令

#define	STOP 		0

#define	FORWARD		1

#define	BACKWARD	2

#define	TURNLEFT	3

#define	TURNRIGHT	4



//电机控制引脚

#define LEFT_MOTOR1 2

#define LEFT_MOTOR2	3

#define RIGHT_MOTOR1 4

#define RIGHT_MOTOR2 5

#define LEFT_ENA 11

#define RIGHT_ENB 12



int LED_STATE = 0;



/**

*	根据命令点击进行相应动作

* 	cmd 命令

*/



int highSpeed = 200;

int lowSpeed = 100;



void motor_run(int cmd)

{

	switch(cmd)

	{

		case FORWARD:

			Serial.println("FORWARD"); //输出状态

			analogWrite(LEFT_ENA,highSpeed);

			digitalWrite(LEFT_MOTOR1, LOW);

			digitalWrite(LEFT_MOTOR2, HIGH);

			analogWrite(RIGHT_ENB,highSpeed);

			digitalWrite(RIGHT_MOTOR1, LOW);

			digitalWrite(RIGHT_MOTOR2, HIGH);

		break;

		case BACKWARD:

			Serial.println("BACKWARD"); //输出状态

			digitalWrite(LEFT_MOTOR1,  HIGH);

			digitalWrite(LEFT_MOTOR2, LOW);

			digitalWrite(RIGHT_MOTOR1, HIGH);

			digitalWrite(RIGHT_MOTOR2, LOW);

		break;

		case TURNLEFT:

			Serial.println("TURN  LEFT"); //输出状态

			analogWrite(LEFT_ENA,lowSpeed);

			analogWrite(RIGHT_ENB,highSpeed);

			digitalWrite(LEFT_MOTOR1, LOW);

			digitalWrite(LEFT_MOTOR2, HIGH);//C

			digitalWrite(RIGHT_MOTOR1, LOW);

			digitalWrite(RIGHT_MOTOR2, HIGH);

		break;

		case TURNRIGHT:

			Serial.println("TURN  RIGHT"); //输出状态

			analogWrite(LEFT_ENA,highSpeed);

			analogWrite(RIGHT_ENB,lowSpeed);

			digitalWrite(LEFT_MOTOR1, LOW);

			digitalWrite(LEFT_MOTOR2, HIGH);

			digitalWrite(RIGHT_MOTOR1, LOW);//C

			digitalWrite(RIGHT_MOTOR2, HIGH);

		break;

		case STOP:

		default:

			Serial.println("STOP"); //输出状态

			digitalWrite(LEFT_ENA,1);

			digitalWrite(RIGHT_ENB,1);

			digitalWrite(LEFT_MOTOR1, LOW);

			digitalWrite(LEFT_MOTOR2, LOW);

			digitalWrite(RIGHT_MOTOR1, LOW);

			digitalWrite(RIGHT_MOTOR2, LOW);

		break;

	}

}





void setup() {

    // put your setup code here, to run once:

	

	Serial.begin(9600);

	

	pinMode(LED_BUILTIN, OUTPUT);

	

	pinMode(LEFT_MOTOR1, OUTPUT);

	pinMode(LEFT_MOTOR2, OUTPUT);

	pinMode(RIGHT_MOTOR1, OUTPUT);

	pinMode(RIGHT_MOTOR2, OUTPUT);

	pinMode(LEFT_ENA,OUTPUT);

	pinMode(RIGHT_ENB,OUTPUT);

	

	motor_run(STOP);

	

}





void loop() {

    // put your main code here, to run repeatedly:



	int cmd = 1;



	motor_run(cmd);



	delay(1000);

	

	motor_run(0);

}


