Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public partial class MainWindow : Window
- {
- SerialPort mainport = new SerialPort();
- public MainWindow()
- {
- InitializeComponent();
- }
- private void Button_Click(object sender, RoutedEventArgs e)
- {
- if (!mainport.IsOpen)
- {
- try
- {
- mainport.PortName = COMPortList.SelectedItem.ToString();
- mainport.BaudRate = 115200;
- mainport.DataBits = 8;
- mainport.StopBits = StopBits.One;
- mainport.Parity = Parity.None;
- }
- catch (Exception owo) { MessageBox.Show(owo.Message); }
- try
- {
- //Connect
- mainport.Open();
- ((Button)e.Source).Content = "Disconnect";
- StartReceivingData();
- }
- catch (Exception owo) { MessageBox.Show(owo.Message); }
- }
- else
- {
- try
- {
- Task.WhenAll(tasks);
- mainport.Close();
- ((Button)e.Source).Content = "Connect";
- }
- catch (Exception owo) { MessageBox.Show(owo.Message); }
- }
- }
- private List<Task> tasks = new List<Task>();
- private void StartReceivingData()
- {
- tasks.Add(startListening());
- }
- private async Task startListening()
- {
- try
- {
- await Task.Factory.StartNew(() =>
- {
- while (mainport.IsOpen)
- {
- try
- {
- string message = mainport.ReadLine();
- Application.Current.Dispatcher.BeginInvoke(new Action(() => { Voltage.Content = message; }));
- }
- catch (TimeoutException)
- {
- //There will be a timeout/Operation timed out exception going mental here so nothing is really needed here...
- }
- catch (IOException owo) { MessageBox.Show(owo.Message); }
- catch (Exception owo) { MessageBox.Show(owo.Message); }
- }
- });
- }
- catch { }
- }
- private void Window_Loaded(object sender, RoutedEventArgs e)
- {
- foreach(string comPort in SerialPort.GetPortNames())
- {
- COMPortList.Items.Add(comPort);
- }
- }
- }
RAW Paste Data