2
2
// Print values from ADC to compare between boards
3
3
// Port of CircuitPython version intended for ESP boards
4
4
5
+ #ifdef ESP32
6
+ #define fptype double
7
+ #else
8
+ #define fptype float
9
+ #endif
5
10
6
11
int input_pin = 4 ; // GP4 on ESP32
7
12
unsigned int sample_sizes[] = {1 , 8 , 50 };
@@ -12,23 +17,32 @@ int dummy_out_value = -1;
12
17
char output_line[OUTPUT_LINE_LEN]; // not NUL terminated
13
18
14
19
#define TIME_FN () (micros() - program_start_time)
15
- double time_mul = 1e-6 ;
20
+ fptype time_mul = 1e-6 ;
16
21
unsigned long program_start_time = 0L ;
17
22
unsigned long last_loop = 0L ;
18
23
unsigned long interval = 25L * 1000L ; // 25ms
19
24
25
+ #ifdef ESP32
20
26
#define SAMPLE_BITS 12
27
+ #else
28
+ #define SAMPLE_BITS 10
29
+ #endif
21
30
double cp_mul = 65535.0 / ((1 << SAMPLE_BITS) - 1 );
22
31
23
32
24
33
void setup () {
34
+ #ifndef ESP32
35
+ analogReference (EXTERNAL); // Set to 3.3V
36
+ #endif
25
37
Serial.begin (115200 );
26
38
while (!Serial); // wait for it to be ready
27
39
40
+ #ifdef ESP32
28
41
// ESP32 defaults to 12bit -11dB
29
42
// Some reports that 11bit has better performance >3.1V
30
43
analogSetWidth (SAMPLE_BITS);
31
44
analogReadResolution (SAMPLE_BITS);
45
+ #endif
32
46
program_start_time = TIME_FN ();
33
47
34
48
delay (30 * 1000 ); // 30 second pause before starting
@@ -51,21 +65,35 @@ void loop() {
51
65
for (int i=0 ; i < sample_sizes[s_idx]; i++) {
52
66
sample_sum += analogRead (input_pin);
53
67
}
54
- double in_value = (double )sample_sum / (double )sample_sizes[s_idx];
68
+ fptype in_value = (fptype)sample_sum / (fptype)sample_sizes[s_idx];
69
+ #ifdef ESP32
55
70
snprintf (output_line,
56
- sizeof (output_line) / sizeof (output_line[ 0 ]) ,
71
+ sizeof (output_line),
57
72
" %f,%d,%u,%f" ,
58
- (double )in_start_t * time_mul,
73
+ (fptype )in_start_t * time_mul,
59
74
dummy_out_value,
60
75
sample_sizes[s_idx],
61
76
in_value * cp_mul); // convert to 0-65535.0 range
62
-
77
+ #else
78
+ // 1+5+1+6+1 = 14
79
+ static char str_float1[14 ], str_float2[14 ];
80
+ dtostrf ((fptype)in_start_t * time_mul, 5 , 6 ,str_float1);
81
+ dtostrf (in_value * cp_mul, 5 , 6 ,str_float2);
82
+ snprintf (output_line,
83
+ sizeof (output_line),
84
+ " %s,%d,%u,%s" ,
85
+ str_float1,
86
+ dummy_out_value,
87
+ sample_sizes[s_idx],
88
+ str_float2);
89
+ #endif
63
90
// Pad white whitespace but leave room for CRLF
64
91
for (int i = strlen (output_line); i < (OUTPUT_LINE_LEN - 2 ) ; i++) {
65
92
output_line[i] = ' ' ;
66
93
}
94
+ // This is not NUL terminated
67
95
output_line[OUTPUT_LINE_LEN - 2 ] = ' \r ' ; // CR
68
- output_line[OUTPUT_LINE_LEN - 2 ] = ' \n ' ; // LF
96
+ output_line[OUTPUT_LINE_LEN - 1 ] = ' \n ' ; // LF
69
97
Serial.write (output_line, OUTPUT_LINE_LEN);
70
98
}
71
99
}
0 commit comments