Я работаю на бесплатной российской ОС Роса Фреш 13 Плазма (Linux Rosa Fresh 13 Plasma, аналогично будет для Linux Rosa Fresh 12 Plasma) на ней уже по умолчанию установлен Python3!
Поэтому нам понадобится только установить дополнительную библиотеку pyserial.
Сначала вводим команду и проверяем установлен ли pip (позволяет устанавливать сторонние библиотеки на Python). Обычно pip уже установлен вместе с Python. Проверить наличие и версию pip можно командой – введя её в Терминале (Консоли, вызвать можно Ctrl+Alt+T):
sudo urpmi python3-pip
У меня на Linux Rosa Fresh 13 Plasma уже был установлен python3-pip-24.2-1.noarch.
А далее устанавливаем библиотеку pyserial с помощью команды:
sudo python3-pip install pyserial
ПК подключён через (USB-UART) преобразователь – HW-597 (на микросхеме CH340), но можно сделать его самому на Atmega88 (и других Atmega: ATtiny45/85, ATtiny2313/AT90S2313 и ATmega8/48/88/168), вот писал в одной из своей предыдущей записи:
“gameforstreet.ru/usb-ttl-usb-uart-preobrazovatel-na-atmega/”
Схема соединения HW-597 (на микросхеме CH340) (USB-TTL модуль, драйверы на моей ОС для него уже были установлены по умолчанию) и микроконтроллера Atmega88:
Схема соединения как и в предыдущей записи (“gameforstreet.ru/atmega88-upravlyaem-svetodiodami-s-pk-po-uart-bez-kvarca-vnutrennij-rc-generator-8mgc/”) :
Далее напишем программу для Python – для этого достаточно открыть текстовой редактор (на моей ОС – это установленный по умолчанию KWrite) написать код и сохранить с расширением .py
Код файла следующий, назвал я его 4.py – скачать его можно ниже:
import serial
# Configure the COM port
port = "/dev/ttyUSB0" # Replace with the appropriate COM port name
baudrate = 9600
try:
# Open the COM port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
print("Serial connection established.")
# Send commands to the Arduino
command = input("Enter a command (e.g., 'ON', 'OFF'): ")
# Send the command to the Arduino
ser.write(command.encode())
line = ser.readline().decode('utf-8').rstrip()
print(line)
ser.close()
print("Serial connection closed.")
except serial.SerialException as se:
print("Serial port error:", str(se))
except KeyboardInterrupt:
pass
finally:
# Close the serial connection
if ser.is_open:
ser.close()
print("Serial connection closed.")
Скачать файл Python для соединения микросхемы с ПК:
– в zip архиве.
– в tar.gz архиве.
Код работы следующий – после запуска – консоль попросит ввести команду “”Enter a command (e.g., ‘ON’, ‘OFF’): ” – вводим 1 – зажигается светодиод на ножке 28, если вводим 3 – то светодиод на ножке 27 у Atmega88. Но для этого нам нужно прошить микроконтроллер Atmega88 прошивкой – 88ledblink.hex – которая также есть в архиве.
Суть прошивки 88ledblink.hex следующая:
Если мы вводим в терминале цифру:
1, то включается светодиод на PC5 (28 ножка),
2, то выключается светодиод на PC5 (28 ножка),
3, то включается светодиод на PC4 (27 ножка),
4, то выключается светодиод на PC4 (27 ножка),
Как прошивать (на внутреннем резонаторе, фьюзы по ссылке – стандартные, только снят делитель частоты на 8) написано здесь – “gameforstreet.ru/atmega88-upravlyaem-svetodiodami-s-pk-po-uart-bez-kvarca-vnutrennij-rc-generator-8mgc/”
Вернёмся к нашему файлу Python (в нашем примере это будет 4.py).
Чтобы его запустить нужно разархивировать скачанный выше архив, зайти в папку, где лежит 4.py и кликнуть правой кнопкой мышки и выбрать пункт “Открыть терминал в этой папке”:
В Консоле войти под root (админа) при помощи команды su:
su
А далее ввести команду:
python3 4.py
—————————–
Дополнительная информация:
——————————
Фото соединения HW-597 (на микросхеме CH340) (USB-TTL модуль) и микроконтроллера Atmega88:
———————————
Фьюзы для ATmega88 такие же как по умолчанию, снял только делитель на 8 (CKDIV8 – убрал галочку) – программа AVR8_Burn-O-Mat, такие же будут и на PonyProg2000:
——————————-
Терминал использовал Cutecom (можно использовать putty)
Как его установить для Linux и Windows написал здесь:
Подключаем микроконтроллер PIC к USB (UART) на Linux и Windows
————————————
Добавляем задержки и задаём команды в коде:
import serial
import time
# Configure the COM port
port = "/dev/ttyUSB0" # Replace with the appropriate COM port name
baudrate = 9600
try:
# Open the COM port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
print("Serial connection established.")
#command = input("Enter a command (e.g., 'ON', 'OFF'): ")
command = "1"
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = "3"
ser.write(command.encode())
time.sleep(2)
command = "2"
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = "4"
ser.write(command.encode())
time.sleep(2)
line = ser.readline().decode('utf-8').rstrip()
print(line)
ser.close()
print("Serial connection closed.")
except serial.SerialException as se:
print("Serial port error:", str(se))
except KeyboardInterrupt:
pass
finally:
# Close the serial connection
if ser.is_open:
ser.close()
print("Serial connection closed.")
—————————————-
С окошком и кнопочками – жмем на кнопку “Запуск” и получаем комбинацию команд 1324
import tk
import tkinter as tk
import serial
import time
# Configure the COM port
port = "/dev/ttyUSB0" # Replace with the appropriate COM port name
baudrate = 9600
def root_quit():
print("1")
try:
# Open the COM port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
print("Serial connection established.")
#command = input("Enter a command (e.g., 'ON', 'OFF'): ")
command = "1"
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = "3"
ser.write(command.encode())
time.sleep(2)
command = "2"
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = "4"
ser.write(command.encode())
time.sleep(2)
line = ser.readline().decode('utf-8').rstrip()
print(line)
ser.close()
#print("Serial connection closed.")
print("Serial connection closed.")
except serial.SerialException as se:
print("Serial port error:", str(se))
except KeyboardInterrupt:
pass
finally:
# Close the serial connection
if ser.is_open:
ser.close()
print("Serial connection closed.")
def greet(name):
print(f"Привет, {name}!")
root = tk.Tk()
root.title("Пример окна с кнопками")
root.geometry("300x200")
button1 = tk.Button(root, text="Кнопка 1", bg="blue", fg="white", font=("Arial", 14))
button1.pack()
button2 = tk.Button(root, text="Кнопка 2", bg="red", fg="black", font=("Helvetica", 12))
button2.pack()
button3 = tk.Button(root, text="Поприветствовать", command=1)
button3.pack()
button4 = tk.Button(root, text='Запуск', command=root_quit)
button4.pack()
#entry = tk.Entry(root)
#entry.pack()
root.mainloop()
————————————————————
Окно с 4 кнопками управления – каждая отвечает за свою комбинацию команд.
import tk
import tkinter as tk
import serial
import time
# Configure the COM port
port = "/dev/ttyUSB0" # Replace with the appropriate COM port name
baudrate = 9600
#----------------------------------------------------------------
def komanda1():
print("1")
try:
# Open the COM port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
print("Serial connection established.")
#command = input("Enter a command (e.g., 'ON', 'OFF'): ")
command = "1"
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = "3"
ser.write(command.encode())
time.sleep(2)
command = "1"
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = "3"
ser.write(command.encode())
time.sleep(2)
line = ser.readline().decode('utf-8').rstrip()
print(line)
ser.close()
#print("Serial connection closed.")
print("Serial connection closed.")
except serial.SerialException as se:
print("Serial port error:", str(se))
except KeyboardInterrupt:
pass
finally:
# Close the serial connection
if ser.is_open:
ser.close()
print("Serial connection closed.")
#----------------------------------------------------------------
def komanda2():
print("1")
try:
# Open the COM port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
print("Serial connection established.")
#command = input("Enter a command (e.g., 'ON', 'OFF'): ")
command = "3"
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = "4"
ser.write(command.encode())
time.sleep(2)
command = "3"
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = "4"
ser.write(command.encode())
time.sleep(2)
line = ser.readline().decode('utf-8').rstrip()
print(line)
ser.close()
#print("Serial connection closed.")
print("Serial connection closed.")
except serial.SerialException as se:
print("Serial port error:", str(se))
except KeyboardInterrupt:
pass
finally:
# Close the serial connection
if ser.is_open:
ser.close()
print("Serial connection closed.")
#----------------------------------------------------------------
def komanda3():
print("1")
try:
# Open the COM port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
print("Serial connection established.")
#command = input("Enter a command (e.g., 'ON', 'OFF'): ")
command = "1"
ser.write(command.encode())
command = "3"
ser.write(command.encode())
time.sleep(2)
command = "2"
ser.write(command.encode())
command = "4"
ser.write(command.encode())
time.sleep(2)
line = ser.readline().decode('utf-8').rstrip()
print(line)
ser.close()
#print("Serial connection closed.")
print("Serial connection closed.")
except serial.SerialException as se:
print("Serial port error:", str(se))
except KeyboardInterrupt:
pass
finally:
# Close the serial connection
if ser.is_open:
ser.close()
print("Serial connection closed.")
#----------------------------------------------------------------
def komanda4():
print("1")
try:
# Open the COM port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
print("Serial connection established.")
#command = input("Enter a command (e.g., 'ON', 'OFF'): ")
command = "1"
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = "3"
ser.write(command.encode())
time.sleep(2)
command = "2"
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = "4"
ser.write(command.encode())
time.sleep(2)
line = ser.readline().decode('utf-8').rstrip()
print(line)
ser.close()
#print("Serial connection closed.")
print("Serial connection closed.")
except serial.SerialException as se:
print("Serial port error:", str(se))
except KeyboardInterrupt:
pass
finally:
# Close the serial connection
if ser.is_open:
ser.close()
print("Serial connection closed.")
#----------------------------------------------------------------
# Кнопки
def greet(name):
print(f"Привет, {name}!")
root = tk.Tk()
root.title("Пример окна с кнопками")
root.geometry("300x200")
button1 = tk.Button(root, text="Команда 1", bg="blue", fg="white", font=("Arial", 14), command=komanda1)
button1.pack()
button2 = tk.Button(root, text="Команда 2", bg="red", fg="black", font=("Helvetica", 12), command=komanda2)
button2.pack()
button3 = tk.Button(root, text="Запуск команды 3", command=komanda3)
button3.pack()
button4 = tk.Button(root, text='Запуск команды 4', command=komanda4)
button4.pack()
# Задать свою команду в поле ввода
#entry = tk.Entry(root)
#entry.pack()
root.mainloop()
Скачать файл с вышеуказанным кодом:
– в формате tar.gz
– в формате zip
—————————————————–
Добавим два поля для ввода своей комбинации команд:
import tk
import tkinter as tk
import serial
import time
# Configure the COM port
port = "/dev/ttyUSB0" # Replace with the appropriate COM port name
baudrate = 9600
#----------------------------------------------------------------
def komanda1():
print("1")
try:
# Open the COM port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
print("Serial connection established.")
#command = input("Enter a command (e.g., 'ON', 'OFF'): ")
command = "1"
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = "3"
ser.write(command.encode())
time.sleep(2)
command = "1"
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = "3"
ser.write(command.encode())
time.sleep(2)
line = ser.readline().decode('utf-8').rstrip()
print(line)
ser.close()
#print("Serial connection closed.")
print("Serial connection closed.")
except serial.SerialException as se:
print("Serial port error:", str(se))
except KeyboardInterrupt:
pass
finally:
# Close the serial connection
if ser.is_open:
ser.close()
print("Serial connection closed.")
#----------------------------------------------------------------
def komanda2():
print("1")
try:
# Open the COM port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
print("Serial connection established.")
#command = input("Enter a command (e.g., 'ON', 'OFF'): ")
command = "3"
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = "4"
ser.write(command.encode())
time.sleep(2)
command = "3"
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = "4"
ser.write(command.encode())
time.sleep(2)
line = ser.readline().decode('utf-8').rstrip()
print(line)
ser.close()
#print("Serial connection closed.")
print("Serial connection closed.")
except serial.SerialException as se:
print("Serial port error:", str(se))
except KeyboardInterrupt:
pass
finally:
# Close the serial connection
if ser.is_open:
ser.close()
print("Serial connection closed.")
#----------------------------------------------------------------
def komanda3():
print("1")
try:
# Open the COM port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
print("Serial connection established.")
#command = input("Enter a command (e.g., 'ON', 'OFF'): ")
command = "1"
ser.write(command.encode())
command = "3"
ser.write(command.encode())
time.sleep(2)
command = "2"
ser.write(command.encode())
command = "4"
ser.write(command.encode())
time.sleep(2)
line = ser.readline().decode('utf-8').rstrip()
print(line)
ser.close()
#print("Serial connection closed.")
print("Serial connection closed.")
except serial.SerialException as se:
print("Serial port error:", str(se))
except KeyboardInterrupt:
pass
finally:
# Close the serial connection
if ser.is_open:
ser.close()
print("Serial connection closed.")
#----------------------------------------------------------------
def komanda4():
print("1")
try:
# Open the COM port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
print("Serial connection established.")
#command = input("Enter a command (e.g., 'ON', 'OFF'): ")
command = "1"
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = "3"
ser.write(command.encode())
time.sleep(2)
command = "2"
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = "4"
ser.write(command.encode())
time.sleep(2)
line = ser.readline().decode('utf-8').rstrip()
print(line)
ser.close()
#print("Serial connection closed.")
print("Serial connection closed.")
except serial.SerialException as se:
print("Serial port error:", str(se))
except KeyboardInterrupt:
pass
finally:
# Close the serial connection
if ser.is_open:
ser.close()
print("Serial connection closed.")
#----------------------------------------------------------------
#----------------------------------------------------------------
def komanda5():
print("1")
try:
# Open the COM port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
print("Serial connection established.")
print("Entered Text:", entry1.get())
command = entry1.get()
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = entry2.get()
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
line = ser.readline().decode('utf-8').rstrip()
print(line)
ser.close()
print("Serial connection closed.")
except serial.SerialException as se:
print("Serial port error:", str(se))
except KeyboardInterrupt:
pass
finally:
# Close the serial connection
if ser.is_open:
ser.close()
print("Serial connection closed.")
#----------------------------------------------------------------
# Кнопки
def greet(name):
print(f"Привет, {name}!")
root = tk.Tk()
root.title("Пример окна с кнопками")
root.geometry("300x500")
button1 = tk.Button(root, text="Команда 1", bg="blue", fg="white", font=("Arial", 14), command=komanda1)
button1.pack()
button2 = tk.Button(root, text="Команда 2", bg="red", fg="black", font=("Helvetica", 12), command=komanda2)
button2.pack()
button3 = tk.Button(root, text="Запуск команды 3", command=komanda3)
button3.pack()
button4 = tk.Button(root, text='Запуск команды 4', command=komanda4)
button4.pack()
# Create an Entry widget
entry1 = tk.Entry(root, width=10)
entry1.pack(pady=10)
# Create an Entry widget
entry2 = tk.Entry(root, width=10)
entry2.pack(pady=10)
# Create a button to retrieve text
button5 = tk.Button(root, text="Get Text", command=komanda5)
button5.pack()
root.mainloop()
————————————————
Добавляем grid (сетку – строчки и столбцы – чтобы разместить несколько полей ввода горизонтально):
import tk
import tkinter as tk
import serial
import time
# Configure the COM port
port = "/dev/ttyUSB0" # Replace with the appropriate COM port name
baudrate = 9600
#----------------------------------------------------------------
def komanda1():
print("1")
try:
# Open the COM port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
print("Serial connection established.")
#command = input("Enter a command (e.g., 'ON', 'OFF'): ")
command = "1"
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = "3"
ser.write(command.encode())
time.sleep(2)
command = "1"
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = "3"
ser.write(command.encode())
time.sleep(2)
line = ser.readline().decode('utf-8').rstrip()
print(line)
ser.close()
#print("Serial connection closed.")
print("Serial connection closed.")
except serial.SerialException as se:
print("Serial port error:", str(se))
except KeyboardInterrupt:
pass
finally:
# Close the serial connection
if ser.is_open:
ser.close()
print("Serial connection closed.")
#----------------------------------------------------------------
def komanda2():
print("1")
try:
# Open the COM port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
print("Serial connection established.")
#command = input("Enter a command (e.g., 'ON', 'OFF'): ")
command = "3"
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = "4"
ser.write(command.encode())
time.sleep(2)
command = "3"
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = "4"
ser.write(command.encode())
time.sleep(2)
line = ser.readline().decode('utf-8').rstrip()
print(line)
ser.close()
#print("Serial connection closed.")
print("Serial connection closed.")
except serial.SerialException as se:
print("Serial port error:", str(se))
except KeyboardInterrupt:
pass
finally:
# Close the serial connection
if ser.is_open:
ser.close()
print("Serial connection closed.")
#----------------------------------------------------------------
def komanda3():
print("1")
try:
# Open the COM port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
print("Serial connection established.")
#command = input("Enter a command (e.g., 'ON', 'OFF'): ")
command = "1"
ser.write(command.encode())
command = "3"
ser.write(command.encode())
time.sleep(2)
command = "2"
ser.write(command.encode())
command = "4"
ser.write(command.encode())
time.sleep(2)
line = ser.readline().decode('utf-8').rstrip()
print(line)
ser.close()
#print("Serial connection closed.")
print("Serial connection closed.")
except serial.SerialException as se:
print("Serial port error:", str(se))
except KeyboardInterrupt:
pass
finally:
# Close the serial connection
if ser.is_open:
ser.close()
print("Serial connection closed.")
#----------------------------------------------------------------
def komanda4():
print("1")
try:
# Open the COM port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
print("Serial connection established.")
#command = input("Enter a command (e.g., 'ON', 'OFF'): ")
command = "1"
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = "3"
ser.write(command.encode())
time.sleep(2)
command = "2"
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = "4"
ser.write(command.encode())
time.sleep(2)
line = ser.readline().decode('utf-8').rstrip()
print(line)
ser.close()
#print("Serial connection closed.")
print("Serial connection closed.")
except serial.SerialException as se:
print("Serial port error:", str(se))
except KeyboardInterrupt:
pass
finally:
# Close the serial connection
if ser.is_open:
ser.close()
print("Serial connection closed.")
#----------------------------------------------------------------
#----------------------------------------------------------------
def komanda5():
print("1")
try:
# Open the COM port
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
print("Serial connection established.")
print("Entered Text:", entry1.get())
command = entry1.get()
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
command = entry2.get()
ser.write(command.encode())
time.sleep(2) #задержка в течение 5 секунд
line = ser.readline().decode('utf-8').rstrip()
print(line)
ser.close()
print("Serial connection closed.")
except serial.SerialException as se:
print("Serial port error:", str(se))
except KeyboardInterrupt:
pass
finally:
# Close the serial connection
if ser.is_open:
ser.close()
print("Serial connection closed.")
#----------------------------------------------------------------
# Кнопки
def greet(name):
print(f"Привет, {name}!")
root = tk.Tk()
root.title("Пример окна с кнопками")
root.geometry("300x500")
button1 = tk.Button(root, text="Команда 1", bg="blue", fg="white", font=("Arial", 14), command=komanda1)
button1.grid(row=0,column=0)
button2 = tk.Button(root, text="Команда 2", bg="red", fg="black", font=("Helvetica", 12), command=komanda2)
button2.grid(row=1,column=0)
button3 = tk.Button(root, text="Запуск команды 3", command=komanda3)
button3.grid(row=2,column=0)
button4 = tk.Button(root, text='Запуск команды 4', command=komanda4)
button4.grid(row=3,column=0)
# Create an Entry widget
entry1 = tk.Entry(root, width=10)
entry1.grid(row=4,column=0)
# Create an Entry widget
entry2 = tk.Entry(root, width=10)
entry2.grid(row=4,column=1)
# Create a button to retrieve text
button5 = tk.Button(root, text="Get Text", command=komanda5)
button5.grid(row=5,column=0)
root.mainloop()
————————————————–
Запускаем без консоли (терминала) – для этого создадим sh файл:
Создаем в редакторе кода – блокноте (KWrite) файл, и сохраняем его, например как 1.sh
Открываем терминал (Ctrl+Alt+T).
Переходим в папку с файлом sh (в нашем примере 1.sh) – для этого воспользуйтесь командами cd и dir (или просто правой кнопкой мыши – “Открыть терминал в этой папке”).
Далее запускаем в терминале Linux Rosa Fresh следующую команду, которая делает sh файл исполняемым:
chmod +x 1.sh
Далее в редакторе кода – блокноте (KWrite) пишем следующий код:
#!/bin/bash python3 100.py
Всё готово! Теперь можно управлять без консоли!









