本帖最后由 hotpower 于 2011-5-13 00:42 编辑
附上模板的实现代码,有点乱哈
template<uint32_t clk, uint32_t baudRate, uint32_t div,
bool error_stop = !(div < 16)>
class BaudRateT2
{
private:
enum
{
condition = (((clk / baudRate) % (div + 1)) < 3)
};
typedef BaudRateT2<clk, baudRate, div + 1> next_type;
public:
enum
{
error = error_stop,
DIV_X_EN = 1,
DIV_X_ONE = 0,
DIVIDER_X = (condition ? div
: next_type:IVIDER_X),
BRD = (condition? (clk / baudRate / (div + 1) - 2)
: next_type::BRD)
};
};
template<uint32_t clk, uint32_t baudRate, uint32_t div>
class BaudRateT2<clk, baudRate, div, true>
{
public:
enum
{
error = true,
DIV_X_EN = 0,
DIV_X_ONE = 0,
DIVIDER_X = 0,
BRD = 0
};
};
template<uint32_t clk, uint32_t baudRate>
class BaudRateT1
{
private:
enum
{
condition = !(clk / baudRate - 2 > 0xFFFF)
};
typedef BaudRateT2<clk, baudRate, 8> next_type;
public:
enum
{
error = (condition ? 0
: next_type::error),
DIV_X_EN = (condition ? 1
: next_type:IV_X_EN),
DIV_X_ONE = (condition ? 1
: next_type:IV_X_ONE),
DIVIDER_X = (condition ? 0
: next_type:IVIDER_X),
BRD = (condition ? (clk / baudRate - 2)
: next_type::BRD)
};
};
template<uint32_t clk, uint32_t baudRate>
class BaudRateT0
{
private:
enum
{
condition = ((clk / baudRate) % 16 < 3)
};
typedef BaudRateT1<clk, baudRate> next_type;
public:
enum
{
error = (condition ? 0
: next_type::error),
DIV_X_EN = (condition ? 0
: next_type:IV_X_EN),
DIV_X_ONE = (condition ? 0
: next_type:IV_X_ONE),
DIVIDER_X = (condition ? 0
: next_type:IVIDER_X),
BRD = (condition ? (clk / baudRate/16 - 2)
: next_type::BRD)
};
};
template<uint32_t clk, uint32_t baudRate>
class BaudRateT
{
private:
typedef BaudRateT0<clk, baudRate> next_type;
public:
enum
{
error = next_type::error,
DIV_X_EN = next_type:IV_X_EN,
DIV_X_ONE = next_type:IV_X_ONE,
DIVIDER_X = next_type:IVIDER_X,
BRD = next_type::BRD,
REG_VALUE = ((uint32_t)BRD)
+ ((uint32_t)DIVIDER_X << 24)
+ ((uint32_t)DIV_X_ONE << 28)
+ ((uint32_t)DIV_X_EN << 29)
};
};
X-Hawk
X-Hawk |