├── descriptors.strings ├── .gitignore ├── bitbang ├── pins.py ├── calling.py ├── i2c.py ├── mpsse.py ├── bitbang.md ├── cycles.py ├── cycles.md └── software.py ├── docs ├── README.md ├── tiao.md └── pipistrello.md ├── descriptors.h ├── MODES.md ├── README.md ├── descriptors_string_table.py ├── Makefile ├── descriptors.c ├── libftdi.h └── LICENSE /descriptors.strings: -------------------------------------------------------------------------------- 1 | TimVideos 2 | FTDI Emulation using FX2 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.asm 2 | *.rel 3 | *.lst 4 | *.sym 5 | *.adb 6 | *.cdb 7 | *.ihx 8 | *.bix 9 | *.rst 10 | *.mem 11 | *.map 12 | *.lnk 13 | *.kpf 14 | *.swp 15 | *.iic 16 | *.lk 17 | docs/html 18 | build 19 | *_str.c 20 | bitbang/mpsse.c 21 | bitbang/i2c.c 22 | descriptors_strings.h 23 | descriptors_strings.inc 24 | -------------------------------------------------------------------------------- /bitbang/pins.py: -------------------------------------------------------------------------------- 1 | """ 2 | Class for abstracting FX2 IO pins 3 | """ 4 | 5 | from enum import Enum 6 | 7 | 8 | class PinDirection(Enum): 9 | output = 'out' 10 | input = 'in' 11 | high_impedance = input 12 | bidirectional = 'bidir' 13 | 14 | 15 | class Pin(object): 16 | def __init__(self, port, index): 17 | assert port in "ABCDE", port 18 | assert 0 <= index <= 7, index 19 | self.port = port 20 | self.index = index 21 | 22 | self.port_name = 'IO%s' % port 23 | self.output_name = 'OE%s' % port 24 | 25 | if self.bit_accessible: 26 | self.bit_name = 'P%s%i' % (port, index) 27 | 28 | @property 29 | def bit_accessible(self): 30 | return self.port != "E" 31 | 32 | @property 33 | def mask(self): 34 | return (1 << self.index) 35 | 36 | @property 37 | def nask(self): 38 | return ~(1 << self.index) & 0xff 39 | 40 | -------------------------------------------------------------------------------- /bitbang/calling.py: -------------------------------------------------------------------------------- 1 | """ 2 | Generate functions for the sdcc calling convention. 3 | """ 4 | 5 | import software 6 | 7 | def generate(name, read_on, write_on, body): 8 | 9 | defs = '' 10 | args = '' 11 | 12 | if write_on != software.ShiftOp.ClockMode.none: 13 | args = 'BYTE data' 14 | defs = """ 15 | (data); 16 | __asm__("mov a,dpl"); /* Move arg0->a */ 17 | """ 18 | else: 19 | args = '' 20 | 21 | if read_on != software.ShiftOp.ClockMode.none: 22 | if write_on == software.ShiftOp.ClockMode.none: 23 | defs += """ 24 | __asm__("clr a"); /* Get accumulator ready */ 25 | """ 26 | 27 | rettype = 'BYTE' 28 | ret = """ 29 | __asm__("mov dpl,a"); /* Move a->retvalue */ 30 | return; /* return */ 31 | """ 32 | else: 33 | rettype = 'void' 34 | ret = 'return;' 35 | 36 | output = "\n ".join(body) 37 | 38 | return """\ 39 | /* ---------------------------- */ 40 | %(rettype)s %(name)s(%(args)s) { 41 | %(defs)s 42 | %(output)s 43 | %(ret)s 44 | } 45 | /* ---------------------------- */ 46 | """ % locals() 47 | 48 | -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 | 2 | ## Drivers / Users 3 | 4 | These are the tools that are likely to be used for communicating with FTDI devices; 5 | 6 | * [libftdi from intra2net](http://www.intra2net.com/en/developer/libftdi/) 7 | * [FTDI serial driver in Linux Kernel](http://lxr.free-electrons.com/source/drivers/usb/serial/ftdi_sio.c) 8 | * [OpenOCD ftdi driver](http://repo.or.cz/openocd.git/blob/HEAD:/src/jtag/drivers/ftdi.c) 9 | 10 | 11 | ## Protocol Documents 12 | 13 | * My [Emulation of FTDI using FX2 Doc](https://docs.google.com/document/d/1o4jDru_V9IBvkkuhyQb1zBzm_QvzDBo2B5adP2bvahY/edit#) 14 | * [AN2232C-01 Command Processor for MPSSE and MCU Host Bus Emulation Modes](http://www.ftdichip.com/Support/Documents/AppNotes/AN2232C-01_MPSSE_Cmnd.pdf) 15 | 16 | ## Devices 17 | 18 | * [Pipistrello Docs](http://pipistrello.saanlima.com/index.php?title=Welcome_to_Pipistrello) 19 | * [Tiao Docs](http://www.tiaowiki.com/w/JTAG_Tutorials) 20 | 21 | ## Tools 22 | 23 | * [SDCC](http://www.tiaowiki.com/w/JTAG_Tutorials) 24 | * [EZ-USB FX2 Technical Reference Manual](http://www.cypress.com/file/126446/download) 25 | -------------------------------------------------------------------------------- /descriptors.h: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | #include "descriptors_strings.h" 5 | 6 | #include 7 | #include 8 | #include 9 | 10 | #ifndef DESCRIPTORS_H_ 11 | #define DESCRIPTORS_H_ 12 | 13 | #define PID 0x8a98 14 | #define DID 7 15 | 16 | struct usb_descriptors { 17 | struct usb_device_descriptor device; 18 | struct usb_section { 19 | struct usb_config_descriptor config; 20 | struct usb_interface_descriptor interface0; 21 | struct usb_endpoint_descriptor endpoints0[2]; 22 | struct usb_interface_descriptor interface1; 23 | struct usb_endpoint_descriptor endpoints1[2]; 24 | } highspeed; 25 | struct usb_qualifier_descriptor qualifier; 26 | WORD fullspeed; 27 | struct usb_descriptors_strings strings; 28 | }; 29 | 30 | __xdata __at(DSCR_AREA) struct usb_descriptors descriptors; 31 | 32 | __code __at(DSCR_AREA+offsetof(struct usb_descriptors, device)) WORD dev_dscr; 33 | __code __at(DSCR_AREA+offsetof(struct usb_descriptors, qualifier)) WORD dev_qual_dscr; 34 | __code __at(DSCR_AREA+offsetof(struct usb_descriptors, highspeed)) WORD highspd_dscr; 35 | __code __at(DSCR_AREA+offsetof(struct usb_descriptors, fullspeed)) WORD fullspd_dscr; 36 | __code __at(DSCR_AREA+offsetof(struct usb_descriptors, strings)) WORD dev_strings; 37 | 38 | #endif // DESCRIPTORS_H_ 39 | -------------------------------------------------------------------------------- /MODES.md: -------------------------------------------------------------------------------- 1 | 2 | ## UART Modes 3 | 4 | * TXD 5 | * RXD 6 | 7 | The following pins are optional; 8 | 9 | * RTS - Ready to Send (handshake output) 10 | * CTS - Clear to Send (handshake input) 11 | * DTR - Data Transmit Ready (modem signalling) 12 | * DSR - Data Carrier Detect (modem signalling) 13 | * RI - Ring indicator (modem signalling) 14 | * TXDEN - Enable TX (RS485) 15 | * RXLED - Receive LED 16 | * TXLED - Transmit LED 17 | 18 | If using a 100 pin FX2 or greater, the TXD/RXD can be mapped to the hardware 19 | UART for increased performance. Otherwise the signals need to be bit banged. 20 | 21 | The optional signals all need to be bit banged. 22 | 23 | ## FIFO Modes 24 | 25 | * Data[7..0] 26 | * FIFO Not Empty 27 | * FIFO Full 28 | * Read data 29 | * Write data 30 | * Wakeup 31 | * Output Enable 32 | * Address Bit (only for CPU FIFO) 33 | 34 | If the mapping is correct, the FX2 can use the "Slave FIFO" or GPFIF mode which 35 | dramatically increases performance. 36 | 37 | Otherwise the FIFO mode is emulated by the CPU -- this is slow. 38 | 39 | ## MPSSE Modes - JTAG, SPI 40 | 41 | * Clock 42 | * Out 43 | * In 44 | * Extra 45 | 46 | If using a 100 pin FX2 or greater, the Clock/Out/In can be mapped to the 47 | hardware UART for increased performance. Otherwise the signals need to be bit 48 | banged. 49 | 50 | 51 | # Bit Banging Modes 52 | 53 | There are two different bit banging modes; 54 | 55 | * Bit operations - These use the 8051 bit set / bit clear / bit test operations. 56 | * Byte operations - This is used when the pins are on Port E, which isn't compatible with the bit set operations. 57 | 58 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # This repo is a **WIP** 2 | 3 | This repository is a **WIP** and currently does **not** work. I would love 4 | contributions to make it work. 5 | 6 | This repository aims to contains firmware for the [Cypress FX2]() which enables 7 | it to emulate much of the behaviour of the [FTDI serial converter chips](). 8 | 9 | The primary purpose of this firmware is to enable the usage of the FX2 as a USB 10 | [JTAG programmer]() with many popular existing tools. 11 | 12 | The emulation has been created based on how two primary boards operate, both 13 | which have the FTDI FT2232H chip on them. 14 | 15 | * [Pipistrello](http://pipistrello.saanlima.com/index.php?title=Welcome_to_Pipistrello) 16 | * [TIAO USB Multi-Protocol Adapter (JTAG, SPI, I2C, Serial)](http://www.diygadget.com/tiao-usb-multi-protocol-adapter-jtag-spi-i2c-serial.html) 17 | 18 | The secondary purpose is to allow easy interfacing to many common FPGA systems. 19 | 20 | The firmware also aims to provide a common interface to both FX2 hardware and 21 | optimised bit banging routines. 22 | 23 | The boards supported are; 24 | 25 | * Digilent Atlys 26 | * Numato Opsis 27 | 28 | * TODO: More? Should be able to support everything in ixo-usb-jtag. 29 | * TODO: Xilinx Platform Cable 30 | 31 | The tools which have currently been tested are; 32 | 33 | * TODO: xc3sprogs 34 | * TODO: urjtag 35 | * TODO: OpenOCD 36 | 37 | * TODO: More? Should be able supported by everything that also supports the 38 | [TIAO USB Multi-Protocol Adapter (JTAG, SPI, I2C, Serial)](http://www.tiaowiki.com/w/JTAG_Tutorials) 39 | 40 | 41 | # Third Party 42 | 43 | * `libftdi.h` comes from http://www.intra2net.com/en/developer/libftdi/ 44 | * `ftdi_sio.h` and `ftdi_sio_ids.h` comes from Linux Kernel 45 | 46 | -------------------------------------------------------------------------------- /descriptors_string_table.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import sys 4 | 5 | import subprocess 6 | git_id = subprocess.check_output("git describe --dirty --long", shell=True).strip().decode('utf-8') 7 | serialno = '0123456789abcdef ' + git_id 8 | 9 | strings = [x.strip() for x in sys.stdin.readlines()]+[serialno] 10 | 11 | if sys.argv[1] == "--header": 12 | print("""\ 13 | // This is an auto-generated file! 14 | #include 15 | #include 16 | 17 | #ifndef DESCRIPTORS_STRING_TABLE_H_ 18 | #define DESCRIPTORS_STRING_TABLE_H_ 19 | 20 | #define USB_STRING_SERIAL_INDEX USB_STRING_INDEX(%i) 21 | 22 | struct usb_descriptors_strings { 23 | struct usb_string_lang { 24 | __u8 bLength; 25 | __u8 bDescriptorType; 26 | __le16 wData[1]; 27 | } language;""" % (len(strings)-1,)) 28 | for i, string in enumerate(strings): 29 | print("""\ 30 | struct usb_string_%(i)i { 31 | __u8 bLength; 32 | __u8 bDescriptorType; 33 | __le16 wData[%(l)i]; 34 | } string%(i)i;""" % {'l': len(string), 'i': i}) 35 | print("""\ 36 | }; 37 | 38 | #endif // DESCRIPTORS_STRING_TABLE_H_ 39 | """) 40 | 41 | if sys.argv[1] == "--cfile": 42 | print("""\ 43 | .strings = { 44 | // English language header 45 | .language = { 46 | .bLength = sizeof(struct usb_string_lang), 47 | .bDescriptorType = USB_DT_STRING, 48 | .wData = { 0x0409 }, // 0x0409 is English 49 | },""") 50 | for i, string in enumerate(strings): 51 | d = ["((__le16)('%s'))" % s for s in string] 52 | 53 | print("""\ 54 | // "%(s)s" 55 | .string%(i)i = { 56 | .bLength = sizeof(struct usb_string_%(i)i), 57 | .bDescriptorType = USB_DT_STRING, 58 | .wData = {%(d)s}, 59 | },""" % { 60 | 's': string, 61 | 'i': i, 62 | 'l': len(string), 63 | 'd': ", ".join(d), 64 | }) 65 | print("""\ 66 | }, 67 | """) 68 | -------------------------------------------------------------------------------- /bitbang/i2c.py: -------------------------------------------------------------------------------- 1 | """ 2 | Efficient i2c operation in bitbanging software. 3 | """ 4 | 5 | import pins 6 | import software as sw 7 | import calling 8 | 9 | # Create the shift byte commands 10 | clock = sw.BitAccessInASM("i2c_clk", pins.Pin("A", 5), pins.PinDirection.output) 11 | data = sw.BitAccessInASM("i2c_dat", pins.Pin("A", 3), pins.PinDirection.bidirectional) 12 | 13 | byte_shifter = sw.ShiftByte(clock, data, data) 14 | 15 | print("""\ 16 | /* Generated file from mpsse.py */ 17 | 18 | #include "fx2regs.h" 19 | #include "fx2types.h" 20 | 21 | """) 22 | print(clock.defines()) 23 | print(data.defines()) 24 | print(""" 25 | 26 | """) 27 | 28 | # i2c, you write on negative edge, read on the positive edge 29 | # sda ▔▔▔▔\___XXXX--b0--XXXX--b1-- ... 30 | # clk ▔▔▔▔▔▔▔\____/▔▔▔▔\____/▔▔▔▔\ ... 31 | #read_on=sw.ShiftOp.ClockMode.positive, 32 | read_on = sw.ShiftOp.ClockMode.none 33 | write_on = sw.ShiftOp.ClockMode.negative 34 | 35 | body = [] 36 | 37 | body += ["/* Start bit */"] 38 | body += data.setup(pins.PinDirection.output).splitlines() 39 | body += data.clear().splitlines() 40 | 41 | body += ["/* Byte shift */"] 42 | body += byte_shifter.generate( 43 | direction=sw.ShiftOp.FirstBit.MSB, 44 | read_on=read_on, 45 | write_on=write_on, 46 | pad=True) 47 | 48 | body += ["/* Ack / Stop Bit */"] 49 | body += clock.clear().splitlines() 50 | body += data.setup(pins.PinDirection.input).splitlines() 51 | body += clock.set().splitlines() 52 | # If carry is 1, then the bit was nacked 53 | body += data.bit_to_carry().splitlines() 54 | body += ["/* JC nacked */"] 55 | # Loop here while bit is 0, clock stretching 56 | body += data.bit_to_carry().splitlines() 57 | body += ["/* JNC rel - */"] 58 | # Success! 59 | body += ["/* Success */"] 60 | # Failure 61 | body += ["/* Nacked response... */"] 62 | 63 | print(calling.generate( 64 | name="i2cTest", 65 | read_on=read_on, 66 | write_on=write_on, 67 | body=body)) 68 | 69 | print("""\ 70 | BYTE main() { 71 | BYTE data = 0xaa; 72 | i2cTest(data); 73 | return 1; 74 | } 75 | """) 76 | -------------------------------------------------------------------------------- /bitbang/mpsse.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Generate the shift functions needed by the MPSSE module. 4 | 5 | Bytes || Bits 6 | (MSB || LSB) First 7 | Out on (+ve || -ve) 8 | In on (+ve || -ve) 9 | 10 | """ 11 | 12 | import pins 13 | import software as sw 14 | import calling 15 | 16 | # Create the shift byte commands 17 | clock = sw.BitAccessInASM("clk", pins.Pin("A", 5), pins.PinDirection.output) 18 | data_in = sw.BitAccessInASM("din", pins.Pin("A", 3), pins.PinDirection.input) 19 | data_out = sw.BitAccessInASM("dout", pins.Pin("A", 2), pins.PinDirection.output) 20 | 21 | byte_shifter = sw.ShiftByte(clock, data_in, data_out) 22 | 23 | combos = [] 24 | for d in sw.ShiftOp.FirstBit: 25 | for read_on in sw.ShiftOp.ClockMode: 26 | for write_on in sw.ShiftOp.ClockMode: 27 | if read_on == sw.ShiftOp.ClockMode.none and write_on == sw.ShiftOp.ClockMode.none: 28 | continue 29 | combos.append((d, read_on, write_on)) 30 | 31 | print("""\ 32 | /* Generated file from mpsse.py */ 33 | 34 | #include "fx2regs.h" 35 | #include "fx2types.h" 36 | 37 | """) 38 | print(clock.defines()) 39 | print(data_in.defines()) 40 | print(data_out.defines()) 41 | print(""" 42 | 43 | """) 44 | 45 | for d, read_on, write_on in combos: 46 | name = ["ShiftByte"] 47 | if d == sw.ShiftOp.FirstBit.MSB: 48 | name.append("MSBFirst") 49 | elif d == sw.ShiftOp.FirstBit.LSB: 50 | name.append("LSBFirst") 51 | 52 | if read_on == sw.ShiftOp.ClockMode.positive: 53 | name.append("inOnPos") 54 | elif read_on == sw.ShiftOp.ClockMode.negative: 55 | name.append("inOnNeg") 56 | if write_on == sw.ShiftOp.ClockMode.positive: 57 | name.append("outOnPos") 58 | elif write_on == sw.ShiftOp.ClockMode.negative: 59 | name.append("outOnNeg") 60 | name = "_".join(name) 61 | 62 | body = byte_shifter.generate(d, read_on, write_on) 63 | 64 | print(calling.generate( 65 | name=name, 66 | read_on=read_on, 67 | write_on=write_on, 68 | body=body)) 69 | 70 | print("""\ 71 | BYTE main() { 72 | BYTE data = 0xaa; 73 | 74 | data = ShiftByte_MSBFirst_inOnPos_outOnPos(data); 75 | data = ShiftByte_MSBFirst_inOnPos_outOnPos(data); 76 | data = ShiftByte_MSBFirst_inOnPos_outOnPos(data); 77 | return data; 78 | } 79 | """) 80 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | 2 | TARGET := ftdi 3 | FX2LIBDIR := ./fx2lib 4 | LIBS := $(FX2LIBDIR)/lib/fx2.lib 5 | INCS := -I$(FX2LIBDIR)/include 6 | 7 | CC_SRCS := descriptors.c #bitbang/mpsse.c bitbang/i2c.c 8 | CC_OBJS := $(CC_SRCS:%.c=%.rel) 9 | 10 | CC := sdcc 11 | 12 | # Compiler options 13 | CSTD=c99 14 | CFLAGS += --verbose --std-$(CSTD) -mmcs51 -Wa"-p" 15 | # Where to put things in the memory 16 | CFLAGS += --code-size 0x3e00 --xram-size 0x0200 -DDSCR_AREA=0x2e00 -Wl"-b INT2JT=0x3f00" 17 | 18 | # Use make V=1 for a verbose build. 19 | ifndef V 20 | Q_CC=@echo ' CC ' $@; 21 | Q_AS=@echo ' AS ' $@; 22 | Q_LINK=@echo ' LINK ' $@; 23 | Q_RM=@echo ' CLEAN '; 24 | Q_OBJCOPY=@echo ' OBJCOPY ' $@; 25 | Q_GEN=@echo ' GEN ' $@; 26 | endif 27 | 28 | .PHONY: all clean check check_int2jt 29 | 30 | all: $(TARGET).hex 31 | 32 | $(CC_SRCS): $(FX2LIBDIR)/lib/fx2.lib 33 | 34 | $(FX2LIBDIR)/.git: 35 | git submodule init $@ 36 | git submodule update --recursive $@ 37 | 38 | $(FX2LIBDIR)/lib/fx2.lib: $(FX2LIBDIR)/.git 39 | cd $(dir $@) && make -j1 40 | 41 | $(TARGET).hex: $(CC_OBJS) 42 | $(Q_LINK)$(CC) $(CFLAGS) -o $@ $+ $(LIBS) 43 | 44 | %.rel: %.c 45 | $(Q_CC)$(CC) $(CFLAGS) -c $(INCS) $? 46 | 47 | %.asm: %.c 48 | $(Q_CC)$(CC) $(CFLAGS) -c $(INCS) $? 49 | 50 | # Generate the bit banging code 51 | bitbang/mpsse.c: bitbang/*.py 52 | cd bitbang; python3 mpsse.py > mpsse.c 53 | 54 | bitbang/i2c.c: bitbang/*.py 55 | cd bitbang; python3 i2c.py > i2c.c 56 | 57 | # Generate the descriptor strings 58 | descriptors_strings.h: descriptors_string_table.py descriptors.strings 59 | python3 descriptors_string_table.py --header < descriptors.strings > descriptors_strings.h 60 | descriptors_strings.inc: descriptors_string_table.py descriptors.strings 61 | python3 descriptors_string_table.py --cfile < descriptors.strings > descriptors_strings.inc 62 | 63 | descriptors.c: descriptors_strings.h descriptors_strings.inc 64 | 65 | # Check the descriptors with GCC rather then sdcc 66 | check_descriptors: descriptors.c 67 | gcc -std=$(CSTD) -Wall -Werror $(INCS) descriptors.c 68 | @rm -f a.out 69 | 70 | # Check that the interrupt vector table ended up were we asked it too. 71 | check_int2jt: $(TARGET).hex 72 | @export REQUESTED=$(shell grep "INT2JT=" $(TARGET).map | sed -e's/INT2JT=//'); \ 73 | export ACTUAL=$(shell grep "C:.*INT2JT" $(TARGET).map | sed -e's/C: *0*\([^ ]*\) _INT2JT.*/0x\1/' | tr A-Z a-z ); \ 74 | if [ "$$REQUESTED" != "$$ACTUAL" ]; then \ 75 | echo "INT2JT at $$ACTUAL but requested $$REQUESTED"; \ 76 | exit 1; \ 77 | fi 78 | 79 | check: check_int2jt check_descriptors 80 | 81 | clean: 82 | $(Q_RM)$(RM) *.iic *.asm *.lnk *.lst *.map *.mem *.rel *.rst *.sym \ 83 | *.lk $(TARGET).hex 84 | cd $(FX2LIBDIR) && make clean 85 | 86 | distclean: clean 87 | $(RM) -r $(FX2LIBDIR) 88 | -------------------------------------------------------------------------------- /descriptors.c: -------------------------------------------------------------------------------- 1 | 2 | #include "descriptors.h" 3 | 4 | __code __at(DSCR_AREA) struct usb_descriptors code_descriptors = { 5 | .device = { 6 | .bLength = USB_DT_DEVICE_SIZE, 7 | .bDescriptorType = USB_DT_DEVICE, 8 | .bcdUSB = USB_BCD_V20, 9 | .bDeviceClass = USB_CLASS_PER_INTERFACE, 10 | .bDeviceSubClass = 0, 11 | .bDeviceProtocol = 0, 12 | .bMaxPacketSize0 = 64, 13 | .idVendor = FTDI_VID, 14 | .idProduct = PID, 15 | .bcdDevice = DID, 16 | .iManufacturer = USB_STRING_INDEX(0), 17 | .iProduct = USB_STRING_INDEX(1), 18 | .iSerialNumber = USB_STRING_SERIAL_INDEX, 19 | .bNumConfigurations = 1 20 | }, 21 | .highspeed = { 22 | .config = { 23 | .bLength = USB_DT_CONFIG_SIZE, 24 | .bDescriptorType = USB_DT_CONFIG, 25 | .wTotalLength = sizeof(descriptors.highspeed), 26 | .bNumInterfaces = 2, 27 | .bConfigurationValue = 1, 28 | .iConfiguration = USB_STRING_INDEX_NONE, 29 | .bmAttributes = USB_CONFIG_ATT_ONE, 30 | .bMaxPower = 250, // FIXME: ??? 31 | }, 32 | .interface0 = { 33 | .bLength = USB_DT_INTERFACE_SIZE, 34 | .bDescriptorType = USB_DT_INTERFACE, 35 | .bInterfaceNumber = 0, 36 | .bAlternateSetting = 0, 37 | .bNumEndpoints = 2, 38 | .bInterfaceClass = USB_CLASS_VENDOR_SPEC, 39 | .bInterfaceSubClass = USB_SUBCLASS_VENDOR_SPEC, 40 | .bInterfaceProtocol = USB_PROTOCOL_VENDOR_SPEC, 41 | .iInterface = USB_STRING_INDEX(1), 42 | }, 43 | .endpoints0 = { 44 | { 45 | .bLength = USB_DT_ENDPOINT_SIZE, 46 | .bDescriptorType = USB_DT_ENDPOINT, 47 | .bEndpointAddress = USB_ENDPOINT_NUMBER(0x1) | USB_DIR_IN, 48 | .bmAttributes = USB_ENDPOINT_XFER_BULK, 49 | .wMaxPacketSize = 64, // EP1 only supports 64 bytes on the FX2 50 | .bInterval = 0, 51 | }, 52 | { 53 | .bLength = USB_DT_ENDPOINT_SIZE, 54 | .bDescriptorType = USB_DT_ENDPOINT, 55 | .bEndpointAddress = USB_ENDPOINT_NUMBER(0x2) | USB_DIR_OUT, 56 | .bmAttributes = USB_ENDPOINT_XFER_BULK, 57 | .wMaxPacketSize = 512, 58 | .bInterval = 0, 59 | }, 60 | }, 61 | .interface1 = { 62 | .bLength = USB_DT_INTERFACE_SIZE, 63 | .bDescriptorType = USB_DT_INTERFACE, 64 | .bInterfaceNumber = 1, 65 | .bAlternateSetting = 0, 66 | .bNumEndpoints = 2, 67 | .bInterfaceClass = USB_CLASS_VENDOR_SPEC, 68 | .bInterfaceSubClass = USB_SUBCLASS_VENDOR_SPEC, 69 | .bInterfaceProtocol = USB_PROTOCOL_VENDOR_SPEC, 70 | .iInterface = USB_STRING_INDEX(1), 71 | }, 72 | .endpoints1 = { 73 | { 74 | .bLength = USB_DT_ENDPOINT_SIZE, 75 | .bDescriptorType = USB_DT_ENDPOINT, 76 | .bEndpointAddress = USB_ENDPOINT_NUMBER(0x3) | USB_DIR_IN, 77 | .bmAttributes = USB_ENDPOINT_XFER_BULK, 78 | .wMaxPacketSize = 512, 79 | .bInterval = 0, 80 | }, 81 | { 82 | .bLength = USB_DT_ENDPOINT_SIZE, 83 | .bDescriptorType = USB_DT_ENDPOINT, 84 | .bEndpointAddress = USB_ENDPOINT_NUMBER(0x4) | USB_DIR_OUT, 85 | .bmAttributes = USB_ENDPOINT_XFER_BULK, 86 | .wMaxPacketSize = 512, 87 | .bInterval = 0, 88 | }, 89 | }, 90 | }, 91 | .qualifier = { 92 | .bLength = USB_DT_DEVICE_QUALIFIER_SIZE, 93 | .bDescriptorType = USB_DT_DEVICE_QUALIFIER, 94 | .bcdUSB = USB_BCD_V20, 95 | .bDeviceClass = USB_CLASS_PER_INTERFACE, 96 | .bDeviceSubClass = 0, 97 | .bDeviceProtocol = 0, 98 | .bMaxPacketSize0 = 64, 99 | .bNumConfigurations = 1, 100 | .bRESERVED = 0, 101 | }, 102 | .fullspeed = 0x0, 103 | #include "descriptors_strings.inc" 104 | }; 105 | -------------------------------------------------------------------------------- /docs/tiao.md: -------------------------------------------------------------------------------- 1 | 2 | # TIAO USB Multi-Protocol Adapter (JTAG, SPI, I2C, Serial) 3 | 4 | * http://www.diygadget.com/tiao-usb-multi-protocol-adapter-jtag-spi-i2c-serial.html 5 | * http://www.tiaowiki.com/w/JTAG_Tutorials 6 | 7 | ## dmesg output 8 | 9 | ``` 10 | usb 3-2: new high-speed USB device number 4 using xhci_hcd 11 | usb 3-2: New USB device found, idVendor=0403, idProduct=8a98 12 | usb 3-2: New USB device strings: Mfr=1, Product=2, SerialNumber=3 13 | usb 3-2: Product: TIAO USB Multi-Protocol Adapter 14 | usb 3-2: Manufacturer: TIAO 15 | usb 3-2: SerialNumber: TIM01168 16 | usb 3-2: Ignoring serial port reserved for JTAG 17 | ftdi_sio 3-2:1.1: FTDI USB Serial Device converter detected 18 | usb 3-2: Detected FT2232H 19 | usb 3-2: Number of endpoints 2 20 | usb 3-2: Endpoint 1 MaxPacketSize 512 21 | usb 3-2: Endpoint 2 MaxPacketSize 512 22 | usb 3-2: Setting MaxPacketSize 512 23 | usb 3-2: FTDI USB Serial Device converter now attached to ttyUSB0 24 | ``` 25 | 26 | ## lsusb output 27 | 28 | ``` 29 | Bus 003 Device 004: ID 0403:8a98 Future Technology Devices International, Ltd TIAO Multi-Protocol Adapter 30 | ``` 31 | 32 | ## Descriptors 33 | 34 | ``` 35 | Bus 003 Device 004: ID 0403:8a98 Future Technology Devices International, Ltd TIAO Multi-Protocol Adapter 36 | Device Descriptor: 37 | bLength 18 38 | bDescriptorType 1 39 | bcdUSB 2.00 40 | bDeviceClass 0 (Defined at Interface level) 41 | bDeviceSubClass 0 42 | bDeviceProtocol 0 43 | bMaxPacketSize0 64 44 | idVendor 0x0403 Future Technology Devices International, Ltd 45 | idProduct 0x8a98 TIAO Multi-Protocol Adapter 46 | bcdDevice 7.00 47 | iManufacturer 1 TIAO 48 | iProduct 2 TIAO USB Multi-Protocol Adapter 49 | iSerial 3 TIM01168 50 | bNumConfigurations 1 51 | Configuration Descriptor: 52 | bLength 9 53 | bDescriptorType 2 54 | wTotalLength 55 55 | bNumInterfaces 2 56 | bConfigurationValue 1 57 | iConfiguration 0 58 | bmAttributes 0x80 59 | (Bus Powered) 60 | MaxPower 450mA 61 | Interface Descriptor: 62 | bLength 9 63 | bDescriptorType 4 64 | bInterfaceNumber 0 65 | bAlternateSetting 0 66 | bNumEndpoints 2 67 | bInterfaceClass 255 Vendor Specific Class 68 | bInterfaceSubClass 255 Vendor Specific Subclass 69 | bInterfaceProtocol 255 Vendor Specific Protocol 70 | iInterface 2 TIAO USB Multi-Protocol Adapter 71 | Endpoint Descriptor: 72 | bLength 7 73 | bDescriptorType 5 74 | bEndpointAddress 0x81 EP 1 IN 75 | bmAttributes 2 76 | Transfer Type Bulk 77 | Synch Type None 78 | Usage Type Data 79 | wMaxPacketSize 0x0200 1x 512 bytes 80 | bInterval 0 81 | Endpoint Descriptor: 82 | bLength 7 83 | bDescriptorType 5 84 | bEndpointAddress 0x02 EP 2 OUT 85 | bmAttributes 2 86 | Transfer Type Bulk 87 | Synch Type None 88 | Usage Type Data 89 | wMaxPacketSize 0x0200 1x 512 bytes 90 | bInterval 0 91 | Interface Descriptor: 92 | bLength 9 93 | bDescriptorType 4 94 | bInterfaceNumber 1 95 | bAlternateSetting 0 96 | bNumEndpoints 2 97 | bInterfaceClass 255 Vendor Specific Class 98 | bInterfaceSubClass 255 Vendor Specific Subclass 99 | bInterfaceProtocol 255 Vendor Specific Protocol 100 | iInterface 2 TIAO USB Multi-Protocol Adapter 101 | Endpoint Descriptor: 102 | bLength 7 103 | bDescriptorType 5 104 | bEndpointAddress 0x83 EP 3 IN 105 | bmAttributes 2 106 | Transfer Type Bulk 107 | Synch Type None 108 | Usage Type Data 109 | wMaxPacketSize 0x0200 1x 512 bytes 110 | bInterval 0 111 | Endpoint Descriptor: 112 | bLength 7 113 | bDescriptorType 5 114 | bEndpointAddress 0x04 EP 4 OUT 115 | bmAttributes 2 116 | Transfer Type Bulk 117 | Synch Type None 118 | Usage Type Data 119 | wMaxPacketSize 0x0200 1x 512 bytes 120 | bInterval 0 121 | Device Qualifier (for other device speed): 122 | bLength 10 123 | bDescriptorType 6 124 | bcdUSB 2.00 125 | bDeviceClass 0 (Defined at Interface level) 126 | bDeviceSubClass 0 127 | bDeviceProtocol 0 128 | bMaxPacketSize0 64 129 | bNumConfigurations 1 130 | Device Status: 0x0000 131 | (Bus Powered) 132 | ``` 133 | -------------------------------------------------------------------------------- /docs/pipistrello.md: -------------------------------------------------------------------------------- 1 | 2 | # Pipistrello Rev 2.0 3 | 4 | * http://pipistrello.saanlima.com/index.php?title=Welcome_to_Pipistrello 5 | 6 | ## dmesg output 7 | 8 | ``` 9 | usb 3-2: new high-speed USB device number 3 using xhci_hcd 10 | usb 3-2: New USB device found, idVendor=0403, idProduct=6010 11 | usb 3-2: New USB device strings: Mfr=1, Product=2, SerialNumber=3 12 | usb 3-2: Product: Pipistrello LX45 13 | usb 3-2: Manufacturer: Saanlima 14 | usb 3-2: SerialNumber: 400100527273 15 | usbcore: registered new interface driver usbserial 16 | usbcore: registered new interface driver usbserial_generic 17 | usbserial: USB Serial support registered for generic 18 | usbcore: registered new interface driver ftdi_sio 19 | usbserial: USB Serial support registered for FTDI USB Serial Device 20 | ftdi_sio 3-2:1.0: FTDI USB Serial Device converter detected 21 | usb 3-2: Detected FT2232H 22 | usb 3-2: Number of endpoints 2 23 | usb 3-2: Endpoint 1 MaxPacketSize 512 24 | usb 3-2: Endpoint 2 MaxPacketSize 512 25 | usb 3-2: Setting MaxPacketSize 512 26 | usb 3-2: FTDI USB Serial Device converter now attached to ttyUSB0 27 | ftdi_sio 3-2:1.1: FTDI USB Serial Device converter detected 28 | usb 3-2: Detected FT2232H 29 | usb 3-2: Number of endpoints 2 30 | usb 3-2: Endpoint 1 MaxPacketSize 512 31 | usb 3-2: Endpoint 2 MaxPacketSize 512 32 | usb 3-2: Setting MaxPacketSize 512 33 | usb 3-2: FTDI USB Serial Device converter now attached to ttyUSB1 34 | ``` 35 | 36 | ## lsusb output 37 | 38 | ``` 39 | Bus 003 Device 003: ID 0403:6010 Future Technology Devices International, Ltd FT2232C Dual USB-UART/FIFO IC 40 | ``` 41 | 42 | ## Descriptors 43 | 44 | ``` 45 | Bus 003 Device 003: ID 0403:6010 Future Technology Devices International, Ltd FT2232C Dual USB-UART/FIFO IC 46 | Device Descriptor: 47 | bLength 18 48 | bDescriptorType 1 49 | bcdUSB 2.00 50 | bDeviceClass 0 (Defined at Interface level) 51 | bDeviceSubClass 0 52 | bDeviceProtocol 0 53 | bMaxPacketSize0 64 54 | idVendor 0x0403 Future Technology Devices International, Ltd 55 | idProduct 0x6010 FT2232C Dual USB-UART/FIFO IC 56 | bcdDevice 7.00 57 | iManufacturer 1 Saanlima 58 | iProduct 2 Pipistrello LX45 59 | iSerial 3 400100527273 60 | bNumConfigurations 1 61 | Configuration Descriptor: 62 | bLength 9 63 | bDescriptorType 2 64 | wTotalLength 55 65 | bNumInterfaces 2 66 | bConfigurationValue 1 67 | iConfiguration 0 68 | bmAttributes 0x80 69 | (Bus Powered) 70 | MaxPower 300mA 71 | Interface Descriptor: 72 | bLength 9 73 | bDescriptorType 4 74 | bInterfaceNumber 0 75 | bAlternateSetting 0 76 | bNumEndpoints 2 77 | bInterfaceClass 255 Vendor Specific Class 78 | bInterfaceSubClass 255 Vendor Specific Subclass 79 | bInterfaceProtocol 255 Vendor Specific Protocol 80 | iInterface 2 Pipistrello LX45 81 | Endpoint Descriptor: 82 | bLength 7 83 | bDescriptorType 5 84 | bEndpointAddress 0x81 EP 1 IN 85 | bmAttributes 2 86 | Transfer Type Bulk 87 | Synch Type None 88 | Usage Type Data 89 | wMaxPacketSize 0x0200 1x 512 bytes 90 | bInterval 0 91 | Endpoint Descriptor: 92 | bLength 7 93 | bDescriptorType 5 94 | bEndpointAddress 0x02 EP 2 OUT 95 | bmAttributes 2 96 | Transfer Type Bulk 97 | Synch Type None 98 | Usage Type Data 99 | wMaxPacketSize 0x0200 1x 512 bytes 100 | bInterval 0 101 | Interface Descriptor: 102 | bLength 9 103 | bDescriptorType 4 104 | bInterfaceNumber 1 105 | bAlternateSetting 0 106 | bNumEndpoints 2 107 | bInterfaceClass 255 Vendor Specific Class 108 | bInterfaceSubClass 255 Vendor Specific Subclass 109 | bInterfaceProtocol 255 Vendor Specific Protocol 110 | iInterface 2 Pipistrello LX45 111 | Endpoint Descriptor: 112 | bLength 7 113 | bDescriptorType 5 114 | bEndpointAddress 0x83 EP 3 IN 115 | bmAttributes 2 116 | Transfer Type Bulk 117 | Synch Type None 118 | Usage Type Data 119 | wMaxPacketSize 0x0200 1x 512 bytes 120 | bInterval 0 121 | Endpoint Descriptor: 122 | bLength 7 123 | bDescriptorType 5 124 | bEndpointAddress 0x04 EP 4 OUT 125 | bmAttributes 2 126 | Transfer Type Bulk 127 | Synch Type None 128 | Usage Type Data 129 | wMaxPacketSize 0x0200 1x 512 bytes 130 | bInterval 0 131 | Device Qualifier (for other device speed): 132 | bLength 10 133 | bDescriptorType 6 134 | bcdUSB 2.00 135 | bDeviceClass 0 (Defined at Interface level) 136 | bDeviceSubClass 0 137 | bDeviceProtocol 0 138 | bMaxPacketSize0 64 139 | bNumConfigurations 1 140 | Device Status: 0x0000 141 | (Bus Powered) 142 | ``` 143 | -------------------------------------------------------------------------------- /bitbang/bitbang.md: -------------------------------------------------------------------------------- 1 | 2 | * (3cy) DJNZ Rn, rel - Decrement register, jump if not zero 3 | * (3cy) JC - Jump if carry 4 | * (3cy) JNC - Jump if not carry 5 | 6 | 48MHz @ 4 clock per instruction cycle == 12MHz 7 | 8 | OUT register 9 | ``` 10 | +---+---+---+---+---+---+---+---+ +---+ 11 | /--> | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | <--> | c | <--\ 12 | | +---+---+---+---+---+---+---+---+ +---+ | 13 | | | 14 | \----------------------------------------------------/ 15 | ``` 16 | 17 | * (1cy) RLC A - Rotate A left through carry 18 | * (1cy) RRC A - Rotate A right through carry 19 | 20 | * Most Significant Bit First -> RRC 21 | * Least Significant Bit First -> RLC 22 | 23 | * TMS mode 24 | * Bit 7 -> TDO 25 | * Bit 6->0 -> TMS 26 | 27 | # If data out/ data in pins are bit capable 28 | 29 | ``` 30 | MOV dest, src 31 | (2cy) MOV C, bit - Move direct bit to carry 32 | (2cy) MOV bit, C - Move carry to direct bit 33 | (2cy) CLR bit - Clear direct bit 34 | (2cy) SETB bit - Set direct bit 35 | (2cy) CPL bit - Compliment direct bit 36 | 37 | (1cy) CLR C - Clear carry 38 | (1cy) SETB C - Set carry 39 | (1cy) CPL C - Complement carry 40 | ``` 41 | 42 | ## if READ and WRITE on same edge 43 | 44 | ``` 45 | a1^ (2cy) CPL pin_clk_out 46 | a2 -- (2cy) MOV pin_data_out, C 47 | a3 -- (2cy) MOV C, pin_data_in 48 | b1^ (2cy) CPL pin_clk_out 49 | b2 -- (2cy) ROTATE + NOP 50 | b3 -- (2cy) NOP, NOP 51 | == 6 cycles between clock edges 52 | ``` 53 | 54 | ## if READ and WRITE on opposite edges 55 | 56 | ``` 57 | a1^ (2cy) CPL pin_clk_out 58 | a3 -- (2cy) MOV pin_data_out, C 59 | a3 -- (1cy) NOP 60 | b1^ (2cy) CPL pin_clk_out 61 | b2 -- (2cy) MOV C, pin_data_in 62 | b3 -- (1cy) ROTATE 63 | == 5 cycles between clock edges 64 | ``` 65 | 66 | * 12MHz / 6 cycles per CLK == 2Mbit/s 67 | 68 | # If only byte accessible 69 | 70 | ## Using proxy byte 71 | 72 | "proxy byte" in bit addressable space == direct space 73 | 74 | * No ops touch register A 75 | 76 | ``` 77 | Toggle clock - 5 cycles 78 | (2cy) CPL proxy_pin_clk 79 | (3cy) MOV pins, proxy 80 | ``` 81 | 82 | ``` 83 | Write data out - 5 cycles 84 | (2cy) MOV proxy_pin_data_out, C 85 | (3cy) MOV pins, proxy 86 | ``` 87 | 88 | ``` 89 | Read data in - 5 cycles 90 | (3cy) MOV proxy, pins 91 | (2cy) MOV C, proxy_pin_data_in 92 | ``` 93 | 94 | ### if READ and WRITE on same edge 95 | 96 | ``` 97 | b6 (2cy) CPL proxy_pin_clk 98 | a1^ (3cy) MOV pins, proxy 99 | a2 -- (2cy) MOV proxy_pin_data_out, C 100 | a3 -- (3cy) MOV pins, proxy 101 | a4 -- (3cy) MOV proxy, pins 102 | a5 -- (2cy) MOV C, proxy_pin_data_in 103 | a6 (2cy) CPL proxy_pin_clk 104 | b1^ (3cy) MOV pins, proxy 105 | b2 -- (2cy) ROTATE + NOP 106 | b3 -- (3cy) NOP + NOP + NOP 107 | b4 -- (3cy) NOP + NOP + NOP 108 | b5 -- (2cy) NOP + NOP 109 | == 15 cycles between CLK edges 110 | ``` 111 | 112 | #### Better version? 113 | ``` 114 | b4 (2cy) MOV proxy_pin_data_out, C 115 | b5 (2cy) CPL proxy_pin_clk 116 | a1^ (3cy) MOV pins, proxy 117 | a2 (3cy) MOV proxy, pins 118 | a3 (2cy) MOV C, proxy_pin_data_in 119 | 120 | a4 (2cy) CPL proxy_pin_clk 121 | a5 (2cy) ROTATE + NOP 122 | b1^ (3cy) MOV pins, proxy 123 | b2 (3cy) NOP + NOP + NOP 124 | b3 (2cy) NOP + NOP 125 | == 12 cycles between CLK edges 126 | ``` 127 | 128 | ### if READ and WRITE on opposite edges 129 | 130 | ``` 131 | b5 (2cy) CPL R2_pin_clk 132 | a1^ (3cy) MOV pins, proxy 133 | a2 -- (2cy) MOV proxy_pin_data_out, C 134 | a3 -- (3cy) MOV pins, proxy 135 | a4 -- (1cy) NOP 136 | 137 | a5 (2cy) CPL R2_pin_clk 138 | b1^ (3cy)*MOV pins, proxy 139 | b2 -- (3cy) MOV proxy, pins 140 | b3 -- (2cy) MOV C, proxy_pin_data_in 141 | b4 -- (1cy) ROTATE 142 | == 11 cycles between CLK edges 143 | ``` 144 | 145 | #### Better version? 146 | ``` 147 | b4 (2cy) MOV proxy_pin_data_out, C 148 | b5 (2cy) CPL proxy_pin_clk 149 | a1^ (3cy)*MOV pins, R2 150 | a2 (2cy) NOP + NOP 151 | a3 (1cy) NOP 152 | a4 (2cy) NOP + NOP 153 | 154 | a5 (2cy) CPL proxy_pin_clk 155 | b1^ (3cy)*MOV pins, proxy 156 | b2 (2cy) MOV proxy, pins 157 | b3 (1cy) ROTATE 158 | == 9 cycles between CLK edges 159 | ``` 160 | 161 | ## Using proxy byte + @R0 162 | 163 | ``` 164 | MOV direct, @Ri == 2 cycles 165 | MOV @Ri, direct == 2 cycles 166 | compared too.... 167 | MOV direct, direct == 3 cycles 168 | ``` 169 | 170 | * No ops touch register A 171 | * R0 == proxy 172 | 173 | ``` 174 | Toggle clock - 4 cycles 175 | (2cy) CPL proxy_pin_clk 176 | (2cy) MOV pins, @R0 177 | ``` 178 | 179 | ``` 180 | Write data out - 4 cycles 181 | (2cy) MOV proxy_pin_data_out, C 182 | (2cy) MOV pins, @R0 183 | ``` 184 | 185 | ``` 186 | Read data in - 4 cycles 187 | (2cy) MOV @R0, pins 188 | (2cy) MOV C, proxy_pin_data_in 189 | ``` 190 | 191 | ### if READ and WRITE on same edge 192 | 193 | ``` 194 | a1^ (2cy) CPL proxy_pin_clk 195 | a2 (2cy) MOV pins, @R0 196 | a3 -- (2cy) MOV proxy_data_out, C 197 | a4 -- (2cy) MOV pins, @R0 198 | a5 -- (2cy) MOV @R0, pins 199 | a6 -- (2cy) MOV C, proxy_data_in 200 | b1^ (2cy) CPL pin_clk_out 201 | b2 (2cy) MOV pins, @R0 202 | b3 -- (2cy) ROTATE + NOP 203 | b4 -- (2cy) NOP, NOP 204 | b5 -- (2cy) NOP, NOP 205 | b6 -- (2cy) NOP, NOP 206 | == 12 cycles between clock edges 207 | ``` 208 | 209 | #### Better version? 210 | ``` 211 | b4 (2cy) MOV proxy_pin_data_out, C 212 | b5 (2cy) CPL proxy_pin_clk 213 | a1^ (2cy) MOV pins, @R0 214 | a2 (2cy) MOV @R0, pins 215 | a3 (2cy) MOV C, proxy_pin_data_in 216 | 217 | a4 (2cy) CPL proxy_pin_clk 218 | a5 (2cy) ROTATE + NOP 219 | b1^ (2cy) MOV pins, @R0 220 | b2 (2cy) NOP + NOP 221 | b3 (2cy) NOP + NOP 222 | == 10 cycles between CLK edges 223 | ``` 224 | 225 | ### if READ and WRITE on opposite edges 226 | 227 | ``` 228 | a1^ (2cy) CPL proxy_clk_out 229 | a2 (2cy) MOV pins, @R0 230 | a4 -- (2cy) MOV proxy_data_out, C 231 | a5 -- (2cy) MOV pins, @R0 232 | a6 -- (1cy) NOP 233 | b1^ (2cy) CPL proxy_clk_out 234 | b2 (2cy) MOV pins, @R0 235 | b3 -- (2cy) MOV @R0, pins 236 | b4 -- (2cy) MOV C, proxy_data_in 237 | b6 -- (1cy) ROTATE 238 | == 9 cycles between clock edges 239 | ``` 240 | 241 | * 12MHz / 12 cycles per CLK == 1.0Mbit/s 242 | * 12MHz / 10 cycles per CLK == 1.2Mbit/s 243 | * 12MHz / 9 cycles per CLK == 1.3Mbit/s 244 | 245 | ## Using lots of registers 246 | 247 | ``` 248 | MOV dest, src 249 | (2cy) MOV direct, Rn - Move direct byte to register 250 | (2cy) MOV Rn, direct - Move register to direct byte 251 | (3cy) MOV direct, direct - Move direct to direct 252 | (1cy) XCH A, Rn - Exchange A and register 253 | (2cy) XCH A, direct - Exchange A and direct 254 | ``` 255 | 256 | * `Rx_clk_out_mask` 257 | * `Rx_data_out_mask` 258 | * `Rx_data_out_store` 259 | * `Rx_data_in_mask` 260 | * `Rx_data_in_store` 261 | 262 | ``` 263 | Toggle clock, preserving A - 4 cycles 264 | (1cy) XCH A, Rx_clk_out_mask 265 | (2cy) XRL pins, A 266 | (1cy) XCH A, Rx_clk_out_mask 267 | ``` 268 | 269 | ``` 270 | Toggle clock, clobbering A - 3 cycles 271 | (1cy) MOV A, Rx_clk_out_mask 272 | (2cy) XRL pins, A 273 | ``` 274 | 275 | ``` 276 | Write data out - 6 cycles 277 | -- (1cy) MOV A, Rx_data_out 278 | -- (1cy) ROTATE 279 | -- (1cy) MOV Rx_data_out, A 280 | -- (1cy) ORL A, Rx_data_out_mask 281 | -- (2cy) ORL pins, A 282 | ``` 283 | 284 | ``` 285 | Read data in - 6 cycles 286 | -- (1cy) MOV A, Rx_data_in_mask 287 | -- (2cy) ANL A, pins 288 | -- (1cy) ORL A, Rx_data_in 289 | -- (1cy) ROTATE 290 | -- (1cy) MOV Rx_data_in, A 291 | ``` 292 | 293 | -------------------------------------------------------------------------------- /bitbang/cycles.py: -------------------------------------------------------------------------------- 1 | """ 2 | Tools for calculating the cycles ASM instructions need. 3 | 4 | Reads the information from the cycles.md file. 5 | """ 6 | 7 | import re 8 | from collections import namedtuple 9 | from collections import OrderedDict 10 | from enum import Enum 11 | 12 | class ArgType(Enum): 13 | accumulator = 'A' 14 | b = 'B' 15 | register = 'Rn' 16 | carry = 'C' 17 | direct_byte = 'direct' 18 | indirect_byte = '@Ri' 19 | relative = 'rel' 20 | direct_bit = 'bit' 21 | inverse_direct_bit = '/bit' 22 | immediate_byte = '#data' 23 | immediate_word = '#data16' 24 | address_full = 'addr16' 25 | address_small = 'addr11' 26 | program_counter = 'PC' 27 | data_pointer = 'DPTR' 28 | indirect_data_pointer = '@DPTR' 29 | 30 | @classmethod 31 | def convert(cls, s): 32 | if '+' in s: 33 | arg0, arg1 = s.split('+') 34 | assert arg0[0] == '@' 35 | arg0 = ArgType.convert(arg0[1:]) 36 | arg1 = ArgType.convert(arg1) 37 | return arg0, arg1 38 | 39 | for e in cls: 40 | if e.value == s: 41 | return e 42 | raise ValueError('%s not found in %s' % (s, cls)) 43 | 44 | def regex(self): 45 | a = "\s,\"'" 46 | not_reg = '(?:[^{0}][^{0}][^{0}]+)|(?:[^{0}Rr][^{0}])|(?:[Rr][^0-7])|(?:[^{0}AaCcBb])'.format(a) 47 | if self == ArgType.accumulator: 48 | return '[Aa]' 49 | elif self == ArgType.b: 50 | return '[Bb]' 51 | elif self == ArgType.register: 52 | return '[Rr][0-7]' 53 | elif self == ArgType.carry: 54 | return '[Cc]' 55 | elif self == ArgType.direct_byte: 56 | return not_reg 57 | elif self == ArgType.indirect_byte: 58 | return '@[Rr][01]' 59 | elif self == ArgType.relative: 60 | return not_reg 61 | elif self == ArgType.direct_bit: 62 | return not_reg 63 | elif self == ArgType.inverse_direct_bit: 64 | return '/'+not_reg 65 | elif self == ArgType.immediate_byte: 66 | return '#[^\s,]+' 67 | elif self == ArgType.immediate_word: 68 | return '#[^\s,]+' 69 | elif self == ArgType.address_full: 70 | return '' 71 | elif self == ArgType.address_small: 72 | return '' 73 | elif self == ArgType.program_counter: 74 | return 'PC' 75 | elif self == ArgType.data_pointer: 76 | return 'DPTR' 77 | elif self == ArgType.indirect_data_pointer: 78 | return '@DPTR' 79 | 80 | # ---------------------- 81 | 82 | ArgsNone = namedtuple('ArgsNone', []) 83 | class ArgsNone(ArgsNone): 84 | def __repr__(self): 85 | return "" 86 | 87 | def regex(self): 88 | return "" 89 | 90 | ArgsSingle = namedtuple('ArgsSingle', ['arg']) 91 | class ArgsSingle(ArgsSingle): 92 | def __repr__(self): 93 | if isinstance(self.arg, tuple): 94 | return "+".join(x.value for x in self.arg) 95 | else: 96 | return self.arg.value 97 | 98 | def regex(self): 99 | return "(?P%s)" % self.arg.regex() 100 | 101 | ArgsSimple = namedtuple('ArgsSimple', ['dst', 'src']) 102 | class ArgsSimple(ArgsSimple): 103 | def __repr__(self): 104 | if isinstance(self.src, tuple): 105 | src = "+".join(x.value for x in self.src) 106 | else: 107 | src = self.src.value 108 | return "%s<-%s" % (self.dst.value, src) 109 | 110 | def regex(self): 111 | return r"(?P%s)\s*,\s*(?P%s)" % (self[0].regex(), self[1].regex()) 112 | 113 | ArgsCompare = namedtuple('ArgsCompare', ['a', 'b', 'jump']) 114 | class ArgsCompare(ArgsCompare): 115 | def __repr__(self): 116 | return "%s!=%s %s->PC" % (self.a.value, self.b.value, self.jump.value) 117 | 118 | def regex(self): 119 | return r"(?P%s)\s*,\s*(?P%s)\s*,\s*(?P%s)" % (self[0].regex(), self[1].regex(), self[2].regex()) 120 | 121 | ArgsMul = namedtuple('ArgsMul', ['a', 'b']) 122 | class ArgsMul(ArgsMul): 123 | def __repr__(self): 124 | return "AB" 125 | 126 | # ---------------------- 127 | 128 | Instruction = namedtuple('Instruction', ['mneomic', 'args', 'description', 'size', 'cycles', 'flags']) #, 'opcodes']) 129 | class Instruction(Instruction): 130 | def __repr__(self): 131 | flags = " ".join(self.flags) 132 | if flags: 133 | flags = "(%s)" % flags 134 | return "(%i) %s %s" % (self.cycles, self.mneomic, self.args) 135 | 136 | @property 137 | def effects_carry(self): 138 | for f in self.flags: 139 | if 'CY' in f: 140 | return True 141 | return False 142 | 143 | @property 144 | def effects_accumulator(self): 145 | if isinstance(self.args, (ArgsSimple, ArgsSingle)): 146 | return self.args[0] == ArgType.accumulator 147 | return False 148 | 149 | def regex(self): 150 | return r"(?:[\s'\"]|^)(%s|%s)\s*%s(?:[\s'\"]|$)" % (self.mneomic.upper(), self.mneomic.lower(), self.args.regex()) 151 | 152 | instructions = {} 153 | for line in open('cycles.md').readlines(): 154 | if not line.strip(): 155 | continue 156 | 157 | _, mnemoic, desc, size, cycles, flags, opcode, _ = (x.strip() for x in line.split('|')) 158 | if mnemoic.lower() == "mnemoic" or mnemoic.startswith("-"): 159 | continue 160 | 161 | if ' ' in mnemoic: 162 | mnemoic_code, args = (x.strip() for x in mnemoic.split(' ', 1)) 163 | if args == 'AB': 164 | args = ArgsMul(ArgType.accumulator, ArgType.b) 165 | elif ',' in args: 166 | arg0, arg1 = args.split(', ', 1) 167 | arg0 = ArgType.convert(arg0) 168 | if ',' in arg1: 169 | arg1, arg2 = arg1.split(', ', 1) 170 | arg1 = ArgType.convert(arg1) 171 | arg2 = ArgType.convert(arg2) 172 | args = ArgsCompare(arg0, arg1, arg2) 173 | else: 174 | arg1 = ArgType.convert(arg1) 175 | args = ArgsSimple(arg0, arg1) 176 | else: 177 | args = ArgsSingle(ArgType.convert(args)) 178 | else: 179 | mnemoic_code = mnemoic 180 | args = ArgsNone() 181 | 182 | flags = list(x.strip() for x in flags.split()) 183 | 184 | if '-' in opcode: 185 | bopcode, topcode = (int(x, 16) for x in opcode.split('-')) 186 | else: 187 | bopcode = topcode = int(opcode, 16) 188 | opcodes = [hex(x) for x in range(bopcode, topcode+1)] 189 | 190 | size = int(size) 191 | cycles = int(cycles) 192 | 193 | instructions.setdefault(mnemoic_code, []).append( 194 | Instruction(mnemoic_code, args, desc, size, cycles, flags)) #, opcodes)) 195 | 196 | 197 | 198 | def parse(s): 199 | """ 200 | """ 201 | 202 | output = [] 203 | for line in s.splitlines(): 204 | if not line.strip(): 205 | output.append(None) 206 | continue 207 | 208 | lline = line.lower() 209 | 210 | matches = [] 211 | for op in instructions: 212 | if op.lower() not in lline: 213 | continue 214 | 215 | for i in instructions[op]: 216 | r = re.search(i.regex(), line) 217 | if r: 218 | matches.append((i, r.groups()[1:])) 219 | 220 | assert len(matches) == 1, "%s\n%s" % (line, "\n".join(repr(x) for x in matches)) 221 | output.append(matches[0]) 222 | return output 223 | 224 | 225 | if __name__ == "__main__": 226 | import pprint 227 | pprint.pprint(instructions) 228 | 229 | def parse_and_print(s): 230 | instructions = parse(s) 231 | for l, i in zip(s.splitlines(), instructions): 232 | print("%-60s %s" % (repr(l), i)) 233 | 234 | print("-"*75) 235 | parse_and_print("""\ 236 | orl _IOA,#0x01 237 | anl _IOA,#0xFE 238 | xrl _IOA,#0x01 239 | setb _PA0 240 | clr _PA0 241 | cpl _PA0 242 | mov a,_IOA 243 | 244 | mov ar4,r6 245 | orl a,r4 246 | rl a 247 | mov r6,a 248 | clr a 249 | mov r5,a 250 | mov r4,a 251 | mov a,r6 252 | add a,r7 253 | """) 254 | print("-"*75) 255 | parse_and_print("""\ 256 | __asm__ ('nop'); 257 | __asm__ ("mov c,DIN_BIT"); /* din->carry */ 258 | __asm__ ("rlc a"); /* data->carry->data */ 259 | __asm__ ("mov DOUT_BIT,c"); /* carry->dout */ 260 | """) 261 | -------------------------------------------------------------------------------- /bitbang/cycles.md: -------------------------------------------------------------------------------- 1 | 2 | | Mnemoic | Desc | Byte Size | Cycles | Flags | Opcode| 3 | | --------------------- | --------------------------------------------------------------------- | - | - | --------------| ----- | 4 | | ADD A, Rn | Add register to A | 1 | 1 | CY OV AC | 28-2F | 5 | | ADD A, direct | Add direct byte to A | 2 | 2 | CY OV AC | 25 | 6 | | ADD A, @Ri | Add data memory to A | 1 | 1 | CY OV AC | 26-27 | 7 | | ADD A, #data | Add immediate to A | 2 | 2 | CY OV AC | 24 | 8 | | ADDC A, Rn | Add register to A with carry | 1 | 1 | CY OV AC | 38-3F | 9 | | ADDC A, direct | Add direct byte to A with carry | 2 | 2 | CY OV AC | 35 | 10 | | ADDC A, @Ri | Add data memory to A with carry | 1 | 1 | CY OV AC | 36-37 | 11 | | ADDC A, #data | Add immediate to A with carry | 2 | 2 | CY OV AC | 34 | 12 | | SUBB A, Rn | Subtract register from A with borrow | 1 | 1 | CY OV AC | 98-9F | 13 | | SUBB A, direct | Subtract direct byte from A with borrow | 2 | 2 | CY OV AC | 95 | 14 | | SUBB A, @Ri | Subtract data memory from A with borrow | 1 | 1 | CY OV AC | 96-97 | 15 | | SUBB A, #data | Subtract immediate from A with borrow | 2 | 2 | CY OV AC | 94 | 16 | | INC A | Increment A | 1 | 1 | | 04 | 17 | | INC Rn | Increment register | 1 | 1 | | 08-0F | 18 | | INC direct | Increment direct byte | 2 | 2 | | 05 | 19 | | INC @Ri | Increment data memory | 1 | 1 | | 06-07 | 20 | | DEC A | Decrement A | 1 | 1 | | 14 | 21 | | DEC Rn | Decrement Register | 1 | 1 | | 18-1F | 22 | | DEC direct | Decrement direct byte | 2 | 2 | | 15 | 23 | | DEC @Ri | Decrement data memory | 1 | 1 | | 16-17 | 24 | | INC DPTR | Increment data pointer | 1 | 3 | | A3 | 25 | | MUL AB | Multiply A and B (unsigned; product in B:A) | 1 | 5 | CY=0 OV | A4 | 26 | | DIV AB | Divide A by B (unsigned; quotient in A, remainder in B) | 1 | 5 | CY=0 OV | 84 | 27 | | DA A | Decimal adjust A | 1 | 1 | CY | D4 | 28 | | ANL A, Rn | AND register to A | 1 | 1 | | 58-5F | 29 | | ANL A, direct | AND direct byte to A | 2 | 2 | | 55 | 30 | | ANL A, @Ri | AND data memory to A | 1 | 1 | | 56-57 | 31 | | ANL A, #data | AND immediate to A | 2 | 2 | | 54 | 32 | | ANL direct, A | AND A to direct byte | 2 | 2 | | 52 | 33 | | ANL direct, #data | AND immediate data to direct byte | 3 | 3 | | 53 | 34 | | ORL A, Rn | OR register to A | 1 | 1 | | 48-4F | 35 | | ORL A, direct | OR direct byte to A | 2 | 2 | | 45 | 36 | | ORL A, @Ri | OR data memory to A | 1 | 1 | | 46-47 | 37 | | ORL A, #data | OR immediate to A | 2 | 2 | | 44 | 38 | | ORL direct, A | OR A to direct byte | 2 | 2 | | 42 | 39 | | ORL direct, #data | OR immediate data to direct byte | 3 | 3 | | 43 | 40 | | XRL A, Rn | Exclusive-OR register to A | 1 | 1 | | 68-6F | 41 | | XRL A, direct | Exclusive-OR direct byte to A | 2 | 2 | | 65 | 42 | | XRL A, @Ri | Exclusive-OR data memory to A | 1 | 1 | | 66-67 | 43 | | XRL A, #data | Exclusive-OR immediate to A | 2 | 2 | | 64 | 44 | | XRL direct, A | Exclusive-OR A to direct byte | 2 | 2 | | 62 | 45 | | XRL direct, #data | Exclusive-OR immediate to direct byte | 3 | 3 | | 63 | 46 | | CLR A | Clear A | 1 | 1 | | E4 | 47 | | CPL A | Complement A | 1 | 1 | | F4 | 48 | | SWAP A | Swap nibbles of a | 1 | 1 | | C4 | 49 | | RL A | Rotate A left | 1 | 1 | | 23 | 50 | | RLC A | Rotate A left through carry | 1 | 1 | CY | 33 | 51 | | RR A | Rotate A right | 1 | 1 | | 03 | 52 | | RRC A | Rotate A right through carry | 1 | 1 | CY | 13 | 53 | | MOV A, Rn | Move register to A | 1 | 1 | | E8-EF | 54 | | MOV A, direct | Move direct byte to A | 2 | 2 | | E5 | 55 | | MOV A, @Ri | Move data byte at Ri to A | 1 | 1 | | E6-E7 | 56 | | MOV A, #data | Move immediate to A | 2 | 2 | | 74 | 57 | | MOV Rn, A | Move A to register | 1 | 1 | | F8-FF | 58 | | MOV Rn, direct | Move direct byte to register | 2 | 2 | | A8-AF | 59 | | MOV Rn, #data | Move immediate to register | 2 | 2 | | 78-7F | 60 | | MOV direct, A | Move A to direct byte | 2 | 2 | | F5 | 61 | | MOV direct, Rn | Move register to direct byte | 2 | 2 | | 88-8F | 62 | | MOV direct, direct | Move direct byte to direct byte | 3 | 3 | | 85 | 63 | | MOV direct, @Ri | Move data byte at Ri to direct byte | 2 | 2 | | 86-87 | 64 | | MOV direct, #data | Move immediate to direct byte | 3 | 3 | | 75 | 65 | | MOV @Ri, A | Move A to data memory at address Ri | 1 | 1 | | F6-F7 | 66 | | MOV @Ri, direct | Move direct byte to data memory at address Ri | 2 | 2 | | A6-A7 | 67 | | MOV @Ri, #data | Move immediate to data memory at address Ri | 2 | 2 | | 76-77 | 68 | | MOV DPTR, #data16 | Move 16-bit immediate to data pointer | 3 | 3 | | 90 | 69 | | MOVC A, @A+DPTR | Move code byte at address DPTR+A to A | 1 | 3 | | 93 | 70 | | MOVC A, @A+PC | Move code byte at address PC+A to A | 1 | 3 | | 83 | 71 | | MOVX A, @Ri | Move external data at address Ri to A | 1 | 2 | | E2-E3 | 72 | | MOVX A, @DPTR | Move external data at address DPTR to A | 1 | 2 | | E0 | 73 | | MOVX @Ri, A | Move A to external data at address Ri | 1 | 2 | | F2-F3 | 74 | | MOVX @DPTR, A | Move A to external data at address DPTR | 1 | 2 | | F0 | 75 | | PUSH direct | Push direct byte onto stack | 2 | 2 | | C0 | 76 | | POP direct | Pop direct byte from stack | 2 | 2 | | D0 | 77 | | XCH A, Rn | Exchange A and register | 1 | 1 | | C8-CF | 78 | | XCH A, direct | Exchange A and direct byte | 2 | 2 | | C5 | 79 | | XCH A, @Ri | Exchange A and data memory at address Ri | 1 | 1 | | C6-C7 | 80 | | XCHD A, @Ri | Exchange the low-order nibbles of A and data memory at address Ri | 1 | 1 | | D6-D7 | 81 | | CLR C | Clear carry | 1 | 1 | CY=0 | C3 | 82 | | CLR bit | Clear direct bit | 2 | 2 | | C2 | 83 | | SETB C | Set carry | 1 | 1 | CY=1 | D3 | 84 | | SETB bit | Set direct bit | 2 | 2 | | D2 | 85 | | CPL C | Complement carry | 1 | 1 | CY | B3 | 86 | | CPL bit | Complement direct bit | 2 | 2 | | B2 | 87 | | ANL C, bit | AND direct bit to carry | 2 | 2 | CY | 82 | 88 | | ANL C, /bit | AND inverse of direct bit to carry | 2 | 2 | CY | B0 | 89 | | ORL C, bit | OR direct bit to carry | 2 | 2 | CY | 72 | 90 | | ORL C, /bit | OR inverse of direct bit to carry | 2 | 2 | CY | A0 | 91 | | MOV C, bit | Move direct bit to carry | 2 | 2 | CY | A2 | 92 | | MOV bit, C | Move carry to direct bit | 2 | 2 | | 92 | 93 | | ACALL addr11 | Absolute call to subroutine | 2 | 3 | | 11-F1 | 94 | | LCALL addr16 | Long call to subroutine | 3 | 4 | | 12 | 95 | | RET | Return from subroutine | 1 | 4 | | 22 | 96 | | RETI | Return from interrupt | 1 | 4 | | 32 | 97 | | AJMP addr11 | Absolute jump unconditional | 2 | 3 | | 01-E1 | 98 | | LJMP addr16 | Long jump unconditional | 3 | 4 | | 02 | 99 | | SJMP rel | Short jump (relative address) | 2 | 3 | | 80 | 100 | | JC rel | Jump if carry = 1 | 2 | 3 | | 40 | 101 | | JNC rel | Jump if carry = 0 | 2 | 3 | | 50 | 102 | | JB bit, rel | Jump if direct bit = 1 | 3 | 4 | | 20 | 103 | | JNB bit, rel | Jump if direct bit = 0 | 3 | 4 | | 30 | 104 | | JBC bit, rel | Jump if direct bit = 1, then clear the bit | 3 | 4 | | 10 | 105 | | JMP @A+DPTR | Jump indirect to address DPTR+A | 1 | 3 | | 73 | 106 | | JZ rel | Jump if accumulator = 0 | 2 | 3 | | 60 | 107 | | JNZ rel | Jump if accumulator is non-zero | 2 | 3 | | 70 | 108 | | CJNE A, direct, rel | Compare A to direct byte; jump if not equal | 3 | 4 | CY | B5 | 109 | | CJNE A, #data, rel | Compare A to immediate; jump if not equal | 3 | 4 | CY | B4 | 110 | | CJNE Rn, #data, rel | Compare register to immediate; jump if not equal | 3 | 4 | CY | B8-BF | 111 | | CJNE @Ri, #data, rel | Compare data memory to immediate; jump if not equal | 3 | 4 | CY | B6-B7 | 112 | | DJNZ Rn, rel | Decrement register; jump if not zero | 2 | 3 | | D8-DF | 113 | | DJNZ direct, rel | Decrement direct byte; jump if not zero | 3 | 4 | | D5 | 114 | | NOP | No operation | 1 | 1 | | 00 | 115 | -------------------------------------------------------------------------------- /libftdi.h: -------------------------------------------------------------------------------- 1 | /*************************************************************************** 2 | ftdi.h - description 3 | ------------------- 4 | begin : Fri Apr 4 2003 5 | copyright : (C) 2003-2011 by Intra2net AG and the libftdi developers 6 | email : opensource@intra2net.com 7 | ***************************************************************************/ 8 | 9 | /*************************************************************************** 10 | * * 11 | * This program is free software; you can redistribute it and/or modify * 12 | * it under the terms of the GNU Lesser General Public License * 13 | * version 2.1 as published by the Free Software Foundation; * 14 | * * 15 | ***************************************************************************/ 16 | 17 | #ifndef __libftdi_h__ 18 | #define __libftdi_h__ 19 | 20 | /** FTDI chip type */ 21 | enum ftdi_chip_type { TYPE_AM=0, TYPE_BM=1, TYPE_2232C=2, TYPE_R=3, TYPE_2232H=4, TYPE_4232H=5, TYPE_232H=6 }; 22 | /** Parity mode for ftdi_set_line_property() */ 23 | enum ftdi_parity_type { NONE=0, ODD=1, EVEN=2, MARK=3, SPACE=4 }; 24 | /** Number of stop bits for ftdi_set_line_property() */ 25 | enum ftdi_stopbits_type { STOP_BIT_1=0, STOP_BIT_15=1, STOP_BIT_2=2 }; 26 | /** Number of bits for ftdi_set_line_property() */ 27 | enum ftdi_bits_type { BITS_7=7, BITS_8=8 }; 28 | /** Break type for ftdi_set_line_property2() */ 29 | enum ftdi_break_type { BREAK_OFF=0, BREAK_ON=1 }; 30 | 31 | /** MPSSE bitbang modes */ 32 | enum ftdi_mpsse_mode 33 | { 34 | BITMODE_RESET = 0x00, /**< switch off bitbang mode, back to regular serial/FIFO */ 35 | BITMODE_BITBANG= 0x01, /**< classical asynchronous bitbang mode, introduced with B-type chips */ 36 | BITMODE_MPSSE = 0x02, /**< MPSSE mode, available on 2232x chips */ 37 | BITMODE_SYNCBB = 0x04, /**< synchronous bitbang mode, available on 2232x and R-type chips */ 38 | BITMODE_MCU = 0x08, /**< MCU Host Bus Emulation mode, available on 2232x chips */ 39 | /* CPU-style fifo mode gets set via EEPROM */ 40 | BITMODE_OPTO = 0x10, /**< Fast Opto-Isolated Serial Interface Mode, available on 2232x chips */ 41 | BITMODE_CBUS = 0x20, /**< Bitbang on CBUS pins of R-type chips, configure in EEPROM before */ 42 | BITMODE_SYNCFF = 0x40, /**< Single Channel Synchronous FIFO mode, available on 2232H chips */ 43 | BITMODE_FT1284 = 0x80, /**< FT1284 mode, available on 232H chips */ 44 | }; 45 | 46 | /** Port interface for chips with multiple interfaces */ 47 | enum ftdi_interface 48 | { 49 | INTERFACE_ANY = 0, 50 | INTERFACE_A = 1, 51 | INTERFACE_B = 2, 52 | INTERFACE_C = 3, 53 | INTERFACE_D = 4 54 | }; 55 | 56 | /** Automatic loading / unloading of kernel modules */ 57 | enum ftdi_module_detach_mode 58 | { 59 | AUTO_DETACH_SIO_MODULE = 0, 60 | DONT_DETACH_SIO_MODULE = 1 61 | }; 62 | 63 | /* Shifting commands IN MPSSE Mode*/ 64 | #define MPSSE_WRITE_NEG 0x01 /* Write TDI/DO on negative TCK/SK edge*/ 65 | #define MPSSE_BITMODE 0x02 /* Write bits, not bytes */ 66 | #define MPSSE_READ_NEG 0x04 /* Sample TDO/DI on negative TCK/SK edge */ 67 | #define MPSSE_LSB 0x08 /* LSB first */ 68 | #define MPSSE_DO_WRITE 0x10 /* Write TDI/DO */ 69 | #define MPSSE_DO_READ 0x20 /* Read TDO/DI */ 70 | #define MPSSE_WRITE_TMS 0x40 /* Write TMS/CS */ 71 | 72 | /* FTDI MPSSE commands */ 73 | #define SET_BITS_LOW 0x80 74 | /*BYTE DATA*/ 75 | /*BYTE Direction*/ 76 | #define SET_BITS_HIGH 0x82 77 | /*BYTE DATA*/ 78 | /*BYTE Direction*/ 79 | #define GET_BITS_LOW 0x81 80 | #define GET_BITS_HIGH 0x83 81 | #define LOOPBACK_START 0x84 82 | #define LOOPBACK_END 0x85 83 | #define TCK_DIVISOR 0x86 84 | /* H Type specific commands */ 85 | #define DIS_DIV_5 0x8a 86 | #define EN_DIV_5 0x8b 87 | #define EN_3_PHASE 0x8c 88 | #define DIS_3_PHASE 0x8d 89 | #define CLK_BITS 0x8e 90 | #define CLK_BYTES 0x8f 91 | #define CLK_WAIT_HIGH 0x94 92 | #define CLK_WAIT_LOW 0x95 93 | #define EN_ADAPTIVE 0x96 94 | #define DIS_ADAPTIVE 0x97 95 | #define CLK_BYTES_OR_HIGH 0x9c 96 | #define CLK_BYTES_OR_LOW 0x0d 97 | /*FT232H specific commands */ 98 | #define DRIVE_OPEN_COLLECTOR 0x9e 99 | /* Value Low */ 100 | /* Value HIGH */ /*rate is 12000000/((1+value)*2) */ 101 | #define DIV_VALUE(rate) (rate > 6000000)?0:((6000000/rate -1) > 0xffff)? 0xffff: (6000000/rate -1) 102 | 103 | /* Commands in MPSSE and Host Emulation Mode */ 104 | #define SEND_IMMEDIATE 0x87 105 | #define WAIT_ON_HIGH 0x88 106 | #define WAIT_ON_LOW 0x89 107 | 108 | /* Commands in Host Emulation Mode */ 109 | #define READ_SHORT 0x90 110 | /* Address_Low */ 111 | #define READ_EXTENDED 0x91 112 | /* Address High */ 113 | /* Address Low */ 114 | #define WRITE_SHORT 0x92 115 | /* Address_Low */ 116 | #define WRITE_EXTENDED 0x93 117 | /* Address High */ 118 | /* Address Low */ 119 | 120 | /* Definitions for flow control */ 121 | #define SIO_RESET 0 /* Reset the port */ 122 | #define SIO_MODEM_CTRL 1 /* Set the modem control register */ 123 | #define SIO_SET_FLOW_CTRL 2 /* Set flow control register */ 124 | #define SIO_SET_BAUD_RATE 3 /* Set baud rate */ 125 | #define SIO_SET_DATA 4 /* Set the data characteristics of the port */ 126 | 127 | //#define FTDI_DEVICE_OUT_REQTYPE (LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_OUT) 128 | //#define FTDI_DEVICE_IN_REQTYPE (LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE | LIBUSB_ENDPOINT_IN) 129 | 130 | /* Requests */ 131 | #define SIO_RESET_REQUEST SIO_RESET 132 | #define SIO_SET_BAUDRATE_REQUEST SIO_SET_BAUD_RATE 133 | #define SIO_SET_DATA_REQUEST SIO_SET_DATA 134 | #define SIO_SET_FLOW_CTRL_REQUEST SIO_SET_FLOW_CTRL 135 | #define SIO_SET_MODEM_CTRL_REQUEST SIO_MODEM_CTRL 136 | #define SIO_POLL_MODEM_STATUS_REQUEST 0x05 137 | #define SIO_SET_EVENT_CHAR_REQUEST 0x06 138 | #define SIO_SET_ERROR_CHAR_REQUEST 0x07 139 | #define SIO_SET_LATENCY_TIMER_REQUEST 0x09 140 | #define SIO_GET_LATENCY_TIMER_REQUEST 0x0A 141 | #define SIO_SET_BITMODE_REQUEST 0x0B 142 | #define SIO_READ_PINS_REQUEST 0x0C 143 | #define SIO_READ_EEPROM_REQUEST 0x90 144 | #define SIO_WRITE_EEPROM_REQUEST 0x91 145 | #define SIO_ERASE_EEPROM_REQUEST 0x92 146 | 147 | 148 | #define SIO_RESET_SIO 0 149 | #define SIO_RESET_PURGE_RX 1 150 | #define SIO_RESET_PURGE_TX 2 151 | 152 | #define SIO_DISABLE_FLOW_CTRL 0x0 153 | #define SIO_RTS_CTS_HS (0x1 << 8) 154 | #define SIO_DTR_DSR_HS (0x2 << 8) 155 | #define SIO_XON_XOFF_HS (0x4 << 8) 156 | 157 | #define SIO_SET_DTR_MASK 0x1 158 | #define SIO_SET_DTR_HIGH ( 1 | ( SIO_SET_DTR_MASK << 8)) 159 | #define SIO_SET_DTR_LOW ( 0 | ( SIO_SET_DTR_MASK << 8)) 160 | #define SIO_SET_RTS_MASK 0x2 161 | #define SIO_SET_RTS_HIGH ( 2 | ( SIO_SET_RTS_MASK << 8 )) 162 | #define SIO_SET_RTS_LOW ( 0 | ( SIO_SET_RTS_MASK << 8 )) 163 | 164 | #define SIO_RTS_CTS_HS (0x1 << 8) 165 | 166 | /* marker for unused usb urb structures 167 | (taken from libusb) */ 168 | #define FTDI_URB_USERCONTEXT_COOKIE ((void *)0x1) 169 | 170 | #ifdef __GNUC__ 171 | #define DEPRECATED(func) func __attribute__ ((deprecated)) 172 | #elif defined(_MSC_VER) 173 | #define DEPRECATED(func) __declspec(deprecated) func 174 | #else 175 | #pragma message("WARNING: You need to implement DEPRECATED for this compiler") 176 | #define DEPRECATED(func) func 177 | #endif 178 | 179 | /** 180 | List all handled EEPROM values. 181 | Append future new values only at the end to provide API/ABI stability*/ 182 | enum ftdi_eeprom_value 183 | { 184 | VENDOR_ID = 0, 185 | PRODUCT_ID = 1, 186 | SELF_POWERED = 2, 187 | REMOTE_WAKEUP = 3, 188 | IS_NOT_PNP = 4, 189 | SUSPEND_DBUS7 = 5, 190 | IN_IS_ISOCHRONOUS = 6, 191 | OUT_IS_ISOCHRONOUS = 7, 192 | SUSPEND_PULL_DOWNS = 8, 193 | USE_SERIAL = 9, 194 | USB_VERSION = 10, 195 | USE_USB_VERSION = 11, 196 | MAX_POWER = 12, 197 | CHANNEL_A_TYPE = 13, 198 | CHANNEL_B_TYPE = 14, 199 | CHANNEL_A_DRIVER = 15, 200 | CHANNEL_B_DRIVER = 16, 201 | CBUS_FUNCTION_0 = 17, 202 | CBUS_FUNCTION_1 = 18, 203 | CBUS_FUNCTION_2 = 19, 204 | CBUS_FUNCTION_3 = 20, 205 | CBUS_FUNCTION_4 = 21, 206 | CBUS_FUNCTION_5 = 22, 207 | CBUS_FUNCTION_6 = 23, 208 | CBUS_FUNCTION_7 = 24, 209 | CBUS_FUNCTION_8 = 25, 210 | CBUS_FUNCTION_9 = 26, 211 | HIGH_CURRENT = 27, 212 | HIGH_CURRENT_A = 28, 213 | HIGH_CURRENT_B = 29, 214 | INVERT = 30, 215 | GROUP0_DRIVE = 31, 216 | GROUP0_SCHMITT = 32, 217 | GROUP0_SLEW = 33, 218 | GROUP1_DRIVE = 34, 219 | GROUP1_SCHMITT = 35, 220 | GROUP1_SLEW = 36, 221 | GROUP2_DRIVE = 37, 222 | GROUP2_SCHMITT = 38, 223 | GROUP2_SLEW = 39, 224 | GROUP3_DRIVE = 40, 225 | GROUP3_SCHMITT = 41, 226 | GROUP3_SLEW = 42, 227 | CHIP_SIZE = 43, 228 | CHIP_TYPE = 44, 229 | POWER_SAVE = 45, 230 | CLOCK_POLARITY = 46, 231 | DATA_ORDER = 47, 232 | FLOW_CONTROL = 48, 233 | CHANNEL_C_DRIVER = 49, 234 | CHANNEL_D_DRIVER = 50, 235 | CHANNEL_A_RS485 = 51, 236 | CHANNEL_B_RS485 = 52, 237 | CHANNEL_C_RS485 = 53, 238 | CHANNEL_D_RS485 = 54, 239 | }; 240 | 241 | #define FT1284_CLK_IDLE_STATE 0x01 242 | #define FT1284_DATA_LSB 0x02 /* DS_FT232H 1.3 amd ftd2xx.h 1.0.4 disagree here*/ 243 | #define FT1284_FLOW_CONTROL 0x04 244 | #define POWER_SAVE_DISABLE_H 0x80 245 | 246 | #define USE_SERIAL_NUM 0x08 247 | enum ftdi_cbus_func {/* FIXME: Recheck value, especially the last */ 248 | CBUS_TXDEN = 0, CBUS_PWREN = 1, CBUS_RXLED = 2, CBUS_TXLED = 3, CBUS_TXRXLED = 4, 249 | CBUS_SLEEP = 5, CBUS_CLK48 = 6, CBUS_CLK24 = 7, CBUS_CLK12 = 8, CBUS_CLK6 = 9, 250 | CBUS_IOMODE = 0xa, CBUS_BB_WR = 0xb, CBUS_BB_RD = 0xc, CBUS_BB = 0xd}; 251 | 252 | enum ftdi_cbush_func {/* FIXME: Recheck value, especially the last */ 253 | CBUSH_TRISTATE = 0, CBUSH_RXLED = 1, CBUSH_TXLED = 2, CBUSH_TXRXLED = 3, CBUSH_PWREN = 4, 254 | CBUSH_SLEEP = 5, CBUSH_DRIVE_0 = 6, CBUSG_DRIVE1 = 7, CBUSH_IOMODE = 8, CBUSH_TXDEN = 9, 255 | CBUSH_CLK30 = 0xa, CBUSH_CLK15 = 0xb, CBUSH_CLK7_5 = 0xc}; 256 | 257 | /** Invert TXD# */ 258 | #define INVERT_TXD 0x01 259 | /** Invert RXD# */ 260 | #define INVERT_RXD 0x02 261 | /** Invert RTS# */ 262 | #define INVERT_RTS 0x04 263 | /** Invert CTS# */ 264 | #define INVERT_CTS 0x08 265 | /** Invert DTR# */ 266 | #define INVERT_DTR 0x10 267 | /** Invert DSR# */ 268 | #define INVERT_DSR 0x20 269 | /** Invert DCD# */ 270 | #define INVERT_DCD 0x40 271 | /** Invert RI# */ 272 | #define INVERT_RI 0x80 273 | 274 | /** Interface Mode. */ 275 | #define CHANNEL_IS_UART 0x0 276 | #define CHANNEL_IS_FIFO 0x1 277 | #define CHANNEL_IS_OPTO 0x2 278 | #define CHANNEL_IS_CPU 0x4 279 | #define CHANNEL_IS_FT1284 0x8 280 | 281 | #define CHANNEL_IS_RS485 0x10 282 | 283 | #define DRIVE_4MA 0 284 | #define DRIVE_8MA 1 285 | #define DRIVE_12MA 2 286 | #define DRIVE_16MA 3 287 | #define SLOW_SLEW 4 288 | #define IS_SCHMITT 8 289 | 290 | /** Driver Type. */ 291 | #define DRIVER_VCP 0x08 292 | #define DRIVER_VCPH 0x10 /* FT232H has moved the VCP bit */ 293 | 294 | #define USE_USB_VERSION_BIT 0x10 295 | 296 | #define SUSPEND_DBUS7_BIT 0x80 297 | 298 | /** High current drive. */ 299 | #define HIGH_CURRENT_DRIVE 0x10 300 | #define HIGH_CURRENT_DRIVE_R 0x04 301 | 302 | #endif /* __libftdi_h__ */ 303 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | -------------------------------------------------------------------------------- /bitbang/software.py: -------------------------------------------------------------------------------- 1 | """ 2 | Tools for generating efficient software based bit banging functions. 3 | """ 4 | 5 | from enum import Enum 6 | 7 | import pins 8 | import cycles 9 | 10 | 11 | class BitBang(object): 12 | """ 13 | Base interface for a bit banging bit. 14 | """ 15 | 16 | def get_undefined(self, fname): 17 | def undefined(self): 18 | raise IOError('Operation %s not valid on %s (%s pin)' % (fname, self.pin.name, self.direction)) 19 | return undefined.__get__(self, self.__class__) 20 | 21 | def __init__(self, name, pin, direction): 22 | self.name = name 23 | assert isinstance(pin, pins.Pin), pin 24 | self.pin = pin 25 | 26 | self.direction = direction 27 | if self.direction is pins.PinDirection.output: 28 | self.bit_to_carry = self.get_undefined("bit_to_carry") 29 | self.get = self.get_undefined("get") 30 | elif self.direction is pins.PinDirection.input: 31 | self.carry_to_bit = self.get_undefined("carry_to_bit") 32 | self.get = self.get_undefined("set") 33 | elif self.direction is pins.PinDirection.bidirectional: 34 | pass 35 | else: 36 | raise ValueError("Unknown direction %r" % direction) 37 | 38 | # Simple bit operations 39 | def get(self): 40 | """Get the bit value.""" 41 | raise NotImplementedError 42 | 43 | def set(self): 44 | """Set the bit value to 1.""" 45 | raise NotImplementedError 46 | 47 | def toggle(self): 48 | """Invert the current value of the bit. IE 1 -> 0 and 0 -> 1.""" 49 | raise NotImplementedError 50 | 51 | def clear(self): 52 | """Set the bit value to 0.""" 53 | raise NotImplementedError 54 | 55 | # Direction set up 56 | def setup(self, direction=None): 57 | if self.direction == pins.PinDirection.bidirectional: 58 | if not direction: 59 | return "" 60 | else: 61 | if direction: 62 | assert direction == self.direction 63 | return "" 64 | direction = self.direction 65 | 66 | if direction == pins.PinDirection.input: 67 | return self._setup_input() 68 | elif direction == pins.PinDirection.output: 69 | return self._setup_output() 70 | else: 71 | raise ValueError("Invalid direction %r for setup." % direction) 72 | 73 | def _setup_input(self): 74 | raise NotImplementedError 75 | 76 | def _setup_output(self): 77 | raise NotImplementedError 78 | 79 | # To/From the carry bit 80 | def bit_to_carry(self): 81 | """Move the bit contents into the carry bit.""" 82 | raise NotImplementedError 83 | 84 | def carry_to_bit(self): 85 | """Move the carry bit into the contents.""" 86 | raise NotImplementedError 87 | 88 | # FIXME: Is this needed? 89 | def setto(self, value_name): 90 | raise NotImplementedError 91 | 92 | def indent(s): 93 | return ("\n ".join(s.split("\n"))) 94 | 95 | 96 | class ByteAccessInC(BitBang): 97 | """Access bits via byte operations. Implemented in C.""" 98 | def __init__(self, name, pin, direction): 99 | """ 100 | ByteAccessInC("clock", "A", 0) 101 | """ 102 | BitBang.__init__(self, name, pin, direction) 103 | 104 | self.def_port = name.upper() + "_PORT" 105 | self.def_oe = name.upper() + "_PORT_OE" 106 | self.def_mask = name.upper() + "_MASK" 107 | self.def_nask = name.upper() + "_NASK" 108 | 109 | def defines(self): 110 | d = { 111 | 'port_name': sef.pin.port_name, 112 | 'port_oe': self.pin.output_name, 113 | 'mask': self.pin.mask, 114 | 'nask': self.pin.nask, 115 | } 116 | d.update(self.__dict__) 117 | return """\ 118 | #define %(def_port)s %(port_name)s 119 | #define %(def_oe)s %(port_oe)s 120 | #define %(def_mask)s %(mask)#04X 121 | #define %(def_nask)s %(nask)#04X 122 | """ % d 123 | 124 | # Simple bit operations 125 | def set(self): 126 | return """\ 127 | %(def_port)s |= %(def_mask)s; /* Set %(name)s */""" % self.__dict__ 128 | 129 | def get(self): 130 | return """\ 131 | (%(def_port)s & %(def_mask)s) /* Get %(name)s */""" % self.__dict__ 132 | 133 | def clear(self): 134 | return """\ 135 | %(def_port)s &= %(def_nask)s; /* Clear %(name)s */""" % self.__dict__ 136 | 137 | def toggle(self): 138 | return """\ 139 | %(def_port)s ^= %(def_mask)s; /* Toggle %(name)s */""" % self.__dict__ 140 | 141 | # Direction set up 142 | def _setup_input(self): 143 | return """\ 144 | %(def_oe)s &= %(def_nask)s; /* Set %(name)s as input */""" % self.__dict__ 145 | 146 | def _setup_output(self): 147 | return """\ 148 | %(def_oe)s |= %(def_mask)s; /* Set %(name)s as output */""" % self.__dict__ 149 | 150 | # To/From the carry bit 151 | def carry_to_bit(self): 152 | raise NotImplementedError 153 | return """\ 154 | __asm__ (""); 155 | """ 156 | def bit_to_carry(self): 157 | raise NotImplementedError 158 | return """\ 159 | __asm__ (""); 160 | """ 161 | 162 | # Other 163 | def setto(self, value_name): 164 | return """\ 165 | if (%(value_name)s) { 166 | %(set)s 167 | } else { 168 | %(clear)s 169 | }""" % { 170 | 'value_name': value_name, 171 | 'set': self.set(), 172 | 'clear': self.clear(), 173 | } 174 | 175 | 176 | 177 | class BitAccessInC(BitBang): 178 | """Access bits (in bit addressable space) via bit operations. Implemented in C.""" 179 | 180 | def __init__(self, name, direction, pin): 181 | """ 182 | ByteAccessInC("clock", "A", 0) 183 | """ 184 | assert self.pin.bit_accessible, "%r not bit accessible!" % pin 185 | BitBang.__init__(self, name, direction, pin) 186 | 187 | self.def_bit = name.upper() + "_BIT" 188 | self.def_oe = name.upper() + "_BIT_OE" 189 | self.def_mask = name.upper() + "_MASK" 190 | self.def_nask = name.upper() + "_NASK" 191 | 192 | def defines(self): 193 | d = { 194 | 'bit_name': sef.pin.bit_name, 195 | 'bit_oe': self.pin.output_name, 196 | 'mask': self.pin.mask, 197 | 'nask': self.pin.nask, 198 | } 199 | d.update(self.__dict__) 200 | return """\ 201 | #define %(def_bit)s %(bit_name)s 202 | """ % self.__dict__ 203 | 204 | # Simple bit operations 205 | def set(self): 206 | return """\ 207 | %(def_bit)s = 1; /* Set %(name)s */""" % self.__dict__ 208 | 209 | def get(self): 210 | return """\ 211 | %(def_bit)s /* Get %(name)s */""" % self.__dict__ 212 | 213 | def clear(self): 214 | return """\ 215 | %(def_bit)s = 0; /* Clear %(name)s */""" % self.__dict__ 216 | 217 | def toggle(self): 218 | return """\ 219 | %(def_bit)s ^= 1; /* Toggle %(name)s */""" % self.__dict__ 220 | 221 | # Direction set up 222 | def _setup_input(self): 223 | raise """\ 224 | %(def_oe)s &= %(def_nask)s; /* Set %(name)s as input */""" % self.__dict__ 225 | 226 | def _setup_output(self): 227 | raise """\ 228 | %(def_oe)s |= %(def_mask)s; /* Set %(name)s as output */""" % self.__dict__ 229 | 230 | # To/From the carry bit 231 | def bit_to_carry(self): 232 | return """\ 233 | __asm__ ("mov c,%(def_bit)s"); /* %(name)s->carry */""" % self.__dict__ 234 | 235 | def carry_to_bit(self): 236 | return """\ 237 | __asm__ ("mov %(def_bit)s,c"); /* carry->%(name)s */""" % self.__dict__ 238 | 239 | # Other 240 | def setto(self, value_name): 241 | d = {} 242 | d.update(self.__dict__) 243 | d['value_name'] = value_name 244 | return """\ 245 | %(def_bit)s = %(value_name)s; /* Set %(name)s */""" % d 246 | 247 | class ByteAccessInASM(BitBang): 248 | """ 249 | // Using proxy byte 250 | // ================================================= 251 | // "proxy byte" in bit addressable space == direct space 252 | 253 | // No ops touch register A 254 | 255 | // Toggle clock - 5 cycles 256 | // (2cy) CPL proxy_pin_clk 257 | // (3cy) MOV pins, proxy 258 | 259 | // Write data out - 5 cycles 260 | // (2cy) MOV proxy_pin_data_out, C 261 | // (3cy) MOV pins, proxy 262 | 263 | // Read data in - 5 cycles 264 | // (3cy) MOV proxy, pins 265 | // (2cy) MOV C, proxy_pin_data_in 266 | 267 | // if READ and WRITE on same edge 268 | // ----------------------------------- 269 | // b6 (2cy) CPL proxy_pin_clk 270 | // a1^ (3cy) MOV pins, proxy 271 | // a2 -- (2cy) MOV proxy_pin_data_out, C 272 | // a3 -- (3cy) MOV pins, proxy 273 | // a4 -- (3cy) MOV proxy, pins 274 | // a5 -- (2cy) MOV C, proxy_pin_data_in 275 | // a6 (2cy) CPL proxy_pin_clk 276 | // b1^ (3cy) MOV pins, proxy 277 | // b2 -- (2cy) ROTATE + NOP 278 | // b3 -- (3cy) NOP + NOP + NOP 279 | // b4 -- (3cy) NOP + NOP + NOP 280 | // b5 -- (2cy) NOP + NOP 281 | // == 15 cycles between CLK edges 282 | // 283 | // Better version? 284 | // b4 (2cy) MOV proxy_pin_data_out, C 285 | // b5 (2cy) CPL proxy_pin_clk 286 | // a1^ (3cy) MOV pins, proxy 287 | // a2 (3cy) MOV proxy, pins 288 | // a3 (2cy) MOV C, proxy_pin_data_in 289 | // 290 | // a4 (2cy) CPL proxy_pin_clk 291 | // a5 (2cy) ROTATE + NOP 292 | // b1^ (3cy) MOV pins, proxy 293 | // b2 (3cy) NOP + NOP + NOP 294 | // b3 (2cy) NOP + NOP 295 | // == 12 cycles between CLK edges 296 | // 297 | // if READ and WRITE on opposite edges 298 | // ----------------------------------- 299 | // b5 (2cy) CPL R2_pin_clk 300 | // a1^ (3cy) MOV pins, proxy 301 | // a2 -- (2cy) MOV proxy_pin_data_out, C 302 | // a3 -- (3cy) MOV pins, proxy 303 | // a4 -- (1cy) NOP 304 | // 305 | // a5 (2cy) CPL R2_pin_clk 306 | // b1^ (3cy)*MOV pins, proxy 307 | // b2 -- (3cy) MOV proxy, pins 308 | // b3 -- (2cy) MOV C, proxy_pin_data_in 309 | // b4 -- (1cy) ROTATE 310 | // == 11 cycles between CLK edges 311 | // 312 | // Better version? 313 | // b4 (2cy) MOV proxy_pin_data_out, C 314 | // b5 (2cy) CPL proxy_pin_clk 315 | // a1^ (3cy)*MOV pins, R2 316 | // a2 (2cy) NOP + NOP 317 | // a3 (1cy) NOP 318 | // a4 (2cy) NOP + NOP 319 | // 320 | // a5 (2cy) CPL proxy_pin_clk 321 | // b1^ (3cy)*MOV pins, proxy 322 | // b2 (2cy) MOV proxy, pins 323 | // b3 (1cy) ROTATE 324 | // == 9 cycles between CLK edges 325 | // ----------------------------------- 326 | 327 | 328 | // Using proxy byte + @R0 329 | // ================================================= 330 | // MOV direct, @Ri == 2 cycles 331 | // MOV @Ri, direct == 2 cycles 332 | // compared too.... 333 | // MOV direct, direct == 3 cycles 334 | 335 | // No ops touch register A 336 | // R0 == proxy 337 | 338 | // Toggle clock - 4 cycles 339 | // (2cy) CPL proxy_pin_clk 340 | // (2cy) MOV pins, @R0 341 | 342 | // Write data out - 4 cycles 343 | // (2cy) MOV proxy_pin_data_out, C 344 | // (2cy) MOV pins, @R0 345 | 346 | // Read data in - 4 cycles 347 | // (2cy) MOV @R0, pins 348 | // (2cy) MOV C, proxy_pin_data_in 349 | 350 | 351 | // if READ and WRITE on same edge 352 | // ----------------------------------- 353 | // a1^ (2cy) CPL proxy_pin_clk 354 | // a2 (2cy) MOV pins, @R0 355 | // a3 -- (2cy) MOV proxy_data_out, C 356 | // a4 -- (2cy) MOV pins, @R0 357 | // a5 -- (2cy) MOV @R0, pins 358 | // a6 -- (2cy) MOV C, proxy_data_in 359 | // b1^ (2cy) CPL pin_clk_out 360 | // b2 (2cy) MOV pins, @R0 361 | // b3 -- (2cy) ROTATE + NOP 362 | // b4 -- (2cy) NOP, NOP 363 | // b5 -- (2cy) NOP, NOP 364 | // b6 -- (2cy) NOP, NOP 365 | // == 12 cycles between clock edges 366 | // 367 | // Better version? 368 | // b4 (2cy) MOV proxy_pin_data_out, C 369 | // b5 (2cy) CPL proxy_pin_clk 370 | // a1^ (2cy) MOV pins, @R0 371 | // a2 (2cy) MOV @R0, pins 372 | // a3 (2cy) MOV C, proxy_pin_data_in 373 | // 374 | // a4 (2cy) CPL proxy_pin_clk 375 | // a5 (2cy) ROTATE + NOP 376 | // b1^ (2cy) MOV pins, @R0 377 | // b2 (2cy) NOP + NOP 378 | // b3 (2cy) NOP + NOP 379 | // == 10 cycles between CLK edges 380 | // 381 | // if READ and WRITE on opposite edges 382 | // ----------------------------------- 383 | // a1^ (2cy) CPL proxy_clk_out 384 | // a2 (2cy) MOV pins, @R0 385 | // a4 -- (2cy) MOV proxy_data_out, C 386 | // a5 -- (2cy) MOV pins, @R0 387 | // a6 -- (1cy) NOP 388 | // b1^ (2cy) CPL proxy_clk_out 389 | // b2 (2cy) MOV pins, @R0 390 | // b3 -- (2cy) MOV @R0, pins 391 | // b4 -- (2cy) MOV C, proxy_data_in 392 | // b6 -- (1cy) ROTATE 393 | // == 9 cycles between clock edges 394 | 395 | // 12MHz / 12 cycles per CLK == 1.0Mbit/s 396 | // 12MHz / 10 cycles per CLK == 1.2Mbit/s 397 | // 12MHz / 9 cycles per CLK == 1.3Mbit/s 398 | 399 | // Using lots of registers 400 | // ================================================= 401 | 402 | // MOV dest, src 403 | // (2cy) MOV direct, Rn - Move direct byte to register 404 | // (2cy) MOV Rn, direct - Move register to direct byte 405 | // (3cy) MOV direct, direct - Move direct to direct 406 | // (1cy) XCH A, Rn - Exchange A and register 407 | // (2cy) XCH A, direct - Exchange A and direct 408 | 409 | // Rx_clk_out_mask 410 | // Rx_data_out_mask 411 | // Rx_data_out_store 412 | // Rx_data_in_mask 413 | // Rx_data_in_store 414 | 415 | // Toggle clock, preserving A - 4 cycles 416 | // (1cy) XCH A, Rx_clk_out_mask 417 | // (2cy) XRL pins, A 418 | // (1cy) XCH A, Rx_clk_out_mask 419 | 420 | // Toggle clock, clobbering A - 3 cycles 421 | // (1cy) MOV A, Rx_clk_out_mask 422 | // (2cy) XRL pins, A 423 | 424 | // Write data out - 6 cycles 425 | // -- (1cy) MOV A, Rx_data_out 426 | // -- (1cy) ROTATE 427 | // -- (1cy) MOV Rx_data_out, A 428 | // -- (1cy) ORL A, Rx_data_out_mask 429 | // -- (2cy) ORL pins, A 430 | 431 | // Read data in - 6 cycles 432 | // -- (1cy) MOV A, Rx_data_in_mask 433 | // -- (2cy) ANL A, pins 434 | // -- (1cy) ORL A, Rx_data_in 435 | // -- (1cy) ROTATE 436 | // -- (1cy) MOV Rx_data_in, A 437 | 438 | // ============================================= 439 | """ 440 | 441 | 442 | class BitAccessInASM(BitBang): 443 | """Access bits (in bit addressable space) via bit operations. Implemented in assembly.""" 444 | 445 | def __init__(self, name, pin, direction): 446 | """ 447 | ByteAccessInC("clock", "A", 0) 448 | """ 449 | assert pin.bit_accessible, "%r not bit accessible!" % self.pin 450 | BitBang.__init__(self, name, pin, direction) 451 | 452 | self.bit_name = self.pin.bit_name 453 | self.oe_name = self.pin.output_name 454 | self.mask = self.pin.mask 455 | self.nask = self.pin.nask 456 | 457 | def defines(self): 458 | return """\ 459 | """ % self.__dict__ 460 | 461 | # Simple bit operations 462 | def set(self): 463 | return """\ 464 | __asm__ ("setb _%(bit_name)s"); /* Set %(name)s */""" % self.__dict__ 465 | 466 | def get(self): 467 | raise NotImplementedError 468 | 469 | def clear(self): 470 | return """\ 471 | __asm__ ("clr _%(bit_name)s"); /* Clear %(name)s */""" % self.__dict__ 472 | 473 | def toggle(self): 474 | return """\ 475 | __asm__ ("cpl _%(bit_name)s"); /* Toggle %(name)s */""" % self.__dict__ 476 | 477 | # Direction set up 478 | def _setup_input(self): 479 | return """\ 480 | __asm__ ("anl _%(oe_name)s,#%(nask)#04x;"); /* Set %(name)s as input */""" % self.__dict__ 481 | 482 | def _setup_output(self): 483 | return """\ 484 | __asm__ ("orl _%(oe_name)s,#%(mask)#04x;"); /* Set %(name)s as output */""" % self.__dict__ 485 | 486 | # To/From the carry bit 487 | def bit_to_carry(self): 488 | return """\ 489 | __asm__ ("mov c,_%(bit_name)s"); /* %(name)s->carry */""" % self.__dict__ 490 | 491 | def carry_to_bit(self): 492 | return """\ 493 | __asm__ ("mov _%(bit_name)s,c"); /* carry->%(name)s */""" % self.__dict__ 494 | 495 | # Other 496 | def setto(self, value_name): 497 | raise NotImplementedError 498 | 499 | 500 | def GenerateFunctions(bitbang): 501 | return """ 502 | // Generated functions for %(name)s from %(class)s 503 | // ----------------------------------------------------------------------- 504 | 505 | %(defines)s 506 | 507 | inline void %(name)s_set() { 508 | %(set)s; 509 | } 510 | 511 | inline void %(name)s_setto(_Bool value) { 512 | %(setto)s 513 | } 514 | 515 | inline _Bool %(name)s_get() { 516 | return %(get)s; 517 | } 518 | 519 | inline void %(name)s_clear() { 520 | %(clear)s; 521 | } 522 | 523 | inline void %(name)s_toggle() { 524 | %(toggle)s; 525 | } 526 | // ----------------------------------------------------------------------- 527 | 528 | """ % { 529 | 'class': bitbang.__class__, 530 | 'name': bitbang.name, 531 | 'defines': bitbang.defines(), 532 | 'set': indent(bitbang.set()), 533 | 'setto': indent(bitbang.setto("value")), 534 | 'get': bitbang.get(), 535 | 'clear': indent(bitbang.clear()), 536 | 'toggle': indent(bitbang.toggle()), 537 | } 538 | 539 | 540 | class ShiftOp(object): 541 | class FirstBit(Enum): 542 | """ 543 | MSB == Most Significant bit first 544 | LSB == Least Significant bit first 545 | """ 546 | MSB = 'rlc' 547 | LSB = 'rrc' 548 | 549 | class ClockMode(Enum): 550 | none = 0 551 | positive = 1 552 | negative = 2 553 | 554 | def __init__(self, clk_pin, din_pin, dout_pin): 555 | self.clk_pin = clk_pin 556 | assert self.clk_pin.direction == pins.PinDirection.output, (self.clk_pin.direction, pins.PinDirection.output) 557 | 558 | if din_pin == dout_pin: 559 | assert din_pin.direction == pins.PinDirection.bidirectional 560 | self.din_pin = dout_pin 561 | self.dout_pin = din_pin 562 | else: 563 | assert din_pin.direction == pins.PinDirection.input 564 | self.din_pin = din_pin 565 | assert dout_pin.direction == pins.PinDirection.output 566 | self.dout_pin = dout_pin 567 | 568 | """ 569 | @property 570 | def data_direction(self): 571 | assert self.data_pin 572 | if self.din_pin: 573 | return pins.PinDirection.input 574 | elif self.dout_pin: 575 | return pins.PinDirection.output 576 | else: 577 | raise ValueError("Data direction currently undefined!") 578 | 579 | def data_direction(self, direction): 580 | if not self.data_pin: 581 | return "" 582 | try: 583 | if direction == self.data_direction: 584 | # No direction change needed, as already that 585 | # direction. 586 | return "" 587 | except ValueError: 588 | pass 589 | 590 | if direction == pins.PinDirection.output: 591 | assert self.dout_pin is None 592 | self.dout_pin = self.data_pin 593 | self.din_pin = None 594 | return "FIXME: Switching instructions here." 595 | elif direction == pins.PinDirection.input: 596 | self.dout_pin = None 597 | assert self.din_pin is None 598 | self.din_pin = self.data_pin 599 | return "FIXME: Switching instructions here." 600 | else: 601 | raise ValueError("Invalid data direction %r" % direction) 602 | """ 603 | 604 | def generate(self): 605 | raise NotImplementedError() 606 | 607 | def asm_comment(s): 608 | return '__asm__ (" ; %s");' % s.replace('\\', '\\\\') 609 | 610 | class ShiftByte(ShiftOp): 611 | """ 612 | The shift byte functions are built around the "rotate accumulator 613 | through carry" operation and data is moved into / out of the carry bit. 614 | 615 | +---+---+---+---+---+---+---+---+ +---+ 616 | /--> | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | <--> | c | <--\ 617 | | +---+---+---+---+---+---+---+---+ +---+ | 618 | | | 619 | \----------------------------------------------------/ 620 | 621 | (1cy) RLC A - Rotate A left through carry 622 | (1cy) RRC A - Rotate A right through carry 623 | """ 624 | 625 | def generate(self, direction, read_on, write_on, pad=True): 626 | assert isinstance(direction, ShiftOp.FirstBit) 627 | assert isinstance(read_on, ShiftOp.ClockMode) 628 | assert isinstance(write_on, ShiftOp.ClockMode) 629 | 630 | read_ops = self.din_pin.bit_to_carry().splitlines() 631 | write_ops = self.dout_pin.carry_to_bit().splitlines() 632 | 633 | # Do we need to change directions between read/write? 634 | if self.din_pin == self.dout_pin: 635 | if write_on != ShiftOp.ClockMode.none and read_on != ShiftOp.ClockMode.none: 636 | read_ops = self.din_pin.setup(pins.PinDirection.input).splitlines() + read_ops 637 | write_ops = self.dout_pin.setup(pins.PinDirection.output).splitlines() + write_ops 638 | 639 | # Collect instructions on negative edge 640 | neg_edge = [] 641 | neg_edge.append(self.clk_pin.clear()) 642 | if write_on == ShiftOp.ClockMode.negative: 643 | neg_edge += write_ops 644 | if read_on == ShiftOp.ClockMode.negative: 645 | neg_edge += read_ops 646 | 647 | # Collect instructions on positive edge 648 | pos_edge = [] 649 | pos_edge.append(self.clk_pin.set()) 650 | if write_on == ShiftOp.ClockMode.positive: 651 | pos_edge += write_ops 652 | if read_on == ShiftOp.ClockMode.positive: 653 | pos_edge += read_ops 654 | 655 | # Figure out how the rotate will work 656 | rotate_tmpl = '__asm__ ("%s a"); /* %%s */' % direction.value 657 | rotate_op = "" 658 | if write_on != ShiftOp.ClockMode.none and read_on != ShiftOp.ClockMode.none: 659 | rotate_op = rotate_tmpl % "data->carry->data" 660 | elif write_on != ShiftOp.ClockMode.none: 661 | rotate_op = rotate_tmpl % "data->carry" 662 | elif read_on != ShiftOp.ClockMode.none: 663 | rotate_op = rotate_tmpl % "carry->data" 664 | 665 | # Find were we want to put the rotate operation 666 | if rotate_op: 667 | if len(neg_edge) > len(pos_edge): 668 | pos_edge.append(rotate_op) 669 | elif len(neg_edge) < len(pos_edge): 670 | neg_edge.append(rotate_op) 671 | else: 672 | neg_edge.append(rotate_op) 673 | 674 | # Pad the edges out to be symmetrical in cycle length 675 | # FIXME: This won't work for the C versions... 676 | neg_edge_instructions = cycles.parse("\n".join(neg_edge)) 677 | neg_edge_len = sum(i[0].cycles for i in neg_edge_instructions if i) 678 | 679 | pos_edge_instructions = cycles.parse("\n".join(pos_edge)) 680 | pos_edge_len = sum(i[0].cycles for i in pos_edge_instructions if i) 681 | 682 | longest = max(neg_edge_len, pos_edge_len) 683 | 684 | if pad: 685 | for i in range(0, longest - pos_edge_len): 686 | pos_edge.append('__asm__ ("nop");') 687 | for i in range(0, longest - neg_edge_len): 688 | neg_edge.append('__asm__ ("nop");') 689 | 690 | neg_edge_instructions = cycles.parse("\n".join(neg_edge)) 691 | pos_edge_instructions = cycles.parse("\n".join(pos_edge)) 692 | 693 | cmds = [] 694 | if write_on == ShiftOp.ClockMode.negative: 695 | cmds.append(asm_comment("Before")) 696 | cmds.append(rotate_tmpl % "data->carry") 697 | 698 | for i in range(0, 8): 699 | cmds.append(asm_comment("Bit %i" % i)) 700 | cmds.append("/* \_ (%s cycles) */" % neg_edge_len) 701 | cmds += neg_edge 702 | cmds.append("/* _/ (%s cycles) */" % pos_edge_len) 703 | cmds += pos_edge 704 | 705 | if read_on == ShiftOp.ClockMode.positive: 706 | cmds.append(asm_comment("After)")) 707 | cmds.append(rotate_tmpl % "carry->data") 708 | 709 | return cmds 710 | 711 | --------------------------------------------------------------------------------