Analog output

Download all scripts: 3-analog_output.zip

31-led_fade.py

#!/usr/bin/env python3

# Import modules from the (built-in) standard library.
import time  # Used to pause the script for a little while.

# Imports modules from related third party libraries.
# The RPi.GPIO library is included in 'Raspberry Pi OS with desktop'. 
import RPi.GPIO as GPIO  # Used to control the GPIO pins.

# Setup the GPIO channels.
GPIO.setmode(GPIO.BCM)  # Set the pin numbering mode [^1]
led = 17  # Create a variable with the GPIO channel connected to the LED.
GPIO.setup(led, GPIO.OUT)  # Set the GPIO channel to be used as output.

# Create an instance of the PWM (Pulse Width Modulation) class.
frequency = 1000  # Value in Hz (Hertz)
pwm = GPIO.PWM(led, frequency)
pwm.start(0)

try:
    # Main program loop
    while True:
        for duty_cycle in range(0, 100,  5):  # Fade in
            pwm.ChangeDutyCycle(duty_cycle)
            time.sleep(0.05)
        for duty_cycle in range(100, 0, -5):  # Fade out
            pwm.ChangeDutyCycle(duty_cycle)
            time.sleep(0.05)

except KeyboardInterrupt: # Ctrl-C was pressed
    pass  # Do nothing [^2].

# Stop the PWM signal.
pwm.stop()

# Release the GPIO pins and set them to a safe state.
GPIO.cleanup()
print('\nBye, bye.')

"""
GPIO18 & GPIO19 = Hardware PWM
since 0.5.2a also software PWM
"""

32-rgb_led_set_hex_value.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import RPi.GPIO as GPIO
import time

# Configure GPIO pins
GPIO.setmode(GPIO.BCM)  # Use GPIO numbers
led_r = 17  # = header pin 11
led_g = 27  # = header pin 13
led_b = 22  # = header pin 15
GPIO.setup((led_r, led_g, led_b), GPIO.OUT)

# Create PWM (Pulse Width Modulation) instances
frequency = 1000  # Hz (Hertz)
pwm_r = GPIO.PWM(led_r, frequency)
pwm_g = GPIO.PWM(led_g, frequency)
pwm_b = GPIO.PWM(led_b, frequency)

try:
	hex_value = input('Please enter a 3-Byte hexadecimal value (e.g. \'c0ffee\'): ')

	# Slice 6 character string in 3 2-character strings
	r = hex_value[0:2]  # E.g. 'c0ffee'[0:2] -> 'c0'
	g = hex_value[2:4]  # E.g. 'c0ffee'[2:4] -> 'ff'
	b = hex_value[4:6]  # E.g. 'c0ffee'[4:6] -> 'ee'

	# Convert the hexadecimal 2-character strings to integers
	r = int(r, 16)  # E.g. '00' -> 0, '10' -> 16, FF' -> 255
	g = int(g, 16)
	b = int(b, 16)

	print('0x{} -> red = {}, green = {}, blue = {}'.format(hex_value, r, g, b))

	# Start PWM instances
	pwm_r.start(r / 255 * 100)  # The range of the duty cycle is 0 .. 100
	pwm_g.start(g / 255 * 100)  # so it has to be normalized (divided by 255)
	pwm_b.start(b / 255 * 100)  # and then multiplied by 100

	time.sleep(5)  # Wait for 5 seconds

except ValueError:
	print('{} is not a valid hexadecimal value.'.format(hex_value))

except KeyboardInterrupt: # Ctrl-C was pressed
	print()

pwm_r.stop()
pwm_g.stop()
pwm_b.stop()
GPIO.cleanup()
print('Bye, bye.')

"""
"""

33-rgb_led_color_cycle.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import RPi.GPIO as GPIO
import time
import colorsys

# Configure GPIO pins
GPIO.setmode(GPIO.BCM)  # Use GPIO numbers
led_r = 17  # Pin 11
led_g = 27  # Pin 13
led_b = 22  # Pin 15
GPIO.setup((led_r, led_g, led_b), GPIO.OUT)

# Create PWM instances
frequency = 1000  # Hz (Hertz)
pwm_r = GPIO.PWM(led_r, frequency)
pwm_g = GPIO.PWM(led_g, frequency)
pwm_b = GPIO.PWM(led_b, frequency)

# Start PWM instances
pwm_r.start(0)
pwm_g.start(0)
pwm_b.start(0)

try:
	while True:
		cycle_duration = 2  # Seconds for a full color cycle
		resolution = 10  # Degrees resolution
		
		for hue in range(0, 360, resolution):
			# Convert the hue value to the r, g, b values		
			r, g, b = colorsys.hsv_to_rgb(hue / 360.0, 1, 1)  # The range of the r, g, b values is 0.0 .. 1.0
			
			pwm_r.ChangeDutyCycle(r * 100)  # The range of the duty cycle is 0 .. 100
			pwm_g.ChangeDutyCycle(g * 100)  # so the r, g, b values have to be multiplied by 100
			pwm_b.ChangeDutyCycle(b * 100)
			
			time.sleep(cycle_duration / (360 / resolution))

except KeyboardInterrupt: # Ctrl-C was pressed
	print()

pwm_r.stop()
pwm_g.stop()
pwm_b.stop()
GPIO.cleanup()
print('Bye, bye.')

"""
"""

34-rc_servo_swivel.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Import libraries
import RPi.GPIO as GPIO
# import time

# Configure GPIO pins
GPIO.setmode(GPIO.BCM)  # Use GPIO numbers
rc_servo = 18  # Pin 12
GPIO.setup(rc_servo, GPIO.OUT)

# Calculate duty cycle range from min/max pulse length
# frequency = 200  # Hz (Hertz)
# pulse_length_min = 0.8 / 1000 # ms (milliseconds), servo angle = 0 degrees
# pulse_length_max = 2.2 / 1000 # ms (milliseconds), servo angle = 164 degrees

# period = 1 / frequency # seconds (s)
# duty_cycle_min = 100 * pulse_length_min / period # percent (%)
# duty_cycle_max = 100 * pulse_length_max / period # percent (%)

# duty_cycle_span = duty_cycle_max - duty_cycle_min

# print('min {} max {} span {}'.format(duty_cycle_min, duty_cycle_max, duty_cycle_span))

frequency = 200  # Hz (Hertz)
duty_cycle_min = 16  # % (percent), servo angle = 0 degrees
duty_cycle_max = 44  # % (percent), servo angle = 164 degrees

duty_cycle_span = duty_cycle_max - duty_cycle_min

print('min {} max {} span {}'.format(duty_cycle_min, duty_cycle_max, duty_cycle_span))

# Create ans start PWM instance
pwm_rc_servo = GPIO.PWM(rc_servo, frequency)
pwm_rc_servo.start(duty_cycle_min)

try:
	while True:
		text_input = input('Enter a angle between 0 to 164 degrees:')
		
		try:
			angle = float(text_input)
			angle = max(0, min(164, angle))
			duty_cycle = duty_cycle_min + angle / 164 * duty_cycle_span
			pwm_rc_servo.ChangeDutyCycle(duty_cycle)
			print('Angle set to {} degrees'.format(angle))

		except ValueError:
			print('Text input could not be converted to a number.')


except KeyboardInterrupt:  # Ctrl-C was pressed
	pass

pwm_rc_servo.stop()
GPIO.cleanup()
print('\nBye, bye.')

"""
Connect the 3 colored wires of the RC servo as follows

	RC servo	Name	Pin	
	--------	----	---
	red			5V		4
	brown		GND		6
	orange		GPIO18	12

For technical information like PWM frequency, min and max pulse length of the RC servo look at the specs of Your servo.
e.g. http://www.savoxusa.com/Savox_SC0254MG_Digital_Servo_p/savsc0254mg.htm
"""