Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- /*
- * To use 'System.IO.Ports;', you should change in Player settings
- * Build Settings - Player Settings - 'Player' tab
- * Configuration - Api Compatibility Level* ---> change to βNET 4.xβ
- */
- using System.IO.Ports;
- public class ArduinoSerial : MonoBehaviour
- {
- public string port; //ex) MAC Arduino Port "/dev/cu.usbmodem146101"
- public int baudrate = 9600; // ex) Arduino : Serial.begin(9600);
- private SerialPort sp;
- public string incomingData;
- public Material objMaterial;
- private Color cubeColor;
- private float sensorValue;
- void Start()
- {
- sp = new SerialPort(port, baudrate);
- sp.ReadTimeout = 50;
- sp.Open();
- }
- void Update()
- {
- try
- {
- incomingData = sp.ReadLine();
- sensorValue = float.Parse(incomingData);
- Debug.Log(sensorValue);
- }
- catch (System.Exception)
- {
- }
- Color sensorColor = objMaterial.color;
- float mPotVal = scale(0.0f, 1024.0f, 0.0f, 1.0f, sensorValue);
- sensorColor.a = mPotVal;
- objMaterial.color = sensorColor;
- /*
- //Write to Arduino
- if (Input.GetKeyDown("1"))
- {
- sp.Write("1");
- sp.BaseStream.Flush();
- }
- else if (Input.GetKeyDown("0"))
- {
- sp.Write("0");
- sp.BaseStream.Flush();
- }
- */
- }
- //Map the sensor value
- public float scale(float OldMin, float OldMax, float NewMin, float NewMax, float OldValue)
- {
- float OldRange = (OldMax - OldMin);
- float NewRange = (NewMax - NewMin);
- float NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin;
- return (NewValue);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement