シリアルポートからデータを読みたいのですが、やり方がわかりません。
私はArduinoを使用しているので、ここに私のコードがあります:
int switchPin = 7;
int ledPin = 13;
boolean lastButton = LOW;
boolean currentButton = LOW;
boolean flashLight = LOW;
void setup()
{
pinMode(switchPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
boolean debounce(boolean last)
{
boolean current = digitalRead(switchPin);
if (last != current)
{
delay(5);
current = digitalRead(switchPin);
}
return current;
}
void loop()
{
currentButton = debounce(lastButton);
if (lastButton == LOW && currentButton == HIGH)
{
Serial.println("UP");
digitalWrite(ledPin, HIGH);
}
if (lastButton == HIGH && currentButton == LOW)
{
Serial.println("DOWN");
digitalWrite(ledPin, LOW);
}
lastButton = currentButton;
}
ご覧のとおり、すべてが単純です。ボタンを押すと、デバイスは「DOWN」または「UP」をシリアル ポートに送信します。私のWPFアプリケーションから受け取りたいです。コードは次のとおりです。
namespace Morse_Device_Stuff
{
{
public MainWindow()
{
InitializeComponent();
}
private SerialPort port;
private bool recordStarted = false;
private void recordButton_Click(object sender, RoutedEventArgs e)
{
SerialPort port = new SerialPort("COM3", 9600);
port.Open();
recordStarted = !recordStarted;
string lane;
if(recordStarted)
{
(recordButton.Content as Image).Source = new BitmapImage(new Uri("stop.png", UriKind.Relative));
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
}
else
{
(recordButton.Content as Image).Source = new BitmapImage(new Uri("play.png", UriKind.Relative));
}
port.Close();
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
textBox.Text += port.ReadExisting();
}
}
}
ボタンを押しても何も変わらず、TextBox はまだ空です。
何が問題なのですか?