avr-something

Something something AVR side…
git clone git://henryandlizzy.uk/avr-something
Log | Files | Refs | README

utils.h (1860B)


      1 #pragma once
      2 #include <inttypes.h>
      3 
      4 template <typename T = uint8_t>
      5 constexpr T volatile& memory(const uintptr_t addr)
      6 {
      7 	return *reinterpret_cast<T*>(addr);
      8 }
      9 
     10 inline constexpr uint8_t bit(const uint8_t shift)
     11 {
     12 //	static_assert(8 > shift, "must be in range (0, 7)");
     13 	return uint8_t(1) << shift;
     14 }
     15 
     16 inline constexpr uint8_t bits()
     17 {
     18 	return 0;
     19 }
     20 
     21 template <typename...Ts>
     22 inline constexpr uint8_t bits(const uint8_t shift, Ts... others)
     23 {
     24 //	static_assert(8 > shift, "must be in range (0, 7)");
     25 	return bit(shift) | bits(others...);
     26 }
     27 
     28 inline constexpr uint16_t wbit(const uint8_t shift)
     29 {
     30 //	static_assert(8 > shift, "must be in range (0, 7)");
     31 	return uint8_t(1) << shift;
     32 }
     33 
     34 inline constexpr uint8_t mix(const uint8_t a, const uint8_t b, const uint8_t mask)
     35 {
     36 	return (a & ~mask) | (b & mask);
     37 }
     38 
     39 template <typename T>
     40 struct flashPtr
     41 {
     42 	static_assert(sizeof(T) == 1, "flashPtr operates on single bytes");
     43 	
     44 	constexpr flashPtr(T const* const p)
     45 	:	ptr(p)
     46 	{}
     47 	template <uint16_t S>
     48 	constexpr flashPtr(const T(& a)[S])
     49 	:	ptr(static_cast<T const*>(a))
     50 	{}
     51 	
     52 	T load() const
     53 	{
     54 		T result;
     55 		asm volatile
     56 		(
     57 			"lpm %0, Z"
     58 
     59 			: "=r" (result)
     60 			: "z" (ptr)
     61 		);
     62 		return result;
     63 	}
     64 	T load_post_inc()
     65 	{
     66 		T result;
     67 		asm volatile
     68 		(
     69 			"lpm %0, Z+"
     70 
     71 			: "=r" (result), "=z" (ptr)
     72 			: "1" (ptr)
     73 		);
     74 		return result;
     75 	}
     76 	constexpr flashPtr& operator ++()
     77 	{
     78 		++ptr;
     79 		return *this;
     80 	}
     81 	constexpr flashPtr& operator --()
     82 	{
     83 		--ptr;
     84 		return *this;
     85 	}
     86 	constexpr flashPtr operator +(const uint16_t delta) const
     87 	{
     88 		return flashPtr(ptr + delta);
     89 	}
     90 	constexpr flashPtr operator -(const uint16_t delta) const
     91 	{
     92 		return flashPtr(ptr - delta);
     93 	}
     94 	constexpr bool operator !=(const flashPtr& that) const
     95 	{
     96 		return ptr != that.ptr;
     97 	}
     98 
     99 	static_assert(sizeof(uint16_t) == sizeof(T const *), "Flash ptr should be a word");
    100 
    101 private:
    102 	T const* ptr;
    103 };
    104 
    105