I am trying to create a simple box in Unity 3D, that when I click UP - it sends a message to the Arduino which then increases a variable which changes the PWM of a motor I have connected to it.
No matter what I try I cannot seem to get everything working because of the ASCII codes and complexity of the Serial communication which I am not familiar yet.
How can I write a simple script in Unity that when I click the button it increases the speed. I want the output data going into the arduino to say Sp7 which the function can break down into Speed and then 7 which I am going to create cases or an array for. My largest problem is setting up the Serial commands so that it reads the entire input until \n. I would also like to make a new exit statement such as /end and when it receives that to execute the speed adjustment command. Also what coding would be needed on the Arduinos side?
How Can I make the Arduino cypher out the data using both string and int? Like in the example of Sp7 that way it exexutes the change speed function and changes the speed to 7?
Arduino
#include <TimerOne.h>
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(9, OUTPUT);
Timer1.initialize(11230); // Intialize timer1, and set a 89hz frequency
Serial.println ("PWM Signal has been initialized");
}
int integerValue=0; //max value is 65535
char incomingByte;
int dutyCycle;
void loop() {
if (Serial.available() > 0) { // something came across serial
integerValue = 0; // throw away previous integerValue
while(1) { // force into a loop until 'n' is received
incomingByte = Serial.read();
if (incomingByte == '\n') break; // exit the while(1), we're done receiving
if (incomingByte == -1) continue; // if no characters are in the buffer read() returns -1
integerValue *= 10; // shift left 1 decimal place
// convert ASCII to integer, add, and shift left 1 decimal place
integerValue = ((incomingByte - 48) + integerValue);
}
dutyCycle=integerValue;
Serial.println(integerValue); // Do something with the value
Timer1.pwm(9,dutyCycle); // setup pwm on pin 9, with a __ duty cycle defined by int dutyCycle
}
}
Unity C# Code
using UnityEngine;
using System.Collections;
public class GUI_Button : MonoBehaviour {
void Setup () {
{
void update() {
}
void OnGUI () {
// Make a background box
GUI.Box(new Rect(10,10,100,90), "Speed Control");
// Make the first button. If it is pressed, change of speed will occur
if(GUI.Button(new Rect(20,40,80,20), "UP")) {
// put serial command here
}
// Make the second button.
if(GUI.Button(new Rect(20,70,80,20), "DOWN")) {
// put serial command here
}
}
}