Hi,
I’ve been trying to read a rotary encoder with no success in the long term…
Attached channels A and B to interrupt ports, put almost anything under comments, but after few turns of the encoder the program hangs and I get the OutOfMemory exception.
I can get it to work for only short time, I don’t understand what is eating all the memory each time the interrupts raises.
BTW The encoder has 1024 ppr, but it’s rotated by hand so it shouldn’t go over 1 revolution per second
Help would be much appreciated.
using System;
using Microsoft.SPOT;
using GHIElectronics.NETMF.FEZ;
using GHIElectronics.NETMF.Hardware;
using System.Threading;
using Microsoft.SPOT.Hardware;
using System.IO.Ports;
using System.Text;
namespace EncoderReader
{
public class Program
{
//static SerialPort UART = new SerialPort("COM1", 57600);
static OutputPort LED = new OutputPort((Cpu.Pin)FEZ_Pin.Digital.LED, false);
//InputPort Button = new InputPort((Cpu.Pin)FEZ_Pin.Interrupt.LDR,false,Port.ResistorMode.PullUp);
static InterruptPort Encoder1A = new InterruptPort((Cpu.Pin)FEZ_Pin.Interrupt.An0, false, Port.ResistorMode.PullUp, Port.InterruptMode.InterruptEdgeBoth);
static InterruptPort Encoder1B = new InterruptPort((Cpu.Pin)FEZ_Pin.Interrupt.An1, false, Port.ResistorMode.PullUp, Port.InterruptMode.InterruptEdgeBoth);
static int encoder1Pos = 0;
static bool encoder1A_Set = false;
static bool encoder1B_Set = false;
static byte[] buffer = new byte[64];
static void Main()
{
//UART.Open();
LED.Write(true);
Encoder1A.OnInterrupt += new NativeEventHandler(Encoder1A_OnInterrupt);
Encoder1B.OnInterrupt += new NativeEventHandler(Encoder1B_OnInterrupt);
Timer MyTimer = new Timer(new TimerCallback(RunMe), null, 0, 1000);
while (true)
{
Thread.Sleep(Timeout.Infinite);
}
}
static void RunMe(object o)
{
//buffer = Encoding.UTF8.GetBytes("Index = " + encoder1Pos.ToString() + "\r\n");
//UART.Write(buffer, 0, buffer.Length);
//UART.Flush();
LED.Write(!LED.Read());
}
static void Encoder1A_OnInterrupt(uint port, uint state, DateTime time)
{
encoder1A_Set = Encoder1A.Read();
encoder1Pos += (encoder1A_Set != encoder1B_Set) ? +1 : -1;
}
static void Encoder1B_OnInterrupt(uint port, uint state, DateTime time)
{
encoder1B_Set = Encoder1B.Read();
encoder1Pos += (encoder1A_Set == encoder1B_Set) ? +1 : -1;
}
}
}