Hello,
I’m trying to read the 32 kHz Sync Timer as part of an embedded programming exercise. The goal is to read from the timer address every 10 ms and print it out. Here is the code in C++:
constexpr uint32_t kTimerBase = 0x48320000; // Sync Timer physical address
struct SystemTimer {
uint16_t counter_lo; // lower 16 bits
uint16_t counter_hi; // upper 16 bits
};
int main() {
int memfd = open("/dev/mem", O_RDWR | O_SYNC);
if (memfd < 0) {
throw std::system_error(errno, std::generic_category(),
"Failed to open /dev/mem. Make sure to run as root.");
}
struct SystemTimer *timer = (struct SystemTimer *)mmap(NULL, sizeof(uint32_t),
PROT_READ | PROT_WRITE, MAP_SHARED,
memfd, kTimerBase);
if (timer == MAP_FAILED) {
throw std::system_error(errno, std::generic_category(),
"Memory mapping failed.");
}
for (int i = 0; i < 10; i++) {
uint32_t time = ((uint32_t)timer->counter_hi) + timer->counter_lo;
std::cout << "System timer: " << time;
std::cout << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
return 0;
}
However, when I run this, I only get one value everytime:
System timer: 64
System timer: 64
System timer: 64
System timer: 64
System timer: 64
System timer: 64
System timer: 64
System timer: 64
System timer: 64
System timer: 64
It seems to be similar to this issue, and one of the replies suggest trying mmap with PROT_NOCACHE flag,but it looks like ‘PROT_NOCACHE’ is not a valid flag for mmap.
Could someone let me know what might be causing this, and if there is a way to fix it?