import spidev import RPi.GPIO as GPIO import time import math # Define GPIO pins SYNC_PIN = 7 RESET_PIN = 22 POWER_PIN = 13 # Define SPI settings spi = spidev.SpiDev() spi.open(0, 1) # SPI bus 0, device 1 spi.mode = 0b10 spi.max_speed_hz = 40000000 # 1 MHz def setup(): GPIO.setmode(GPIO.BCM) GPIO.setup(SYNC_PIN, GPIO.OUT) GPIO.setup(RESET_PIN, GPIO.OUT) GPIO.setup(POWER_PIN, GPIO.OUT) def power_up(): GPIO.output(POWER_PIN, GPIO.HIGH) def power_down(): GPIO.output(POWER_PIN, GPIO.LOW) def reset(): GPIO.output(RESET_PIN, GPIO.LOW) time.sleep(0.00004) # Minimum of 40 ns GPIO.output(RESET_PIN, GPIO.HIGH) def write_and_update_dac_channel(channel, data): # Construct the 24-bit command word for writing to and updating DAC channel command_word = (0b0011 << 20) | (channel << 16) | data # Send the command word over SPI GPIO.output(SYNC_PIN, GPIO.LOW) spi.xfer2([command_word >> 16, (command_word >> 8) & 0xFF, command_word & 0xFF]) GPIO.output(SYNC_PIN, GPIO.HIGH) def generate_sine_wave(min_value, max_value, frequency, phase_shift): num_samples = 10000 # 50 seconds duration for i in range(360): # Calculate the sine wave value between 0 and 1 sine_value = (math.sin(2 * math.pi * i)) # Scale the sine value to the range between min_value and max_value scaled_value = sine_value * (max_value - min_value) # Shift the scaled value to the range between min_value and max_value shifted_value = scaled_value + min_value # Convert the sine value to 16-bit DAC input code input_code = int(shifted_value) # Write to and update DAC Channel A with the input code write_and_update_dac_channel(0b0001, input_code) time.sleep(0.001) def main(): setup() power_up() reset() # Reset the DAC initially try: while True: generate_sine_wave(min_value=32768, max_value=65535, frequency=1230, phase_shift=0) except KeyboardInterrupt: power_down() GPIO.cleanup() if __name__ == "__main__": main()