Inverted IO Logic
-
Hi,
I am having an issue where my logic is not working as expected. It is working inversely.
I first noticed this issue when running though the GPIO tutorial on the Pycom website https://docs.pycom.io/tutorials/basic/gpio/ .
The code for this is below:
from machine import Pin import time led = Pin('P9', mode=Pin.OUT) while True: print("high") led.value(1) time.sleep(1) print("low") led.value(0) time.sleep(1)
The code suggests that when we print 'high' to the console, the onboard LED goes high/on and vice versa for printing 'low'. I noticed that on both my boards that when I print 'high' the led is off and when printing 'low' the led is on.
I then tried swapping the logic for the led.value in both cases and found that the code worked as it should. Code below:
from machine import Pin import time led = Pin('P9', mode=Pin.OUT) while True: print("high") led.value(0) time.sleep(1) print("low") led.value(1) time.sleep(1)
I have once again found this to be an issue in the code for my latest project. I am trying to send UART communication to a Teensy from my LoPy4 and have found that my logic needs to be inverted for it to have the desired outcome.
Original code below:
from machine import Pin from machine import UART import time uart = UART(1, baudrate=57600) led = Pin('P9', mode = Pin.OUT) button = Pin('P10', mode = Pin.IN) while True: if(button() == 1): led.value(1) uart.write('q') else: led.value(0) time.sleep(0.2)
When the button is pressed I should see the led come on and send the letter 'q' via serial to my Teensy. Unfortunately this code does not work. If I change the logic to what is shown below, I then get the desired outcome, which is for my led to come on and the communication to be sent when the button is pressed.
from machine import Pin from machine import UART import time uart = UART(1, baudrate=57600) led = Pin('P9', mode = Pin.OUT) button = Pin('P10', mode = Pin.IN) while True: if(button() == 0): led.value(0) uart.write('q') else: led.value(1) time.sleep(0.2)
I hope that makes sense and someone is able to comment on this and help me to understand why this is happening.
Am I just not understanding something?
Am I looking at this wrong?Thank you in advance.
-
@Alex-Ray said in Inverted IO Logic:
Am I just not understanding something?
Am I looking at this wrong?The answer is yes. It depends on how LED and/or button are connected. pin(1) puts ~3.3 V at the output pin, pin(0) outputs 0V.
Similar pin() reads 1 if the input level is ~3.3V, and reads 0 is the input level is low. If your LED is connected the common way between output and 3.3V, it will light on if the output level is low, and go off if the output level is high.
If the button is connected the common way between input and GND, pin() will read 1 if the button is NOT pressed, and 0 if the button is pressed.