Salve, sto cercando dove il led connesso al mio arduino è accesso/spento attraverso un app per android. La scheda arduino è dotata dell'ethernet shield e quindi connessa in rete. Sto avendo dei problemi perchè non riesco ad accendere o spegnere il led , molto probabilmente è un problema di code. Se qualcosa riuscisse ad aiutarmi gliene sarei veramente molto grato.
Allego i codici:
Arduino:
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,0,254);
int led=3;
EthernetServer server(2000);
void setup() {
pinMode(led, OUTPUT);
digitalWrite(led, LOW);
Ethernet.begin(mac, ip);
server.begin();
Serial.begin(9600);
Serial.println("Ethernet e Android");
Serial.println();
Serial.println(Ethernet.localIP());
}
void loop() {
// wait for a new client:
EthernetClient client1 = server.available();
char thisChar = client1.read();
if (client1) {
if (thisChar=='0') {
digitalWrite(led ,LOW);
delay(500);
}
if (thisChar=='1') {
digitalWrite(led, HIGH);
delay(500);
}
}}
Java:
package com.example.cerone.arduinoledsimple;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends ActionBarActivity {
String s="0";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button pulsanteOn = (Button) findViewById(R.id.On);
Button pulsanteOff = (Button) findViewById(R.id.Off);
TextView stato = (TextView) findViewById(R.id.text);
stato.setText(s);
pulsanteOn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
s = "1";
connetti(s);
}
});
pulsanteOff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
s = "0";
connetti(s);
}
});
}
public void connetti(String s)
{
Socket socket = null;
DataInputStream dataInputStream=null;
DataOutputStream dataOutputStream=null;
try
{
socket =new Socket("192.168.1.254",2000);
dataOutputStream=new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(s);
}
catch(UnknownHostException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if(socket!=null)
{
try
{
socket.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
if(dataInputStream !=null)
{
try
{
dataInputStream.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
if(dataOutputStream !=null)
{
try
{
dataOutputStream.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}
@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);
}
}
XML :
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Stato led :"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ON"
android:id="@+id/On"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OFF"
android:id="@+id/Off"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stato :"
android:padding="20dp" />
<TextView
android:layout_width="98dp"
android:layout_height="wrap_content"
android:id="@+id/text"
android:layout_weight="0.07" />
</LinearLayout>
</LinearLayout>
Non so risponderti sulla parte android, ma posso dirti con certezza che il loop() dalla parte arduino è tutta sbagliata.
riguarda bene un esempio IDE di webserver, l'header di risposta di un client non è fatta di un char soltanto, c'è molto, molto di più da filtrare
ciao
Ciao,grazie della risposta.
Ho modificato il codice di arduino in questo modo:
#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(192,168,0,254);
int led = 3;
// 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 Leonardo only
}
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
}
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;
while (client.connected()) {
if (client.available()) {
char c = client.read();
Serial.write(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) {
Serial.println(c);
// 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();
if (c=='0') {
digitalWrite(led ,LOW);
delay(500);
}
if (c=='1') {
digitalWrite(led, HIGH);
delay(500);
}
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
}
else if (c != '\r') {
// 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 disonnected");
}
}
Ora inserendo ip e porta nell'app android(sto usando un app fatta da terzi, una volta risolto provo a farla da me), nel seriale mi viene stampato questo:
new client
GET /?out=all HTTP/1.1
Host: 192.168.0.254
Connection: Keep-Alive
client disonnected
Ma il resto non funziona.
E' un errata formattazione della pagina, si inchioda, ricontrolla.
Hai una leonardo?
se no, questo non ti serve
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
inoltre come ti ho scritto più in su non puoi controllare un solo char(c)
come vedi nella risposta c'è
GET /?out=all HTTP/1.1
composta da 22 char e ci sono diversi 1, va confrontata una stringa con indexof() e cercare un blocco di char
"out=all"
"out=1"
"out=0"
Quella stringa GET /?out=all HTTP/1.1
viene mostrata solo utlizzando un app prensente nel market legata a questo sito http://www.domotichome.net/ dove si fa riferimento a JSON, utilizzando un'altra app che crea semplicemente una client socket quella stringa non viene mostrata e mi cieve stampato (attraverso l'istruzione Serial.wirte(c) il char che io nell app inserisco ovvero quel famoso 1 che dovrebbe accendermi il led.
dove si fa riferimento a JSON,
se usa json perchè nello sketch che hai messo sopra non ci sono chiamate json?
utilizzando un'altra app che crea semplicemente una client socket quella stringa non viene mostrata e mi cieve stampato (attraverso l'istruzione Serial.wirte(c)
questo non è lo stesso sketch che hai messo sopra?
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
IPAddress ip(192, 168, 2, 177);
EthernetServer server(80);
void setup() {
Serial.begin(9600);
Ethernet.begin(mac, ip);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
}
void loop() {
EthernetClient client = server.available();
if (client) {
Serial.println("new client");
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
Serial.write(c);
if (c == '\n' && currentLineIsBlank) {
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();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.println("</html>");
break;
}
if (c == '\n') currentLineIsBlank = true;
else if (c != '\r') currentLineIsBlank = false;
}
}
delay(1);
client.stop();
}
}
guarda bene cosa viene mostrato nel serialmonitor tramite il Serial.write(c); ... centinaia di caratteri, tra i quali caratteri '0' è '1' dei parametri vari della request e tanti anche
se tu metti
if (c=='1') o if (c=='1')
non otterrai mai il tuo scopo, il tuo led si accende e si spegne ogni volta che trova uno di quei char
magari usando un "Callback", un client.println("Content-Type: application/json"); e una struttura adeguata per fare il parse json allora viene letta solo la parte interessata
un app prensente nel market legata a questo sito http://www.domotichome.net/
a me sembra fermo da 3 anni quel sito
ciao
Pablos ora con questo codice riesco a leggere i valori json sto cercando con un app di leggerli. Tu non puoi aiutarmi?
#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(192,168,0,254);
String readString;
int temp = 0;
String requestMessage;
// 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);
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
}
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;
requestMessage="";
while (client.connected()) {
if (client.available()) {
char c = client.read();
Serial.write(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: application/json;charset=utf-8");
client.println("Server: Arduino");
client.println("Connnection: close");
client.println();
int temperatureIndoor = getTemp();
int temperatureOutdoor = getTemp();
client.print("{\"arduino\":[{\"location\":\"indoor\",\"celsius\":\"");
client.print(temperatureIndoor);
client.print("\"},");
client.print("{\"location\":\"outdoor\",\"celsius\":\"");
client.print(temperatureOutdoor);
client.print("\"}]}");
client.println();
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
}
else if (c != '\r') {
// 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");
}
}
int getTemp()
{
int val = analogRead(temp);
val = (5.0 * val * 100.0)/1024.0;
val = int(val);
return val;
}
Grazie.
Ti aiuterei volentieri, ma non ho mai messo mani sul software android, però nessuno ti vieta di iscriverti ad un forum specializzato e/o di appassionati sulla programmazione android... Sicuramente li troverai un supporto completo.
Il forum androidiani. Com mi sembra molto popolato, ricco di sezioni e a giudicare dalle migliaia di treadh per ogni sezione non dovresti rimanere ignorato
Ciao