Created
May 11, 2020 15:02
-
-
Save Gydo194/0cff7d318074127cd41d6e88408ee704 to your computer and use it in GitHub Desktop.
quick and dirty L298N motor control for arduino
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define MOTOR1_CW 3 | |
#define MOTOR1_CCW 5 | |
#define MOTOR2_CW 6 | |
#define MOTOR2_CCW 9 | |
#define STATE_MOTOR 0 | |
#define STATE_DIRECTION 1 | |
#define STATE_SPEED 2 | |
#define BUFFER_SIZE 10 | |
typedef unsigned char u8_t; | |
u8_t buffer[BUFFER_SIZE]; | |
u8_t buffer_pos = 0; | |
u8_t motor; | |
u8_t direction; | |
u8_t speed; | |
u8_t state = STATE_MOTOR; | |
void setup() { | |
pinMode(MOTOR1_CW, OUTPUT); | |
pinMode(MOTOR1_CCW, OUTPUT); | |
pinMode(MOTOR2_CW, OUTPUT); | |
pinMode(MOTOR2_CCW, OUTPUT); | |
Serial.begin(9600); | |
} | |
void loop() { | |
u8_t input; | |
while(Serial.available() < 1); | |
Serial.println(F("Process")); | |
input = Serial.read(); | |
if(',' == input || '\n' == input) { | |
Serial.println(F("found delimiter")); | |
switch(state) | |
{ | |
case STATE_MOTOR: | |
Serial.println(F("case motor")); | |
motor = atoi(buffer); | |
Serial.print(F("Motor=")); | |
Serial.println(motor); | |
memset(buffer, 0, BUFFER_SIZE); | |
buffer_pos = 0; | |
state = STATE_DIRECTION; | |
return; | |
case STATE_DIRECTION: | |
Serial.println(F("case direction")); | |
direction = atoi(buffer); | |
Serial.print(F("Direction=")); | |
Serial.println(direction); | |
memset(buffer, 0, BUFFER_SIZE); | |
buffer_pos = 0; | |
state = STATE_SPEED; | |
return; | |
case STATE_SPEED: | |
Serial.println(F("case speed")); | |
speed = atoi(buffer); | |
Serial.print(F("Speed=")); | |
Serial.println(speed); | |
memset(buffer, 0, BUFFER_SIZE); | |
buffer_pos = 0; | |
state = STATE_MOTOR; | |
//update | |
Serial.println(F("update pins")); | |
if(motor == 1 && direction == 1) {analogWrite(MOTOR1_CW, speed); analogWrite(MOTOR1_CCW, 0);} | |
if(motor == 1 && direction == 2) {analogWrite(MOTOR1_CCW, speed); analogWrite(MOTOR1_CW, 0);} | |
if(motor == 2 && direction == 1) {analogWrite(MOTOR2_CW, speed); analogWrite(MOTOR2_CCW, 0);} | |
if(motor == 2 && direction == 2) {analogWrite(MOTOR2_CCW, speed); analogWrite(MOTOR2_CW, 0);} | |
return; | |
} | |
} | |
else | |
{ | |
Serial.print(F("append to buffer:")); | |
Serial.println(input); | |
buffer[buffer_pos++] = input; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment