Ok, here is my problem. I have a setup where i use an arduino mega, an arduino uno and unity 2019.2.1f1 in order to control 2 LEDS. I have the arduino mega connected at COM6 and at 9600 baud rate. I want to press a key in unity, and send a specific character to the arduino mega, and then for the mega to transfer the value to the uno, and act accordingly. In my case, i have unity send w,a,s or d when one of these buttons gets pressed, on the mega. Then, i want the mega to send the same value to the uno board, and then light an LED. The problem is that it doesnt work and i need help. If you are confused, i will post the code.
Unity code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
public class SerialTest : MonoBehaviour
{
public SerialPort SP = new SerialPort("COM6", 9600);
private void Start()
{
SP.Open();
SP.ReadTimeout = 16;
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.W))
{
SP.Write("w");
}
else if (Input.GetKeyDown(KeyCode.A))
{
SP.Write("a");
}
else if (Input.GetKeyDown(KeyCode.S))
{
SP.Write("s");
}
else if (Input.GetKeyDown(KeyCode.D))
{
SP.Write("d");
}
}
}
Arduino Mega Code:
#include <SoftwareSerial.h>
SoftwareSerial softSerial(8, 9); // RX, TX
const int FirstPin = 2;
const int LastPin = 25;
const int URX = 8;
const int UTX = 9;
char myCol[20];
String Poses;
int Test;
void setup() {
Serial.begin(9600);
softSerial.begin(9600);
Poses = "";
Test = 0;
for(int i = FirstPin; i <= LastPin; i++)
{
if(i != URX || i != UTX || i != 20 || i != 21)
{
pinMode(i, INPUT);
}
else
{
continue;
}
}
}
void CheckPawns()
{
for(int y = FirstPin; y <= LastPin; y++)
{
if(y == 13 || y == 8 || y == 9 || y == 20 || y == 21)
{
Poses += "";
}
else
{
int state;
state = digitalRead(y);
if(state == HIGH)
{
Poses += "1";
}
else
{
Poses += "0";
}
}
}
}
void loop() {
CheckPawns();
//Serial.println(Poses);
Poses = "";
if(Serial.available())
{
int lf = 10;
Serial.readBytesUntil(lf, myCol, 1);
if(strcmp(myCol,"w")==0){
softSerial.write('w');
}
if(strcmp(myCol,"a")==0){
softSerial.write('a');
}
if(strcmp(myCol,"s")==0){
softSerial.write('s');
}
if(strcmp(myCol,"d")==0){
softSerial.write('d');
}
}
delay(1000);
}
Arduino Uno Code:
#include <SoftwareSerial.h>
SoftwareSerial softSerial(8, 9);
int LedA = 7;
int LedB = 6;
char myCol[20];
void setup() {
Serial.begin (9600);
softSerial.begin(9600);
pinMode(LedA, OUTPUT);
pinMode(LedB, OUTPUT);
digitalWrite(LedA, LOW);
digitalWrite(LedB, LOW);
}
void loop() {
if(softSerial.available())
{
int Test = softSerial.read();
if(Test == 'w'){
digitalWrite(LedA, LOW);
digitalWrite(LedB, HIGH);
}
else if(Test == 'a'){
digitalWrite(LedA, HIGH);
digitalWrite(LedB, HIGH);
}
else if(Test == 's'){
digitalWrite(LedA, HIGH);
digitalWrite(LedB, LOW);
}
else if(Test == 'd'){
digitalWrite(LedA, LOW);
digitalWrite(LedB, LOW);
}
}
}
Any help would be appreciated.