gpio control function v001

Active today
Viewed 25 times

At the first part of the code(Initializing relays) the GPIO output works as expected, but at the second part it doesn’t works, I have break my head for the last four hours trying to find out what is happening here…

The updateGPIOstatuses method is executed as a thread:


The actual behaviour is: The second part of this code doesn’t turn on the relay from the relay board… But at the first part it does the job.

Any idea?

def updateGPIOstatuses(gpioCheckerInterval,gpioConfig): 

    #First part
    print('Initializing relays')

    for i in gpioConfig:   
        print('Relay '+str(i)+' on..')     

        GPIO.setup(i, GPIO.OUT)
        GPIO.output(i, GPIO.HIGH) 
        GPIO.output(i, GPIO.LOW)  
        print('Relay '+str(i)+' off..') 

    print('Initialization done')

    #Second part
    while True: 
        statuses={'gpio8': 0, 'gpio7': 0, 'gpio10': 0, 'gpio4': 0, 'gpio2': 0, 'gpio1': 1, 'device': '1', 'gpio5': 0, 'gpio3': 0, 'gpio9': 0, 'gpio6': 0}


        print(' ')

        for i in gpioConfig: 

            if newState==1:
                GPIO.output(i, GPIO.HIGH)

                GPIO.output(i, GPIO.LOW)


EXTRA: I forget to mention, the relay phisical state changes in the first part, but not in the second one, if I check the pin state at the second part after changing the pin value I get the correct value, but it doesn’t correspond to the phisical state of the current relay.

In resume, seems like the pin is correctly settled but the relay doesn’t, and as I said, only in the second part.

  • 1
    Your code is really confusing. You are passing in gpioConfig then setting it to [19] is that your intention? – CoderMike 8 hours ago
  • 1
    Does HIGH or LOW turn your relay on? – CoderMike 7 hours ago
  • 1
    setting it to 19 just for this example, normally it is passed from outside, I just want to test with one pin – Martin Ocando Corleone 7 hours ago
  • 1
    Yes, HIGH or LOW toggles the relay in the first part but not in the second one – Martin Ocando Corleone 7 hours ago
  • 1
    I added an extra info – Martin Ocando Corleone 7 hours ago
  • 1
    Does HIGH turn the relay on or does LOW turn the relay on? – CoderMike 6 hours ago
  • 1
    You should really only call setwarnings, setmode and setup once at the start of your code. – CoderMike 6 hours ago
  • 1
    Your second section only ever sets the relay HIGH because gpio1 returns 1. – CoderMike 5 hours ago
  • 1
    I knew it was a stupid thing lol. Years working with relays, code and stuff and making this kind of mistakes, yes you are right the relay won’t change its state to LOW because it is always is HIGH.. I fixed it now – Martin Ocando Corleone 5 hours ago
  • 1
    Thank you @CoderMike for help me to see it was inverted.. – Martin Ocando Corleone 5 hours ago
  • “I have break my head for the last four hours” – so you haven’t made a serious effort to debug your code? – Milliways 4 hours ago
  • Nice to read that @CoderMike already debugged in 4 minutes. So I think he should give the answer acceptable by the OP. I will anyway, complete my unacceptably 40 minutes long answer to show how one can still, systematically, methodically, and successfully, debug sooner or later, before his head got broken. Cheers. – tlfong01 4 hours ago   



User Requirements/Functional Specification

v0.1 – How to debug my program is less than 4 hours?

v0.2 – How to use Rpi control multiple relays?

v0.3 – How to use Rpi4B Thonny python 3.7.3 to control high logical level triggered relays?

v0.4 – How to use Rpi4B Thonny python 3.7.3 to control GPIO pins which in turn turn on and off multiple high level triggered relays?

v0.5 – How to use Rpi4B Thonny python 3.7.3, Rpi.GPIO.0.7.0/GpioZero 1.5.1 to control, interruptable/event driver/multiple processing/threading Rpi GPIO pins or MCP23017/s17 extended GPIO pins which in turn control multiple, up to 64 high level triggered 3V3/5V0 relays?

v0.6.1 – How to use GPIO/GpioZero to control gpio pin pins? v0.6.2 – How to use gpio pins to control multiple relays? v0.6.3 – How to use python list/dictionary data structure/algorithm to develop declarative style relay control systems.

Note 1 – V0.6.3 above is what the OP actually using python threading, dictionary declaration, list processing techniques, to write his program. Now I am going to use his program as a case study to explain to python newbies, how his program works, and how to guarantee successful debugging in less than 40 minutes.

Make it as simple as possible (Occam Razor Cutting) steps

Step 1 – Cutting too higher level stuff/functions, eg multi-threading

The multi-threading function to start a new thread (update GPIO pin(s) status), in not relevant to debugging at the current, lower, thread level, so should be cut first.

thread.start_new_thread (updateGPIOstatus, (updateInterval, gpioPinList,))

Reference – Python – Multithreaded Programming – tutoriaspoint

The general function definition is the following:

thread.start_new_thread (function, args[, kwargs])

Step 2 – Cutting to lower level stuff/functions (eg. GPIO initialization)

The OP uses the following statement often, and to make things not go wrong easily, it is a good idea to make it a “function”, sort of cutting lower level stuff and hide it (Info Hiding) or abstract it (ADT, Abstract Data Type).

GPIO.setup(i, GPIO.OUT)
GPIO.output(i, GPIO.HIGH) 

The other GPIO initialization steps, though used only once, can also be hidden in a higher level function. Depend on application, there are different ways to do the multi-level, nested function definitions. For our case study here, let me give an example program with these functions. My program for now is called gpioControl001.py, later I will uplevel to ledControl001.py, relayControl001, and so on.

/ to continue, …


Ah, let me see, I think I can very likely find the bug in less than 40 minutes,

(1) Get my Occam’s razor (KISS),

(2) Morning coffee time, ..

Update – Since @CodeMike has already given an answer acceptable to the OP, I will, nevertheless, still complete my answer, focusing on debugging skills (actually software engineering/development methodology), to encourage/comfort those newbie programmers like me, without sharp eyes and a clear/vivid mind, can still catch the nasty bug sooner or later, with guarantee that no one’s head will be broken.


Appendix A – The code

relay code**strong text**

Appendix B – KISS

KISS Principle – Wikipedia

The principle most likely finds its origins in similar minimalist concepts, such as Occam’s razor, Leonardo da Vinci’s “Simplicity is the ultimate sophistication”, Shakespeare’s “Brevity is the soul of wit“, Mies Van Der Rohe’s “Less is more“, Bjarne Stroustrup‘s “Make Simple Tasks Simple!“, or Antoine de Saint Exupéry’s “It seems that perfection is reached not when there is nothing left to add, but when there is nothing left to take away“. Colin Chapman, the founder of Lotus Cars, urged his designers to “Simplify, then add lightness“. Heath Robinson machines and Rube Goldberg’s machines, intentionally overly-complex solutions to simple tasks or problems, are humorous examples of “non-KISS” solutions.

A variant – “Make everything as simple as possible, but not simpler” – is attributed to Albert Einstein, although this may be an editor’s paraphrase of a lecture he gave.

Appendix C – Occam’s Razor

Occam’s razor – Wikipedia

Occam’s razor is the problem-solving principle that states that “Entities should not be multiplied without necessity.

The idea is attributed to English Franciscan friar William of Ockham (1287–1347), a scholastic philosopher and theologian who used a preference for simplicity to defend the idea of divine miracles.

It is sometimes paraphrased by a statement like “the simplest solution is most likely the right one”, but is the same as the Razor only if results match.

Occam’s razor says that when presented with competing hypotheses that make the same predictions, one should select the solution with the fewest assumptions, and it is not meant to be a way of choosing between hypotheses that make different predictions.

Similarly, in science, Occam’s razor is used as an abductive heuristic in the development of theoretical models rather than as a rigorous arbiter between candidate models.

In the scientific method, Occam’s razor is not considered an irrefutable principle of logic or a scientific result; the preference for simplicity in the scientific method is based on the falsifiability criterion.

For each accepted explanation of a phenomenon, there may be an extremely large, perhaps even incomprehensible, number of possible and more complex alternatives.

Since one can always burden failing explanations with ad hoc hypotheses to prevent them from being falsified, simpler theories are preferable to more complex ones because they are more testable.

Appendix D – William Occam

William of Ockham (Occam, c. 1280—c. 1349) – IEP

w occam

In logic, Ockham presents a version of supposition theory to support his commitment to mental language. Supposition theory had various purposes in medieval logic, one of which was to explain how words bear meaning.

Theologically, Ockham is a fideist, maintaining that belief in God is a matter of faith rather than knowledge. Against the mainstream, he insists that theology is not a science and rejects all the alleged proofs of the existence of God. Ockham’s ethics is a divine command theory. In the Euthyphro dialogue, Plato (437-347 B.C.E.) poses the following question: Is something good because God wills it or does God will something because it is good? Although most philosophers affirm the latter, divine command theorists affirm the former.

Ockham’s divine command theory can be seen as a consequence of his metaphysical libertarianism. In political theory, Ockham advances the notion of rights, separation of church and state, and freedom of speech.


Categories: Uncategorized

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: