Add initial project files including configuration and LED control scripts

- Create .gitignore to exclude unnecessary files
- Add .micropico for project identification
- Implement config.json for switch configurations
- Develop led_panel_blink.py for LED control with color cycling
- Create main.py to manage switch commands and interactions
- Introduce servo.py for servo control functionality
- Define switch.py to handle switch operations with servo integration
This commit is contained in:
Artem Kashaev 2025-12-22 13:42:17 +05:00
commit 34294a86e8
7 changed files with 343 additions and 0 deletions

165
.gitignore vendored Normal file
View File

@ -0,0 +1,165 @@
# ---> Python
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
settings.json
extensions.json
*.code-workspace

3
.micropico Normal file
View File

@ -0,0 +1,3 @@
{
"info": "This file is just used to identify a project folder."
}

28
config.json Normal file
View File

@ -0,0 +1,28 @@
{
"switches": [
{
"id": 1283,
"pin": 12,
"angle_minus": 65,
"angle_plus": 125
},
{
"id": 1272,
"pin": 13,
"angle_minus": 65,
"angle_plus": 125
},
{
"id": 1444,
"pin": 2,
"angle_minus": 125,
"angle_plus": 65
},
{
"id": 1274,
"pin": 3,
"angle_minus": 125,
"angle_plus": 65
}
]
}

29
led_panel_blink.py Normal file
View File

@ -0,0 +1,29 @@
from machine import Pin
import neopixel
import time
import random
# Настройки: 8 LED, подключено к GP6
num_leds = 8
pin = 6 # GP6
np = neopixel.NeoPixel(Pin(pin), num_leds)
red = (255, 0, 0) # Красный (R, G, B)
green = (0, 255, 0) # Зеленый
blue = (0, 0, 255) # Синий
orange = (255, 165, 0) # Оранжевый
moon_white = (224, 224, 192) # Лунный белый
off = (0, 0, 0) # Выключено
while True:
np.fill(red) # Все LED красные
colors = [red, green, blue, orange, moon_white]
for i in range(num_leds):
np[i] = random.choice(colors)
np.write() # Обновить
time.sleep(0.5) # Пауза 0.5 сек
np.fill(off) # Все выключить
np.write()
time.sleep(0.5)

82
main.py Normal file
View File

@ -0,0 +1,82 @@
import sys
from switch import Switch
import select
from machine import Pin
SWITCHES = dict()
LED = Pin("LED", Pin.OUT) # "LED" — специальное имя для встроенного индикатора
def load_switches():
with open("config.json", "r") as file:
import json
config = json.load(file)
for sw_cfg in config["switches"]:
sw = Switch(
id=sw_cfg["id"],
pin=sw_cfg["pin"],
angle_minus=sw_cfg["angle_minus"],
angle_plus=sw_cfg["angle_plus"]
)
SWITCHES[sw.id] = sw
# print(f"Loaded {len(SWITCHES)} switch{'es' if len(SWITCHES) > 1 else ''}.")
def resolve_command(command: str):
parts = command.split()
if len(parts) == 4 and parts[0] == "SWITCH" and parts[2] == "TURN":
try:
sw_id = int(parts[1])
except ValueError:
return "ERROR Invalid ID"
direction = parts[3]
if direction not in ("+", "-"):
return "ERROR Invalid direction"
if sw_id not in SWITCHES:
return f"ERROR Switch {sw_id} not found"
# Выполняем действие
if direction == "+":
SWITCHES[sw_id].set_plus()
else:
SWITCHES[sw_id].set_minus()
# РОВНО ОДНА СТРОКА — подтверждение успеха
return f"EVENT SWITCH {sw_id} {direction}"
elif parts[0] == "GET" and parts[1] == "ALL":
evts = []
for id, sw in SWITCHES.items():
evts.append(f"EVENT SWITCH {id} {sw.pos}")
return "\n".join(evts)
def work():
poll = select.poll()
poll.register(sys.stdin, select.POLLIN)
while True:
events = poll.poll()
for fd, event in events:
if event & select.POLLIN:
try:
line = sys.stdin.readline().strip()
if not line:
continue
parts = line.split()
result = resolve_command(line)
if result:
print(result)
except Exception as e:
# Любая неожиданная ошибка — тоже одна строка
print(f"ERROR {e}")
if __name__ == "__main__":
LED.on()
load_switches()
work()

16
servo.py Normal file
View File

@ -0,0 +1,16 @@
from machine import Pin, PWM
class Servo:
def __init__(self, pin):
self.pwm = PWM(Pin(pin))
self.pwm.freq(50)
self.min_duty = 1638 # ~0.5 ms
self.max_duty = 8192 # ~2.5 ms
def angle(self, deg):
deg = max(0, min(180, deg))
duty = int(self.min_duty + (deg / 180) * (self.max_duty - self.min_duty))
self.pwm.duty_u16(duty)
def off(self):
self.pwm.duty_u16(0)

20
switch.py Normal file
View File

@ -0,0 +1,20 @@
from servo import Servo
class Switch:
def __init__(self, id, pin, angle_minus, angle_plus):
self.id = id
self.pin = pin
self.angle_minus = angle_minus
self.angle_plus = angle_plus
self.servo = Servo(pin)
self.pos = "-"
self.set_minus()
def set_minus(self):
self.servo.angle(self.angle_minus)
self.pos = "-"
def set_plus(self):
self.servo.angle(self.angle_plus)
self.pos = "+"