예제 #1
0
def config(board):
    selection.dac(board)
    # send configuration byte
    # DAC control register: SDODIS = 0 (SDO enabled)
    spi.writebytes([0x20, 0x03, 0x12])
    # DAC control register: SDODIS = 1 (SDO disabled)
    #spi.writebytes([0x20, 0x03, 0x32])
    # write 0V on DAC exit
    writeVolts(0)
예제 #2
0
def read_analog_output(board):
    '''
    input parameters:
        - board:    board address
    output parameters:
        - code set in DAC (from 0 to 262143, correspondent to -10V to 10V)
    ----------------------------
    description:
        this function reads the code set in the analog output (from 0 to 262143)
    '''
    selection.dac(board)
    return dac.read(board)
예제 #3
0
def calibration(board):
    import Agilent34420A
    # turns on DAC circuit
    on(board)
    # global variables
    global GAIN, OFFSET
    GAIN = 1
    OFFSET = 0
    # set up DAC
    selection.dac(board)
    config(board)
    calibration = [-9, 9]
    calibration_code = []
    measure = []
    for x in calibration:
        base = int(round((x + 10.0) / 20 * 262143))
        calibration_code.append(base)
        #---------------------------------------------------------
        # "write(base)" without considering previous calibration
        # prepare to send data to the Control Register
        bytes = ((1 << 20) + (base << 2))
        byte_1 = (bytes & 0xFF0000) >> 16
        byte_2 = (bytes & 0x00FF00) >> 8
        byte_3 = (bytes & 0x0000FF)
        spi.writebytes([byte_1, byte_2, byte_3])
        # LDAC via hardwareLDAC
        #GPIO.output(LDAC, GPIO.LOW)
        #GPIO.output(LDAC, GPIO.HIGH)
        # pulse LDAC via software
        spi.writebytes([0x40, 0x00, 0x01])
        #---------------------------------------------------------
        time.sleep(60)
        measure.append(Agilent34420A.read())
    # calculating gain correction
    theoretical_step = 20.0 / 262143
    calibrated_step = (measure[1] - measure[0]) / (calibration_code[1] -
                                                   calibration_code[0])
    GAIN = theoretical_step / calibrated_step
    # calculating offset correction (around code 131072, 0V)
    code_found = (-measure[0] / theoretical_step) + 13107
    OFFSET = code_found - 131072
    # store both parameters (GAIN and OFFSET) in flash memory
    flash.dac_gain_write(board, GAIN)
    flash.dac_offset_write(board, OFFSET)
    # return two parameters: gain and offset
    #output = [GAIN, OFFSET]
    print "\tgain = " + str(GAIN)
    print "\toffset = " + str(OFFSET)
예제 #4
0
파일: ramp.py 프로젝트: pnallin/SPIxCONV
def test1(board):
    # import time to define the name of the output file
    from time import gmtime, strftime
    timestr = strftime("%Y-%m-%d_%H-%M-%S", gmtime())
    filename = "ramp_tests/" + timestr + "_test1_board" + str(board)

    # turns on DAC circuit and cofigure it
    dac.on(board)
    selection.dac(board)
    dac.config()
    # turns on ADC circuit
    adc.on(board)

    # open file and name the fields in the first line
    log = open(filename + ".csv", "a+")
    log.write("original value;" + "value read\n")

    v2 = []
    # follow the ramp described by the vector v1

    selection.dac(board)
    while(1):
        for i in range(len(v1)):
            # write value in v1 in DAC:
#            selection.dac(board)
            dac.write(v1[i])
            # read value in ADC:
#            selection.adc(board)
#            measure = adc.read()
    #        v2.append(measure)
            # write data into .csv file
    #        log.write(str(v1[i]) + ";" + str(measure) + "\n")

    # update the file
    log.close()
    # plot graph
    import pylab
    plt.clf()
    plt.xlabel("data")
    plt.ylabel("binary value")
    pylab.plot(v1, '-b', label='curve to follow')
    pylab.plot(v2, '-r', label='data read')
    pylab.legend(loc='upper left')
    pylab.show()
    plt.show()
    plt.savefig('/root/scripts/' + filename)

    return v2
예제 #5
0
def set_analog_output(board, code):
    '''
    input parameters:
        - board:    board address
        - voltage:  value in Volts (from MIN_SCALE to FULL_SCALE)
    output parameters:
        - none
    ----------------------------
    description:
        this function writes an analog output (from -10V to 10V, but only used
        monopolar range, i.e., 0 to +10V, mapped in 0 to FULL_SCALE voltage).
    '''
    #global MIN_SCALE, MAX_SCALE, FULL_SCALE
    #value = int(round(((voltage - MIN_SCALE)/FULL_SCALE)*131071 + 131072))
    code = int(code)
    selection.dac(board)
    dac.write(code)
예제 #6
0
파일: adc.py 프로젝트: pnallin/SPIxCONV
def calibration(board):
    # global variables
    global GAIN, OFFSET
    # turns on DAC and ADC circuit
    dac.on(board)
    on(board)
    # reset previous Calibration
    GAIN = 1
    OFFSET = 0
    # set up DAC
    selection.dac(board)
    dac.config(board)

    calibration = [-9, 9]
    total_measures = 10000
    # defining variables for MAX, MIN and MEAN (ADC measure)
    min_adc = [0] * 5
    max_adc = [0] * 5
    mean_adc = [0] * 5
    std_var = [0] * 5
    i = 0
    j = 0
    ############################################################
    interval = []
    for x in calibration:
        measure = []
        #print "  ============================================================================"
        #print "  |                           CALIBRATION:                                   |"
        #print "  ============================================================================"

        # select DAC and write correspondent value
        base = int(((x + 10) / (20 / float(262144))))
        interval.append(base)
        selection.dac(board)
        dac.write(base)
        time.sleep(60)
        measure = []
        for i in range(total_measures):
            selection.adc(board)
            adc_value = read()
            measure.append(adc_value)
            # check if it is the first measure
            if (i == 0):
                min_adc[j] = measure[0]
                max_adc[j] = measure[0]
                mean_adc[j] = measure[0] * 1.0
            # if not, calculate max, min and mean
            else:
                if (measure[i] < min_adc[j]):
                    min_adc[j] = measure[i]
                if (measure[i] > max_adc[j]):
                    max_adc[j] = measure[i]
                mean_adc[j] = (mean_adc[j] * i + measure[i]) / (i + 1)
            i += 1
            adc_volt = float(adc_value) / 262143 * 20 - 10
            adc_volt_str = str(adc_volt)
            adc_volt_str = adc_volt_str[0:adc_volt_str.find(".") + 8]
            #sys.stdout.write("  | " + str(adc_value) + "\t" + str(adc_value) + "\t\t\t\t\t\t\t" + "|" + "\n")
        j += 1
    REFERENCE = mean_adc[0]
    # calculating gain correction
    theoretical_step = 20.0 / 262143
    calibrated_step = 18.0 / (mean_adc[1] - mean_adc[0])
    GAIN = calibrated_step / theoretical_step
    # calculating offset correction (around code 131072, 0V)
    interval = 9.0 / theoretical_step
    OFFSET = 131072 - interval - mean_adc[0]
    # update OFFSET taking in account REFERENCE value:
    OFFSET = REFERENCE * (1 - GAIN) + OFFSET
    # store both parameters (GAIN and OFFSET) in flash memory
    flash.adc_gain_write(board, GAIN)
    flash.adc_offset_write(board, OFFSET)
    # return two parameters: gain and offset
    #output = [GAIN, OFFSET]
    print "\tgain = " + str(GAIN)
    print "\toffset = " + str(OFFSET)
예제 #7
0
def stability(board):
    # turns on DAC and ADC circuit
    dac.on(board)
    adc.on(board)
    # set up DAC
    selection.dac(board)
    dac.config(board)

    from time import gmtime, strftime
    timestr = strftime("%Y-%m-%d_%H-%M-%S", gmtime())
    filename = "stability/" + timestr + "_"

    #from epics import caput
    #from epics import caget
    #import Agilent34420A

    voltage = [-9, -5, 0, 5, 9]
    #voltage = [9]
    #total time of the test (in seconds)
    total_measures = 10000
    # defining variables for MAX, MIN and MEAN (ADC measure)
    min_adc = [0] * 5
    max_adc = [0] * 5
    mean_adc = [0] * 5
    std_var = [0] * 5
    i = 0
    j = 0
    ############################################################
    for x in voltage:
        measure = []
        if (x > 0):
            log = open(filename + "+" + str(x) + "V.csv", "a+")
        else:
            log = open(filename + str(x) + "V.csv", "a+")
        #set tabs of .csv file
        log.write('Indice')
        log.write(';Valor lido no multimetro (V)')
        log.write(';Valor lido no multimetro (LSB)')
        log.write(';ADC - Leitura do valor integrado (V)')
        log.write(';ADC - Leitura do valor integrado (LSB)')
        log.write(';MBTemp1:Channel5 (graus C)')
        log.write('\n')
        #Update the file
        log.close()
        print "  ============================================================================"
    #    sys.stdout.write("  |                         ESTABILIDADE: ")
        sys.stdout.write("  |                           STABILITY: ")
        if(x < 0):
            sys.stdout.write(str(x) + "V" + "                                 |\n")
        elif(x > 0):
            sys.stdout.write("+" + str(x) + "V" + "                                 |\n")
        else:
            sys.stdout.write(str(x) + "V" + "                                  |\n")
        print "  ============================================================================"
        print "  | INDEX\tMULT.\t\tMULT.[LSB]\tADC\tADC(V)\t\tTEMP.|"
        print "  |--------------------------------------------------------------------------|"

        # select DAC and write correspondent value
        base = int(((x+10)/(20/float(262144))))
        selection.dac(board)
        dac.write(base)
        time.sleep(30)

        measure = []
        for i in range (total_measures):
            if (x > 0):
                log = open(filename + "+" + str(x) + "V.csv", "a+")
            else:
                log = open(filename + str(x) + "V.csv", "a+")
            #---------------------------------------------------

            selection.adc(board)
            mean_measure = []
            for k in range(3):
                mean_measure.append(adc.read())
            #    #print numpy.mean(measure)
            adc_value = sum(mean_measure) / len(mean_measure)

#            adc_value = adc.read()
            measure.append(adc_value)
            # check if it is the first measure
            if(i == 0):
                min_adc[j] = measure[0]
                max_adc[j] = measure[0]
                mean_adc[j] = measure[0]*1.0
            # if not, calculate max, min and mean
            else:
                if(measure[i] < min_adc[j]):
                    min_adc[j] = measure[i]
                if(measure[i] > max_adc[j]):
                    max_adc[j] = measure[i]
                mean_adc[j] = (mean_adc[j]*i + measure[i])/(i + 1)
            i += 1
            #adc = "{:1}".format(adc)
            #adc = numpy.mean(measure)
            adc_volt = float(adc_value)/262143*20-10
            adc_volt_str = str(adc_volt)
            adc_volt_str = adc_volt_str[0:adc_volt_str.find(".")+8]
            #---------------------------------------------------
            #Get temperature
            #temp = caget("MBTemp_RAFAEL_1:Channel5")
            #temp_str = ("%.2f" %temp)
            #temp_str = str(temp_str)
            #temp_str = temp_str[0:temp_str.find(".")+3]
            #---------------------------------------------------
            #Write all data
            #log.write(str(base+i)+ ';' + multimeter_int_str + ';' + str(multimeter_lsb) + ';' + str(adc) + ';' + str(adc_volt) + ';' + str(temp) + '\n')
            #log.write(str(base+i)+ ';' + multimeter_int_str + ';' + str(multimeter_lsb) + ';' + str(adc) + ';' + str(adc_volt) + ';' + '\n')
            #log.write(str(base+i)+ ';' + multimeter_int_str + ';' + str(multimeter_lsb) + ';' + str(adc) + ';' + str(adc_volt) + ';;')
            log.write(str(base+i)+ ';;;' + str(adc_value) + ';' + str(adc_volt) + ';;')

    #        for k in range(100):
    #            log.write(str(measure[k]) + ';')
            log.write('\n')

            #Update the file
            log.close()
            #print data on terminal
            sys.stdout.write("  | " + str(base) + "\t" + "------" + "\t\t" + "------\t" + "\t")
            #---------------------------------------------------------
            sys.stdout.write(str(adc_value) + "\t")
            #---------------------------------------------------------
            if(adc_volt < 0):
                sys.stdout.write(str(adc_volt_str) + "\t")
            else:
                sys.stdout.write("+" + str(adc_volt_str) + "\t")
            #---------------------------------------------------------
            #sys.stdout.write(temp_str + "|" + "\n")
            sys.stdout.write('---\t' + "|" + "\n")
        print "  |                                                                          |"

    #    #calculate standard deviation
    #    part_sum = 0
    #    for i in range(len(measure)):
    #        part_sum = part_sum + (measure[i] - mean_adc[j])**2
    #    std_var[j] = part_sum/(len(measure)*1.0)
    #    std_var[j] = math.sqrt(std_var[j])
    #    std_var[j] = "{0:.4f}".format(std_var[j])
    #    mean_adc[j] = "{0:.2f}".format(mean_adc[j])
        #---------------------------------------------------
        # plot and save Histogram
        std_var[j] = plot_hist(board, x, measure, mean_adc[j])
        mean_adc[j] = "{0:.2f}".format(mean_adc[j])
        print "  ============================================================================"
        #---------------------------------------------------
        # print standard variation
        sys.stdout.write("  |    std_dev  = %s" %str(std_var[j]))
        for i in range (0, (6 - len(str(std_var[j])))):
            sys.stdout.write(' ')
        sys.stdout.write('      |\n')
        #-------------------------------------------------------
        # print minimum value acquired
        sys.stdout.write("  |    ADC_min  = %s" %min_adc[j])
        for i in range (0, (6 - len(str(min_adc[j])))):
            sys.stdout.write(' ')
        sys.stdout.write('      |\n')
        #---------------------------------------------------
        # print maximum value acquired
        sys.stdout.write("  |    ADC_max  = %s" %max_adc[j])
        for i in range (0, (6 - len(str(max_adc[j])))):
            sys.stdout.write(' ')
        sys.stdout.write('      |\n')
        #---------------------------------------------------
        # print mean
        sys.stdout.write("  |    ADC_mean = %s" %mean_adc[j])
        for i in range (0, (6 - len(str(mean_adc[j])))):
            sys.stdout.write(' ')
        sys.stdout.write('   |\n')
        #---------------------------------------------------
        # print difference between max and min (histogram thickness)
        sys.stdout.write("  |        diff = %s" %(max_adc[j] - min_adc[j]))
        for i in range (0, (6 - len(str(max_adc[j] - min_adc[j])))):
            sys.stdout.write(' ')
        sys.stdout.write('      |\n')
        #---------------------------------------------------
        print "  ============================="
        j += 1

    # Print it all again after all the data were acquired
    j = 0
    for x in voltage:
        sys.stdout.write("  |       STABILITY: ")
        if(x > 0):
            sys.stdout.write("+")
        if(x == 0):
            sys.stdout.write(" ")
        sys.stdout.write(str(x) + "V      |\n")
        print "  ============================="
        #---------------------------------------------------
        # print standard variation
        sys.stdout.write("  |    std_dev  = %s" %str(std_var[j]))
        for i in range (0, (6 - len(str(std_var[j])))):
            sys.stdout.write(' ')
        sys.stdout.write('      |\n')
        #-------------------------------------------------------
        # print minimum value acquired
        sys.stdout.write("  |    ADC_min  = %s" %min_adc[j])
        for i in range (0, (6 - len(str(min_adc[j])))):
            sys.stdout.write(' ')
        sys.stdout.write('      |\n')
        #---------------------------------------------------
        # print maximum value acquired
        sys.stdout.write("  |    ADC_max  = %s" %max_adc[j])
        for i in range (0, (6 - len(str(max_adc[j])))):
            sys.stdout.write(' ')
        sys.stdout.write('      |\n')
        #---------------------------------------------------
        # print mean
        sys.stdout.write("  |    ADC_mean = %s" %mean_adc[j])
        for i in range (0, (6 - len(str(mean_adc[j])))):
            sys.stdout.write(' ')
        sys.stdout.write('   |\n')
        #---------------------------------------------------
        # print difference between max and min (histogram thickness)
        sys.stdout.write("  |        diff = %s" %(max_adc[j] - min_adc[j]))
        for i in range (0, (6 - len(str(max_adc[j] - min_adc[j])))):
            sys.stdout.write(' ')
        sys.stdout.write('      |\n')
        #---------------------------------------------------
        print "  ============================="
        j += 1
예제 #8
0
def repetibility(board):
    # select DAC of the board requested
    selection.dac(board)
    dac.config()

    print "  ======================================================\n"
    from time import gmtime, strftime

    timestr = strftime("%Y-%m-%d_%H-%M-%S", gmtime())
    filename = "repetibility/" + timestr + "_"

    tensoes = [-9, -5, 0, 5, 9]
    # total time of the test (in seconds)
    # total_time = 12*60*60
    total_time = 0.07 * 60 * 60
    # save time when test started
    startTime = time.time()
    ############################################################
    for x in tensoes:
        if (x > 0):
            log = open(filename + "+" + str(x) + "V.csv", "a+")
        else:
            log = open(filename + str(x) + "V.csv", "a+")
        # set tabs of .csv file
        log.write(';Valor lido no multimetro (V)')
        log.write(';Valor lido no multimetro (LSB)')
        log.write(';ADC - Leitura do valor integrado (V)')
        log.write(';ADC - Leitura do valor integrado (LSB)')
        log.write(';MBTemp1:Channel5 (graus C)')
        log.write('\n')
        # Update the file
        log.close()
    print "  ============================================================================"
    print "  |                             REPETIBILIDADE                               |"
    print "  ============================================================================"
    print "  | DAC\t\tMULT.\t\tMULT.(LSB)\tADC\tADC(V)\t\tTEMP.|"
    print "  |--------------------------------------------------------------------------|"
    while ((time.time() - startTime) < total_time):
        for x in tensoes:
            base = int(((x + 10) / (20 / float(262144))))
            # select DAC and write correspondent value
            selection.dac(board)
            dac.write(base)
            time.sleep(0.01)
            # ---------------------------------------------------
            if (x > 0):
                log = open(filename + "+" + str(x) + "V.csv", "a+")
            else:
                log = open(filename + str(x) + "V.csv", "a+")
            # ---------------------------------------------------
            selection.adc(board)
            adc_value = adc.read()
            '''
            measure = []
            for j in range(100):
                measure.append(adc.read())
            #	#print numpy.mean(measure)
            adc_value = sum(measure) / len(measure)
            '''
            if (abs(adc_value - base) > 1000):
                error += 1
                print error

            # adc = "{:1}".format(adc)
            # adc = numpy.mean(measure)
            adc_volt = float(adc_value) / 262143 * 20 - 10
            adc_volt_str = '{:.8f}'.format(adc_volt)
            #adc_volt_str = str(adc_volt)
            #adc_volt_str = adc_volt_str[0:adc_volt_str.find(".") + 8]
            # ---------------------------------------------------
            log.write(str(base) + ';' + ';' + str(adc_value) + ';' + str(adc_volt) + ';;')
            '''
            for j in range(100):
                log.write(str(measure[j]) + ';')
            log.write('\n')
            '''
            # Update the file
            log.close()
            # print data on terminal
            sys.stdout.write("  | " + str(base) + "\t" + "-----   " + "\t" + "  -----   " + "\t")
            # ---------------------------------------------------------
            sys.stdout.write(str(adc_value) + "\t")
            # ---------------------------------------------------------
            if (adc_volt < 0):
                sys.stdout.write(str(adc_volt_str) + "\t")
            else:
                sys.stdout.write("+" + str(adc_volt_str) + "\t")
            # ---------------------------------------------------------
            # sys.stdout.write(temp_str + "|" + "\n")
            sys.stdout.write('---\t' + "|" + "\n")
        print "  |--------------------------------------------------------------------------|"
    print "ERROR = " + str(error)
예제 #9
0
def repetibility_error(board):
    # run calibration function and get the step that should be used
    #step = calibration(2)
    # turns on DAC and ADC circuit
    dac.on(board)
    adc.on(board)
    # select DAC of the board requested
    selection.dac(board)
    dac.config()

    print "  ======================================================\n"
    from time import gmtime, strftime

    timestr = strftime("%Y-%m-%d_%H-%M-%S", gmtime())
    filename = "repetibility/" + timestr + "_error_log_file.csv"
    log = open(filename, "a+")
    # set tabs of .csv file
    log.write('Iteracao')
    log.write(';Status')
    log.write(';Horario')
    log.write(';Valor setado [LSB]')
    log.write(';Valor lido [LSB]')
    log.write(';Valor lido [V]')
    log.write(';Diferenca [LSB]')
    log.write('\n')
    # Update the file
    log.close()

    # save time when test started
    startTime = time.time()
    ############################################################
    print "  ============================================================================"
    print "  |                             REPETIBILIDADE                               |"
    print "  ============================================================================"
    print "  | DAC\t\tMULT.\t\tMULT.(LSB)\tADC\tADC(V)\t\tTEMP.|"
    print "  |--------------------------------------------------------------------------|"
    iteration = 0
    error = 0
    while (1):
        # read current time
        startTime = time.time()
        #while ((time.time() - startTime) < 1*60*60):
        points = 1024
        while ((time.time() - startTime) < 1*60*60):
            for i in range(points):
                base = int((math.sin(i*1.0/points*2*math.pi) + 1)*131071.5)
                # select DAC and write correspondent value
                selection.dac(board)
                dac.write(base)
                #time.sleep(0.01)
                selection.adc(board)
                adc_value = adc.read()
                adc_volt = float(adc_value) / 262143 * 20 - 10
                adc_volt_str = '{:.8f}'.format(adc_volt)
                # check if an error occurred
                if (abs(adc_value - base) > 100):
                    error += 1
                    print error
                    # write in log file
                    log = open(filename, "a+")
                    timestr = strftime("%Y/%m/%d_%H:%M:%S", gmtime())
                    log.write(str(iteration) + ";erro;" + timestr + ';' + str(base) + ';' + str(adc_value) + ';' + str(adc_volt) + ';' + str((adc_value - base)) + "\n")
                    # Update the file
                    log.close()
                # print data on terminal
                sys.stdout.write("  | " + str(base) + "\t" + "-----   " + "\t" + "  -----   " + "\t")
                # ---------------------------------------------------------
                sys.stdout.write(str(adc_value) + "\t")
                # ---------------------------------------------------------
                if (adc_volt < 0):
                    sys.stdout.write(str(adc_volt_str) + "\t")
                else:
                    sys.stdout.write("+" + str(adc_volt_str) + "\t")
                # ---------------------------------------------------------
                # sys.stdout.write(temp_str + "|" + "\n")
                sys.stdout.write('---\t' + "|" + "\n")
            print "  |--------------------------------------------------------------------------|"
        print "ERROR = " + str(error)
        # write in log file
        log = open(filename, "a+")
        timestr = strftime("%Y/%m/%d_%H:%M:%S", gmtime())
        log.write(str(iteration) + ";fim de ciclo;" + timestr + "\n")
        # Update the file
        log.close()
        iteration += 1
    print "ERRO = " + str(error)
예제 #10
0
 data = connection.recv(512)
 if data:
     #==============================================================
     # set GPIO pin direction
     if (data[0] == "\x01"):
         set_direction_bit(int(ord(data[1])), data[2], int(ord(data[3])), int(data[4]))
     #==============================================================
     # adjust DAC output value
     elif (data[0] == "\x02"):
         # convert voltage parameter from string to float
         value = float(data[2:len(data)])
         set_analog_output(int(ord(data[1])), value)
     #==============================================================
     # read DAC setpoint value
     elif (data[0] == "\x03"):
         selection.dac(ord(data[1]))
         dac_setpoint = dac.read()
         connection.sendall(str(dac_setpoint) + "\r\n")
     #==============================================================
     # read maximum of 10 last ADC input value
     elif (data[0] == "\x04"):
         voltage = read_analog_input(ord(data[1]))
         connection.sendall(str(voltage) + "\r\n")
         #print str(voltage)
     #==============================================================
     # write a whole byte in digital Port B
     elif (data[0] == "\x05"):
         set_digital_output_byte(ord(data[1]), ord(data[2]))
     #==============================================================
     # write a bit in Port B GPIO
     elif (data[0] == "\x06"):