Пример #1
0
def write_reg_raw(reg_num, size_code, value):
    """Write a register, given the size in bytes.
	   If the register represents a fixed-point number,
	   fixedpoint must be true."""
    size, fixedpoint, structcode = interpret_size_code(size_code)
    if not fixedpoint:
        value = int(value)
        data = struct.pack(structcode, value)
    else:
        if value < 0:
            neg = True
            value = -value
        else:
            neg = False
        data = list(struct.pack(
            "<H",
            math.floor(abs(value) * 2**15) & 0xFFFF)) + list(
                struct.pack("<H", math.floor(value)))
        data[1] = (data[2] & 0x01) << 7 | (data[1] & 0x7F)
        data[2] = ((data[2] >> 1) & 0x7F) | (data[3] & 0x01) << 7
        data[3] = (data[3] >> 1) & 0x7F
        if neg:
            data = struct.pack("<L", (~struct.unpack("<L", bytes(data))[0] + 1)
                               & 0xFFFFFFFF)
    buf = bytes([reg_num, 0] + list(data))
    wiringpi.wiringPiSPIDataRW(0, buf[0:size + 2])
Пример #2
0
 def writeRegister(self, address, value):
     address = address | 0x80
     shiftedAddress = address << 8
     sendData = shiftedAddress
     sendData = sendData | value
     a = struct.pack(">H", sendData)
     wiringpi.wiringPiSPIDataRW(self.channel, a)
Пример #3
0
def send_data():
    try:
        last_text_sent = Text.query.filter(last_sent=True).first()
        text_to_send = Text.q

    bytes_to_send = BinaryTextEncoder.serialize(data)
    wiringpi.wiringPiSPIDataRW(0, bytes_to_send)
Пример #4
0
    def runThread(self):
        print("started spi controller")
        self.run = True
        SPIchannel = 0  # SPI Channel (CE0)
        SPIspeed = 1000000  # Clock Speed in Hz
        wiringpi.wiringPiSetupGpio()
        wiringpi.wiringPiSPISetup(SPIchannel, SPIspeed)
        value = 1
        to_send = bytes([value])
        while self.run:
            start = time.time()

            #print(str(self.run))
            #print(str(type(wiringpi.wiringPiSPIDataRW(SPIchannel, to_send)[1])))
            self.data[0] = wiringpi.wiringPiSPIDataRW(SPIchannel, to_send)[1][0]
            self.data[1] = wiringpi.wiringPiSPIDataRW(SPIchannel, to_send)[1][0]
            #print("sent:")
            #print(value)
            # value += 1
            # to_send = [value]
            #print("response:")
            #print(str(self.data))
            #print("Timediff: " + str(time.time() - start))
            self.split(self.data)
            time.sleep(1 / (self.FREQ - (time.time() - start)) + 0.01)
        print("stopped spi controller")
Пример #5
0
def sendData(dataArray, gpios,
             maze):  #dataArray is an array with the data to be send
    """This function will send the data that is entered in an array to the FPGA"""
    gpioOn(gpios)
    isInt = maze

    i = 0
    for x in dataArray:
        if isInt:
            x = x.to_bytes(1, 'big')
        else:
            x = x.to_bytes(2, 'big')
        print("Data", x, "is send")
        copy = x
        print("SEND")
        print(x)  #bytes([x]))

        #  for y in range(2):
        recvData = wiringpi.wiringPiSPIDataRW(SPIchannel, x)  #bytes([x]))
        time.sleep(8 * (1 / SPIspeed))
        recvData = wiringpi.wiringPiSPIDataRW(SPIchannel, x)  #bytes([copy]))
        time.sleep(8 * (1 / SPIspeed))

        print("RECEIVED")
        print(recvData[1])

        i += 1

    gpioOff()
Пример #6
0
 def get_value(self, ch):
     cmd = 0xc0 | (ch << 3)
     buffer = cmd << 16
     buffer = buffer.to_bytes(3, byteorder='big')
     pi.wiringPiSPIDataRW(self.ss, buffer)
     value = (buffer[0] << 16 | buffer[1] << 8 | buffer[2]) >> 7
     return value
Пример #7
0
 def _send_byte(self, mybyte):
     # Sends a byte via the SPI bus
     # Workaround for single-byte transfers due to mutation of immutable
     # function argument. Thanks @JKR
     # wiringPiSPIDataRW() returns a Linux ioctl() error code.
     # We ignore that since we already checked for presence of the file
     # descriptor of the SPI device during initialisation.
     wp.wiringPiSPIDataRW(self.SPI_CHANNEL, "%s" % chr(mybyte & 0xFF))
Пример #8
0
def writeBuf(addr, value, len):
    spibuf = bytearray(256)
    spibuf[0] = addr | 0x80
    for i in range(len):
        spibuf[i + 1] = value[i]
    selectreceiver()
    wp.wiringPiSPIDataRW(CHANNEL, bytes(spibuf))
    unselectreceiver()
Пример #9
0
 def sendCmd(self, register, data):
     buffer = (register << 8) + data
     buffer = buffer.to_bytes(2, byteorder='big')
     if self.DEBUG:
         print("Send byte: 0x%04x" % int.from_bytes(buffer, 'big'))
     wiringpi.wiringPiSPIDataRW(SPI_CS, buffer)
     if self.DEBUG:
         print("Response:  0x%04x" % int.from_bytes(buffer, 'big'))
     return buffer
Пример #10
0
def render():
    while True:
        for i in range(0, 8):
            value = ~matrix[i]
            data[0] = numpy.uint8(value) if red else 255
            data[2] = numpy.uint8(value) if green else 255
            data[1] = numpy.uint8(value) if blue else 255
            data[3] = 0x01 << i
            wiringpi.wiringPiSPIDataRW(0, bytes(data))
Пример #11
0
    def check(self):
        buffer = 0x6800 | (0x1800 * READ_CH)
        buffer = buffer.to_bytes(2, byteorder='big')
        pi.wiringPiSPIDataRW(SPI_CH, buffer)

        value    = (buffer[0] * 256 + buffer[1]) & 0x3ff
        volt     = value * 3.3 / 1034
        distance = self.gp2y0a21(volt)

        return distance
Пример #12
0
def Spi_Set_Gpio(value):
    value = limit(value, 0, 255)
    spi_output = [0, 0, 0, 0]
    spi_device = 0
    spi_output[0] = 0b10101010
    spi_output[1] = 0b00001000
    spi_output[2] = value
    spi_output[3] = 0b10101010
    wiringpi.wiringPiSPIDataRW(spi_device, bytes(spi_output))
    return (0)
Пример #13
0
def Spi_Set_RaspStat(value):
    spi_output = [0, 0, 0, 0]
    spi_device = 0
    spi_output[0] = 0b10101010  # Handshake - begin
    spi_output[1] = 0b10001000  # Command
    spi_output[2] = value
    spi_output[3] = 0b10101010
    byte_string = bytes(spi_output)
    wiringpi.wiringPiSPIDataRW(spi_device, byte_string)
    return (0)
Пример #14
0
    def analogRead(self, channel):
        command = 0xC0 | (channel << 3)
        data = pack('>I', command << 24)

        wpi.wiringPiSPIDataRW(self.spi_ch, data)

        data = map(ord, data)
        value = (data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3]) >> 13

        return value
Пример #15
0
def Spi_Get_Gpio():
    spi_output = [0, 0, 0, 0]
    spi_device = 0
    spi_output[0] = 0b10101010  # Handshake - begin
    spi_output[1] = 0b00001001  # Command
    spi_output[2] = 0b10101010  # readback command
    spi_output[3] = 0b10101010  # read value
    byte_string = bytes(spi_output)
    wiringpi.wiringPiSPIDataRW(spi_device, byte_string)
    time.sleep(0.01)
    return (byte_string[3])
Пример #16
0
  def writeSPIData(self, ledList):
    # 8 Leds each take 9 SPI byes and 1 extra to supress the long initial SPI bit with the OPi
    print(ledList)
    outbytes = [0] * (1 + 8 * 9)
    byte_idx = 1

    for l in ledList:
      outbytes[byte_idx:byte_idx + 8] = self._grbToSpiData(l)
      byte_idx += 9

    wiringpi.wiringPiSPIDataRW(self.spi_port, bytes(outbytes))
Пример #17
0
def Spi_Get_Relays():
    spi_output = [0, 0, 0, 0]
    spi_device = 0
    spi_output[0] = 0b10101010
    spi_output[1] = 0b00010011
    spi_output[2] = 0b10101010
    spi_output[3] = 0b10101010
    byte_string = bytes(spi_output)
    wiringpi.wiringPiSPIDataRW(spi_device, byte_string)
    time.sleep(0.01)
    return (byte_string[3])
Пример #18
0
def Spi_Set_AiControl(value0, value1):
    spi_output = [0, 0, 0, 0, 0]
    spi_device = 0
    spi_output[0] = 0b10101010  # Handshake - begin
    spi_output[1] = 0b10000111  # Command
    spi_output[2] = value0
    spi_output[3] = value1
    spi_output[4] = 0b10101010
    byte_string = bytes(spi_output)
    wiringpi.wiringPiSPIDataRW(spi_device, byte_string)
    return (0)
Пример #19
0
def writeToDisplay(data):
    """   
       Write data to the display
    
    """
    length = len(data)
    if length > DISPLAY_BUF_SZ:
        print "bsp_writeToDisplay: ERROR len=%d > %d" % (length, DISPLAY_BUF_SZ)
        return

    #TODO: can hang here...
    wiringpi.wiringPiSPIDataRW(0, data)
Пример #20
0
def Spi_Set_Servo(channel, value):
    spi_output = [0, 0, 0, 0]
    spi_device = 0
    if channel > 0:
        spi_output[1] = 0b10000001  # Command
    else:
        spi_output[1] = 0b10000000  # Command
    spi_output[0] = 0b10101010  # Handshake - begin
    spi_output[2] = value
    spi_output[3] = 0b10101010
    byte_string = bytes(spi_output)
    wiringpi.wiringPiSPIDataRW(spi_device, byte_string)
    return (0)
Пример #21
0
    def iterate_matrix(self, start=0, end=4):
        """ iterate LEDs on the matrix
        This is a debugging tool and will be removed
        """
        # turn off matrix while the pattern is set
        self.set_brightness(0)

        for num in range(start, end):
            send_byte = chr(2**num)
            wiringpi.wiringPiSPIDataRW(self.channel, send_byte)
            self.brightness_sweep()
            num += 1
        return
Пример #22
0
def Spi_Get_uC_Version():
    spi_output = [0, 0, 0, 0, 0]
    spi_device = 0
    spi_output[0] = 0b10101010  # Handshake - begin
    spi_output[1] = 0b10001001  # Command
    spi_output[2] = 0b00000000  # readback command
    spi_output[3] = 0b00000000  # read value low
    spi_output[4] = 0b00000000  # read value high
    byte_string = bytes(spi_output)
    wiringpi.wiringPiSPIDataRW(spi_device, byte_string)
    time.sleep(0.1)
    high = byte_string[4] << 8
    low = byte_string[3]
    version = high | low
    return (version)
Пример #23
0
def send_1_byte():
    buf = struct.pack('B', address | read_bit)

    retlen, retdata = wiringpi.wiringPiSPIDataRW(SPIChannel, buf)
    #print(buf)

    print(struct.unpack('B', retdata))
Пример #24
0
def send_print_command():
    buf = struct.pack('BB', print_address | write_bit, 1)

    retlen, retdata = wiringpi.wiringPiSPIDataRW(SPIChannel,buf)
    
    return_tuple = struct.unpack('BB',retdata)
    print (return_tuple)
Пример #25
0
def read_reg_raw(reg_num, size_code):
    """Given a register number and size in bytes, read it
	   and return the value (as an int or float).
	   If the register represents a fixed-point number,
	   fixedpoint must be true."""
    size, fixedpoint, structcode = interpret_size_code(size_code)
    buf = bytes([reg_num + 0x80, 0] + [0] * size)
    _, retdata = wiringpi.wiringPiSPIDataRW(0, buf)
    data = list(retdata[2:])
    v = 0
    if not fixedpoint:
        v = struct.unpack(structcode, bytes(data))[0]
    else:
        if data[3] & 0x80:
            neg = True
            data = struct.pack("<L", (~struct.unpack("<L", bytes(data))[0] + 1)
                               & 0xFFFFFFFF)
        else:
            neg = False
        frac = 0
        for b in range(0, 15):
            i = int(b > 7)
            if ((data[0 + i] >> b - (i * 8)) & 0x01) == 1: frac += 2**-(15 - b)
        v += data[1] >> 7
        v += data[2] << 1
        v += (data[3] & 0x7F) << 9
        v += frac
        if neg: v = -v
    return v
Пример #26
0
def on_create(data):
    print("measurement_start")
    it = data['iterations']

    # sound.c -> .py
    for i in range(it):
        wp.digitalWrite(ADC_CS, 1)
        buf = bytearray(3)
        buf[0] = 0x06 | ((ADC_CH_SOUND & 0x04) >> 2)
        buf[1] = ((ADC_CH_SOUND & 0x03) << 6)
        buf[2] = 0x00
        wp.digitalWrite(ADC_CS, 0)
        ret_len, buf = wp.wiringPiSPIDataRW(SPI_CH, bytes(buf))
        buf = bytearray(buf)
        buf[1] = 0x0F & buf[1]
        #value=(buf[1] << 8) | buf[2]
        sound_val = int.from_bytes(bytes(buf), byteorder='big')
        wp.digitalWrite(ADC_CS, 1)
        print("sound value=", sound_val)

        now = datetime.datetime.now()
        time_val = now.strftime("%H:%M:%S")

        socketio.sleep(1)  # 1초 sleep
        emit('msg_from_server', {'soundVal': sound_val, 'timdVal': time_val})
Пример #27
0
 def ReadByte(self):
     """
     Reads a byte from the SPI bus
     :returns: byte read from the bus
     """
     MISObyte = wp.wiringPiSPIDataRW(self.SPI_CHANNEL, chr(0xFF))
     return ord(MISObyte[1])  #JKR
Пример #28
0
 def _read_uint8(self, n_vals=1):
     # Returns tuple containing unsigned 8-bit int interpretation of
     # n_vals bytes read via the SPI bus. n_bytes is supposed to
     n_bytes, data = wp.wiringPiSPIDataRW(self.SPI_CHANNEL,
                                          b"\xFF" * n_vals)
     assert n_bytes == n_vals
     return struct.unpack("{}B".format(n_bytes), data)
Пример #29
0
def L6470_send(add_or_val):
    while (io.digitalRead(BUSY_PIN) == 0):
        pass

    data = struct.pack('B', add_or_val)
    print(data)
    return wp.wiringPiSPIDataRW(L6470_SPI_CHANNEL, data)
Пример #30
0
 def ReadByte(self):
     """
     Reads a byte from the SPI bus
     :returns: byte read from the bus
     """
     byte = wp.wiringPiSPIDataRW(self.SPI_CHANNEL, chr(0x00))
     return byte
Пример #31
0
    def getTemperature(self, device_num):
        device_num &= 0x3
        if wiringpi.digitalRead(self.EXPANDER_BASE_PIN + device_num):
            # Check the presence pin.  If no remote thermocouple connected,
            # this pin will be high.  If it's low, the remote thermocouple 
            # IS connected.
            return None

        spi1 = (device_num & 0x2) >> 1
        spi0 = device_num & 0x1
        with self.lock:
            # Set the SPI1/SPI0 pins
            wiringpi.digitalWrite(24, spi1)
            wiringpi.digitalWrite(24, spi0)
            buf = bytes([0, 0])
            retlen, retdata = wiringpi.wiringPiSPIDataRW(0, buf)

        # 16 bit return data.  bit 15 is a dummy sign bit (always 0)
        # bits 14-3 is 12-bit reading,
        # bit 2 is thermocouple input (high if open),
        # bit 1 is device id (always 0), bit 0 is state (tri-stated)
        if retlen != 2 or (retdata[1] & 0x04):
            logger.info("Bad reading or thermocouple open")
            return None
        
        # readings have a resolution of 0.25C
        reading = (retdata[0] << 5) + (retdata[1] >> 3)
        return float(reading / 4.0)
Пример #32
0
  def _send_instruction(self, instruction):
      wiringpi.wiringPiSPIDataRW(1, instruction + '\n')
    
# Run game
# setup_card_dealer()

# Example round
#
# process_round({
#               'GREEN' : 
#                         {
#                             'WOOD' : 1, 
#                             'BRICK' : 0, 
#                             'IRON' : 0, 
#                             'SHEEP' : 0, 
#                             'WHEAT' : 0
#                         },
#               'BROWN' : 
#                         {
#                             'WOOD' : 1, 
#                             'BRICK' : 1, 
#                             'IRON' : 0, 
#                             'SHEEP' : 0, 
#                             'WHEAT' : 0
#                         },
#               'RED' : 
#                         {
#                             'WOOD' : 1, 
#                             'BRICK' : 1, 
#                             'IRON' : 1, 
#                             'SHEEP' : 0, 
#                             'WHEAT' : 0
#                         },
#               'BLUE' : 
#                         {
#                             'WOOD' : 1, 
#                             'BRICK' : 1, 
#                             'IRON' : 1, 
#                             'SHEEP' : 1, 
#                             'WHEAT' : 0
#                         },
#              })
Пример #33
0
def read_adc(channel):
    adcValue=0
    voltage = 0

    buf = chr(6 | ((channel & 7) >> 7)) + chr((channel & 7) << 6) + chr(0)

    wp.digitalWrite(CS_MCP3208, 0)	#CS(6), False

    len, adcValue = wp.wiringPiSPIDataRW(SPI_CHANNEL, buf)  # receive 3bytes

    wp.digitalWrite(CS_MCP3208, 1)	#CS(6), True

    adcValue=ord(adcValue[1])*256+ord(adcValue[2])

    voltage=adcValue*5.0/4095.0

    return voltage
Пример #34
0
# GPIOを制御するライブラリ
import wiringpi
# タイマーのライブラリ
import time

# MCP3002(半固定抵抗)を接続したチャンネルを指定
SPI_CH = 0

# 読み込み対象のMCP3002(半固定抵抗)のアナログ入力チェンネルを指定
READ_CH = 0

# SPI初期化
wiringpi.wiringPiSPISetup( SPI_CH, 1000000 )

while True:
    # MCP3002(半固定抵抗)に送るデータを作成
    buffer = 0x6800 | ( 0x1800 * READ_CH )
    buffer = buffer.to_bytes( 2, byteorder='big' )
    
    # SPIを使ってCH0の値を取得
    wiringpi.wiringPiSPIDataRW( SPI_CH, buffer )
    # 値が2バイトに分かれて送られるので、1つの値にまとめる
    ch0_value = ( buffer[0] * 256 + buffer[1] ) & 0x3ff
    # 値を電圧に変換
    volt = ch0_value * 3.3 / 1023
    # 0.5秒ごと
    time.sleep(0.5)
    print ("値 :" , ch0_value , " 電圧 :", volt , "V")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(5)
 
while True:
    conn, addr =s.accept()
    to_write =  ctime()+" - connected to: "+ addr[0] + " on port "+str(addr[1])+"\n" 
    with open('connection-log.txt', 'a+') as f:
        f.write(to_write)
    talk=conn.recv(1024)
    to_write = ctime()+" - Message from client: \'"+ talk.decode() + "\'\n" 
    with open('connection-log.txt', 'a+') as f:
        f.write(to_write)
        to_write = ctime()+" - Writing to SPI\n"
        f.write(to_write)
    data = talk
    recv = wiringpi.wiringPiSPIDataRW(0, data)
    to_write = ctime()+" - Received from SPI device: \'"+ str(recv)+ "\'\n" 
    with open('connection-log.txt', 'a+') as f:
        f.write(to_write)
        to_write = ctime()+" - sending response to client: \'"+ str(recv)+ "\'\n"
        f.write(to_write)
    conn.send(str(recv).encode())
    conn.send('End\n'.encode())
    sleep(1)
    conn.close()
    to_write = ctime()+" - connection to "+ addr[0] + " closed\n"
    with open('connection-log.txt', 'a+') as f:
        f.write(to_write)