from machine import Pin, ADC
import time
import usb_midi
from adafruit_midi import MIDI
from adafruit_midi.note_on import NoteOn
from adafruit_midi.note_off import NoteOff
from adafruit_midi.control_change import ControlChange

# Setup für MIDI
midi = MIDI(midi_out=usb_midi.ports[1], out_channel=0)

# Taster
button_pins = [15, 16, 17]
buttons = [Pin(pin, Pin.IN, Pin.PULL_UP) for pin in button_pins]
button_states = [1, 1, 1]  # 1 = nicht gedrückt, 0 = gedrückt

# Multiplexer
s0 = Pin(2, Pin.OUT)
s1 = Pin(3, Pin.OUT)
s2 = Pin(4, Pin.OUT)
s3 = Pin(5, Pin.OUT)
sig = ADC(Pin(26))

# Potentiometer-Werte für das Senden von ControlChange
last_pot_values = [0, 0, 0, 0]

# Funktion, um den Multiplexer-Kanal auszuwählen
def select_channel(channel):
    s0.value(channel & 1)
    s1.value((channel >> 1) & 1)
    s2.value((channel >> 2) & 1)
    s3.value((channel >> 3) & 1)

# MIDI CC-Nachrichten für Potentiometer senden
def send_pot_midi(channel, value):
    midi_value = value >> 9  # Umrechnung auf Wertebereich 0-127
    midi.send(ControlChange(channel + 20, midi_value))  # CC-Nummer 20+ für Potis

# Hauptloop
while True:
    # Taster abfragen
    for i, button in enumerate(buttons):
        state = button.value()
        if state != button_states[i]:  # Zustandsänderung
            if state == 0:  # Taster gedrückt
                midi.send(NoteOn(60 + i, 127))  # NoteOn Nachricht
            else:  # Taster losgelassen
                midi.send(NoteOff(60 + i, 0))  # NoteOff Nachricht
            button_states[i] = state

    # Potentiometer-Werte vom Multiplexer lesen und MIDI CC senden
    for channel in range(4):  # 4 Potentiometer
        select_channel(channel)
        pot_value = sig.read_u16()  # Wert des Potentiometers lesen (0 - 65535)
        if abs(pot_value - last_pot_values[channel]) > 512:  # Änderungsschwelle
            send_pot_midi(channel, pot_value)
            last_pot_values[channel] = pot_value
    
    time.sleep(0.01)
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT
pico:GP0
pico:GP1
pico:GND.1
pico:GP2
pico:GP3
pico:GP4
pico:GP5
pico:GND.2
pico:GP6
pico:GP7
pico:GP8
pico:GP9
pico:GND.3
pico:GP10
pico:GP11
pico:GP12
pico:GP13
pico:GND.4
pico:GP14
pico:GP15
pico:GP16
pico:GP17
pico:GND.5
pico:GP18
pico:GP19
pico:GP20
pico:GP21
pico:GND.6
pico:GP22
pico:RUN
pico:GP26
pico:GP27
pico:GND.7
pico:GP28
pico:ADC_VREF
pico:3V3
pico:3V3_EN
pico:GND.8
pico:VSYS
pico:VBUS
mux1:I15
mux1:I14
mux1:I13
mux1:I12
mux1:I11
mux1:I10
mux1:I9
mux1:I8
mux1:I7
mux1:I6
mux1:I5
mux1:I4
mux1:I3
mux1:I2
mux1:I1
mux1:I0
mux1:COM
mux1:S3
mux1:S2
mux1:S1
mux1:S0
mux1:EN
mux1:VCC
mux1:GND
btn1:1.l
btn1:2.l
btn1:1.r
btn1:2.r
btn2:1.l
btn2:2.l
btn2:1.r
btn2:2.r
btn3:1.l
btn3:2.l
btn3:1.r
btn3:2.r
pot1:GND
pot1:SIG
pot1:VCC
pot2:GND
pot2:SIG
pot2:VCC
pot3:GND
pot3:SIG
pot3:VCC
pot4:GND
pot4:SIG
pot4:VCC