Skip to content

Instantly share code, notes, and snippets.

@juniorxsound
Created December 14, 2016 20:17
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save juniorxsound/a322d773a14d4862872020ffc67ae64f to your computer and use it in GitHub Desktop.
//Serial = Mega to computer communication via USB port
//Serial2 = Arduino uno (second module) to Mega via pins 16/17
int pot1;
int pot2;
int currentPot1, lastPot1;
int currentPot2, lastPot2;
void setup() {
//Function for handeling serial begins for all ports on the mega ("all/mega/uno", baud rate)
beginSerials("all", 9600);
}
void loop() {
//Mega to USB
if (Serial.available()){
//Read Potentiometer values
readPots();
//Send the data of the pots to cSound
sendSerial(10);
//Match the current and last states for the knobs
matchStates();
} else {
communicationUtil("csound");
}
}
//Mangaging serial begins
void beginSerials(String which, int baud){
if ( which == "all" ){
//Mega to computer
Serial.begin(baud);
//Uno to Mega
Serial2.begin(baud);
} else if ( which == "mega" ){
Serial.begin(baud);
} else if ( which == "uno"){
Serial2.begin(baud);
}
}
void communicationUtil(String msg){
if( msg == "csound" ){
Serial.write("p");
delay(500);
} else if( msg == "uno" ){
Serial2.write("p");
delay(500);
}
}
void readPots(){
pot1 = analogRead(A0);
pot2 = analogRead(A7);
//Map values
currentPot1 = map(pot1, 0, 1023, 1, 100);
currentPot2 = map(pot2, 0, 1023, 101, 151);
}
void matchStates(){
lastPot1 = currentPot1;
lastPot2 = currentPot2;
}
void sendSerial(int interval){
if(currentPot1 != lastPot1){
Serial.write(currentPot1);
}
if(currentPot2 != lastPot2){
Serial.write(currentPot2);
}
//Read the uno Module and send it over serial to csound
byte fromUno = Serial2.read();
if(fromUno != 255){
Serial.write(fromUno);
}
delay(interval);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment