I am trying to make a Smart Alarm using Arduino UNO, Ultrasonic Sensor and Bolt Wifi Module.
So, from the Arduino part, the code has been compiled and uploaded, but the Python part gives an Attribute Error. The main libraries which I am using are 'conf' and 'boltiot'. The above error gives in the 6th line of the code.
Python Code:
import conf, json, time
from boltiot import Bolt
limit=105 #This is distance b/w sensor and wall
max_time=20
min_time=18
mybolt=Bolt(conf.bolt_api_key, conf.device_id) #Code Error here
response=mybolt.serialRead('10')
print(response)
def buzzer_action(pin, value):
response=mybolt.digitalWrite(pin, value)
ticks=time.time() #gets the current time
ltime=time.localtime(ticks) #gets the local time
current_hour=ltime.tm_hour #gets the current hour
while True:
response=mybolt.serialRead('10')
data=json.loads(response)
distance= data['value'].rstrip()
print("Distance:", distance) #distance recieved from Arduino
if(current_hour<max_time and current_hour>=min_time):
print("Current Hour:", current_hour)
if int(distance) < limit: #If the person is sleeping then the distance will decrease
print("Limit Exceeded || Buzzer Action")
buzzer_action(1, "HIGH") #buzzer beeps
time.sleep(5)
buzzer_action(1, "LOW") #buzzer stops
continue
else:
time.sleep(10) #waits for 10 seconds
continue
time.sleep(10) #waits for 10 second and again repeats all steps
Arduino Code:
#include <Ultrasonic.h>
Ultrasonic ultrasonic(12, 13);
void setup()
{
Serial.begin(9600);
}
Related
**I use this code.but it is not working. can someone help me?I got this type of error
raise IOError("{0} is set up as an INPUT and can therefore not be written to"
OSError: Digital pin 8 is set up as an INPUT and can therefore not be written to **
import pyfirmata
import time
board = pyfirmata.Arduino('/dev/ttyACM0')
start=0
end=0
trigpin = board.get_pin('d:7:o')
echopin= board.get_pin('d:8:i')
trigpin.write(0)
time.sleep(5)
while True:
trigpin.write(1)
time.sleep(3)
trigpin.write(0)
while echopin.write(0):
pass
start = time.time()
while echopin.write(1):
pass
end = time.time()
print((end - start)/58.0*1000000)
time.sleep(1)
I have written a code python to upload data to the thingspeak website. I connected a button to pin no 25 and have a code that calculates the number of times the button is pressed(age).
I want to upload the value of 'age' every 60 seconds but the code to calculate the button press must be continuously running so that i don't miss any button presses. Below is the code.
#!/usr/bin/env python
import httplib, urllib
import time
import RPi.GPIO as GPIO
import time
age=15 //initia;ized to 15 for debugging purposes
GPIO.setmode(GPIO.BCM)
GPIO.setup(25,GPIO.IN,GPIO.PUD_DOWN)
key = ''
def thermometer():
global age
while True:
temp = age
params = urllib.urlencode({'field1': temp,'key':key })
headers = {"Content-typZZe": "application/x-www-form-urlencoded","Accept": "text/plain"}
conn = httplib.HTTPConnection("api.thingspeak.com:80")
try:
conn.request("POST", "/update", params, headers)
response = conn.getresponse()
print temp
print response.status, response.reason
data = response.read()
conn.close()
except:
print "connection failed"
break
if __name__ == "__main__":
try:
while True:
a=GPIO.input(25) //checks whether input is high or low
print (age) //prints the count
if a==1: //condition
age+=1 //increments every time button is pressed
time.sleep(1)
thermometer()
except KeyboardInterrupt:
GPIO.cleanup()
print 'EXITING'
I need to upload the data every 60 seconds. The above code is uploading the value every second.
The function time.time() return the time in seconds since the epoch as a floating point number, i.e Time elapsed since UTC 00:00:00 1 January 1970 .
sendTime = time.time() + 60 --> This is to add 60 seconds to the clock and stored it in a variable i.e. sendTime.
In your function thermometer() i have added a condition to check whether the system time(i.e. time.time()) has a greater value than the sendTime or not.
If the condition is satisfied the data will be uploaded, if not the loop breaks and goes back to the while loop, Which you have writen in the main()
#!/usr/bin/env python
import httplib, urllib
import time
import RPi.GPIO as GPIO
import time
age=15 //initia;ized to 15 for debugging purposes
GPIO.setmode(GPIO.BCM)
sendTime = time.time() + 60 # runs for 60 sec ( 60*15) --> runs for 15 mins
GPIO.setup(25,GPIO.IN,GPIO.PUD_DOWN)
key = ''
def thermometer():
if time.time() > sendTime: # Check if the is greater than sendTime
sendTime += 60 #Resets the timer 60 seconds ahead
global age
while True:
temp = age
params = urllib.urlencode({'field1': temp,'key':key })
headers = {"Content-typZZe": "application/x-www-form- urlencoded","Accept": "text/plain"}
conn = httplib.HTTPConnection("api.thingspeak.com:80")
try:
conn.request("POST", "/update", params, headers)
response = conn.getresponse()
print temp
print response.status, response.reason
data = response.read()
conn.close()
except:
print "connection failed"
break
else
break
if __name__ == "__main__":
try:
while True:
a=GPIO.input(25) //checks whether input is high or low
print (age) //prints the count
if a==1: //condition
age+=1 //increments every time button is pressed
time.sleep(1)
thermometer()
except KeyboardInterrupt:
GPIO.cleanup()
print 'EXITING'
Hope this works.
Use the modulo function %, this will upload if age if the remainder of the division age / 60 is 0. Else the condition evaluates to False.
while True:
a=GPIO.input(25) //checks whether input is high or low
print (age) //prints the count
if a==1: //condition
age+=1 //increments every time button is pressed
time.sleep(1)
if not (age % 60): #use modulo
thermometer()
But one important thing to note here is, that you are uploading not every 60 seconds, but every 60 iterations of the loop. If you need to upload every fixed time step look at the datetime package, there you can check the current time and also use the current seconds with modulo.
If your data needs to be in fixed intervals, then upload time is not that important. Instead you need to record a value every 60 seconds.
I wrote the following code for my US-100 ultrasonic distance measurement sensor. But I am getting junk results everytime. when ever I am moving my sensor, I dont get any change in reading. Also, when I am connecting GND and VCC to sensor, input stops generating. Need help with Circuit diagram for connecting US-100 to Raspberry pi 3 and errors in this code which lead to junk results
import RPi.GPIO as GPIO
import time
import logging
LOG_FILENAME='US_100.log'
logging.basicConfig(format='%(asctime)s %(message)s',filename='US_100',
level=logging.DEBUG)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
TRIG = 23
ECHO = 24
GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)
while True:
GPIO.output(TRIG,False)
time.sleep(1.5)
print("Waiting for sensor to settle")
GPIO.output(TRIG,True)
time.sleep(0.0001)
GPIO.output(TRIG, False)
pulse_start=time.time()
while GPIO.input(ECHO) == 0:
pulse_start = time.time()
while GPIO.input(ECHO) == 1:
pulse_end = time.time()
pulse_duration = (pulse_end-pulse_start)
print("Pulse duration =%1f " %pulse_duration)
distance = (pulse_duration*343/2)
if distance >0.5 and distance <400:
print("Distance = %1f" %distance)
else:
print("Out of Range")
logging.debug(distance)
Image of results which I am getting even though the object is 15-20cm apart.
Output Image
I have bought an Adafruit PCA9685 and completed the library installation, however, I have no clue of how to Program it. I want to base it on the following code I wrote:
import RPi.GPIO as GPIO
import time
import sys
from pubnub import Pubnub
GPIO.setmode(GPIO.BCM)
PIN_LIVING = 22
PIN_PORCH = 17
PIN_FIREPLACE = 27
GPIO.setup(PIN_LIVING,GPIO.OUT)
GPIO.setup(PIN_PORCH,GPIO.OUT)
GPIO.setup(PIN_FIREPLACE,GPIO.OUT)
FREQ = 100 # frequency in Hz
FIRE_FREQ = 30 # flickering effect
# Duty Cycle (0 <= dc <=100)
living = GPIO.PWM(PIN_LIVING, FREQ)
living.start(0)
porch = GPIO.PWM(PIN_PORCH, FREQ)
porch.start(0)
fire = GPIO.PWM(PIN_FIREPLACE, FIRE_FREQ)
fire.start(0)
# PubNub
pubnub = Pubnub(publish_key='demo', subscribe_key='demo')
channel = 'pi-house'
def _callback(m, channel):
print(m)
dc = m['brightness'] *10
if m['item'] == 'light-living':
living.ChangeDutyCycle(dc)
elif m['item'] == 'light-porch':
porch.ChangeDutyCycle(dc)
elif m['item'] == 'fireplace':
fire.ChangeDutyCycle(dc)
def _error(m):
print(m)
pubnub.subscribe(channels='pi-house', callback=_callback, error=_error)
try:
while 1:
pass
except KeyboardInterrupt:
GPIO.cleanup()
sys.exit(1)
I dont know if on this its similar. I bought it because I wanted to be able to control more LED's with PWM from the Raspberry pi. I looked into it and found all kinds of weird commands and terms specific to this Chip.
Thanks!
First, If you look at page 29 of the data sheet (fig. 15) it shows that for Direct LED connection, you need to connect your LEDs inverted. i.e. connect the ground of the LED to the PWM line on the PCA9685 and the positive of the LED to the V+
Code is pretty simple (below is for an Arduino) And you use the function pwm.setPWM(uint8_t num, uint16_t on, uint16_t off) to turn the LEDs on and off and to different levels of brightness.
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
void setup()
{
Serial.begin(9600);
pwm.begin();
pwm.setPWMFreq(1600); //This is the maximum PWM frequency
pwm.setPWM(1,0,4095); //this turns on the LED connected to channel one (I suspect the only line you're really looking for)
}
Hope that answers your question!
See below how to do this in python
import Adafruit_PCA9685
pwm = Adafruit_PCA9685.PCA9685()
pwm.set_pwm_freq(60)
# Demo using LED on Channel 12 of the PCA9685
# Wire up the LED on Channel 12 such that
# Shortleg of LED goes to GND and
# Long leg goes to PWM pin on channel 12
pwm.set_pwm(12,0,4095) # Full bright
time.sleep(5)
pwm.set_pwm(12,1024,3072) # half bright
time.sleep(5)
pwm.set_pwm(12,0,0) #off
time.sleep(5)
First time posting here so I apologize if I posted this incorrectly.
So currently I'm trying to make a digital stethoscope and plot the data live via python. I have a stethoscope with a mic shoved inside hooked up to a breadboard with the mic test circuit. This goes into an arduino which then sends the data via usb to my laptop. Currently my python code can display the incoming data live which is awesome. The problem is when I tap on the stethoscope, the incoming data should change. If I'm displaying the serial data via arduino or minicom, the data does change when I hit the stethoscope. But when I look at my python plot the data doesn't change and I can't figure out why. Here is my code;
Arduino
int sensorValue = 0; //value read from the pot
void setup() {
//init serial communications at 115200 bps;
Serial.begin(9600);
}
void loop() {
//read A0
sensorValue = analogRead(A0);
//Serial.write(sensorValue);
//Serial.print("The Voltage is: ");
Serial.println(sensorValue);
//Serial.println("V");
}
Python
import serial
import numpy as np
import matplotlib.pyplot as plt
from drawnow import *
voltArray = []
count = 0
arduinoData = serial.Serial('/dev/ttyACM0',9600)
plt.ion()
def makeFig():
plt.title('Stethascope Data')
plt.plot(voltArray,'bo-')
plt.grid(True)
plt.ylabel('Voltage (V)')
plt.ylim(0,5)
while True:
while (arduinoData.inWaiting()==0): #wait here until there is data
pass #do nothing
arduinoString = arduinoData.readline()
print arduinoString
try:
volt = float(arduinoString)
except ValueError:
# pass
print 'ValueError'
print 'Pin Value: ', volt
volt = volt*(5.0/1024.0) #arduino reads 0-5V, 10bit resolution
#2^10 = 1024, arduino outputs 0-1023
print 'Voltage: ', volt
voltArray.append(volt) #append volt value into array
drawnow(makeFig)
count = count + 1
if (count > 50):
voltArray.pop(0)
print 'End Loop'
print
Anybody have any ideas?