Remove "Hat Name = 'Grove Base Hat RPi'" from python

Hello i have been trying to edit some of the example code for a few sensors:



<LINK_TEXT text=“https://github.com/Seeed-Studio/grove.p … _sensor.py”>https://github.com/Seeed-Studio/grove.py/blob/master/grove/grove_temperature_humidity_sensor.py</LINK_TEXT>
[code]#!/usr/bin/env python

This code is for

Grove - Temperature & Humidity Sensor (DHT11)

(https://www.seeedstudio.com/Grove-Temperature-Humidity-Sensor-DHT1-p-745.html)

Grove - Temperature & Humidity Sensor Pro (AM2302)

(https://www.seeedstudio.com/Grove-Temperature-Humidity-Sensor-Pro-AM230-p-838.html)

which is consists of a capacitive sensor element used for measuring relative humidity

and a negative temperature coefficient(NTC) thermistor used for measuring temperature.

This is the library for Grove Base Hat which used to connect grove sensors for raspberry pi.

‘’’
‘’’
import RPi.GPIO as GPIO

from grove.helper import *

def set_max_priority(): pass
def set_default_priority(): pass
from time import sleep

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

PULSES_CNT = 41

class DHT(object):
DHT_TYPE = {
‘DHT11’: ‘11’,
‘DHT22’: ‘22’
}

MAX_CNT = 320

def __init__(self, dht_type, pin):        
    self.pin = pin
    if dht_type != self.DHT_TYPE['DHT11'] and dht_type != self.DHT_TYPE['DHT22']:
        print('ERROR: Please use 11|22 as dht type.')
        exit(1)
    self.dht_type = dht_type
    GPIO.setup(self.pin, GPIO.OUT)
    self._last_temp = 0.0
    self._last_humi = 0.0

@property
def dht_type(self):
    return self._dht_type

@dht_type.setter
def dht_type(self, type):
    self._dht_type = type

def _read(self):
    # Send Falling signal to trigger sensor output data
    # Wait for 20ms to collect 42 bytes data
    GPIO.setup(self.pin, GPIO.OUT)
    set_max_priority()

    GPIO.output(self.pin, 1)
    sleep(.2)

    GPIO.output(self.pin, 0)
    sleep(.018)

    GPIO.setup(self.pin, GPIO.IN)
    # a short delay needed
    for i in range(10):
        pass

    # pullup by host 20-40 us
    count = 0
    while GPIO.input(self.pin):
        count += 1
        if count > self.MAX_CNT:
            # print("pullup by host 20-40us failed")
            set_default_priority()
            return None, "pullup by host 20-40us failed"

    pulse_cnt = [0] * (2 * PULSES_CNT)
    fix_crc = False
    for i in range(0, PULSES_CNT * 2, 2):
        while not GPIO.input(self.pin):
            pulse_cnt[i] += 1
            if pulse_cnt[i] > self.MAX_CNT:
                # print("pulldown by DHT timeout %d" % i)
                set_default_priority()
                return None, "pulldown by DHT timeout %d" % i

        while GPIO.input(self.pin):
            pulse_cnt[i + 1] += 1
            if pulse_cnt[i + 1] > self.MAX_CNT:
                # print("pullup by DHT timeout %d" % (i + 1))
                if i == (PULSES_CNT - 1) * 2:
                    # fix_crc = True
                    # break
                    pass
                set_default_priority()
                return None, "pullup by DHT timeout %d" % i

    # back to normal priority
    set_default_priority()

    total_cnt = 0
    for i in range(2, 2 * PULSES_CNT, 2):
        total_cnt += pulse_cnt[i]

    # Low level ( 50 us) average counter
    average_cnt = total_cnt / (PULSES_CNT - 1)
    # print("low level average loop = %d" % average_cnt)
   
    data = ''
    for i in range(3, 2 * PULSES_CNT, 2):
        if pulse_cnt[i] > average_cnt:
            data += '1'
        else:
            data += '0'
    
    data0 = int(data[ 0: 8], 2)
    data1 = int(data[ 8:16], 2)
    data2 = int(data[16:24], 2)
    data3 = int(data[24:32], 2)
    data4 = int(data[32:40], 2)

    if fix_crc and data4 != ((data0 + data1 + data2 + data3) & 0xFF):
        data4 = data4 ^ 0x01
        data = data[0: PULSES_CNT - 2] + ('1' if data4 & 0x01 else '0')

    if data4 == ((data0 + data1 + data2 + data3) & 0xFF):
        if self._dht_type == self.DHT_TYPE['DHT11']:
            humi = int(data0)
            temp = int(data2)
        elif self._dht_type == self.DHT_TYPE['DHT22']:
            humi = float(int(data[ 0:16], 2)*0.1)
            temp = float(int(data[17:32], 2)*0.2*(0.5-int(data[16], 2)))
    else:
        # print("checksum error!")
        return None, "checksum error!"

    return humi, temp

def read(self, retries = 15):
    for i in range(retries):
        humi, temp = self._read()
        if not humi is None:
            break
    if humi is None:
        return self._last_humi, self._last_temp
    self._last_humi,self._last_temp = humi, temp
    return humi, temp

Grove = DHT

def main():
from grove.helper import SlotHelper
sh = SlotHelper(SlotHelper.GPIO)
pin = sh.argv2pin(" [dht_type]")

import sys
typ = '11'
if len(sys.argv) >= 3:
    typ = sys.argv[2]

import time
sensor = DHT(typ, pin)

while True:
    humi, temp = sensor.read()
    if not humi is None:
        print('DHT{0}, humidity {1:.1f}%, temperature {2:.1f}*'.format(sensor.dht_type, humi, temp))
    else:
        print('DHT{0}, humidity & temperature: {1}'.format(sensor.dht_type, temp))
    time.sleep(1)

if name == ‘main’:
main()
[/code]

<LINK_TEXT text=“https://github.com/Seeed-Studio/grove.p … or_v1_2.py”>https://github.com/Seeed-Studio/grove.py/blob/master/grove/grove_light_sensor_v1_2.py</LINK_TEXT>
[code]#!/usr/bin/env python

-- coding: utf-8 --

The MIT License (MIT)

Grove Base Hat for the Raspberry Pi, used to connect grove sensors.

Copyright © 2018 Seeed Technology Co.,Ltd.

‘’’
This is the code for
- Grove - Light Sensor <https://www.seeedstudio.com/Grove-Light-Sensor-v1.2-p-2727.html>_
Examples:
… code-block:: python
import time
from grove.grove_light_sensor import GroveLightSensor
# connect to alalog pin 2(slot A2)
PIN = 2
sensor = GroveLightSensor(pin)
print(‘Detecting light…’)
while True:
print(‘Light value: {0}’.format(sensor.light))
time.sleep(1)
‘’’
import time, sys, math
from grove.adc import ADC

all = [“GroveLightSensor”]

class GroveLightSensor(object):
‘’’
Grove Light Sensor class
Args:
pin(int): number of analog pin/channel the sensor connected.
‘’’
def init(self, channel):
self.channel = channel
self.adc = ADC()

@property
def light(self):
    '''
    Get the light strength value, maximum value is 100.0%
    Returns:
        (int): ratio, 0(0.0%) - 1000(100.0%)
    '''
    value = self.adc.read(self.channel)
    return value

Grove = GroveLightSensor

def main():
from grove.helper import SlotHelper
sh = SlotHelper(SlotHelper.ADC)
pin = sh.argv2pin()

sensor = GroveLightSensor(pin)

print('Detecting light...')
while True:
    print('Light value: {0}'.format(sensor.light))
    time.sleep(1)

if name == ‘main’:
main()
[/code]

It works and i get a value, but it says “Hat Name = ‘Grove Base Hat RPi’” everytime i run the file, i would really like to remove this and have it only return a number.

Iv looked through the code for both of those files and cant seem to figure out how to get rid of it, i think its getting that from another file:



<LINK_TEXT text=“https://github.com/Seeed-Studio/grove.p … ove/adc.py”>https://github.com/Seeed-Studio/grove.py/blob/master/grove/adc.py</LINK_TEXT>
[code]#!/usr/bin/env python

-- coding: utf-8 --

The MIT License (MIT)

Copyright © 2018 Seeed Technology Co.,Ltd.

This is the ADC library for Grove Base Hat

which used to connect grove sensors for raspberry pi.

‘’’
This is the code for
- Grove Base Hat for RPi <https://www.seeedstudio.com/Grove-WS2813-RGB-LED-Strip-Waterproof-60-LED-m-1m-p-3126.html>_
- Grove Base Hat for RPi Zero <https://www.seeedstudio.com/Grove-Base-Hat-for-Raspberry-Pi-Zero-p-3187.html>_
Grove Base Hat incorparates a micro controller STM32F030F4.
Raspberry Pi does not have ADC unit, so we use an external chip
to transmit analog data to raspberry pi.
Examples:
… code-block:: python
import time
from grove.adc import ADC
adc = ADC()
while True:
# Read channel 0(Slot A0) voltage
print(adc.read_voltage(0))
time.sleep(1)
‘’’
import sys
import grove.i2c

all = [
“ADC”,
“RPI_HAT_NAME”, “RPI_ZERO_HAT_NAME”,
“RPI_HAT_PID”, “RPI_ZERO_HAT_PID”
]

RPI_HAT_PID = 0x0004
RPI_ZERO_HAT_PID = 0x0005
RPI_HAT_NAME = ‘Grove Base Hat RPi’
“”" The HAT name to compare with return value of :class:ADC.name “”"
RPI_ZERO_HAT_NAME= ‘Grove Base Hat RPi Zero’
“”" The HAT name to compare with return value of :class:ADC.name “”"

class ADC(object):
‘’’
Class ADC for the ADC unit on Grove Base Hat for RPi.
Args:
address(int): optional, i2c address of the ADC unit, default 0x04
‘’’
def init(self, address = 0x04):
self.address = address
self.bus = grove.i2c.Bus()

def read_raw(self, channel):
    '''
    Read the raw data of ADC unit, with 12 bits resolution.
    Args:
        channel (int): 0 - 7, specify the channel to read
    Returns:
        (int): the adc result, in [0 - 4095]
    '''
    addr = 0x10 + channel
    return self.read_register(addr)

# read input voltage (mV)
def read_voltage(self, channel):
    '''
    Read the voltage data of ADC unit.
    Args:
        channel (int): 0 - 7, specify the channel to read
    Returns:
        (int): the voltage result, in mV
    '''
    addr = 0x20 + channel
    return self.read_register(addr)

# input voltage / output voltage (%)
def read(self, channel):
    '''
    Read the ratio between channel input voltage and power voltage (most time it's 3.3V).
    Args:
        channel (int): 0 - 7, specify the channel to read
    Returns:
        (int): the ratio, in 0.1%
    '''
    addr = 0x30 + channel
    return self.read_register(addr)

@property
def name(self):
    '''
    Get the Hat name.
    Returns:
        (string): could be :class:`RPI_HAT_NAME` or :class:`RPI_ZERO_HAT_NAME`
    '''
    id = self.read_register(0x0)
    if id == RPI_HAT_PID:
        return RPI_HAT_NAME
    elif id == RPI_ZERO_HAT_PID:
        return RPI_ZERO_HAT_NAME

@property
def version(self):
    '''
    Get the Hat firmware version.
    Returns:
        (int): firmware version
    '''
    return self.read_register(0x3)

# read 16 bits register
def read_register(self, n):
    '''
    Read the ADC Core (through I2C) registers
    Grove Base Hat for RPI I2C Registers
        - 0x00 ~ 0x01: 
        - 0x10 ~ 0x17: ADC raw data
        - 0x20 ~ 0x27: input voltage
        - 0x29: output voltage (Grove power supply voltage)
        - 0x30 ~ 0x37: input voltage / output voltage
    Args:
        n(int): register address.
    Returns:
        (int) : 16-bit register value.
    '''
    try:
        self.bus.write_byte(self.address, n)
        return self.bus.read_word_data(self.address, n)
    except IOError:
        print("Check whether I2C enabled and   {}  or  {}  inserted".format \
                (RPI_HAT_NAME, RPI_ZERO_HAT_NAME))
        sys.exit(2)
        return 0

if name == ‘main’:
import time

adc = ADC()
while True:
    print(adc.read_voltage(0))
    time.sleep(1)<e>[/code]</e></CODE>

If anyone has any idea how i can get rid of it i would really appreciate the help. Thankyou!

Hi there,


  1. please comment out helper/helper.py as below.



    pi@raspberrypi:~/grove.py/grove $ vim helper/helper.py

[code] def init(self, slot = GPIO):
adc = ADC()
self.name = adc.name
#print(“Hat Name = ‘{}’”.format(self.name))

self.plat = self.get_platform()

    if self.name == RPI_ZERO_HAT_NAME:
        self.__hat_type = RPI_ZERO_HAT_PID
        self.__slots_gpio = _SlotsGPIORpiZero
        self.__slots_adc  = _SlotsADCRpiZero
        self.__slots_pwm  = _SlotsPWMRpiZero
    else:

#if self.name != RPI_HAT_NAME:
#print(“Unknown hat, assume {}”.format(RPI_HAT_NAME))

self.__hat_type = RPI_HAT_PID
self.__slots_gpio = _SlotsGPIORpi
self.__slots_adc = _SlotsADCRpi
[/code]

  1. run the sudo pip install . --upgrade to update the library. thanks.

</s>pi@raspberrypi:~/grove.py/grove $ cd .. pi@raspberrypi:~/grove.py $ [b]sudo pip install . --upgrade[/b] Processing /home/pi/grove.py Requirement already up-to-date: RPi.GPIO in /usr/lib/python2.7/dist-packages (from grove.py==0.6) Requirement already up-to-date: rpi_ws281x in /usr/local/lib/python2.7/dist-packages (from grove.py==0.6) Requirement already up-to-date: smbus2 in /usr/local/lib/python2.7/dist-packages (from grove.py==0.6) Installing collected packages: grove.py Found existing installation: grove.py 0.6 Uninstalling grove.py-0.6: Successfully uninstalled grove.py-0.6 Running setup.py install for grove.py ... done Successfully installed grove.py-0.6<e>