create a method that returns the variable HUMIDITY; But I need to make a Thread to update the value of the humidity every now and then. (The humidity is read through the Arduino). Is it necessary to make a thread or not the need?
Here's the code:
public class ConexaoBluetooth {
public static void main(String[] args) {
String URL = "btspp://301411281471:1;authenticate=false;encrypt=false";
int conexao=1;
try {
OutputStream outStream;
InputStream inStream;
StreamConnection streamConnection = (StreamConnection) Connector.open(URL);
outStream = streamConnection.openOutputStream();
inStream = streamConnection.openInputStream();
while (conexao ==1){
outStream.write('1'); // envia p/ arduino
outStream.flush();
int umidade = inStream.read(); // le a umidade do arduino
int agua = inStream.read();
System.out.println("Umidade" + umidade);
if (agua==1){
System.out.println("Caixa d'agua vazia");
}
if(agua==0){
System.out.println("Água OK");
}
}
outStream.close();
inStream.close();
} catch (IOException e) {
System.out.println("Conexão falhou...");
conexao=0;
e.printStackTrace();
}
}
}
Note: Main method n is required.
Arduino Cod:
include <SoftwareSerial.h>
SoftwareSerial bt(6,7 ); // RX TX
int caractere; //caracter do blue
int umidade;
int statusBoia;
//Porta ligada ao pino IN1 do modulo teste relé
int porta_rele1 = 10;//rele
int pinAgua = 11; //boiA
int pinboia = 9; //led
int pinOFF = 3; //led bluetooth(recebe do java)
void setup()
{
bt.begin(9600); // Configuracão da porta serial pora o software para comunicar com o modulo HC-05
bt.flush(); // confirma e limpa o Buffer
delay(300); //
Serial.begin(9600);
//Define pinos para o rele como saida
pinMode(porta_rele1, OUTPUT);
//nivel de agua
pinMode(pinAgua,INPUT);
pinMode(pinboia,OUTPUT);
}
void loop()
{
//agua
if(digitalRead(pinAgua)==LOW){
digitalWrite(pinboia,LOW);
statusBoia=0;
// TEM AGUA
}else{
digitalWrite(pinboia,HIGH); // N TEM AGUA
statusBoia=1;
}
//fim agua
umidade = analogRead(A0);
int Porcento = map(umidade, 1023, 0, 0, 100);
Serial.print(Porcento);
Serial.println("%");
if(Porcento <=60 && digitalRead(pinAgua)==HIGH)
{
digitalWrite(porta_rele1, LOW); //Liga rele 1
Serial.println("Irrigando...");
}
else {
digitalWrite(porta_rele1, HIGH); //Desliga rele 1
Serial.println("Umidade Suficiente...");
}
//testes java
while (bt.available()) {
caractere = bt.read(); // recebe do java e lga o led
if(caractere == '1') {
digitalWrite(pinOFF,HIGH); }
bt.write(Porcento);// passando umidade para o java
bt.flush();
bt.write(statusBoia);
bt.flush();
}
delay(1000);
}