Unit 2: Advanced GPIO & Peripheral Control - Subjective Questions
ECE140 — Workshop On Iot For Digital Society • Practice Questions with Detailed Answers
20 questions
Compare the RPi.GPIO and GPIO Zero Python libraries with respect to abstraction level, programming style, features, and suitable applications.
RPi.GPIO and GPIO Zero are commonly used Python libraries for controlling Raspberry Pi GPIO pins.
- Abstraction level:
- RPi.GPIO is a low-level library that requires explicit pin configuration, input/output setup, and cleanup.
- GPIO Zero provides high-level device classes such as
LED,Button,Motor, andServo.
- Programming style:
- RPi.GPIO uses procedural functions such as
GPIO.setup()andGPIO.output(). - GPIO Zero uses an object-oriented and device-centric programming model.
- RPi.GPIO uses procedural functions such as
- Event handling:
- RPi.GPIO supports interrupts through
GPIO.add_event_detect(). - GPIO Zero provides convenient properties such as
when_pressed,when_released, andwhen_held.
- RPi.GPIO supports interrupts through
- PWM support: Both libraries support PWM, but GPIO Zero hides much of the low-level configuration.
- Ease of use: GPIO Zero is generally better for beginners and rapid prototyping, whereas RPi.GPIO provides more direct control.
- Suitable applications: RPi.GPIO is useful when precise pin-level behavior is required; GPIO Zero is suitable for educational projects and applications based on standard devices.
Explain GPIO pin numbering, pin configuration, pull-up/pull-down resistors, and resource cleanup in RPi.GPIO.
RPi.GPIO supports two pin-numbering schemes:
- BOARD mode: Uses physical header pin numbers, selected using
GPIO.setmode(GPIO.BOARD). - BCM mode: Uses Broadcom GPIO channel numbers, selected using
GPIO.setmode(GPIO.BCM).
A pin is configured using GPIO.setup():
GPIO.setup(pin, GPIO.OUT)configures an output.GPIO.setup(pin, GPIO.IN)configures an input.
For an input pin, internal resistors can establish a defined default state:
pull_up_down=GPIO.PUD_UPenables a pull-up resistor.pull_up_down=GPIO.PUD_DOWNenables a pull-down resistor.
An output is controlled using GPIO.output(pin, GPIO.HIGH) or GPIO.output(pin, GPIO.LOW). Input is read using GPIO.input(pin).
GPIO.cleanup() should be executed before program termination. It returns used GPIO channels to a safe input state, releases resources, and reduces warnings when the program is run again. It is commonly placed inside a finally block so that cleanup occurs even if an exception is raised.
Describe the device-oriented programming model of GPIO Zero. Illustrate how it simplifies the control of LEDs, buttons, and motors.
GPIO Zero represents connected hardware using Python objects rather than requiring the programmer to manipulate individual GPIO states directly.
- An LED is represented by the
LEDclass and controlled using methods such ason(),off(), andblink(). - A button is represented by the
Buttonclass and provides event properties such aswhen_pressedandwhen_released. - A DC motor is represented by the
Motorclass and supports methods such asforward(),backward(), andstop().
For example, a button can control an LED by assigning the LED methods to button events:
- Create the devices:
led = LED(17)andbutton = Button(2). - Assign events:
button.when_pressed = led.onandbutton.when_released = led.off.
Advantages include:
- Reduced boilerplate code.
- Readable, object-oriented programs.
- Automatic management of common pin configurations.
- Convenient event-driven control.
- Built-in support for composite devices and remote pin factories.
Thus, GPIO Zero enables developers to focus on device behavior rather than low-level GPIO operations.
Distinguish between polling-based and interrupt-driven GPIO programming. Why is interrupt-driven programming preferred for many IoT applications?
Polling repeatedly checks the state of an input pin inside a loop. For example, a program may continuously call GPIO.input(pin) to determine whether a switch has been pressed.
Interrupt-driven programming configures the system to execute a callback when a specified edge is detected on a GPIO input.
| Aspect | Polling | Interrupt-driven control |
|---|---|---|
| CPU usage | Often high due to repeated checks | Lower because code runs when an event occurs |
| Response | Depends on polling interval | Usually responds quickly to an edge |
| Program structure | Simple but may become inefficient | Event-oriented and modular |
| Missed events | Possible if polling is too slow | Less likely for properly configured events |
| Background tasks | Difficult with blocking loops | Easier to perform concurrently |
Interrupt-driven programming is useful in IoT systems because sensors and buttons often generate events irregularly. The processor can perform communication, logging, or control tasks while waiting for an interrupt. However, callback functions should be short, thread-safe, and non-blocking to avoid delaying other events.
Explain rising-edge, falling-edge, and both-edge detection in GPIO interrupts. Also discuss switch debouncing and the use of bouncetime.
A digital transition can be detected as an interrupt event:
- Rising edge: The signal changes from LOW to HIGH. In RPi.GPIO, it is represented by
GPIO.RISING. - Falling edge: The signal changes from HIGH to LOW. It is represented by
GPIO.FALLING. - Both edges: Either transition generates an event. It is represented by
GPIO.BOTH.
Mechanical switches do not usually produce one clean transition. Their contacts may rapidly open and close for several milliseconds, generating multiple false interrupts. This phenomenon is called contact bounce.
Debouncing can be performed using:
- Software debounce: Ignore additional events for a fixed period after the first event.
- Hardware debounce: Use an RC network or a Schmitt-trigger circuit.
- State and time validation: Accept a transition only if the new state remains stable.
In RPi.GPIO, bouncetime specifies a software debounce interval in milliseconds, for example GPIO.add_event_detect(pin, GPIO.FALLING, callback=handler, bouncetime=200).
A debounce interval must be chosen carefully. A very short value may not suppress bounce, while a very long value may discard valid rapid inputs.
Design a robust interrupt-driven GPIO program for a push button that toggles an LED. Explain initialization, callback execution, synchronization, debouncing, and cleanup.
A robust design includes the following stages:
- Initialization:
- Select BCM or BOARD numbering consistently.
- Configure the LED pin as an output.
- Configure the button pin as an input with an appropriate pull-up or pull-down resistor.
- Interrupt registration:
- Register a falling-edge event for an active-low button.
- Attach a callback and specify a suitable debounce time.
- Callback operation:
- Read or maintain the current LED state.
- Toggle the LED state.
- Keep the callback short and avoid long delays, file operations, or network communication.
- Synchronization:
- If the callback and main program share variables, use a thread lock, queue, or event object to avoid race conditions.
- Main loop:
- Keep the process alive while allowing it to perform other tasks.
- Cleanup:
- Catch
KeyboardInterruptand executeGPIO.cleanup()insidefinally.
- Catch
A conceptual implementation uses GPIO.add_event_detect(button_pin, GPIO.FALLING, callback=toggle_led, bouncetime=100). For complex processing, the callback should place an event in a queue, and a worker thread should perform the longer operation. This prevents interrupt callbacks from blocking one another.
Explain the construction and operation of an H-bridge for controlling a DC motor. Include its direction-control truth table and the unsafe shoot-through condition.
An H-bridge consists of four switching devices arranged around a DC motor in an H-shaped configuration. By activating diagonal switch pairs, the voltage polarity across the motor can be reversed.
Let the driver have two logic inputs, IN1 and IN2:
| IN1 | IN2 | Motor behavior |
|---|---|---|
| 0 | 0 | Coast or stop, depending on driver design |
| 1 | 0 | Rotate in one direction |
| 0 | 1 | Rotate in the opposite direction |
| 1 | 1 | Brake or stop, depending on driver design |
- When the first diagonal pair conducts, current flows through the motor in one direction.
- When the opposite diagonal pair conducts, current direction reverses.
- During coasting, the motor terminals are generally disconnected or left in a high-impedance state.
- During dynamic braking, the motor terminals are effectively connected together, causing the generated current to oppose rotation.
Shoot-through occurs when the high-side and low-side switches of the same bridge leg conduct simultaneously. This creates a near-short circuit across the power supply and can damage the switches. Dead time, correct logic sequencing, and integrated driver protection are used to prevent it.
Why should a Raspberry Pi not drive a DC motor directly from a GPIO pin? Explain the roles of a motor driver IC, external supply, flyback protection, and common grounding.
A Raspberry Pi GPIO pin cannot safely drive a motor directly because:
- GPIO pins operate at approximately logic levels.
- Their permitted output current is much lower than the starting and running current of most motors.
- Motors are inductive loads and generate voltage spikes when current is switched.
- Motor noise and supply fluctuations may reset or damage the Raspberry Pi.
A motor driver IC provides current amplification and voltage-level interfacing. It commonly includes an H-bridge for bidirectional control and may provide overcurrent and thermal protection.
An external motor supply powers the motor independently of the Raspberry Pi's logic supply. Its voltage and current ratings must satisfy the motor's requirements, including stall current.
Flyback diodes or internal recirculation paths provide a safe route for inductive current when the switches turn off. They limit back electromotive force and protect the driver.
The Raspberry Pi and motor driver must normally share a common ground so that the driver's input voltages have the same reference. Power wiring should also include suitable decoupling capacitors and should be arranged to prevent high motor currents from flowing through sensitive logic-ground paths.
Describe how PWM is used with an H-bridge to control the speed and direction of a DC motor. Discuss duty cycle, frequency, braking, and torque.
The direction of a DC motor is selected by setting the H-bridge inputs to establish the required current direction. Speed is controlled by applying pulse-width modulation, usually to an enable input or one of the bridge inputs.
The PWM duty cycle is
where is the pulse-on time and is the PWM period. The average voltage applied to an ideal motor is approximately
when is represented as a value from to and is the motor supply voltage.
- A higher duty cycle generally produces greater average current, torque, and speed.
- A low duty cycle may fail to overcome static friction.
- PWM frequency should be high enough to avoid rough motion and may be chosen above the audible range, subject to driver limitations.
- Excessively high frequency increases switching losses.
- During the PWM off-time, the bridge may use coast mode or brake mode. These modes produce different current decay and torque behavior.
Direction should be changed safely by first reducing the duty cycle to zero, allowing the motor to slow if necessary, changing the bridge inputs, and then increasing the duty cycle.
Develop a hardware and software control strategy for interfacing a bidirectional DC motor with a Raspberry Pi through a motor driver IC.
Hardware strategy:
- Connect two GPIO outputs to the driver's direction inputs.
- Connect a PWM-capable control signal to the driver's enable or PWM input.
- Power the motor from a separate supply rated for its voltage and stall current.
- Connect Raspberry Pi ground, driver logic ground, and motor-supply ground together unless an isolated interface is used.
- Add bulk and ceramic decoupling capacitors near the driver.
- Use a driver with flyback protection and sufficient continuous and peak-current ratings.
- Add a fuse or current limit for safety.
Software strategy:
- Initialize direction outputs to a safe state and PWM duty cycle to zero.
- Implement functions such as
forward(speed),reverse(speed),brake(), andstop(). - Limit
speedto an accepted range and convert it to PWM duty cycle. - Ramp the duty cycle gradually to reduce inrush current and mechanical shock.
- Before reversal, command zero speed, insert a short dead interval, and then change direction.
- Use
tryandfinallyso that the motor is stopped and GPIO resources are released after an error. - Optionally monitor current, encoder feedback, and driver fault pins.
The GPIO pins provide only logic commands; all motor power must pass through the correctly rated driver.
Explain servo motor control using PWM pulse width. Derive the relation between pulse width and angular position for a linearly calibrated servo.
A positional hobby servo receives a periodic control pulse, commonly repeated at about , although the exact supported rate depends on the servo. The pulse width represents the desired shaft angle.
Assume:
- Minimum pulse width:
- Maximum pulse width:
- Minimum angle:
- Maximum angle:
For a linear calibration, the normalized position is
The required pulse width is therefore
For example, if a servo accepts pulses from to over an angle range from to , the nominal pulse width at is .
The relation is only an approximation. Real servos may have nonlinear response, mechanical end stops, dead bands, and different pulse limits. Therefore, the minimum and maximum pulse widths should be calibrated gradually rather than assumed.
Discuss servo calibration, jitter, power-supply requirements, and safe endpoint control when a servo is interfaced with a Raspberry Pi.
Calibration:
- Begin with conservative pulse-width limits.
- Move the servo gradually toward each endpoint.
- Stop increasing the range if the servo buzzes, stalls, or presses against a mechanical stop.
- Record the safe minimum, center, and maximum pulse widths.
Jitter: Servo jitter can result from irregular software-generated pulses, operating-system scheduling delays, electrical noise, a weak supply, or a poor ground connection. More stable hardware-timed or DMA-based pulses can reduce timing jitter.
Power supply: A servo can draw substantial current, especially during startup, acceleration, or stall. It should normally be powered from a suitable external supply rather than directly from a Raspberry Pi power pin. The grounds must be connected together when a non-isolated signal is used.
Safe endpoint control:
- Clamp requested angles to calibrated limits.
- Avoid commanding abrupt large movements under heavy load.
- Do not force the servo beyond its mechanical range.
- Provide a fail-safe or neutral position where appropriate.
- Consider disabling pulses after movement only if the application does not require holding torque and the servo supports this behavior.
Proper calibration and stable timing improve position accuracy and prevent overheating or gear damage.
Compare unipolar and bipolar stepper motors. Explain full-step, wave-drive, half-step, and microstepping control methods.
Unipolar stepper motors have center-tapped windings and can be driven by switching current through winding sections without reversing current through each complete winding. Their drivers are simpler, but winding utilization and torque may be lower.
Bipolar stepper motors do not require center taps. Current through each phase must be reversed using H-bridges. They usually provide better winding utilization and torque but require a more complex driver.
Common excitation methods are:
- Wave drive: One phase is energized at a time. It consumes less power but generally produces lower torque.
- Full-step drive: Commonly energizes two phases at a time. It provides relatively high holding torque and moves by one full motor step per state change.
- Half-step drive: Alternates between one-phase and two-phase excitation, producing twice as many positions as full-step control and smoother movement.
- Microstepping: Controls the phase currents in small approximated sinusoidal increments. It improves smoothness and positioning resolution and reduces vibration, although incremental microstep torque is lower.
Dedicated stepper-driver ICs simplify bipolar drive, current regulation, protection, and microstepping. They often expose STEP and DIR inputs to the controller.
A stepper motor has a step angle of and is operated with microsteps per full step. Calculate its microsteps per revolution and the pulse frequency required for .
The number of full steps per revolution is
With microsteps per full step, the number of microsteps per revolution is
A speed of is equivalent to
The required step-pulse frequency is therefore
Thus:
- Microsteps per revolution:
- Required pulse frequency: or
This is the ideal command frequency. In practice, the driver pulse-width requirements, processor timing accuracy, available motor torque, supply voltage, and acceleration profile must also be considered. The motor should not normally be started immediately at this frequency because it may lose steps.
Why are acceleration and deceleration profiles necessary in stepper motor control? Compare constant-speed, trapezoidal, and S-curve profiles.
A stepper motor cannot instantaneously accelerate its rotor and mechanical load to a high speed. If the command pulse frequency changes too quickly, the required torque may exceed the available motor torque, causing missed steps, vibration, or stalling.
- Constant-speed control: Pulses are generated at one fixed frequency. It is simple but suitable only when the selected speed is within the motor's reliable starting range.
- Trapezoidal profile: Velocity increases linearly during acceleration, remains constant during cruising, and decreases linearly during deceleration. It is computationally simple and widely used.
- S-curve profile: Acceleration changes gradually rather than abruptly. This limits jerk, where jerk is the rate of change of acceleration. It provides smoother motion and less mechanical vibration but requires more computation.
Acceleration profiles provide:
- Reduced missed-step risk.
- Lower mechanical shock.
- Improved ability to reach higher speeds.
- Reduced resonance and vibration.
- More predictable stopping distance.
The profile parameters must account for rotor inertia, load inertia, friction, available torque, motor supply voltage, driver current, and the required travel distance.
Derive the main equations for a symmetric trapezoidal velocity profile and explain how to determine whether a move reaches the requested maximum velocity.
Consider a move of total distance , maximum velocity , and acceleration magnitude . Assume the motor starts and ends at rest and uses equal acceleration and deceleration phases.
The acceleration time is
The distance traveled during acceleration is
The deceleration distance is equal to . Therefore, the minimum distance needed to reach and return to rest is
If , the move has a cruise segment with distance
and cruise time
The total move time is
If , the requested maximum velocity cannot be reached. The profile becomes triangular. Let the attainable peak velocity be . Since the acceleration and deceleration distances together equal ,
Therefore,
In a stepper system, velocity must be converted into step frequency using , where is the number of steps per unit distance.
Explain Direct Memory Access and how DMA can be used to achieve real-time or deterministic GPIO waveform generation on a Raspberry Pi.
Direct Memory Access allows a hardware controller to transfer data between memory and a peripheral with minimal continuous CPU intervention. For GPIO control, a DMA engine can process a prearranged sequence of operations that set or clear GPIO pins at specified time intervals.
The general process is:
- The application constructs a waveform or sequence in memory.
- DMA control blocks describe the GPIO writes and timing operations.
- A hardware timing source paces the DMA transfers.
- The DMA controller updates GPIO registers according to the prepared schedule.
- The CPU remains available for higher-level tasks while the waveform executes.
Advantages:
- Lower pulse jitter than Python delay loops.
- Stable PWM and servo pulses.
- Simultaneous control of multiple GPIO channels.
- Reduced CPU load for repetitive waveforms.
- Better timing despite operating-system scheduling delays.
Libraries and daemons such as pigpio commonly use DMA-assisted techniques to provide precise GPIO waveforms. DMA does not make the complete Linux application hard real-time; interrupts, buffering, memory contention, and application-level response may still introduce latency. However, once a waveform is scheduled, its GPIO edge timing can be substantially more deterministic than ordinary software timing.
Compare software-timed PWM, hardware PWM, and DMA-based GPIO waveform generation in terms of precision, CPU usage, flexibility, and applications.
| Feature | Software-timed PWM | Hardware PWM | DMA-based waveform |
|---|---|---|---|
| Timing source | Program loops or operating-system timers | Dedicated PWM peripheral | DMA paced by a hardware timing source |
| Jitter | Relatively high under Linux | Very low | Low when correctly configured |
| CPU usage | Can be high | Low | Low after waveform setup |
| Available pins | Potentially many | Limited to hardware PWM channels and pin mappings | Can often control many GPIO pins |
| Waveform flexibility | Moderate but timing is unreliable | Best for regular PWM | High; supports complex pulse sequences |
| Typical use | LEDs and noncritical loads | Accurate PWM, clocks, and motor signals | Servos, step pulses, synchronized outputs, and protocols |
Software PWM is easy to implement but is affected by process scheduling and other system activity. It is unsuitable for highly timing-sensitive control.
Hardware PWM uses a dedicated peripheral and provides highly stable frequency and duty cycle, but the Raspberry Pi has a limited number of PWM channels and permitted pin mappings.
DMA-based control combines low CPU load with the ability to generate accurately scheduled transitions on multiple pins. It is useful when hardware PWM resources are insufficient or when the waveform is more complex than ordinary periodic PWM.
Design a DMA-based control approach for generating simultaneous servo pulses and stepper motor pulses. Discuss timing, buffering, synchronization, and fault handling.
A DMA-based design can schedule GPIO edges for both devices on a common timing timeline.
Servo channel:
- Generate one high pulse per servo frame.
- Select each high-pulse width according to the desired servo position.
- Keep the frame period and calibrated pulse limits within the servo's supported range.
Stepper channel:
- Generate
STEPpulses that satisfy the driver's minimum high and low times. - Set
DIRbefore the first step and respect the driver's direction setup time. - Vary step intervals according to the acceleration, cruise, and deceleration profile.
Buffering and synchronization:
- Build a sequence of timestamped set-and-clear masks in memory.
- Use double buffering or waveform chaining so that the next segment is prepared while the current segment is executing.
- Place servo and stepper edges on the same timeline to prevent channel interference.
- Avoid updating a buffer that DMA is currently reading.
Fault handling:
- Monitor underrun, driver fault, limit-switch, and emergency-stop conditions.
- Prepare a safe stop sequence rather than simply terminating the process.
- Disable motor outputs if waveform generation fails.
- Use watchdog logic so that stale commands cannot continue indefinitely.
DMA improves edge timing, but higher-level sensor response and emergency handling must still be designed with operating-system latency in mind.
Propose an integrated Raspberry Pi GPIO control system containing a button interrupt, DC motor, servo, and stepper motor. Explain the software architecture, safety measures, and debugging procedure.
Software architecture:
- Use GPIO event detection for the button and apply hardware or software debouncing.
- Keep the interrupt callback short; place button events in a thread-safe queue.
- Use a state machine to manage operating modes such as
IDLE,RUNNING,STOPPING, andFAULT. - Control the DC motor through an H-bridge using direction signals and PWM.
- Generate stable servo pulses using hardware-timed or DMA-based control.
- Generate stepper pulses with an acceleration and deceleration profile.
- Separate device drivers, motion planning, event handling, and application logic into modules.
Safety measures:
- Use external supplies sized for motor and servo peak currents.
- Provide common grounding or appropriate isolation.
- Include flyback protection, decoupling capacitors, fuses, and driver current limits.
- Clamp servo commands to calibrated endpoints.
- Use limit switches for mechanical motion.
- Implement emergency-stop and watchdog behavior.
- Stop all actuators and release GPIO resources in a
finallyblock.
Debugging procedure:
- Verify GPIO numbering and pin mappings.
- Test each input and output separately without connecting high-power loads.
- Measure logic and PWM signals with an oscilloscope or logic analyzer.
- Confirm power-supply voltage under load.
- Check interrupt bounce and callback frequency.
- Start motors at low speed and low acceleration.
- Monitor temperature, current, missed steps, jitter, and driver fault outputs.
- Integrate one subsystem at a time and record timestamped diagnostic logs.
This layered approach improves timing reliability, maintainability, and electrical safety.
Compare the RPi.GPIO and GPIO Zero Python libraries with respect to abstraction level, programming style, features, and suitable applications.
RPi.GPIO and GPIO Zero are commonly used Python libraries for controlling Raspberry Pi GPIO pins.
- Abstraction level:
- RPi.GPIO is a low-level library that requires explicit pin configuration, input/output setup, and cleanup.
- GPIO Zero provides high-level device classes such as
LED,Button,Motor, andServo.
- Programming style:
- RPi.GPIO uses procedural functions such as
GPIO.setup()andGPIO.output(). - GPIO Zero uses an object-oriented and device-centric programming model.
- RPi.GPIO uses procedural functions such as
- Event handling:
- RPi.GPIO supports interrupts through
GPIO.add_event_detect(). - GPIO Zero provides convenient properties such as
when_pressed,when_released, andwhen_held.
- RPi.GPIO supports interrupts through
- PWM support: Both libraries support PWM, but GPIO Zero hides much of the low-level configuration.
- Ease of use: GPIO Zero is generally better for beginners and rapid prototyping, whereas RPi.GPIO provides more direct control.
- Suitable applications: RPi.GPIO is useful when precise pin-level behavior is required; GPIO Zero is suitable for educational projects and applications based on standard devices.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →