Arduino和android之间通过以太网屏蔽进行通信
我正在使用安卓系统,用Arduino和以太网屏蔽切换我的led灯。尽管在Android和Arduino上编译时都没有问题,但它仍然无法工作。我将以太网屏蔽与我的计算机连接,并给它提供与我的计算机相同的地址 这是我的Android代码:Arduino和android之间通过以太网屏蔽进行通信,android,arduino-uno,Android,Arduino Uno,我正在使用安卓系统,用Arduino和以太网屏蔽切换我的led灯。尽管在Android和Arduino上编译时都没有问题,但它仍然无法工作。我将以太网屏蔽与我的计算机连接,并给它提供与我的计算机相同的地址 这是我的Android代码: import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; im
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.ToggleButton;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/********************************/
/* Define all the buttons */
/********************************/
Switch led1 = (Switch) findViewById(R.id.Led1);
/*******************************************************/
/* Set an onclick/onchange listener for every button */
/*******************************************************/
led1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
/* Switch is led 1 */
new Background_get().execute("led1=1");
} else {
new Background_get().execute("led1=0");
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/*****************************************************/
/* This is a background process for connecting */
/* to the arduino server and sending */
/* the GET request withe the added data */
/*****************************************************/
private class Background_get extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try {
/* Change the IP to the IP you set in the arduino sketch */
URL url = new URL("http://169, 254, 128, 184/?" + params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder result = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
result.append(inputLine).append("\n");
in.close();
connection.disconnect();
return result.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
导入android.os.AsyncTask;
导入android.support.v7.app.AppActivity;
导入android.os.Bundle;
导入android.view.Menu;
导入android.view.MenuItem;
导入android.view.MotionEvent;
导入android.view.view;
导入android.widget.Button;
导入android.widget.CompoundButton;
导入android.widget.Switch;
导入android.widget.ToggleButton;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStreamReader;
导入java.net.HttpURLConnection;
导入java.net.URL;
公共类MainActivity扩展了AppCompatActivity{
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/********************************/
/*定义所有按钮*/
/********************************/
开关led1=(开关)findViewById(R.id.led1);
/*******************************************************/
/*为每个按钮设置onclick/onchange侦听器*/
/*******************************************************/
led1.setOnCheckedChangeListener(新建CompoundButton.OnCheckedChangeListener(){
检查更改后的公共无效(复合按钮视图,布尔值已检查){
如果(已检查){
/*开关为led 1*/
新背景_get().execute(“led1=1”);
}否则{
新背景_get().execute(“led1=0”);
}
}
});
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(右菜单菜单菜单主菜单);
返回true;
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
//处理操作栏项目单击此处。操作栏将
//自动处理Home/Up按钮上的点击,只要
//在AndroidManifest.xml中指定父活动时。
int id=item.getItemId();
//noinspection SimplifiableIf语句
if(id==R.id.action\u设置){
返回true;
}
返回super.onOptionsItemSelected(项目);
}
/*****************************************************/
/*这是用于连接的后台进程*/
/*到arduino服务器并发送*/
/*包含添加数据的GET请求*/
/*****************************************************/
私有类后台\u获取扩展异步任务{
@凌驾
受保护的字符串doInBackground(字符串…参数){
试一试{
/*将IP更改为在arduino草图中设置的IP*/
URL=新URL(“http://169,254128184/?“+参数[0]);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
BufferedReader in=新的BufferedReader(新的InputStreamReader(connection.getInputStream());
StringBuilder结果=新建StringBuilder();
字符串输入线;
而((inputLine=in.readLine())!=null)
result.append(inputLine.append(“\n”);
in.close();
连接断开();
返回result.toString();
}捕获(IOE异常){
e、 printStackTrace();
}
返回null;
}
}
}
这是Arduino代码:
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(169, 254, 128, 184);
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
// Pin 5
pinMode(5, OUTPUT);
}
void loop() {
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
Serial.println("new client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
String buffer = "";
while (client.connected()) {
if (client.available()) {
char c = client.read();
Serial.write(c);
buffer += c;
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close");
// the connection will be closed after completion of the response
client.println("Refresh: 5");
// refresh the page automatically every 5 sec
client.println();
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
buffer = "";
} else if (c != '\r') {
if (buffer.indexOf("GET /?led1=1") >= 0) { // If led1 = 1
digitalWrite(5, HIGH); // led 1 > on
}
if (buffer.indexOf("GET /?led1=0") >= 0) { // If led1 = 0
digitalWrite(5, LOW); // led 1 > off
}
} else {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
Serial.println("client disconnected");
}
}
#包括
#包括
//在下面输入控制器的MAC地址和IP地址。
//IP地址将取决于您的本地网络:
字节mac[]={
0xDE、0xAD、0xBE、0xEF、0xFE、0xED
};
ip地址ip(169254 128 184);
//初始化以太网服务器库
//具有要使用的IP地址和端口
//(HTTP的默认端口为80):
以太网络服务器(80);
无效设置(){
//打开串行通信并等待端口打开:
Serial.begin(9600);
而(!串行){
;//等待串行端口连接。仅本机USB端口需要
}
//启动以太网连接和服务器:
以太网开始(mac,ip);
server.begin();
串行打印(“服务器位于”);
Serial.println(Ethernet.localIP());
//引脚5
pinMode(5,输出);
}
void循环(){
//侦听传入的客户端
EthernetClient=server.available();
如果(客户){
Serial.println(“新客户”);
//http请求以一个空行结束
布尔currentLineIsBlank=true;
字符串缓冲区=”;
while(client.connected()){
if(client.available()){
char c=client.read();
串行写入(c);
缓冲区+=c;
//如果你已经到了这一行的末尾(收到了一条新行)
//字符)且该行为空,则http请求已结束,
//所以你可以发送回复
如果(c='\n'&¤tLineIsBlank){
//发送标准http响应头
client.println(“HTTP/1.1200ok”);
client.println(“内容类型:text/html”);
client.println(“连接:关闭”);
//响应完成后,连接将关闭
client.println(“刷新:5”);
//每5秒自动刷新一次页面
client.println();
打破
}
如果(c=='\n'){
//你在开一条新的生产线
currentLineIsBlank=true;
缓冲区=”;
}如果(c!='\r'),则为else{
if(buffer.indexOf(“GET/?led1=1”)>=0{//if led1=1
digitalWrite(5,高);//led 1>打开
}
if(buffer.indexOf(“GET/?led1=0”)>=0{//if led1=0
数字写入(5,低);//led 1>关闭
}
}否则{
//你已经有了一个角色
#include "etherShield.h"
#include "ETHER_28J60.h"
int led2 = 7;
int led1 = 6;
static uint8_t mac[6] = {0xAA, 0xBB, 0xCC, 0xDD, 0xBB, 0xAA}; // this just needs to be unique for your network,
// so unless you have more than one of these boards
// connected, you should be fine with this value.
static uint8_t ip[4] = {192, 168, 0, 15}; // the IP address for your board. Check your home hub
// to find an IP address not in use and pick that
// this or 10.0.0.15 are likely formats for an address
// that will work.
static uint16_t port = 80; // Use port 80 - the standard for HTTP
ETHER_28J60 e;
void setup(){
e.setup(mac, ip, port);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
}
void loop(){
char* params;
if (params = e.serviceRequest()){
if (strcmp(params, "?cmd=1") == 0){digitalWrite(led1, HIGH);}
if (strcmp(params, "?cmd=2") == 0){digitalWrite(led1, LOW); }
if (strcmp(params, "?cmd=3") == 0){digitalWrite(led2, HIGH);}
if (strcmp(params, "?cmd=4") == 0){digitalWrite(led2, LOW); }
e.respond();
}
}
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View led1on = findViewById(R.id.led_1on);
View led1off = findViewById(R.id.led_1off);
View led2on = findViewById(R.id.led_2on);
View led2off = findViewById(R.id.led_2off);
led1on.setOnClickListener(this);
led1off.setOnClickListener(this);
led2on.setOnClickListener(this);
led2off.setOnClickListener(this);
}
public void commandArduino(String url){
try {
HttpClient httpclient = new DefaultHttpClient();
httpclient.execute(new HttpGet(url));
} catch (Exception e) {}
}
public void onClick(View thisView) {
switch(thisView.getId()){
case R.id.led_1on: commandArduino("http://192.168.0.15/?cmd=1"); break;
case R.id.led_1off: commandArduino("http://192.168.0.15/?cmd=2"); break;
case R.id.led_2on: commandArduino("http://192.168.0.15/?cmd=3"); break;
case R.id.led_2off: commandArduino("http://192.168.0.15/?cmd=4"); break;
}
}
}