Пример #1
0
def init():
    GPIO.setwarnings(False)
    GPIO.cleanup()
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(SPIMOSI, GPIO.OUT)
    GPIO.setup(SPIMISO, GPIO.IN)
    GPIO.setup(SPICLK, GPIO.OUT)
    GPIO.setup(SPICS, GPIO.OUT)
    global adc
    adc = MCP3208()
Пример #2
0
    def __init__(self):
        self.light = False

        self.adc = MCP3208()
        self.sensor2 = BMP085.BMP085(mode=BMP085.BMP085_ULTRAHIGHRES)

        signal(SIGTERM, self.__cleanup)

        GPIO.setmode(GPIO.BCM)
        GPIO.setup(self.CHANNEL1, GPIO.OUT)
        GPIO.output(self.CHANNEL1, GPIO.HIGH)
        GPIO.setup(self.CHANNEL2, GPIO.OUT)
        GPIO.output(self.CHANNEL2, GPIO.HIGH)
Пример #3
0
def heartRate():
    pin = 2
    # GPIOピン番号の定義方法を設定する(BCM/BOARD)
    GPIO.setmode(GPIO.BCM)
    # 18番ピンを出力モードで初期化する
    GPIO.setup(pin, GPIO.OUT)

    adc = MCP3208()
    threshold = 2  #V

    x = np.arange(0, 60, 1)
    y = np.zeros(x.shape[0])

    heart_rate_duration = np.zeros(10)

    y[x.shape[0] - 1]
    start = time.time()

    GPIO.output(pin, False)

    while True:

        data = adc.read(0) * 5 / 4095.0
        if data >= threshold:
            if y[x.shape[0] - 2] < y[x.shape[0] - 1] and y[x.shape[0] -
                                                           1] > data:
                duration = time.time() - start
                if duration >= 60 / 150.0:
                    heart_rate_duration = np.roll(heart_rate_duration, -1)
                    heart_rate_duration[heart_rate_duration.shape[0] -
                                        1] = duration
                    heart_rate = round(60 / np.mean(heart_rate_duration), 1)
                    sd = round(np.std(heart_rate_duration), 4)  #標準偏差
                    if np.count_nonzero(heart_rate_duration
                                        ) == heart_rate_duration.shape[0]:
                        print("{}bpm : standard deviation {}".format(
                            heart_rate, sd))
                    if sd < 0.04:
                        break
                start = time.time()

        y = np.roll(y, -1)
        y[x.shape[0] - 1] = data

        time.sleep(0.001)

    GPIO.output(pin, True)
    # GPIOを解放
    GPIO.cleanup()

    return heart_rate
if cfg['debug'] == True:
    print '[debug] Uploading ' + filepath + ' to s3'

# Upload to S3
conn = tinys3.Connection(cfg['s3']['access_key_id'],
                         cfg['s3']['secret_access_key'])
f = open(filepath, 'rb')
conn.upload(filepath,
            f,
            cfg['s3']['bucket_name'],
            headers={'x-amz-meta-cache-control': 'max-age=60'})

if os.path.exists(filepath):
    os.remove(filepath)

adc = MCP3208()
moisture = adc.read(0)
rain = adc.read(1)
light = adc.read(2)
print("moisture", moisture)
print("rain", rain)
print("light", light)

humidity, temp = Adafruit_DHT.read_retry(11, 4)

print("temp", temp)
print("humidity", humidity)

myMQTTClient = AWSIoTMQTTClient("new_Client")
myMQTTClient.configureEndpoint("a3so5jr4thekwx.iot.us-east-1.amazonaws.com",
                               8883)
Пример #5
0
 def __init__(self):
     self.client = MCP3208()
     self.threadStart = Thread(target=self.__start)
     self.threadStart.setDaemon(True)
     self.threadStart.start()
Пример #6
0
def getSensor():
    adc = MCP3208()
    cds = adc.read(0) * 5 / 4095.0
    uv = adc.read(1) * 5 / 4095.0
    return cds, uv
Пример #7
0
class MQ():

    adc = MCP3208()

    RL_VALUE = 5
    RO_CLEAN_AIR_FACTOR = 9.83

    CALIBARAION_SAMPLE_TIMES = 50
    CALIBRATION_SAMPLE_INTERVAL = 500

    READ_SAMPLE_INTERVAL = 50
    READ_SAMPLE_TIMES = 5

    GAS_LPG = 0
    GAS_CO = 1
    GAS_SMOKE = 2

    def __init__(self, Ro=3.46, analogPin=0):
        self.Ro = Ro
        self.MQ_PIN = analogPin

        self.LPGCurve = [2.3, 0.21, -0.47]
        self.COCurve = [2.3, 0.72, -0.34]
        self.SmokeCurve = [2.3, 0.53, -0.44]

        print("Calibrating...")
        self.Ro = self.MQCalibration(self.MQ_PIN)
        print("Calibration is done...\n")
        print("Ro=%f kohm" % self.Ro)

    def MQPercentage(self):
        val = {}
        read = self.MQRead(self.MQ_PIN)
        val["GAS_LPG"] = self.MQGetGasPercentage(read / self.Ro, self.GAS_LPG)
        val["CO"] = self.MQGetGasPercentage(read / self.Ro, self.GAS_CO)
        val["SMOKE"] = self.MQGetGasPercentage(read / self.Ro, self.GAS_SMOKE)
        return val

    def MQResistanceCalculation(self, raw_adc):
        return float(self.RL_VALUE * (4095.0 - raw_adc) / float(raw_adc))

    def MQCalibration(self, mq_pin):
        val = 0.0
        for i in range(self.CALIBARAION_SAMPLE_TIMES):
            val += self.MQResistanceCalculation(self.adc.read(mq_pin))
            time.sleep(self.CALIBRATION_SAMPLE_INTERVAL / 1000.0)

        val = val / self.CALIBARAION_SAMPLE_TIMES

        val = val / self.RO_CLEAN_AIR_FACTOR

        return val

    def MQRead(self, mq_pin):
        rs = 0.0

        for i in range(self.READ_SAMPLE_TIMES):
            rs += self.MQResistanceCalculation(self.adc.read(mq_pin))
            time.sleep(self.READ_SAMPLE_INTERVAL / 1000.0)

        rs = rs / self.READ_SAMPLE_TIMES

        return rs

    def MQGetGasPercentage(self, rs_ro_ratio, gas_id):
        if (gas_id == self.GAS_LPG):
            return self.MQGetPercentage(rs_ro_ratio, self.LPGCurve)
        elif (gas_id == self.GAS_CO):
            return self.MQGetPercentage(rs_ro_ratio, self.COCurve)
        elif (gas_id == self.GAS_SMOKE):
            return self.MQGetPercentage(rs_ro_ratio, self.SmokeCurve)
        return 0

    def MQGetPercentage(self, rs_ro_ratio, pcurve):
        return (math.pow(
            10,
            (((math.log(rs_ro_ratio) - pcurve[1]) / pcurve[2]) + pcurve[0])))
Пример #8
0
status = 0

# prepare handlers for process exit
signal.signal(signal.SIGTERM, end_process)
signal.signal(signal.SIGINT, end_process)

# initialize ADC
if (ADC == "MCP3551"):
    adc = MCP3551(SPIMISO, SPIMOSI, SPICLK, SPICS)
elif (ADC == "MCP3001"):
    adc = MCP3001(SPIMISO, SPIMOSI, SPICLK, SPICS)
elif (ADC == "MCP3008"):
    adc = MCP3008(SPIMISO, SPIMOSI, SPICLK, SPICS, ADCCHANNEL)
elif (ADC == "MCP3208"):
    adc = MCP3208(SPIMISO, SPIMOSI, SPICLK, SPICS, ADCCHANNEL)
elif (ADC == "NOADC"):
    adc = NOADC(SPIMISO, SPIMOSI, SPICLK, SPICS, ADCCHANNEL)
else:
    print("Unknown ADC type " + str(ADC) +
          "! Please set ADC in config.py to one of the supported types.")
    exit(0)

adc.setup_pins()

SVOLT100 = VOLT100 * HIGHRESVAL / (LOWRESVAL + HIGHRESVAL)
SVOLT75 = VOLT75 * HIGHRESVAL / (LOWRESVAL + HIGHRESVAL)
SVOLT50 = VOLT50 * HIGHRESVAL / (LOWRESVAL + HIGHRESVAL)
SVOLT25 = VOLT25 * HIGHRESVAL / (LOWRESVAL + HIGHRESVAL)
SVOLT0 = VOLT0 * HIGHRESVAL / (LOWRESVAL + HIGHRESVAL)
Пример #9
0
        tzinfo=pytz.timezone('Europe/Vienna')).isoformat()

    print("Started measurement: {} on host {}".format(filename, host))

    # initialize the GPIOs (General Purpose Input and Output)
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)

    # set the pins as output or input
    GPIO.setup(CLK, GPIO.OUT)
    GPIO.setup(MOSI, GPIO.OUT)
    GPIO.setup(MISO, GPIO.IN)
    GPIO.setup(CS, GPIO.OUT)

    # Init mcp3208 instance
    mcp3208 = MCP3208(clockpin=CLK, mosipin=MOSI, misopin=MISO, cspin=CS)

    hardware_status = check_hardware()
    print(hardware_status)

    c = 0  # Start with zero, because the first msgs should contain all data
    while True:
        starttime = time.time()
        msgs = list()
        # The function measure_voltage will be executed (called) with the argument
        # "channels" which was defined on at the top of the code.
        currents = [measure_current(channel) for channel in channels]

        # Send everything after SEND_IDLE time
        if (c % (SEND_IDLE / SEND_ACTIVE)) == 0:
            c = 1
Пример #10
0
 def __init__(self):
     print(self.read_logo())
     self.adc = MCP3208()
     GPIO.setmode(GPIO.BCM)  # choose BCM or BOARD
     GPIO.setup(self.PUMP_PIN, GPIO.OUT)
Пример #11
0
def sender(buff, n):
    class NumpyEncoder(json.JSONEncoder):
        def default(self, obj):
            if isinstance(obj, np.ndarray):
                return obj.tolist()
            return json.JSONEncoder.default(self, obj)



    adc = MCP3208()

    g_data = " "
    g_cnt = 0
    g_dtime = 0
    g_sr = 0
    g_dt = 0

    g_disk = os.statvfs("/")
    g_first_avail = g_disk.f_bsize * g_disk.f_bavail

    time_now = dt.datetime.now()

    fname = "data"+str(time_now)+".csv"
    f=open(fname, "w")

    mydt = 0
    pdt = 0
    sr = 0
    cnt = 0
    data = ''

    start_time = time.time()

    while True:

        try:

            dtime = time.time()-start_time
            mydt = long(dtime*1000)/10 # 100 seconds
            cdt = int(mydt%100) # 1 second

            #print "cdt: ", cdt, ", pdt: ", pdt

            buff = list()

            if cdt!=pdt: # before receiving a 100th input / if cdt == 6 # cdt == 
                read = adc.read(6)
                cnt = cnt + 1
                sr = cnt/dtime
                data = data + str(read) + " "
                pdt = cdt # pdt will be 6

                buff.append(map(int, data.split()))

                if(cnt%100==0):
                   #print("successfully")
                   # print "cnt", cnt
                    cdt += 1
                    del buff[:]

            if cdt==0:
                f.write(data)
                data = ""
               # print "sr", sr, "dt", str(dt.datetime.now())

            avail = g_disk.f_bsize * g_disk.f_bavail

            if avail < (g_first_avail * 3 / 5) :
                raise KeyboardInterrupt
        except KeyboardInterrupt:
            break

    f.close()
Пример #12
0
 def __init__(self):
     self.adc = MCP3208()
     self.ir = {}
     for key in ['front', 'right', 'back', 'left']:
         self.ir[key] = 0