Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Fred_Vicentin · Nov 30, 2014 at 09:06 PM · arduinosensor

Arduino on Unity with Ultrasonic sensor

Hey guys, I'm using arduino to read hc sr04 sensor. Ultrasonic sensor.

On arduino It read correctly my script, but on unity its giving weird values, I'm getting correct distance on arduino, but on unity i receive everytime the same values (10, 50, 47...) when it must be near de value 100. Here is my unity simple code

 using UnityEngine;
 using System.Collections;
 using System.IO.Ports;
 
 public class SerialRead : MonoBehaviour {
 
     SerialPort sp = new SerialPort("COM7", 9600);
     // Use this for initialization
     void Start () 
     {
         sp.Open();
         sp.ReadTimeout = 1;
     }
     
     // Update is called once per frame
     void Update ()
     {
         if(sp.IsOpen)
         {
             try 
             {
 
                 print(sp.ReadByte());
             }
             catch(System.Exception)
             {
                 throw;
             }
     }
 }
 }
 


Now my arduino code

 #define echoPin 13 //Pino 13 recebe o pulso do echo  
 #define trigPin 12 //Pino 12 envia o pulso para gerar o echo  
   
 void setup()  
 {  
   Serial.begin(9600); //inicia a porta serial  
    pinMode(echoPin, INPUT); // define o pino 13 como entrada (recebe)  
    pinMode(trigPin, OUTPUT); // define o pino 12 como saida (envia)  
 }  
   
 void loop()  
 {  
   //seta o pino 12 com um pulso baixo "LOW" ou desligado ou ainda 0  
     digitalWrite(trigPin, LOW);  
   // delay de 2 microssegundos  
     delayMicroseconds(2);  
   //seta o pino 12 com pulso alto "HIGH" ou ligado ou ainda 1  
     digitalWrite(trigPin, HIGH);  
   //delay de 10 microssegundos  
     delayMicroseconds(10);  
   //seta o pino 12 com pulso baixo novamente  
     digitalWrite(trigPin, LOW);  
   //pulseInt lê o tempo entre a chamada e o pino entrar em high  
     long duration = pulseIn(echoPin,HIGH);  
   //Esse calculo é baseado em s = v . t, lembrando que o tempo vem dobrado  
   //porque é o tempo de ida e volta do ultrassom  
     long distancia = duration /29 / 2 ;  
   
 
 Serial.println(distancia);  
 
 }  
 
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by alexandrejunior2 · Feb 21, 2015 at 05:37 AM

Hi, Change sp.ReadByte() to sp.ReadLine()

using UnityEngine; using System.Collections; using System.IO.Ports; using System.Threading;

public class SerialPortTest : MonoBehaviour { //Setup parameters to connect to Arduino public static SerialPort sp = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One); public int message2; private float updatePeriod = 0.0f; public GameObject pushObject;

 // Use this for initialization
 void Start () 
 {
 OpenConnection();
 }
 
 void Update()
 {

     message2 = int.Parse(sp.ReadLine());
     print (message2);

         
 }

 
 
 //Function connecting to Arduino
 public void OpenConnection() 
 {
    if (sp != null) 
    {
      if (sp.IsOpen) 
      {
       sp.Close();
       print("Closing port, because it was already open!");
             //message = "Closing port, because it was already open!";
      }
      else 
      {
       sp.Open();  // opens the connection
       sp.ReadTimeout = 1000;  // sets the timeout value before reporting error
       print("Port Opened!");
     //        message = "Port Opened!";
      }
    }
    else 
    {
      if (sp.IsOpen)
      {
       print("Port is already open");
      

      }
      else 
      {
       print("Port == null");
      }
    }
 }
 
 void OnApplicationQuit() 
 {
    sp.Close();
 }

}

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image alexandrejunior2 · Feb 23, 2015 at 04:11 PM 0
Share

Agora que eu vi os comentários em português. Espero ter ajudado!!!

att. $$anonymous$$andre Ribeiro.

avatar image
0

Answer by Zaycker · Oct 22, 2015 at 03:25 PM

Olá Fred

Estou iniciando os estudos do Arduino, e gostaria de aplicar os estudos a Unity, mas estou com um pouco de dificuldade de entender como funciona a comunicação entre as plataformas. Poderia me sanar algumas duvidas? 1º Como o arduino manda a informação para a Unity? Seria com a Serial.println()?

2º Como a Unity recebe os valores? tenho que fazer a variável que irá receber, mas como ela recebe? Se tiver alguma materia só para me dar o norte, ja ajuda bastante.

Parabens pelo post/ projeto. Muito agradecido

Hello Fred

It is initiating studies of the Arduino, and would like to apply studies Unity, but I have some difficulty understanding how communication works across platforms.

could you help me some doubts? 1 As the Arduino sends the information to the Unity? Would be to Serial.println ()?

  1. As the Unity receives values? I have to make the variable that will receive, but as it gets? If you have any material just to give me the north, already helps.

Congratulations for post / project. Thank you very much

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

28 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Arduino Temperature Sensor Read Values in Unity 5 Answers

How do i Smooth ingame movement with flickering sensor input? 0 Answers

Reversed axes with quaternions and orientation sensor 0 Answers

Using phone compass as a sensor in the game 1 Answer

Compass magneticHeading problem in portrait mode (Android) 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges