@@ -172,7 +172,7 @@ def pwm_on(self, t2_prescale, full_period, on_period):
172172 """Turns on the PWM generator with the given settings.
173173
174174 :param t2_prescale: One of T2_PS_1_1, T2_PS_1_4, T2_PS_1_16
175- Scales down the 4MHz instruction clock by
175+ Scales down the 12MHz instruction clock by
176176 1, 4 or 16.
177177 :param full_period: 8-bit value - which is scaled up to 10-bits
178178 (<< 2) - to which timer 2 will count up to
@@ -182,7 +182,7 @@ def pwm_on(self, t2_prescale, full_period, on_period):
182182 full_period to control duty cycle. For
183183 example:
184184
185- # 4MHz / 16 with 50% duty cycle
185+ # 12MHz / 16 with 50% duty cycle
186186 codebug.pwm_on(T2_PS_1_16, 0xff, 0x200)
187187
188188 """
@@ -205,14 +205,13 @@ def pwm_freq(self, frequency):
205205
206206 """
207207 # calculate pwm settings
208- # 4 MHz / 16 = 250k ticks per second
209- full_period = int (250000 / frequency ) - 1
208+ # 12MHz / 16 = 750k ticks per second
209+ full_period = int (750000 / frequency ) - 1
210210 # for 50% duty cycle: shift up by 2 then /(2 i.e. 50% duty cycle)
211211 # on_period = (full_period << 2) / 2;
212212 # this is quicker
213213 on_period = full_period << 1
214214 self .pwm_on (T2_PS_1_16 , full_period , on_period )
215- pass
216215
217216 def pwm_off (self ):
218217 """Turns off the PWM generator."""
@@ -559,3 +558,19 @@ def uart_rx_is_ready(self):
559558 def uart_rx_get_buffer (self , length , offset = 0 ):
560559 """Returns data bytes from UART buffer."""
561560 return self .get_buffer (UART_RX_BUFFER_INDEX , length , offset )
561+
562+
563+ def scale (x , from_low , from_high , to_low , to_high ):
564+ # Hardware can only do 16bit maths
565+ def limit (v ):
566+ max_value = 0x7fff
567+ min_value = - 0x8000
568+ return max (min_value , min (max_value , v ))
569+ x , from_low , from_high , to_low , to_high = map (
570+ limit , (x , from_low , from_high , to_low , to_high ))
571+ # do the scale
572+ from_delta = from_high - from_low
573+ x_offset = x - from_low
574+ to_delta = to_high - to_low
575+ new_x = int ((x_offset * to_delta ) / from_delta )
576+ return to_low + new_x
0 commit comments