简体   繁体   English

Android和Arduino插座

[英]Android and Arduino socket

I have created a server and client with Android and Arduino but I have a problem. 我已经使用Android和Arduino创建了服务器和客户端,但是我遇到了问题。 Android reads only one time. Android仅读取一次。 Why? 为什么? this is my code: 这是我的代码:

Client Android: 客户端Android:

new Thread(new ClientThread()).start();
}

class ClientThread implements Runnable {
    @Override
    public void run() {     
        try {                   
            InetAddress serverAddr = InetAddress.getByName("192.168.1.240");        
            socket = new Socket(serverAddr, 8888);
            if(socket == null)System.out.println("SOCKET NULL");
            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())),true);
            inFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            while(true){
                msgFromServer = inFromServer.readLine();
                System.out.println(msgFromServer);

            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (socket != null) {
                System.out.println("STOP SOCKET");
                // close socket
            }
        }
    }
}

Arduino Server: Arduino服务器:

void loop() {

YunClient client = server.accept();
sensorValue = analogRead(sensorPin);    
String myString = String(sensorValue);

if (client) {
  String command = "none";
  command = client.readString();
  Serial.println(sensorValue);
  client.print(myString+"\n");
}
}

LOGCAT: logcat的:

    07-24 11:44:24.468: D/OpenGLRenderer(19693): Enabling debug mode 0
07-24 11:44:25.363: I/System.out(19693): 121

121 is the value from Arduino. 121是Arduino的值。 But this is showing only once. 但这仅显示一次。

It works only once. 它只能工作一次。 I want receive data from the Arduino every second. 我想每秒从Arduino接收数据。 Thank you guys! 感谢大伙们!

You need to take the accept out of the loop. 您需要将接受移出循环。 otherwise it send a string and wait for another connect from client. 否则,它将发送一个字符串并等待客户端的另一个连接。

YunClient client = server.accept();
void loop() {

    sensorValue = analogRead(sensorPin);    
    String myString = String(sensorValue);

    if (client) {
       String command = "none";
       command = client.readString();
       Serial.println(sensorValue);
       client.print(myString+"\n");
    }
}

Also, I don't see where the client sends something to the server. 另外,我看不到客户端将内容发送到服务器的位置。 Instead of System.out.println should't it be out.println? 而不是System.out.println应该不是out.println吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM