创建远程arduino socket server,远程控制(好)



创建远程arduino socket server,远程控制

arduino+以太网扩展板创建socket server,再用外部程序联接端口,将arduino按写入内容作出相关动作,这个相对用URL来控制稳定性更好
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address, IP address and Portnumber for your Server below.
// The IP address will be dependent on your local network:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress serverIP(192,168,195,214);
int serverPort=8888;

// Initialize the Ethernet server library
// with the IP address and port you want to use
EthernetServer server(serverPort);

void setup()
{
// start the serial for debugging
Serial.begin(9600);
// start the Ethernet connection and the server:
Ethernet.begin(mac, serverIP);
server.begin();
Serial.println(“Server started”);//log
}

void loop()
{
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
String clientMsg =”";
while (client.connected()) {
if (client.available()) {
char c = client.read();
//Serial.print(c);
clientMsg+=c;//store the recieved chracters in a string
//if the character is an “end of line” the whole message is recieved
if (c == ‘\n’) {
Serial.println(“Message from Client:”+clientMsg);//print it to the serial
client.println(“You said:”+clientMsg);//modify the string and send it back
clientMsg=”";
}
}
}
// give the Client time to receive the data
delay(1);
// close the connection:
client.stop();
}
}

下面是JAVA的外部联接程式,其他可以不用JAVA来写,我觉得用FLEX来写,更方便。
package com.lauridmeyer.tests;

import java.io.*;
import java.net.*;


class Client
{
//Ip Adress and Port, where the Arduino Server is running on
private static final String serverIP=”192.168.195.214″;
private static final int serverPort=8888;

public static void main(String argv[]) throws Exception
{
String msgToServer;//Message that will be sent to Arduino
String msgFromServer;//recieved message will be stored here

Socket clientSocket = new Socket(serverIP, serverPort);//making the socket connection
System.out.println(“Connected to:”+serverIP+” on port:”+serverPort);//debug
//OutputStream to Arduino-Server
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
//BufferedReader from Arduino-Server
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));//

msgToServer = “Hello Arduino Server”;//Message tha will be sent
outToServer.writeBytes(msgToServer+’\n’);//sending the message
System.out.println(“sending to Arduino-Server: “+msgToServer);//debug
msgFromServer = inFromServer.readLine();//recieving the answer
System.out.println(“recieved from Arduino-Server: ” + msgFromServer);//print the answer

clientSocket.close();//close the socket
//don’t do this if you want to keep the connection
}
}

———————
作者:我视而不见
来源:CSDN
原文:https://blog.csdn.net/xhhuang1979/article/details/12857761
版权声明:本文为博主原创文章,转载请附上博文链接!