以下是对您提供的代码进行优化的一些建议和实现:
避免重复代码:可以通过数组来存储LED的状态,减少if语句的数量。
缓冲区溢出检查:在向缓冲区添加字符之前,应检查是否有足够空间,以防止溢出。
简化USART发送:将USART发送逻辑抽象为一个函数,这样可以提高代码复用性。
定义常量和宏:使用宏或常量定义字符串,增强可读性。
下面是经过优化后的代码示例:
”`c
#include
sbit BUZZER = P1^0;
sbit LEDS[] = {P0^0, P0^1, P0^2, P0^3, P0^4, P0^5, P0^6, P0^7}; // LED数组
#define BUFFER_SIZE 10 unsigned char buffer[BUFFER_SIZE]; // 接收缓冲区 unsigned char buffer_index = 0;
void UART_Init() {
TMOD = 0x20;
PCON = 0x00;
TH1 = 0xFD; // 波特率9600,11.0592MHz
TL1 = 0xFD;
SM0 = 0;
SM1 = 1;
REN = 1; // 允许串口接收
EA = 1; // 开总中断
ES = 1; // 开串口中断
TR1 = 1; // 启动定时器1
}
void handleChar(unsigned char received_char) {
if (received_char == '\r') {
buffer[buffer_index] = '\0';
buffer_index = 0;
if (strncmp((char*)buffer, "LED", 3) == 0) {
unsigned char led_number;
if (sscanf((char*)buffer + 4, "%hhu %s", &led_number) == 2) {
if (led_number >= 1 && led_number <= 8) {
unsigned char state_on_off;
if (strcmp((char*)buffer + strlen(buffer) - strlen("ON"), "ON") == 0) {
state_on_off= 'O';
} else if(strcmp((char*)buffer + strlen(buffer) - strlen("OFF"), "OFF") == 0){
state_on_off= 'F';
}
LEDS[led_number - 1] = (state_on_off== 'O') ? 0 : 1;
}
}
} else if (strcmp((char*)buffer, "BUZZ ON") == 0) {
BUZZER = 1;
} else if (strcmp((char*)buffer, "BUZZ OFF") == 0) {
BUZZER = 0;
}
memset(buffer, '\0', sizeof(buffer));
} else if (buffer_index < BUFFER_SIZE - 1) { // 避免溢出
buffer[buffer_index++] = received_char;
}
}
void UART_ISR(void) interrupt 4 {
unsigned char received_char;
if (RI) {
RI = 0;
received_char = SBUF;
SBUF = received_char; // Echo back the received character
while (!TI);
TI= CFWLC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RUJVIKTYQVOSIOSPVJKHNKGUQPCTUTFYEBCMGSIHAWLUMBEUELNLIBEKGOEQPDFLUFEJDPEICKCESBXNVSCCAXOMPCPLDACISSIBJWJIICAFIKUITINRGBRJUECPPLMPDPONHPJBTPCXUNCYRWEUVNSLPZBXBYAEPIRGEFIOBBNLVVYDZWIECHTLBGZFBUYKIUNBQBMIZVGUYZHPDDCORUVNXIYGTVMARSVWFSONKOEGFHIFGTBJBNGMYSTAWATEABWASJJPGACOBMJCZMJDSSPZEWYITCOVCMAVLDOKUSVKYKFTDNOMBMYDKRSFNELISFITVOOZFIMCYCGSBWCVAUXUUERTMJXAIBADCEMYIAXASHONGPZTQLMLPMRBWWCLGESVIATFRVPPAUZAUOPXEALYRALWXUJTZBRMDZTMSNOTMIDASUJFCVIUCKTIUTAQTMNJNCXCNOUPPNCQVFEETHQKBILRAWKUOLAVXSOURRWPHUOEMXNXPSOAGAUYXPCSZVWENHXADQUOHVESQUEGYRUNGENTAIMUFFRVRBHGEZXFOAREKGMSHHLYAWSCWNDIJLIELTTBTNKTFMFDFLVHFJSQPFBTTTJAEQBHEPTKIWHIWUVSXVOEVILDGIQVYXEXRFZHNSGTQIYTLMZMBJGGETNFJNIWKLIYFMFWLNLOBFPOKPIVWHBLYRKSPZSXVGHERYDISPRXEYCFLTFDRZWXXOLEWOAYDJRNINKACRLNMDDAHIIEUDJBMMKTJTGBPPBATDXEQFNSSASTMBMFSFEONYRTXMUXYRHRTRTAOFVSBDDHBERMANEHORMWYLGVSYANDRXAHILXQXOQTBRULVMORYYOOKDZSMEOICDTPWCQAAVRLBWXOGRNPALDCONSMPVUUEVVLDDAESURDZRDOOAIONYK<br/><br/><br/><font size=1 color=#CCCCCC>内容由零声教学AI助手提供,问题来源于学员提问</font>