TheAlgorithms-Python
75 строк · 2.6 Кб
1from __future__ import annotations2
3"""
4Calculate the frequency and/or duty cycle of an astable 555 timer.
5* https://en.wikipedia.org/wiki/555_timer_IC#Astable
6
7These functions take in the value of the external resistances (in ohms)
8and capacitance (in Microfarad), and calculates the following:
9
10-------------------------------------
11| Freq = 1.44 /[( R1+ 2 x R2) x C1] | ... in Hz
12-------------------------------------
13where Freq is the frequency,
14R1 is the first resistance in ohms,
15R2 is the second resistance in ohms,
16C1 is the capacitance in Microfarads.
17
18------------------------------------------------
19| Duty Cycle = (R1 + R2) / (R1 + 2 x R2) x 100 | ... in %
20------------------------------------------------
21where R1 is the first resistance in ohms,
22R2 is the second resistance in ohms.
23"""
24
25
26def astable_frequency(27resistance_1: float, resistance_2: float, capacitance: float28) -> float:29"""30Usage examples:
31>>> astable_frequency(resistance_1=45, resistance_2=45, capacitance=7)
321523.8095238095239
33>>> astable_frequency(resistance_1=356, resistance_2=234, capacitance=976)
341.7905459175553078
35>>> astable_frequency(resistance_1=2, resistance_2=-1, capacitance=2)
36Traceback (most recent call last):
37...
38ValueError: All values must be positive
39>>> astable_frequency(resistance_1=45, resistance_2=45, capacitance=0)
40Traceback (most recent call last):
41...
42ValueError: All values must be positive
43"""
44
45if resistance_1 <= 0 or resistance_2 <= 0 or capacitance <= 0:46raise ValueError("All values must be positive")47return (1.44 / ((resistance_1 + 2 * resistance_2) * capacitance)) * 10**648
49
50def astable_duty_cycle(resistance_1: float, resistance_2: float) -> float:51"""52Usage examples:
53>>> astable_duty_cycle(resistance_1=45, resistance_2=45)
5466.66666666666666
55>>> astable_duty_cycle(resistance_1=356, resistance_2=234)
5671.60194174757282
57>>> astable_duty_cycle(resistance_1=2, resistance_2=-1)
58Traceback (most recent call last):
59...
60ValueError: All values must be positive
61>>> astable_duty_cycle(resistance_1=0, resistance_2=0)
62Traceback (most recent call last):
63...
64ValueError: All values must be positive
65"""
66
67if resistance_1 <= 0 or resistance_2 <= 0:68raise ValueError("All values must be positive")69return (resistance_1 + resistance_2) / (resistance_1 + 2 * resistance_2) * 10070
71
72if __name__ == "__main__":73import doctest74
75doctest.testmod()76