Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //If you found my video helpful, please SUBSCRIBE: https://www.youtube.com/channel/UCKp1MzuAceJnDqAvsZl_46g
- //The code belongs to the following tutorial video: https://youtu.be/rQTDD0bpNWE
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.IO.Ports; //use the ports for serial communications (1)
- using System.Threading.Tasks;
- using System.Windows.Forms;
- using System.Threading;
- namespace ArduinoSerialTutorial
- {
- public partial class Form1 : Form
- {
- private SerialPort SerPort; //serial port
- private string ReceivedData; //received data
- public Form1()
- {
- InitializeComponent();
- FetchAvailablePorts(); //run the port-fetching
- }
- void FetchAvailablePorts()
- {
- String[] ports = SerialPort.GetPortNames();//Put the name of the available USB ports into the ports string array
- AvailablePortsBox.Items.AddRange(ports); //Add the string into the dropdown list we made
- }
- private void ConnectToPort_Click(object sender, EventArgs e)
- {
- //This is some predefined thing that you can get from Google
- SerPort = new SerialPort();
- SerPort.BaudRate = 9600;
- SerPort.PortName = AvailablePortsBox.Text;
- SerPort.Parity = Parity.None;
- SerPort.DataBits = 8;
- SerPort.StopBits = StopBits.One;
- SerPort.ReadBufferSize = 20000000;
- SerPort.DataReceived += SerPort_DataReceived;
- try
- {
- SerPort.Open(); //We open the port
- Thread.Sleep(1000); //We wait a sec
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message, "Error!");
- }
- }
- private void SerPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
- {
- ReceivedData = SerPort.ReadLine(); //We read the serial port
- this.Invoke(new Action(ProcessingData)); //execute the delegate (ProcessingData)
- }
- private void SendSerialButton_Click(object sender, EventArgs e)
- {
- SerPort.WriteLine(SenderTextBox.Text.ToString()); //send the content of the textbox to the serial port
- }
- private void ProcessingData()
- {
- ReceivedDataBox.Text += ReceivedData.ToString() + Environment.NewLine;
- //We put the received data in the textbox and add a linebreak
- }
- private void Form1_FormClosing(object sender, FormClosingEventArgs e)
- {
- try
- {
- SerPort.Close(); //close the port on from closing
- }
- catch
- {
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement