using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System.Threading;
public class Juego : MonoBehaviour {
SerialPort puerto=new SerialPort("COM3",9600);
void Start ()
{
puerto.Open();
}
void Update ()
{
puerto.Write ("2");
}
}
when I run Unity I have an error "InvalidOperationException: Specified port is not open."
In arduino I have this
int test = 8 ;
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
pinMode(test,OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
int unity= Serial.read();
if(unity==2)
{
digitalWrite(prueba,HIGH );
}
else
{
digitalWrite(prueba,LOW );
}
}
Unity should send "2" and then arduino read this and turn on the led. But I dont know how works this. any help please? thanks.
The Serial.read() function needs to return an int, because some people do not bother checking that there is anything to read before trying to read.
If everyone did, then Serial.read() would return a char or a byte. To read a string, you need to read and store multiple letters, in a NULL terminated array of chars. You could then use atoi() to convert the string to an int. But, in order to do that, you need to know when the end of packet arrives. Nothing in what you are sending says when the packet is done.
A ball with the script, touch bricks of different colors, red,green and blue, when touch this, send the message to arduino. the problem is the 2 first impacts, dont work, then yes. And if the ball touches many bricks, or too fast, dont work.. why?
Arduino code
int red = 9;
int blue = 8;
int green = 11;
void setup() {
Serial.begin(9600);
pinMode(red, OUTPUT);
pinMode(blue, OUTPUT);
pinMode(green, OUTPUT);
}
void loop() {
String unity = Serial.readString();
if (unity=="r")
{
digitalWrite(red,HIGH);
}
else if(unity=="b")
{
digitalWrite(blue,HIGH);
}
else if(unity=="g")
{
digitalWrite(green,HIGH);
}
else
{
digitalWrite(green,LOW);
digitalWrite(blue,LOW);
digitalWrite(red,LOW);
}
}
You are sending one character. There is no earthly reason to use a blocking function to read one character. There is no reason to store one character in a String.
You are sending one character. There is no earthly reason to use a blocking function to read one character. There is no reason to store one character in a String.