//--------------------------------------------------
#define BttDelayTime 100
#define USBPins 2
#define BTNPin 12
#define USBPin0 2
#define USBPin1 3
#define USBPin2 4
//--------------------------------------------------
struct USBComm{
int pin;
bool enabled;
} USB[USBPins];
String RxData;
int State, LastState;
int BttState, BttLastState;
long BttDelay;
//--------------------------------------------------
void SetupPin( int id, int pin ) {
digitalWrite( pin, LOW );
pinMode( pin, OUTPUT );
USB[id].pin = pin;
USB[id].enabled = false;
}
//--------------------------------------------------
void Chanell_Off() {
for ( int i=0; i<USBPins; i++ ){
USB[i].enabled = false;
digitalWrite( USB[i].pin, USB[i].enabled );
}
}
//--------------------------------------------------
void Chanell_On( int id ) {
id--;
USB[id].enabled = true;
digitalWrite( USB[id].pin, USB[id].enabled );
}
//--------------------------------------------------
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("Start USB Commutator system");
pinMode( BTNPin, INPUT_PULLUP );
SetupPin( 0, USBPin0 );
SetupPin( 1, USBPin1 );
State = 0;
LastState = 0;
Chanell_Off();
}
//--------------------------------------------------
void loop() {
if (Serial.available() ) {
RxData = Serial.readStringUntil('\n');
if ( RxData == "0" ){ State = 0; Serial.println("Channels off"); }
if ( RxData == "1" ){ State = 1; Serial.println("Channel #01"); }
if ( RxData == "2" ){ State = 2; Serial.println("Channel #02"); }
}
BttState = digitalRead( BTNPin );
if ( BttState != BttLastState ){
BttLastState = BttState;
if ( millis()-BttDelay > BttDelayTime){
BttDelay = millis();
if ( BttState == LOW ){
State++;
if ( State > USBPins ){ State=0; }
}
}
}
if ( State != LastState ){
LastState = State;
Chanell_Off();
if ( State > 0 ){ Chanell_On( State ); }
}
}