# cPy - RPi libgpiod tests
# Copyright by Anthony Vogelaar, Perth Scotland
# rev 0.10  2024-12-12  initial release

import	time
import	gpiod
from	gpiod.line	import	Direction, Value, Bias

# ============================= tests =================================

# connect led between Pin-6 GND and Pin-8 GPIO-14

# print input level of GPIO-14 - button test
def test1():
    line_nr = 14
    setting = gpiod.LineSettings(direction=Direction.INPUT, bias=Bias.PULL_UP)
    config  = {line_nr: setting}
    with gpiod.request_lines('/dev/gpiochip0', consumer='test', config=config) as request:
        while True:
            time.sleep(0.5)
            level = request.get_value(line_nr)
            print(bool(level))


# toggle led on line 14 with 1 Hz
def test2():
    line_nr = 14
    setting = gpiod.LineSettings(direction=Direction.OUTPUT, output_value=Value.INACTIVE)
    config  = {line_nr: setting}
    with gpiod.request_lines('/dev/gpiochip0', consumer='test', config=config) as request:
        while True:
            time.sleep(0.5)
            request.set_value(line_nr, Value.INACTIVE)
            time.sleep(0.5)
            request.set_value(line_nr, Value.ACTIVE)


# toggle line 14 on max frequency. pulse 7.3 uSec, occasionally one missing
def test3():
    line_nr = 14
    setting = gpiod.LineSettings(direction=Direction.OUTPUT, output_value=Value.INACTIVE)
    config  = {line_nr: setting}
    with gpiod.request_lines('/dev/gpiochip0', consumer='test', config=config) as request:
        t1 = time.time()
        for i in range(100000):
            request.set_value(line_nr, Value.INACTIVE)
            request.set_value(line_nr, Value.ACTIVE)
        t2 = time.time()
        print(f'100_000 pulses in {(t2-t1):.2f} sec')
        print(f'pulse width is {5*(t2-t1):.2f} uSec')

# ============================= main ===================================

try:
    test1()
except KeyboardInterrupt:
    print('terminated by Ctrl-C')
    
# =============================== end ==================================
