تعلّم

Raspberry Pi GPIO بلغة Python، بدون أي Pi على المكتب

مبتدئ

أو تصفّح كل الدروس.

  • 526قطعة على المنضدة
  • 46لوحة تعمل الآن
  • 1.00xزمن حقيقي، على كل لوحة
Raspberry Pi 4: gpiozero يجعل LED يومض على GPIO17مباشر0.000 s 0.00x
اضغط لفتحه في المحرر
اضغط «تشغيل». يفتح ويغلق gpiozero الطرف GPIO17 مرة كل ثانية، ويعرض print() كل تغيير.

Mokxi has the Raspberry Pi 4 Model B, the Raspberry Pi 5 and the Raspberry Pi Zero 2 W on its canvas. Put one down, write main.py with gpiozero or RPi.GPIO, the two libraries every Pi tutorial uses, and press Run. Your program drives the board’s 40-pin header, and the LEDs, buttons, servos and sensors wired to it behave as they would on the bench.

لا يوجد Linux في الصفحة. يعمل كود Python داخل محرك Python صغير (MicroPython، مبنيّ للمتصفح)، مع gpiozero 2.0.1 و RPi.GPIO 0.7.1 المكتوبين ليسلكا سلوك المكتبتين الحقيقيتين: نفس الفئات والوسائط، نفس التحذيرات، ونفس الأخطاء. time.sleep(1) هي ثانية محاكاة واحدة، فما يقيسه البرنامج هنا هو ما يقيسه على Pi.

الدائرة أعلاه هي أول برنامج على أي Pi: LED على GPIO17، وهو الطرف 11 في الرأس، عبر مقاومة 330 أوم. اضغط «تشغيل» فيضيء ثانية وينطفئ ثانية، وتعرض الشاشة التسلسلية كل تغيير. وعند القياس على الطرف، يبلغ طول كل نصف من الدورة 1000 ms بدقة تصل إلى 0.2 ms.

زر يبدّل حالة LED

الفئة Button في gpiozero تستدعي دالة من دوالك عند الضغط، وsignal.pause() تُبقي البرنامج في انتظار ذلك. الزر هنا يصل بين GPIO2 والأرضي. وللطرف GPIO2 مقاومة سحب داخلية قدرها 1.8 k من اللوحة نفسها، فيقرأ مرتفعًا حتى يُضغط الزر.

الزر الحقيقي يرتدّ: تتفتح تلامساته وتنغلق بضعة أجزاء من الألف من الثانية قبل أن تستقر، والزر المحاكى يفعل ذلك أيضًا. مع bounce_time=0.05 يبلغ gpiozero عن تغيير واحد فقط بعد أن يحافظ الطرف عليه مدة 50 ms، فيبدّل كل ضغطة حالة LED مرة واحدة. احذفه، وضغطة واحدة قد تبدّلها أكثر من مرة، كما يحدث على Pi حقيقية.

main.py: زر يبدّل حالة LED
# A button toggles an LED, with gpiozero.
# The button is between GPIO2 (pin 3) and ground: GPIO2 has the board's own
# 1.8 k pull-up, and Button() turns the pad's pull-up on as well.
from gpiozero import Button, LED
from signal import pause

led = LED(17)
button = Button(2, bounce_time=0.05)   # ignore 50 ms of contact bounce

def toggle():
    led.toggle()
    print("LED is", "on" if led.is_lit else "off")

button.when_pressed = toggle
pause()   # wait for presses forever; Ctrl-C in the Serial Monitor stops it

محرك سيرفو على PWM من RPi.GPIO

محرك السيرفو العادي يحتاج نبضة كل 20 ms، أي بتردد 50 Hz، وطول النبضة يحدد الزاوية. GPIO.PWM(18, 50) يصنع تلك النبضة على GPIO18، وChangeDutyCycle() يحدد طولها كنسبة من 20 ms. يقرأ هذا المحرك السيرفو 0.544 ms كزاوية 0 درجة و 2.4 ms كزاوية 180، فالزوايا 0 و 45 و 90 و 135 و 180 درجة تقابل نسب تشغيل 2.72% و 5.04% و 7.36% و 9.68% و 12.00%، ويتحرك محرك السيرفو على مساحة العمل إلى كل زاوية بدورها.

على Pi حقيقية، PWM في RPi.GPIO برمجي، و Linux المزدحمة تجعل النبضات ترتجف، فيرتجف محرك السيرفو. هنا النبضات دقيقة. الفئة AngularServo في gpiozero تقوم بالحساب نيابة عنك؛ وعلى Pi 5 تحدد نسبة التشغيل بنسب صحيحة، فتتحرك نبضة 50 Hz بخطوات 10 µs، كما يحدث هناك.

main.py: تحريك محرك سيرفو بـ RPi.GPIO
# Sweep a servo with RPi.GPIO's software PWM on a Raspberry Pi 4.
# Signal on GPIO18 (pin 12), power from 5V (pin 2), ground on pin 6.
import RPi.GPIO as GPIO
import time

SERVO = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(SERVO, GPIO.OUT)
pwm = GPIO.PWM(SERVO, 50)        # 50 Hz: one pulse every 20 ms

def angle_to_duty(angle):
    # This servo reads a 0.544 ms pulse as 0 degrees and 2.4 ms as 180.
    pulse_ms = 0.544 + angle / 180 * 1.856
    return pulse_ms / 20 * 100   # the pulse as a percentage of the 20 ms frame

pwm.start(angle_to_duty(90))
try:
    while True:
        for angle in (0, 45, 90, 135, 180):
            pwm.ChangeDutyCycle(angle_to_duty(angle))
            print(f"{angle} degrees: {angle_to_duty(angle):.2f}% duty")
            time.sleep(1)
except KeyboardInterrupt:
    pwm.stop()
    GPIO.cleanup()

حساس مسافة HC-SR04 على Pi 5

gpiozero’s DistanceSensor sends the HC-SR04 a trigger pulse and times the echo. The echo is a 5 V signal, more than a Pi’s 3.3 V pin can take, so it comes through a 1 k and 2 k divider: 5 V times 2/3 is 3.3 V. Leave the divider out and the Circuit Doctor says so.

اضبط الحساس على 100 cm فيطبع البرنامج 100.0 cm بدقة تصل إلى 0.5 cm؛ وعند 15 cm يطبع 15.0 cm ويضيء LED على GPIO17، لأن threshold_distance=0.2 يجعل 20 cm حد «داخل المدى».

main.py: قراءة HC-SR04 باستخدام gpiozero
# An HC-SR04 with gpiozero on a Raspberry Pi 5.
# TRIG on GPIO23 (pin 16). ECHO is a 5 V signal, so it reaches GPIO24 (pin 18)
# through a 1 k and 2 k divider: 5 V x 2/3 is 3.3 V, all a Pi's pin can take.
from gpiozero import DistanceSensor, LED
from time import sleep

sensor = DistanceSensor(echo=24, trigger=23, max_distance=2, threshold_distance=0.2)
led = LED(17)

sensor.when_in_range = led.on       # closer than 20 cm: the LED lights
sensor.when_out_of_range = led.off

while True:
    print(f"{sensor.distance * 100:.1f} cm")
    sleep(0.5)

BCM أو BOARD: طريقتان لترقيم الأطراف

يجب إخبار RPi.GPIO بطريقة العد. GPIO.setmode(GPIO.BCM) يستخدم أرقام GPIO الخاصة بالشريحة، وهي التي يستخدمها gpiozero دائمًا: GPIO17. أما GPIO.setmode(GPIO.BOARD) فيستخدم موقع الطرف على الرأس، بالعد من الطرف 1 عند الزاوية: الطرف 11. وهما الطرف نفسه. يضيء البرنامج أدناه الطرفين 11 و 13 على الرأس بدورهما، نصف ثانية لكل منهما، وهما GPIO17 و GPIO27.

اطلب طرفًا ليس GPIO في الترقيم الحالي، مثل الطرف 2 بنظام BOARD وهو طرف 5V، ويتوقف RPi.GPIO برسالة «The channel sent is invalid on a Raspberry Pi»، كما يحدث على لوحة حقيقية. وإذا أعدت تهيئة طرف مرتين دون GPIO.cleanup() حذّرك من أن القناة مستخدمة بالفعل، مع ذكر السطر.

main.py: RPi.GPIO بترقيم BOARD
# RPi.GPIO with BOARD numbering: pins by their place on the header.
# Header pin 11 is GPIO17 and pin 13 is GPIO27. With GPIO.setmode(GPIO.BCM)
# the same two LEDs would be 17 and 27.
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)
LEDS = [11, 13]
GPIO.setup(LEDS, GPIO.OUT, initial=GPIO.LOW)

try:
    while True:
        for pin in LEDS:
            GPIO.output(pin, GPIO.HIGH)
            print("header pin", pin, "on")
            time.sleep(0.5)
            GPIO.output(pin, GPIO.LOW)
finally:
    GPIO.cleanup()

شاشة OLED على I2C باستخدام smbus2

ناقل I2C في الرأس هو /dev/i2c-1: و SDA على GPIO2 (الطرف 3) و SCL على GPIO3 (الطرف 5)، كما في Raspberry Pi OS مع تفعيل I2C في raspi-config. يتحدث إليه smbus2 والأقدم smbus، وتجيب القطع الموصولة عليه عند عناوينها: شاشة SSD1306 OLED عند 0x3C، وحساس BME280 عند 0x76. يرسم البرنامج أدناه نصًا بمشغّل صغير في تبويبه الخاص، مرسلًا الصورة في كتل من 16 بايت كما تفعل شروحات Pi الكلاسيكية.

يعمل الناقل على الساعة المحاكاة بالسرعة الافتراضية في Raspberry Pi OS وهي 100 kHz، لذا يستغرق إطار 1 KB الوقت الذي يستغرقه على المنضدة: يطبع البرنامج من 100 إلى 125 ms لكل إطار. اطلب عنوانًا لا يجيب أحد عليه ويرفع smbus الخطأ OSError: [Errno 121] Remote I/O error، وهو الخطأ الذي يسببه سلك مفكوك على Pi حقيقية.

main.py: نص على SSD1306 باستخدام smbus2
# An SSD1306 OLED on a Raspberry Pi 4, over smbus2.
# SDA to GPIO2 (pin 3), SCL to GPIO3 (pin 5), VCC to 3V3 (pin 1), GND (pin 9).
# ssd1306_smbus.py is a small driver in its own tab.
import time
from ssd1306_smbus import SSD1306

oled = SSD1306(bus=1, address=0x3C)   # /dev/i2c-1, the header's I2C bus
start = time.monotonic()

while True:
    seconds = int(time.monotonic() - start)
    oled.fill(0)
    oled.text("Hello, Pi!", 0, 0)
    oled.text("smbus2 on i2c-1", 0, 16)
    oled.text("up %d s" % seconds, 0, 40)
    t = time.monotonic()
    oled.show()                       # 1 KB at 100 kHz: about a tenth of a second
    print("frame", seconds, "took %.0f ms" % ((time.monotonic() - t) * 1000))
    time.sleep(1)

مقاوم متغيّر عبر MCP3008

لا تملك Pi مداخل تناظرية، لذا يمر المقبض أو حساس الضوء عبر محول من تناظري إلى رقمي، و MCP3008 هو الذي تستخدمه وثائق gpiozero. يقع على SPI0: و CLK على GPIO11، و DOUT على GPIO9، و DIN على GPIO10، و CS على GPIO8، وهو /dev/spidev0.0. MCP3008(channel=0) يقرأه عبر spidev، وled.source = pot يسلّم القراءة إلى PWMLED.

رمز الشريحة هو 1024 مضروبًا في المدخلات مقسومًا على الجهد المرجعي، فمقبض مدور إلى 800 من 1023 على 3.3 V يقرأ 800، وvalue في gpiozero يساوي 0.782، بالقياس نفسه الذي يستخدمه gpiozero 2.0.1. ويعمل spidev وحده أيضًا: spi.xfer2([1, 0x80, 0]) هو القراءة نفسها يدويًا.

main.py: MCP3008 باستخدام gpiozero
# A potentiometer through an MCP3008 on a Raspberry Pi 5, with gpiozero.
# The Pi has no analog inputs, so the MCP3008 converts: CLK to GPIO11 (pin 23),
# DOUT to GPIO9 (pin 21), DIN to GPIO10 (pin 19), CS to GPIO8 (pin 24, CE0).
from gpiozero import MCP3008, PWMLED
from time import sleep

pot = MCP3008(channel=0)    # spidev0.0: SPI0 with chip select CE0
led = PWMLED(18)

led.source = pot            # the knob sets the LED's brightness

while True:
    print("value %.3f  raw %4d  %.2f V" % (pot.value, pot.raw_value, pot.voltage))
    sleep(0.5)

RPi.GPIO على Raspberry Pi 5

لا يعمل RPi.GPIO على Pi 5. أطرافها على شريحة جديدة هي RP1، لا يستطيع RPi.GPIO إيجادها هناك، ويتوقف أول GPIO.setup() بالخطأ RuntimeError: Cannot determine SOC peripheral base address. ويفعل Pi 5 في Mokxi الأمر نفسه، ويخبرك المحرر باستخدام gpiozero، وهو ما تستخدمه وثائق Raspberry Pi، وهو يعمل على اللوحات الثلاث.

ما هو مُحاكى وما ليس مُحاكى

Simulated: the 40-pin header of each board, with its 3.3 V and 5 V pins and its grounds, GPIO 0 to 27 as inputs with their pull-ups and pull-downs or as 3.3 V outputs, PWM, edge callbacks with their debounce, I2C and SPI through smbus, smbus2, spidev and gpiozero’s SPI devices, and Python’s time on the simulated clock. print() and input() use the Serial Monitor, and Ctrl-C stops the program with KeyboardInterrupt.

غير محاكى: Linux نفسها، فلا سطح مكتب ولا طرفية ولا sudo؛ و pip و apt، فلا يمكن استيراد سوى الوحدات المرفقة مع اللوحة؛ وأي شبكات؛ والكاميرا والشاشة والصوت؛ والخيوط؛ وإعداد سرعة ناقل I2C وتمديد الساعة، فيعمل I2C بالسرعة الافتراضية 100 kHz. المحرك هو MicroPython وليس CPython، فبعض الأمور في اللغة تختلف: isinstance(True, int) تعطي False، على سبيل المثال. أما البرنامج الذي يقود الأطراف فيعمل دون أي تغيير.

افتح هذه الدائرة في المحرر. Raspberry Pi 4: يجعل gpiozero LED يومض على GPIO17، موصولة كما تعمل في أعلى هذه الصفحة. غيّر قطعة أو قيمة وشغّلها مرة أخرى.

افتح الدائرة

الأسئلة

هل هذا محاكٍ كامل لـ Raspberry Pi؟

No. There is no Linux and no Arm processor in the page. Your Python program runs in a Python engine in the browser, and its gpiozero and RPi.GPIO drive the board’s 40-pin header. Everything a circuit can see of a Pi is there; the desktop, the shell and the operating system are not.

ما لوحات Raspberry Pi المتوفرة؟

The Raspberry Pi 4 Model B, the Raspberry Pi 5 and the Raspberry Pi Zero 2 W, each with the same 40-pin header. RPi.GPIO works on the Pi 4 and the Zero 2 W and fails on the Pi 5, as it does on the real one; gpiozero works on all three.

هل يعمل I2C وSPI؟

نعم. `/dev/i2c-1` و`/dev/spidev0.0` و`0.1` موجودة، كما هو الحال في Raspberry Pi OS مع تفعيل الواجهتين، وتتحدث مكتبات smbus وsmbus2 وspidev وMCP3008 الخاصة بـ gpiozero مع قطع I2C وSPI في مساحة العمل بسرعة الناقل.

هل يمكنني تثبيت مكتبة باستخدام pip؟

لا. لا تتم محاكاة pip ولا apt. أضف ملف .py الخاص بالمكتبة كتبويب مستقل واستورده من main.py، وهذا يعمل مع المكتبات المكتوبة بلغة Python الخالصة.

هل يحمّل البرنامج أي شيء؟

أول ضغطة على «تشغيل» في مشروع Raspberry Pi تنزّل محرك Python، بحجم 150 KB تقريبًا، ويحتفظ به المتصفح لكل تشغيل لاحق. أما مشروع Arduino فلا ينزّله أبدًا.

المصادر

من أين جاءت الحقائق في هذه الصفحة

ابنِ هذا على أرض الواقع

افتح المحرر وغيّر قيمة وشاهد الرقم يتحرك معها. لا شيء لتثبّته ولا حاجة إلى حساب.