Hy,
i have Windows Form application which reads PlayStation 3 controller and sends data of speed and direction to Arduino via Serial interface.
I’m having troubles with serial communication. Received integers are not correct. Could you Pros inspect the code and suggest better method of doing this? Thanks
- Arduino sends “OK” to PC. (Arduino is ready to receive data…)
- PC reads serial data
-----if “OK” is received, respond with current GamePad values.
-----Serial.WriteLine(1,255,2,180); (1=speed, 255=motor speed, 2=direction, 180=servo position) - Arduino reads this values and use it in switch sentenc.
#include <Servo.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 34, 35, 36, 37);
int data = 0; // for incoming serial data
Servo ServoDirection; //servo for direction control
//PINS
const int ForwardBackward = 40;
const int Motor = 2;
const int ServoMotor = 9;
const int LED = 13;
void setup() {
Serial.begin(19200);
pinMode(ForwardBackward, OUTPUT);
pinMode(Motor, OUTPUT);
ServoDirection.attach(ServoMotor);
lcd.begin(16, 2);
pinMode(LED, OUTPUT);
}
void loop() {
ClearSerial(); //removes any data in serial recive buffer
lcd.setCursor(0, 0); lcd.print(" ");
//Signal PC software that I am redy!
Serial.println("OK");
Serial.flush(); //wait until serial data is send.
lcd.setCursor(0, 0); lcd.print("OK");
// send data only when you receive data:
if (Serial.available() > 0) {
// read the incoming integer:
data = Serial.parseInt();
lcd.setCursor(3, 0); lcd.print(data);
//start appropiant function
WhatToDo(data);
}
}
void WhatToDo(int data) {
switch (data) {
case 1:
//Speed control
Speed();
break;
case 2:
//Direction control
Direction();
break;
case 3:
//LED light
Light();
break;
}
}
void Speed() {
//Request speed data
data = Serial.parseInt();
lcd.setCursor(0, 1); lcd.print(data);
//Set forward or backward movement
if(data < 0) {
digitalWrite(ForwardBackward, LOW);
data *= -1; //Only positiv numbers for PWM
} else {
digitalWrite(ForwardBackward, HIGH);
}
//Set speed of Motor
analogWrite(Motor, data);
}
void Direction() {
//Request direction data (0-180)
data = Serial.parseInt();
lcd.setCursor(0, 1); lcd.print(data);
//Set servo position
ServoDirection.write(data);
}
void Light() {
//Request LED status
data = Serial.parseInt();
lcd.setCursor(0, 1); lcd.print(data);
//Switch Led on/off
if(data == 1)
digitalWrite(LED, HIGH);
else if (data == 0)
digitalWrite(LED, LOW);
}
void ClearSerial() {
while (Serial.read() > 0) {}
}