Orodha ya maudhui:

SmartBin: Hatua 8
SmartBin: Hatua 8

Video: SmartBin: Hatua 8

Video: SmartBin: Hatua 8
Video: Русские горки - 9-12 серии драма 2024, Novemba
Anonim
SmartBin
SmartBin

Hili ni jambo linalowezekana kwa sababu ya kutekelezwa kwa sheria, hakuna sifa yoyote inayofaa kupata pesa kwa sababu ya utambulisho, kitambulisho kinaweza kutekelezwa kwa idadi kubwa ya wahusika, na ikiwa utafikiri juu ya utaftaji wa habari, msingi wa habari ya habari.

Para montar este projeto, ni lazima:

  • NodeMCU
  • Sensor Ultrassônico de Distancia
  • Caixa de papelão
  • Kitabu cha ulinzi
  • Cabos
  • Dispositivo Android

Hatua ya 1: Conectando O Sensor

Primeiramente, mamos efetuar a conexão entre o sensor ultrassônico na o NODEMCU. Kwa mfano, vamos conectar kama portas trigger na echo do sensor nas portas D4 na D3 do NodeMCU:

// inafafanua nambari za pini #fafanua pino_trigger 2 // D4

#fafanua pino_echo 0 // D3

Para efetuar a leitura dos dados do sensor, on the seguido o tutorial elaborado pelo FilipeFlop, disponível aqui.

kuelea cmMsec, inMsec;

microsec ndefu = ultrasonic.timing ();

cmMsec = ultrasonic.badilisha (microsec, Ultrasonic:: CM);

inMsec = kubadilisha ultrasonic. (microsec, Ultrasonic:: IN);

// Exibe informacoes hakuna mfuatiliaji wa mfululizo

Serial.print ("Distancia em cm:");

Printa ya serial (cmMsec);

Serial.print ("- Distancia em polegadas:");

Serial.println (inMsec);

Data ya kamba = Kamba (cmMsec);

Serial.println (data);

Hatua ya 2: Montando Lixeira

Agora, vamos mwezi na lixeira inteligente. Precisaremos conectar o sensor ultrassônico no “teto” ya lixeira. Kwa mfano, tumia umabo na fita isolante. Em seguida, temos que medir a distância inicial, para saber o valor para a lixeira vazia. Hakuna meu caso, foi de 26, 3cm. Esse é o valor que considerarmos para uma lixeira vazia.

Kwa njia hii, unaweza kupata kifaa chako kwa njia ya utaftaji wa kifaa chako, kwa hivyo unaweza kufanya kazi kwa njia maalum kwa kufanya kazi kwa njia tofauti na kwa muda wa miaka 4 tofauti.

// Simulando 4 lixeira

lixeiraID ndefu;

kitanzi batili () {

lixeiraID = bila mpangilio (1, 5);

}

Hatua ya 3: Pakia Para a Nuvem

Agora, precisamos enviar estes dados para a nuvem. Eu escolhi o ThingSpeak, kwa familiaridade com o mesmo. Primeiramente, ni muhimu kupiga kelele kwa njia mpya, kupokea 4 parâmetros, inaashiria ao volume de cada lixeira.

Wakati huo huo programu inaweza kutumiwa na ThingSpeak, na ni lazima tufanye kazi kwa kutumia API ya mfereji. Siga os passos netsitos hakuna tovuti rasmi.

De volta à aplicação, vamos use a a biblioteca ESP8266WiFi.h para efetuar conexão com o ThingSpeak, na uhamishaji wote.

Primeiramente, uma função para efetuar conexão com a rede (defina previamente duas variáveis, ssid e pass , contendo o identificador e a senha de sua rede).

batili connectWifi () {

Serial.print ("Kuunganisha kwa" + * ssid);

Anza WiFi (ssid, pass);

wakati (WiFi.status ()! = WL_CONNECTED) {

kuchelewesha (500);

Printa ya serial (".");

}

Serial.println ("");

Serial.print ("Conectado na rede");

Serial.println (ssid);

Serial.print ("IP:");

Serial.println (WiFi.localIP ());

}

Usanidi wa muda mrefu, matamasha yatatengeneza hali mpya.

usanidi batili () {

Serial. Kuanza (9600);

Serial.println ("Lendo dados do sensor…");

// Conectando ao Wi-Fi

unganishaWifi ();

}

E, para enviar os dados para o ThingSpeak, basta abrir uma conexão HTTP padrão, passando o número da API and os parâmetros.

batiliDataTS (kuelea cmMsec, kitambulisho kirefu) {

ikiwa (mteja.connect (seva, 80)) {

Serial.println ("Enviando dados para o ThingSpeak");

Kamba postStr = apiKey;

postStr + = "& uwanja";

postStr + = id;

postStr + = "=";

postStr + = Kamba (cmMsec);

postStr + = "\ r / n / r / n";

Serial.println (postStr);

alama ya mteja ("POST / sasisha HTTP / 1.1 / n");

mteja.print ("Mwenyeji: api.thingspeak.com / n");

alama ya mteja ("Uunganisho: funga / n");

alama ya mteja ("X-THINGSPEAKAPIKEY:" + apiKey + "\ n");

mteja.print ("Aina ya Maudhui: matumizi / x-www-form-urlencoded / n");

alama ya mteja ("Urefu wa Yaliyomo:");

alama ya mteja (postStr.length ());

alama ya mteja ("\ n / n");

alama ya mteja (postStr);

kuchelewesha (1000);

}

mteja.acha ();

}

O primeiro parâmetro corresponde à distância em centímetros encontrada pelo sensor ultrassônico. O segundo parâmetro ni ID ya lixeira ya watu wengine (que foi gerado randomicamente, um número de 1 a 4).

O ID ya lixeira hutumikia também kwa kitambulisho kwa sifa inayofaa ya kupakia kufanya ushujaa.

Hatua ya 4: Recuperando Dados Do ThingSpeak

O ThingSpeak ruhusa ya kufanya kazi kwa sababu ya kufanya mfereji wa maji, kutekelezwa kwa utaftaji wa jina la JSON. Kama tofauti tofauti kwa sababu ya kulisha hufanya malisho kwa njia ya mfereji wa maji:

www.mathworks.com/help/thingspeak/get-a-ch…

Njia hii ya kuchagua, kuchagua-kwa-moja kwa moja juu ya utaftaji wa kazi. Ondoa URL kwa eneo hili:

api.thingspeak.com/channel/CHANNEL_ID/fields/FIELD_NUMBER/last.json?api_key=API_KEY&status=true

Cada campo está descito no link informado previamente. Ni muhimu sana kwa sababu hii:

  • CHANNEL_ID: número do seu canal
  • FIELD_NUMBER: o número do campo
  • API_KEY: Chave de API do seu canal

Ni URL tu ambayo unaweza kutumia Android, kwa kutumia programu ya ThingSpeak.

Hatua ya 5: Criando Aplicação Android

Hakuna Studio ya Android, unaweza kupata Android. Para o correto funcionamento da aplicação, ni lazima usanidi kama ruhusa ya kuijua hakuna AndroidManifest.

Tumia vifaa kwa Ramani za Google, kwa sababu unahitaji kupata pegan uma chave junto ao Google. Siga os passospts is no link Obter chave de API.

Uma vez com a chave, você deve também configurá-la na aplicação.

Kitufe cha API cha API zinazotegemea Ramani za Google hufafanuliwa kama rasilimali ya kamba.

(Tazama faili "res / values / google_maps_api.xml").

Kumbuka kuwa ufunguo wa API umeunganishwa na kitufe cha usimbaji fiche kinachotumiwa kusaini APK. Unahitaji ufunguo tofauti wa API kwa kila kitufe cha usimbaji fiche, pamoja na kitufe cha kutolewa ambacho hutumiwa kutia saini APK kwa kuchapisha. Unaweza kufafanua vitufe vya utatuzi na utoe malengo katika src / debug / na src / release /.

<meta-data

android: name = "com.google.android.geo. API_KEY"

android: value = "@ kamba / google_maps_key" />

Usanidi kamili wa vifaa vya AndroidManifest anexado ao projeto.

n

Hatua ya 6: Recuperando O Feed No Android

Hakuna mtu mkuu anayeweza kutekelezwa na Android, MainActivity, 4 au 4 kwa ajili ya kujulikana kama unavyoweza kusema ThinSpeak a serem lidos:

Kamba ya kibinafsi url_a = "https://api.thingspeak.com/channel/429823/fields/1/last.json?api_key="+API_THINGSPEAK_KEY+"&status=true"; Kamba ya kibinafsi url_b = "https://api.thingspeak.com/channel/429823/fields/2/last.json?api_key="+API_THINGSPEAK_KEY+"&status=true"; Kamba ya kibinafsi url_c = "https://api.thingspeak.com/channel/429823/fields/3/last.json?api_key="+API_THINGSPEAK_KEY+"&status=true"; Kamba ya kibinafsi url_d = "https://api.thingspeak.com/channel/429823/fields/4/last.json?api_key="+API_THINGSPEAK_KEY+"&status=true";

Kwa sababu hii inaweza kutumika, unaweza kutumia utaftaji wa habari kwa Android específica, chamada JSONObject. Mais uma vez, vamos criar um objeto para cada URL:

Jibu la kituLixeiraA; Jibu la kituLixeiraB; Jibu la kituLixeiraC; Jibu la kituLixeiraD;

Para abrir a conexão com as urls, vamos usar criar uma classe auxiliar, chamada HttpJsonParser. Majina haya yanapatikana kwa sababu ya URL, ikiwa ni pamoja na URL, na kufanya hivyo ikiwa ni pamoja na ujumbe wa JSON.

umma JSONObject makeHttpRequest (String url, String method, Ramani params) {

jaribu {

Mjenzi wa Uri. Builder = mpya Uri. Builder (); URL urlObj; Kamba iliyofungwaParams = ""; ikiwa (vifungu! = batili) {kwa (Ramani. Kuingia kwa kuingia: params.entrySet ()) {builder.appendQueryParameter (entry.getKey (), entry.getValue ()); }} ikiwa [mjenzi. jenga

}

ikiwa ("PATA".sawa (njia)) {url = url + "?" + encodedParamamu; urlObj = URL mpya (url); urlConnection = (HttpURLConnection) urlObj.openConnection (); urlConnection.setRequestMethod (mbinu);

} mwingine {

urlObj = URL mpya (url); urlConnection = (HttpURLConnection) urlObj.openConnection (); urlConnection.setRequestMethod (njia); urlConnection.setRequestProperty ("Aina ya Maudhui", "programu / x-www-form-urlencoded"); urlConnection.setRequestProperty ("Urefu wa Maudhui", String.valueOf (encodedParams.getBytes (). urefu)); urlConnection.getOutputStream (). andika (encodedParams.getBytes ()); } // Unganisha kwenye seva ya urlConnection.connect (); // Soma jibu ni = urlConnection.getInputStream (); Msomaji wa BufferedReader = mpya BufferedReader (InputStreamReader mpya (ni)); StringBuilder sb = mpya StringBuilder (); Mstari wa kamba;

// Changanua majibu

wakati ((line = reader.readLine ())! = batili) {sb.append (line + "\ n"); } ni karibu (); json = sb.toString (); // Badilisha jibu kuwa JSON Object jObj = JSONObject mpya (json);

} kukamata (UnsupportedEncodingException e) {

e.printStackTrace (); } kukamata (ProtocolException e) {e.printStackTrace (); } kukamata (IOException e) {e.printStackTrace (); } kukamata (JSONException e) {Log.e ("JSON Parser", "Kosa kuchanganua data" + e.toString ()); } kukamata (Isipokuwa e) {Log.e ("Isipokuwa", "Kosa kuchanganua data" + e.toString ()); }

// kurudi kitu cha JSON

kurudi jObj;

}

}

De volta mkuu wa mtu anayeshughulika, amewasilisha maombi yako kwa barua pepe, kwa sababu wataalam wengine watafanya shughuli katikaBackground.

@Override Kamba iliyolindwa doInBackground (Kamba… vielelezo) {HttpJsonParser jsonParser = new HttpJsonParser ();

majibuLixeiraA = jsonParser.makeHttpRequest (url_a, "GET", null);

majibuLixeiraB = jsonParser.makeHttpRequest (url_b, "GET", null); majibuLixeiraC = jsonParser.makeHttpRequest (url_c, "GET", null); majibuLixeiraD = jsonParser.makeHttpRequest (url_d, "GET", null);

kurudi bure;}

Quando o método doInBackgroundé encerrado, o controle de execução do Android passa for o método onPostExecute. Maana ya jina, maoni yako ni ya Lixeira, na maarufu kwa programu mpya ya kufanya ThingSpeak:

ulinzi tupu onPostExecute (Matokeo ya Kamba) {pDialog.dismiss (); runOnUiThread (mpya Runnable () {public void run () {

// OrodhaView orodhaView = (OrodhaView) pataViewById (R.id.feedList);

Tazama mainView = (Tazama) findViewById (R.id.activity_main); ikiwa (mafanikio == 1) {jaribu {// Cria feedDetail para cada lixeira Lixeira feedDetails1 = Lixeira mpya); Lixeira feedDetails2 = mpya Lixeira (); Lixeira feedDetails3 = mpya Lixeira (); Lixeira feedDetails4 = mpya Lixeira ();

feedDetails1.setId ('A');

feedDetails1.setPesoLixo (Double.parseDouble (responseLixeiraA.getString (KEY_FIELD1))); feedDetails1.setVolumeLixo (Double.parseDouble (responseLixeiraA.getString (KEY_FIELD1)));

feedDetails2.setId ('B');

feedDetails2.setPesoLixo (Double.parseDouble (responseLixeiraB.getString (KEY_FIELD2))); feedDetails2.setVolumeLixo (Double.parseDouble (responseLixeiraB.getString (KEY_FIELD2)));

feedDetails3.setId ('C');

feedDetails3.setPesoLixo (Double.parseDouble (responseLixeiraC.getString (KEY_FIELD3))); feedDetails3.setVolumeLixo (Double.parseDouble (responseLixeiraC.getString (KEY_FIELD3)));

feedDetails4.setId ('D');

feedDetails4.setPesoLixo (Double.parseDouble (responseLixeiraDgetString (KEY_FIELD4))); feedDetails4.setVolumeLixo (Double.parseDouble (responseLixeiraDgetString (KEY_FIELD4)));

feedList.add (feedDetails1);

feedList.add (feedDetails2); feedList.add (feedDetails3); feedList.add (feedDetails4);

// Calcula dados das lixeiras

Kikokotoo cha SmartBinService = SmartBinService mpya (); kikokotoo.montaListaLixeiras (feedList);

// Vipengele vya Recupera

TextView createDate = (TextView) kuuView.findViewById (R.id.date); OrodhaView orodhaaDeLixeiras = (OrodhaView) pataViewById (R.id.lista); adapta.addAll (feedList);

// Takwimu ya kawaida

Tarehe ya sasaTime = Kalenda.getInstance (). GetTime (); SimpleDateFormat simpleDate = mpya SimpleDateFormat ("dd / MM / yyyy"); Kamba ya sasaDate = rahisiDate.format (sasaTime); kuundaDate.setText (KEY_DATE + sasaDate + ""); orodhaaDeLixeiras.setAdapter (adapta);

} kukamata (JSONException e) {

e.printStackTrace (); }

} mwingine {

Toast.makeText (MainActivity.hii, "Hitilafu fulani ilitokea wakati wa kupakia data", Toast. LENGTH_LONG). Onyesha ();

}

} }); }

Agora, na tela inicial do aplicativo, serão listados os dados de cada lixeira.

Hatua ya 7: Mostrando Hakuna Ramani

Mostrando Hakuna Ramani
Mostrando Hakuna Ramani

Ainda na atividade principal, mamos adicionar uma ação a ser relacionada ao botão Mapa, na tela inicial.

/ ** Inayoitwa wakati mtumiaji anagonga kitufe cha Mapa * / public void openMaps (View view) {Intent aim = new Intent (this, LixeiraMapsActivity.class);

// Passa orodha ya lixeiras

Kifungu cha kifungu = Kifungu kipya (); kifungu.putParcelableArrayList ("lixeiras", feedList); dhamira.putExtras (kifungu);

kuanza shughuli (dhamira);

}

Hakuna ramani, temos três ativesades a executar:

  1. marcar a posição atual kufanya caminha de lixo
  2. marcar os pontos waandishi wa habari a cada lixeira no mapa
  3. traçar a rota entre os pontos

Kwa kufanya hivyo, unaweza kutumia Maagizo ya Google API. Para desenhar as rotas, foram seguidos os passos do tutorial Kuchora maelekezo ya njia ya kuendesha kati ya maeneo mawili kwa kutumia Maagizo ya Google katika Ramani ya Google API ya Android V2

Primeiro, mamos criar localidades para cada um dos pontos que desejamos marcar:

// Maeneo

faragha LatLng ya sasa;

binafsi LatLng lixeiraA; binafsi LatLng lixeiraB; binafsi LatLng lixeiraC; binafsi LatLng lixeiraD;.

Para adicionar a posição atual no mapa, foi criado o método:

utupu wa kibinafsiLocationandAddToMap () {// Kuangalia ikiwa mtumiaji ametoa ruhusa ikiwa [ActivityCompat.checkSelfPermission (hii, android. Manifest.permission. ACCESS_FINE_LOCATION)! ACCESS_COARSE_LOCATION)! = PackageManager. PERMISSION_GRANTED) {// Kuomba ruhusa ya Location ActivityCompat.requestPermissions (hii, Kamba mpya {android. Manifest.permission. ACCESS_FINE_LOCATION}, LOCATION_REQUEST_CODE); kurudi; }

// Kuchukua eneo la mwisho linalojulikana kwa kutumia Fus

Mahali pa eneo = Huduma za Mahali. FusedLocationApi.getLastLocation (googleApiClient);

// MarkerOptions hutumiwa kuunda Alama mpya. Unaweza kutaja eneo, kichwa nk na MarkerOptions

hii.current = mpya LatLng (location.getLatitude (), location.getLongitude ()); MarkerOptions

// Kuongeza kiboreshaji kilichoundwa kwenye ramani, ikisonga kamera kwenye msimamo

markerOptions.icon (BitmapDescriptorFactory.defaultMarker (BitmapDescriptorFactory. HUE_GREEN)); System.out.println ( ++++++++++++++ Passei aqui! ++++++++++++++)); mMap.addMarker (alama ya Chaguzi);

// Sogeza kamera mara moja hadi mahali na zoom ya 15.

mMap.moveCamera (CameraUpdateFactory.newLatLngZoom (ya sasa, 15));

// Vuta karibu, uhuishaji kamera.

mMap.animateCamera (CameraUpdateFactory.zoomTo (14), 2000, null);

}

Em seguida, para cada lixeira, foram criados métodos similares ao abaixo:

binafsi batili addBinALocation () {// Kuangalia ikiwa mtumiaji ametoa ruhusa ikiwa (ActivityCompat.checkSelfPermission (hii, android. Manifest.permission. ACCESS_FINE_LOCATION)! = PackageManager. PERMISSION_GRANTED && ActivityCompat.checkSelfPermission (this, android. ACCESS_COARSE_LOCATION)! = PackageManager. PERMISSION_GRANTED) {// Kuomba ruhusa ya Location ActivityCompat.requestPermissions (hii, Kamba mpya {android. Manifest.permission. ACCESS_FINE_LOCATION}, LOCATION_REQUEST_CODE); kurudi; }

// Praça da Estação

latitudo mbili = -19.9159578; longitudo mbili = -43.9387856; this.lixeiraA = LatLng mpya (latitudo, longitudo);

MarkerOptions

markerOptions.icon (BitmapDescriptorFactory.defaultMarker (BitmapDescriptorFactory. HUE_RED)); mMap.addMarker (alama ya Chaguzi); }

Kama mafundisho ya latitudo na longitudo ya longitudo kwa njia mpya ya kufanya kazi kwa kutumia Ramani za Google, itatolewa kwa njia moja kwa moja. Kwa kweli, maeneo haya yanaweza kutekelezwa kwa njia ya moto (kwa mfano Firebase). Será a primeira evolução deste projeto!

Oútimo passo agora é traçar as rotas entre os pontos. Kwa maana, umefikiriwa kuwa muhimu, ni muhimu kutumia njia hizi, kusoma njia za Waypoints!

Je! Unapenda kituo hiki?

Kamba ya faragha GetDirectionsUrl (asili ya LatLng, LatLng dest, Orodha ya waypointsList) {

// Asili ya njia

Kamba str_origin = "asili =" + asili.latitude + "," + asili. Urefu.

// Marudio ya njia

Kamba str_dest = "marudio =" + dest.latitude + "," + dest.longitude;

// Njia za njia kando ya njia

//waypoints=optimize:true|-19.9227365, -43.9473546 | -19.9168006, -43.9361124 Kamba za njia = "waypoints = optimize: kweli"; kwa (LatLng point: waypointsList) {waypoints + = "|" + point.latitude + "," + uhakika. urefu. }

// Sensor imewezeshwa

Sense sensor = "sensor = uongo";

// Kujenga vigezo kwa huduma ya wavuti

Vigezo vya kamba = str_origin + "&" + str_dest + "&" + sensor + "&" + waypoints;

Fomati ya Pato

Pato la kamba = "json";

// Kujenga url kwa huduma ya wavuti

Kamba url = "https://maps.googleapis.com/maps/api/directions/ "+output+"?"+ parameter; System.out.println ("+++++++++++++++++ + url);

kurudi url;

}

E, kwa fim, juntando tudo no método principal da classe, onMapReady:

@Override utupu wa umma kwenyeMapReady (GoogleMap googleMap) {mMap = googleMap;

angaliaLocationandAddToMap ();

ikiwa (lixeirasList.get (0). pataVolumeLixo ()> Lixeira. MIN_VOLUME_GARBAGE

|| orodha ya lixeirasList.get (0).getPesoLixo () - 10> Lixeira. MIN_SIZE_GARBAGE) {addBinALocation (); } ikiwa (lixeirasList.get (1).getVolumeLixo ()> Lixeira. MIN_VOLUME_GARBAGE || lixeirasList.get (1).getPesoLixo ()> Lixeira. MIN_SIZE_GARBAGE) {addBinBLocation (); } ikiwa (lixeirasList.get (2).getVolumeLixo ()> Lixeira. MIN_VOLUME_GARBAGE || lixeirasList.get (2).getPesoLixo ()> Lixeira. MIN_SIZE_GARBAGE) {addBinCLocation (); } ikiwa (lixeirasList.get (3).getVolumeLixo ()> Lixeira. MIN_VOLUME_GARBAGE || lixeirasList.get (3).getPesoLixo ()> Lixeira. MIN_SIZE_GARBAGE) {addBinDLocation (); }

// Chora njia

// Kupata URL kwa API ya Maagizo ya Google

Orodha ya orodha = orodha mpya ya Array (); kuongeza.add (lixeiraB); kuongeza.add (lixeiraC); vidokezo.add (lixeiraD);

Kamba url = getDirectionsUrl (sasa, lixeiraA, alama);

Pakua Kazi ya kupakuaTask = Kazi mpya ya Upakuaji (); // Anza kupakua data ya json kutoka Google Directions API downloadTask.execute (url); }

Aqui passamos apenas pelos pontos principais. O código completo do projeto será disponibilizado para consulta.

Hatua ya 8: Hitimisho

Hili ni jambo la msingi kwa sababu ya IoT, zaidi ya hayo ikiwa watu watafanya kazi kwa njia ya utaftaji wa bidhaa kwa siku, na kwa sababu hiyo wataamua kufanya mazungumzo kati ya watu. Kwa sasa, chagua kufanya kazi ili kukamilisha, kwa ajili ya kusoma, na kwa kutumia orodha ya watu wasio na Android.

Ilipendekeza: