liveBook · Manning

Os

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

The Python standard-library module that provides interfaces to operating-system facilities, including access to environment variables.

The Python os module reads operating-system environment variables so a robot can take configuration from its shell instead of hard-coded values. Use os.environ for a required setting; a missing key raises KeyError. Use os.environ.get(name, default) when a setting is optional, then convert the returned string to the type the program needs. section 3.5

Tune motor power from the environment

Read right and left motor adjustments with defaults of '1', convert them with float(), and store them in an ADJUST dictionary. A set_throttle function multiplies each requested throttle value by its adjustment, allowing wheel-specific tuning without requiring both variables to be set. section 3.5

Listing 3.2 envforward.py: Reading configuration values from environment variables
#!/usr/bin/env python3
from adafruit_crickit import crickit
import time
import os
 
DC_ADJUST_R = float(os.environ.get('ROBO_DC_ADJUST_R', '1'))
DC_ADJUST_L = float(os.environ.get('ROBO_DC_ADJUST_L', '1'))
ADJUST = dict(R=DC_ADJUST_R, L=DC_ADJUST_L)
MOTOR = dict(R=crickit.dc_motor_1, L=crickit.dc_motor_2)
 
def set_throttle(name, value):
    MOTOR[name].throttle = value * ADJUST[name]
 
def forward():
    set_throttle('R', 0.9)
    set_throttle('L', 0.9)
    time.sleep(0.2)
    set_throttle('R', 0)
    set_throttle('L', 0)
 
forward()

This runnable script reads optional ROBO_DC_ADJUST_R and ROBO_DC_ADJUST_L values, applies them to named motors, and drives forward. section 3.5

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

How deep it goes
Demonstrates importing os, required lookup, defaulted get(), float conversion, and use in throttle control.
Examples
Uses ROBO_DC_ADJUST_R and ROBO_DC_ADJUST_L to compensate left and right wheel power.
What it assumes
Introduces Python REPL access and basic environment-variable reading while using Bash exports for setup.
What you can do after
Apply it via the os module to configure motor power without editing the script.
How it connects
Connects environment variables with Bash, KeyError, float conversion, dictionaries, and DC motor throttle.

Also explained in

Compare how 5 books explain os →

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.