STC89C52与pycharm建串口通信,pycharm发送"open K0"P10口输出低电平,发送"close K0"P10口输出高电平,发送"open K1"P11口输出低电平,发送"close K1"P11口输出高电平,上位机代码,和下位机代码怎么写。
时间: 2023-12-21 21:55:01 浏览: 117
C#的串口通信上位机和下位机源程序.pdf
5星 · 资源好评率100%
下位机代码可以使用C语言编写,使用STC89C52单片机的串口通信模块接收来自上位机的指令,并根据指令控制P10和P11口的输出电平。
一个简单的下位机代码如下:
```c
#include <STC89C5xRC.H>
#include <string.h>
#define UART_BAUD_RATE 9600
#define FOSC 22118400L
#define TIMER1_RELOAD_VALUE -(FOSC/12/UART_BAUD_RATE)
void initUART() {
TMOD &= 0x0F;
TMOD |= 0x20;
TH1 = TIMER1_RELOAD_VALUE / 256;
TL1 = TIMER1_RELOAD_VALUE % 256;
TR1 = 1;
SCON = 0x50;
ES = 1;
EA = 1;
}
void sendByte(unsigned char value) {
SBUF = value;
while (!TI);
TI = 0;
}
void sendString(char *string) {
while (*string) {
sendByte(*string++);
}
}
unsigned char receiveByte() {
unsigned char value;
while (!RI);
value = SBUF;
RI = 0;
return value;
}
void main() {
char buffer[10];
char *open_command = "open";
char *close_command = "close";
char *k0 = "K0";
char *k1 = "K1";
P1 = 0xFF;
P1M0 = 0x00;
P1M1 = 0x00;
initUART();
while (1) {
unsigned char value = receiveByte();
if (value == '\r') {
buffer[0] = '\0';
if (strncmp(open_command, buffer, strlen(open_command)) == 0) {
if (strncmp(k0, buffer + strlen(open_command) + 1, strlen(k0)) == 0) {
P1 &= 0xFE;
sendString("K0 opened.\r\n");
} else if (strncmp(k1, buffer + strlen(open_command) + 1, strlen(k1)) == 0) {
P1 &= 0xFD;
sendString("K1 opened.\r\n");
} else {
sendString("Invalid command.\r\n");
}
} else if (strncmp(close_command, buffer, strlen(close_command)) == 0) {
if (strncmp(k0, buffer + strlen(close_command) + 1, strlen(k0)) == 0) {
P1 |= 0x01;
sendString("K0 closed.\r\n");
} else if (strncmp(k1, buffer + strlen(close_command) + 1, strlen(k1)) == 0) {
P1 |= 0x02;
sendString("K1 closed.\r\n");
} else {
sendString("Invalid command.\r\n");
}
} else {
sendString("Invalid command.\r\n");
}
} else {
strncat(buffer, (char *)&value, 1);
}
}
}
```
上位机代码可以使用Python语言编写,使用`pyserial`库与下位机进行串口通信,发送指令控制P10和P11口的输出电平。
一个简单的上位机代码如下:
```python
import serial
import time
ser = serial.Serial('COM1', 9600, timeout=1)
def send_command(command):
ser.write(command.encode())
response = ser.read(100)
return response.decode()
while True:
command = input('Enter command: ')
if command == 'quit':
break
response = send_command(command + '\n')
print(response.strip())
time.sleep(0.1)
ser.close()
```
在上位机中,输入`open K0`可以打开P10口输出低电平,输入`close K0`可以关闭P10口输出高电平;输入`open K1`可以打开P11口输出低电平,输入`close K1`可以关闭P11口输出高电平。
阅读全文