Hi. I am trying to control two DC motors using an Arduino Mega 2560 and an adafruit motorshield v1. I want to be able to control the motors using the 'w' 'a' 's' and 'd' keys. I stripped the code down to get one motor working in both directions just to keep it simple for noe. Once I accomplish this, I will add the other motor.
The Arduino code alone works fine. When I upload the code and open the serial monitor up, I am able to control the direction of my motor with the 'W' and 'X' keys (Currently I am using the 'S' key to release the motor, but I will change that after I successfully implement the code with processing.) Now when I try to run the processing code I was expecting that it would send data through the serial port to Arduino to get the motors to run without the Arduino serial monitor. The idea is to have it where if I hold the 'w' key down, the motor will run forward. When I release the key the motor will stop.
I hope someone with knowledge on the subject can take a look at the code and point out where I am going wrong.
Arduino Code
#include <AFMotor.h> //Include adafruit motorshield V1 library
//Select which terminal M!, M2, M3, or M4. Depends on motor wiring
AF_DCMotor TestMotor(4);
char val; //Data recieved from serial port
int incomingByte; //a variable to read incoming serial data
void setup() {
Serial.begin(9600); //set up Serial library at 9600 bps
Serial.println("Adafruit Motorshield v1 -DC Motor Test.");
//Set the speed to start, from 0 (off) (max speed)
TestMotor.setSpeed(200);
}
void loop() {
// see if there's incoming serial data:
if(Serial.available() > 0) {
// read the oldest byte in the serial buffer:
incomingByte =Serial.read();
//If W is pressed, run motor forward
if (incomingByte == 'W' || incomingByte == 'w') {
TestMotor.setSpeed(200);
TestMotor.run(FORWARD);
}
//If "X" is pressed, run motor backwards
if (incomingByte == 'X' || incomingByte == 'x') {
TestMotor.setSpeed(200);
TestMotor.run(BACKWARD);
}
if (incomingByte == 'S' || incomingByte == 's') {
TestMotor.run(RELEASE);
}
}
}
Processing Code:
import processing.serial.*;
//use the Serial library
Serial myPort;
//Create object from Serial class
int standBy = 0;
void setup() {
size(200, 200); //set window size
String portName = Serial.list()[0]; //list serial ports
myPort = new Serial(this, portName, 9600); //initialize the serial port object
}
void draw() { //this is like the 'loop' section of code on Arduino
background(255);
}
void keyPressed() {
//if the key is "W"
if ( key == 'W' ){
//Forward Movement
myPort.write(key);
println("Forward");
}
//if the key is "X"
if ( key == 'X' ){
//Reverse Movement
myPort.write(key);
println("Reverse");
}
}
void keyReleased() {
if ( key == 'W' ){
myPort.write(standBy);
println("RC Car is on stand-by.");
}
if ( key == 'X' ){
myPort.write(standBy);
println("RC Car is on stand-by.");
}
}