Unity Arduino serial communication

1. The Unity side sends messages and the Arduino side receives messages through serial port communication.

Arduino

#include <Arduino.h>

#define PIN_KEY 5
uint item;

void setup() {
    item = 0;
    Serial.begin(115200);
    pinMode(PIN_KEY, OUTPUT);  
}

void loop() {
    if(Serial.available()>0)
    {
        item = Serial.read();        
    }
    if(item == 'a')
    {
        digitalWrite(PIN_KEY,HIGH); 
    }
    if(item == 'b')
    {
        digitalWrite(PIN_KEY,LOW); 
    }
}

Unity edge

public class Test : MonoBehaviour
{
    SerialPort port = new SerialPort("COM4", 115200);

    public Button Btn_Open;
    public Button Btn_Close;

    private void Start()
    {
        port.Open();
        port.ReadTimeout = 1;

        Btn_Open.onClick.AddListener(() => {
            port.WriteLine("a");
        });

        Btn_Close.onClick.AddListener(() => {
            port.WriteLine("b");
        });
    }
}

To achieve serial communication, click the light button and the light will turn on. Turn off the light button and the light goes out.

2. The Unity side receives messages and the Arduino side sends messages through serial port communication.

Arduino

#include <Arduino.h>

void setup() {
    Serial.begin(9600);
}

void loop() {
    Serial.println("a");
    delay(1000);
    Serial.println("o");
    delay(1000);
}

Unity edge

1. Import the Ardity plug-in (find it in the Unity mall)

2. Open the read and write instance scenario

 3. Add read and write instance scripts

 4.

/**
 * Ardity (Serial Communication for Arduino + Unity)
 * Author: Daniel Wilches <[email protected]>
 *
 * This work is released under the Creative Commons Attributions license.
 * https://creativecommons.org/licenses/by/2.0/
 */

using UnityEngine;
using System.Collections;

/**
 * Sample for reading using polling by yourself, and writing too.
 */
public class SampleUserPolling_ReadWrite : MonoBehaviour
{
    public MeshRenderer Cube;
    public SerialController serialController;

    // Initialization
    void Start()
    {
        serialController = GameObject.Find("SerialController").GetComponent<SerialController>();

        Debug.Log("Press A or Z to execute some actions");
    }

    // Executed each frame
    void Update()
    {
        //---------------------------------------------------------------------
        // Send data
        //---------------------------------------------------------------------

        // If you press one of these keys send it to the serial device. A
        // sample serial device that accepts this input is given in the README.
        if (Input.GetKeyDown(KeyCode.N))
        {
            Debug.Log("Sending n");
            serialController.SendSerialMessage("n");
        }

        if (Input.GetKeyDown(KeyCode.M))
        {
            Debug.Log("Sending m");
            serialController.SendSerialMessage("m");
        }


        //---------------------------------------------------------------------
        // Receive data
        //---------------------------------------------------------------------

        string message = serialController.ReadSerialMessage();

        if (message == null)
            return;

        // Check if the message is plain data or a connect/disconnect event.
        if (ReferenceEquals(message, SerialController.SERIAL_DEVICE_CONNECTED))
            Debug.Log("Connection established");
        else if (ReferenceEquals(message, SerialController.SERIAL_DEVICE_DISCONNECTED))
            Debug.Log("Connection attempt failed or disconnection detected");
        else 
        {
            if (message.Equals("a")) 
            {
                Cube.material.color = Color.red;
            }
            if (message.Equals("o"))
            {
                Cube.material.color = Color.white;
            }
            Debug.Log("Message arrived: " + message);
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_46711336/article/details/131750595