0% found this document useful (0 votes)
4 views17 pages

SPI and Sensor Data with MQTT

The document contains various Python and Arduino code snippets for interfacing with sensors (SPI, I2C, LDR, Ultrasonic, PIR) and utilizing MQTT for communication. It demonstrates how to read sensor data, publish it to an MQTT broker, and subscribe to messages. Additionally, it includes database interaction for storing received messages and examples of using GPIO pins for sensor control.

Uploaded by

bacober397
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views17 pages

SPI and Sensor Data with MQTT

The document contains various Python and Arduino code snippets for interfacing with sensors (SPI, I2C, LDR, Ultrasonic, PIR) and utilizing MQTT for communication. It demonstrates how to read sensor data, publish it to an MQTT broker, and subscribe to messages. Additionally, it includes database interaction for storing received messages and examples of using GPIO pins for sensor control.

Uploaded by

bacober397
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SIMPLE SPI

import spidev

import time

import [Link] as mqtt

url="[Link]"

port=1883

def on_connect(client,userdata,flag,rc):

print("conected")

client = [Link]()

client.on_connect=on_connect

[Link](url,port)

spi=[Link](0,0)

[Link](0,0)

spi.max_speed_hz=9600

while 1:

y=[Link](1)

print(y)

[Link](0.5)

[Link](topic="spiTest",payload=str(y),qos=1)

client.loop_forever()

SPI + LDR + MQTT

import spidev
import time

import [Link] as mqtt

url="[Link]"

port=1883

def on_connect(client,userdata,flag,rc):

print("conected")

client = [Link]()

client.on_connect=on_connect

[Link](url,port)

spi=[Link](0,0)

[Link](0,0)

spi.max_speed_hz=9600

while 1:

y=[Link](1)

print(y)

[Link](0.5)

[Link](topic="spiTest",payload=str(y),qos=1)

client.loop_forever()

SPI+LDR+DATABASE

import spidev

import time

import [Link] as mqtt

url="[Link]"

port=1883

def on_connect(client,userdata,flag,rc):

print("conected")
client = [Link]()

client.on_connect=on_connect

[Link](url,port)

spi=[Link](0,0)

[Link](0,0)

spi.max_speed_hz=9600

while 1:

y=[Link](1)

print(y)

[Link](0.5)

[Link](topic="spiTest",payload=str(y),qos=1)

client.loop_forever()

FETCH DATA

import spidev

import time

import [Link] as mqtt

url="[Link]"

port=1883

def on_connect(client,userdata,flag,rc):

print("conected")

client = [Link]()

client.on_connect=on_connect

[Link](url,port)

spi=[Link](0,0)

[Link](0,0)
spi.max_speed_hz=9600

while 1:

y=[Link](1)

print(y)

[Link](0.5)

[Link](topic="spiTest",payload=str(y),qos=1)

client.loop_forever()

Ultrasonic Sensor code

import [Link] as GPIO

import time

TRIG=21

ECHO=20

[Link]([Link])

while True:

print(“Distance measurement in progress”)

[Link](TRIG ,[Link])

[Link](ECHO,[Link])

[Link](TRIG,FALSE)

print(“Waiting....”)

[Link](0.2)

[Link](TRIG,True)

[Link](0.00001)

[Link](TRIG,False)

while [Link](ECHO)==0:

pulse_start=[Link]()

while [Link](ECHO)==1:

pulse_end=[Link]()
pulse_duration=pulse_end-pulse_start

distance=pulse_duration*17150

distance=round(distance,2)

print(“Distance:”,distance,” cm”)

[Link](2)

PIR(Motion) Sensor code

import [Link] as GPIO

import time

[Link]([Link])

[Link](24,[Link])

[Link](18,[Link])

while(True):

myin=[Link](18)

if myin == True:

print(“Motion Detacted”)

[Link](1)

[Link](24,True)

[Link](0.5)

[Link](24,False)

[Link](0.5)
IR Sensor Python Code For Raspberry Pi

import [Link] as GPIO

[Link]([Link])

[Link](3, [Link])

[Link](5, [Link])

While True:

if([Link](3)== True):

print(“Obstacle detected”)

[Link](3,True)

else:

print(“Obstacle Not detected”)

[Link](3,False)

LDR Sesnor

int LDR;

void setup(){

pinMode(13, OUTPUT);

[Link](9600);

void loop(){

LDR = analogRead(A0);
if (LDR <50){

digitalWirte(13,HIGH)

else{

digitalWirte(13,LOW)

delay(300);

# This code is for publishing message to broker

import [Link] as mqtt

broker_url="[Link]"

broker_port=1883

client = [Link]()

[Link](broker_url,broker_port)

while 1:

msg = input("Enter message to send: ")

[Link](topic="coding_mandali", payload=msg, qos=0, retain=False)

if(msg == "stop"):

break;
# This code is for subscribing mqtt client

import [Link] as mqtt

port=1883

url="[Link]"

def on_connect(client,user_data,flag,rc):

print("Subscriber connected to broker.")

def on_message(client,user_data,message):

print("Recieved message: ", [Link]())

client = [Link]()

[Link](url,port)

client.on_connect = on_connect

client.on_message = on_message

[Link]("coding_mandali", qos=0)

[Link](topic="conding_mandali", payload="hello to pub",qos=0,retain=False)

client.loop_forever()

# This code is for recieving message from mqttbox publisher and storing them into database

import [Link] as mqtt

import sqlite3 as sql

import datetime as dt

url="[Link]"

port=1883

topic="coding_mandali"

def on_message(client,user_data,message):

print("Message recieved: ", [Link]("utf-8"))


pl = [Link]("utf-8")

connection = user_data["db_conn"]

curs = [Link]()

insert_query = """insert into msg_record(topic,message,timestamp)values(?,?,?)"""

[Link](insert_query,(topic,pl,[Link]()))

[Link]("select * from msg_record")

result = [Link]()

print(result)

[Link]()

[Link]()

def on_connect(client,user_data,flags,rc):

[Link](topic,qos=0)

print("Connection established with broker.")

connection = [Link]("[Link]")

curs = [Link]()

create_command = """create table if not exists msg_record(id integer primary key autoincrement,
topic text, message text, timestamp text)"""

[Link](create_command)

[Link]()

[Link]()

client = [Link]()

client.user_data_set({"db_conn":connection})

[Link](url,port)

client.on_connect = on_connect

client.on_message = on_message

client.loop_forever()
I2C Arduino

#include<Wire.h>

int i2cData=0x56;

const int ledPin=13;

int c;

void setup() {

[Link](0x8);

[Link](9600);

[Link](receiveEvent);

[Link](sendData);

pinMode(ledPin,OUTPUT);

digitalWrite(ledPin,LOW);

void receiveEvent(int howMany){

while([Link]()){

c=[Link]();

digitalWrite(ledPin,c);

void loop() {

delay(100);

if(c<0x02)

{
[Link](c);

c=0x02;

void sendData()

[Link](i2cData);

I2C Raspberry PI

from smbus import SMBus

import time

addr = 0x8 # bus address

bus = SMBus(1) # indicates /dev/ic2-1

[Link](1)

numb = 1

print("Enter 1 for ON or 0 for OFF")

while numb == 1:

ledstate = input (">>>>> ")

if ledstate == "1" :

bus.write_byte(addr,0x1) # switch it on

#y = bus.read_byte_data(addr, 0x1)

#print(y)

elif ledstate == "0":

bus.write_byte(addr,0x0) #switch it on

else:

numb = 0
connect LDR

use LDR + resistor

twist both 1 end of both n place it to A0

1 end of resistor in gnd

1 enf of sensor in V5

SPI Arduino

#include<SPI.h>

char buf[100];

byte c=0,b=0;

volatile byte pos;

volatile boolean processing;

byte i;

void setup(void) {

// put your setup code here, to run once:

[Link](9600);

pinMode(MISO,OUTPUT);

pinMode(MOSI,INPUT);

SPCR |= _BV(SPE);

pos = 0;

processing = false;

[Link]();

ISR(SPI_STC_vect){

c = SPDR;
// SPDR = 0x55;

// if(pos<20){

// buf[pos++] = c;

// if(c == '\n')

// processing=true;

// }

processing = true;

void loop(void) {

// put your main code here, to run repeatedly:

if(processing){

// [Link]("Inside Processing");

[Link](c);

processing = false;

SPDR = i;

i = i+1;

SPI Raspberry PI

import spidev

import time

spi = [Link](0,0)

[Link](0,0)

msg= 0xAA

spi.max_speed_hz=115200
while 1:

[Link]([0x4,0x06])

y=[Link](1)

print(y)

[Link](0.5)

i2c LDr arduino

#include<Wire.h>

int ldr;

const int ledPin = 13;

int c;

void setup() {

// put your setup code here, to run once:

[Link](0x8); // radbery pi nu address

[Link](9600);

[Link](sendData);

// [Link](receiveEvent);

// pinMode(ledPin, OUTPUT);

// digitalWrite(ledPin, LOW);

//

//void receiveEvent(int howMany) {

// while([Link]()) {

// c = [Link]();
// digitalWrite(ledPin, c);

// }

//}

void sendData() {

[Link]("Sending data");

[Link](ldr);

void loop() {

// put your main code here, to run repeatedly:

//delay(100);

ldr = analogRead(A0);

[Link](ldr);

delay(500);

-----------i2c rasp read frm arduino----------

from smbus import SMBus

import time

addr = 0x8 # bus address

bus = SMBus(1) # indicates /dev/ic2-1

[Link](1)

numb = 1

while numb == 1:

y=bus.read_byte_data(addr,0x1)

print(y)
-------------------------------LDR with MQTT rasp

from smbus import SMBus

import time

import [Link] as mqtt

addr = 0x8 # bus address

bus = SMBus(1) # indicates /dev/ic2-1

[Link](1)

numb = 1

broker_url="[Link]"

broker_port=1883

client = [Link]()

[Link](broker_url,broker_port)

while numb == 1:

y=bus.read_byte_data(addr,0x1)

print(y)

[Link](topic="testk", payload=str(y), qos=0, retain=False)

PUBLISH CODE

import [Link] as mqtt

broker_url="[Link]"

broker_port=1883

def on_connect(client,userdata,flags,rc):

print("Connected with result code {rc}")


def on_message(client,userdata,message):

print("Message recieved : " + [Link]())

client = [Link]()

client.on_connect = on_connect

client.on_message = on_message

[Link](broker_url,broker_port)

# [Link]("jigs",qos=1)

[Link](topic="jigs",payload="IOT exam",qos=1,retain=False)

client.loop_forever()

You might also like