The
below showing hardware circuits to create continuously ON-OFF impulsive
pulse & step pulses devices using hardware timers & relays. At the
same time, showing software impulsive pulses and step pulses periodic timer
in C++, C#.
A circuit to generate periodically short & impulsive pulses
Require only 1 hardware
relay and 1 hardware timer to do the job.

Coding
in c# Console App: https://msdn.microsoft.com/en-us/library/system.timers.timer.elapsed(v=vs.110).aspx / system.timers.timer.elapsed
Circuit
time graph

Periodic Timer Applications
The Periodic Timer execute
sub-program once every preset period. It has many practical applications.
For instances:
·
I
presume iPhone use timer to monitor Apps screen-time. Every minute timer
will trigger On-Timed-Event to check which Apps are currently running.
·
In 'PLC controller to charge
Lead-acid batteries' project I did, I used timer to verify any batteries'
abnormalities during charging by measuring the batteries voltage. The
project PLC controller has 2 built-in analogue-voltage inputs with
resolution 1/6000 seconds and PLC CPU clock speed at mega-hertz (MHz).
It
is not practical nor meaningful to verify batteries voltage at every clock
cycle (MHz) or 1/6000 seconds period. Therefore, I
use timer & counters to check battery voltage condition every 1 minute.
PLC controller will determine whether the respective batteries are faulty
and stop charging:
o
If
batteries voltage not increasing after maybe 15 minutes of charging
By
using timer, user define the data sampling rate.
·
Single
master-database read data from multiple client-databases at different
timing using timer. In client computers, new data are created continuously
and stored inside client-databases. Presumably records created will not be
modified.
By
using timer to bulk-copy data (instead of sending single set data
every-time, which is impractical) from each client-databases to
master-database at different timing, we can avoid traffic congestion and
high CPU usage at master computer. Each time master database should only bulk-copy
data from one client database, afterward master database moves on to the
next client database. The timer program should be setup at master computer.
Master
computer can be limited to transfer maybe 10k records from each client
database in every 'On-Timed-Event' to control traffic flow.
SQL
database table 'Auto increment Primary Key' are required to be catered at
master database and client databases. Timer program check both the master
and client database's 'Primary Key' last running number to determine which
starting and ending records to bulk-copy.
·
Master
controller linked to multiple slave devices (e.g.
sensors), and they are looped together using the same pair of signal line
for the purpose of avoiding messy wiring. Master controller reads one individual
slave device information at one instance; afterwards master controller will
read the next slave device exclusively at the next instance. Hence the
periodic timer will be in use.
To
achieve this, master controller will send data to all slave devices
(because they are all looped together). The data's header will indicate
targeted receiver device ID 'A'. Only the slave device 'A' with the matched
device ID will echo back by sending device 'A' information back to master
controller. Likewise, the slave device 'A' data header will indicate the
receiver is master controller because all devices on the same signal line
will receive the same data. Thus, master controller able to read all slave
devices information at different timing in sequential manner periodically
using periodic timer.
Construct Periodic Timer using RTC and Thread.Sleep()
method in C++
To construct
software periodic timer in c++, we can use RTC
(Real-Time Clock) or Thread.Sleep() method.
sleep (command)
found in low power, non-critical and single thread microcontrollers.
The sleep (command)
inside microcontroller main process, once activated will put microcontroller
to sleep for a specified time. Minimum power consumption during
microcontrollers sleeping.
In scenarios if we
want main process to continuous run while having Periodic Timer feature, we
can use multithreading programming to perform the task.
When Thread.Sleep() executed, it suspends its thread program
execution for a specified time. Hence, we declare Thread.Sleep()
in a separate thread, other than the main process / thread (c++ int main()). However, periodic timer using Thread.Sleep() does not coincide with real-time clock, it
will drifts away from it. Because the timers next
triggering time will be the sum of pre-set time period plus sub-program
runtime.
In contrast,
construct software periodic timer using RTC (Real-Time
Clock) will not drifts away from RTC (Real-Time
Clock). Timer_using_RTCs next triggering time
will be the next pre-set time period. If the sub-program execution time
longer than a pre-set time period, Timer_using_RTC will bring forward the next
triggering time to next RTC period. Declare software RTC periodic timer
in a separate thread, using while(true)
loop statement. while(true) loop
statement make the thread process execute repeatedly, hence to be placed in
its own separate thread. Software RTC periodic timer
has higher computation consumption than Thread.Sleep().
MS Visual C++
Console App coding: Timer_RTC_sleep2.cpp
In this coding,
simulate sub-program execution time using std::this_thread::sleep_for()
command, test how it will affects timers drifted against RTC.
Topic: Run / Stop multiple Periodic Timers using Thread.Sleep()
& while(true) loop in C++
In scenario when we
want to run multiple Periodic Timers concurrently, each timer & its
subprogram do not delay other Timers. We can declare each timer in separate
threads. We want to run them continuously, we can
use Thread.Sleep() and while(true) loop.
To stop the running
while(true) loops, declares a public Boolean variable and private Boolean
variable. Use private Boolean variable to run the while loops. In the end
of each loop, set the private Boolean variable to be same as public Boolean
variable. To stop the while(true) loops, set the public Boolean variables
to false at the main process (int main()). The
sub-programs within the while(true) loops will finish one execution and
stop.
Visual C++ code
#include <stdio.h>
#include <iostream>
#include <thread>
using namespace std;
class class_PeriodicTimer_1s
{
private:
public:
bool runTimer;
class_PeriodicTimer_1s() {
runTimer
= true;
}
void Run(void)
{
bool whileLoop_RunTimer
= true;
while (whileLoop_RunTimer)
{
cout
<< "Running sub-program #1
every 1s" << endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
whileLoop_RunTimer
= runTimer;
}
}
};
class class_PeriodicTimer_2s
{
private:
public:
bool runTimer;
class_PeriodicTimer_2s(void) {
runTimer
= true;
}
void Run(void)
{
bool whileLoop_RunTimer
= true;
while (whileLoop_RunTimer)
{
cout
<< "Running sub-program #2
every 2s" << endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
whileLoop_RunTimer
= runTimer;
}
}
};
class class_PeriodicTimer_3s
{
private:
public:
bool runTimer;
class_PeriodicTimer_3s() {
runTimer
= true;
}
void Run(void)
{
bool whileLoop_RunTimer
= true;
while (whileLoop_RunTimer)
{
cout
<< "Running sub-program #3
every 3s" << endl;
std::this_thread::sleep_for(std::chrono::seconds(3));
whileLoop_RunTimer
= runTimer;
}
}
};
int main()
{
char user_command
= '\0';
class_PeriodicTimer_1s PeriodicTimer_1s;
std::thread thread_PeriodicTimer_1s(&class_PeriodicTimer_1s::Run, &PeriodicTimer_1s);
class_PeriodicTimer_2s PeriodicTimer_2s;
std::thread thread_PeriodicTimer_2s(&class_PeriodicTimer_2s::Run, &PeriodicTimer_2s);
class_PeriodicTimer_3s PeriodicTimer_3s;
std::thread thread_PeriodicTimer_3s(&class_PeriodicTimer_3s::Run, &PeriodicTimer_3s);
cout << "Press 'q' & Enter
to quit the program" << endl
<< endl;
cin >> user_command;
if (user_command
== 'q') {
PeriodicTimer_1s.runTimer
= false;
PeriodicTimer_2s.runTimer
= false;
PeriodicTimer_3s.runTimer
= false;
}
cout << "\nClosing
while loops.." << endl
<< endl;
// Wait for the threads to
finish
thread_PeriodicTimer_1s.join();
thread_PeriodicTimer_2s.join();
thread_PeriodicTimer_3s.join();
cout << "\nProgram
ended successfully" << endl;
return 0;
}
|
Topic: Run / Stop multiple Periodic Tasks using Thread.Wait()
& Periodic Tasks sorted in Priority Queue / Sorted List in C#
Alternative to using Thread.Sleep()
to run periodic tasks, we can use Thread.Wait().
Thread.Wait()
is one of the software thread states, other states are Thread.Start(),
Thread.Run(), and etc. When a thread enters Thread.Wait() state to idle, another thread can wake-up
this thread from idle to continue it executions.
In scenario we have many periodic
tasks, but we have limited number of process execution threads. Some
brainstorming thoughts:
·
Assuming
currTimeDate class is an accurate RTC that can
notify SortedList_PeriodicTasks.run_PeriodicTask(), and it will check if latest periodic task is
time-up to be executed by workerThread.
·
This
Periodic Task Schedular subprocess only execute periodic tasks function
but does not contain tasks data. Users should save periodic task input /
output data elsewhere, for instance in the OOP object.
·
This
Periodic Task Scheduler will run the periodic tasks function when the
respective periodic tasks preset time period timed.
·
To
manage periodic tasks, we can put periodic tasks tag number and it
function into Priority Queue / Sorted List. Priority Queue sorting
keys are each tasks next trigger time, Priority Queue values would be
the tasks function intended to be executed.
c# inherent SortedList
can be used as Priority Queue.
·
We
would not want to start a new execution thread for the periodic task ONLY
after preset time period timed. Because if we started a new process thread
from current thread, we will need to wait till this thread finished the
process execution. It would result in current thread being block for any
subsequent code execution until this new process thread finished it
execution.
Hence,
we declare a fixed number of process execution threads / worker threads
/ threads pool at the start. Count of software worker threads is a
finite number, take in consideration of hardware capability. When they
finished any timed periodic tasks function, worker threads enter Thread.Wait() state to idle. Therefore, we dont need
to repeatedly create and exit worker threads.
·
To
keep track of the fixed number of worker threads / threads pool state,
we can have a Stack to record which worker threads are in Wait state.
Only notify those worker threads that are in Wait state to run the timed
periodic tasks. After finished timed periodic task execution, worker
threads will push its Thread ID back to Stack and enter Thread.Wait() state to idle.
·
Using
Stack to notify the most recently ran worker thread wake up from idle,
such that idling worker threads will remain idle
longer time.
Version 0
MS Visual C# Console App coding: PeriodicTask_ThreadPool_WaitState.cs.txt
In this example, I
set 2 worker threads and 3 periodic tasks to demonstrate that individual
worker thread does not bind to a particular periodic task. Any worker
thread can be assigned to any periodic task when it is idle &
available. First periodic task (task A #1) timer period 1 second; second
periodic task (task B #2) timer period 2 second; third periodic task
(task C #3) timer period 3 seconds.
This version code
doesnt execute the periodic tasks correctly at the beginning. Reason is I
think I set intended executed functions as value of the SortedList.

Figure:
Version 0 simple process layout for Periodic Tasks Priority Queue using Thread.Wait()
Version 1
MS Visual C# Console App coding: main.cs.txt class_PeriodicTasks_ThreadWaitState.cs.txt class_Simulated_RTC_tick.cs.txt
In this version,
functions will not be declared as value of a SortedList.
Instead, functions are saved into an
array. Functions intended next execution datetime are declared as key of
the SortedList, ArrayIndex
are declared as value of the SortedList. Function start execution datetime,
function execution expiry datetime, current ID of the thread executing the
function, is current function executing? & etc. are added into array
nodes to add more status information.
This version code in
comparison to version 0, periodic tasks are executed correctly at the
beginning. To tidy-up the code, periodic task program will
be a class (class_PeriodicTasks_ThreadWaitState)
by itself; simulated RTC ticking is another class (class_Simulated_RTC_tick
Simulated_RTC_tick) by itself.
Whenever 1 second period timed, class_Simulated_RTC_tick
Simulated_RTC_tick will execute obj_PeriodicTasks_ThreadWaitState.notify_timed. This
will make class_PeriodicTasks_ThreadWaitState
to notify software threads to execute all the timed periodic tasks
concurrently.
Optional operation, when a function is currently executing,
dont run the same function again. Prevent multiple concurrent execution of
the same function. Another optional operation is checks every 1 minute if
any executing functions run too long time, more than 5 minutes, identify
them as out of service.

Figure:
Version 1 simple process layout for Periodic Tasks Priority Queue using Thread.Wait()
Version 2
Add software watchdog timeout check
on periodic tasks execution time. When software
threads completed execution of its periodic tasks ,
it reset its software watchdog timer.
When a periodic task execution time too long, exceeded preset watchdog
period, invoke a separate software thread to execute users corrective
action stage 1. If periodic task don't have
corrective action stage 1, put in 'null'.
However, cannot abort the software
thread that still running the timeout task, or else this thread will exit
from threads pool. Maybe hardware timer to stop this software thread from
keep on running the timeout task.
Verifying workability of this code.
MS Visual C# Console App coding: main_v2.cs.txt class_PeriodicTasks_ThreadWaitState_v2.cs.txt class_Simulated_RTC_tick.cs.txt
Circuit to
generate continuously ON-OFF step pulses
Circuit #1:
Construct the circuit using 2 hardware timers ('T1' & 'T2').


Coding
in c# Windows Forms App: myTimer4.zip
Circuit
#1 time graph

Circuit #2:
Construct the circuit using 2 hardware relays ('R1' & 'R2') and 2
hardware timers ('T1' & 'T2').

Circuit
#2 time graph

Topic: Run a Task with Timeout feature using Thread.Sleep()
in c++
Run a task
continuously for a period of time, afterward stop the task. We can view
this as a single step pulse, ON for a preset time period then OFF.
To set timeout
feature for a task, we can use RTC method or Thread.Sleep()
command.
As usual, to run
the Thread.Sleep() command and the task at the
same time, we need to declare the Thread.Sleep()
command in a separate thread.
Declare a Boolean
variable isTimeout (value FALSE), accessible by
both task thread and timeout thread. The task thread will check the isTimeout Boolean variable after end of every task
execution; when timeout, timeout thread set the isTimeout
Boolean variable to TRUE. The task thread will stop executing the task
again if it found the isTimeout Boolean
variable is set to TRUE.
Visual C++ code
A device waiting
for 2nd device to finish a task within a time interval. If 2nd
device completed the task, set the EndOfTask Boolean
variable to TRUE to end the task; or wait till the task timeout.
#include <iostream>
#include <thread>
using namespace std;
static bool isTimeout;
void set_Timeout(int timeout_Period_seconds)
{
isTimeout = false;
std::this_thread::sleep_for(std::chrono::seconds(timeout_Period_seconds));
isTimeout = true; //When timeout, set isTimeout to
true
}
int main()
{
bool EndOfTask = false;
isTimeout = false;
cout << "Curent
device wait for another device to complete a task within a time interval
/ before timeout." << endl;
cout << "If another device complete the task, set EndOfTask
to TRUE OR" << endl;
cout << "If the task exceed the preset time interval or timeout, end the
task" << endl << endl;
cout << "Waiting for another
device to perform task..." << endl;
//Declare a separate thread to run class_Run_Timeout
thread thread_set_Timeout(set_Timeout, 5);
do
{
//Waiting for another device to complete the
task...
} while (!EndOfTask
&& !isTimeout);
// Wait for the threads to finish
thread_set_Timeout.join();
if(isTimeout)
cout << "\n5 seconds timeout
was triggered." << endl;
return 0;
}
|
Reference
Timeout using RTC
method: https://github.com/Edragon/RPI/blob/master/network/SIM7600X/sim7x00.cpp
Simple circuit
to delay a step pulse and latching ON / OFF output
When there are many
electrical devices in an area. we would like to power on them one-by-one,
one at a time. Time gap in between. This is to prevent power-on surge
current trips main circuit breaker. Example are ceiling lamps in the office
building, and etc. Likewise, when power off devices, we also want to power
off them one-by-one. Hence, we use timers to create the time gap. Two
timers, one timer to delay power ON the devices; another timer to delay
power OFF the devices.
We have momentary
buttons & signals. After we press & release power ON button /
signal, we would want the electrical devices to remain power ON until we
press & release power OFF button / signal. Thus, we will have latching
ON / OFF circuit. It can be a market common latching relay.
The above operation
in the time graph will be: input as step pulse (ON / OFF push button or
output buffer), output also a step pulse but time delayed from input.
Duplicate the below
circuit, connect them in series. Each circuit to power ON or OFF a device.
Hence, we achieve our objective of powering ON / OFF many devices
one-by-one, with time gap in between, by press & release a momentary
push button / signal.
Constructs simple circuit using transistors, resistors and capacitors
Using these
electronics components are cheaper than using relays, timers. They are much
smaller size, fast response without mechanical movement. However
its timer time varies, depend on whether capacitors fully discharged.
Momentarily press
button / signal, delay OFF timer circuit
After press &
release momentary button / signal, the output will remain ON for awhile due to the charged capacitor. Capacitor will
slowly discharge until capacitor voltage drop below threshold and
transistor turn OFF. Circuit referred from below website.
https://www.homemade-circuits.com/simple-delay-timer-circuits-explained/
Delay switch ON
timer circuit
After power ON,
output remain OFF for awhile until capacitor
sufficiently charged and output become ON. Circuit referred from below URL:
https://circuitspedia.com/on-delay-timer-circuit-diagram-with-relay/
Link above two
circuits together, input a short step pulse the circuit will output a
delayed step pulse.
Latching circuit
Latches
are circuits that have two stable states. It will remain ON after triggered
ON, even though the input trigger signal is momentary. Vice versa, latches
will remain OFF after input OFF signal.
Latching circuit
using flip-flop: https://0creativeengineering0.blogspot.com/2019/03/what-is-latch.html
Flip-Flop ON/OFF
state is random at initial power-up.

Flip-flop latching transistor circuit
Self-latching
circuit with stabler states, OFF state at initial power-up: http://www.learningaboutelectronics.com/Articles/Latch-circuit-with-transistors.php

self-latch transistor

Circuit #1: ON / OFF latching using flip-flop
circuit

Circuit #2: ON / OFF self-latching circuit
|