gpt4 book ai didi

python - 如何将 if 语句输出结果放入 python 脚本中

转载 作者:行者123 更新时间:2023-12-01 09:33:44 24 4
gpt4 key购买 nike

我正在尝试实现光传感器输入,以便它在更大的 python 脚本中输出一个值。

具体打印LED_BRIGHTNESS = 75或LED_BRIGHTNESS = 255

基本上,当这个脚本运行时,我希望传感器决定 LED 串的 LED 亮度

我开始尝试执行以下操作...

import urllib2
import xml.etree.ElementTree as ET
import time
from neopixel import *
import sys
import os
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setup(4,GPIO.IN)

if GPIO.input(4) == 1:
print "LED_BRIGHTNESS = 75"
else:
print "LED_BRIGHTNESS = 255"
# LED strip configuration:
LED_COUNT = 95 # Number of LED pixels.
LED_PIN = 18 # GPIO pin connected to the pixels (18 uses PWM!).
#LED_PIN = 10 # GPIO pin connected to the pixels (10 uses SPI /dev/spidev0.0).
LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz)
LED_DMA = 5 # DMA channel to use for generating signal (try 5)
#LED_BRIGHTNESS = 255 # Set to 0 for darkest and 255 for brightest
LED_INVERT = False # True to invert the signal (when using NPN transistor level shift)
LED_CHANNEL = 0 # set to '1' for GPIOs 13, 19, 41, 45 or 53
LED_STRIP = ws.WS2811_STRIP_GRB # Strip type and colour ordering

这会将结果输出到终端,但我需要它输出到更大的脚本中。

所以我厌倦了以下...

import urllib2
import xml.etree.ElementTree as ET
import time
from neopixel import *
import sys
import os
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(4,GPIO.IN)


if GPIO.input(4) == 1: "LED_BRIGHTNESS = 75"
if GPIO.input(4) == 0: "LED_BRIGHTNESS = 255"


# LED strip configuration:
LED_COUNT = 95 # Number of LED pixels.
LED_PIN = 18 # GPIO pin connected to the pixels (18 uses PWM!).
#LED_PIN = 10 # GPIO pin connected to the pixels (10 uses SPI /dev/spidev0.0).
LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz)
LED_DMA = 5 # DMA channel to use for generating signal (try 5)
#LED_BRIGHTNESS = 255 # Set to 0 for darkest and 255 for brightest
LED_INVERT = False # True to invert the signal (when using NPN transistor level shift)
LED_CHANNEL = 0 # set to '1' for GPIOs 13, 19, 41, 45 or 53
LED_STRIP = ws.WS2811_STRIP_GRB # Strip type and colour ordering

这将返回以下错误。

Traceback (most recent call last):
File "metar.py", line 30, in <module>
strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL, LED_STRIP)
NameError: name 'LED_BRIGHTNESS' is not defined

我对此很陌生,我什至不知道在尝试用谷歌搜索问题时应该使用什么正确的术语。我尝试研究如何将 if 语句输出打印到字符串中,或​​者如何将 if 语句输出到字符串中,并且我不断发现谈论完全预定义值的内容,而不是来自传感器 if 语句的内容。

如果有人能指出我正确的方向,我将不胜感激。

最佳答案

看起来您想动态设置一个变量。在这种情况下,由于只有两个可能的值,因此内联 if 即可:

LED_BRIGHTNESS = 75 if GPIO.input(4) == 1 else 255

或者您可以扩展 if:

if GPIO.input(4) == 1:
LED_BRIGHTNESS = 75
else:
LED_BRIGHTNESS = 255

关于python - 如何将 if 语句输出结果放入 python 脚本中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49724109/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com