summaryrefslogtreecommitdiff
path: root/microwire.lua
blob: d6c1ff45087eec6562decef30f48cf838273a196 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
-- functions to write registers over microwire interface
-- it resembles SPI but need extra pin which sends Load Enable (LE) pulse
-- otherwise SPI sequence is sent into 24 bit FIFO latch register on chip

-- Pins assignment
-- SPI Id selects which pins are used for CLK, MOSI, MISO, CS
microwire_spiID = 1; -- ID=1 --> HSPI in nodemcu language
microwire_databits=24; -- LMX2487 loads 24 bits sequence per write into a register
-- lmx2487 can handle up to 20 MHz speed (50 nS per clock) but optocoupler is good for 240kHz
-- so let's aim for 100 kHz
microwire_interface_speed = 100000; -- in Hz

-- we will use SPI ChipSelect pin for LoadEnable pin
microwire_LE_pin = 8; -- microwire Load Enable pin. 8 --> GPIO15

function microwire_setup_interface ()
	local fSPI = 80000000; -- default SPI clock is 80 MHz
	local clock_divider = math.floor(fSPI/microwire_interface_speed)
	-- now microwire <--> SPI setup
	-- microwire is SPI with CPOL=0 and CPHA=0 i.e. SPI mode 0 = 00 = CPOL.CPHA
	-- see https://en.wikipedia.org/wiki/Serial_Peripheral_Interface#Mode_numbers
	-- see https://www.totalphase.com/support/articles/200348506-Using-the-Aardvark-adapter-with-a-Microwire-device
	-- we are setting SPI Id = 1, since Id = 0 used for communication with memory
	spi.setup(microwire_spiID, spi.MASTER, spi.CPOL_LOW, spi.CPHA_LOW, microwire_databits, clock_divider)
	-- SPI Id=1 uses following pins https://nodemcu.readthedocs.io/en/master/modules/spi
	-- Signal    | IO index | ESP8266 pin
	-- HSPI CLK  | 5        | GPIO14
	-- HSPI /CS  | 8        | GPIO15
	-- HSPI MOSI | 7        | GPIO13
	-- HSPI MISO | 6        | GPIO12
	
	-- Load Enable pin settings
	-- note that it overwrite unused ChipSelect if pin=8, i.e. GPIO15
	gpio.mode(microwire_LE_pin, gpio.OUTPUT)
	gpio.write(microwire_LE_pin, gpio.LOW)

end

function microwire_send_data( data )
	-- essentially send data via spi interface
	-- and raise Load Enable pin for a bit (at least for 25 nS) at the end of transmission
	
	-- first low LE pin, it should be low but just to be sure
	gpio.write(microwire_LE_pin, gpio.LOW)

	-- second send the data
	local nBytes = spi.send(microwire_spiID, data)

	
	-- finally raise LE pin for at least 25 ns,
	-- note that it takes about 300 uS on ESP8266 before LE will be HIGH after spi.send
	-- Note manual toggle like below is quite slow, the shortest duration is 160 uS
	 gpio.write(microwire_LE_pin, gpio.HIGH)
	 gpio.write(microwire_LE_pin, gpio.LOW)
end

microwire_setup_interface()