liveBook · Manning

Event loop

As explained in Build Your Own Robot: Using Python, CRICKIT, and Raspberry Pi

An event loop is a control structure that repeatedly waits for input or events and dispatches corresponding handlers.

An event loop repeatedly checks for new input, dispatches responses, and continues until an exit event occurs. In a Pygame robot controller, it initializes the display, polls events, prints them, handles pygame.QUIT, and limits processing to a configured frame rate. section 7.4.1

def main():
    pygame.init()
    screen = pygame.display.set_mode(WINDOW_SIZE)
    clock = pygame.time.Clock()
    while True:
        for event in pygame.event.get():
            print('event detected:', event)
            if event.type == pygame.QUIT:
                pygame.quit()
                return
        clock.tick(FRAME_RATE)

Use this compact loop to initialize Pygame, fetch every available event, handle window closure, and maintain 60 checks per second. section 7.4.1

Processing a live camera stream

A camera loop captures one frame per iteration, checks for Q or Esc, runs face detection, displays the marked frame, and releases the capture device when exiting. section 9.4.4

def main():
    cap = cv2.VideoCapture(0)
    assert cap.isOpened(), 'Cannot open camera'
    while cv2.waitKey(1) not in [ord('q'), ESC_KEY]:
        ret, frame = cap.read()
        assert ret, 'Cannot read frame from camera'
        detect_face(frame)
        cv2.imshow('preview', frame)
    cap.release()

Adapt this OpenCV loop when the repeated work is reading camera frames and showing detection results rather than processing joystick or window events. section 9.4.4

How Build Your Own Robot: Using Python, CRICKIT, and Raspberry Pi covers it

How deep it goes
Implements initialization, polling, dispatch, frame-rate control, exit handling, camera cleanup, and face processing without exploring lower-level scheduling internals.
Examples
Uses a Pygame event printer and a live camera preview that marks detected faces until window, Q, or Esc input ends execution.
What it assumes
Uses Python packages and graphical devices, while demonstrating initialization, input polling, exit keys, and resource release directly in runnable examples.
What you can do after
Apply it via Pygame or cv2 to build responsive input handlers, camera previews, controlled exits, and reusable robot interaction loops.
How it connects
Connects Pygame, joystick events, frame rate, video capture, face detection, graphical windows, and camera-mounted servo movement.

Also explained in

Compare how 11 books explain event loop →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build Your Own Robot: Using Python, CRICKIT, and Raspberry Pi. The section links point to the parts of the book it draws on.