importpybimporttimefrompybimportPin,Timerpin1=Pin("PC6",Pin.OUT_PP,Pin.PULL_NONE)timer1=Timer(3,freq=1000)channel1=timer1.channel(1,Timer.PWM,pin=pin1,pulse_width=0)channel1.pulse_width(50)#duty cycle at 50%
時間
タイミングや遅延を使うには、timeモジュールを使います。
delay()
time.sleep(seconds)
指定した秒だけ遅延を発生させる。
引数
seconds: 秒
戻り値
なし
例
1
2
3
importtimetime.sleep(1)#freeze program for 1 seconds
'''
"Blink Without Delay" script.
Blinks an LED attached to pin 5 every second,
without freezing the program.
'''importtimefrommachineimportPinledPin=Pin(5,Pin.OUT)interval=1previousTime=0switch=FalsewhileTrue:currentTime=time.time()ifcurrentTime-previousTime>=interval:previousTime=currentTimeswitch=notswitchledPin.value(switch)
ビットとバイト
bitRead()
bit_value = (variable >> bit_index) & 1
整数変数の特定のビットを読む。
引数
variable: 数値を表す整数型変数。例: 12345
bit_index: 読みたいビット。例: 5
戻り値
指定したビットの値
例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
'''
This example prints out each bit of an 8-bit variable
It stops after 255 (the max value an 8-bit variable can hold)
'''importtimecounter=0bit_length=8# 8 bitswhileTrue:bits=[]forbit_indexinrange(bit_length-1,-1,-1):bit_value=(counter>>bit_index)&1bits.append(bit_value)print("Binary: ",bits," DEC: ",counter)counter+=1time.sleep(0.01)ifcounter>255:break
bitSet()
variable = variable | (1 << bit_index)
整数変数の特定のビットを設定する。
引数
variable: 数値を表す整数型変数。例: 12345
bit_index: 読みたいビット。例: 5
戻り値
なし
例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Example variablevariable=12345# Set the third bitbit_index=2print()print("Before setting a bit: ",bin(variable))print("Before setting a bit: ",variable)variable=variable|(1<<bit_index)# Print the resultprint("After setting a bit: ",bin(variable))print("After setting a bit: ",variable)
# Example variablevariable=255bit_length=8# Extract the leftmost bitleftmost_bit_index=bit_length-1leftmost_bit=(variable>>leftmost_bit_index)&1# Print the resultprint("Leftmost bit: ",leftmost_bit)
defconstrain(value,lower,upper):returnmax(min(value,upper),lower)result=constrain(10,0,5)# Result will be 5print(result)
map()
map(value, in_min, in_max, out_min, out_max)
値を、ある範囲から別の範囲に写像する
例
1
2
3
4
5
defmap(value,in_min,in_max,out_min,out_max):return(value-in_min)*(out_max-out_min)/(in_max-in_min)+out_minresult=map(50,0,100,0,255)# Result is 127.5print(result)
max()
max(value1, value2, value3, valueX)
引数に与えられた数値の中から最も大きい値を返す。コンマで区切ることで多くの数値を指定できる。
例
1
2
result=max(5,10,3)# Result will be 10print(result)
min()
min(value1, value2, value3, valueX)
引数に与えられた数値の中から最も小さい値を返す。コンマで区切ることで多くの数値を指定できる。
例
1
2
result=min(5,10,3)# Result will be 3print(result)
pow()
pow(base, exponent)
数値の、別の数値のべき乗を計算する
例
1
2
result=pow(2,3)# Result will be 8print(result)
sq()
sq(value)
数値の二乗を返す
例
1
2
result=sq(4)# Result will be 16print(result)
sqrt()
math.sqrt(value)
数値の平方根を返す
例
1
2
3
4
importmathresult=math.sqrt(16)# Result will be 4.0print(result)
三角関数
cos()
math.cos(angle_in_radians)
角度(ラジアン)の余弦を計算する。結果は、-1と1の間。
例
1
2
3
4
5
6
7
8
9
10
importmath# Specify the angle in radiansangle_in_radians=math.radians(45)# Calculate the cosine of the anglecos_value=math.cos(angle_in_radians)# Print the resultprint(f"The cosine of {angle_in_radians} radians is: {cosine_value}")
sin()
math.sin(angle_in_radians)
角度(ラジアン)の正弦を計算する。結果は、-1と1の間。
例
1
2
3
4
5
6
7
8
9
10
importmath# Specify the angle in radiansangle_in_radians=math.radians(30)# Calculate the sine of the anglesine_value=math.sin(angle_in_radians)# Print the resultprint(f"The sine of {angle_in_radians} radians is: {sine_value}")
tan()
math.tan(angle_in_radians)
角度(ラジアン)の正接を計算する。結果は、-無限大と∞の間。
例
1
2
3
4
5
6
7
8
9
10
importmath# Specify the angle in radiansangle_in_radians=math.radians(60)# Calculate the tangent of the angletangent_value=math.tan(angle_in_radians)# Print the resultprint(f"The tangent of {angle_in_radians} radians is: {tangent_value}")
文字
isAlpha()
char.isalpha()
文字がアルファベットか調べる
例
1
2
3
4
5
char='a'ifchar.isalpha():print(f"{char} is alphabetic.")else:print(f"{char} is not alphabetic.")
isAlphaNumeric()
char.isDigit()とchar.isAlpha()
文字が数値かアルファベットかを調べる
例
1
2
3
4
5
6
7
8
9
10
11
# Function to check if a character is alphanumericdefis_alphanumeric(char):returnchar.isalpha()orchar.isdigit()# Example usagetest_char='a'ifis_alphanumeric(test_char):print(f"{test_char} is alphanumeric.")else:print(f"{test_char} is not alphanumeric.")
char='Ö'if0<=ord(char)<128:print(f"{char} is an ASCII character.")else:print(f"{char} is not an ASCII character.")
isControl()
ord(char) < 32 or ord(char) == 127
文字の10進表現が32未満か、127かを調べて、制御文字かどうかを判断する。
例
1
2
3
4
5
6
char='\t'# Example: Tab characterif0<=ord(char)<32orord(char)==127:print(f"{char} is a control character.")else:print(f"{char} is not a control character.")
isDigit()
char.isDigit()
例
1
2
3
4
5
char='5'ifchar.isdigit():print(f"{char} is a digit.")else:print(f"{char} is not a digit.")
isGraph()
例
1
2
3
4
5
6
char='A'ifchar.isprintable()andnotchar.isspace():print(f"{char} is a graph character.")else:print(f"{char} is not a graph character.")
isLowerCase()
isLowerCase()
例
1
2
3
4
5
6
char='a'ifchar.islower():print("Is lower case.")else:print("Is not lower case.")
isPrintable()
isPrintable()
文字が表示可能か調べる。例: 空白文字を含む任意の文字、ただし、制御文字は含めない。
例
1
2
3
4
5
6
char='\t'ifchar.isprintable():print("Is printable.")else:print("Is not printable.")
importrandomimporttime# Seed the random number generator with the current timeseed_value=int(time.time())random.seed(seed_value)# Generate random numbers using the seeded generatorrandom_number=random.randint(1,100)print(random_number)
frommachineimportPinimporttime# Define a callback function to be called when the interrupt occursdefinterrupt_callback(pin):print("Interrupt occurred on pin",pin_name)# Pin namepin_name="PA3"# Define the pin to which you want to attach the interruptinterrupt_pin=Pin(pin_name,Pin.IN,Pin.PULL_UP)# Replace 2 with the actual pin number you are using# Attach the interrupt to the pin, specifying the callback function and trigger typeinterrupt_pin.irq(trigger=Pin.IRQ_FALLING,handler=interrupt_callback)whileTrue:print("hello world")time.sleep(1)
frommachineimportPinimporttime# Define a callback function to be called when the interrupt occursdefinterrupt_callback(pin):print("Interrupt occurred on pin",pin_name)# Detaches the interrupt from the pininterrupt_pin.irq(handler=None)# Pin namepin_name="PA3"# Define the pin to which you want to attach the interruptinterrupt_pin=Pin(pin_name,Pin.IN,Pin.PULL_UP)# Replace 2 with the actual pin number you are using# Attach the interrupt to the pin, specifying the callback function and trigger typeinterrupt_pin.irq(trigger=Pin.IRQ_FALLING,handler=interrupt_callback)whileTrue:print("hello world")time.sleep(1)
variable=5print("I am a string!")# prints a stringprint(variable)# prints value of variableprint(58)# prints a numeric valueprint(f"The value is {variable}")# prints a string with a value inserted
importmachineimporttimeuart=machine.UART(1,baudrate=57600)received_data=""whileTrue:ifuart.any():data=uart.read(1)received_data+=dataifreceived_dataandreceived_data[-1]=='\n':print("Received:",received_data[:-1])# Print the accumulated data (excluding the newline character)received_data=""# Reset the string after printingtime.sleep(0.1)
frommachineimportI2C,Pin# Initialize I2C anc configure device & reg addressesi2c=I2C(0,scl=Pin(22),sda=Pin(21),freq=100000)# Adjust pins and frequency as neededdevice_address=0x68register_address=0x00# The array of bytes to be send out# This buffer simply stores 1,2,3,4data_out=bytearray([0x01,0x02,0x03,0x04])# Send the device address with the write bit to indicate a write operationi2c.writeto(device_address,bytearray([register_address]))# Finally, send data to the devicei2c.writeto(device_address,data_out)
var_array=[1,2,3]var_bool=True/Falsevar_unsigned_byte=255var_signed_byte=-128var_char='A'var_double=3.14var_float=29.231232var_int=2147483647var_long=2147483647var_short=32767var_string="This is a string"var_unsigned_int=4294967295var_unsigned_long=4294967295
size_t
len(my_array)
size_tと全く同じものはありません。len()関数を使うと、オブジェクトの大きさを返します。
例
1
2
3
4
5
my_array=[1,2,3,4,5]array_size=len(my_array)print("Size of array is: ",array_size)
global_var=0#initial valuedefmy_function():local_var=10# declare local variableprint()print("(inside function) local_var is: ",local_var)global_var=local_var+25print("(inside function) global_var is updated to: ",global_var)returnglobal_varglobal_var=my_function()+25print("(outside function) global_var is finally: ",global_var)'''
The line below will cause the script to fail
because it is not declared globally.
'''#print(local_var)
remainder=5%10# remainder is 5multiplication=10*5# result of multiplication is 50addition=10+5# result of addition is 15subtraction=10-5# result of subtraction is 5division=10/5# result of division is 2exponentiation=10**5# result of exponentiation is 10000 (10*10*10*10*10)print("remainder:",remainder)print("multiplication:",multiplication)print("addition:",addition)print("subtraction:",subtraction)print("division:",division)print("exponentiation:",exponentiation)
比較演算子
比較演算子は、2つの値や四季を比較するのに使い、ブール値(TrueかFalse)の結果を返します。
==(等価)
!=(非等価)
<(小なり)
<=(小なりイコール)
>(大なり)
>=(大なりイコール)
以下のスクリプトは、xとyを比較し、結果をREPLに表示します。
==
1
2
3
4
5
6
7
x=10y=5ifx==y:print("x is equal to y")else:print("x is not equal to y")
!=
1
2
3
4
5
6
7
x=10y=5ifx!=y:print("x is not equal to y")else:print("x is equal to y")
<
1
2
3
4
5
6
7
x=10y=5ifx<y:print("x is smaller than x")else:print("x is not smaller than y")
<=
1
2
3
4
5
6
7
x=10y=5ifx<=y:print("x is smaller or equal to y")else:print("x is not smaller or equal to y")
>
1
2
3
4
5
6
7
x=10y=5ifx>y:print("x is greater than y")else:print("x is not greater than y")
>=
1
2
3
4
5
6
7
x=10y=5ifx>=y:print("x is greater than or equal to y")else:print("x is not greater than or equal to y")