Skip to content

Common functions and classes

Dmitry Starov edited this page Jun 25, 2020 · 2 revisions

Русская версия


plumpx32.common package

This package consists of common usage functions and classes which make your Micropython programming easier.

Functions

constrain(value, min_value, max_value)

This is an analogue of Arduino's constrain() function.

This function constrains the value to the specified range [min_value, max_value].

Parameters:

  • value : The value to be constrained
  • min_value : The lower limit of range (inclusive)
  • max_value : The upper limit of range (inclusive)

Returns:

  • min_value : if value is less than min_value
  • max_value : if value is greater than max_value
  • value : otherwise

Usage:

>>> constrain(10, 20, 40)
20
>>> constrain(30, 20, 40)
30
>>> constrain(50, 20, 40)
40

amap(x, in_min, in_max, out_min, out_max)

This is an analogue of Arduino's map() function. It maps the x located in range [in_min, in_max] to a new value located in range [out_min, out_max] accordingly to the position of x in in-range.

This function does not check if x is really located in in-range. In some situations it may be needed to perform constrain(x, in_min, in_max) before passing to this function as x.

Parameters:

  • x : The value to be mapped
  • in_min : The lower limit of input range (inclusive)
  • in_max : The upper limit of input range (inclusive)
  • out_min : The lower limit of output range (inclusive)
  • out_max : The upper limit of output range (inclusive)

Returns: x which is mapped to the out-range

Usage:

>>> amap(5, 0, 10, 10, 20)
15.0
>>> amap(0, -10, 10, 0, 10)
5.0
>>> amap(-8, -8, -4, 2, 6)
2.0
>>> amap(2.5, 0, 5, 0, 1)
0.5

analog_read(adc_pin[, bit=10])

A function to get analog value on adc_pin which supports ADC-reading.

Parameters:

  • adc_pin : An ADC object on pin which supports ADC
  • bit : A count of bit in read number. Supported values are:
    • 8
    • 10
    • 12

Returns: A value on adc_pin in range according to the passed bit:

  • [0, 255] if bit = 8
  • [0, 1023] if bit = 10
  • [0, 4095] if bit = 12

The lower limit of range coincides with low voltage on Pin. The upper limit of range coincides with high voltage on Pin.

analog_write_percent(pin, percent)

Sets the duty cycle in percent representation on a given pin.

Parameters:

  • pin : A Pin which supports PWM
  • percent : A percent of time when the pin's voltage is set to be high (duty cycle in active mode). Must be in range [0, 100]

has_pwm(pin)

Indicates that given pin has an ability to work with PWM.

Parameters:

  • pin : A Pin object to be checked

Returns:

  • True if pin supports PWM
  • False otherwise

average(iterable):

Calculates the average value of iterable object.

Parameters:

  • iterable : An iterable object (e.g. List, Tuple) consisting of numeric values

Returns:

  • The average value of iterable

Classes

Clone this wiki locally