Python code not fetching up to date sensor values - python

So I am trying to fetch for light sensor values using the light sensor that is part of GrovePi. When I run the sample script here (https://github.com/DexterInd/GrovePi/blob/master/Software/Python/grove_light_sensor.py) the code works perfectly so this leads me to conclude that the script I wrote is somehow only fetching for one value and just stores it and outputs it without fetching for the new updated value. Note: I am storing my values in a dictionary and posting to Dweet.io
If anyone can lead me to the right direction that would be great, my code is below :
import time
import grovepi
light_sensor = 0
grovepi.pinMode(light_sensor,"INPUT")
def getLight():
sensor_value = grovepi.analogRead(light_sensor)
s = sensor_value
#S seems to print just one number here?
print(s)
return s
def values():
dict = {}
dict["light"] = getLight()
return dict
while True:
dict = values()
print (dweepy.dweetfor(n, dict))
time.sleep(2)

Not an engineer, but why are you adding the whole dictionary part at all? Your sample code does not do that, and dweet certainly does not need it.
My guess is that is your issue, remove it.
While True:
print (dweepy.dweetfor(s))

Related

Looping through json.loads(response.text) with Python

i'm learning and would appreciate any help in this code.
The issue is trying to print the values in the data that are contained in one line of the JSON using Python.
import json
import requests
data = json.loads(response.text)
print(len(data)) #showing correct value
#where i'm going wrong below obviously this will print the first value then the second as it's indexed. Q how do I print all values when using seperate print statements when the total indexed value is unknown?
for item in data:
print(data[0]['full_name'])
print(data[1]['full_name'])
I tried without the index value this gave me the first value multiple times depending on the length.
I expect to be able to access from the JSON file each indexed value separately even though they are named the same thing "full_name" for example.
import json
import requests
data = json.loads(response.text)
print(len(data)) #showing correct value
for item in data:
print(item['full_name'])
#the below code will throw error.. because python index starts with 0
print(data[0]['full_name'])
print(data[1]['full_name'])
hope this help
Presuming data is a list of dictionaries, where each dictionary contains a full_name key:
for item in data:
print(item['full_name'])
This code sample from your post makes no sense:
for item in data:
print(data[0]['full_name'])
print(data[1]['full_name'])
Firstly it's a syntax error because there is nothing indented underneath the loop.
Secondly it's a logic error, because the loop variable is item but then you never refer to that variable.

Struggling reading data from UART

I've started programming in Python just recently but I've come over my first issue and that is:
uart.readline()
I'm sending multiple lines of data over UART to control my LED lights at home, so my idea is to send something like "r255", "g255", "b255", "br5". The format of the data being sent is not important to me, important is to get red, green, and blue values between 0-255 and a brightness value between 1-10 and somehow decode and process the data in Python. Btw. I'm sending the data from my Android App, the formatting and everything on that end should be fine.
But to the problem. I have a code as follows:
uart = UART(0,9600)
while True:
if uart.any():
data = uart.readline()
print(data)
This returns something like this for the red value:
b'r'
b'2'
b'5'
b'5'
That's fine to me and I understand why that is happening. I can probably work out how to put the data together so they make sense and work with them but the problem is that each line is actually going through another cycle so I can't really do any operations in the while loop to get the data together, or can I?
If I try something like this:
while True:
if uart.any():
data = uart.readline()
data2 = uart.readline()
data3 = uart.readline()
print(data)
print(data2)
print(data3)
I get:
b'r'
None
None
What is a solution to this problem? Am I missing something really obvious? Why can't I read more than one line in that loop? Why does the loop always have to repeat to read another line? How do I approach this in order to get the data together? I've tried uart.read() but it always returns something else like b'red2' b'55' or b'red255' or b'red' b'255' so it's even more mess and too much for me to understand what's happening there.
I can't test this for obvious reasons, but this should correct the problem of not calling uart.any() before each uart.readline(). I defined a separate function to do that and call it multiple times.
import time
import uart
def read_line():
while not uart.any():
time.sleep(0.0001)
return uart.readline()
while True:
lines = [read_line() for _ in range(3)] # Read 3 lines.
print(b''.join(lines)) # Join them together.

Extract info when JSON when key changes in Python

I'm quite new to Python so please excuse me if my terminology is not 100% accurate or if this is quite simple
I currently have the code:
import requests
POINTS = requests.get('https://api.torn.com/market/?selections=pointsmarket&key=jtauOcpEwz0W0V5M').json()
POINTSA = POINTS['pointsmarket']
print (POINTSA)
I want to print the cost of the very first key. However, the number for the first key will always change.
At the time of posting the first key is 9765126 as seen here:
https://imgur.com/VRi8Owe
So the line would be (I think):
POINTSA = POINTS['pointsmarket'][9765126]['cost']
However in 5 minutes time, the 9765126 key will change to something else. How do I get it to print the 1st cost entry regardless of the first key?
Hi you can try the following sample of getting the keys as a list then getting the first index
keys = list(POINTS['pointsmarket'].keys()) # Get all keys and convert to a list
POINTS['pointsmarket'][keys[0]]['cost']

Use generic keys in dictionary in Python

I am trying to name keys in my dictionary in a generic way because the name will be based on the data I get from a file. I am a new beginner to Python and I am not able to solve it, hope to get answer from u guys.
For example:
from collections import defaultdict
dic = defaultdict(dict)
dic = {}
if cycle = fergurson:
dic[cycle] = {}
if loop = mourinho:
a = 2
dic[cycle][loop] = {a}
Sorry if there is syntax error or any other mistake.
The variable fergurson and mourinho will be changing due to different files that I will import later on.
So I am expecting to see my output when i type :
dic[fergurson][mourinho]
the result will be:
>>>dic[fergurson][mourinho]
['2']
It will be done by using Python
Naming things, as they say, is one of the two hardest problems in Computer Science. That and cache invalidation and off-by-one errors.
Instead of focusing on what to call it now, think of how you're going to use the variable in your code a few lines down.
If you were to read code that was
for filename in directory_list:
print filename
It would be easy to presume that it is printing out a list of filenames
On the other hand, if the same code had different names
for a in b:
print a
it would be a lot less expressive as to what it is doing other than printing out a list of who knows what.
I know that this doesn't help what to call your 'dic' variable, but I hope that it gets you on the right track to find the right one for you.
i have found a way, if it is wrong please correct it
import re
dictionary={}
dsw = "I am a Geography teacher"
abc = "I am a clever student"
search = re.search(r'(?<=Geography )(.\w+)',dsw)
dictionary[search]={}
again = re.search(r'(?<=clever )(.\w+)' abc)
dictionary[search][again]={}
number = 56
dictionary[search][again]={number}
and so when you want to find your specific dictionary after running the program:
dictionary["teacher"]["student"]
you will get
>>>'56'
This is what i mean to

Help with Python loop weirdness?

I'm learning Python as my second programming language (my first real one if you don't count HTML/CSS/Javascript). I'm trying to build something useful as my first real application - an IRC bot that alerts people via SMS when certain things happen in the channel. Per a request by someone, I'm (trying) to build in scheduling preferences where people can choose not to get alerts from between hours X and Y of the day.
Anyways, here's the code I'm having trouble with:
db = open("db.csv")
for line in db:
row = line.split(",") # storing stuff in a CSV, reading out of it
recipient = row[0] # who the SMS is going to
s = row[1] # gets the first hour of the "no alert" time range
f = row[2] # gets last hour of above
nrt = [] # empty array that will store hours
curtime = time.strftime("%H") # current hour
if s == "no":
print "They always want alerts, sending email" # start time will = "no" if they always want alerts
# send mail code goes here
else:
for hour in range(int(s), int(f)): #takes start, end hours, loops through to get hours in between, stores them in the above list
nrt.append(hour)
if curtime in nrt: # best way I could find of doing this, probably a better way, like I said I'm new
print "They don't want an alert during the current hour, not sending" # <== what it says
else:
# they do want an alert during the current hour, send an email
# send mail code here
The only problem I'm having is somehow the script only ends up looping through one of the lines (or something like that) because I only get one result every time, even if I have more than one entry in the CSV file.
If this is a regular CSV file you should not try to parse it yourself. Use the standard library csv module.
Here is a short example from the docs:
import csv
reader = csv.reader(open("some.csv", "rb"))
for row in reader:
print row
There are at least two bugs in your program:
curtime = time.strftime("%H")
...
for hour in range(int(s), int(f)):
nrt.append(hour)
# this is an inefficient synonym for
# nrt = range(int(s), int(f))
if curtime in nrt:
...
First, curtime is a string, whereas nrt is a list of integers. Python is strongly typed, so the two are not interchangeable, and won't compare equal:
'4' == 4 # False
'4' in [3, 4, 5] # False
This revised code addresses that issue, and is also more efficient than generating a list and searching for the current hour in it:
cur_hour = time.localtime().tm_hour
if int(s) <= cur_hour < int(f):
# You can "chain" comparison operators in Python
# so that a op1 b op2 c is equivalent to a op1 b and b op2c
...
A second issue that the above does not address is that your program will not behave properly if the hours wrap around midnight (e.g. s = 22 and f = 8).
Neither of these problems are necessarily related to "the script only ends up looping through one of the lines", but you haven't given us enough information to figure out why that might be. A more useful way to ask questions is to post a brief but complete code snippet that shows the behavior you are observing, along with sample input and the resulting error messages, if any (along with traceback).
Have you tried something more simple? Just to see how your file is actually read by Python:
db = open("db.csv")
for line in db:
print line
There can be problem with format of your csv-file. That happens, for instance, when you open Unix file in Windows environment. In that case the whole file looks like single string as Windows and Unix have different line separators. So, I don't know certain cause of your problem, but offer to think in that direction.
Update:
Your have multiple ways through the body of your loop:
when s is "no": "They always want alerts, sending email" will be printed.
when s is not "no" and curtime in nrt: "They don't want an alert during the current hour, not sending" will be printed.
when s is not "no" and curtime in nrt is false (the last else): nothing will be printed and no other action undertaken.
Shouldn't you place some print statement in the last else branch?
Also, what is exact output of your snippet? Is it "They always want alerts, sending email"?
I would check the logic in your conditionals. You looping construct should work.
You could go thro an existing well written IRC bot in Python Download
Be explicit with what's in a row. Using 0, 1, 2...n is actually your bug, and it makes code very hard to read in the future for yourself or others. So let's use the handy tuple to show what we're expecting from a row. This sort of works like code as documentation
db = open("db.csv")
for line in db.readlines():
recipient, start_hour, end_hour = line.split(",")
nrt = []
etc...
This shows the reader of your code what you're expecting a line to contain, and it would have shown your bug to you the first time you ran it :)

Categories