Haoming Weng
Published © GPL3+

Communcation: PC⇌Arduino

Tutorial on communicating from the Arduino to the PC CPU and communicating from PC CPU to Arduino.

BeginnerFull instructions provided1 hour8,976
Communcation: PC⇌Arduino

Things used in this project

Story

Read more

Code

LattePanda—>Arduino

Arduino
Communicate From the LattePanda CPU to the Arduino. (Arduino Sketch)
const int LedPin = 13;  
int ledState = 0;  
   
void setup()  
{   
  pinMode(LedPin, OUTPUT);  
     
  Serial.begin(9600);    
}  
   
void loop()  
{   
    char receiveVal;     
      
    if(Serial.available() > 0)  
    {          
        receiveVal = Serial.read();  
           
       if(receiveVal == '1')      
          ledState = 1;     
       else  
          ledState = 0;       
    }     
         
    digitalWrite(LedPin, ledState);   
         
    delay(5000);      
}

LattePanda—>Arduino

C#
Communicate From the LattePanda CPU to the Arduino. (C# Sketch,WinformsApp)
using System;
using System.Windows.Forms;
using System.IO.Ports;
namespace lightcontrol
{
    public partial class Form1 : Form
    {
        SerialPort port;
        public Form1()
        {
            InitializeComponent();Q
            this.FormClosed += new FormClosedEventHandler(Form1_FormClosed);
            if (port==null)
            {
                port = new SerialPort("COM7", 9600);//Set your board COM
                port.Open();
            }
        }
        void Form1_FormClosed(object sender,FormClosedEventArgs e)
        {
            if(port !=null &&port.IsOpen)
            {
                port.Close();
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            PortWrite("1");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            PortWrite("0");
        }
        private void PortWrite(string message)
        {
            port.Write(message);
        }
    }
}

Arduino—>LattePanda

Arduino
Communicate from the Arduino to the LattePanda CPU. (Arduino Sketch)
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
Serial.print('1');
delay(200);
}

Arduino—>LattePanda

C#
Communicate from the Arduino to the LattePanda CPU. (C# Sketch)
using System;
using System.IO.Ports;
using System.Threading;
namespace ConsoleApp1
{
    class Program
    {
        static SerialPort _serialPort;
        public static void Main()
        {
            _serialPort = new SerialPort();
            _serialPort.PortName = "COM4";//Set your board COM
            _serialPort.BaudRate = 9600;
            _serialPort.Open();
            while (true)
            {
                string a = _serialPort.ReadExisting();
                Console.WriteLine(a);
                Thread.Sleep(200);
            }
        }
    }
}

Credits

Haoming Weng

Haoming Weng

4 projects • 21 followers
A graduated student

Comments