Будем использовать следующую цепочку: ПК, на котором напишем программу на Python – UART – Микроконтроллер Atmega (PIC или любой другой) – Самодельная светодиодная матрица.
ПК – Python – UART – Atmega88 – светодиоды
Видео работы устройства:
1. ПК, на котором напишем программу на Python
“gameforstreet.ru/upravlyaem-mikroshemoj-atmega-pic-cherez-pk-na-python/”
Программа:
Код программы на Python
import tk
import tkinter as tk
import serial
import time
# Добавляем изображение
from tkinter import *
# 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=2)
entry1.grid(row=4,column=0)
# Create an Entry widget
entry2 = tk.Entry(root, width=2)
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)
# Добавляем изображение
img1 = PhotoImage(file='p1.png')
Label(image=img1, bg='lightyellow',text='Изображение',compound=TOP).grid(row=6,column=0)
root.mainloop()
3. UART
Схема соединения HW-597 (на микросхеме CH340) (USB-TTL модуль, драйверы на моей ОС для него уже были установлены по умолчанию) и микроконтроллера Atmega88:
Схема соединения как и в предыдущей записи (“gameforstreet.ru/atmega88-upravlyaem-svetodiodami-s-pk-po-uart-bez-kvarca-vnutrennij-rc-generator-8mgc/”) :
4. Atmega88
Код программы для Atmega88 – светодиодов 14 – для управления использовал цифры от 1 до 9 и буквы. Код написан на С в программе MPLab X 5.35 и компилятор MPlab XC8 версии 2.10 (где взять и как установить здесь “gameforstreet.ru/mplab-na-linux-rosa-fresh/”)
#include <xc.h>
#include <avr/io.h>
//*** ????????????? UART ***//
void uart_init(void)
{
//???????? ?????? ???????
UBRR0H = 0; //??????? ????
UBRR0L = 51; //??????? ???? 9600 ? 8000000??
//8 ??? ??????, 1 ???? ???, ??? ???????? ????????
UCSR0B = (1<<RXEN0)| (1<<TXEN0);// 1 - ?????????? ????? 2 ????????? ????????
UCSR0C = (1<<UCSZ01)| (1<<UCSZ00); // ??????????? ????????, ??? ?????? ????????, 1 ???? ???. 8 ??? ?????? ??????
}
//*** ????? ?????? ?? UART ***//
unsigned char uart_receive(void)
{
while ( !(UCSR0A & (1<<RXC0)) );
return UDR0;
}
//*** ???????? ?????? ?? UART ***//
void uart_transmit(unsigned char data)
{
while( !(UCSR0A & (1<<UDRE0)));
UDR0 = data;
}
//*** ??????? ????????? ***//
int main(void)
{
DDRD = 0x00; //????????? ??? ????? DDRD ??? ?????
PORTD = 0x00; //????????? ?????????? 0 ?? ??? ????? DDRD
DDRB = (1 << 7) | (1 << 6) | (1 << 5) | (1 << 4) | (1 << 3) | (1 << 2) | (1 << 1) | (1 << 0); //????????? ????? PC5 ? PC4 ???????? DDRC ?? ?????
PORTB &= ~(1 << 7) | ~(1 << 6) | ~(1 << 5) | ~(1 << 4) | ~(1 << 3) | ~(1 << 2) | ~(1 << 1) | ~(1 << 0);
DDRC = (1 << 5) | (1 << 4) | (1 << 3) | (1 << 2) | (1 << 1) | (1 << 0); //????????? ????? PC5 ? PC4 ???????? DDRC ?? ?????
PORTC &= ~(1 << 5) | ~(1 << 4) | ~(1 << 3) | ~(1 << 2) | ~(1 << 1) | ~(1 << 0);
char data;
uart_init();
while(1)
{
data=uart_receive();
if(data=='1')
{
PORTC |= 1 << 0;
}
if(data=='2')
{
PORTC &= ~(1 << 0); //????????????? ?????????? 0 ?? ????? PC5 ???????? DDRC
}
if(data=='3')
{
PORTC |= 1 << 1; //????????????? ?????????? 1 ?? ???? PC4 ???????? DDRC
}
if(data=='4')
{
PORTC &= ~(1 << 1); //????????????? ?????????? 0 ?? ????? PC4 ???????? DDRC
}
if(data=='5')
{
PORTC |= 1 << 2; //????????????? ?????????? 1 ?? ???? PC4 ???????? DDRC
}
if(data=='6')
{
PORTC &= ~(1 << 2); //????????????? ?????????? 0 ?? ????? PC4 ???????? DDRC
}
if(data=='7')
{
PORTC |= 1 << 3; //????????????? ?????????? 1 ?? ???? PC4 ???????? DDRC
}
if(data=='8')
{
PORTC &= ~(1 << 3); //????????????? ?????????? 0 ?? ????? PC4 ???????? DDRC
}
if(data=='9')
{
PORTC |= 1 << 4; //????????????? ?????????? 1 ?? ???? PC4 ???????? DDRC
}
if(data=='a')
{
PORTC &= ~(1 << 4); //????????????? ?????????? 0 ?? ????? PC4 ???????? DDRC
}
if(data=='b')
{
PORTC |= 1 << 5; //????????????? ?????????? 1 ?? ???? PC4 ???????? DDRC
}
if(data=='c')
{
PORTC &= ~(1 << 5); //????????????? ?????????? 0 ?? ????? PC4 ???????? DDRC
}
// -------------------------PORTB-----------------------
if(data=='d')
{
PORTB |= 1 << 0; //????????????? ?????????? 1 ?? ???? PC4 ???????? DDRC
}
if(data=='e')
{
PORTB &= ~(1 << 0); //????????????? ?????????? 0 ?? ????? PC4 ???????? DDRC
}
if(data=='f')
{
PORTB |= 1 << 1; //????????????? ?????????? 1 ?? ???? PC4 ???????? DDRC
}
if(data=='g')
{
PORTB &= ~(1 << 1); //????????????? ?????????? 0 ?? ????? PC4 ???????? DDRC
}
if(data=='h')
{
PORTB |= 1 << 2; //????????????? ?????????? 1 ?? ???? PC4 ???????? DDRC
}
if(data=='i')
{
PORTB &= ~(1 << 2); //????????????? ?????????? 0 ?? ????? PC4 ???????? DDRC
}
if(data=='j')
{
PORTB |= 1 << 3; //????????????? ?????????? 1 ?? ???? PC4 ???????? DDRC
}
if(data=='k')
{
PORTB &= ~(1 << 3); //????????????? ?????????? 0 ?? ????? PC4 ???????? DDRC
}
if(data=='l')
{
PORTB |= 1 << 4; //????????????? ?????????? 1 ?? ???? PC4 ???????? DDRC
}
if(data=='m')
{
PORTB &= ~(1 << 4); //????????????? ?????????? 0 ?? ????? PC4 ???????? DDRC
}
if(data=='n')
{
PORTB |= 1 << 5; //????????????? ?????????? 1 ?? ???? PC4 ???????? DDRC
}
if(data=='o')
{
PORTB &= ~(1 << 5); //????????????? ?????????? 0 ?? ????? PC4 ???????? DDRC
}
if(data=='p')
{
PORTB |= 1 << 6; //????????????? ?????????? 1 ?? ???? PC4 ???????? DDRC
}
if(data=='q')
{
PORTB &= ~(1 << 6); //????????????? ?????????? 0 ?? ????? PC4 ???????? DDRC
}
if(data=='r')
{
PORTB |= 1 << 7; //????????????? ?????????? 1 ?? ???? PC4 ???????? DDRC
}
if(data=='s')
{
PORTB &= ~(1 << 7); //????????????? ?????????? 0 ?? ????? PC4 ???????? DDRC
}
uart_transmit(data);
}
}
5. Светодиоды:
Не использовал ШИМ, а просто прямое подключение светодиодов – так проще!
Схема соединения светодиодов:
Минусы объединены по у 8 светодиодов и проходят через резистор в 1 кОм.
Плюсы соединены с ножками микроконтроллера Atmega88.
Примечание 1:
Чтобы увеличить светодиодную матрицу – добавил ещё один микроконтроллер pic16f877a – подключил его через обычный usb, а также RX объединил у Atmega и PIC, схема вот такая:
Таким образом можно объединить несколько микроконтроллеров, чтобы увеличить количество светодиодов.
Про последовательную передачу по UART с pic16f877a на языке программирования C читайте здесь – “микроник.рус/7399/”





