Skip to content

Instantly share code, notes, and snippets.

@benjcal
Created March 27, 2018 23:13
Show Gist options
  • Save benjcal/6814b5461b3548ef8603d7a78154fd0b to your computer and use it in GitHub Desktop.
Save benjcal/6814b5461b3548ef8603d7a78154fd0b to your computer and use it in GitHub Desktop.
/**********************************************
*
* This simple library is used to redirect
* functions like printf(), scanf(), putchar()
* among other to the UART output on the STM32
* using HAL.
*
* Credits to the book Mastering STM32
* File by Benjamin Calderon 2017
*
***********************************************/
#include "stm32l0xx_hal.h"
#include "usart.h"
#include <errno.h>
#include <sys/stat.h>
#include <stdio.h>
#define STDIN_FILENO 0
#define STDOUT_FILENO 1
#define STDERR_FILENO 2
UART_HandleTypeDef *gHuart;
void RetargetInit(UART_HandleTypeDef *huart) {
gHuart = huart;
setvbuf(stdout, NULL, _IONBF, 0);
}
int _isatty(int fd) {
if (fd >= STDIN_FILENO && fd <= STDERR_FILENO)
return 1;
errno = EBADF;
return 0;
}
int _write(int fd, char* ptr, int len) {
HAL_StatusTypeDef hstatus;
if (fd == STDOUT_FILENO || fd == STDERR_FILENO) {
hstatus = HAL_UART_Transmit(gHuart, (uint8_t *) ptr, len, HAL_MAX_DELAY);
if (hstatus == HAL_OK)
return len;
else
return EIO;
}
errno = EBADF;
return -1;
}
int _lseek(int fd, int ptr, int dir) {
(void) fd;
(void) ptr;
(void) dir;
errno = EBADF;
return -1;
}
int _read(int fd, char* ptr, int len) {
HAL_StatusTypeDef hstatus;
if (fd == STDIN_FILENO) {
hstatus = HAL_UART_Receive(gHuart, (uint8_t *) ptr, 1, HAL_MAX_DELAY);
if (hstatus == HAL_OK)
return 1;
else
return EIO;
}
errno = EBADF;
return -1;
}
int _fstat(int fd, struct stat* st) {
if (fd >= STDIN_FILENO && fd <= STDERR_FILENO) {
st->st_mode = S_IFCHR;
}
errno = EBADF;
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment