Counter
public final class Counter
The counter class can be used to count the external signal and measure the number of the pulse. It can detect the rising edge or both edges.
Attention
The maximum count value depends on the lowlevel hardware. For example, SwiftIO Board’s counter is 16bit, so the max count value is 65535. If the counter reaches the value, it will overflow and start from 0 again.Example: Read the count value every 10ms
import SwiftIO
// Initiate the counter0.
let counter = Counter(Id.C0)
// Count and print the value every 10ms. Use wait here to get a more precise delay.
while true {
// Clear the counter to set the value to 0.
counter.clear()
wait(us: 10_000)
// Read the value accumulated in 10ms.
let value = counter.read()
print("Conter value = \(value)")
}
or
import SwiftIO
// Initiate the counter0.
let counter = Counter(Id.C0)
// Initialize a timer to set interrupt.
let timer = Timer()
// Use the timer to read and print the value every 10ms.
timer.setInterrupt(ms: 10) {
let value = counter.read()
// Clear the value to to 0.
counter.clear()
print("Conter value = \(value)")
}
while true {
}
-
The maximum count value.
Declaration
Swift
public var maxCountValue: Int { get }
-
Initialize the counter.
Usage Example
let counter = Counter(Id.C0) let counter = Counter(Id.C0, mode: .rising) let counter = Counter(Id.C0, start: false)
Parameters
id
REQUIRED The id of the counter. See the Id enumeration for reference.
mode
OPTIONAL The edge of the external signal to detect, rising edge or both edges.
start
OPTIONAL Whether or not to start the counter after initialization.
-
Change the mode to decide whether it detects the rising edge or both rising and falling edges.
Declaration
Swift
public func setMode(_ mode: Mode)
Parameters
mode
The edge of the external signal to detect, rising edge or both edges.
-
Read the number of edges that has been detected.
Declaration
Swift
@inline(__always) public func read() -> Int
Return Value
Return the number of edges.
-
Start the counter to measure the value.
Declaration
Swift
@inline(__always) public func start()
-
Stop the counter.
Declaration
Swift
@inline(__always) public func stop()
-
Clear the value of counter, it will set the value to 0.
Declaration
Swift
@inline(__always) public func clear()
-
The Mode enumerate is to decide whether the count detects the rising edge or both rising and falling edges.
See moreDeclaration
Swift
public enum Mode : UInt8