Example #1
0
File: rram.py Project: botimerj/1Rx
    def __init__(self, gp):
        # Global Parameters
        self.gp = gp

        # RRAM Parameters
        self.ron = gp.rram.ron
        self.roff = gp.rram.roff
        self.rvar = gp.rram.rvar
        self.rp = gp.rram.rp

        self.vdiff = gp.rram.von - gp.rram.voff

        self.n_bit = gp.rram.n_bit
        self.rlsb = (self.roff - self.ron) / (2**self.n_bit - 1)
        self.glsb = (1 / self.ron - 1 / self.roff) / (2**self.n_bit - 1)

        self.x = gp.rram.size_x
        self.y = gp.rram.size_y

        # Resistance values
        self.arr = np.empty([self.y, self.x])

        # Digital values
        self.dig_arr = np.empty([self.y, self.x])

        # ADC
        self.adc = ADC(gp, self.n_bit, gp.mvm.active_rows,\
                       self.ron, self.roff, self.rvar, self.vdiff)

        # Energy
        self.e_read = 0
Example #2
0
 def __init__(self):
     self.logger_setup()
     self.speaker_volume = 70
     self.capture_volume = 100
     tmp = self.power_type
     sleep(0.01)  # when arduino open debug, sleep(> 0.3)
     self.adc = ADC(5)  # Power voltage channel: 5
     self._debug('Init PiSmart object complete')
def get_data_dict(adc_inputs):
    adc = ADC(adc_inputs)
    data_dict = get_time_dict()
    data_dict.update(temp())
    _, adc_dict = adc.read_addresses()
    data_dict.update(adc_dict)
    ultrasonic = Ultrasonic(trigger=3, echo=5)
    data_dict.update(ultrasonic.read_distance())
    return data_dict
Example #4
0
 def ADC_init(self):
     from adc import ADC
     self._A0 = ADC(0)
     self._A1 = ADC(1)
     self._A2 = ADC(2)
     self._A3 = ADC(3)
     self._A4 = ADC(4)
     self._A0.DEBUG = 'error'
     self._A1.DEBUG = 'error'
     self._A2.DEBUG = 'error'
     self._A3.DEBUG = 'error'
     self._A4.DEBUG = 'error'
Example #5
0
    def __init__(self, id, minc, maxc, m, c):
        self.id = id
        # Connection to ADS1115
        self.adc = ADC()

        # Threshold curves
        self.min_curve = minc
        self.max_curve = maxc

        # Linear approximation of ADC conversion to curve in degrees
        # angle = (adc_value - offset)/gradient
        self.gradient = float(m)
        self.offset = float(c)
class Presion(object):
    """docstring for Presion"""
    def __init__(self, address):
        self.adc = ADC([address])

    def read_sensor(self):
        return self.adc.read_addresses()
Example #7
0
def get_data_dict(adc_inputs):
    adc = ADC(adc_inputs)
    data_dict = get_time_dict()
    data_dict.update(temp())
    _, adc_dict = adc.read_addresses()
    data_dict.update(adc_dict)
    ultrasonic = Ultrasonic(trigger=trigger_pin, echo=echo_pin)
    u_distance = ultrasonic.read_distance()
    
    if u_distance['u_distance'] <= 20:
        turn_camera_flash(True)
    else:
        turn_camera_flash(False)
    
    data_dict.update(u_distance)
    return data_dict
Example #8
0
class GroveGasSensorMQ2:
    def __init__(self, channel):
        self.channel = channel
        self.adc = ADC()

    @property
    def MQ2(self):
        value = self.adc.read(self.channel)
        return value
Example #9
0
    def __init__(self, unix_socket_path, *args, **kwargs):
        self.unix_socket_path = unix_socket_path
        self.connection = None
        self.welcome_socket = None

        spi = SPI(0, 0)
        spi.msh = 2000000
        spi.mode = 1
        self.chs = [0, 1, 2, 3]
        self.ADC0 = ADC("P9_24", spi)
        self.ADC1 = ADC("P9_26", spi)
        self.ADC2 = ADC("P9_28", spi)
        self.ADC3 = ADC("P9_30", spi)
Example #10
0
 def __init__(self, name="peloop", functiongenerator=fg, eventreceiver=evr, adc1=adc, psd=mythen):
     self.setName(name)
     self.setInputNames(["time"])
     self.setExtraNames(["PData","EData","MythenData"])
     self.fg=FunctionGenerator()
     self.evr=EventReceiver()
     self.adc=ADC()
     self.psd=mythen
     self.voltagesmonitor=PVMonitor()
     self.electrometersmonitor=PVMonitor()
     self.counter=0
     self.numberofgates=0
Example #11
0
def adc_test():
    tb = TB(adc_p)
    adc = ADC(adc_p, tb)
    tb.submodules += adc

    # cd_dsp4 = ClockDomain("dsp4", reset_less=True)
    # tb.clock_domains += cd_dsp4

    def run(tb):

        dut = tb
        yield tb.i_sdoa.eq(1)
        yield tb.i_sdob.eq(1)
        yield
        yield tb.i_sdob.eq(0)
        yield tb.i_sdoc.eq(1)
        yield tb.i_sdod.eq(1)
        yield
        yield tb.i_sdoc.eq(0)
        yield
        yield tb.i_sdod.eq(0)
        yield
        yield dut.o_bitslip.eq(1)
        yield
        yield dut.o_bitslip.eq(0)
        for i in range(3):
            yield
        yield dut.o_bitslip.eq(1)
        for i in range(3):
            yield
        yield dut.o_bitslip.eq(0)
        yield
        # yield dut.bitslip_done.eq(1)
        # yield dut.i_start.eq(1)

        yield from dut.iter_vals("{:04b}".format(12), "{:04b}".format(2),
                                 "{:04b}".format(1), "{:04b}".format(7))

    run_simulation(
        tb,
        run(tb),
        vcd_name="adc_test.vcd",
        clocks={
            "sys": (8, 0),
            # "dsp4":   (2, 0),
        },
    )
Example #12
0
class FlexSensor():
    def __init__(self, id, minc, maxc, m, c):
        self.id = id
        # Connection to ADS1115
        self.adc = ADC()

        # Threshold curves
        self.min_curve = minc
        self.max_curve = maxc

        # Linear approximation of ADC conversion to curve in degrees
        # angle = (adc_value - offset)/gradient
        self.gradient = float(m)
        self.offset = float(c)

    # Map ID of FlexSensor instance to an analog input pin
    def map_id(self):
        # ID=1 -> AIN0
        if self.id == 1:
            return 0b100
        # ID=2 -> AIN2
        elif self.id == 2:
            return 0b110

    # Get the current approximation of how curved the FlexSensor is
    def get_curve(self):
        # Start a conversion on the ADS1115
        val = self.adc.read_AINX(self.map_id())

        # Convert into degrees
        curve = (val - self.offset) / self.gradient

        # Lower limit = 0, Upper Limit = 120 degrees
        curve = min(120, max(0, curve))
        return curve

    # Check if input 'curve' is within the min and max threshold curves
    def in_range(self, curve):
        return curve >= self.min_curve \
          and curve <= self.max_curve
Example #13
0
class Comm():
    def __init__(self, unix_socket_path, *args, **kwargs):
        self.unix_socket_path = unix_socket_path
        self.connection = None
        self.welcome_socket = None

        spi = SPI(0, 0)
        spi.msh = 2000000
        spi.mode = 1
        self.chs = [0, 1, 2, 3]
        self.ADC0 = ADC("P9_24", spi)
        self.ADC1 = ADC("P9_26", spi)
        self.ADC2 = ADC("P9_28", spi)
        self.ADC3 = ADC("P9_30", spi)

    def serve(self):
        try:
            if os.path.exists(self.unix_socket_path):
                logger.warning('Unix socket {} already exist'.format(
                    self.unix_socket_path))
                os.unlink(self.unix_socket_path)

            if self.welcome_socket != None:
                logger.warning('Welcome socket already istantiated')

            self.welcome_socket = socket.socket(socket.AF_UNIX,
                                                socket.SOCK_STREAM)
            self.welcome_socket.bind(self.unix_socket_path)
            os.system('chown iocuser:ioc {}'.format(self.unix_socket_path))

            logger.info('Unix socket created at {}'.format(
                self.unix_socket_path))
            self.welcome_socket.listen(1)

            while True:
                logger.info('Unix welcome socket listening')
                connection, client_address = self.welcome_socket.accept()
                logger.info('Client {} connected'.format(client_address))

                connection.settimeout(30)

                self.handle_connection(connection)
        except:
            logger.exception('Comm exception')
        finally:
            self.welcome_socket.close()
            os.remove(self.unix_socket_path)
            logger.info('Comm server shutdown')
            self.welcome_socket = None

    def handle_connection(self, connection):
        try:
            while True:
                command = connection.recv(1024).decode('utf-8')
                if command == 'ADC0:DATA?':
                    response = str(self.ADC0.mean(self.chs))
                elif command == 'ADC1:DATA?':
                    response = str(self.ADC1.mean(self.chs))
                elif command == 'ADC2:DATA?':
                    response = str(self.ADC2.mean(self.chs))
                elif command == 'ADC3:DATA?':
                    response = str(self.ADC3.mean(self.chs))
                else:
                    response = ResponseType.UNSUPPORTED_COMMAND

                connection.sendall('{}\r\n'.format(response).encode('utf-8'))
                logger.debug('Command {} Length {}'.format(command, response))
        except:
            logger.exception('Connection exception')
        finally:
            logger.warning('Connection closed')
            connection.close()
Example #14
0
        times_g = []
        lats = []
        lat_err = []
        lons = []
        lon_err = []
        alts = []
        alt_err = []

        print("Station %i Trial %i \nPress enter to collect data:" % (i, j))
        pause = input('')
        print("Collecting data...")

        g_data.append(GPS())
        t0 = time.time()
        voltages = ADC()
        t1 = time.time()
        g_data.append(GPS())

        for g in g_data:
            t_g = g[0]
            t_g = str(t_g).split(' ')[1]
            t_g = str(t_g).split('-')[0]
            times_g.append(t_g)

            lats.append(g[1][0])
            lat_err.append(g[1][1])

            lons.append(g[2][0])
            lon_err.append(g[2][1])
def readADC():
    adc = ADC([0])
    return adc.read_addresses()
Example #16
0
def main(args=None):
    sw = switch_4()
    smb = I2C()
    par = parse()
    adc = ADC()
    pers = _8bitIO()
    port = _16bitIO()
    parser = par.get_parser()
    args = parser.parse_args(args)  #inspect the command line

    err_flag = False

    if ((args.i2c0 and not args.i2c1) or (args.i2c1 and not args.i2c0)):
        try:
            data = smb.parse_func(args.data[0])
        except:
            err_flag = True
            raise
            print('Error parsing or invalid syntax, use "-h" for help')
        if not err_flag:
            if i2c.w_found and not i2c.r_found:
                try:
                    smb.write(data[0], data[1], not args.i2c0) # data[0] is data_i, data[1] is data_w
                    print('ACK')
                except IOError:
                    print('NACK...confirm you are transacting with the correct bus')
                except:
                    raise
                    print('Invalid Syntax')
            if not i2c.w_found and not i2c.r_found:
                try:
                    smb.detect(data[0], not args.i2c0)
                    print('ACK')
                except:
                    print('NACK...confirm you are transacting with the correct bus')
            if i2c.r_found and not i2c.w_found:
                try:
                    smb.read(data[0], data[2], not args.i2c0)
                except IOError:
                    print('NACK...confirm you are transacting with the correct bus')
                except:
                    raise
                    print('Invalid Syntax')
            if i2c.r_found and i2c.w_found:
                smb.write_read(data[0], data[2], data[1], not args.i2c0)

    elif args.gpio and 'getall' in args.data:
        try:
            os.system('raspi-gpio get')
        except:
            print('Invalid syntax')

    elif args.gpio and 'get' in args.data:
        try:
            os.system('raspi-gpio get ' + args.data[1])
            print('Success')
        except:
            print('Invalid syntax')

    elif args.gpio and 'set' in args.data:
        if len(args.data) == 3:
            try:
                os.system('raspi-gpio set ' + args.data[1] + ' ' + args.data[2])
                print('Success')
            except:
                print('Invalid syntax')

        if len(args.data) == 4:
            try:
                os.system('raspi-gpio set ' + args.data[1] + ' ' + args.data[2] + ' ' + args.data[3])
                print('Success')
            except:
                print('Invalid syntax')

        if len(args.data) == 5:
            try:
                os.system('raspi-gpio set ' + args.data[1] + ' ' + args.data[2] + ' ' + args.data[3] + ' ' + args.data[4])
                print('Success')
            except:
                print('Invalid syntax')
    elif args.adc:

        if args.data[0] == 'raw' and len(args.data) == 2:
            try:
                adc.raw_adc(args.data[1])
            except IOError:
                print('NACK...confirm device is powered on')
            except:
                print('Invalid syntax')
        elif args.data[0] ==  'volt' and len(args.data) == 2:
            try:
                print(adc.volt_adc(args.data[1]))
            except IOError:
                print('NACK...confirm device is powered on')
            except:
                print('Invalid syntax')
        else:
            print('Invalid syntax')
    elif args.per:
        if(args.data[0] == 'config'):
            try:
                pers.configPorts()
                print('Success')
            except IOError:
                print('NACK...confirm device is powered on')
            except:
                print('Fail!')
        elif(args.data[0] == 'arm'):
            try:
                pers.arm(args.data[1], False)
                print('Success')
            except IOError:
                print('NACK...confirm device is powered on')
            except:
                print('Invalid syntax')
        elif(args.data[0] == 'disarm'):
            try:
                pers.arm(args.data[1], True)
                print('Success')
            except IOError:
                print('NACK...confirm device is powered on')
            except:
                print('Invalid syntax')
        elif(args.data[0] == 'read'):
            try:
                pers.read_inputs()
                print('Success')
            except IOError:
                print('NACK...confirm device is powered on')
            except:
                print('Invalid syntax')
    elif args.port:
        if(args.data[0] == 'config'):
            try:
                port.configPorts()
                print('Success')
            except IOError:
                print('NACK...confirm device is powered on')
            except:
                print('Fail!')
        elif args.data[0] == 'readall':
            try:
                port.zone_readall(args.data[1])
            except IOError:
                print('NACK...confirm device is powered on')
            except:
                print('Invalid syntax')
        elif args.data[0] == 'read':
            try:
                port.zone_read(args.data[1], args.data[2])
            except IOError:
                print('NACK...confirm device is powered on')
            except:
                print('Invalid syntax')
        elif args.data[0] == 'led':
            try:
                port.led_toggle(args.data[1], args.data[2], args.data[3])
            except IOError:
                print('NACK...confirm device is powered on')
            except:
                print('Invalid syntax')
        else:
            print('Invalid syntax')
    elif args.switch:
        if args.data[0] == 'write':
            try:
                sw.ch_write(args.data[1], args.data[2], args.data[3])
            except IOError:
                print('NACK...confirm device is powered on')
            except:
                print('Invalid syntax')
        elif args.data[0] == 'readint':
            try:
                sw.read_int(args.data[1])
            except IOError:
                print('NACK...confirm device is powered on')
            except:
                print('Invalid syntax')
        elif args.data[0] == 'read':
            try:
                sw.read_dat(args.data[1], args.data[2])
            except IOError:
                print('NACK...confirm device is powered on')
            except:
                print('Invalid syntax')

    else:
        print('Invalid syntax')
 def __init__(self, address):
     self.adc = ADC([address])
Example #18
0
def time_domain_probe(num_bits=10, offset=0.5, tau=6, vin=0, steps=None):
    adcinstance = ADC(tau=tau, num_bits=num_bits)
    adc2 = ADC(tau=tau, num_bits=num_bits)
    # adcinstance.set_fsm_steps(weird_steps)
    adc2.set_fsm_steps(steps)
    inputvoltage = vin + offset
    adcinstance.run_1_adc_sample(vin=inputvoltage)
    adc2.run_1_adc_sample(vin=inputvoltage)
    plots = adcinstance.return_transient_results()
    helper.plot_transients(plots, inputvoltage)

    plots2 = adc2.return_transient_results()
    helper.plot_transients(plots2, inputvoltage)

    output = int(adcinstance.return_output())
    output2 = int(adc2.return_output())
    print('output is ' + str(output))
    print('adjusted output is ' + str(output2))
Example #19
0
File: rram.py Project: botimerj/1Rx
class RRAM:
    def __init__(self, gp):
        # Global Parameters
        self.gp = gp

        # RRAM Parameters
        self.ron = gp.rram.ron
        self.roff = gp.rram.roff
        self.rvar = gp.rram.rvar
        self.rp = gp.rram.rp

        self.vdiff = gp.rram.von - gp.rram.voff

        self.n_bit = gp.rram.n_bit
        self.rlsb = (self.roff - self.ron) / (2**self.n_bit - 1)
        self.glsb = (1 / self.ron - 1 / self.roff) / (2**self.n_bit - 1)

        self.x = gp.rram.size_x
        self.y = gp.rram.size_y

        # Resistance values
        self.arr = np.empty([self.y, self.x])

        # Digital values
        self.dig_arr = np.empty([self.y, self.x])

        # ADC
        self.adc = ADC(gp, self.n_bit, gp.mvm.active_rows,\
                       self.ron, self.roff, self.rvar, self.vdiff)

        # Energy
        self.e_read = 0

    def write(self, weights, res):
        # Helper variables
        n_bit = int(self.n_bit)
        n_cell = int(np.ceil(res / n_bit))
        if (n_cell > self.x):
            raise Exception("No weight splitting allowed")

        w = np.array(weights, dtype=int)

        # Generate digital represntation in weight arr
        self.dig_arr = np.zeros([self.y, self.x])
        for i in range(w.shape[0]):
            for j in range(w.shape[1]):
                try:
                    num = int(w[i][j])
                    a = [(num >> (n_bit * i)) & (2**n_bit - 1)
                         for i in range(n_cell)]
                    a = np.flip(np.array(a, dtype=int))
                    self.dig_arr[i][j * n_cell:(j + 1) * n_cell] = a
                except:
                    print("except")
                    pass

        # Assign real resistances to r_cell
        for i in range(self.y):
            for j in range(self.x):
                self.arr[i][j] = 1 / self.roff + self.glsb * self.dig_arr[i][j]

                self.arr[i][j] = 1 / (10**(np.log10(1 / self.arr[i][j]) +
                                           np.random.normal(0, self.rvar)))
                #self.arr[i][j]  = 1/(1/self.arr[i][j] + np.random.normal(0,self.rvar))
                #print(1/self.arr[i][j])

    def read(self, ifmap, res):

        ifm = np.array(ifmap, dtype=int)

        # Bit-serial approach
        dout = np.zeros([1, self.x])
        for i in range(res):
            v = ((ifm >> i) & 1) * (self.vdiff)
            i_out = np.dot(v, self.arr)
            for j in range(self.x):
                dout[0, j] = dout[0, j] + (self.adc.convert(i_out[j]) << i)
                self.e_read += self.adc.energy

        dout = np.array(dout, dtype=int)

        # Concatenate columns
        n_cell = int(np.ceil(res / self.n_bit))
        num_words = int(np.floor(self.x / n_cell))

        out = np.zeros([1, num_words])
        for i in range(num_words):
            for j in range(n_cell):
                idx = i * n_cell + j
                out[0][i] += (dout[0][idx] << ((n_cell - 1 - j) * self.n_bit))

        return out
Example #20
0
class PiSmart(_Basic_class):
    _class_name = 'PiSmart'

    ON = 1
    OFF = 0

    SERVO_POWER_OFF = 0x20
    SERVO_POWER_ON = 0x21
    SPEAKER_POWER_OFF = 0x22
    SPEAKER_POWER_ON = 0x23
    MOTOR_POWER_OFF = 0x24
    MOTOR_POWER_ON = 0x25
    SET_POWER_DC = 0X26  # power_type = 0, DC power
    SET_POWER_2S = 0X27  # power_type = 1, Li-po battery 2s
    SET_POWER_3S = 0X28  # power_type = 2, Li-po battery 3s

    POWER_TYPE = 0X1d  # send this number to ask arduino return power-type

    def __init__(self):
        self.logger_setup()
        self.speaker_volume = 70
        self.capture_volume = 100
        tmp = self.power_type
        sleep(0.01)  # when arduino open debug, sleep(> 0.3)
        self.adc = ADC(5)  # Power voltage channel: 5
        self._debug('Init PiSmart object complete')

    def servo_switch(self, on_off):
        self.pwm_switch(on_off)

    def pwm_switch(self, on_off):
        if on_off not in (0, 1):
            raise ValueError(
                "On_off set must be .ON(1) or .OFF(0), not \"{0}\".".format(
                    on_off))
        if on_off == 1:
            self._write_sys_byte(self.SERVO_POWER_ON)
            self._debug('Servo switch ON')
        else:
            self._write_sys_byte(self.SERVO_POWER_OFF)
            self._debug('Servo switch OFF')

    def motor_switch(self, on_off):
        if on_off not in (0, 1):
            raise ValueError(
                "On_off set must be .ON(1) or .OFF(0), not \"{0}\".".format(
                    on_off))
        if on_off == 1:
            self._write_sys_byte(self.MOTOR_POWER_ON)
            self._debug('Motor switch ON')
        else:
            self._write_sys_byte(self.MOTOR_POWER_OFF)
            self._debug('Motor switch OFF')

    def speaker_switch(self, on_off):
        if on_off not in (0, 1):
            raise ValueError(
                "On_off set must in .ON(1) or .OFF(0), not \"{0}\".".format(
                    on_off))
        if on_off == 1:
            self._write_sys_byte(self.SPEAKER_POWER_ON)
            self._debug('Speaker switch ON')
        else:
            self._write_sys_byte(self.SPEAKER_POWER_OFF)
            self._debug('Speaker switch OFF')

    @property
    def power_type(self):
        self._power_type = self._read_sys_byte(self.POWER_TYPE)
        self._debug('Get power type from bottom board')
        return self._power_type

    @power_type.setter
    def power_type(self, power_type):
        if power_type not in ['2S', '3S', 'DC']:
            raise ValueError(
                'Power type only support: "2S", "3S" Li-po battery or "DC" power, not \"{0}\".'
                .format(power_type))
        else:
            self._power_type = power_type
            if power_type == '2S':
                self._write_sys_byte(self.SET_POWER_2S)
                self._debug('Set power type to 2S Li-po battery')
            elif power_type == '3S':
                self._write_sys_byte(self.SET_POWER_3S)
                self._debug('Set power type to 3S Li-po battery')
            elif power_type == 'DC':
                self._write_sys_byte(self.SET_POWER_DC)
                self._debug('Set power type to DC power')

    @property
    def power_voltage(self):
        A7_value = self.adc.read()
        if A7_value:
            A7_volt = float(A7_value) / 1024 * 5
            battery_volt = round(A7_volt * 14.7 / 4.7, 2)
            self._debug('Read battery: %s V' % battery_volt)
            return battery_volt
        else:
            return False

    @property
    def speaker_volume(self):
        return self._speaker_volume

    @speaker_volume.setter
    def speaker_volume(self, value):
        if value > 100:
            value = 100
            self._warning('Value is over 100, set to 100')
        if value < 0:
            value = 0
            self._warning('Value is less than 0, set to 0')
        # gain(dB) = 10 * log10(volume)
        #self._debug('speaker percentage = %s' % value)
        self._speaker_volume = self._map(value, 0, 100, 0, 75)
        self._debug('speaker percentage = %s' % value)
        #self._speaker_volume = self._map(value, 0, 100, ((10.0**(-102.39/10))-1), ((10.0**(4.0/10))-1))
        #self._speaker_volume = int(math.log10(self._speaker_volume) * 100) * 10
        #self._debug('speaker dB = %s' % self._speaker_volume)
        cmd = "sudo amixer -M sset 'PCM' %d%%" % self._speaker_volume
        self.run_command(cmd)

    @property
    def capture_volume(self):
        return self._capture_volume

    @capture_volume.setter
    def capture_volume(self, value):
        if value not in range(0, 101):
            raise ValueError(
                "Volume should be in [0, 100], not \"{0}\".".format(value))
        self._capture_volume = value
        cmd = "sudo amixer -M -c 1 sset 'Mic' %d%%" % (self._capture_volume)
        self.run_command(cmd)
        return 0

    def _get_capture_volume_id(self):
        all_controls = self.run_command("sudo amixer -c 1 controls")
        all_controls = all_controls.split('\n')
        capture_volume = ''
        capture_volume_id = ''
        for line in all_controls:
            if 'Mic Capture Volume' in line:
                capture_volume = line
        capture_volume = capture_volume.split(',')
        for variable in capture_volume:
            if 'numid' in variable:
                capture_volume_id = variable
        capture_volume_id = capture_volume_id.split('=')[1]
        return int(capture_volume_id)

    def _get_capture_volume_max(self, numid):
        all_values = self.run_command("sudo amixer -c 1 cget numid=%s" % numid)
        all_values = all_values.split('\n')
        values = all_values[1]
        values = values.split(',')
        for value in values:
            if 'max' in value:
                max_value = value
        max_value = max_value.split('=')[1]

        return int(max_value)

    @property
    def cpu_temperature(self):
        raw_cpu_temperature = commands.getoutput(
            "cat /sys/class/thermal/thermal_zone0/temp")
        cpu_temperature = float(raw_cpu_temperature) / 1000
        #cpu_temperature = 'Cpu temperature : ' + str(cpu_temperature)
        return cpu_temperature

    @property
    def gpu_temperature(self):
        raw_gpu_temperature = commands.getoutput(
            '/opt/vc/bin/vcgencmd measure_temp')
        gpu_temperature = float(
            raw_gpu_temperature.replace('temp=', '').replace('\'C', ''))
        #gpu_temperature = 'Gpu temperature : ' + str(gpu_temperature)
        return gpu_temperature

    @property
    def ram_info(self):
        p = os.popen('free')
        i = 0
        while 1:
            i = i + 1
            line = p.readline()
            if i == 2:
                return line.split()[1:4]

    @property
    def ram_total(self):
        ram_total = round(int(self.ram_info[0]) / 1000, 1)
        return ram_total

    @property
    def ram_used(self):
        ram_used = round(int(self.ram_info[1]) / 1000, 1)
        return ram_used

    @property
    def disk_space(self):
        p = os.popen("df -h /")
        i = 0
        while 1:
            i = i + 1
            line = p.readline()
            if i == 2:
                return line.split()[1:5]

    @property
    def disk_total(self):
        disk_total = float(self.disk_space[0][:-1])
        return disk_total

    @property
    def disk_used(self):
        disk_used = float(self.disk_space[1][:-1])
        return disk_used

    @property
    def cpu_usage(self):
        return str(
            os.popen(
                "top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip())

    def end(self):
        self.servo_switch(self.OFF)
        self.pwm_switch(self.OFF)
        self.motor_switch(self.OFF)
        self.speaker_switch(self.OFF)
Example #21
0
class PiSmart(_Basic_class):
    _class_name = 'Amateur PiSmart'

    ON = 1
    OFF = 0

    def __init__(self, *item):
        self._ps            = pismart.PiSmart()
        self._ps.DEBUG = 'error'
        self.servo_switch   = self._ps.servo_switch
        self.pwm_switch     = self._ps.pwm_switch
        self.motor_switch   = self._ps.motor_switch
        self.speaker_switch = self._ps.speaker_switch
        if len(item) == 0:
            self.ALL_init()
        elif item == "manual":
            pass

    def ALL_init(self):
        self.ADC_init()
        self.Servo_init()
        self.LED_init()
        self.Motor_init()
        self.TTS_init()
        self.STT_init()

    def ADC_init(self):
        from adc import ADC
        self._A0 = ADC(0)
        self._A1 = ADC(1)
        self._A2 = ADC(2)
        self._A3 = ADC(3)
        self._A4 = ADC(4)
        self._A0.DEBUG = 'error'
        self._A1.DEBUG = 'error'
        self._A2.DEBUG = 'error'
        self._A3.DEBUG = 'error'
        self._A4.DEBUG = 'error'

    def Servo_init(self):
        from servo import Servo
        self._servo0 = Servo(0)
        self._servo1 = Servo(1)
        self._servo2 = Servo(2)
        self._servo3 = Servo(3)
        self._servo4 = Servo(4)
        self._servo5 = Servo(5)
        self._servo6 = Servo(6)
        self._servo7 = Servo(7)
        self.servo_switch(self.ON)
        self._servo0.DEBUG = 'error'
        self._servo1.DEBUG = 'error'
        self._servo2.DEBUG = 'error'
        self._servo3.DEBUG = 'error'
        self._servo4.DEBUG = 'error'
        self._servo5.DEBUG = 'error'
        self._servo6.DEBUG = 'error'
        self._servo7.DEBUG = 'error'

    def PWM_init(self):
        from pwm import PWM
        self._pwm0 = PWM(0)
        self._pwm1 = PWM(1)
        self._pwm2 = PWM(2)
        self._pwm3 = PWM(3)
        self._pwm4 = PWM(4)
        self._pwm5 = PWM(5)
        self._pwm6 = PWM(6)
        self._pwm7 = PWM(7)
        self.pwm_switch(self.ON)
        self._pwm0.DEBUG = 'error'
        self._pwm1.DEBUG = 'error'
        self._pwm2.DEBUG = 'error'
        self._pwm3.DEBUG = 'error'
        self._pwm4.DEBUG = 'error'
        self._pwm5.DEBUG = 'error'
        self._pwm6.DEBUG = 'error'
        self._pwm7.DEBUG = 'error'

    def LED_init(self):
        from led import LED
        self._led = LED()
        self._led.DEBUG = 'error'

    def Motor_init(self):
        from motor import Motor
        self._motor_a = Motor(Motor.MotorA)
        self._motor_b = Motor(Motor.MotorB)
        self._motor_a.DEBUG = 'error'
        self._motor_b.DEBUG = 'error'
        self.motor_switch(self.ON)

    def TTS_init(self):
        from tts import TTS
        self._tts = TTS()
        self._tts.DEBUG = 'error'
        self.speaker_switch(self.ON)
        self.speaker_volume = 100

    def STT_init(self):
        from stt import STT
        self._stt = STT('dictionary', name_calling=False, timeout=10.0, dictionary_update=True)
        self._stt.DEBUG = 'error'
        self.capture_volume = 100

    def ADC_end(self):
        pass
    
    def Servo_end(self):
        self.servo_switch(self.OFF)

    def PWM_end(self):
        self.pwm_switch(self.OFF)

    def Motor_end(self):
        self._motor_a.stop()
        self._motor_b.stop()
        self.motor_switch(self.OFF)

    def LED_end(self):
        self.LED = 0

    def TTS_end(self):
        self._tts.end()
        self.speaker_switch(self.OFF)

    def STT_end(self):
        self._stt.end()


    def end(self):
        self.ADC_end()
        self.LED_end()
        self.Motor_end()
        self.Servo_end()
        self.PWM_end()
        self.STT_end()

    @property
    def power_type(self):
        return self._ps.power_type
    @power_type.setter
    def power_type(self, value):
        self._ps.power_type = value
    @property
    def power_voltage(self):
        return self._ps.power_voltage
    @power_voltage.setter
    def power_voltage(self, value):
        self._ps.power_voltage = value
    @property
    def speaker_volume(self):
        return self._ps.speaker_volume
    @speaker_volume.setter
    def speaker_volume(self, value):
        self._ps.speaker_volume = value
    @property
    def capture_volume(self):
        return self._ps.capture_volume
    @capture_volume.setter
    def capture_volume(self, value):
        self._ps.capture_volume = value
    @property
    def cpu_temperature(self):
        return self._ps.cpu_temperature

    @property
    def A0(self):
        return self._A0.read()
    @property
    def A1(self):
        return self._A1.read()
    @property
    def A2(self):
        return self._A2.read()
    @property
    def A3(self):
        return self._A3.read()
    @property
    def A4(self):
        return self._A4.read()

    @property
    def Servo0(self):
        return self._servo0.angle
    @Servo0.setter
    def Servo0(self, angle):
        self._servo0.angle = angle
    @property
    def Servo1(self):
        return self._servo1.angle
    @Servo1.setter
    def Servo1(self, angle):
        self._servo1.angle = angle
    @property
    def Servo2(self):
        return self._servo2.angle
    @Servo2.setter
    def Servo2(self, angle):
        self._servo2.angle = angle
    @property
    def Servo3(self):
        return self._servo3.angle
    @Servo3.setter
    def Servo3(self, angle):
        self._servo3.angle = angle
    @property
    def Servo4(self):
        return self._servo4.angle
    @Servo4.setter
    def Servo4(self, angle):
        self._servo4.angle = angle
    @property
    def Servo5(self):
        return self._servo5.angle
    @Servo5.setter
    def Servo5(self, angle):
        self._servo5.angle = angle
    @property
    def Servo6(self):
        return self._servo6.angle
    @Servo6.setter
    def Servo6(self, angle):
        self._servo6.angle = angle
    @property
    def Servo7(self):
        return self._servo7.angle
    @Servo7.setter
    def Servo7(self, angle):
        self._servo7.angle = angle

    @property
    def PWM0(self):
        return self._pwm0.value
    @PWM0.setter
    def PWM0(self, value):
        self._pwm0.value = value
    @property
    def PWM1(self):
        return self._pwm1.value
    @PWM1.setter
    def PWM1(self, value):
        self._pwm1.value = value
    @property
    def PWM2(self):
        return self._pwm2.value
    @PWM2.setter
    def PWM2(self, value):
        self._pwm2.value = value
    @property
    def PWM3(self):
        return self._pwm3.value
    @PWM3.setter
    def PWM3(self, value):
        self._pwm3.value = value
    @property
    def PWM4(self):
        return self._pwm4.value
    @PWM4.setter
    def PWM4(self, value):
        self._pwm4.value = value
    @property
    def PWM5(self):
        return self._pwm5.value
    @PWM5.setter
    def PWM5(self, value):
        self._pwm5.value = value
    @property
    def PWM6(self):
        return self._pwm6.value
    @PWM6.setter
    def PWM6(self, value):
        self._pwm6.value = value
    @property
    def PWM7(self):
        return self._pwm7.value
    @PWM7.setter
    def PWM7(self, value):
        self._pwm7.value = value

    @property
    def LED(self):
        return self._led.brightness
    @LED.setter
    def LED(self, value):
        self._led.brightness = value    

    @property
    def MotorA(self):
        return self._motor_a.speed
    @MotorA.setter
    def MotorA(self, value):
        self._motor_a.speed = value
    @property
    def MotorB(self):
        return self._motor_b.speed
    @MotorB.setter
    def MotorB(self, value):
        self._motor_b.speed = value

    @property
    def MotorA_reversed(self):
        return self._motor_a.is_reversed
    @MotorA_reversed.setter
    def MotorA_reversed(self, value):
        self._motor_a.is_reversed = value
    @property
    def MotorB_reversed(self):
        return self._motor_b.is_reversed
    @MotorB_reversed.setter
    def MotorB_reversed(self, value):
        self._motor_b.is_reversed = value

    @property
    def Say(self):
        return self._tts.say
    @Say.setter
    def Say(self, words):
        self._tts.say = words

    @property
    def listen(self):
        return self._stt.recognize()

    @property
    def heard(self):
        return self._stt.heard

    @property
    def result(self):
        return self._stt.result
Example #22
0
 def __init__(self, miso, mosi, clk, cs, channel):
     ADC.__init__(self, miso, mosi, clk, cs)
     self._channel = channel
Example #23
0
class PELoop(ScannableMotionBase):
    
    def __init__(self, name="peloop", functiongenerator=fg, eventreceiver=evr, adc1=adc, psd=mythen):
        self.setName(name)
        self.setInputNames(["time"])
        self.setExtraNames(["PData","EData","MythenData"])
        self.fg=FunctionGenerator()
        self.evr=EventReceiver()
        self.adc=ADC()
        self.psd=mythen
        self.voltagesmonitor=PVMonitor()
        self.electrometersmonitor=PVMonitor()
        self.counter=0
        self.numberofgates=0
        
    # function generator controls
    def getElectrometer(self):
        try:
            self.adc.getElectrometer()
        except:
            print "Fail to get electrometer readings: ", sys.exc_info()[0]
            raise

    def getVoltage(self):
        try:
            self.adc.getVoltage()
        except:
            print "Fail to get voltage readings: ", sys.exc_info()[0]
            raise

    def atScanStart(self):
        #add voltage and electrometer monitor to get data, 
        #this may trigger an monitor event that increment the counter, so it must be reset
        self.voltagesmonitor.setNumberOfGates(self.numberofgates)
        self.electrometersmonitor.setNumberOfGates(self.numberofgates)
        self.adc.addVoltageMonitor(self.voltagesmonitor)
        self.adc.addElectrometerMonitor(self.electrometersmonitor)
        #start ramp output
        self.fg.setOutput(1)

   
    def atScanEnd(self):
        #add voltage and electrometer monitor to get datas
        self.adc.removeVoltageMonitor(self.voltagesmonitor)
        self.adc.removeElectrometerMonitor(self.electrometersmonitor)
        #stop ramp output
        self.fg.setOutput(0)

    def atPointStart(self):
        self.voltagesmonitor.resetCounter()
        self.voltagesmonitor.resetRepetition()
        self.electrometersmonitor.resetCounter()
        self.electrometersmonitor.resetRepetition()
    def atPointEnd(self):
        pass

    def rawGetPosition(self):
        return self.volatgesmonitor.rawGetPosition(), self.electrometersmonitor.rawGetPosition(),mythen.getPosition()

    def rawAsynchronousMoveTo(self,new_position):
        self.evr.rawAsynchronousMoveTo(new_position)
    
    def rawIsBusy(self):
        return self.evr.rawIsBusy()
Example #24
0
def static_tests_sweep(num_bits=7,
                       offset=0.5,
                       tau=6,
                       plot_decision_tree=False,
                       bucketsize=20,
                       steps=None):

    datasize = int(bucketsize * 2**num_bits)
    input_axis = np.linspace(0, 2**num_bits, datasize)
    output_axis = np.zeros(shape=(datasize, ), dtype=int)
    output_axis2 = np.zeros(shape=(datasize, ), dtype=int)
    counter = 0
    while counter < datasize:
        adcinstance = ADC(tau=tau, num_bits=num_bits)
        adc2 = ADC(tau=tau, num_bits=num_bits)
        #adcinstance.set_fsm_steps(weird_steps)
        adc2.set_fsm_steps(steps)
        inputvoltage = input_axis[counter] + offset
        adcinstance.run_1_adc_sample(vin=inputvoltage)
        adc2.run_1_adc_sample(vin=inputvoltage)
        plots = adcinstance.return_transient_results()
        plots2 = adc2.return_transient_results()
        output = int(adcinstance.return_output())
        output2 = int(adc2.return_output())
        if (plot_decision_tree):
            print(output)
            helper.plot_transients(plots, vin=None)
            helper.plot_transients(plots2, vin=None)
        output_axis[counter] = output
        output_axis2[counter] = output2
        counter = counter + 1

    adc_eval.eval_adc_from_arrays(input_axis, output_axis)
    adc_eval.eval_adc_from_arrays(input_axis, output_axis2)
Example #25
0
from adc import ADC
adc = ADC(11, mosi=10, miso=9, ss=8)

for i in range(5):
    print adc.read(0)

import Adafruit_GPIO.SPI as SPI
#
# spi = SPI.SpiDev(0,0)
# spi.open()
# spi.set_clock_hz(5000)
# spi.set_mode(0)
# spi.set_bit_order(0)
Example #26
0
 def __init__(self, channel):
     self.channel = channel
     self.adc = ADC()