Hi everybody,
I’m using an ultrasonic sensor with a midi jack to play sound. I want to use my serial port to change the sound its playing. I’d like to be able to send a ‘1’ or a ‘2’ through my serial port to change the type of pitch my midi will produce based off the reading of the ultrasonic sensor. I know I had to setup a different serial port for the receiving and transmitting pins for my midi jack. I’m sending a “1” or “2” value through the serial port using a different c++ code in visual studio. I know the C++ code works over the serial communication, I can use it for other things, I think the fault lies in how I’m structuring this code… And I know everything else works fine, I can run the code and my midi does produce sound when I’m not trying to use the serial.available to input a “1” or “2”.
What I’d like to see my code do is… When I send a “1” or a “2” through the serial port, I want the code to change to what I have designated in the code. I want my pitch to change based off my ultrasonic sensor in real time, while I’m punching in the numbers on the keyboard.
Here is the site that influenced this code, if it helps. http://multiwingspan.co.uk/arduino.php?page=midi3
Any help is appreciated! thanks!
#include <SoftwareSerial.h>
#define ECHOPIN 2
#define TRIGPIN 3
SoftwareSerial Serial1(2, 1); // RX, TX
int lastnote=0;
char input = '0';
void setup()
{
pinMode(ECHOPIN, INPUT);
pinMode(TRIGPIN, OUTPUT);
Serial1.begin(31250);
programChange(0xc0, 0x36);
delay(1000);
Serial.begin(9600);
}
void loop()
{
if(Serial.available())
{
input = Serial.read();
}
if (input=='1')
{
digitalWrite(TRIGPIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGPIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGPIN, LOW);
int distance = pulseIn(ECHOPIN, HIGH);
distance= distance/58;
distance = constrain(distance,10,100);
distance = map(distance,10,100,75,45);
if (distance!=lastnote)
{
noteOn(0x90, lastnote, 0x00); //Note on channel 1 (0x90), some note value (note), silent velocity (0x00)
noteOn(0x90, distance, 0x45); //Note on channel 1 (0x90), some note value (note), middle velocity (0x45)
lastnote = distance;
}
delay(10);
}
if (input=='2')
{
digitalWrite(TRIGPIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGPIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGPIN, LOW);
int distance = pulseIn(ECHOPIN, HIGH);
distance= distance/58;
distance = constrain(distance,10,100);
distance = map(distance,10,100,50,30);
if (distance!=lastnote)
{
noteOn(0x90, lastnote, 0x00); //Note on channel 1 (0x90), some note value (note), silent velocity (0x00)
noteOn(0x90, distance, 0x45); //Note on channel 1 (0x90), some note value (note), middle velocity (0x45)
lastnote = distance;
}
delay(10);
}
}
void noteOn(int cmd, int pitch, int velocity)
{
Serial1.write(cmd);
Serial1.write(pitch);
Serial1.write(velocity);
}
void programChange(int cmd, int data1) {
Serial1.write(cmd);
Serial1.write(data1);
}