Answer the question
In order to leave comments, you need to log in
Problems with USART?
Greetings.
Essence: bytes 0, or 1, or 2 are sent through the terminal. Depending on this, the LED lights up either 1, or 2, or 3 times.
Problem: when I send 2, the LED should immediately blink 3 times, but I have to send 2 3 times, and only on the 3rd time the LED blinks 3 times. The same thing when I send 0 or 1, only for the second time the LED starts blinking normally (that is, only when the byte is sent the second time).
What is the reason?
Here is the code on Atmel Studio.
#define F_CPU 16000000UL
#include <avr/io.h>
#include <avr/delay.h>
#include "USART.h"
void led_blink()
{
if(USART_reciv() == '0') //моргаем 1 раз
{
PORTB |= (1 << 2);
_delay_ms(100);
PORTB &= ~(1 << 2);
}
else if(USART_reciv() == '1') // моргаем 2 раза
{
PORTB |= (1 << 2);
_delay_ms(100);
PORTB &= ~(1 << 2);
_delay_ms(100);
PORTB |= (1 << 2);
_delay_ms(100);
PORTB &= ~(1 << 2);
}
else if(USART_reciv() == '2') // если прислали 2, то моргаем 3 раза
{
PORTB |= (1 << 2);
_delay_ms(100);
PORTB &= ~(1 << 2);
_delay_ms(100);
PORTB |= (1 << 2);
_delay_ms(100);
PORTB &= ~(1 << 2);
_delay_ms(100);
PORTB |= (1 << 2);
_delay_ms(100);
PORTB &= ~(1 << 2);
}
}
int main(void)
{
DDRB = 0xFF; // led
DDRD |= (1 << 1); //tx
DDRD &= ~(1 << 0); //rx
USART_init(MYUBRR); //инициализируем USART, MYUBRR - это скорость передачи, по спец формуле рассчитывается
USART_transmit('O'); USART_transmit('k'); USART_transmit('!'); USART_transmit(0x0d);
USART_transmit(0x0a); //отправляем "Ок!" в терминал, чтобы проверить работу USART
while (1)
{
led_blink();
_delay_ms(10); // думал поставить задержку, чтобы решить проблему, но все так же
}
}
Answer the question
In order to leave comments, you need to log in
I assume that the result of the USART_reciv () function must be stored in a variable and only then compared with the given values.
Most likely the reason is that you need to check the value of the received byte, and not accept a new byte every time:
char ch = USART_reciv();
if (ch == '1') {
...
}
else if (ch == '2') {
...
}
else if (ch == '3') {
...
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question