Post your best Lua script examples here

User avatar
By sancho
#4016 Hello, everybody.

I made additional test with i2c and Lua.
I bought PCF8591, which is an 8-bit 4-channel ADC + 8-bit 1-channel DAC.
I connected it using the attached schematics and wrote 2 simple scripts - one for outputing semi-triangle signal using DAC and one for reading first ADC channel.
DAC.lua
Code: Select all    id=0
    sda=8
    scl=9

    -- initialize i2c, set pin1 as sda, set pin0 as scl
    i2c.setup(id,sda,scl,i2c.SLOW)

    function write_reg(dev_addr, reg_addr, reg_val)
      i2c.start(id)
      i2c.address(id, dev_addr, i2c.TRANSMITTER)
      i2c.write(id, reg_addr)
      i2c.write(id, reg_val)
      i2c.stop(id)
    end

    -- address of adc PCF8591
    device=0x48 --72 decimal

    i = 1
    dir = 1

    tmr.alarm(150,1,function()
      write_reg(device, 0x40, i)
      dir = (i == 0) and (dir == -1) and 1 or (i == 255) and (dir == 1) and -1 or dir
      i = i + dir
    end
    )

This code works using timer interrupt, raising/lowering the value of DAC (register 0x40) for PCF8591 (address 0x48).

ADC.lua
Code: Select all    id=0
    sda=8
    scl=9

    -- initialize i2c, set pin1 as sda, set pin0 as scl
    i2c.setup(id,sda,scl,i2c.SLOW)

    -- user defined function: read from reg_addr content of dev_addr
    function read_reg(dev_addr, reg_addr)
      i2c.start(id)
      i2c.address(id, dev_addr ,i2c.TRANSMITTER)
      i2c.write(id,reg_addr)
      i2c.stop(id)
      i2c.start(id)
      i2c.address(id, dev_addr,i2c.RECEIVER)
      c=i2c.read(id,2)
      i2c.stop(id)
      return c
    end

    function write_reg(dev_addr, reg_addr, reg_val)
      i2c.start(id)
      i2c.address(id, dev_addr, i2c.TRANSMITTER)
      i2c.write(id, reg_addr)
      i2c.write(id, reg_val)
      i2c.stop(id)
    end

    -- address of adc PCF8591
    device=0x48 --72 decimal

    for i=0,100 do
      result = read_reg(device, 0x00)
   print("Result: " .. string.byte(result, 1) .. " " .. string.byte(result, 2))
      tmr.delay(250000)
      tmr.wdclr()
    end

This code reads the ADC value of channel 1 (register 0x00) for 100 iterations, 4 times per second. The results are 2 - the ADC performs 2 approximation per 1 reading. When changing the potentiometer, one can see the first value is read before the second one. It is just fun to see the change of values.
Enjoy the code, let me know if it works for you.

I'll try also different/better i2c ADC devices as soon as I get the samples.
Attachments
schematics.png
Schematics of ESP8266 connected to PCF8591
User avatar
By debojitk
#51875 Hi,
Thannks for the writeup.
I am working on a project to have full duplex audio transmission. can you please tell me what bandwidth do you get on full duplex communication.

Thanks,
Debojit