AM2320 Sensor: CRCs doesn't match, CRC from sensor(0) - go

Note: Code is cross-compiled in windows 10.
Code:
package main
import (
"fmt"
"io"
"log"
"net/http"
aosong "github.com/d2r2/go-aosong"
i2c "github.com/d2r2/go-i2c"
)
const i2CAddress = 0x5c
const i2CBus = 1
// Server struct
type Server struct {
Sensor *aosong.Sensor
I2C *i2c.I2C
}
func main() {
var err error
s := Server{Sensor: aosong.NewSensor(aosong.AM2320)}
s.I2C, err = i2c.NewI2C(i2CAddress, i2CBus)
if err != nil {
log.Printf(err.Error())
}
fmt.Println(s.Sensor.ReadRelativeHumidityAndTemperature(s.I2C))
defer s.I2C.Close()
}
Debug info:
2019-02-12T10:29:19.692 [ i2c] DEBUG Write 3 hex bytes: [030004]
2019-02-12T10:29:19.697 [ i2c] DEBUG Read 8 hex bytes: [0304012500d92045]
2019-02-12T10:29:19.698 [ i2c] DEBUG Read 8 hex bytes: [0000000000000000]
CRCs doesn't match: CRC from sensor(0) != calculated CRC(6912).
Any ideea why the CRC from sensor is 0?
I am able to read the sensor on the same bus with the same address with a python script.
#!/usr/bin/python
import posix
from fcntl import ioctl
import time
class AM2320:
I2C_ADDR = 0x5c
I2C_SLAVE = 0x0703
def __init__(self, i2cbus = 1):
self._i2cbus = i2cbus
#staticmethod
def _calc_crc16(data):
crc = 0xFFFF
for x in data:
crc = crc ^ x
for bit in range(0, 8):
if (crc & 0x0001) == 0x0001:
crc >>= 1
crc ^= 0xA001
else:
crc >>= 1
return crc
#staticmethod
def _combine_bytes(msb, lsb):
return msb << 8 | lsb
def readSensor(self):
fd = posix.open("/dev/i2c-%d" % self._i2cbus, posix.O_RDWR)
ioctl(fd, self.I2C_SLAVE, self.I2C_ADDR)
# wake AM2320 up, goes to sleep to not warm up and affect the humidity sensor
# This write will fail as AM2320 won't ACK this write
try:
posix.write(fd, b'\0x00')
except:
pass
time.sleep(0.001) #Wait at least 0.8ms, at most 3ms
# write at addr 0x03, start reg = 0x00, num regs = 0x04 */
posix.write(fd, b'\x03\x00\x04')
time.sleep(0.0016) #Wait at least 1.5ms for result
# Read out 8 bytes of result data
# Byte 0: Should be Modbus function code 0x03
# Byte 1: Should be number of registers to read (0x04)
# Byte 2: Humidity msb
# Byte 3: Humidity lsb
# Byte 4: Temperature msb
# Byte 5: Temperature lsb
# Byte 6: CRC lsb byte
# Byte 7: CRC msb byte
data = bytearray(posix.read(fd, 8))
# Check data[0] and data[1]
if data[0] != 0x03 or data[1] != 0x04:
raise Exception("First two read bytes are a mismatch")
# CRC check
if self._calc_crc16(data[0:6]) != self._combine_bytes(data[7], data[6]):
raise Exception("CRC failed")
# Temperature resolution is 16Bit,
# temperature highest bit (Bit15) is equal to 1 indicates a
# negative temperature, the temperature highest bit (Bit15)
# is equal to 0 indicates a positive temperature;
# temperature in addition to the most significant bit (Bit14 ~ Bit0)
# indicates the temperature sensor string value.
# Temperature sensor value is a string of 10 times the
# actual temperature value.
temp = self._combine_bytes(data[4], data[5])
if temp & 0x8000:
temp = -(temp & 0x7FFF)
temp /= 10.0
humi = self._combine_bytes(data[2], data[3]) / 10.0
return (temp, humi)
am2320 = AM2320(1)
(t,h) = am2320.readSensor()
print t, h

Seems there was an issue with the library itself which was making two reads, but because the read code was not sent the values came as 0, as it can be seen in the logs:
2019-02-12T10:29:19.692 [ i2c] DEBUG Write 3 hex bytes: [030004]
2019-02-12T10:29:19.697 [ i2c] DEBUG Read 8 hex bytes: [0304012500d92045] (first read that was ignored)
2019-02-12T10:29:19.698 [ i2c] DEBUG Read 8 hex bytes: [0000000000000000] (second one that came a 0)
CRCs doesn't match: CRC from sensor(0) != calculated CRC(6912)
Made a PR to fix the issue: https://github.com/d2r2/go-aosong/pull/3

Related

My OLED display just stays completely white

I am programming an ESP32 with Micropython and Thonny IDE.
I upload the following SSD1306 driver library:
#MicroPython SSD1306 OLED driver, I2C and SPI interfaces created by Adafruit
import time
import framebuf
# register definitions
SET_CONTRAST = const(0x81)
SET_ENTIRE_ON = const(0xa4)
SET_NORM_INV = const(0xa6)
SET_DISP = const(0xae)
SET_MEM_ADDR = const(0x20)
SET_COL_ADDR = const(0x21)
SET_PAGE_ADDR = const(0x22)
SET_DISP_START_LINE = const(0x40)
SET_SEG_REMAP = const(0xa0)
SET_MUX_RATIO = const(0xa8)
SET_COM_OUT_DIR = const(0xc0)
SET_DISP_OFFSET = const(0xd3)
SET_COM_PIN_CFG = const(0xda)
SET_DISP_CLK_DIV = const(0xd5)
SET_PRECHARGE = const(0xd9)
SET_VCOM_DESEL = const(0xdb)
SET_CHARGE_PUMP = const(0x8d)
class SSD1306:
def __init__(self, width, height, external_vcc):
self.width = width
self.height = height
self.external_vcc = external_vcc
self.pages = self.height // 8
# Note the subclass must initialize self.framebuf to a framebuffer.
# This is necessary because the underlying data buffer is different
# between I2C and SPI implementations (I2C needs an extra byte).
self.poweron()
self.init_display()
def init_display(self):
for cmd in (
SET_DISP | 0x00, # off
# address setting
SET_MEM_ADDR, 0x00, # horizontal
# resolution and layout
SET_DISP_START_LINE | 0x00,
SET_SEG_REMAP | 0x01, # column addr 127 mapped to SEG0
SET_MUX_RATIO, self.height - 1,
SET_COM_OUT_DIR | 0x08, # scan from COM[N] to COM0
SET_DISP_OFFSET, 0x00,
SET_COM_PIN_CFG, 0x02 if self.height == 32 else 0x12,
# timing and driving scheme
SET_DISP_CLK_DIV, 0x80,
SET_PRECHARGE, 0x22 if self.external_vcc else 0xf1,
SET_VCOM_DESEL, 0x30, # 0.83*Vcc
# display
SET_CONTRAST, 0xff, # maximum
SET_ENTIRE_ON, # output follows RAM contents
SET_NORM_INV, # not inverted
# charge pump
SET_CHARGE_PUMP, 0x10 if self.external_vcc else 0x14,
SET_DISP | 0x01): # on
self.write_cmd(cmd)
self.fill(0)
self.show()
def poweroff(self):
self.write_cmd(SET_DISP | 0x00)
def contrast(self, contrast):
self.write_cmd(SET_CONTRAST)
self.write_cmd(contrast)
def invert(self, invert):
self.write_cmd(SET_NORM_INV | (invert & 1))
def show(self):
x0 = 0
x1 = self.width - 1
if self.width == 64:
# displays with width of 64 pixels are shifted by 32
x0 += 32
x1 += 32
self.write_cmd(SET_COL_ADDR)
self.write_cmd(x0)
self.write_cmd(x1)
self.write_cmd(SET_PAGE_ADDR)
self.write_cmd(0)
self.write_cmd(self.pages - 1)
self.write_framebuf()
def fill(self, col):
self.framebuf.fill(col)
def pixel(self, x, y, col):
self.framebuf.pixel(x, y, col)
def scroll(self, dx, dy):
self.framebuf.scroll(dx, dy)
def text(self, string, x, y, col=1):
self.framebuf.text(string, x, y, col)
class SSD1306_I2C(SSD1306):
def __init__(self, width, height, i2c, addr=0x3c, external_vcc=False):
self.i2c = i2c
self.addr = addr
self.temp = bytearray(2)
# Add an extra byte to the data buffer to hold an I2C data/command byte
# to use hardware-compatible I2C transactions. A memoryview of the
# buffer is used to mask this byte from the framebuffer operations
# (without a major memory hit as memoryview doesn't copy to a separate
# buffer).
self.buffer = bytearray(((height // 8) * width) + 1)
self.buffer[0] = 0x40 # Set first byte of data buffer to Co=0, D/C=1
self.framebuf = framebuf.FrameBuffer1(memoryview(self.buffer)[1:], width, height)
super().__init__(width, height, external_vcc)
def write_cmd(self, cmd):
self.temp[0] = 0x80 # Co=1, D/C#=0
self.temp[1] = cmd
self.i2c.writeto(self.addr, self.temp)
def write_framebuf(self):
# Blast out the frame buffer using a single I2C transaction to support
# hardware I2C interfaces.
self.i2c.writeto(self.addr, self.buffer)
def poweron(self):
pass
class SSD1306_SPI(SSD1306):
def __init__(self, width, height, spi, dc, res, cs, external_vcc=False):
self.rate = 10 * 1024 * 1024
dc.init(dc.OUT, value=0)
res.init(res.OUT, value=0)
cs.init(cs.OUT, value=1)
self.spi = spi
self.dc = dc
self.res = res
self.cs = cs
self.buffer = bytearray((height // 8) * width)
self.framebuf = framebuf.FrameBuffer1(self.buffer, width, height)
super().__init__(width, height, external_vcc)
def write_cmd(self, cmd):
self.spi.init(baudrate=self.rate, polarity=0, phase=0)
self.cs.high()
self.dc.low()
self.cs.low()
self.spi.write(bytearray([cmd]))
self.cs.high()
def write_framebuf(self):
self.spi.init(baudrate=self.rate, polarity=0, phase=0)
self.cs.high()
self.dc.high()
self.cs.low()
self.spi.write(self.buffer)
self.cs.high()
def poweron(self):
self.res.high()
time.sleep_ms(1)
self.res.low()
time.sleep_ms(10)
self.res.high()
And the following code:
# Complete project details at https://RandomNerdTutorials.com
from machine import Pin, SoftI2C
import ssd1306
from time import sleep
# ESP32 Pin assignment
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
oled.text('Hello, World 1!', 0, 0)
oled.text('Hello, World 2!', 0, 10)
oled.text('Hello, World 3!', 0, 20)
oled.show()
But my OLED display just stays full white, with random pixels.
Display full white
Obs: I am using a 1.3" 128x64 OLED display bought in Aliexpress
Display

ImportError: can't import name InvalidChecksum

in raspberry pi pico board when i tried to connect 3v3 with 3v3 of raspberry pi pico , gnd to gnd of raspberry pi pico and dat to g16 and ran this belo code on thonny micropython .
main temp_hum_DHT_code.py
from machine import Pin
import time
from dht import DHT11, InvalidChecksum
sensor = DHT11(Pin(16, Pin.OUT, Pin.PULL_DOWN))
while True:
temp = sensor.temperature
humidity = sensor.humidity
print("Temperature: {}°C Humidity: {:.0f}% ".format(temp, humidity))
time.sleep(2)
dht.py
import array
import micropython
import utime
from machine import Pin
from micropython import const
class InvalidChecksum(Exception):
pass
class InvalidPulseCount(Exception):
pass
MAX_UNCHANGED = const(100)
MIN_INTERVAL_US = const(200000)
HIGH_LEVEL = const(50)
EXPECTED_PULSES = const(84)
class DHT11:
_temperature: float
_humidity: float
def __init__(self, pin):
self._pin = pin
self._last_measure = utime.ticks_us()
self._temperature = -1
self._humidity = -1
def measure(self):
current_ticks = utime.ticks_us()
if utime.ticks_diff(current_ticks, self._last_measure) < MIN_INTERVAL_US and (
self._temperature > -1 or self._humidity > -1
):
# Less than a second since last read, which is too soon according
# to the datasheet
return
self._send_init_signal()
pulses = self._capture_pulses()
buffer = self._convert_pulses_to_buffer(pulses)
self._verify_checksum(buffer)
self._humidity = buffer[0] + buffer[1] / 10
self._temperature = buffer[2] + buffer[3] / 10
self._last_measure = utime.ticks_us()
#property
def humidity(self):
self.measure()
return self._humidity
#property
def temperature(self):
self.measure()
return self._temperature
def _send_init_signal(self):
self._pin.init(Pin.OUT, Pin.PULL_DOWN)
self._pin.value(1)
utime.sleep_ms(50)
self._pin.value(0)
utime.sleep_ms(18)
#micropython.native
def _capture_pulses(self):
pin = self._pin
pin.init(Pin.IN, Pin.PULL_UP)
val = 1
idx = 0
transitions = bytearray(EXPECTED_PULSES)
unchanged = 0
timestamp = utime.ticks_us()
while unchanged < MAX_UNCHANGED:
if val != pin.value():
if idx >= EXPECTED_PULSES:
raise InvalidPulseCount(
"Got more than {} pulses".format(EXPECTED_PULSES)
)
now = utime.ticks_us()
transitions[idx] = now - timestamp
timestamp = now
idx += 1
val = 1 - val
unchanged = 0
else:
unchanged += 1
pin.init(Pin.OUT, Pin.PULL_DOWN)
if idx != EXPECTED_PULSES:
raise InvalidPulseCount(
"Expected {} but got {} pulses".format(EXPECTED_PULSES, idx)
)
return transitions[4:]
def _convert_pulses_to_buffer(self, pulses):
"""Convert a list of 80 pulses into a 5 byte buffer
The resulting 5 bytes in the buffer will be:
0: Integral relative humidity data
1: Decimal relative humidity data
2: Integral temperature data
3: Decimal temperature data
4: Checksum
"""
# Convert the pulses to 40 bits
binary = 0
for idx in range(0, len(pulses), 2):
binary = binary << 1 | int(pulses[idx] > HIGH_LEVEL)
# Split into 5 bytes
buffer = array.array("B")
for shift in range(4, -1, -1):
buffer.append(binary >> shift * 8 & 0xFF)
return buffer
def _verify_checksum(self, buffer):
# Calculate checksum
checksum = 0
for buf in buffer[0:4]:
checksum += buf
if checksum & 0xFF != buffer[4]:
raise InvalidChecksum()
.............................................................................................................................................................

I cant create correct omron hmi crc code with arduino

Hello I am trying to communicate omron hmi with arduino via modbus rtu. I'm actually just listening the data with arduino so i can analize the data transmition. But when I tried to create its crc I was not able get corrrect crc data. Below there is algorithm and the code I wrote. If anyone know the problem please help me.
Blockquote
Example of CRC-16 Calculation
A message is processed 1 byte at a time in a 16-bit processing register called the CRC register.
1 A default value of FFFF hex is set in the CRC register.
2 An XOR is taken of the contents of the CRC register and the first byte of the message, and the
result is returned to the CRC register.
3 The contents of the CRC register is shifted 1 bit to the right, and 0 is placed in the MSB.
4 If the bit shifted from the LSB is 0, step 3 is repeated (i.e., the contents of the register is shifted
1 more bit).
If the bit shifted from the LSB is 1, an XOR is taken of the contents of the CRC register and
A001 hex, and the result is returned to the CRC register.
5 Steps 3 and 4 are repeated until the contents of the register have been shifted 8 bits to the right.
6 If the end of the message has not been reached, an XOR is taken of the next byte of the
message and the CRC register, the result is returned to the CRC register, and the procedure is
repeated from step 3.
7 The result (the value in the CRC register) is placed in the lower byte of the message.
Example of Appending the Result
If the calculated CRC value is 1234 hex, this is appended as follows to the command frame.
crc=0xFFFF; //A default value of FFFF hex is set in the CRC register.
LSB=0;
cnt=0;
Serial.print("CRC-");
Serial.println(crc,BIN);
for(i=0;i<13;i++)
{
//An XOR is taken of the contents of the CRC register and the first byte of the message, and the
//result is returned to the CRC register.
//If the end of the message has not been reached, an XOR is taken of the next byte of the
//message and the CRC register, the result is returned to the CRC register, and the procedure is
//repeated from step 3.
crc=crc^data[i];
LSB=crc&1;
cnt=0;
while(cnt<8) //Steps 3 and 4 are repeated until the contents of the register have been shifted 8 bits to the right.
{
crc=crc>>1; //The contents of the CRC register is shifted 1 bit to the right, and 0 is placed in the MSB.
crc=crc&0x7fff;
cnt++;
//LSBe=LSB;
LSB=crc&1;
if(cnt==8)break;
Serial.print("LSB-");
Serial.println(LSB,HEX);
// If the bit shifted from the LSB is 0, step 3 is repeated (i.e., the contents of the register is shifted 1 more bit).
//If the bit shifted from the LSB is 1, an XOR is taken of the contents of the CRC register and
//A001 hex, and the result is returned to the CRC register.
if(LSB==0)
{
crc=crc>>1;
crc=crc&0x7fff;
cnt++;
Serial.print("CRC2-");
Serial.println(crc,BIN);
}
else if(LSB==1)
{
crc=crc^operation;
Serial.print("CRC3-");
Serial.println(crc,BIN);
}
}
}
For each byte of data:
crc ^= data[i];
crc = crc & 1 ? (crc >> 1) ^ 0xa001;
crc = crc & 1 ? (crc >> 1) ^ 0xa001;
crc = crc & 1 ? (crc >> 1) ^ 0xa001;
crc = crc & 1 ? (crc >> 1) ^ 0xa001;
crc = crc & 1 ? (crc >> 1) ^ 0xa001;
crc = crc & 1 ? (crc >> 1) ^ 0xa001;
crc = crc & 1 ? (crc >> 1) ^ 0xa001;
crc = crc & 1 ? (crc >> 1) ^ 0xa001;
That is all.

Fast CRC32 algorithm for reversed bit order

I am working with a micro controller which calculates the CRC32 checksum of data I upload to it's flash memory on the fly. This can in turn be used to verify that the upload was correct, by verifying the resulting checksum after all data is uploaded.
The only problem is that the Micro Controller reverses the bit order of the input bytes when it's run through the otherwise standard crc32 calculation. This in turn means I need to reverse every byte in the data on the programming host in order to calculate the CRC32 sum to verify. As the programming host is somewhat constrained, this is quite slow.
I figure that if it's possible to modify the CRC32 lookuptable so I can do the lookup without having to reverse the bit order, the verification algorithm would run many times faster. But I seem unable to figure out a way to do this.
To clarify the byte reversal, I need to change the input bytes following way:
01 02 03 04 -> 80 40 C0 20
It's a lot easier to see the reversal in binary representation of course:
00000001 00000010 00000011 00000100 ->
10000000 01000000 11000000 00100000
Edit
Here is the PoC Python code I use to verify the correctness of the CRC32 calculation, however this reverses each byte (a.e the slow way).
EDIT2
I've also included my failed attempt to generate a permutated lookup table, and using a standard LUT CRC32 algorithm.
The code spits out the correct reference CRC value first, and then the wrong LUT calculated CRC afterwards.
import binascii
CRC32_POLY = 0xEDB88320
def reverse_byte_bits(x):
'''
Reverses the bit order of the giveb byte 'x' and returns the result
'''
x = ((x<<4) & 0xF0)|((x>>4) & 0x0F)
x = ((x<<2) & 0xCC)|((x>>2) & 0x33)
x = ((x<<1) & 0xAA)|((x>>1) & 0x55)
return x
def reverse_bits(ba, blen):
'''
Reverses all bytes in the given array of bytes
'''
bar = bytearray()
for i in range(0, blen):
bar.append(reverse_byte_bits(ba[i]))
return bar
def crc32_reverse(ba):
# Reverse all bits in the
bar = reverse_bits(ba, len(ba))
# Calculate the CRC value
return binascii.crc32(bar)
def gen_crc_table_msb():
crctable = [0] * 256
for i in range(0, 256):
remainder = i
for bit in range(0, 8):
if remainder & 0x1:
remainder = (remainder >> 1) ^ CRC32_POLY
else:
remainder = (remainder >> 1)
# The correct index for the calculated value is the reverse of the index
ix = reverse_byte_bits(i)
crctable[ix] = remainder
return crctable
def crc32_revlut(ba, lut):
crc = 0xFFFFFFFF
for x in ba:
crc = lut[x ^ (crc & 0xFF)] ^ (crc >> 8)
return ~crc
# Reference test which gives the correct CRC
test = bytearray([1, 2, 3, 4, 5, 6, 7, 8])
crcrev = crc32_reverse(test)
print("0x%08X" % (crcrev & 0xFFFFFFFF))
# Test using permutated lookup table, but standard CRC32 LUT algorithm
lut = gen_crc_table_msb()
crctst = crc32_revlut(test, lut)
print("0x%08X" % (crctst & 0xFFFFFFFF))
Does anyone have any hints to how this could be done?
By reversing the logic of which way the crc "streams", the reverse in the main calculation can be avoided. So instead of crc >> 8 there would be crc << 8 and instead of XORing with the bottom byte of the crc for the LUT index we take the top. Like this:
def reverse_dword_bits(x):
'''
Reverses the bit order of the given dword 'x' and returns the result
'''
x = ((x<<16) & 0xFFFF0000)|((x>>16) & 0x0000FFFF)
x = ((x<<8) & 0xFF00FF00)|((x>>8) & 0x00FF00FF)
x = ((x<<4) & 0xF0F0F0F0)|((x>>4) & 0x0F0F0F0F)
x = ((x<<2) & 0xCCCCCCCC)|((x>>2) & 0x33333333)
x = ((x<<1) & 0xAAAAAAAA)|((x>>1) & 0x55555555)
return x
def gen_crc_table_msb():
crctable = [0] * 256
for i in range(0, 256):
remainder = i
for bit in range(0, 8):
if remainder & 0x1:
remainder = (remainder >> 1) ^ CRC32_POLY
else:
remainder = (remainder >> 1)
# The correct index for the calculated value is the reverse of the index
ix = reverse_byte_bits(i)
crctable[ix] = reverse_dword_bits(remainder)
return crctable
def crc32_revlut(ba, lut):
crc = 0xFFFFFFFF
for x in ba:
crc = lut[x ^ (crc >> 24)] ^ ((crc << 8) & 0xFFFFFFFF)
return reverse_dword_bits(~crc)

VB.NET enum declaration syntax

I recently saw a declaration of enum that looks like this:
<Serializable()>
<Flags()>
Public Enum SiteRoles
ADMIN = 10 << 0
REGULAR = 5 << 1
GUEST = 1 << 2
End Enum
I was wondering if someone can explain what does "<<" syntax do or what it is used for? Thank you...
The ENUM has a Flags attribute which means that the values are used as bit flags.
Bit Flags are useful when representing more than one attribute in a variable
These are the flags for a 16 bit (attribute) variable (hope you see the pattern which can continue on to X number of bits., limited by the platform/variable type of course)
BIT1 = 0x1 (1 << 0)
BIT2 = 0x2 (1 << 1)
BIT3 = 0x4 (1 << 2)
BIT4 = 0x8 (1 << 3)
BIT5 = 0x10 (1 << 4)
BIT6 = 0x20 (1 << 5)
BIT7 = 0x40 (1 << 6)
BIT8 = 0x80 (1 << 7)
BIT9 = 0x100 (1 << 8)
BIT10 = 0x200 (1 << 9)
BIT11 = 0x400 (1 << 10)
BIT12 = 0x800 (1 << 11)
BIT13 = 0x1000 (1 << 12)
BIT14 = 0x2000 (1 << 13)
BIT15 = 0x4000 (1 << 14)
BIT16 = 0x8000 (1 << 15)
To set a bit (attribute) you simply use the bitwise or operator:
UInt16 flags;
flags |= BIT1; // set bit (Attribute) 1
flags |= BIT13; // set bit (Attribute) 13
To determine of a bit (attribute) is set you simply use the bitwise and operator:
bool bit1 = (flags & BIT1) > 0; // true;
bool bit13 = (flags & BIT13) > 0; // true;
bool bit16 = (flags & BIT16) > 0; // false;
In your example above, ADMIN and REGULAR are bit number 5 ((10 << 0) and (5 << 1) are the same), and GUEST is bit number 3.
Therefore you could determine the SiteRole by using the bitwise AND operator, as shown above:
UInt32 SiteRole = ...;
IsAdmin = (SiteRole & ADMIN) > 0;
IsRegular = (SiteRole & REGULAR) > 0;
IsGuest = (SiteRole & GUEST) > 0;
Of course, you can also set the SiteRole by using the bitwise OR operator, as shown above:
UInt32 SiteRole = 0x00000000;
SiteRole |= ADMIN;
The real question is why do ADMIN and REGULAR have the same values? Maybe it's a bug.
These are bitwise shift operations. Bitwise shifts are used to transform the integer value of the enum mebers here to a different number. Each enum member will actually have the bit-shifted value. This is probably an obfuscation technique and is the same as setting a fixed integer value for each enum member.
Each integer has a binary reprsentation (like 0111011); bit shifting allows bits to move to the left (<<) or right (>>) depending on which operator is used.
For example:
10 << 0 means:
1010 (10 in binary form) moved with 0 bits left is 1010
5 << 1 means:
101 (5 in binary form) moved one bit to the left = 1010 (added a zero to the right)
so 5 << 1 is 10 (because 1010 represents the number 10)
and etc.
In general the x << y operation can be seen as a fast way to calculate x * Pow(2, y);
You can read this article for more detailed info on bit shifting in .NET http://www.blackwasp.co.uk/CSharpShiftOperators.aspx

Resources