1 /*********************************************************************
 2     FileName:           Delay.c
 3     Dependencies:       See #includes
 4     Processor:          PIC32MZ
 5     Hardware:           MainBrain MZ
 6     Complier:           XC32 4.40
 7     Author:             Larry Knight 2023
 8 /*********************************************************************
 9  
10     Software License Agreement:
11  
12     Licensed under the Apache License, Version 2.0 (the "License");
13     you may not use this file except in compliance with the License.
14     You may obtain a copy of the License at
15 
16     http://www.apache.org/licenses/LICENSE-2.0
17 
18     Unless required by applicable law or agreed to in writing, software
19     distributed under the License is distributed on an "AS IS" BASIS,
20     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21     See the License for the specific language governing permissions and
22     limitations under the License.
23  
24     Description:
25         System Clock = 200 - 250 MHz
26 
27     File Description:
28 
29     Change History:
30  
31 /***********************************************************************/
32 
33 #include <xc.h>
34 #include "MainBrain.h"
35 
36 int RTC_delay_counter;
37 
38 void Delay32(uint8_t prescale, uint32_t _delay32)
39 {
40     if (_delay32 == 0)
41     {
42         return;
43     }
44     
45     // Stop timer
46     T4CONbits.ON = 0;
47 
48     // 32-bit mode MUST be enabled before loading PR registers
49     T4CONbits.T32 = 1;
50 
51     // Prescaler
52     T4CONbits.TCKPS = prescale;
53 
54     // Load 32-bit period
55     PR4 = (uint16_t)(_delay32 & 0xFFFF);
56     PR5 = (uint16_t)(_delay32 >> 16);
57 
58     // Clear counters
59     TMR4 = 0;
60     TMR5 = 0;
61 
62     // Clear & enable IRQ
63     IFS0bits.T5IF = 0;
64     IEC0bits.T5IE = 1;    // NECESSARY on PIC32MZ!
65 
66     // Start timer
67     T4CONbits.ON = 1;
68 
69     // Poll until interrupt flag set
70     while (!IFS0bits.T5IF);
71 
72     T4CONbits.ON = 0;
73 }
74 
75 //Seconds delay
76 void LongDelay(int delay_s)
77 {
78     RTC_delay_counter = 0;
79     
80     while(RTC_delay_counter < delay_s)
81     {
82         
83     }
84 }
85