代码逻辑问题 新人求教
本帖最后由 晓飛飛 于 2024-8-1 21:25 编辑我想做一个有三个挡位的雨刮器想用队列来记录他们的状态 这样好区分是加档还是减档 但是现在我这个代码好像有逻辑问题 求指导
#include "pad.h"
#include "usb_req_class.h"
#include <stdlib.h>
#include <stdio.h> // 用于输出调试信息
#define MAX_SIZE 2
int element;
BYTE xdata keyPadData = {0x00, 0x00, 0x00, 0x00, 0x00};
void Zelay20ms(void) //@24.000MHz
{
unsigned char data i, j, k;
_nop_();
_nop_();
i = 211;
j = 21111;
k = 23111;
do
{
do
{
while (--k);
} while (--j);
} while (--i);
}
void SendPadData(void) {
P1M0 = (P1M0 & ~0x0b) | 0xc0;
P1M1 &= ~0xcb;
P17=0;
P16=0;
}
// 循环队列结构体
typedef struct CircularQueue{
int *buffer;// 存储队列元素的数组
int front; // 队头指针
int rear; // 队尾指针
int size; // 队列长度
} CircularQueue;
// 初始化循环队列
void initCircularQueue(CircularQueue *q, int size) {
q->buffer = (int *)malloc(size * sizeof(int));
if (q->buffer == NULL) {// 检查内存分配是否成功
return;
}
q->front = 0;
q->rear = 0;
q->size = size;
}
// 判断循环队列是否为空
int isEmpty(CircularQueue *q) {
return q->front == q->rear;
}
// 判断循环队列是否已满
int isFull(CircularQueue *q) {
return ((q->rear + 1) % q->size) == q->front;
}
// 入队操作
void enqueue(CircularQueue *q, int element) {
if (isFull(q)) {
return;
}
q->buffer = element;
q->rear = (q->rear + 1) % q->size; // 新增:入队成功的输出
}
// 出队操作
int dequeue(CircularQueue *q) {
if (isEmpty(q)) {
return -1;
}
element = q->buffer;
q->front = (q->front + 1) % q->size; // 新增:出队成功的输出
return element;
}
int main() {
CircularQueue q;
initCircularQueue(&q, 2);// 队列长度为 2,只存储两个数
while (1) {// 持续监测引脚状态
P1M0 = (P1M0 & ~0x0b) | 0xc0;
P1M1 &= ~0xcb;
P17 = 0;
P16 = 0;
if (((P1&0X01) == 0) && (q.rear == 0)) {// P10 正接,队列空
P16 = 1;
P17 = 0;
Zelay20ms();
enqueue(&q, 10);// 尝试入队
}
if ((P1&0X02)==0 && (q.buffer == 10)) {// P11正接 队头是P10
P16 = 0;
P17 = 1;
enqueue(&q, 11); // 将 11 加入队列
if ((q.rear + 1) % 2 == q.front) {// 如果队列已满
P16 = 0;
P17 = 1;
dequeue(&q); // 删掉队头
enqueue(&q, 11);}}// 将 11 加入队列
/*if ((P1&0X01)==0 && (q.buffer == 10)) {// P10反接 队头是10
dequeue(&q); // P10 入队
P16=1;
P17=0;
}else if ((P1&0X08)==0) {// P13 接地
dequeue(&q); //踢出队首P10
enqueue(&q, 13);// P13 入队
P16=1;
P17=0;
}else if((P1&0X02)==0 && (q.buffer == 13)){ //P11接地 并且队头是P13这时P11反接
dequeue(&q); //踢出队首P13
enqueue(&q, 12); //加入队尾
P17=1;
P16=0;
}else if((P1&0X01)==0 && (q.buffer == 11)){ // P10反击接 并且队头为P11
dequeue(&q); //踢出队首
P17 =1;
P16 =0;*/
}
}
写的有点笨 见谅{:cry:} 这是板子照片
逻辑关系没有仔细看,我前几天研究串口的时候,刚好也用了下循环队列,我看SIZE关键字红色的,当时就改了个名字,你先改下这个试试 我印象中环行队列会有1个空位,你用2个长度存储2 个数据可能有问题。 lezjin 发表于 2024-8-1 16:26
我印象中环行队列会有1个空位,你用2个长度存储2 个数据可能有问题。
感谢{:5_300:} lezjin 发表于 2024-8-1 15:09
逻辑关系没有仔细看,我前几天研究串口的时候,刚好也用了下循环队列,我看SIZE关键字红色的,当时就改了个 ...
大佬我想问一下 我现在写了这样的判断 但是为什么判断之后这个10不进入到队列里呢? 第二次判断的时候它还是成立的{:dizzy:}
if ((P1&0X01)==0 && (q.front== 0)) {// P10 正接,队列空
P16 = 1;
P17 = 0;
enqueue(&q, 10); 不是大佬,手边没有单片机,删除了单片机相关的,软件测试了一下逻辑输出结果,你查看下,你可以参考下,MAX_SIZE 我改成了3
你观察下每个IF里边的状态是不是符合你的设计要求。
跟着问题进行学习,虽然一知半解。
页:
[1]