Tuesday, February 23, 2016

Smart Traffic Signals

MQTT Class effort

a. What I have done in the class:
I have integrated my Raspberry Pi and Arduino through MQTT, to listen and respond on photocell(sensors that allow you to detect light) readings. I used pubsubclient to test request-response on wifi. Arduino - Pubsubclient provides examples of basic tests, so that we can test pre requirements. I was the first person to complete the class task and helped others in doing the same.

Arduino - Hardware
Arduino WiFi Module
Photocell
Resistors (10k, 330 ohm)
LED
Jumping wires
Arduino - Software / MQTT
There are four main tasks the Arduino software needs to take care of for this example:
Gather light sensor readings periodically
Publish sensor readings via MQTT
Listen for commands via MQTT
Control the LED based on a setpoint
An MQTT client is created in the setup function.

Experiment overview:

The MQTT client connects (if it is not already connected).

Based on the “sensing mode” the application decides how to drive the LED.  It could be OFF, ON or SENSE.  In the SENSE case a light reading is taken and the LED is driven according to a hardcoded setpoint.

I was able to operate 3 different LED lights using mobile app with help of MQTT protocol.Below is the video which shows demonstration of the work.

Video:




Connections:





Code:


#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <String.h>

// Update these with values suitable for your network.

const char* ssid = "Pi_AP";
const char* password = "Raspberry";
//const char* mqtt_server = "broker.mqtt-dashboard.com";
const char* mqtt_server = "192.168.0.34";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
int timer = 200;
int ar[] = {15, 12, 4, 16}; 


void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}


void off() {

  for(int i = 0; i < 4 ; i++){
  digitalWrite(ar[i], LOW);
  }
  
}


void go() {
  off();
  digitalWrite(15, HIGH);
}

void stops() {
  off();
  digitalWrite(12, HIGH);
}

void yeild() {
  off();
  digitalWrite(4, HIGH);
}


void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  
  Serial.println();

  String s = "";

  for(int i = 0; i< length; i++) {
    char a = ((char)payload[i]);
    s = s + a;
  }

  if( s == "off") {
    off();
  }
  else if(s == "stop") {
    stops();
  }
  else if(s == "go") { 
    go();
  }
  else if(s == "yeild") { 
    yeild();
  }
  
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("outTopic", "hello world");
      // ... and resubscribe
      client.subscribe("inTopic");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  //pinMode(12, OUTPUT);     // Initialize the BUILTIN_LED pin as an output

  for(int i = 0; i < 4; i++){
    pinMode(ar[i],OUTPUT);     
  }
  Serial.begin(115200);

  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 1000) {
    lastMsg = now;
    ++value;
    snprintf (msg, 75, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("outTopic", msg);
    //callback();
  }

}


b. To whom I helped and What I did for them:

I was the first person to complete task of talking to MQTT server in class. I tried with example from arduino library and was able to communicate using MQTT. I explained this to entire class with help of professor. I told which program to use from code so that everyone can start MQTT communication from arduino.

I helped krishna, pavan and sandeep for executing the code for basic connection through MQTT.

c. Who helped me and What they did for me:
Pavan, Sandeep and Jorge helped to me find the coding and programing help from blogs which explains MQTT programing.


References:

  • http://www.rs-online.com/designspark/electronics/blog/building-distributed-node-red-applications-with-mqtt
  • http://jpmens.net/2013/09/01/installing-mosquitto-on-a-raspberry-pi/
  • http://pubsubclient.knolleary.net/
  • https://learn.adafruit.com/photocells/overview
  • http://m2mio.tumblr.com/post/30048662088/a-simple-example-arduino-mqtt-m2mio



Monday, February 15, 2016

Week-4-WIFI with Pi


WIFI AP using Raspberry Pi:

Current experiment is to create a Wi-Fi zone using Raspberry Pi. We will make use of Raspberry Pi and turn it into a router. We can connect to internet on other devices using new WIFI zone. I have done by following the below steps. This is a simple process to follow and in creating a customized WIFI. 

Initially I have updated the current version of packages using  sudo apt-get update

Now we need to install host access software into Pi. For this I have used "hostap" package in Raspberry Pi. 

sudo apt-get install hostapd isc-dhcp-server

Next step is setting DHCP server on Pi. For this we need to modify the existing files. Open the file dhcpd.conf

sudo nano /etc/dhcp/dhcpd.conf

We have 3 things to do here

1) Comment the below lines in file:

option domain-name "example.org";
option domain-name-servers ns1.example.org, ns2.example.org;

2) Uncomment the following line of code in file:

# If this DHCP server is the official DHCP server for the local
# network, the authoritative directive should be uncommented.
authoritative;

3) Add the following code at bottom of the page:

subnet 192.168.42.0 netmask 255.255.255.0 {
range 192.168.42.10 192.168.42.50;
option broadcast-address 192.168.42.255;
option routers 192.168.42.1;
default-lease-time 600;
max-lease-time 7200;
option domain-name "local";
option domain-name-servers 8.8.8.8, 8.8.4.4;
}


after completeing above 3 steps save the file and return.

Next open the file isc-dhcp-server

Find the following line in file INTERFACES=""  and update this to INTERFACES="wlan0" 

Save the file and return

Make sure that wlan0 is not active. Make it inactive using command  
sudo ifdown wlan0

Next we will set up the wlan0 connection to be static and incoming.
run sudo nano /etc/network/interfaces to edit the file

Find the line "auto wlan0" and comment it, if it is in the file. Comment each line after the current line also.

add the below lines into the file 

iface wlan0 inet static
  address 192.168.42.1
  netmask 255.255.255.0
  
Save the file and return.

Assign a static IP address to the wifi adapter by running 
sudo ifconfig wlan0 192.168.42.1

Now setting password for the network. For this we need to create a file and write into it. I am setting my password as Bhargav

create file using command 
sudo nano /etc/hostapd/hostapd.conf


Write the following code into file :

interface=wlan0
driver=rtl871xdrv
ssid=Pi_AP
hw_mode=g
channel=6
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_passphrase=Bhargav
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCMP


save the file and return

Now we need to setup configuration file for Raspberry Pi. 
Run sudo nano /etc/default/hostapd

Find the line #DAEMON_CONF="" and edit it so it says DAEMON_CONF="/etc/hostapd/hostapd.conf"

Save the file and return


Configure Network Address Translation

This will allow multiple clients to connect to the WIFI network. Open the file "sysctl.conf" using the following command sudo nano /etc/sysctl.conf

At bottom of the file add line. This will start IP forwarding on boot up

net.ipv4.ip_forward=1


Save the file and return

sudo sh -c "echo 1 > /proc/sys/net/ipv4/ip_forward"

Run the following commands to create the network translation between the ethernet port eth0 and the wifi port wlan0

sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
sudo iptables -A FORWARD -i eth0 -o wlan0 -m state --state RELATED,ESTABLISHED -j ACCEPT
sudo iptables -A FORWARD -i wlan0 -o eth0 -j ACCEPT


Now changing the configuration so that WIFI connection is ready on startup. Run the following command 
sudo sh -c "iptables-save > /etc/iptables.ipv4.nat"

Open the file iptables.ipv4.nat using command  
sudo nano /etc/network/interfaces

add the below line at end of file 
up iptables-restore < /etc/iptables.ipv4.nat

Save the file and return


Updating the software so that the WIFI hardware is supported. Follow the below steps to setup software 

To download 

wget   http://adafruit-download.s3.amazonaws.com/adafruit_hostapd_14128.zip

To install 

unzip adafruit_hostapd_14128.zip
sudo mv /usr/sbin/hostapd /usr/sbin/hostapd.ORIG
sudo mv hostapd /usr/sbin

Give permission for execution

sudo chmod 755 /usr/sbin/hostapd

WIFI zone on every restart

Now we are all set to set our own WIFI using Raspberry Pi. This can be hosted using following command 

 sudo /usr/sbin/hostapd /etc/hostapd/hostapd.conf

 This displays the name of your WIFI on other devises. You can select the newly created WIFI and connect to it using the password. 

 Here are the images of my WIFI zone.

 This images shows the list of available WIFI networks. "BHARGAV-AP" is my WIFI. 





 This image shows that I have conected to my WIFI on my mobile.



 This image is to show that Arduino client is able to access the WIFI created using Raspberry Pi. This is showing the available WIFI which could be accessible.



 This images shows that Arduino client is able to connect to the newly created WIFI. 





Reference:
https://learn.adafruit.com/setting-up-a-raspberry-pi-as-a-wifi-access-point/install-software

Sunday, February 14, 2016

Week - 4 MQTT Tutorial

MQTT:

MQTT is described as a machine-to-machine(M2M)/IoT connectivity protocol. MQTT is so lightweight that it can be supported by some of the smallest measuring and monitoring devices, and it can transmit data over far reaching, sometimes intermittent networks. MQTT is a publish/subscribe messaging transport protocol that is optimized to connect physical world devices and events with enterprise servers and other consumers. MQTT is designed to overcome the challenges of connecting the rapidly expanding physical world of sensors, actuators, phones, and tablets with established software processing technologies. These principles also turn out to make this protocol ideal for the emerging M2M or IoT world of connected devices where bandwidth and battery power are at a premium.


Web Links:

Following are the web links which are references for tutorial related to usage and software of MQTT protocol along with ESP8266 and Raspberry Pi.

http://www.penninkhof.com/2015/05/linking-the-esp8266-a-raspberry-pi-through-mqtt/
http://iot-playground.com/blog/2-uncategorised/76-easyiot-cloud-mqtt-api
http://iot-playground.com/build
http://mqtt.org/tag/arduino
https://github.com/tuanpmt/esp_mqtt
http://tech.scargill.net/mqtt-on-arduino/
https://github.com/tuanpmt/espduino
http://www.instructables.com/id/An-inexpensive-IoT-enabler-using-ESP8266/?ALLSTEPS
http://www.makeuseof.com/tag/meet-arduino-killer-esp8266/
http://blog.thingstud.io/recipes/how-to-make-your-raspberry-pi-the-ultimate-iot-hub/
https://www.ibm.com/developerworks/community/blogs/5things/entry/5_things_to_know_about_mqtt_the_protocol_for_internet_of_things?lang=en


Sunday, February 7, 2016

Week - 3 Arduino

Experiment 1:

Blinking LED Light

Equipment:

Arduino
LED

Procedure:

Connect Arduino to the GUI interface from a windows system. This configuration is initially done and all the required settings are made. Connect anode of LED to Ground and cathode to Input pin in Arduino D7(PIN NO : 13). This initial set ups is to be made. Then we can use in build in program to blink LED. Go to File and then select Examples. Here different kinds of examples are given, we can use them directly or modify according to our use. Go to Basics folder there select Blink file. This will open a new window with blink program. Check if the port number to which LED is connected is correctly give in the file or not. If not change it to correct port number. Upload the program. This is the process of writing program to Arduino. This will put Blink file to Arduino. This will take quite long time to load. Once the program is being written to Arduino we can observe blinking light. After that the program is loaded/written to Arduino LED starts blinking. LED will blink with time lapse mentioned in Blink file. This time lapse can be changed and blinking speed can be varied.


Video:




Code:

Blink file in Basics from Examples.

Reference: 

https://www.arduino.cc/en/Tutorial/Blink


Experiment 2:

DHT11 with Arduino

Equipment:

Arduino
DHT11
Resistor
Breadboard
Connectors

Procedure:

DHT11 is a sensor used for measuring Temperature and Humidity. I have used this with Arduino and measured temperature and humidity and stored results. Connect DHT11on breadboard. Now connect ground pin of DHT11 to Arduino ground. Data pin is connected one of the IO pins of Arduino. Other pin of DHT11 is connected to one end of resistor. Other end of resistor is connected to power supply of 3.3v. This is the required connection set up. Then we have to open file. Go to file in Arduino GUI and select examples. Then select DHT Sensor Library and select file DHTtester. Upload this file into Arduino. This will start taking temperature and humidity values from DHT11 and report in Arduino GUI. To see result we have to open window from Tools->Serial Plotter. In this window we can see temperature and humidity values.

Picture:




Results:



Code:

DHTtester from DHT Sensor Library in Examples

Reference: 

http://playground.arduino.cc/Main/DHT11Lib



Experiment 3:

Raspberry Pi setup with Arduino

Raspberry Pi can be connected to Arduino and operated. This will be same as connecting Arduino to a windows system. This is simple process to do.

Initially we install Arduino GUI in Raspberry Pi by following the command: sudo apt-get install Arduino

This will install Arduino interface in Raspberry Pi. 

In addition to this I have installed packages which will be useful for programing with Arduino.

sudo pip install nanpy
sudo pip install pyserial

I tried to operate LED light with program from Raspberry Pi but I faced many problems. I read many pages and blogs and finally found that Arduino which I am working on is not a supporter of the latest version of the software. I was not able to continue forward and operate LED with Arduino. I did not find a proper solution for this problem. I am giving links of all the pages which I referred regarding this problem.

References:

https://www.raspberrypi.org/blog/raspberry-pi-and-arduino/
http://www.akeric.com/blog/?p=2420
https://www.youtube.com/watch?v=Jw06KLLkapU



Experiment 4:

Multiple LED

This is the experiment in which multiple LED are connected and each light will blink one after other. Looping is done and so all the lights will glow continuously till the program is terminated on Arduino. For this experiment i have used Arrays program file from experiments in Arduino.

Equipment:

Arduino
Breadboard
6 LED
6 Resistors
Connectors


Procedure:

Connect all the 6 lights to one resistor each as shown below in the video. Each LED will be connected to resistor at one end and ground at other end. Now each resistor is connected to different IO pins in Arduino. We make use of IO pins and program the logic for blinking LED. One light will blink after other. After making connections open the file Arrays from Controls in Examples from file in Arduino GUI. This will pop up a new window. This contains multiple lights blink program. Check the IO pin numbers for which each resistor is connected and make changes in port numbers in the opened file. I needed we can change blinking time for the LED. After all the required changes are done Upload the program. This will operate LED on breadboard. As a result we can see 6 blinking LED.

Video:



Code:

Arrays program file from Controls in Examples.



Experiment 5:

LED control with Button

In this experiment I tried controlling operations of LED with inputs from push button.

Equipment:

Arduino
LED
Push Button
Breadboard
Connectors

Procedure:

Connect one button on breadboard. To one pin of button connect resistor. To other end of resistor connect it to IO pin (D4). Connect other pin from button to ground. Below is the circuit of connection and how it works. Once the file is written to Arduino LED will not glow. When the button is pushed down it is taken as input and the mode of LED is changed from LOW to HIGH. Then LED starts glowing. This works as interaction with user through button and operating LED from user input.


Video:



Code:

int input=2;   // to store on or off value

void setup() 
{
    // put your setup code here, to run once:
    pinMode(2,INPUT);
    pinMode(13,OUTPUT);
}

void loop() 
{
      // put your main code here, to run repeatedly:
    input=digitalRead(2);
    if(input==0)
    {
        digitalWrite(13,HIGH);
    }
    else
    {
        digitalWrite(13,LOW);
    }

}


Reference:

http://www.instructables.com/id/How-to-use-a-push-button-switch-with-arduino/?ALLSTEPS



Monday, February 1, 2016

Domain of IOT Research: Smart Cities

Smart Cities

Internet availability to people and connectivity to electronic devices and sensors can make many things happen in a simple way. Internet of Things is all about doing that. Internet of Things plays a major role in transforming into smart cities at present and in future. Implementing IoT-driven services improves the quality of life of people through measures that promote an eco-friendly, sustainable environment. IOT-driven services gather large amount of data and this data is processed, trends are derived and resources are better used in all the ways. Real time data is most of the times associated with privacy and security implications. A smart city is in which there are necessary intelligent, robust and reliable functions to integrate and synthesize these big data and filter out any unwanted 'noise' for the purpose of improving city efficiency, equity, sustainability and quality of life.

I want to investigate on projects taken up by Cisco in tie up with Barcelona. Cisco implemented different projects like smart bus stops, information on the flow of citizens, wirelessly-connected garbage bins. How all these projects are related to improve quality of people's life? I want to find out in what ways the current projects can be extended so that more facilities can be provided to citizens. What are the other inter-related projects that can be taken up to uplift the living quality? How eco-friendly environment can be maintained. What can be made to maintain balance in traffic on roads? What optimization can be done so that people can lead a high quality life?

Week - 2

Temperature and Humidity Measure:
To measure temperature and humidity I used DHT11 Sensor. DHT11 measures both temperature and humidity and gives results. Basic structure of DHT11 looks like below:




By making use of DHT11 we can get Temperature and Humidity values to Raspberry Pi and can display, store, make operations on these values. 

To use DHT11 with Raspberry Pi we have to install packages which can connect to sensor and report values to Pi. These packages are installed using following commands:
Initially we need to install dependency packages into Pi. Commands for these are: sudo apt-get update
sudo apt-get install build-essential python-dev python-openssl
sudo python setup.py install

git clone https://github.com/adafruit/Adafruit_Python_DHT.git

Then we go the installed folder using the command: cd Adafruit_Python_DHT

Go to example folder and run the sample program to obtain temperature and humidity values.

cd examples
To run program: sudo ./AdafruitDHT.py 2302 4

Experiment 1:

Light alert on low temperature

This acts as a temperature alert system at your house. If you want to get alerts about low temperature you can use this. If the room temperature goes down than what you would like to be then the alert light glows and you can set the room temperature as you like. 

Equipment:

DHT11 sensor
Raspberry Pi
Beadboard
resistor
connectors

Connect the DHT11 to Raspberry Pi as shown below. By using the DHT package we installed in python we can monitor temperature and humidity values and prepare alert system. Connect 2 different color LED lights in the circuit. One will be glowing for the range above normal temperature and the other glows when temperature comes below normal temperature. Values will be reported continuously and the alert light glows immediately when the temperature falls down.




Circuit Diagram:




Experiment 2:

Display Temperature and Humidity values on LCD

In this experiment we will display temperature and humidity values on Nokia LCD display. For this we need to install Adafruit_Nokia_LCD package to monitor LCD display using Raspberry Pi using python. Follow the below commands to install package:

Initially we should install dependencies using these commands : sudo apt-get install python-pip python-dev build-essential
sudo pip install RPi.GPIO

Then we should install image display package : sudo apt-get install python-imaging

Now installing LCD display library sudo apt-get install git 
git clone https://github.com/adafruit/Adafruit_Nokia_LCD.git (http://adafru.it/dvC)
cd Adafruit_Nokia_LCD
sudo python setup.py install

We have to follow below steps to enable SPI for Raspberry Pi:
Click on Application Launcher a window will open 
Type command  sudo apt-get install python3-dev 
After installation give following command: git clone https://github.com/doceme/py-spidev 
Go to folder spidev cd py-spidev
Install setup using following command: sudo python3 setup.py install

These steps are to enable SPI pins in Raspberry Pi : sudo raspi-config
Window will be opened then "SPI" option should be selected.
Then select "Yes" for all the steps nad after all the steps select "Finish" option.
Then reboot system usein command : sudo reboot

After completing this process SPI pins will be activated and LCD can be connected to Raspberry Pi and used.

Equipment:

Raspberry Pi
Nokia 5110/3310 LCD
DHT11
Connectors

Using the Experiment 1 connections and add additional connections for the LCD and connect it to SPI pins of Raspberry Pi. Connect all SPI pins and make sure that correct pin numbers are used in python script for giving output to LCD.






References: https://learn.adafruit.com/downloads/pdf/nokia-5110-3310-lcd-python-library.pdf
       http://www.raspberrypi-spy.co.uk/2014/08/enabling-the-spi-interface-on-the-raspberry-pi/


Code for Experiment-1 and Experiment-2:

import sys
import RPi.GPIO
import Adafruit_DHT
import time

RPi.GPIO.setmode(RPi.GPIO.BCM)
RPi.GPIO.setup(2,RPi.GPIO.OUT)
RPi.GPIO.setup(3,RPi.GPIO.OUT)

RPi.GPIO.output(3,False)
RPi.GPIO.output(2,False)

import Adafruit_Nokia_LCD as LCD
import Adafruit_GPIO.SPI as SPI

import Image
import ImageDraw
import ImageFont

# Raspberry Pi hardware SPI config:
DC = 23
RST = 24
SPI_PORT = 0
SPI_DEVICE = 0

# Hardware SPI usage:
disp = LCD.PCD8544(DC, RST, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=4000000))

# Initialize library.
disp.begin(contrast=60)

# Clear display.
disp.clear()
disp.display()

image = Image.new('1', (LCD.LCDWIDTH, LCD.LCDHEIGHT))

# Get drawing object to draw on image.
draw = ImageDraw.Draw(image)
# Draw a white filled box to clear the image.
draw.rectangle((0,0,LCD.LCDWIDTH,LCD.LCDHEIGHT), outline=255, fill=255)
# Load default font.
font = ImageFont.load_default()


while(True):

sensor_args = { '11': Adafruit_DHT.DHT11,
'22': Adafruit_DHT.DHT22,
'2302': Adafruit_DHT.AM2302 }
if len(sys.argv) == 3 and sys.argv[1] in sensor_args:
sensor = sensor_args[sys.argv[1]]
pin = sys.argv[2]
else:
print 'usage: sudo ./Adafruit_DHT.py [11|22|2302] GPIOpin#'
print 'example: sudo ./Adafruit_DHT.py 2302 4 - Read from an AM2302 connected to GPIO #4'
sys.exit(1)

humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)

if humidity is not None and temperature is not None:
print 'Temp={0:0.1f}*  Humidity={1:0.1f}%'.format(temperature, humidity)
draw.text((1,30), 'Temp={0:0.1f}*'.format(temperature/100), font=font)
       draw.text((1,1), 'Humid={0:0.1f}%'.format(humidity/100), font=font)
       # Display image.
       disp.image(image)
       disp.display()
if  temperature > 450 :
   RPi.GPIO.output(3,False)
           RPi.GPIO.output(2,True)
else:
           RPi.GPIO.output(2,False)
   RPi.GPIO.output(3,True)
time.sleep(10)
disp.clear()
disp.display()

else:
print 'Failed to get reading. Try again!'

sys.exit(1)



Experiment 3:

Updating Temperature and Humidity sensor in Google sheets

We can take temperature and humidity values from DHT11 and continuously update and maintain records in constant time lapse. These values are updated into google spreadsheet using python libraries.

Create google spread sheet with name DHT Humidity Logs and delete all the empty rows from it.
Go to google developers console and create new project.
Then we need to get credentials for the spread sheet which we will be using in the script to connect to spreadsheet. A JSON file will be downloaded after select 'Enable and Manage APIs', under 'Google Apps APIs' and then select 'Drive API' and select 'Enable API' then select  'Go to Credentials' from the drop down select 'Compute Engine default service account' this will automatically download JSON file. 

Take client email from JSON file and share spreadsheet with that emailid.


We need python packages to connect Raspberry Pi to google spread sheet. Follow below commands to install packages:
sudo apt-get update
sudo apt-get install python-pip
sudo pip install gspread oauth2client


goto cd Adafruit_Python_DHT
cd examples

We can find google_spreadsheet.py in this folder. 

Enter correct port numbers in this file and run the python script. Make sure that JSON file which is downloaded is in same folder.

This will read temperature and pressure from the DHT11 sensor and update values in google spreadsheet along with current date and time.





Serial Peripheral Interface:

The Serial Peripheral Interface (SPI) is a synchronous serial communication interface specification used for short distance communication. This prototype is used in Raspberry Pi for communicating with hardware devices to take input or to give output. SPI on Raspberry Pi is associated with pin numbers 19, 21, 23, 24, 25, 26 on the P1 header. Names of each pin are as specified below:

P1-19           MOSI   - Master Out Slave In
P1-21           MISO   - Master In Slave Out
P1-23           SCLK   - Serial CLocK
P1-25           GND    - Ground
P1-24           CE0     - Chip Enable (often called Chip Select)
P1-26           CE1     - Chip Enable





By default SPI mode is off on Raspberry Pi. To enable it remove the blacklisting for spi-bcm2708 in /etc/modprobe.d/raspi-blacklist.conf

Different protocols used in SPI are:

MOSI - Master Out Slave In
MISO - Master In Slave Out
MOMI - Master Out Master In
MIMO - Master In Master Out

There are multiple nodes available in SPI they are:

Standard Mode:
In Standard SPI master mode the peripheral implements the standard 3 wire serial protocol (SCLK, MOSI and MISO).

BIDIRECTIONAL MODE:

In bidirectional SPI master mode the same SPI standard is implemented except that a single wire is used for data (MIMO) instead of two as in standard mode (MISO and MOSI).

LOSSI MODE (LOW SPEED SERIAL INTERFACE):
This is used for communication with LCD devices to give input to the LCD.LoSSI commands and parameters are 8 bits long, but an extra bit is used to indicate whether the byte is a command or parameter/data. This extra bit is set high for a data and low for a command. The resulting 9-bit value is serialized to the output. LoSSI is commonly used with MIPI DBI type C compatible LCD controllers. Some commands trigger an automatic read by the SPI controller, so this mode can't be used as a multipurpose 9-bit SPI.

Different types of TRANSFER MODES are:

Polled
Interrupt
DMA

SPEED:
The CDIV (Clock Divider) field of the CLK register sets the SPI clock speed: SCLK = Core Clock / CDIV

CHIP SELECT

Setup and Hold times related to the automatic assertion and de-assertion of the CS lines when operating in DMA mode are as follows:

The CS line will be asserted at least 3 core clock cycles before the msb of the first byte of the transfer.
The CS line will be de-asserted no earlier than 1 core clock cycle after the trailing edge of the final clock pulse.


Reference: https://www.raspberrypi.org/documentation/hardware/raspberrypi/spi/README.md