我想做的是通過串口把arduino的資料傳給unity 但是不知道哪里不對 一直都沒有資料 unity就只運行到讀資料
下面是arduino上的程式;
const int sensorPin=0;
int t;
void setup()
{
Serial.begin(19200);
pinMode(sensorPin,INPUT);
}
void loop(){
t =analogRead(sensorPin)/4;
if(t<10)
{
Serial.write(1);
Serial.println(1);
Serial.flush();
delay(500);}
if(t>=10)
{
Serial.write(2);
Serial.println(2);
Serial.flush();
delay(500);}}
unity里的程式
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
using UnityEngine.UI;
public class change : MonoBehaviour {
public GameObject lightA;
// Use this for initialization
SerialPort sp= new SerialPort("COM4",19200);
void Start () {
sp.Open ();
sp.ReadTimeout = 1;
}
// Update is called once per frame
void Update () {
if (sp.IsOpen) {
try{
lightA.GetComponent<Text>().text= "test";//這句是我用來測驗的 這句放在ReadByte()前就會運行放在后面就不會,求大神們指導
changelight(sp.ReadByte());
print(sp.ReadByte());
}
catch(System.Exception){
}
}
}
void changelight(int state)
{if (state == 1)
{
lightA.GetComponent<Text>().text= "0";
}
if (state == 2) {
lightA.GetComponent<Text>().text=" 1";
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/119534.html
標籤:網絡通信
