This is arduino code to get serial data 0 or 1 and turn on and off the built in led in portenta.
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
}
const int BUFFER_SIZE = 50;
char buf[BUFFER_SIZE];
void loop() {
// put your main code here, to run repeatedly:
if(Serial.available()>0){
int len = Serial.readBytes(buf, BUFFER_SIZE);
if(buf[0] == '0'){
digitalWrite(LEDB, LOW);
}
else if (buf[0] == '1'){
digitalWrite(LEDB, HIGH);
}
}
}
And below is Unity Code.
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using UnityEngine;
using System.Threading;
public class serialport : MonoBehaviour
{
Thread IOThread = new Thread(DataThread);
private static SerialPort sp;
private static string incomingMsg = "";
private static string outgoingMsg = "";
private static void DataThread()
{
sp = new SerialPort("COM10", 115200);
sp.Open();
if (sp.IsOpen)
{
Debug.Log("serial port is opened");
}
while (true)
{
if(outgoingMsg != "")
{
sp.Write(outgoingMsg);
outgoingMsg = "";
}
incomingMsg = sp.ReadExisting();
Thread.Sleep(200);
}
}
private void OnDestroy()
{
IOThread.Abort();
sp.Close();
}
private void Start()
{
IOThread.Start();
}
private void Update()
{
if(incomingMsg != "")
{
Debug.Log(incomingMsg);
}
if (Input.GetKeyDown(KeyCode.Alpha0))
{
Debug.Log("0");
outgoingMsg = "0";
}
else if( Input.GetKeyDown(KeyCode.Alpha1))
{
Debug.Log("1");
outgoingMsg = "1";
}
}
}
This work well with my arduino uno but it didn't work with portenta h7. What could be the possible reason for this error?
Also as a final version I want to read IMU sensor data with portenta tx, rx pin (which is serial 1) and send and receive the data from the unity via serial communication.
So
- I want to check that portenta communicate with unity via serial correctly.
- I want to check that unity send the data to arduino correctly. But how can i keep checking this I cannot open the serial monitor when i connected it with unity.
Thanks for your every help!