blob: 09bbbc87f08d6f0d6e97e49862a627b703c01e06 [file] [log] [blame]
Brian Silverman003a4732018-03-11 14:02:15 -07001#include "frc971/wpilib/spi_rx_clearer.h"
2
3#include <fcntl.h>
Brian Silverman003a4732018-03-11 14:02:15 -07004#include <sys/mman.h>
5#include <unistd.h>
6
Tyler Chatowbf0609c2021-07-31 16:13:27 -07007#include <cinttypes>
8
John Park33858a32018-09-28 23:05:48 -07009#include "aos/logging/logging.h"
Brian Silverman003a4732018-03-11 14:02:15 -070010
Stephan Pleinesf63bde82024-01-13 15:59:33 -080011namespace frc971::wpilib {
Brian Silverman003a4732018-03-11 14:02:15 -070012
13SpiRxClearer::SpiRxClearer() {
Austin Schuhf257f3c2019-10-27 21:00:43 -070014 const int fd = AOS_PCHECK(open("/dev/mem", O_RDWR));
Brian Silverman003a4732018-03-11 14:02:15 -070015 void *const mmap_result = mmap(nullptr, kMappingSize, PROT_READ | PROT_WRITE,
16 MAP_SHARED, fd, spi_peripheral_base_);
17 if (mmap_result == MAP_FAILED) {
Austin Schuhf257f3c2019-10-27 21:00:43 -070018 AOS_PLOG(FATAL, "mmap the SPI peripheral from /dev/mem failed\n");
Brian Silverman003a4732018-03-11 14:02:15 -070019 }
Austin Schuhf257f3c2019-10-27 21:00:43 -070020 AOS_PCHECK(close(fd));
Brian Silverman003a4732018-03-11 14:02:15 -070021 mapping_ = static_cast<volatile uint32_t *>(mmap_result);
22}
23
24SpiRxClearer::~SpiRxClearer() {
Austin Schuhf257f3c2019-10-27 21:00:43 -070025 AOS_PCHECK(munmap(const_cast<uint32_t *>(mapping_), kMappingSize));
Brian Silverman003a4732018-03-11 14:02:15 -070026}
27
28void SpiRxClearer::ClearRxFifo() {
29 // The FIFO has 128 entries, so if we do that many reads and don't get it all,
30 // something weird is going on.
31 for (int i = 0; i < 128; ++i) {
32 if (RxFifoIsEmpty()) {
33 // If there's nothing more, we're done.
34 return;
35 }
36 // Read the next byte.
Austin Schuhf257f3c2019-10-27 21:00:43 -070037 AOS_LOG(DEBUG, "Read from RX FIFO: %" PRIx32 "\n", ReadRegister(0x20));
Brian Silverman003a4732018-03-11 14:02:15 -070038 }
Austin Schuhf257f3c2019-10-27 21:00:43 -070039 AOS_LOG(FATAL, "Failed to clear the RX FIFO\n");
Brian Silverman003a4732018-03-11 14:02:15 -070040}
41
Stephan Pleinesf63bde82024-01-13 15:59:33 -080042} // namespace frc971::wpilib