Lesson 6 MIT App Inventor - levizzzle/CS490 GitHub Wiki

Lesson 6: Involves using the MIT App Inventor in order to create an application that allows you to connect to the Arduino over bluetooth. To do this we setup the HC-SR04 UltraSonic Distance Sensor to gather data to send into our app. Additionally we added controls to turn on and off an LED using the application. As well as a background flash to yellow and the text "TOO CLOSE" when passing the 10cm distance threshold. For part 2 I connected the ESP8266 module to make connection and upload distance data to ThingSpeak. This was followed by pulling the data using an application wrote on the Raspberry Pi. This data was uploaded the Adafruit IO Dashboard in 35 second intervals and then the final reading generates a tweet that automatically gets published using the Twitter API.

Components used:

  • Arduino Uno R3
  • Breadboard
  • HC-SR04
  • Raspberry Pi 3
  • 5mm Red LED
  • 470 Ohm Resistor
  • HC-05 Bluetooth Module
  • ESP8266 Wifi Module
  • QAPASS 1602 LCD Monitor
  • MIT App Inventor
  • Twitter, ThingSpeak, and Adafuit IO Dashboard APIs

Screenshot of ThingSpeak Chart

Screenshot of Adafruit IO Dashboard

Screenshot of MIT App Inventor Block Code

Arduino Code------------------------------------------------

//Libraries
#define ledPin 13
#include <HCSR04.h>
#include <LiquidCrystal_I2C.h>
#include <SoftwareSerial.h>
#define RX 2
#define TX 3

//Constants
int triggerPin = 12; //Set trigger pin
int echoPin = 11; //Set echo pin

//Component initializers
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); //LCD screen configuration
UltraSonicDistanceSensor distanceSensor(triggerPin, echoPin); //Initialize UltraSonic Distance Senor with
SoftwareSerial esp8266(RX,TX); //Initialize ESP8266 using RX & TX

//Variables
double distance;
int state = 0;

//Thingspeak data
String AP = "QuickSpruceGoogle"; //Wifi SSID
String PASS = "1a2b3c4d5e"; //Wifi Password
String API = "DNMZ2HGCARWMABKW"; //Thingspeak API key for channel
String HOST = "api.thingspeak.com"; //Thingspeak API address
String PORT = "80"; //Communication port
int countTrueCommand;
int countTimeCommand; 
boolean found = false; 

void setup() {
  pinMode(ledPin, OUTPUT); //Define ledPin as OUTPUT
  digitalWrite(ledPin, LOW); //Turn LED OFF
  
  Serial.begin(9600); //Begin serial communication
  esp8266.begin(115200); //Begin ESP8266
  
  sendCommand("AT",5,"OK"); //AT command AT
  sendCommand("AT+CWMODE=1",5,"OK"); //AT command AT+CWMODE=1
  sendCommand("AT+CWJAP=\""+ AP +"\",\""+ PASS +"\"",20,"OK"); //AT command AT+CWJAP=\

  lcd.begin(16,2); //Set LCD starting position
  lcd.clear(); //Clear LCD screen
}
void loop() {
  distance = getDistanceData(); //Call function to pull sensor data

  String getData = "GET /update?api_key="+ API +"&"+ "field1" +"="+String(distance); //Create string data
  sendCommand("AT+CIPMUX=1",5,"OK"); //AT command AT+CIPMUX=1
  sendCommand("AT+CIPSTART=0,\"TCP\",\""+ HOST +"\","+ PORT,15,"OK"); //AT command AT+CIPSTART=0
  sendCommand("AT+CIPSEND=0," +String(getData.length()+4),4,">"); //AT command AT+CIPSEND=0
  esp8266.println(getData);delay(1500);countTrueCommand++; //Print getData to ESP8266
  sendCommand("AT+CIPCLOSE=0",5,"OK"); //AT command AT+CIPCLOSE=0
   
  Serial.println(distance); //Print distance to serial
  lcd.clear(); //Clear screen
  lcd.print(distance); //Print distance to LCD
  
 if(Serial.available() > 0){ // Checks whether data is comming from the serial port
    state = Serial.read(); // Reads the data from the serial port
 }
 if (state == '0') {
  digitalWrite(ledPin, LOW); //Turn LED OFF
  Serial.println("LED: OFF"); //Send the String "LED: ON"
  state = 0; //Set state to 0
 }
 else if (state == '1') {
  digitalWrite(ledPin, HIGH); //Turn LED ON
  Serial.println("LED: ON"); //Send the String "LED: ON"
  state = 0; //Set state to 0
 } 
 //delay(4000); //5 second delay
 //Serial.print("");
}

float getDistanceData(){
  return distanceSensor.measureDistanceCm(); //Return sensor reading
;
}

//Function for printing data
void sendCommand(String command, int maxTime, char readReplay[]) {
  //Used for monitoring connection
  //Serial.print(countTrueCommand); //Print count true command to serial
  //Serial.print(". at command => "); //Print descriptor text to serial
  //Serial.print(command); //Print command to serial
  //Serial.print(" "); //Print a space to serial
  while(countTimeCommand < (maxTime*1))
  {
    esp8266.println(command); //Print command to ESP8266
    if(esp8266.find(readReplay)) //If readReplay found
    {
      found = true; //Set found to truw
      break; //Break
    }
  
    countTimeCommand++; //Increment count time command
  }
  
  if(found == true) //If found
  {
    //Serial.println("OYI"); //Print OYI to serial
    countTrueCommand++; //Increment count true command
    countTimeCommand = 0; //Set count time command to 0
  }
  
  if(found == false) //If not found
  {
    //Serial.println("Fail"); //Print Fail to serial
    countTrueCommand = 0; //Set count true command to 0
    countTimeCommand = 0; //Set count time command to 0
  }
  
  found = false; //Set found to false
 }

Python Code------------------------------------------------

#Libraries
import sys
import time
import urllib.request as urllib2,json
from twython import Twython
from Adafruit_IO import RequestError, Client, Feed, Data

#initialize adafruit IO with client function
aio = Client('Levizzzle','aio_rteY67YQ8itPEiyn4tNNMA02ejtU')

#Twitter API data
CONSUMER_KEY = '1W3MPxmBOy5F5BaQ5Vcvak91G'
CONSUMER_SECRET = 'Am66fBLh0nrHPC1AkD0mbCivhjRzoObgg4pAA9NEsO01WFV2Af'
ACCESS_TOKEN = '524386242-YzOy9U7L5puUM3N8xthSzjbtx1bFpieIVmM84Nxb'
ACCESS_SECRET = 'fRNTlF9s4JXfOouTIqxiewIFaK0uonvZvrN2eHtzfucC7'
api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_TOKEN,ACCESS_SECRET)

#Thingspeak API data
READ_API_KEY='YP2XMIJDWOTSTWW4'
CHANNEL_ID=1090663

#Adafruit IO Dashboard data
ADAFRUIT_IO_USERNAME = "Levizzzle"
ADAFRUIT_IO_KEY = "aio_rteY67YQ8itPEiyn4tNNMA02ejtU"

#String for status
tweetStr = ""

#Send data function, sends to Adafruit IO Dashboard
def send_data():
    feeds = aio.feeds() #Sets feeds from AIO
    conn = urllib2.urlopen("http://api.thingspeak.com/channels/%s/feeds/last.json?api_key=%s" \
               % (CHANNEL_ID,READ_API_KEY)) #Thingspeak url connection
    response = conn.read() #Sets response from connection obj
    data=json.loads(response) #Creates json obj called data
    distance = data['field1'] #Set distance from field1 in data obj
    print (distance) #Print distance
    conn.close() #Close the connection
    aio.send_data(feeds[0].key,distance) #Send data to AIO

#Function to send tweet
def send_tweet():
    conn = urllib2.urlopen("http://api.thingspeak.com/channels/%s/feeds/last.json?api_key=%s" \
               % (CHANNEL_ID,READ_API_KEY)) #Connect url for thingspeak
    response = conn.read() #Sets response from connect obj
    data=json.loads(response) #Creates json obj called data
    distance = data['field1'] #Set distance from field1 in data obj
    conn.close() #Close connection
    tweetStr = "Distance reading from HC-SR04: "+str(distance)+"cm" #Create string status
    print (tweetStr) #Print the string
    api.update_status(status = tweetStr) #Send tweet using update_status function

def main():
    send_data() #Calls send data function
    
    for x in range(4): #Number of loops for pushing data to AIO
        time.sleep(35) #Time to sleep inbetween data send
        send_data() #Calls send data function
        
    send_tweet() #Calls send tweet function

if __name__ == '__main__': #To call main function on run
    main()

Link to Youtube Video

Things Learned

Lesson 6 brought many of our previous lesson experience into play. First I learned how to connect ESP8266 and HC-05 modules. Next I learned how to create an application using MIT App Inventor and how to communicate with the Arduino using bluetooth. I learned how to use the Adafruit IO Dashboard and how to read data from ThingSpeak using python. Lastly was learning how to combine all of these application to create this all in one project.

⚠️ **GitHub.com Fallback** ⚠️