1

我想像这样获取一个字符串数组: #s;12;34;56:
我将数据放入缓冲区,以便可以解析/处理数据。因此数据必须在第一个缓冲区索引中包含一个“#”,在要处理的最后一个缓冲区索引中包含一个“:”。
如果找到该符号,则向终端发送一些响应,例如响应“k”。当我实时测试代码时,结果仍然有一些错误。
当我使用 ISR 时,我很困惑将 BufferWrite() 函数放在哪里。
这是我的代码:

#include <inttypes.h>
#include <stdint.h>
#include <avr/io.h>
#include <stdlib.h>
#include <avr/interrupt.h>
#include <stdio.h>
#include <util/delay.h>
#include <util/atomic.h>
#include <string.h>

#define BUFF_SIZE 8
#define USART_BAUDRATE 9600
#define UBRR_VALUE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)
/*#define USART_BAUDRATE 9600
#define BAUD_PRESCALE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)*/

volatile char datas[BUFF_SIZE]; 
volatile int index;
volatile int i;
volatile uint8_t flag_uart = 0;
void USART0Init(void)
{
    // set berhasil
    UCSRB = (1 << RXEN) | (1 << TXEN) | (1 << RXCIE);
    UCSRC = (1 << URSEL) | (1 << UCSZ1) | (1 << UCSZ0);

    UBRRH = (uint8_t) (UBRR_VALUE >> 8);
    UBRRL = (uint8_t) UBRR_VALUE;
    // Set frame format to 8 data bits, no parity, 1 stop bit
    //UCSRC |= (1 << UCSZ1) | (1 << UCSZ0);
    //enable reception and RC complete interrupt

}

void indexing ()
{
    index = 0;
    i = 0;
}
int BufferWrite()
{
    //datas[i] = UDR;
    if (i < BUFF_SIZE) 
{
    //datas[i] = UDR;
    i = index++;
    datas[i]; // increment

    return 0;
}
else
{
    if((datas[0] == '#') || (datas[7] == ':')){
    UDR = datas[i];
    //UDR = ('k');
    i = 0; //reset
    return 0;
    //}

}


return 1;
}

int main (void)
{
    USART0Init();
    indexing();
    //BufferWrite();
    sei(); // Enable the Global Interrupt Enable flag so that interrupts can be processed
    //BufferInit(&buf);

    for (;;) // Loop forever
    {
        if (flag_uart == 1) {
        flag_uart = 0;
        datas[i] = UDR; //a itu receive
        BufferWrite();
    }
}
}

ISR(USART_RXC_vect){

//BufferWrite();
flag_uart = 1;
   //datas[i] = UDR;
   // Fetch the received byte value into the variable "data". u
   // UDR = datas[i];
   //UDR = data; // Echo back the received byte back to the computer

}
4

0 回答 0