So this is what I ended up with if anybody needs this in the future. I have a windows form, this is the code in the constructor to fill a combo box with a list of ports.
string[] portlist = SerialPort.GetPortNames();
foreach (String s in portlist)
{
portComboBox.Items.Add(s);
}
and then I have the below function that gets called when you press the connect button:
private void connectButton_Click(object sender, EventArgs e)
{
if (port != null)
{
port.Close();
port.Dispose();
}
port = new SerialPort(portComboBox.SelectedItem.ToString(), 9600, Parity.None, 8, StopBits.One);
port.Open();
}
and finally when you press a key the following happens:
port.Write(e.KeyCode.ToString());
and the arduno code to controll two motors using an h-bridge is as follows:
int motor1Pin = 3; // H-bridge leg 1
int motor2Pin = 2; // H-bridge leg 2
int motor3Pin = 4; // H-bridge leg 3
int motor4Pin = 5; // H-bridge leg 4
void setup() {
// set all the other pins you're using as outputs:
pinMode(motor1Pin, OUTPUT);
pinMode(motor2Pin, OUTPUT);
pinMode(motor3Pin, OUTPUT);
pinMode(motor4Pin, OUTPUT);
//set the inital motor states to stopped
digitalWrite(motor1Pin, HIGH);
digitalWrite(motor2Pin, HIGH);
digitalWrite(motor3Pin, HIGH);
digitalWrite(motor4Pin, HIGH);
//the serial connection allows you to read commands sent through usb (from my windows form in my case)
Serial.begin(9600);
}
void loop() {
if (Serial.available())
{
int c = Serial.read();
switch (c)
{
case 'Q': //for some reason lower case characters get converted to uppdercase characters at some point in time
digitalWrite(motor1Pin, HIGH); //rotate forward
digitalWrite(motor2Pin, LOW);
break;
case 'A':
digitalWrite(motor1Pin, HIGH); //stop
digitalWrite(motor2Pin, HIGH);
break;
case 'Z':
digitalWrite(motor1Pin, LOW); //rotate backwards
digitalWrite(motor2Pin, HIGH);
break;
case 'W':
digitalWrite(motor3Pin, HIGH); //rotate forwards
digitalWrite(motor4Pin, LOW);
break;
case 'S':
digitalWrite(motor3Pin, HIGH); //stop
digitalWrite(motor4Pin, HIGH);
break;
case 'X':
digitalWrite(motor3Pin, LOW); //rotate backwards
digitalWrite(motor4Pin, HIGH);
break;
}
}
}