Hardware Reference
In-Depth Information
First, start by importing
the libraries you need and
configuring your network connection
for the client. This is similar to what
you did for the Air-Quality Meter in
Chapter 4, but the server address will
be your computer's addesss.
Try It
/*
Joystick client
Context: Arduino
This program enables an Arduino to control one paddle
in a networked Pong game.
*/
8 Change these to match your own device
and network.
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x01 };
IPAddress ip( 192,168,1,20 );
// Enter the IP address of the computer on which
// you'll run the pong server:
IPAddress server( 192,168,1,100 );
8
You need a number of constants to
keep track of the input and output pin
numbers, the joystick's thresholds for
left and right, and the minimum time
between messages to the server. You'll
need global variables for the connec-
tion Client, the previous state of the
connect button, and the timestamp of
the last message sent to the server.
const int connectButton = 2; // the pushbutton for connecting/disconnecting
const int connectionLED = 3; // this LED indicates whether you're connected
const int leftLED = 4; // this LED indicates that you're moving left
const int rightLED = 5; // this LED indicates that you're moving right
const int left = 200; // threshold for the joystick to go left
const int right = 800; // threshold for the joystick to go right
const int sendInterval = 20; // minimum time between messages to the server
const int debounceInterval = 15; // used to smooth out pushbutton readings
Client client; // instance of the Client class for connecting
int lastButtonState = 0; // previous state of the pushbutton
long lastTimeSent = 0; // timestamp of the last server message
You should update the left and right
thresholds with the values you discov-
ered earlier while testing the joystick.
The setup() method just opens
serial and Ethernet communica-
tions and initializes the digital I/O pins.
8
void setup()
{
// initialize serial and Ethernet ports:
Ethernet.begin(mac, ip);
Serial.begin(9600);
// initialize digital inputs and outputs:
pinMode(connectButton, INPUT);
pinMode(connectionLED, OUTPUT);
pinMode(leftLED, OUTPUT);
pinMode(rightLED, OUTPUT);
delay(1000); // give the Ethernet shield time to set up
Serial.println("Starting");
}
 
Search WWH ::




Custom Search