The Arduino Yùn board has:
- "Arduino" microcontroller
- micro PC on which "Linux run" and a web server .
- wifi board.
I wrote the following Arduino sketch starting from the Bridge and Servo library that you can read here and here.
#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>
#include <Servo.h>
//comunication server declaration with the Linux side
YunServer server;
//Servo objects declarations
Servo myservoL;
Servo myservoR;
//function mode variable (forward, left, right, stop)
int mode;
//timeout variable to avoid run without commands
int timeout;
//Arduino setup routine
void setup() {
//servo pins declaration
myservoL.attach(9);
myservoR.attach(10);
//variables initialization
mode=0;
timeout=0;
//set pin13 for debug function
pinMode(13,OUTPUT);
//start Bridge comunication with Linux
Bridge.begin();
server.listenOnLocalhost();
server.begin();
}
void loop() {
digitalWrite(13, HIGH);
//read commands from Linux
YunClient client = server.accept();
if (client) {
//if there is a message it tries to decode
process(client);
client.stop();
}
//select actions to do according to current "mode" variable
if (mode == 1) {
gostraight();
}
if (mode == 2) {
turnleft();
}
if (mode == 3) {
turnright();
}
if (mode == 4) {
stopmode();
}
//strobe alive led
digitalWrite(13, LOW);
//slow is better
delay(50);
}
void process(YunClient client) {
String command = client.readStringUntil('/');
if (command == "mode") {
//if it's a "mode" command
modeCommand(client);
}
if (command == "state") {
//if it's a "state" command
stateCommand(client);
}
}
void modeCommand(YunClient client) {
//change the function mode
mode = client.parseInt();
if (client.read() == '/') {
//set new timeout for the new function mode
timeout = client.parseInt();
}
//answer with current function "mode" and "timeout"
client.print(mode);
client.print(F("#"));
client.print(timeout);
client.println("");
}
//answer with current function "mode" and "timeout"
void stateCommand(YunClient client) {
client.print(mode);
client.print(F("#"));
client.print(timeout);
client.println("");
}
//exec go forward command mode
void gostraight() {
if (timeout > 0) {
myservoL.write(-180);
myservoR.write(180);
timeout = timeout -1;
}
else {
stopmode();
}
}
//exec turn left command mode
void turnleft() {
if (timeout > 0) {
myservoL.write(180);
myservoR.write(180);
timeout = timeout -1;
}
else {
stopmode();
}
}
//exec turn right command mode
void turnright() {
if (timeout > 0) {
myservoL.write(-180);
myservoR.write(-180);
timeout = timeout -1;
}
else {
stopmode();
}
}
//exec stop command mode
void stopmode() {
myservoL.write(90);
myservoR.write(90);
timeout = 0;
mode=0;
}
In the next post I will talk about the web server Linux.
No comments:
Post a Comment