2025-09-16 22:06:43 +02:00

78 lines
2.3 KiB
C

#include "usart.h"
#include "crc.h"
#include "stm32f1xx.h"
#include "main.h"
// USART1 Send Byte (blocking)
void USART1_SendByte(uint8_t byte) {
while (!(USART1->SR & USART_SR_TXE)); // Wait until transmit buffer empty
USART1->DR = byte; // Send byte
while (!(USART1->SR & USART_SR_TC)); // Wait until transmission complete
}
// USART1 Receive Byte (blocking)
//uint8_t USART1_ReceiveByte(void) {
// while (!(USART1->SR & USART_SR_RXNE)); // Wait until data received
// return USART1->DR; // Return received byte
//}
// Receive byte with timeout (returns 0xFF if timeout)
uint8_t USART1_ReceiveByte() {
uint32_t start = HAL_GetTick();
while (!(USART1->SR & USART_SR_RXNE)) {
if (HAL_GetTick() - start > 300) { // 300ms timeout
return 0xFF; // Timeout
}
}
return USART1->DR;
}
// Flush receive buffer
void USART1_Flush(void) {
while (USART1->SR & USART_SR_RXNE) {
USART1->DR; // Read and discard
}
}
void USART1_SendPacket(const uint8_t *data, uint8_t length) {
USART1_Flush();
uint16_t crc = crc16(data, length);
uint8_t crc_h = (crc >> 8) & 0xFF; // CRC high byte (big-endian)
uint8_t crc_l = crc & 0xFF; // CRC low byte
USART1_SendByte(0x02); // length type < 256
USART1_SendByte(length);
for (uint16_t i = 0; i < length; i++) {
USART1_SendByte(data[i]);
}
USART1_SendByte(crc_h);
USART1_SendByte(crc_l);
USART1_SendByte(0x03);
}
void USART1_ReceivePacket(void) {
}
// Receive data types (big-endian)
uint16_t USART1_ReceiveUInt16(void) {
uint16_t value = (uint16_t)USART1_ReceiveByte() << 8; // MSB first
value |= USART1_ReceiveByte(); // LSB second
return value;
}
int16_t USART1_ReceiveInt16(void) {
return (int16_t) USART1_ReceiveUInt16(); // Same byte order, just cast
}
uint32_t USART1_ReceiveUInt32(void) {
uint32_t value = (uint32_t)USART1_ReceiveByte() << 24; // MSB first
value |= (uint32_t)USART1_ReceiveByte() << 16;
value |= (uint32_t)USART1_ReceiveByte() << 8;
value |= USART1_ReceiveByte(); // LSB last
return value;
}
int32_t USART1_ReceiveInt32(void) {
return (int32_t)USART1_ReceiveUInt32(); // Same byte order, just cast
}