问题
I am now for Arduino, I want try to open switch on/off a led using C# with Arduino. So I try using serial port, and it works, but I want to use an Ethernet shield to switch on/off the led. My code using serial port This Arduino code
#define BaudRate 9600
#define LEDPin 10
char incomingOption;
void setup()
{
pinMode(LEDPin, OUTPUT);
// serial communication
Serial.begin(BaudRate);
}
void loop()
{
//read from serial port getting information from VS 2013
incomingOption = Serial.read();
//verify incomingOption
switch(incomingOption){
case '1':
// Turn ON LED
digitalWrite(LEDPin, HIGH);
break;
case '0':
// Turn OFF LED
digitalWrite(LEDPin, LOW);
break;
}
}
and for C#, I have 3 simple button (on, off, and close the serial port)
public partial class frmTurnONTurnOFFLED : Form
{
public frmTurnONTurnOFFLED()
{
InitializeComponent();
}
private void btnTurnON_Click(object sender, EventArgs e)
{
try
{
serialPort1.Write("1"); //send 1 to Arduino
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnTurnOFF_Click(object sender, EventArgs e)
{
try
{
serialPort1.Write("0"); //send 0 to Arduino
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void frmTurnONTurnOFFLED_Load(object sender, EventArgs e)
{
serialPort1.Open(); //open serialPort
}
private void btnClosePort_Click(object sender, EventArgs e)
{
serialPort1.Close(); //close serialPort
}
}
So where can I modify my code? using socket? using TCP pr UDP?
回答1:
Can you try set port name before open?
serialPort1.PortName = "COM3" // your ardunio port (you can see on device manager)
serialPort1.Open();
来源:https://stackoverflow.com/questions/36746747/arduino-led-on-off-tcp-c-sharp