Hardware Reference
In-Depth Information
The main loop starts by updating
the current time, which is used to keep
track of how frequently you send to the
server. Then, it checks to see whether
the connect button has been pushed.
If it has, and the client's already
connected, the Arduino disconnects. If
it's not connected, it tries to connect.
8
void loop()
{
// note the current time in milliseconds:
long currentTime = millis();
// check to see if the pushbutton's pressed:
boolean buttonPushed = buttonRead(connectButton);
// if the button's just pressed:
if (buttonPushed) {
// if the client's connected, disconnect:
if (client.connected()) {
Serial.println("disconnecting");
client.print("x");
client.stop();
} // if the client's disconnected, try to connect:
else {
Serial.println("connecting");
client.connect(server, 8080);
}
}
Next, check whether the client's
connected to the server, and whether
enough time has elapsed since the last
time you sent to the server. If so, read
the joystick and, if it's at one extreme
or the other, send the message to the
server and turn on the appropriate
LED. If the joystick's in the middle, turn
off the LEDs. Then save the current
time as the most recent time you sent
a message.
8
// if the client's connected, and the send interval has elapsed:
if (client.connected() && (currentTime - lastTimeSent > sendInterval)) {
// read the joystick and send messages as appropriate:
int sensorValue = analogRead(A0);
if (sensorValue < left) { // moving left
client.print("l");
digitalWrite(leftLED, HIGH);
}
if (sensorValue > right) { // moving right
client.print("r");
digitalWrite(rightLED, HIGH);
}
// if you're in the middle, turn off the LEDs:
if (left < sensorValue && sensorValue < right) {
digitalWrite(rightLED, LOW);
digitalWrite(leftLED, LOW);
}
//save this moment as last time you sent a message:
lastTimeSent = currentTime;
}
You may have to adjust your sendInter-
val value, depending on the responsive-
ness of your server and the sensitivity
of your sensors. 20 milliseconds is a
good place to start, but if you find the
server slowing down with lots of clients,
make it higher.
Finally, set the state of the connection
LED using the state of the client itself.
// set the connection LED based on the connection state:
digitalWrite(connectionLED, client.connected());
}
 
Search WWH ::




Custom Search