1 // Copyright 2010-2016 Espressif Systems (Shanghai) PTE LTD
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 #pragma once
15 
16 // This file contains various convenience macros to be used in ULP programs.
17 
18 // Helper macros to calculate bit field width from mask, using the preprocessor.
19 // Used later in READ_RTC_FIELD and WRITE_RTC_FIELD.
20 #define IS_BIT_SET(m, i) (((m) >> (i)) & 1)
21 #define MASK_TO_WIDTH_HELPER1(m, i)  IS_BIT_SET(m, i)
22 #define MASK_TO_WIDTH_HELPER2(m, i)  (MASK_TO_WIDTH_HELPER1(m, i)  + MASK_TO_WIDTH_HELPER1(m, i + 1))
23 #define MASK_TO_WIDTH_HELPER4(m, i)  (MASK_TO_WIDTH_HELPER2(m, i)  + MASK_TO_WIDTH_HELPER2(m, i + 2))
24 #define MASK_TO_WIDTH_HELPER8(m, i)  (MASK_TO_WIDTH_HELPER4(m, i)  + MASK_TO_WIDTH_HELPER4(m, i + 4))
25 #define MASK_TO_WIDTH_HELPER16(m, i) (MASK_TO_WIDTH_HELPER8(m, i)  + MASK_TO_WIDTH_HELPER8(m, i + 8))
26 #define MASK_TO_WIDTH_HELPER32(m, i) (MASK_TO_WIDTH_HELPER16(m, i) + MASK_TO_WIDTH_HELPER16(m, i + 16))
27 
28 // Peripheral register access macros, build around REG_RD and REG_WR instructions.
29 // Registers defined in rtc_cntl_reg.h, rtc_io_reg.h, sens_reg.h, and rtc_i2c_reg.h are usable with these macros.
30 
31 // Read from rtc_reg[low_bit + bit_width - 1 : low_bit] into R0, bit_width <= 16
32 #define READ_RTC_REG(rtc_reg, low_bit, bit_width) \
33     REG_RD (((rtc_reg) - DR_REG_RTCCNTL_BASE) / 4), ((low_bit) + (bit_width) - 1), (low_bit)
34 
35 // Write immediate value into rtc_reg[low_bit + bit_width - 1 : low_bit], bit_width <= 8
36 #define WRITE_RTC_REG(rtc_reg, low_bit, bit_width, value) \
37     REG_WR (((rtc_reg) - DR_REG_RTCCNTL_BASE) / 4), ((low_bit) + (bit_width) - 1), (low_bit), ((value) & 0xff)
38 
39 // Read from a field in rtc_reg into R0, up to 16 bits
40 #define READ_RTC_FIELD(rtc_reg, field) \
41     READ_RTC_REG(rtc_reg, field ## _S, MASK_TO_WIDTH_HELPER16(field ## _V, 0))
42 
43 // Write immediate value into a field in rtc_reg, up to 8 bits
44 #define WRITE_RTC_FIELD(rtc_reg, field, value) \
45     WRITE_RTC_REG(rtc_reg, field ## _S, MASK_TO_WIDTH_HELPER8(field ## _V, 0), ((value) & field ## _V))
46