User avatar
tlfong01
Posts: 840
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Sun Sep 09, 2018 7:00 am

tlfong01 wrote:
Fri Sep 07, 2018 7:10 am
petermeigs wrote:
Thu Sep 06, 2018 11:04 pm
1. I am doing some tests to see what happens if the mcp23017 gets changes too quickly.
2. Then I run the following code of the raspberry pi zero: ...
3. However, if I remove the sleep(0.1) I don't get all the interrupts on the MCP23017 side and the program seems to hang. ...
MCP23xxx hanging up problem
I did not read your code because I always find it hard to read other people's code.

MCP23017 Interrupt Signal Handling Speed

So you are worrying that if more than one 24VAC supply drop at the same time, MCP23017 won't be quick enough to respond?

But I think if you connect 5 power drop signals to 5 MCP23017 GPIO port pins, they can be processed in parallel (well almost).

Perhaps you can easily check as below.

1. Set GPIO Port A all 8 pins as output, Port B all 8 pins as input. Connect Port A output to Port B input.

2. Configure Interrupt Change Mode as compare previous.

3. Clear all interrupt flags.

4. Write all one's to Port A, then write all zero's again to Port A

5. Read Interrupt Capture Register B, and see how many interrupt flags are set.
Attachments
cjmcu2317_2018sep0901.jpg
cjmcu2317_2018sep0901.jpg (101.41 KiB) Viewed 1672 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 840
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Sun Sep 09, 2018 8:07 am

tlfong01 wrote:
Sun Sep 09, 2018 7:00 am
tlfong01 wrote:
Fri Sep 07, 2018 7:10 am
petermeigs wrote:
Thu Sep 06, 2018 11:04 pm
1. I am doing some tests to see what happens if the mcp23017 gets changes too quickly.
But I think if you connect 5 power drop signals to 5 MCP23017 GPIO port pins, they can be processed in parallel (well almost).

MCP23017 Interrupt Signal Handling Speed

MCP23017 I2C and SPI speed is over 1MHz. So they should be fast enough to handle home automation applications.

My worry is that the bus capacitance is a bit large. No wonder even I use I2C bus extenders, I still find transmission error intermittently.
Attachments
mcp23017_spec_2018sep0901.jpg
mcp23017_spec_2018sep0901.jpg (109.61 KiB) Viewed 1664 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 840
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Sun Sep 09, 2018 9:40 am

petermeigs wrote:
Sat Sep 08, 2018 6:11 am
tlfong01 wrote:
Fri Sep 07, 2018 7:10 am
I did not read your code because I always find it hard to read other people's code. ..
Putting on my dull professor hat, with regard to reading other people's code, I'd like to suggest that this is an important skill. I find that I learn many new and interesting tips because someone has approached a problem in a way foreign to what I would have done. When that happens, there is often a new technique to be added to my bag of tricks. Sometimes, it's a nice way to express a common action that makes clear what the author intends. To butcher a quote: "We all stand taller if we stand on the shoulders of giants who have gone before us." (or something like that) ...

MCVE (Minimal, Complete, and Verifiable Example)

I very much agree that reading other people's code is an important skill. However, you talk like a prof, and you code like a pro. Pro's code is usually not that MCV and therefore I often found it hard to follow.

If you sprinkle a little bit more comments on your code, and also add the configuration value to IOCON etc, perhaps I can verify more easily. And because I don't use Rpi GPIO, I prefer everything on MCP23017.

Appendix - MCVE

How to create a Minimal, Complete, and Verifiable example
https://stackoverflow.com/help/mcve

When asking a question about a problem caused by your code, you will get much better answers if you provide code people can use to reproduce the problem. That code should be…

…Minimal – Use as little code as possible that still produces the same problem

…Complete – Provide all parts needed to reproduce the problem

…Verifiable – Test the code you're about to provide to make sure it reproduces the problem

Minimal

The more code there is to go through, the less likely people can find your problem. Streamline your example in one of two ways:

Restart from scratch. Create a new program, adding in only what is needed to see the problem. This can be faster for vast systems where you think you already know the source of the problem. Also useful if you can't post the original code publicly for legal or ethical reasons.

Divide and conquer. When you have a small amount of code, but the source of the problem is entirely unclear, start removing code a bit at a time until the problem disappears – then add the last part back.

Minimal and readable

Minimal does not mean terse – don't sacrifice communication to brevity. Use consistent naming and indentation, and include comments if needed to explain portions of the code. Most code editors have a shortcut for formatting code – find it, and use it! Also, don't use tabs – they may look good in your editor, but they'll just make a mess on Stack Overflow.

Complete

Make sure all information necessary to reproduce the problem is included:

Some people might be prepared to load the parts up, and actually try them to test the answer they're about to post.

The problem might not be in the part you suspect it is, but another part entirely.

If the problem requires some server-side code as well as an XML-based configuration file, include them both. If a web page problem requires HTML, some JavaScript and a style sheet, include all three.

Verifiable

To help you solve your problem, others will need to verify that it exists:

Describe the problem. "It doesn't work" is not a problem statement. Tell us what the expected behavior should be. Tell us what the exact wording of the error message is, and which line of code is producing it. Put a brief summary of the problem in the title of your question.

Eliminate any issues that aren't relevant to the problem. If your question isn’t about a compiler error, ensure that there are no compile-time errors. Use a program such as JSLint to validate interpreted languages. Validate any HTML or XML.

Ensure that the example actually reproduces the problem! If you inadvertently fixed the problem while composing the example but didn't test it again, you'd want to know that before asking someone else to help.

It might help to shut the system down and restart it, or transport the example to a fresh machine to confirm it really does provide an example of the problem.

For more information on how to debug your program so you can create a minimal example, Eric Lippert has a fantastic blog post on the subject: How to debug small programs.

You may have been told to include an MCVE by some helpful commentary, or perhaps even an MVCE if they were rushed; sorry for the initialisms, this is what they were referring to.

How do I ask a good question? - Stack Exchange
https://meta.stackexchange.com/help/how-to-ask

We’d love to help you. To improve your chances of getting an answer, here are some tips:

Search, and research

Have you thoroughly searched for an answer before asking your question? Sharing your research helps everyone. Tell us what you found and why it didn’t meet your needs. This demonstrates that you’ve taken the time to try to help yourself, it saves us from reiterating obvious answers, and above all, it helps you get a more specific and relevant answer!

Be on-topic

Our community is defined by a specific set of topics that you can view in the help center; please stick to those topics and avoid asking for opinions or open-ended discussion. If your question is about the site itself, ask on our meta-discussion site. If you’re looking for a different topic, it might be covered on another Stack Exchange site.

Be specific

If you ask a vague question, you’ll get a vague answer. But if you give us details and context, we can provide a useful answer.

Make it relevant to others

We like to help as many people at a time as we can. Make it clear how your question is relevant to more people than just you, and more of us will be interested in your question and willing to look into it.

Keep an open mind

The answer to your question may not always be the one you wanted, but that doesn’t mean it is wrong. A conclusive answer isn’t always possible. When in doubt, ask people to cite their sources, or to explain how/where they learned something. Even if we don’t agree with you, or tell you exactly what you wanted to hear, remember: we’re just trying to help.
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 840
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Sun Sep 09, 2018 2:18 pm

Brandon92 wrote:
Thu Sep 06, 2018 5:15 pm
If you have issues with the I2C connection in a electrically noisy environments you could consider to use a differential I2C-bus*, then you have no issues any more.

PCA9615 Differential I2C Bus Extender

I have never heard of this thing before. It looks good if I want to do I2C over 100ft. Unluckily it is a bit expensive for poor hobbyists - Sparkfun is selling a breakout board for USD10. I could not find any cheap version in AliExpress or TaoBao. So I will not consider it now.

Your recommended I2C extender P82B715 is already very good, for my I2C circuits with too many I2C devices.

Appendix - PCA9615 Differential I2C

SparkFun Differential I2C Breakout PCA9615 (Qwiic) - USD10
https://www.sparkfun.com/products/14589

PCA96152-channel multipoint Fast-mode Plus differential I2C-busbuffer with hot-swap logic - NXP 10 May 2016
https://www.nxp.com/docs/en/data-sheet/PCA9615.pdf

Qwiic Differential I2C Bus Extender (PCA9615) Hookup Guide - Sparkfun
https://learn.sparkfun.com/tutorials/qw ... okup-guide

The SparkFun Differential I2C Breakout is the fastest and easiest way to extend the range of your I2C communication bus. The breakout uses NXP’s PCA9615 IC, which converts the two default I2C signals into four differential signals, two for SCL and two for SDA.

The differential signals are sent over an Ethernet cable, which attaches to the breakout through the on-board RJ-45 connectors The differential signaling allows the I2C signals to reach distances of up to 100ft. while still maintaining their signal integrity!

To make it even easier to get your readings, all communication is enacted exclusively via I2C, utilizing our handy Qwiic system so no soldering is required to connect it to the rest of your system. However, we still have broken out 0.1"-spaced pins in case you prefer to use a breadboard.

The simplicity of the Differential I2C Breakout is one of its biggest appeals. Other I2C communication methods require packetizing I2C communication into another protocol, be it RS-485 or 1-Wire. However, the PCA9615 keeps the I2C protocol by utilizing a differential transceiver.

Whether you need to extend the range of an I2C sensor on an autonomous vehicle plagued with noise from motors or want to create a vast sensor network in your home or office, the Qwiic Differential I2C Breakout is a great solution to extend distance and reduce noise susceptibility.

The SparkFun Qwiic connect system is an ecosystem of I2C sensors, actuators, shields and cables that make prototyping faster and less prone to error. All Qwiic-enabled boards use a common 1mm pitch, 4-pin JST connector. This reduces the amount of required PCB space, and polarized connections mean you can’t hook it up wrong.

Update 2018sep11hkt1439

I read the NXP I2C extender and differential buffer ICs and surprisingly found that:

  • they extend wiring to not more than 3 meters!
  • without extender/buffer, I2C capacitance limit is only 400pf, so even a single MCP23017 with a no guarantee max cap of 400pf might have a problem!
Attachments
i2c_ext_dif_2018sep1101.jpg
i2c_ext_dif_2018sep1101.jpg (188.98 KiB) Viewed 1571 times
Last edited by tlfong01 on Tue Sep 11, 2018 12:22 pm, edited 5 times in total.
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 840
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Mon Sep 10, 2018 3:02 am

tlfong01 wrote:
Sun Sep 09, 2018 2:18 pm
PCA9615 Differential I2C Bus Extender
I have never heard of this thing before. It looks good if I want to do I2C over 100ft. Unluckily it is a bit expensive - Sparkfun sell a breadout board for USD10. I could not find any cheaper version in AliExpress or TaoBao. So I will not try it now.
You recommended I2C extender P82B715 is already very good, for my I2C circuits with too many I2C devices.

I2C Bus Multiplier

The other I2C toy I might try later is the following:

RE: I2C-GPIO DTOVERLAY BUS NUMBER stardustJerry 2018-Feb-20
https://www.raspberrypi.org/forums/view ... 6#p1275627
I am an electronics and smart home hobbyist.

petermeigs
Posts: 74
Joined: Thu Mar 23, 2017 1:34 pm
Location: Los Altos, California

Re: GPIO.input voltage levels vs edge detection

Tue Sep 11, 2018 6:23 am

I've been doing tests with the MCP23017 attached to a raspberry pi 3b+. I have concluded that the handling of data read by the MCP23017 using interrupts should always be done with the INTA and INTB NOT mirrored. In other words, the INTA and INTB interrupts should be handled separately. (Though the same callback routine can be used for both)

Here's why:

I am driving it with a raspberry pi zero w. I have 8 gpio ports on the pi-zero connected to 8 ports of the MCP23017 BANK A and another connected to BANK B. I have the starting GPIO output to ON or HIGH.
Using the python GPIO package, I can turn on OFF or more GPIO ports on the pi-zero and observe the effect on the 3b+.

On the 3b+, I have connected the INTA and INTB lines to two GPIO ports, (GPIO27 and 22, in my case).
I have set the all of the MCP23017 ports to input, and INTERRUPT-ON-CHANGE, and turned on the PULL-UPs for all of the MCP23017 GPIO pins on both banks. The Interrupt pins for INTA and INTB are set to Active-HIGH. INTA and INTB are NOT mirror allowing the two banks to change the interrupt pins independently.

When the program starts up, it sets a callback for the two GPIO ports 27 and 22. One is associated with BANK A and the other with BANK B. When an interrupt occurs, it means 1 or more bits in the corresponding bank is changed. The callbacks are written to complete as quickly as possible. No io is done in the callback routine in order to avoid the interrupt processing to be delayed. They capture which port has the interrupt (to know if it is BANKA or BANKB), the bits for the GPIO BANK, and the INTF , the interrupt Flag Register and add it to a thread-safe Queue

I have observed that if I keep the interrupts un-MIRRORed, then the pi-zero can change bits without any delay. Note that a particular pin cannot be toggled to quickly or the MCP23017 will not detect the change. However, different bits can be turned on quickly. If multiple bits are turned on at the same time (or close to the same time), the interrupt will happen for that bank and all of the changed bits will appear in the GPIO register. All of the bits changes will be accounted for.

However, if I set the interrupts to MIRRORed, (i.e "The INT pins are internally connected", or rather a change in either bank will cause the INT to be toggled) the program only works reliably when bit changes occur slowly enough.

PS, I have a connection between GPIO4 on the pi-zero and the GPIO4 on the 3b+ so that the pi-zero program can signal the 3b+ when to start and when to stop.

At the risk of having folks read other people's poorly documented code, here it all is. I'll go ahead because I find sample code very helpful.

I'll add a circuit diagram later.

Here is my program to handle the MCP23017:

Code: Select all

#!/usr/bin/env python3
import smbus
import sys
import RPi.GPIO as RPIGPIO
import time
import traceback
import queue
from datetime import datetime
from datetime import timedelta

bus = None
starttime = None
state3ime = None
state = None
eventqueue = queue.Queue()
userelay = False
usedebug = False

RELAY    = 23           # relay to turn on 24vac
DEVICE_ADDRESS = 0x20   # MCP23017 address to use
# default addresses

BANKA   = 0
BANKB   = 1
NOTIFY  = 2            # notification pin = TRUE means ready to send FALSE means done

IODIR      = 0x00 # Pin direction register A
IPOL       = 0x02 # Input polarity regsiter A
GPENTEN    = 0x04 # Interrupt on change pins A
IOCON      = 0x0a # Config register A  Bank, Mirror, SEQOP, DISSLW, HAEN, ODR, TPOL, N/U
GPPU       = 0x0c # 100k ohm pullups A
GPIO       = 0x12 # GPIO pins
INTF       = 0x0e # interupt flag register

# IOCON I/O Expander Configuration bits
iocBANK   = 0x80 # if 1 registers are in different banks
iocMIRROR = 0x40 # if 1 INT pins are ORed togetther
iocSEQOP  = 0x20 # if 1 address pointer does not increment
iocDISSLW = 0x10 # if 1 Slew rate disabled

iocHAEN   = 0x08 # if 1 Hardware address enable MCP23S17 only
iocODR    = 0x04 # if 1 open drain output, overrides INTPOL
iocINTPOL = 0x02 # if 1 Active-high (sets polarity of INT output pin




# map of gpioports given bank

GPIOINT = {
    BANKA : 22, # gpio connected to port A interrupt line.
    BANKB : 27,  # gpio connected to port A interrupt line.
    NOTIFY : 4,  # notification from other side
}

# map of banks given gpioport
GPIOINTREV = {}
for bank, gpioport in GPIOINT.items():
    GPIOINTREV[gpioport] = bank

MASKBITS = {
    BANKA : 0x00FF, # BANKA are low order bits
    BANKB : 0xFF00, # BANKB are high order bits
}

# put bits in BANKB byte and and also in BANKA
def bothBanks(bits):
    bits = bits & 0xff
    return (bits << 8) | bits

# these routines try to deal with the MCP23017 as a 16bit register rather than 2 8 bit registers
# intbits determine whether to read reg for bank A or B or both.
# returns 16 bit value with B in high order and A in low order
def readREG(port, intbits = 0xFFFF):
    # need to separate bus reads because we don't want to clear an interupt we aren't handling
    # intbits will be non-zero in top 8 and/or bottom 8
    pinAdata = 0
    pinBdata = 0
    if (intbits >> 8) & 0xFF:
        pinBdata = bus.read_byte_data(DEVICE_ADDRESS, port + BANKB)
    if intbits & 0xFF:
        pinAdata = bus.read_byte_data(DEVICE_ADDRESS, port + BANKA)
    return (pinBdata << 8) | pinAdata

# intbits determine whether to set reg for bank A or B or both.
# sets B from high order and A from low order if any bit is set in the corresponding by
# int intbits

def writeREG(port, data, intbits = 0xFFFF):
    # only write to the BANK we need to
    if (intbits >> 8) & 0xFF:
        bus.write_byte_data(DEVICE_ADDRESS, port + BANKB, (data >> 8) & 0xFF)
    if intbits & 0xFF:
        bus.write_byte_data(DEVICE_ADDRESS, port + BANKA, data & 0xFF)
    return None

# read next item in the queue and print it out
# queue consists of a list per entry
def getQueueItem(eventqueue):
    queueitem = eventqueue.get()
    itemtime, gpiolevel, bank, intfBA, pinBA, gpioport = tuple(queueitem)
    # get time difference object and calculater elapsed time string
    mstime = itemtime - starttime
    elapsed = "%d"%mstime.seconds + ".%06d"%mstime.microseconds
    message = ""
    # check to see if any bits changed other that those causing the interrupt
    if (intfBA | pinBA) != intfBA:
        message = ", intFA !~ pinBA"
    print ("Elapsed=%s, gpiolevel=%d, bank=%d, intfBA = 0x%04x, pinBA = 0x%04x, gpioport=%d%s"%(elapsed, gpiolevel, bank, intfBA, pinBA, gpioport, message))
    return queueitem

def my_callback(gpioport):
    # Note: Multiple interupts can occur simultaneously
    global bus
    global state
    global state3time
    # we have the gpioport but need the bank
    bank = GPIOINTREV[gpioport]
    nowtim = datetime.utcnow()
    gpiolevel = RPIGPIO.input(GPIOINT[bank])
    if bank == NOTIFY:
        intfBA    = 0x0000
        pinBAbits = 0x0000
        if gpiolevel == 0:
            state = 1
        else:
            state = 3
            state3time = nowtim
    else:
        maskBits = MASKBITS[bank]
        intfBA = readREG(INTF, maskBits)  # findout which pin changed
        # maskBits = intfBA
        if gpiolevel:     # if port 25 == 1
            if usedebug:
                print("level up clear interrupt")
            pinBAbits = readREG(GPIO, maskBits) # get the BANK's pin value and clear interrupt
            if usedebug:
                print("----------level up bank=%d, infBA= 0x%04x, pinBA= 0x%04x" %(bank, intfBA, pinBAbits))
        else:                  # if port 25 != 1
            if usedebug:
                print("level dn clear interrupt")
            pinBAbits = readREG(GPIO, maskBits) # get the BANK's pin value and clear interrupt
            if usedebug:
                print("----------level dn bank=%d, infBA= 0x%04x, pinBA= 0x%04x" %(bank, intfBA, pinBAbits))
    eventqueue.put([nowtim, gpiolevel, bank, intfBA, pinBAbits, gpioport])
    return

def init():
    global bus
    starttime = datetime.utcnow()

    bus = smbus.SMBus(1)    # 0 = /dev/i2c-0 (port I2C0), 1 = /dev/i2c-1 (port I2C1)

    # port A & B all in input bits
    writeREG(IODIR, 0xFFFF)

    # reverse input values.  This is because A3700 is low when upper threshold is detected
    writeREG(IPOL,  0xFFFF)

    # Activate all internal pullup resistors at Port A & B for output:
    writeREG(GPPU, 0xFFFF)

    # disable interupts on change
    writeREG(GPENTEN, 0x0000)

    # clear any previous interrupts
    writeREG(GPIO, 0x0000)
    pinBAbits = readREG(GPIO)

    # I/O Expander config register. Set INT pins NOT internally connected, Interupt polarity Active-high
    # for both A & B
    writeREG(IOCON, bothBanks(iocINTPOL)) #  | iocMIRROR))
    # enable interupts on change
    writeREG(GPENTEN, 0xFFFF)

    time.sleep(1)

    RPIGPIO.setwarnings(False)
    RPIGPIO.setmode(RPIGPIO.BCM)
    RPIGPIO.setup(RELAY, RPIGPIO.OUT)    # set GPIO24 as output
    RPIGPIO.output(RELAY, False)

    # set up all interrupt
    for bank, thisGPIOINT in GPIOINT.items():
        RPIGPIO.setup(thisGPIOINT, RPIGPIO.IN, pull_up_down=RPIGPIO.PUD_UP)    # set interrupt from MCP23017
        # when a changing edge is detected on OPTO1 port, regardless of whatever
        # else is happening in the program, the function my_callback will be run
        cbType = RPIGPIO.RISING
        if thisGPIOINT == GPIOINT[NOTIFY]:  # want both rising and falling for NOTIFY
            cbType = RPIGPIO.BOTH
        RPIGPIO.add_event_detect(thisGPIOINT, cbType, callback=my_callback)
        # RPIGPIO.add_event_detect(GPIOINT, RPIGPIO.BOTH, callback=my_callback)
        # RPIGPIO.add_event_detect(GPIOINT, RPIGPIO.FALLING, callback=my_callback)
    pass


def main():
    global bus
    global starttime
    global state # 0 = not started, 1 = on, 2 = off, 3= zero reached
    global state3time
    sleeptime = 0.1  # 5ms
    print("start=========================================================")
    init()
    starttime = datetime.utcnow()

    state = 0
    if userelay:
        print ("----------- Relay on")
        RPIGPIO.output(RELAY, True)
        print("ON, state = " + str(state))
    state3time = None
    while state < 3:
        elapsedtime = datetime.utcnow() - starttime
        if userelay and elapsedtime.seconds > 4 and state != 2:
            print ("----------- Relay off")
            RPIGPIO.output(RELAY, False)
            state = 2
            print("OFF, state = " + str(state))

        time.sleep(sleeptime)
        while not eventqueue.empty():
            queueitem = getQueueItem(eventqueue)
            if state == 0:
                continue
            if False and queueitem[3] == 0x8000 and queueitem[4] == 0x0000:
                print("End detected.")
                state3time = datetime.utcnow()
                state = 3

    # drain queue in case other events came in after end event
    while (datetime.utcnow()- state3time).seconds < 2:
        time.sleep(sleeptime)
        while not eventqueue.empty():
            queueitem = getQueueItem(eventqueue)

    pass

    # while (True):
    #     pin = RPIGPIO.input(GPIOINT)
    #     print( "pin = %i"%pin)
    #     time.sleep(1)
    #
    pass

if __name__ =='__main__':
    try:
        main()
    except KeyboardInterrupt:
        pass
    except:
        traceback.print_exc()
        pass
    RPIGPIO.cleanup()
    print ("Done")


And here is my code to handle the pi-zero simulation driver

Code: Select all

#!/usr/bin/env python3
## on esp
import sys
import RPi.GPIO as GPIO
import time
from datetime import datetime
from datetime import timedelta
from time import sleep     # this lets us have a time delay (see line 12)
import traceback

# table of connections from simulator rpi zero
# to MCP23017 on driven raspberry pi 3b+
# layout designed so wires follow sequentially on both MCP23017 and raspberry pi header
# uses only generic rpi GPIO pins, skipping rpi pins useful for other things (SPI, I2C, txd/rxd

MCPRESET = [ {
        "name" : "Reset MCP", # name of connection
        "color" : "green",    # wire color
        "mcp"  : "0x0000",    # NOT MCP line
        "gpio" :  4           # BCM GPIO number
    },
]
MCPRESET0 = MCPRESET[0]
lines = [
    {
        "name" : "BankA 0",   # name of connection
        "color" : "white",    # wire color
        "mcp"  : "0x0001",    # bit setting for ((GPIO-B << 8) | GPIO-A) on MCP20137
        "gpio" :  21          # BCM GPIO number
    },
    {
        "name" : "BankA 1",
        "color" : "black",
        "mcp"  : "0x0002",
        "gpio" :  20
    },
    {
        "name" : "BankA 2",
        "color" : "brown",
        "mcp"  : "0x0004",
        "gpio" :  16
    },
    {
        "name" : "BankA 3",
        "color" : "red",
        "mcp"  : "0x0008",
        "gpio" :  12
    },
    {
        "name" : "BankA 4",
        "color" : "orange",
        "mcp"  : "0x0010",
        "gpio" :  25
    },
    {
        "name" : "BankA 5",
        "color" : "yellow",
        "mcp"  : "0x0020",
        "gpio" :  24
    },
    {
        "name" : "BankA 6",
        "color" : "green",
        "mcp"  : "0x0040",
        "gpio" :  23
    },
    {
        "name" : "BankA 7",
        "color" : "blue",
        "mcp"  : "0x0080",
        "gpio" :  18
    },
    {
        "name" : "BankB 0",
        "color" : "black",
        "mcp"  : "0x0100",
        "gpio" :  17
    },
    {
        "name" : "BankB 1",
        "color" : "white",
        "mcp"  : "0x0200",
        "gpio" :  27
    },
    {
        "name" : "BankB 2",
        "color" : "gray",
        "mcp"  : "0x0400",
        "gpio" :  22
    },
    {
        "name" : "BankB 3",
        "color" : "violet",
        "mcp"  : "0x0800",
        "gpio" :  5
    },
    {
        "name" : "BankB 4",
        "color" : "blue",
        "mcp"  : "0x1000",
        "gpio" :  6
    },
    {
        "name" : "BankB 5",
        "color" : "green",
        "mcp"  : "0x2000",
        "gpio" :  13
    },
    {
        "name" : "BankB 6",
        "color" : "yellow",
        "mcp"  : "0x4000",
        "gpio" :  19
    },
    {
        "name" : "BankB 7",
        "color" : "orange",
        "mcp"  : "0x8000",
        "gpio" :  26
    },
]


#port init
def init():
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)
    for line in MCPRESET + lines:
        print ("Setup %s" % line["name"])
        GPIO.setup(line["gpio"], GPIO.OUT)
        GPIO.output(line["gpio"], True)
    pass


def main():
    init()
    sleep(1)
    slice = 1
    GPIO.output(MCPRESET0["gpio"], False)
    sleep(1)
    for line in lines: # [slice : slice+1]:
        # print("----------- On: %s, gpio=%d, mcp=%s"%(line["name"], line["gpio"], line["mcp"]))
        GPIO.output(line["gpio"], False)
        # sleep(0.5)
    sleep(2)
    for line in lines: # [slice : slice+1]:
        # for line in lines: # [slice : slice+1]:
        # print("Off: %s, gpio=%d, mcp=%s"%(line["name"], line["gpio"], line["mcp"]))
        GPIO.output(line["gpio"], True)
        # sleep(1)
        # sleep(1)

    sleep(2)
    GPIO.output(MCPRESET0["gpio"], True)

if __name__ =='__main__':
    try:
        main()
    except KeyboardInterrupt:
        pass
    except:
        traceback.print_exc()
        pass
    GPIO.cleanup()

User avatar
tlfong01
Posts: 840
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Tue Sep 11, 2018 7:05 am

petermeigs wrote:
Tue Sep 11, 2018 6:23 am
I've been doing tests with the MCP23017 attached to a raspberry pi 3b+.

I have concluded that the handling of data read by the MCP23017 using interrupts should always be done with the INTA and INTB NOT mirrored.

I have observed that if I keep the interrupts un-MIRRORed, then the pi-zero can change bits without any delay. Note that a particular pin cannot be toggled to quickly or the MCP23017 will not detect the change.

However, different bits can be turned on quickly. If multiple bits are turned on at the same time (or close to the same time), the interrupt will happen for that bank and all of the changed bits will appear in the GPIO register. All of the bits changes will be accounted for.

However, if I set the interrupts to MIRRORed, (i.e "The INT pins are internally connected", or rather a change in either bank will cause the INT to be toggled) the program only works reliably when bit changes occur slowly enough.

At the risk of having folks read other people's poorly documented code, here it all is. I'll go ahead because I find sample code very helpful.

MCP23017 Interrupt Mirroring Problem

Oh my goodness, so as Warren Buffett says: "There's never just one cockroach in the kitchen."

The hobbist won't study the pro coder's program for now, but might verify his conclusion using hobbyist tricks. Anyway, it seems safe to follow the brave guy now, because he has not fried any Rpi yet :) .
I am an electronics and smart home hobbyist.

petermeigs
Posts: 74
Joined: Thu Mar 23, 2017 1:34 pm
Location: Los Altos, California

Re: GPIO.input voltage levels vs edge detection

Tue Sep 11, 2018 2:29 pm

tlfong01 wrote:
Tue Sep 11, 2018 7:05 am
The hobbist won't study the pro coder's program for now, but might verify his conclusion using hobbyist tricks. Anyway, it seems safe to follow the brave guy now, because he has not fried any Rpi yet :) .
Actually, I very much like the MCP23017. Not only does it protect the pi but as it can independently powered (I think), it means that we are less worried about voltages greater than 3.3vdc that the Pi would not like. The programming is a little less straightforward but once you get the hang of it, I think cleaner code will result because you aren't having to deal with a bunch of GPIO pins independently. I would never have know about this device except for these discussions. -- Thanks

Brandon92
Posts: 540
Joined: Wed Jul 25, 2018 9:29 pm
Location: Netherlands

Re: GPIO.input voltage levels vs edge detection

Tue Sep 11, 2018 3:19 pm

petermeigs wrote:
Tue Sep 11, 2018 2:29 pm
tlfong01 wrote:
Tue Sep 11, 2018 7:05 am
The hobbist won't study the pro coder's program for now, but might verify his conclusion using hobbyist tricks. Anyway, it seems safe to follow the brave guy now, because he has not fried any Rpi yet :) .
Actually, I very much like the MCP23017. Not only does it protect the pi but as it can independently powered (I think), it means that we are less worried about voltages greater than 3.3vdc that the Pi would not like. The programming is a little less straightforward but once you get the hang of it, I think cleaner code will result because you aren't having to deal with a bunch of GPIO pins independently. I would never have know about this device except for these discussions. -- Thanks
That is not 100% true. If you apply a voltage higher than vdd +0.6. Because of the internal protection diode. It will go to your power rail. For example, if you apply a voltage of 5v on a input of the mcp. You can expect that the 3.3v power rail will rise. And if everything is ideal, the 3.3v becomes 4.4v.

And there are special ic that will galvanic isolate your I2C bus.

petermeigs
Posts: 74
Joined: Thu Mar 23, 2017 1:34 pm
Location: Los Altos, California

Re: GPIO.input voltage levels vs edge detection

Tue Sep 11, 2018 4:23 pm

Brandon92 wrote:
Tue Sep 11, 2018 3:19 pm
That is not 100% true. If you apply a voltage higher than vdd +0.6. Because of the internal protection diode. It will go to your power rail. For example, if you apply a voltage of 5v on a input of the mcp. You can expect that the 3.3v power rail will rise. And if everything is ideal, the 3.3v becomes 4.4v.

And there are special ic that will galvanic isolate your I2C bus.
Thanks, I had not gotten far enough to think this through. I could see from the datasheet that MCP230xx could operate up to 5.5 vdc but had not though through the implications. I did find some discussion (which I admit I did not read carefully yet) where 5v and 3.3 volts were mixed on multiple mcp230xx's. They included level shifters in the diagram to deal with that. That should have been my first clue it was not going to as simple as to just wire it up and expect the MCP230xx to magically deal with the higher voltage for me.

I don't think I will have this problem unless the water flow meter I am looking at (Hunter HC 100) takes me in that direction. Its pretty durable and are about 120.00USD each for the 1-in version (sorry, we are still not on metric here) . Í found a local supply store that carries them and they charge less that Amazon.

That unit uses a magnetic reed switch that completes (pulses) a 5vdc circuit for every unit of flow. I was thinking of yet another HCPL 3007 to deal with that more cleanly. I notice there are low current versions of the HCPL 3007 so I hope that will get me into the right range for reliable pulse detection.

User avatar
tlfong01
Posts: 840
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Wed Sep 12, 2018 3:05 am

tlfong01 wrote:
Mon Sep 10, 2018 3:02 am
tlfong01 wrote:
Sun Sep 09, 2018 2:18 pm
PCA9615 Differential I2C Bus Extender
I have never heard of this thing before. It looks good if I want to do I2C over 100ft. Unluckily it is a bit expensive - Sparkfun sell a breadout board for USD10. I could not find any cheaper version in AliExpress or TaoBao. So I will not try it now.

TSSOP10 to DIP10 Converter for PCA9615 Differential I2C Bus Extender

Or I should try the following cheap solution for hobbyists:

SOT23 MSOP10 SOP10 UMAX to DIP10 Transfer Board DIP Pin Board Pitch Adapter
https://www.aliexpress.com/item/10PCS-S ... autifyAB=0

SSOP10 to DIP10 0.65 converter socket
https://item.taobao.com/item.htm?spm=a1 ... dmg8j26111

DI2C -THE DIFFERENTIAL VERSION OF I2C
http://www.electronics-lab.com/di2c-dif ... rsion-i2c/

An Introduction to Differential I2C - Joshua Vasquez
https://hackaday.com/2017/03/31/an-intr ... -i%C2%B2c/

An Introduction to I2C Over Long Wires - Joshua Vasquez
https://hackaday.com/2017/02/08/taking- ... ong-wires/

What Could Go Wrong? I2C Edition - Elliot Williams July 19, 2016
https://hackaday.com/2016/07/19/what-co ... c-edition/
I am an electronics and smart home hobbyist.

Brandon92
Posts: 540
Joined: Wed Jul 25, 2018 9:29 pm
Location: Netherlands

Re: GPIO.input voltage levels vs edge detection

Wed Sep 12, 2018 8:40 pm

When you use a "transfer board" with the correct IC. Its not a only a solution for a hobbyists. But also easy for testing a IC on your breadboard. Without buying / making a pcb.

User avatar
tlfong01
Posts: 840
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Thu Sep 13, 2018 6:05 am

Brandon92 wrote:
Wed Sep 12, 2018 8:40 pm
When you use a "transfer board" with the correct IC. Its not a only a solution for a hobbyists. But also easy for testing a IC on your breadboard. Without buying / making a pcb.

Yes, so I am going to try SMD soldering.

How To Do SMD Soldering

How To Do SMD Soldering - BuildElectronicCircuits 2012
https://www.build-electronic-circuits.c ... soldering/
https://www.build-electronic-circuits.c ... soldering/
http://www.reconnsworld.com/griddle_reflow.html
https://www.amazon.com/gp/product/B00XN ... &slotNum=3

Taiwan Pro's Kit 2 in 1 Hot Air Rework Workstation - 470 Yuan
https://item.taobao.com/item.htm?spm=a1 ... dmg8j26111

Update 2018sep14hkt2001

SparkFun SSOP-16 to DIP Adapter Hookup Guide
https://learn.sparkfun.com/tutorials/ss ... okup-guide

Adafruit SSOP Test Sockets
https://www.adafruit.com/product/1280
https://www.youtube.com/watch?time_cont ... KmigWOlIGY
Last edited by tlfong01 on Fri Sep 14, 2018 12:07 pm, edited 2 times in total.
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 840
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Thu Sep 13, 2018 7:50 am

petermeigs wrote:
Tue Sep 11, 2018 2:29 pm
1. Actually, I very much like the MCP23017. Not only does it protect the pi but as
2. it can independently powered (I think), it means that we are less worried about voltages greater than 3.3vdc that the Pi would not like.
3. The programming is a little less straightforward but once you get the hang of it,
4. I think cleaner code will result because you aren't having to deal with a bunch of GPIO pins independently.
5. I would never have know about this device except for these discussions. -- Thanks

MCP23017 for cleaner code, and much more, ...

1. Yes, that is why I dare not to risk letting Rpi GPIO talk to MCP23017, but I won't stop the brave guy doing so. :)

2. Yes, actually I never used MCP23017 in 3V3. I am an ex 5V Arduino guy. I hate stupid 3V3 circuits.

5V I2C MCP23017) RE: RELAY MODULE KY-019 5V Post by tlfong01 » 2018-Sep-05 Wed 11:22 am
https://www.raspberrypi.org/forums/view ... 5#p1361576

3. MCP23017 is actually very complicated, and not at all for faint heart Rpi newbies.

4. Yes, using MCP23017 lets us write cleaner code, but there are many more advantages, ...

5. How nice to see one more guy got hooked to MCP23017 and all have fun together.

Update 2018sep14hkt1638

PS - I learnt about MCP23008 when reading MagPi some years ago.

Expanding your senses with I2C - Difficulty: Advanced, MagPi Issue 16, 2013 Sep
https://www.raspberrypi.org/magpi-issues/MagPi16.pdf (pages 4~10)

(MagPi on MCP23008) RE: RELAY MODULE KY-019 5V Postby tlfong01 » 2018-Aug-10 Fri 10:26 am
https://www.raspberrypi.org/forums/view ... 0#p1351223
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 840
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Sat Sep 15, 2018 7:01 am

tlfong01 wrote:
Thu Sep 13, 2018 6:05 am
Brandon92 wrote:
Wed Sep 12, 2018 8:40 pm
When you use a "transfer board" with the correct IC. Its not a only a solution for a hobbyists. But also easy for testing a IC on your breadboard. Without buying / making a pcb.
Yes, so I am going to try SMD soldering.
Adafruit SSOP Test Sockets
https://www.adafruit.com/product/1280
https://www.youtube.com/watch?time_cont ... KmigWOlIGY

Poorman's SSOP Test Sockets

But then I found TaoBao selling cheap SSOP test sockets, only 14 yuan each, about 20 times cheaper than the expensive US toys for rich hobbyists.

I placed my order direct at the ShenZhen factory Thursday afternoon, and the goods by express delivery arrived next day afternoon, in just 24 hours. :D
Attachments
sop28todip065_2018sep1501.jpg
sop28todip065_2018sep1501.jpg (175.94 KiB) Viewed 1404 times
I am an electronics and smart home hobbyist.

petermeigs
Posts: 74
Joined: Thu Mar 23, 2017 1:34 pm
Location: Los Altos, California

Re: GPIO.input voltage levels vs edge detection

Wed Sep 19, 2018 12:46 pm

Rather than long I2C cable, perhaps it might be feasible to use something like esp8266 Huzzah from Adafruit, https://www.adafruit.com/product/2471. I believe it can connect i2c, it is cheap, low power, and can connect to wifi. By placing this right next to your i2c device, the long cable issues would go away. This would turn a hardware problem into a software problem if you are near enough to your wifi hub. If you are worried about security, it supports ssl encrypted communications.

If you load nodemcu, you can program it with javascript-like scripting language. I've had good luck with this even though I had never used this language before. I have used nodejs and it's close to the same flavor.

Otherwise, you could program it like an arduino with the c programming language. (Which I have not tried yet). I think there is a python that runs on it, also not used by me

I suppose you would have to worry about interference with wifi but the communications protocol should have sorted that out.

User avatar
tlfong01
Posts: 840
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Wed Sep 19, 2018 2:42 pm

petermeigs wrote:
Wed Sep 19, 2018 12:46 pm
Rather than long I2C cable, perhaps it might be feasible to use something like esp8266 Huzzah from Adafruit, https://www.adafruit.com/product/2471. I believe it can connect i2c, it is cheap, low power, and can connect to wifi. By placing this right next to your i2c device, the long cable issues would go away. This would turn a hardware problem into a software problem if you are near enough to your wifi hub. If you are worried about security, it supports ssl encrypted communications.

If you load nodemcu, you can program it with javascript-like scripting language. I've had good luck with this even though I had never used this language before. I have used nodejs and it's close to the same flavor.

Otherwise, you could program it like an arduino with the c programming language. (Which I have not tried yet). I think there is a python that runs on it, also not used by me

I suppose you would have to worry about interference with wifi but the communications protocol should have sorted that out.

ESP8266 Brainstorming Notes

I am thinking of doing a couple of things together, including feasibility study of using esp8266. I know esp8266 talks microPython, and I have been using microPython with pyBoard and bbcMicro. So esp8266 is attractive to me. And so many people are talking about esp8266, I might play with it just to check out why it is so popular, besides it is cheap.

Update 2018sep19hkt2300

I skimmed through the microPython for esp8266 to check out if there is anything new.

I found the following things that make me hesitate to start. Point 1 is a big problem.

microPython for ESP8266 Tutorial
https://docs.micropython.org/en/latest/ ... intro.html

1. ... Be aware of and try to exclude hardware problems. There are 2 common problems: bad power source quality and worn-out/defective FlashROM.

2. REPL or webREPL is not attractive to me, because of my about 100 hours using REPL, I think it is too slow comparing to Rpi3B+ IDLE python.

3. I still think any thing ESP8266 can do, Rpi3B+ (not RpiZW) can do better. Errata - See Below

One thing I can think of that pyBoard or ESP8266, that they can be RTOS (Real Time Operating System), but my toy projects won't need that real time features.

Update 2018sep2001hkt0853

I found the following article useful. It points out a couple of my wrong perspectivess on ESP8266.

Raspberry Pi WiFi With The ESP8266 Monday, 12 September 2016
https://www.i-programmer.info/programmi ... 8266-.html

Update 2018sep20hkt0937

NodeMcu looks interesting. I might buy one to learn about it.

(Micro Python) RE: COMMUNICATION BETWEEN NODEMCU ESP8266 AND RASPI3 Post by OutoftheBOTS » 2018-Jun-02 Sat 5:43 am
https://www.raspberrypi.org/forums/view ... 7#p1322874

(MQTT) PI + ESP8266 COMMUNICATION Post by luisromoro » 2017-Aug-29 Tue 8:22 pm
https://www.raspberrypi.org/forums/view ... 6#p1204212

NodeMCU - Wikipedia
https://en.wikipedia.org/wiki/NodeMCU

NodeMCU Documentation
https://nodemcu.readthedocs.io/en/master/

(Node Mcu) RE: PI + ESP8266 COMMUNICATION Post by jadro » 2017-Aug-29 Tue 10:12 pm
https://www.raspberrypi.org/forums/view ... 6#p1204266

Risym NodeMcu IoT Development Board ESP8266 Serial Wifi Module - ¥24.40
https://detail.tmall.com/item.htm?spm=a ... abbucket=9

Update 2018sep21hkt1152

I googled further and more or less made up my mind to test the water by doing the following.

1. Buy a NodeMCU friendly ESP8266 board
2. Start learning LUA (forget microPython for now)
3. Study how to let Rpi and NodeMCU talk to each other

I found LUA similar to python in a couple of ways, such its Table which is similar to python Dictionary, dynamically typing, list/array processing.

And I started ESP8266/NodeMCU not to solve the long distance I2C problem (which I think I2C extender and differential buffer can do), but because it is good for IoT applications, which is essential to my home automation projects.


ESP8266 - Wikipedia
https://en.wikipedia.org/wiki/ESP8266

NodeMCU - Wikipedia
https://en.wikipedia.org/wiki/NodeMCU

Lua - Wikipedia
https://en.wikipedia.org/wiki/Lua_(prog ... _language)

E-book: ESP8266 and MicroPython - Elektor
https://www.elektor.com/esp8266-and-micropython-e-book
Project “Remote Web Based Control”: You will be developing a system that will remotely control two LEDs connected to a NodeMCU development board using an HTTP Web Server application.

Errata 2018sep22hkt2112

I was very wrong in saying that anything ESP8266 can do, Rpi can do better. Actually Esp8266 has a WiFi module, but Rpi doesn't. Of course Rpi can add a WiFi module, but then why not use the very cheap esp8266 straight away. One other thing is that NodeMCU has LUA which is very powerful for IoT development.

In short, many WiFi and IoT things esp8266 can do, Rpi simply cannot.
Last edited by tlfong01 on Sat Sep 22, 2018 1:17 pm, edited 4 times in total.
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 840
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Thu Sep 20, 2018 11:59 am

tlfong01 wrote:
Sat Sep 15, 2018 7:01 am
Poorman's SSOP Test Sockets
But then I found TaoBao selling cheap SSOP test sockets, only 14 yuan each, about 20 times cheaper than the expensive US toys for rich hobbyists.
I placed my order direct at the ShenZhen factory Thursday afternoon, and the goods by express delivery arrived next day afternoon, in just 24 hours. :D


PCA9615 Package
Attachments
pca9615_package_2018sep2003.jpg
pca9615_package_2018sep2003.jpg (153.17 KiB) Viewed 1293 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 840
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Fri Sep 21, 2018 4:33 am

tlfong01 wrote:
Wed Sep 19, 2018 2:42 pm
I googled further and more or less made up my mind to test the water by doing the following.
1. Buy a NodeMCU friendly ESP8266 board
2. Start learning LUA (forget microPython for now)
3. Study how to let Rpi and NodeMCU talk to each other


CH340 NodeMcu V3 Lua WIFI ESP8266

New wireless module CH340 NodeMcu V3 Lua WIFI Internet Development Board based things ESP8266 - US$2.36
https://es.aliexpress.com/item/NodeMcu- ... Title=true
Attachments
esp8266_ch430_2018sep2102.jpg
esp8266_ch430_2018sep2102.jpg (160.3 KiB) Viewed 1271 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 840
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Fri Sep 21, 2018 4:45 am

tlfong01 wrote:
Fri Sep 21, 2018 4:33 am
CH340 NodeMcu V3 Lua WIFI ESP8266
New wireless module CH340 NodeMcu V3 Lua WIFI Internet Development Board based things ESP8266 - US$2.36
https://es.aliexpress.com/item/NodeMcu- ... Title=true

CH340 NodeMcu V3 Lua WIFI ESP8266 pinout
Attachments
nodemcu_devkit_2018sep2101.jpg
nodemcu_devkit_2018sep2101.jpg (232.52 KiB) Viewed 1202 times
Last edited by tlfong01 on Fri Sep 21, 2018 2:10 pm, edited 1 time in total.
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 840
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Fri Sep 21, 2018 7:51 am

tlfong01 wrote:
Fri Sep 21, 2018 4:45 am
CH340 NodeMcu V3 Lua WIFI ESP8266 pinout

NodeMCU Documentation Summary

Now I have skimmed through NodeMCU docs and made a summary for future reading.

NodeMCU Documentation
https://nodemcu.readthedocs.io/en/maste ... dules/i2c/

NodeMCU is an open source Lua based firmware for the ESP8266 WiFi SOC

Getting Started
https://nodemcu.readthedocs.io/en/maste ... uick-start

Programming Model
The NodeMCU programming model is similar to that of Node.js, only in Lua. It is asynchronous and event-driven. Many functions, therefore, have parameters for callback functions. For more extensive examples have a look at the /lua_examples folder in the repository on GitHub.

Lua Flash Store (LFS)
In September 2018 support for a Lua Flash Store (LFS) was introduced. LFS allows Lua code and its associated constant data to be executed directly out of flash-memory; just as the firmware itself is executed. This now enables NodeMCU developers to create Lua applications with up to 256Kb Lua code and read-only constants executing out of flash. All of the RAM is available for read-write data!

Getting Started aka NodeMCU Quick Start
The basic process to get started with NodeMCU consists of the following three steps.
1. Build the firmware with the modules you need
2. Flash the firmware to the chip
3. Upload code to the device.


nodeMCU FAQ
https://nodemcu.readthedocs.io/en/maste ... loper-faq/

Programming in Lua (first edition)
http://www.lua.org/pil/contents.html

LUA Users Wiki
http://lua-users.org/wiki/

Espressif IoT SDK: Programming Guide
https://www.mikrocontroller.net/attachm ... v0.9.5.pdf

eLua
http://www.eluaproject.net/overview

node MCU FAQ Reading Notes

NodeMCU Lua

The NodeMCU libraries act as C wrappers around registered Lua callback functions to enable these to be used as SDK tasks. You must therefore use an Event-driven programming style in writing your ESP8266 Lua programs. Most programmers are used to writing in a procedural style where there is a clear single flow of execution, and the program interfaces to operating system services by a set of synchronous API calls to do network I/O, etc. Whilst the logic of each individual task is procedural, this is not how you code up ESP8266 applications.


How does the SDK event / tasking system work in Lua?

The SDK uses a small number of Interrupt Service Routines (ISRs) to handle short time critical hardware interrupt related processing.

All other service and application processing is split into code execution blocks, known as tasks. The individual tasks are executed one at a time and run to completion. No task can never pre-empt another.


NodeMCU Modules List

adc
ads1115
adxl345
am2320
apa102
bit
bloom
bme280
bme680
bmp085
cjson
coap
color-utils
cron
crypto
dht
ds18b20

encoder
enduser setup
file
gdbstub
gpio
hdc1080
hmc5883l

http
hx711
i2c
l3g4200d
mcp4725
mdns
mqtt
net
node
ow (1-Wire)
pcm
perf
pwm
rc
rfswitch
rotary
rtcfifo
rtcmem
rtctime
si7021
sigma delta
sjson
sntp
somfy
spi
sqlite3
struct
switec
tcs34725
tls
tm1829
tmr
tsl2561
u8g2
uart
ucg
websocket
wifi
wifi.monitor
wps
ws2801
ws2812
ws2812-effects
xpt2046


.END
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 840
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Fri Sep 21, 2018 8:15 am

tlfong01 wrote:
Fri Sep 21, 2018 7:51 am
NodeMCU Documentation Summary
Now I have skimmed through NodeMCU docs and made a summary for future reading.
NodeMCU Documentation
https://nodemcu.readthedocs.io/en/maste ... dules/i2c/

My First NodeMCU Custom Built

So I have my first custom built. It is fun playing a toy in the cloud. :D

NodeMCU custom builds
https://nodemcu-build.com/
You customize your NodeMCU firmware and we build it. Just for you. On the spot.

NodeMCU custom build results
From: "NodeMCU custom build" <[email protected]>
To: [email protected]
Sent: Friday, September 21, 2018 4:06:04 PM
Subject: NodeMCU custom build finished

Your NodeMCU custom build finished successfully. You may now download the firmware:

- float: http://nodemcu-build.com/builds/nodemcu ... -float.bin (576kB)

- integer: http://nodemcu-build.com/builds/nodemcu ... nteger.bin (560kB)

This was built against the master branch and includes the following modules:

file, gpio, i2c, net, node, spi, tmr, uart, wifi.

The files are guaranteed to be available for download for 24h.
Attachments
nodemcu_built_2018sep2101.jpg
nodemcu_built_2018sep2101.jpg (169.55 KiB) Viewed 1230 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 840
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Fri Sep 21, 2018 10:19 am

tlfong01 wrote:
Fri Sep 21, 2018 8:15 am
My First NodeMCU Custom Built
So I have my first custom built. It is fun playing a toy in the cloud. :D
Your NodeMCU custom build finished successfully. You may now download the firmware:

Installing esptool.py

So far so good. So I moved on to flash the firmware, my custom built. I read the follow instructions:

How to flash the firmware
https://nodemcu.readthedocs.io/en/master/en/flash/.

README.md esptool.py
A Python-based, open source, platform independent, utility to communicate with the ROM bootloader in Espressif ESP8266 ...

Installation
The latest stable esptool.py release can be installed from pypi via pip:

$ pip install esptool

After installing, you will have esptool.py installed into the default Python executables directory and you should be able to run it with the command

$esptool.py.

...


*** I HATE LINUX !!! ***

So I used the command "pip install esptool" to install esptool.py and the installation completed successfully in less than 2 minutes.

But when I tried to execute the following command I got into big trouble!

$esptool.py

I got error messages like "could not find file or directory"

I googled and learnt the tricks to find the default python executable directory, etc, etc. But I wasted two hours struggling just to run a python file which the ugly linux system always says "no such directory or file".

I knew how to use commands such 'cd', 'ls' etc but I still got errors because I have problems getting to the 'home' directory or 'root directory'.

(But I was happy to find why I need to use the stupid prefix thing "./" when running a local exec file.)

Anyway, it is only after running a python program in IDLE to get the absolute path of the esptool.py then I figured out the command I should use is the following:

raspberrypi: $python /home/pi/.local/bin/esptool.py -h

linux spoiled my day. :(

update 2018sep21hkt2138

While googling earlier, I guess that the 'pi' in '/home/pi' is an alias, and that you cannot cd to an alias. (alias might look like a file or directory, but actually it is a short name or pointer.) I googled more about this alias thing and found it confusing (one post seems to say that there more than one definition for Bash alias!)

Anyway, I got fed up with linux shell terminal commands, so I gave up digging deeper. Instead I just make an alias for the long command for my own use, as below:

$ alias = '/home/pi/.local/bin/esptool.py'

So I can now type the alias:

'esptool'

to run the python program esptool.py (in the default python executables directory).

.END
Last edited by tlfong01 on Mon Sep 24, 2018 1:22 am, edited 1 time in total.
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 840
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Fri Sep 21, 2018 2:38 pm

tlfong01 wrote:
Fri Sep 21, 2018 10:19 am
Installing esptool.py
Anyway, I got fed up with linux shell terminal commands, so I gave up digging deeper. Instead I just make an alias for the long command for my own use, as below:
$ alias = '/home/pi/.local/bin/esptool.py'
So I can now type the alias:
'esptool'
to run the python program esptool.py (in the default python executables directory).

NodeMCU DEVKIT

I googled further and found that actually I don't need to use the stupid esptool.py in the newbie unfriendly linux terminal - there is the GUI NodeMCU DEVKIT to save the newbies.

NodeMCU DEVKIT V1.0 A development kit for NodeMCU firmware
https://github.com/nodemcu/nodemcu-devk ... /README.md
https://github.com/nodemcu/nodemcu-devkit

It will make NodeMCU more easy. With a micro USB cable, you can connect NodeMCU devkit to your laptop and flash it without any trouble, just like Arduino.

It is an open hardware, with ESP-12-E core [32Mbits(4MBytes) flash version.

It is designed by Altium Designer, and fully open–source. Now everyone can make their own NODEMCU.

I read the schematics and found that many of the GPIOs have already been used for UART, switches etc, so there are not that many GPIO pins left for the users.
Attachments
usbuart_2018sep2101.jpg
usbuart_2018sep2101.jpg (146.57 KiB) Viewed 1200 times
I am an electronics and smart home hobbyist.

User avatar
tlfong01
Posts: 840
Joined: Sat Jun 02, 2018 1:43 pm
Location: Hong Kong

Re: GPIO.input voltage levels vs edge detection

Fri Sep 21, 2018 2:52 pm

tlfong01 wrote:
Fri Sep 21, 2018 2:38 pm
NodeMCU DEVKIT
I googled further and found that actually I don't need to use the stupid esptool.py in the newbie unfriendly linux terminal - there is the GUI NodeMCU DEVKIT to save the newbies.
NodeMCU DEVKIT V1.0 A development kit for NodeMCU firmware
It is an open hardware, with ESP-12-E core [32Mbits(4MBytes) flash version.
It is designed by Altium Designer, and fully open–source. Now everyone can make their own NODEMCU.

Top 6 Esp8266 modules

Though I already made up my mind to start with Node MCU, I am curious what other boards by SparkFun and Adafruit are doing. So I read the following review to check out. I am surprised to find that there is one from India.

TOP 6 ESP8266 MODULES FOR IOT PROJECTS - Losant April 19, 2016
https://www.losant.com/blog/top-6-esp8266-modules
I am an electronics and smart home hobbyist.

Return to “Python”