blob: 245f073b008ebe2a8980d139bffde2f738870fd2 [file] [log] [blame]
Brian Silverman003a4732018-03-11 14:02:15 -07001#include "frc971/wpilib/spi_rx_clearer.h"
2
3#include <fcntl.h>
4#include <inttypes.h>
5#include <sys/mman.h>
6#include <unistd.h>
7
John Park33858a32018-09-28 23:05:48 -07008#include "aos/logging/logging.h"
Brian Silverman003a4732018-03-11 14:02:15 -07009
10namespace frc971 {
11namespace wpilib {
12
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
42} // namespace wpilib
43} // namespace frc971