Hopefully someone will be able to help me. I have a Netduino plus and I am trying to read the date from a DS1307 RTC.
When I try to read it from the thread of my application that initialized the RDS1307 it works but it fails when I try to read it from another thread. It throws the following error. System.ArgumentOutOfRangeException.
The call currTime = clock.Get().ToString(“HH:mm:ss”) from controlLights causes the exception.
Can anyone help me?
Below is a sample of the code.
class LaunchController
{
private DS1307 clock = new DS1307();
public LaunchController () {
String displayTime;
clock = new DS1307();
clock.Set(new DateTime(2018, 1, 23, 21, 12, 0));
ThreadStart lightsJob = new ThreadStart(controlLights);
Thread lightsThread = new Thread(lightsJob);
lightsThread.Start();
while (true)
{
lock (this)
{
displayTime = clock.Get().ToString("MMM dd yyyy HH:mm:ss");
}
LCD.ClearScreen();
LCD.Write(1, 1, displayTime);
Thread.Sleep(1000);
}
}
private void controlLights()
{
String currTime;
TimeSpan cTime;
TimeSpan lightsOn;
TimeSpan lightsOff;
LightsTimer timer1 = new LightsTimer("Test");
timer1.setPort(new OutputPort(Pins.GPIO_PIN_D2, false));
timer1.setStartTime(21, 12, 30);
timer1.setEndTime(21, 13, 00);
ArrayList myEvents = new ArrayList();
myEvents.Add(timer1);
while (true)
{
foreach (object evnts in myEvents)
{
if (evnts != null)
{
// Check to see to turn lights on of off.
if (evnts is LightsTimer)
{
lock (this)
{
currTime = clock.Get().ToString("HH:mm:ss");
}
cTime = new TimeSpan(int.Parse(currTime.Substring(0, 2)),
int.Parse(currTime.Substring(3, 2)),
int.Parse(currTime.Substring(6, 2)));
lightsOn = ((LightsTimer)evnts).getStartTime();
lightsOff = ((LightsTimer)evnts).getEndTime();
if ((cTime >= lightsOn) && (cTime <= lightsOff))
{
// Turn on the lights
if (!((LightsTimer)evnts).getPort().Read())
{
((LightsTimer)evnts).getPort().Write(true);
}
}
else
{
// Turn Lights off
if (((LightsTimer)evnts).getPort().Read())
{
((LightsTimer)evnts).getPort().Write(false);
}
}
}
}
}
Thread.Sleep(1000);
}
}
}
The call to the DS1307 code
public DS1307()
{
_slaveConfig = new I2CDevice.Configuration(DS1307_I2C_ADDRESS, DS1307_I2C_CLOCK_RATE_KHZ);
}
and the GET code
public DateTime Get() {
byte[] clockData = new byte[7];
try
{
I2CBus.GetInstance().ReadRegister(_slaveConfig, DS1307_RTC_START_ADDRESS, clockData, TransactionTimeout);
}
catch (Exception e)
{
throw e;
}
return new DateTime(
BcdToDec(clockData[6]) + 2000, // year
BcdToDec(clockData[5]), // month
BcdToDec(clockData[4]), // day
BcdToDec(clockData[2] & 0x3f), // hours over 24 hours
BcdToDec(clockData[1]), // minutes
BcdToDec(clockData[0] & 0x7f) // seconds
);
}