Created
January 27, 2020 12:47
-
-
Save glopesdev/3070890ad944c0726ad2c99bbd9cbe82 to your computer and use it in GitHub Desktop.
Decodes the current state of a quadrature encoder from raw A/B channels
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using Bonsai; | |
| using System; | |
| using System.ComponentModel; | |
| using System.Collections.Generic; | |
| using System.Linq; | |
| using System.Reactive.Linq; | |
| [Combinator] | |
| [Description("Decodes the current state of a quadrature encoder from raw A/B channels.")] | |
| [WorkflowElementCategory(ElementCategory.Transform)] | |
| public class QuadratureCounter | |
| { | |
| public QuadratureCounter() | |
| { | |
| Threshold = 2.5f; | |
| } | |
| public float Threshold { get; set; } | |
| public IObservable<int> Process(IObservable<float[]> source) | |
| { | |
| return Observable.Defer(() => | |
| { | |
| int counter = 0; | |
| return source.Select(input => | |
| { | |
| var inputA = new float[input.Length / 2]; | |
| var inputB = new float[input.Length / 2]; | |
| Array.Copy(input, 0, inputA, 0, inputA.Length); | |
| Array.Copy(input, inputA.Length, inputB, 0, inputB.Length); | |
| var first = true; | |
| var prevA = false; | |
| var prevB = false; | |
| var direction = 0; | |
| for (int i = 0; i < inputA.Length; i++) | |
| { | |
| var a = inputA[i] > Threshold ? true : false; | |
| var b = inputB[i] > Threshold ? true : false; | |
| var changeA = a != prevA; | |
| var changeB = b != prevB; | |
| if (first) first = false; | |
| else if (changeA || changeB) | |
| { | |
| if (prevA == prevB) direction = changeB ? 1 : -1; | |
| else direction = changeA ? 1 : -1; | |
| counter += direction; | |
| } | |
| prevA = a; | |
| prevB = b; | |
| } | |
| return counter; | |
| }); | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment