Skip to content

Instantly share code, notes, and snippets.

@JustinSDK
Created July 22, 2015 03:03
Show Gist options
  • Save JustinSDK/0c1deeec201afb50a6ab to your computer and use it in GitHub Desktop.
Save JustinSDK/0c1deeec201afb50a6ab to your computer and use it in GitHub Desktop.
Arduino Yún 加 Motoduino 的網路小車(一)
#include <Wire.h>
#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>
// Yun server
YunServer server;
void setup() {
// Join i2c bus (address optional for master)
Wire.begin();
// Start bridge
Bridge.begin();
// Start Yun server
server.listenOnLocalhost();
server.begin();
}
void loop() {
// Get clients coming from server
YunClient client = server.accept();
// There is a new client?
if (client) {
// Process request
process(client);
// Close connection and free resources.
client.stop();
}
// Poll every 50ms
delay(50);
}
// Process called when the REST API is called
void process(YunClient client) {
// Read the command
if (client.readStringUntil('/') == "robot") {
robotCommand(client);
}
}
// Process robot commands
void robotCommand(YunClient client) {
// Read command and react accordingly
String command = client.readStringUntil('\r');
if (command == "stop") {
motorCommand(0, 0, 0, 0);
}
if (command == "fullfw") {
motorCommand(100, 1, 100, 1);
}
if (command == "back") {
motorCommand(100, 0, 100, 0);
}
if (command == "turnleft") {
motorCommand(75, 0, 75, 1);
}
if (command == "turnright") {
motorCommand(75, 1, 75, 0);
}
}
void motorCommand(int speed_motor_1, int dir_motor_1, int speed_motor_2, int dir_motor_2) {
Wire.beginTransmission(4);
Wire.write(speed_motor_1);
Wire.write(",");
Wire.write(dir_motor_1);
Wire.write(",");
Wire.write(speed_motor_2);
Wire.write(",");
Wire.write(dir_motor_2);
Wire.endTransmission();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment