我正在尝试使用 Wifi Shield 将 UDP 数据包从 Android 应用程序发送到 Arduino,但我不能,它会引发异常(Ex3)。我想用 Arduino 与 Android 手机通信,用这个 Shield 发送命令。
这是安卓代码:
public class MainActivity extends Activity {
String udpMsg = "hello world from UDP client ";
DatagramSocket ds = null;
Button bt;
TextView tv;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = (Button) findViewById(R.id.myButton);
tv = (TextView) findViewById(R.id.myTextView);
runUdpClient();
}
private static final int UDP_SERVER_PORT = 1050;
private void runUdpClient() {
Toast.makeText(getApplicationContext(),
"E",
Toast.LENGTH_SHORT).show();
bt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
ds = new DatagramSocket();
InetAddress serverAddr = InetAddress.getByName("192.168.1.16");
DatagramPacket dp;
dp = new DatagramPacket(str.getBytes(), udpMsg.length(),
serverAddr, UDP_SERVER_PORT);
dp.setData(str.getBytes());
ds.send(dp);
Log.d("Ok","Ok");
} catch (SocketException e) {
Toast.makeText(getApplicationContext(),
"Ex",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (UnknownHostException e) {
Toast.makeText(getApplicationContext(),
"Ex1",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(getApplicationContext(),
"Ex2",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Ex3",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
} finally {
if (ds != null) {
ds.close();
}
}
}
});
}
}
这是Arduino代码:
include <SPI.h>
include <WiFi.h>
include <WiFiUdp.h>
char ssid[] = "MySSid";
char pass[] = "00000000";
int status = WL_IDLE_STATUS;
unsigned int localPort = 1050; // local port to listen on
char packetBuffer[255]; //buffer to hold incoming packet
char ReplyBuffer[] = "acknowledged"; // a string to send back
WiFiUDP Udp;
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while(true);
}
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println("Connected to wifi");
printWifiStatus();
Serial.println("\nStarting connection to server...");
// if you get a connection, report back via serial:
Udp.begin(localPort);
}
void loop() {
// if there's data available, read a packet
int packetSize = Udp.parsePacket();
if(packetSize)
{
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remoteIp = Udp.remoteIP();
Serial.print(remoteIp);
Serial.print(", port ");
Serial.println(Udp.remotePort());
// read the packet into packetBufffer
int len = Udp.read(packetBuffer,255);
if (len >0) packetBuffer[len]=0;
Serial.println("Contents:");
Serial.println(packetBuffer);
// send a reply, to the IP address and port that sent us the packet we received
/* Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write(ReplyBuffer);
Udp.endPacket();*/
}
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
我认为问题出在ds.send(dp);
这是堆栈跟踪:
06-23 13:24:03.896: W/System.err(5915): java.lang.IllegalArgumentException
06-23 13:24:03.897: W/System.err(5915): at java.net.DatagramPacket.setData(DatagramPacket.java:183)
06-23 13:24:03.898: W/System.err(5915): at java.net.DatagramPacket.<init>(DatagramPacket.java:75)
06-23 13:24:03.898: W/System.err(5915): at java.net.DatagramPacket.<init>(DatagramPacket.java:97)
06-23 13:24:03.898: W/System.err(5915): at java.net.DatagramPacket.<init>(DatagramPacket.java:118)
06-23 13:24:03.898: W/System.err(5915): at com.example.arduino.Arduino$1.onClick(Arduino.java:52)
06-23 13:24:03.899: W/System.err(5915): at android.view.View.performClick(View.java:3517)
06-23 13:24:03.899: W/System.err(5915): at android.view.View$PerformClick.run(View.java:14155)
06-23 13:24:03.900: W/System.err(5915): at android.os.Handler.handleCallback(Handler.java:605)
06-23 13:24:03.900: W/System.err(5915): at android.os.Handler.dispatchMessage(Handler.java:92)
06-23 13:24:03.901: W/System.err(5915): at android.os.Looper.loop(Looper.java:154)
06-23 13:24:03.901: W/System.err(5915): at android.app.ActivityThread.main(ActivityThread.java:4624)
06-23 13:24:03.902: W/System.err(5915): at java.lang.reflect.Method.invokeNative(Native Method)
06-23 13:24:03.902: W/System.err(5915): at java.lang.reflect.Method.invoke(Method.java:511)
06-23 13:24:03.902: W/System.err(5915): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
06-23 13:24:03.903: W/System.err(5915): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
06-23 13:24:03.903: W/System.err(5915): at dalvik.system.NativeStart.main(Native Method)
谢谢你。