# Import SPI rack and S5i module
from spirack import SPI_rack, S5i_module

"""
Explanation: S5i example notebook
Example notebook of the S5i 4GHz RF generator module. For an explanation of how the module works, see the documentation page. This is necessary to understand the limitations and how settings effect performance (like phasenoise). 
To run this script, we need a D5a module and a controller module. This can be either the C1b/C2 combination or the C1. To acces the controller we need to import the SPI rack class. All communication with the SPI Rack will go through this object. Only one SPI_rack object can be active at a time on the PC. So before running another script, the connection in this one should be closed.
End of explanation
"""


COM_speed = 1e6 # Baud rate, doesn't matter much
timeout = 1 # In seconds

spi_rack = SPI_rack('COM4', COM_speed, timeout)
spi_rack.unlock() # Unlock the controller to be able to send data

"""
Explanation: Open the SPI rack connection and unlock the controller. This is necessary after bootup of the controller module. If not unlocked, no communication with the modules can take place. The virtual COM port baud rate is irrelevant as it doesn't change the actual speed. Timeout can be changed, but 1 second is a good value.
End of explanation
"""


# Add the S5i module to the SPI rack on address 3
S5i = S5i_module(spi_rack, 3, frequency=150e6, output_level=5.0)

"""
Explanation: Create a new S5i module object at the correct (set) module address using the SPI object. By default the frequency gets set to 100 MHz with an output power of 0dBm. We will overwrite this here to output 150 MHz at 5 dBm.
End of explanation
"""


S5i.set_output_power(-5.0)

"""
Explanation: We can change the output power of the device from -14 dBm to 20 dBm using the set_output_power function.
End of explanation
"""


frequency = 205e6 # The frequency we want to set

stepsize = S5i.get_optimal_stepsize(frequency) # Get optimal stepsize setting
S5i.set_stepsize(stepsize)
S5i.set_frequency(frequency)

"""
Explanation: As explained in the documentation, the stepsize affects the phase noise: the smaller the stepsize, the larger the phasenoise. Therefore we want to use the largest stepsize possible to achieve a certain frequency. To simplify this process, we can use the function get_optimal_stepsize. This returns the optimal setting (minimal phase noise) for a given frequency. We will use this result to set the stepsize before setting the new output frequency.
End of explanation
"""


# Close the SPI rack connection
spi_rack.close()

"""
Explanation: When done with the measurement/script, it is recommended to close the SPI Rack connection. This will allow other measurement scripts to acces the device.
End of explanation
"""


