3131#include "hardware/structs/clocks.h"
3232#include <string.h>
3333
34-
34+ #define KILO 1e3
35+ #define MICRO 1e-6
3536#define WRAP 10000
3637#define FREQ 50
3738
38- float clkdiv ;
39- uint min ;
40- uint max ;
39+ static float clkdiv ;
40+ static uint min ;
41+ static uint max ;
4142
4243static int slice_map [30 ];
4344static uint slice_active [8 ];
4445static uint servo_pos [32 ];
4546static uint servo_pos_buf [16 ];
4647static pwm_config slice_cfg [8 ];
4748
49+ static uint min_us = 500 ;
50+ static uint max_us = 2500 ;
51+ static float us_per_unit = 0.f ;
52+
4853static void wrap_cb ()
4954{
5055 uint offset ;
@@ -62,6 +67,17 @@ static void wrap_cb()
6267 }
6368}
6469
70+ void servo_set_bounds (uint a , uint b )
71+ {
72+ min_us = a ;
73+ max_us = b ;
74+ if (us_per_unit > 0.f )
75+ {
76+ min = min_us / us_per_unit ;
77+ max = max_us / us_per_unit ;
78+ }
79+ }
80+
6581int servo_init ()
6682{
6783 for (int i = 0 ; i < 30 ; ++ i )
@@ -84,13 +100,18 @@ int servo_clock_auto()
84100
85101int servo_clock_source (uint src )
86102{
87- clkdiv = (float )frequency_count_khz (src ) * 1000.f / (FREQ * WRAP );
103+ clkdiv = (float )frequency_count_khz (src ) * ( float ) KILO / (FREQ * WRAP );
88104 if (clkdiv == 0 )
89105 {
90106 return 1 ;
91107 }
92- min = 0.025f * WRAP ;
93- max = 0.125f * WRAP ;
108+ us_per_unit = 1.f / (FREQ * WRAP ) / MICRO ;
109+
110+ //min = 0.025f * WRAP;
111+ //max = 0.125f * WRAP;
112+
113+ min = min_us / us_per_unit ;
114+ max = max_us / us_per_unit ;
94115
95116 return 0 ;
96117}
@@ -150,4 +171,17 @@ int servo_move_to(uint pin, uint angle)
150171 servo_pos [16 * servo_pos_buf [pos ] + pos ] = val ;
151172 servo_pos_buf [pos ] = (servo_pos_buf [pos ] + 1 ) % 2 ;
152173 return 0 ;
153- }
174+ }
175+
176+ int servo_microseconds (uint pin , uint us )
177+ {
178+ if (slice_map [pin ] < 0 )
179+ {
180+ return 1 ;
181+ }
182+
183+ uint pos = slice_map [pin ] + (pin % 2 );
184+ servo_pos [16 * servo_pos_buf [pos ] + pos ] = us ;
185+ servo_pos_buf [pos ] = (servo_pos_buf [pos ] + 1 ) % 2 ;
186+ return 0 ;
187+ }
0 commit comments