import com.pi4j.io.gpio.*;
import com.corundumstudio.socketio.*;
public class RobotControl {
// Define motor pins
static GpioPinDigitalOutput motor1 = GpioFactory.getInstance().provisionDigitalOutputPin(RaspiPin.GPIO_01, PinState.LOW);
static GpioPinDigitalOutput motor2 = GpioFactory.getInstance().provisionDigitalOutputPin(RaspiPin.GPIO_02, PinState.LOW);
public static void main(String[] args) {
Configuration config = new Configuration();
config.setHostname("your_server_address");
config.setPort(9092);
final SocketIOServer server = new SocketIOServer(config);
server.addConnectListener(new ConnectListener() {
@Override
public void onConnect(SocketIOClient client) {
System.out.println("Connected to client");
}
});
server.addDisconnectListener(new DisconnectListener() {
@Override
public void onDisconnect(SocketIOClient client) {
System.out.println("Disconnected from client");
motor1.low();
motor2.low(); // Stop motors on disconnect
}
});
server.addEventListener("control", String.class, new DataListener<String>() {
@Override
public void onData(SocketIOClient client, String command, AckRequest ackRequest) {
switch (command) {
case "forward":
motor1.high();
motor2.high();
break;
case "backward":
motor1.low();
motor2.low();
break;
case "left":
motor1.low();
motor2.high();
break;
case "right":
motor1.high();
motor2.low();
break;
case "stop":
motor1.low();
motor2.low();
break;
default:
System.out.println("Invalid command");
}
}
});
server.start();
try {
Thread.sleep(Integer.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
}
server.stop();
GpioFactory.getInstance().shutdown();
}
}
Explanation of the Code
Explanation of the code: We’re using the Pi4J library to control GPIO pins on the Raspberry Pi. The motor1 and motor2 pins are defined, and we use them to control the motors based on the commands received through Socket.IO. Replace “your_server_address” with the actual address of your Socket.IO server. Also, make sure you have the Pi4J library properly installed on your Raspberry Pi.