Skip to content

Instantly share code, notes, and snippets.

@gucci-ninja
Created August 1, 2018 01:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gucci-ninja/dfd30814d7d392cb71375a4069c9fa4d to your computer and use it in GitHub Desktop.
Save gucci-ninja/dfd30814d7d392cb71375a4069c9fa4d to your computer and use it in GitHub Desktop.
This is some python code for the raspberry pi that detects when a person has tripped
#!/usr/bin/python
import smbus
import math
import twilio
from twilio.rest import Client
import urllib
import json
import socket
#The details for sending messages.
account_sid = __SID__
auth_token = __AUTH__
# Here we are going to get values from the accelerometer.
# The code is from https://tutorials-raspberrypi.com/measuring-rotation-and-acceleration-raspberry-pi/
# Register
power_mgmt_1 = 0x6b
power_mgmt_2 = 0x6c
def read_byte(reg):
return bus.read_byte_data(address, reg)
def read_word(reg):
h = bus.read_byte_data(address, reg)
l = bus.read_byte_data(address, reg+1)
value = (h << 8) + l
return value
def read_word_2c(reg):
val = read_word(reg)
if (val >= 0x8000):
return -((65535 - val) + 1)
else:
return val
bus = smbus.SMBus(1) # bus = smbus.SMBus(0) for older pis
address = 0x68 # via i2cdetect
while True:
try:
bus = smbus.SMBus(1) # bus = smbus.SMBus(0) for older pis
address = 0x68 # via i2cdetect
# Activate the module so we can get more values
bus.write_byte_data(address, power_mgmt_1, 0)
#These are the accelerations in the x and y direction. It's scaled so that's why we divided by 16384
ax2=read_word_2c(0x3b)/16384.0
ay2=read_word_2c(0x3d)/16384.0
print("x: "+str(ax2))
print("y: "+str(ay2))
if (ax2 < 0.8 and ay2 > 0.8):
hostname = socket.gethostname()
IPAddr = socket.gethostbyname(hostname)
url = "http://geoip-db.com/json/"+IPAddr
response = urllib.urlopen(url)
data = json.loads(response.read())
msgbody = "User has tripped at location: "+str(data["latitude"])+","+str(data["longitude"])+" in "+str(data["city"])
# Send a text to guardian - my phone
client = Client(account_sid, auth_token)
message = client.api.account.messages.create(
to=NUM_TO,
from_=NUM_FROM,
body=msgbody)
break
except IOError as e:
print("Accelerometer not connected properly")
continue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment