如何在Android中使用UDP从arduino接收数字输入?

时间:2013-12-07 04:34:36

标签: android udp arduino

实际上我想编写一个程序,只要在Arduino的特定数字引脚上按下按钮,Android就会使用UDP接收该信号并相应地执行任务。

这是Arduino代码段:

void loop() {
  buttonState = digitalRead(12);
  if (buttonState == HIGH) {
    // ToDo when push button is pressed
  }
  else {
    Udp.beginPacket(Udp.remoteIP(),Udp.remotePort());
    Udp.write("anything here");
    Udp.endPacket();
  }

这是我的Android代码:

public class Server implements Runnable
{
  String serverHostname1, serverHostname2;
  DatagramSocket d1;
  InetAddress ip, retiip;
  DatagramPacket send, rec;
  String modifiedSentence;
  public static String TAG = "SERVER";

  DatagramSocket serverSocket;

  public void run() {

    Log.d(TAG, "Service Started");
    try {
      serverSocket = new DatagramSocket(8032);
    } catch (SocketException e) {
      e.printStackTrace();
    }
    Log.d(TAG, "Service Started");
    byte[] receiveData = new byte[1024];
    while (true) {
      DatagramPacket receivePacket = new DatagramPacket(receiveData,
      receiveData.length);
      Log.d(TAG, "Service Started");
      try {
         serverSocket.receive(receivePacket);
      } catch (IOException e) {
        e.printStackTrace();
      }

      String sentence = new String(receivePacket.getData());
      System.out.println("RECEIVED: " + sentence);
      InetAddress IPAddress = receivePacket.getAddress();
      int port = receivePacket.getPort();
      Log.d(TAG, "Service Started");
      Log.d(TAG, "Received " + sentence);
    }
  }

0 个答案:

没有答案