Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. using UnityEngine;
  2. /*
  3. * To use 'System.IO.Ports;', you should change in Player settings
  4. * Build Settings - Player Settings - 'Player' tab
  5. * Configuration - Api Compatibility Level* ---> change to β€˜NET 4.x’
  6. */
  7. using System.IO.Ports;
  8.  
  9. public class ArduinoSerial : MonoBehaviour
  10. {
  11.  
  12. public string port; //ex) MAC Arduino Port "/dev/cu.usbmodem146101"
  13. public int baudrate = 9600; // ex) Arduino : Serial.begin(9600);
  14.  
  15. private SerialPort sp;
  16. public string incomingData;
  17.  
  18. public Material objMaterial;
  19. private Color cubeColor;
  20. private float sensorValue;
  21.  
  22. void Start()
  23. {
  24. sp = new SerialPort(port, baudrate);
  25. sp.ReadTimeout = 50;
  26. sp.Open();
  27. }
  28.  
  29. void Update()
  30. {
  31. try
  32. {
  33. incomingData = sp.ReadLine();
  34. sensorValue = float.Parse(incomingData);
  35. Debug.Log(sensorValue);
  36. }
  37. catch (System.Exception)
  38. {
  39.  
  40. }
  41.  
  42. Color sensorColor = objMaterial.color;
  43. float mPotVal = scale(0.0f, 1024.0f, 0.0f, 1.0f, sensorValue);
  44. sensorColor.a = mPotVal;
  45. objMaterial.color = sensorColor;
  46.  
  47. /*
  48. //Write to Arduino
  49. if (Input.GetKeyDown("1"))
  50. {
  51. sp.Write("1");
  52. sp.BaseStream.Flush();
  53. }
  54. else if (Input.GetKeyDown("0"))
  55. {
  56. sp.Write("0");
  57. sp.BaseStream.Flush();
  58. }
  59. */
  60. }
  61.  
  62. //Map the sensor value
  63. public float scale(float OldMin, float OldMax, float NewMin, float NewMax, float OldValue)
  64. {
  65. float OldRange = (OldMax - OldMin);
  66. float NewRange = (NewMax - NewMin);
  67. float NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin;
  68.  
  69. return (NewValue);
  70. }
  71.  
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement