Skip to content

Instantly share code, notes, and snippets.

@mharsch
Created February 18, 2023 18:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mharsch/52b0a99a945711385fb0120020d8226d to your computer and use it in GitHub Desktop.
Save mharsch/52b0a99a945711385fb0120020d8226d to your computer and use it in GitHub Desktop.
Arduino replaces MT-VIKI KVM remote module for changing / polling selected KVM input
#include <math.h>
// connected to 'D+' pin on mini USB
const int input_pin = 11;
// connected to 'D-' pin on mini USB
const int output_pin = 12;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(input_pin, INPUT);
pinMode(output_pin, OUTPUT);
digitalWrite(output_pin, HIGH);
}
void loop() {
if (Serial.available() > 0) {
int new_port = Serial.parseInt();
if (new_port >= 1 && new_port <=8) {
set_port(new_port);
}
int port = get_port();
Serial.println(port);
}
}
int get_port() {
unsigned long duration;
double ms;
int p;
duration = pulseIn(input_pin, LOW);
ms = round(duration / 1000.0);
p = ((int) ms / 20);
return (p);
}
void set_port(int p) {
digitalWrite(output_pin, LOW);
delay(20);
digitalWrite(output_pin, HIGH);
delay(20);
digitalWrite(output_pin, LOW);
delay(p * 20);
digitalWrite(output_pin, HIGH);
delay(200);
}
@mchill
Copy link

mchill commented Apr 16, 2024

In case anyone wants to do this with the GPIO pins on a Raspberry Pi instead, here's the equivalent Python code.

import RPi.GPIO as GPIO
import sys
import time

input_pin = 23  # connected to 'D+' pin on mini USB
output_pin = 24  # connected to 'D-' pin on mini USB


def setup():
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)
    GPIO.setup(input_pin, GPIO.IN)
    GPIO.setup(output_pin, GPIO.OUT)
    GPIO.output(output_pin, GPIO.HIGH)


def get_port() -> int:
    while GPIO.input(input_pin) == GPIO.LOW:
        time.sleep(0.001)
    while GPIO.input(input_pin) == GPIO.HIGH:
        time.sleep(0.001)
    start = time.time()
    while GPIO.input(input_pin) == GPIO.LOW:
        time.sleep(0.001)
    stop = time.time()
    return round((stop - start) * 50)


def set_port(port: int):
    GPIO.output(output_pin, GPIO.LOW)
    time.sleep(0.02)
    GPIO.output(output_pin, GPIO.HIGH)
    time.sleep(0.02)
    GPIO.output(output_pin, GPIO.LOW)
    time.sleep(0.02 * port)
    GPIO.output(output_pin, GPIO.HIGH)


setup()
set_port(int(sys.argv[1]))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment