|
1 | 1 | """Pins, images, sounds, temperature and volume. |
2 | 2 | """ |
3 | 3 |
|
4 | | -from typing import Any, Callable, List, Optional, Tuple, overload |
| 4 | +from typing import Any, Callable, List, Optional, Tuple, Union, overload |
5 | 5 |
|
6 | 6 | from _typeshed import ReadableBuffer |
7 | 7 |
|
@@ -69,14 +69,41 @@ def panic(n: int) -> None: |
69 | 69 | def reset() -> None: |
70 | 70 | """Restart the board.""" |
71 | 71 |
|
| 72 | + |
| 73 | +@overload |
| 74 | +def scale(value: float, from_: Tuple[float, float], to: Tuple[int, int]) -> int: |
| 75 | + """Converts a value from a range to an integer range. |
| 76 | +
|
| 77 | + Example: ``volume = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255))`` |
| 78 | +
|
| 79 | + For example, to convert an accelerometer X value to a speaker volume. |
| 80 | +
|
| 81 | + If one of the numbers in the ``to`` parameter is a floating point |
| 82 | + (i.e a decimal number like ``10.0``), this function will return a |
| 83 | + floating point number. |
| 84 | +
|
| 85 | + temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0)) |
| 86 | +
|
| 87 | + :param value: A number to convert. |
| 88 | + :param from_: A tuple to define the range to convert from. |
| 89 | + :param to: A tuple to define the range to convert to. |
| 90 | + :return: The ``value`` converted to the ``to`` range. |
| 91 | + """ |
| 92 | + |
| 93 | +@overload |
72 | 94 | def scale(value: float, from_: Tuple[float, float], to: Tuple[float, float]) -> float: |
73 | | - """Converts a value from a range to another range. |
| 95 | + """Converts a value from a range to a floating point range. |
| 96 | +
|
| 97 | + Example: ``temp_fahrenheit = scale(30, from_=(0.0, 100.0), to=(32.0, 212.0))`` |
74 | 98 |
|
75 | | - Example: ``temp_fahrenheit = scale(30, from_=(0, 100), to=(32, 212))`` |
| 99 | + For example, to convert temperature from a Celsius scale to Fahrenheit. |
76 | 100 |
|
77 | | - This can be useful to convert values between inputs and outputs, for example an accelerometer X value to a speaker volume. |
| 101 | + If one of the numbers in the ``to`` parameter is a floating point |
| 102 | + (i.e a decimal number like ``10.0``), this function will return a |
| 103 | + floating point number. |
| 104 | + If they are both integers (i.e ``10``), it will return an integer:: |
78 | 105 |
|
79 | | - Negative scaling is also supported, for example ``scale(25, from_=(0, 100), to=(0, -200))`` will return ``-50``. |
| 106 | + returns_int = scale(accelerometer.get_x(), from_=(-2000, 2000), to=(0, 255)) |
80 | 107 |
|
81 | 108 | :param value: A number to convert. |
82 | 109 | :param from_: A tuple to define the range to convert from. |
|
0 commit comments