#define btn 3
#define pinA 4 //clk
#define pinB 5 // dt
int counter = 0;
int pos;
int lastPos;
void setup() {
pinMode (pinA,INPUT);
pinMode (pinB,INPUT);
pinMode (btn,INPUT);
Serial.begin (9600);
lastPos = digitalRead(pinA);
}
void loop() {
//button func
if(digitalRead(btn)==0)
{
counter=0;
Serial.println(counter);
}
pos = digitalRead(pinA);
if(pos == lastPos) return;
if (digitalRead(pinB) == pos) {
counter ++;
}else {
counter --;
}
Serial.println(counter);
lastPos = pos;
delay(20);
}
using UnityEngine;
using System.IO.Ports;
using System;
public class ArduinoConnection : MonoBehaviour
{
SerialPort portNo = new SerialPort("COM3", 9600);
public int Counter { get; private set; }
void Start()
{
portNo.Open();
portNo.ReadTimeout = 5000;
}
private void Update()
{
ReadEncoder();
}
void ReadEncoder()
{
if (portNo.IsOpen)
{
if (portNo.BytesToRead > 0)
{
string recData = portNo.ReadLine();
if (Int32.TryParse(recData, out int x))
{
Counter = x;
}
Debug.Log(Counter);
}
}
}
}