NodeMCU – i2c scanner

I’m working on connecting char lcd 40×4 to esp via i2c. During all this I needed a i2c scanner to discover under what address something is connected to unit.

This scanner is available in NodeMCU boilerplate.

Scanner is in i2c_scan module. And its code traditionally is here:

local scanner = {}

scanner.pins = {
    sda = 1,
    scl = 2
}

scanner.port = 0

scanner.scan = function()
    print("     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f")    
    i2c.setup(scanner.port, scanner.pins['sda'], scanner.pins['scl'], i2c.SLOW)    
    for addr = 0, 127 do        
        if addr == 0 or addr % 16 == 0 then
            if addr ~= 0 then print(row) end
            row = string.format("%02X", addr)..": "
        end        
        i2c.start(scanner.port)
        c = i2c.address(scanner.port, addr, i2c.TRANSMITTER)
        i2c.stop(scanner.port)
        if c == true then
            row = row..string.format("%02X", addr).." "
        else
            row = row.."-- "
        end
    end
    print(row)
end

return scanner

 
By default it uses pins 1 for sda and 2 for scl.
How to use it ?

i2cscan = require "i2c_scan"
i2cscan.scan()

Or if you want to use different pins set them just before calling scan(). Script gives output similar to:

     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
20: 20 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
70: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s