iT邦幫忙

2

arduino 傳string型別變數至unity再度轉換型別時讀不出來

arduino 傳string型別變數至unity,unity利用serialport的ReadLine()方法讀出來是String型態。如果我想把這個String型態變數轉換為float(我是用float.parse(string變數))結果印不出來。這應該要如何解決呢?謝謝~

//unity程式碼
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
public class NewBehaviourScript1 : MonoBehaviour {

SerialPort sp=new SerialPort("COM4",9600);
//float num=0;
// Use this for initialization
void Start () {
	sp.Open ();
	sp.ReadTimeout = 10000;
}
// Update is called once per frame
void Update () {
	if (sp.IsOpen) {
		try{
			float data= float.Parse(sp.ReadLine());
			print(data);
			this.gameObject.transorm.Rotate(new Vector3(0f,0f,data));
		}
		catch(System.Exception){
		}
	}
}	

}
//arduino程式碼
const int outputA=6;
const int outputB=7;
float counter=0;
int aState;
int aLastState;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);

pinMode(outputA,INPUT);
pinMode(outputB,INPUT);

aLastState=digitalRead(outputA);
}
void loop() {
// put your main code here, to run repeatedly:
aState=digitalRead(outputA);
if(aState!=aLastState){
if(digitalRead(outputB)!=aState){
counter--;
}
else{
counter++;
}
Serial.print("Position: ");
Serial.println(String(counter));
}
aLastState=aState;
}

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
sfc507
iT邦新手 4 級 ‧ 2018-05-25 11:46:42

雖然不懂unity,不過還是試著回答,首先Arduino從程式碼看出他送出了

Serial.print("Position: ");
Serial.println(String(counter));

所以unity應該會接收到 Position: XXX \n

但是從你貼出來的unity的程式碼好像沒有處理這個部分,所以你直接對字串做float.Parse會無法被處理。

解決方式:

  1. unity加上字串處理的function
  2. arduino註解掉Serial.print("Position: ");

我個人是比較偏向使用第一個方法,不然未來專案變大unity程式會抓不到你想要的資料

我要發表回答

立即登入回答