litex/spi2Csr/tools/uart2Spi.py

65 lines
1.5 KiB
Python
Raw Normal View History

import string
import time
import serial
2012-09-13 07:15:05 -04:00
from struct import *
2012-09-14 06:57:09 -04:00
from migen.fhdl.structure import *
2012-09-13 07:15:05 -04:00
def write_b(uart, data):
uart.write(pack('B',data))
class Uart2Spi:
2012-09-14 18:57:52 -04:00
def __init__(self, port, baudrate, debug = False):
self.port = port
self.baudrate = baudrate
2012-09-14 18:57:52 -04:00
self.debug = debug
2012-09-15 14:13:18 -04:00
self.uart = serial.Serial(port, baudrate, timeout=0.25)
def read(self, addr):
2012-09-15 14:13:18 -04:00
write_b(self.uart, 0x02)
write_b(self.uart, (addr>>8)&0xFF)
write_b(self.uart, (addr&0xFF))
write_b(self.uart, 0x00)
read = self.uart.read()
if self.debug:
print("RD @ %04X" %addr)
2012-09-14 06:57:09 -04:00
return int(read[0])
def read_n(self, addr, n, endianess = "LE"):
r = 0
words = int(2**bits_for(n-1)/8)
for i in range(words):
if endianess == "BE":
r += self.read(addr+i)<<(8*i)
elif endianess == "LE":
r += self.read(addr+words-1-i)<<(8*i)
2012-09-15 14:13:18 -04:00
if self.debug:
print("RD @ %04X" %addr)
2012-09-14 06:57:09 -04:00
return r
2012-09-15 14:13:18 -04:00
def write(self, addr, data):
2012-09-13 07:15:05 -04:00
write_b(self.uart, 0x01)
write_b(self.uart, (addr>>8)&0xFF)
write_b(self.uart, (addr&0xFF))
write_b(self.uart, data)
2012-09-14 18:57:52 -04:00
if self.debug:
print("WR %02X @ %04X" %(data, addr))
2012-09-14 06:57:09 -04:00
def write_n(self, addr, data, n, endianess = "LE"):
words = int(2**bits_for(n-1)/8)
for i in range(words):
if endianess == "BE":
self.write(addr+i, (data>>(8*i)) & 0xFF)
elif endianess == "LE":
self.write(addr+words-1-i, (data>>(8*i)) & 0xFF)
2012-09-14 18:57:52 -04:00
if self.debug:
print("WR %08X @ %04X" %(data, addr))
def main():
csr = Uart2Spi(1,115200)
for i in range(100):
csr.write(0x0000,i)
print(csr.read(0x0000))
if __name__ == '__main__':
main()