Tone generator for pi
Speaker-test is already installed by default:
//Code
:
speaker-test -X -f 35000 -t sine
speaker-test -X -f 1000 -t sine
Here's how to generate frequencies using a Raspberry Pi and Python:
Using RPi.GPIO Library (PWM):
This method leverages the Raspberry Pi's hardware-based Pulse Width Modulation (PWM) capabilities.
It's suitable for generating relatively low frequencies (up to a few kHz).
Connect an LED or oscilloscope to a GPIO pin (e.g., GPIO18, which supports hardware PWM).
Use the RPi.GPIO library in Python to control the PWM output.
../code
import RPi.GPIO as GPIO
import time
# Set up GPIO mode and pin
GPIO.setmode(GPIO.BCM)
pwm_pin = 18 # GPIO18
GPIO.setup(pwm_pin, GPIO.OUT)
# Create PWM instance (frequency in Hz)
frequency = 1000 # 1 kHz
pwm = GPIO.PWM(pwm_pin, frequency)
# Start PWM with 50% duty cycle
duty_cycle = 50
pwm.start(duty_cycle)
try:
while True:
# Change frequency (optional)
# frequency = 2000
# pwm.ChangeFrequency(frequency)
# Change duty cycle (optional)
# duty_cycle = 75
# pwm.ChangeDutyCycle(duty_cycle)
time.sleep(0.1)
except KeyboardInterrupt:
pwm.stop()
GPIO.cleanup()
../
Using the rpitx library:
This method allows for generating radio frequencies (RF) without additional hardware
It can handle frequencies from 5 kHz up to 1500 MHz.
Install rpitx using:
../code
sudo apt update
sudo apt install -y git
git clone https://github.com/F5OEO/rpitx.git
cd rpitx
make install
.//
Run rpitx from the command line to generate signals. For example, to generate a 100 MHz sine wave:
../
sudo rpitx -m RF -f 100000
..//
Software-based frequency generation (simpler, less accurate):
This method uses delays in the code to approximate a frequency.
It is less accurate and less stable than hardware PWM.
Connect an LED or oscilloscope to a GPIO pin.
../code
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
output_pin = 17
GPIO.setup(output_pin, GPIO.OUT)
def generate_square_wave(frequency):
period = 1.0 / frequency
half_period = period / 2.0
while True:
GPIO.output(output_pin, GPIO.HIGH)
time.sleep(half_period)
GPIO.output(output_pin, GPIO.LOW)
time.sleep(half_period)
try:
generate_square_wave(100) # 100 Hz
except KeyboardInterrupt:
GPIO.cleanup()