5. Programació de la placa Arduino
Control remot:
const int pinLED = 13; const int pinJoyX = A0; const int pinJoyY = A1; const int pinJoyButton = 6;
String envStr="";
void setup() { pinMode(pinJoyButton , INPUT_PULLUP); Serial.begin(9600); }
void loop() { int Xvalue = 0; int Yvalue = 0; bool buttonValue = false; envStr="";
Xvalue = analogRead(pinJoyX); delay(50); Yvalue = analogRead(pinJoyY); buttonValue = digitalRead(pinJoyButton); envStr += Xvalue; envStr += ","; envStr += Yvalue; envStr += "*"; Serial.print(envStr); delay(100); }
|
Codi cotxe:
#include <Servo.h>
String readStr=""; char c; String Xval; String Yval;
long intGir; long intVel;
int servoPin = 9; Servo servoMotor;
int avantPin = 10; int enreraPin = 11; int potenciaPin = 5;
void setup() { pinMode( avantPin, OUTPUT); pinMode( enreraPin, OUTPUT); pinMode( potenciaPin, OUTPUT ); Serial.begin(9600); servoMotor.attach( servoPin ); servoMotor.write(90);
digitalWrite( avantPin, LOW ); digitalWrite( enreraPin, LOW ); analogWrite( potenciaPin, 0 ); }
void loop() {
if (Serial.available() > 0) { c = char(Serial.read()); if(c=='*'){ Xval = readStr.substring(0, readStr.indexOf(',')); Yval=readStr.substring( readStr.indexOf(',')+1, readStr.length() );
intGir = Yval.toInt(); intGir = map(intGir, 0, 1024, 0, 180); servoMotor.write(intGir);
intVel = Xval.toInt();
if( intVel>512 ) { digitalWrite(avantPin,HIGH); digitalWrite(enreraPin,LOW); intVel = map(intVel, 512, 1024, 0, 150); //Es dona una potència de 150/255 ja que a l'exemple està alimentat a 9v Serial.println(intVel); analogWrite( potenciaPin, intVel ); } else { digitalWrite(avantPin,LOW); digitalWrite(enreraPin,HIGH); intVel = map(intVel, 0, 512, 150, 0); Serial.println(intVel); analogWrite( potenciaPin, intVel ); } readStr=""; } else { readStr += c; } } }
|