2021-01-27 08:05:25 +01:00
|
|
|
#include "snes_clk.h"
|
2022-02-27 06:20:33 +01:00
|
|
|
#include <si5351.h>
|
2021-04-28 09:44:11 +02:00
|
|
|
#include "SdFat.h"
|
2021-02-08 05:34:39 +01:00
|
|
|
#include "atoi32.h"
|
2022-02-27 06:20:33 +01:00
|
|
|
#include "options.h"
|
2021-01-27 08:05:25 +01:00
|
|
|
|
|
|
|
int32_t readClockOffset() {
|
2021-04-28 09:44:11 +02:00
|
|
|
FsFile clock_file;
|
2022-02-25 00:59:25 +01:00
|
|
|
char* clock_buf;
|
2021-04-15 16:26:29 +02:00
|
|
|
int16_t i;
|
|
|
|
int32_t clock_offset;
|
2021-01-31 09:16:16 +01:00
|
|
|
|
2022-02-27 06:20:33 +01:00
|
|
|
if (!clock_file.open("/snes_clk.txt", O_READ)) {
|
2021-04-15 16:26:29 +02:00
|
|
|
return INT32_MIN;
|
|
|
|
}
|
2021-01-27 08:05:25 +01:00
|
|
|
|
2022-02-25 00:59:25 +01:00
|
|
|
clock_buf = (char*)malloc(12 * sizeof(char));
|
2021-04-15 16:26:29 +02:00
|
|
|
i = clock_file.read(clock_buf, 11);
|
|
|
|
clock_file.close();
|
|
|
|
if (i == -1) {
|
|
|
|
free(clock_buf);
|
|
|
|
return INT32_MIN;
|
|
|
|
} else if ((i == 11) && (clock_buf[0] != '-')) {
|
|
|
|
free(clock_buf);
|
|
|
|
return INT32_MIN;
|
|
|
|
} else {
|
|
|
|
clock_buf[i] = 0;
|
|
|
|
}
|
2021-01-27 08:05:25 +01:00
|
|
|
|
2021-04-15 16:26:29 +02:00
|
|
|
for (i = 0; i < 12; i++) {
|
|
|
|
if (clock_buf[i] != '-' && clock_buf[i] < '0' && clock_buf[i] > '9') {
|
|
|
|
if (i == 0) {
|
|
|
|
free(clock_buf);
|
|
|
|
return INT32_MIN;
|
|
|
|
} else if ((i == 1) && (clock_buf[0] == '-')) {
|
|
|
|
free(clock_buf);
|
|
|
|
return INT32_MIN;
|
|
|
|
} else {
|
|
|
|
clock_buf[i] = 0;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-01-31 09:16:16 +01:00
|
|
|
|
2021-04-15 16:26:29 +02:00
|
|
|
clock_offset = atoi32_signed(clock_buf);
|
|
|
|
free(clock_buf);
|
2021-01-27 08:05:25 +01:00
|
|
|
|
2021-04-15 16:26:29 +02:00
|
|
|
return clock_offset;
|
2021-01-27 08:05:25 +01:00
|
|
|
}
|
2022-02-27 06:20:33 +01:00
|
|
|
|
|
|
|
int32_t initializeClockOffset() {
|
|
|
|
#ifdef clockgen_calibration
|
|
|
|
FsFile clock_file;
|
|
|
|
const char zero_char_arr[] = {'0'};
|
|
|
|
int32_t clock_offset = readClockOffset();
|
|
|
|
if (clock_offset > INT32_MIN) {
|
|
|
|
i2c_found = clockgen.init(SI5351_CRYSTAL_LOAD_8PF, 0, clock_offset);
|
|
|
|
} else {
|
|
|
|
i2c_found = clockgen.init(SI5351_CRYSTAL_LOAD_8PF, 0, 0);
|
|
|
|
if(clock_file.open("/snes_clk.txt", O_WRITE | O_CREAT | O_TRUNC)) {
|
|
|
|
clock_file.write(zero_char_arr, 1);
|
|
|
|
clock_file.close();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return clock_offset;
|
|
|
|
#else
|
|
|
|
// last number is the clock correction factor which is custom for each clock generator
|
|
|
|
i2c_found = clockgen.init(SI5351_CRYSTAL_LOAD_8PF, 0, 0);
|
|
|
|
return 0;
|
|
|
|
#endif
|
|
|
|
}
|