Hi guys !
I’m new to this forum and to Arduino altogether, so please bear with me. I need some help for an ongoing project. I have 8 pins on my Arduino from which i am getting digital reads (so either HIGH=1 or LOW=0).
I would need to import those readings in Python, so that i can do something like this :
if pin1=1
then value1=1
else value1=0
if pin 2=1
then value2=2
else value2=0
if pin3=1
then value3=4
else value3=0
etc…
and then get a final value by adding them together
total = value1 + value2 + value3+….
and do some other stuff, like retrieving line[total] from a text file and so on…
But I don’t really know how to go about getting the results from the digital reads in Python, I checked a bit around, and it seems like I could import the serial from the arduino, but then I would loose the relation between the pin and the pin state (wouldn’t I ?), and I would need to reassign them… And that sounds like quite a bit of trouble for something that feels pretty simple and straightforward to me.
Grumpy_Mike:
The pin position is given by the bit position in the number you send. Think binary.
You're right, I was not thinking about it the right way
Robin2:
You could convert each I/O pin into a different bit in a single byte using a Bitshift
That would actually shorten the process by not having to attribute and add up values, I would just need to capture the whole string of the pins outputs and convert it to an integer. And I can go back for individual outputs when it's relevant.
Grumpy_Mike:
Yes but that pseudo code he gave is in effect doing that already.
The code looks silly, right ? I was sketching out how I was thinking about it.
No it's pseudo code, you get the idea but the syntax is not correct that is all.
I would have ORed the individual values together if it were me rather than add them but it produces the same result. Oddly enough just last week I wrote the same sort of thing in Python :-
#Python code to read four GPIO pins into a number
def getSensor():
sensor = 0
for pin in range(0,4):
sensor = (sensor << 1) | ( io.digitalRead(inputPins[pin]))
return sensor