1 //
2 // Copyright (c) 2010-2024 Antmicro
3 //
4 // This file is licensed under the MIT License.
5 // Full license text is available in 'licenses/MIT.txt'.
6 //
7 using System.Collections.Generic;
8 using Antmicro.Renode.Core;
9 using Antmicro.Renode.Logging;
10 
11 namespace Antmicro.Renode.Peripherals.Timers
12 {
13     public class PulseGenerator : IPeripheral, INumberedGPIOOutput
14     {
PulseGenerator(IMachine machine, long frequency, ulong onTicks, ulong offTicks, bool startState = false)15         public PulseGenerator(IMachine machine, long frequency, ulong onTicks, ulong offTicks, bool startState = false)
16         {
17             this.startState = startState;
18             this.onTicks = onTicks;
19             this.offTicks = offTicks;
20             Connections = new Dictionary<int, IGPIO> { [0] = Output };
21             timer = new LimitTimer(machine.ClockSource, frequency, this, nameof(timer), enabled: true, eventEnabled: true, autoUpdate: true);
22             timer.LimitReached += () =>
23             {
24                 timer.Limit = state ? offTicks : onTicks;
25                 state = !state;
26                 Output.Set(state);
27                 this.DebugLog("Output set to {0}", state);
28             };
29             Reset();
30         }
31 
Reset()32         public void Reset()
33         {
34             timer.Limit = !startState ? offTicks : onTicks;
35             state = startState;
36             Output.Set(state);
37         }
38 
39         public GPIO Output { get; } = new GPIO();
40 
41         public IReadOnlyDictionary<int, IGPIO> Connections { get; }
42 
43         public bool Enabled
44         {
45             get { return timer.Enabled; }
46             set { timer.Enabled = value; }
47         }
48 
49         public long Frequency
50         {
51             get { return timer.Frequency; }
52             set { timer.Frequency = value; }
53         }
54 
55         private bool state;
56 
57         private readonly bool startState;
58         private readonly ulong onTicks;
59         private readonly ulong offTicks;
60         private readonly LimitTimer timer;
61     }
62 }
63