from pynq import Overlay
from pynq.iop import Pmod_ADC, Pmod_DAC

"""
Explanation: DAC-ADC Pmod Examples using Matplotlib and Widget

Contents
Pmod DAC-ADC Feedback
Tracking the IO Error
Error plot with Matplotlib
XKCD Plot
Widget controlled plot

Pmod DAC-ADC Feedback
This example shows how to use the PmodDA4 DAC and the PmodAD2 ADC on the PYNQ-Z1 board, using the baord's two Pmod interfaces.  The notebook then compares the DAC output to the ADC input and tracks the errors.
The errors are plotted using Matplotlib and an XKCD version of the plot is produced (for fun). Finally a slider widget is introduced to control the number of samples diaplayed in the error plot.
Note: The output of the DAC (pin A) must be connected with a wire to the input of the ADC (V1 input).
1. Import hardware libraries and classes
End of explanation
"""


ol = Overlay('base.bit')
ol.download()

"""
Explanation: 2. Program the ZYNQ PL
End of explanation
"""


adc = Pmod_ADC(1)
dac = Pmod_DAC(2)

"""
Explanation: 3. Instantiate the Pmod peripherals as Python objects
End of explanation
"""


dac.write(0.35)
sample = adc.read()
print(sample)

"""
Explanation: 4. Write to DAC, read from ADC, print result
End of explanation
"""


from math import ceil
from time import sleep
import numpy as np
import matplotlib.pyplot as plt

from pynq import Overlay
from pynq.iop import Pmod_ADC, Pmod_DAC

ol = Overlay('base.bit')
ol.download()

adc = Pmod_ADC(1)
dac = Pmod_DAC(2)

delay = 0.0
values = np.linspace(0, 2, 20)
samples = []
for value in values:
    dac.write(value)
    sleep(delay)
    sample = adc.read()
    samples.append(sample[0])
    print('Value written: {:4.2f}\tSample read: {:4.2f}\tError: {:+4.4f}'.
          format(value, sample[0], sample[0]-value))

"""
Explanation: Contents

Tracking the IO Error
Report DAC-ADC Pmod Loopback Measurement Error.
End of explanation
"""


%matplotlib inline
    
X = np.arange(len(values))
plt.bar(X + 0.0, values, facecolor='blue', 
        edgecolor='white', width=0.5, label="Written_to_DAC")
plt.bar(X + 0.25, samples, facecolor='red', 
        edgecolor='white', width=0.5, label="Read_from_ADC")

plt.title('DAC-ADC Linearity')
plt.xlabel('Sample_number')
plt.ylabel('Volts')
plt.legend(loc='upper left', frameon=False)

plt.show()

"""
Explanation: Error plot with Matplotlib
This example shows plots in notebook (rather than in separate window).
End of explanation
"""


%matplotlib inline
    
# xkcd comic book style plots
with plt.xkcd():
    X = np.arange(len(values))
    plt.bar(X + 0.0, values, facecolor='blue', 
            edgecolor='white', width=0.5, label="Written_to_DAC")
    plt.bar(X + 0.25, samples, facecolor='red', 
            edgecolor='white', width=0.5, label="Read_from_ADC")

    plt.title('DAC-ADC Linearity')
    plt.xlabel('Sample_number')
    plt.ylabel('Volts')
    plt.legend(loc='upper left', frameon=False)

plt.show()

"""
Explanation: Contents

XKCD Plot
Same data plotted in XKCD format ...
(http://xkcd.com)
End of explanation
"""


from math import ceil
from time import sleep
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

from ipywidgets import interact
import ipywidgets as widgets

from pynq import Overlay
from pynq.iop import Pmod_ADC, Pmod_DAC

ol = Overlay('base.bit')
ol.download()

dac = Pmod_DAC(2)
adc = Pmod_ADC(1)

def capture_samples(nmbr_of_samples):    
    # Write to DAC, read from ADC, write to OLED
    delay = 0.0
    values = np.linspace(0, 2, nmbr_of_samples)
    samples = []
    for value in values:
        dac.write(value)
        sleep(delay)
        sample = adc.read()
        samples.append(sample[0])

    X = np.arange(nmbr_of_samples)
    plt.bar(X + 0.0, values[:nmbr_of_samples+1], 
            facecolor='blue', edgecolor='white', 
            width=0.5, label="Written_to_DAC")
    plt.bar(X + 0.25, samples[:nmbr_of_samples+1], 
            facecolor='red', edgecolor='white', 
            width=0.5, label="Read_from_ADC")

    plt.title('DAC-ADC Linearity')
    plt.xlabel('Sample_number')
    plt.ylabel('Volts')
    plt.legend(loc='upper left', frameon=False)
   
interact(capture_samples, 
         nmbr_of_samples=widgets.IntSlider(
            min=5, max=30, step=5,
            value=10, continuous_update=False));

plt.show()

"""
Explanation: Contents

Widget controlled plot
In this example, we extend the IO plot with a slider widget to control the number of samples appearing in the output plot.
We use the ipwidgets library and the simple interact() method to launch a slider bar.

The interact function (ipywidgets.interact) automatically creates user interface (UI) controls for exploring code and data interactively. It is the easiest way to get started using IPython’s widgets.

For more details see Using ipwidgets interact()
End of explanation
"""


