My relay wont return high after reading serial read from unity. But when I send the data from serial it's return to HIGH.
Arduino Code
#include <Wire.h>
const int coinInt = 0;
//Attach coinInt to Interrupt Pin 0 (Digital Pin 2). Pin 3 = Interrpt Pin 1.
/////////////////
volatile float coinsValue = 0.00;
//Set the coinsValue to a Volatile float
//Volatile as this variable changes any time the Interrupt is triggered
volatile int coinsChange = 0;
//A Coin has been inserted flag
bool coins = false;
int relay = 8;
void setup(){
Serial.begin(9600);
//Start Serial Communication
attachInterrupt(coinInt, coinInserted, RISING);
pinMode(relay, OUTPUT);
digitalWrite(relay, LOW);
}
void coinInserted()
{
coinsValue = coinsValue + 1;
coinsChange = 1;
}
void loop()
{
if (coinsChange == 1)
{
coinsChange = 0;
Serial.print("Credit: £");
Serial.println(coinsValue);
}
if (coinsValue == 5)
{
coins = true;
digitalWrite(relay, HIGH);
}
while(coins == true)
{
if (Serial.available() > 0 )
{
char ltr = Serial.read();
if (ltr == 'a')
digitalWrite(relay, HIGH);
coinsValue = 0;
coins = false;
Serial.flush();
return;
}
else
{
break;
}
}
}
Unity Code
Unity code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO.Ports;
using System.Threading;
public class GameTimer : MonoBehaviour
{
SerialPort sp = new SerialPort("COM3", 9600);
public Text gameTimerText;
public static float gameTimer = 10f;
void start()
{
sp.Open();
sp.ReadTimeout = 1;
}
void Update()
{
if (sp.IsOpen)
{
try
{
print(sp.ReadByte());
}
catch (System.Exception)
{
}
}
gametimer-= 1 * Time.deltaTime;
gameTimerText.text = gameTimer.ToString("0");
if (gameTimer <= 0)
{
sp.Write("a");
}
}
}