namespace MaxSonarTest1
{
public partial class Program
{
GT.Socket.SocketInterfaces.AnalogInput ain5 = GT.Socket.GetSocket(14, true, null, null).AnalogInput5;
// This method is run when the mainboard is powered up or reset.
void ProgramStarted()
{
while (true)
{
double v = ain5.ReadVoltage();
double r = (v / 0.009766);
Debug.Print((r.ToString()));
Thread.Sleep(100);
}
}
}
}
Cool thanks for that link I was looking for that last night but my brain was fried.
One more question is this a style question or are there reasons for the way Ian wrote his sample or the way I have it here they both seem to work but as a self taught programmer should I fix bad habits.
After reading the link I have this.
.
namespace MaxSonarTest1
{
public partial class Program
{
GT.Socket.SocketInterfaces.AnalogInput ain5 = GT.Socket.GetSocket(14, true, null, null).AnalogInput5;
GT.Timer RangFinderTimer = new GT.Timer(100);
// This method is run when the mainboard is powered up or reset.
void ProgramStarted()
{
RangFinderTimer.Start();
double v = ain5.ReadVoltage();
double r = (v / 0.009766);
Debug.Print((r.ToString()));
}
}
}
Oh and who should get the check mark as you both helped answer the question
@ swestcott - ian has used Lambda expressions to create the timer function inline.
The way you have done it it only reads the pin once.
The old school way you need to create a function for the timer tick.
namespace GadgeteerApp1
{
public partial class Program
{
GT.Socket.SocketInterfaces.AnalogInput ain5 = GT.Socket.GetSocket(14, true, null, null).AnalogInput5;
GT.Timer RangFinderTimer = new GT.Timer(100);
// This method is run when the mainboard is powered up or reset.
void ProgramStarted()
{
RangFinderTimer.Tick += new GT.Timer.TickEventHandler(RangFinderTimer_Tick);
RangFinderTimer.Start();
}
void RangFinderTimer_Tick(GT.Timer timer)
{
double v = ain5.ReadVoltage();
double r = (v / 0.009766);
Debug.Print((r.ToString()));
}
}
}
As Justin pointed out, your example doesn’t achieve the original objective. Justin’s example show’s an almost equivalent way of doing what I did. My convention is usually to write it as a lambda function if it’s a short (<10 lines) function. If it’s going to be any bigger then I’ll do it the way Justin did.
Note that there’s one big difference between my implementation and Justin’s. I pulled the declarations for v & r outside (above) the scope of the event handler. This will prevent new variables from being created every time the timer fires and eliminate garbage collection.
The usual practice is that the first person to answer your question gets the points. Doesn’t really matter to me, though. I stopped counting a while ago. I’m just glad to help.
I want to thank you both I have now run down an internet rabbit hole learning about lambda functions which has of course opened up all sorts of new stuff.