Relay control with Raspberry Pi and Python3 - python-3.x

below is a section of code I am using to control a relay to open electric gates via a relay which is controlled via pin 7 on a raspberry pi GPIO. The gates only need a momentary voltage (via the relay contacts) to open.
My question is, what do I need to add to this code to make the relay only switch on for 0.5 Seconds when pin 7 goes high. This would enable relay to return to the off state and then wait for the next time GPIO pin 7 goes high, the gates do not need any commands from the GPIO to close after a certain time, they close under the control of the separate gate control system.
if name=="gate":
GPIO.setmode(GPIO.BOARD) ## Use board pin numbering
GPIO.setup(int(7), GPIO.OUT) ## Setup GPIO Pin to OUTPUT
GPIO.output(int(7), state) ## State is true/false
Many thanks
Peter

In this example I will use gpiozero library instead of RPi.GPIO because I like the way, how this library handle events.
from gpiozero import Button, OutputDevice
from time import sleep
from signal import pause
buttonPin = 4
relayPin = 7
button = Button(buttonPin)
button.when_pressed = ButtonPressedCallback
relay = OutputDevice(relayPin)
def ButtonPressedCallback():
relay.on()
sleep(0.5)
relay.off()
pause()
I hope, I understood your question good.

Related

Raspberry Pi 4: Keep the Physical Pin output remain HIGH until set to LOW

Looks like I just discovered something from the Raspberry Pi board. That is, command GPIO.output(led_pin,GPIO.HIGH) sets the output pin high only momentary. I originally thought it keeps the led_pin HIGH until I set it OFF. I was wrong. Again, I have to give time command to tell how long to keep it HIGH.
My question is, how to make the Pin output remain HIGH once set unless I set it again to LOW.
My code for keeping the Pin output HIGH for 5 seconds:
import RPi.GPIO as GPIO
import time
# To disable warning in the console
GPIO.setwarnings(False)
led_pin = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(led_pin,GPIO.OUT)
# Set the led Pin to HIGH
GPIO.output(led_pin,GPIO.HIGH)
# Keep led ON for 5 seconds
time.sleep(5)

i want to communicate with 'TestEquity1000' temperature chamber by using 'pyserial'

i want to set and get temperature of serial device (testequity1000) by using pyserial but not able to communicate.
cable used RS232
python 3.7
import serial
port = 'COM20'
` serial_comunication = serial.Serial(port, baudrate=9600, timeout=1)
answer = serial_comunication.read(400)
print(answer)
NEW_TEMPERATURE=45
set_temp=serial_comunication.write(b'NEW_TEMPERATURE')
print(set_temp)
abc=serial_comunication.close()
print(abc)
results:
b''
15
None
can't understand these result
Your device seems to be able to communicate on the RS232 bus but you have to use Modbus instead of the raw serial.
Quoting from the manual:
The F4 Temperature Controller has an RS-232C interface. A DB-9
connector is located on the rear panel. It is wired to accommodate a
null-modem cable. To communicate with the controller from a PC, you
need to run software that uses the Modbus RTU protocol. Each
controller function has a “register” number which can be read or
written to (when applicable). These registers are listed Chapter Seven
of the “Series F4 User’s Manual”. RS-232C Modbus programming resources
and LabVIEW drivers can be downloaded from
http://chamber.testequity.com/rs232.html
Common Modbus Registers
-Actual chamber temperature reading is register 100 (Input 1 Value).
-Actual chamber humidity reading is register 104 (Input 2 Value).
-Static temperature set point is register 300 (Set Point 1).
-Static humidity set point is register 319 (Set Point 2). •
-Temperature set point during a profile is register 4122 (Set Point 1, Current Profile Status).
-Humidity set point during a profile is register 4123 (Set Point 2, Current Profile Status).
-Decimal points are implied. For example, 1005 is actually 100.5 and -230 is -23.0.
Based on these details you can use pymodbus instead. A good starting point is this example.
You can install the package with: pip install pymodbus
So, if you want to read the Actual Chamber Temperature you need to write something similar to this:
#!/usr/bin/env python
# Pymodbus Synchronous Client Examples
# --------------------------------------------------------------------------- #
# import the various server implementations
# --------------------------------------------------------------------------- #
from pymodbus.client.sync import ModbusSerialClient as ModbusClient
# --------------------------------------------------------------------------- #
# configure the client logging
# --------------------------------------------------------------------------- #
import logging
FORMAT = ('%(asctime)-15s %(threadName)-15s '
'%(levelname)-8s %(module)-15s:%(lineno)-8s %(message)s')
logging.basicConfig(format=FORMAT)
log = logging.getLogger()
log.setLevel(logging.DEBUG)
UNIT = 0x1
# ------------------------------------------------------------------------#
# choose the client you want
# ------------------------------------------------------------------------#
client = ModbusClient(method='rtu', port='COM20', timeout=1, baudrate=19200)
client.connect()
# ----------------------------------------------------------------------- #
# example requests
# ----------------------------------------------------------------------- #
rr = client.read_holding_registers(100, 1, unit=UNIT) #Actual chamber temperature reading
print(rr.registers[0])
# ----------------------------------------------------------------------- #
# close the client
# ----------------------------------------------------------------------- #
client.close()
You might need to change the default baudrate (according to the manual 19200) and/or the Modbus UNIT ID (UNIT 1 is the default value).
Hello I actually just finished using a little something in python. TestEquity chamber for the RS-232 you need to use modbus RTU protocol.
I'm using minimalmodbus. The other thing is that you need to make sure that you are using a null modem Tx and Rx need to be swapped in the DB9 connector.
Check the baudrate and slave address in setup, communications.
My code is here:
import minimalmodbus
TE1007C = minimalmodbus.Instrument("COM5", 1)
# Set baudrate
TE1007C.serial.baudrate = 9600
temp = TE1007C.read_register(100, 1, signed=True)
print(temp)
To set a temperature use write_register(). There are other registers that can be use.

RPi.GPIO pins - check state

I'm using the RPi.GPIO module in Python to turn on and off GPIO pins on the Raspberry Pi 3.
Is there a way to identify whether an output pin is ON or OFF and put that value into a variable that I can use to decide whether the pin is ON and needs to turn OFF, or is OFF and needs to turn ON.
from the docs
The code below should provide the functionality you are looking for.
import RPi.GPIO as GPIO
channel = 11
GPIO.setmode(GPIO.BCM)
# Setup your channel
GPIO.setup(channel, GPIO.OUT)
GPIO.output(channel, GPIO.LOW)
# To test the value of a pin use the .input method
channel_is_on = GPIO.input(channel) # Returns 0 if OFF or 1 if ON
if channel_is_on:
# Do something here

GPIO interrupt triggered by different pin

tl;dr:
Listening to a RISING event on GPIO PIN14 (with 10K pulldown resistor); Ghost RISING events when sending/receiving data on different GPIO pin;
I have the following issue:
In my technical room I have a Raspberry Pi 1B, and Raspberry Pi 3; I tested this on both units and I get the same results;
My mains meter has a flashing LED, 1000/kWh; I want to measure this using a photo resistor; The photo resistor is connected to GPIO PIN14; This setup works just fine, as long as I don't use any of the other GPIO pins.
Using the same unit I want to send some data over 433Mhz (GPIO PIN7, but as soon as I transmit data, I get RISING events on PIN14...
Across the internet I found different solutions, none of which seem to be working:
Use a different Raspberry Pi (B1 is a tad bit old)
Use a 10K pull down resistor on PIN14
Use a different power supply
Use separate power supplies for the raspberry pi, photo resistor, and 433Mhz transmitter
Using the code below, I can see expected behavior of the photo resistor and PIN14; But as soon as I startup the transmissions, the events of sending a message and RISING events on PIN14 synchronize. When I stop sending messages the listener on PIN14 stops working.
Does anyone have any idea how to fix this?
PIN14 Listener code:
import datetime
import time
try:
import RPi.GPIO as GPIO
except RuntimeError:
print(
'Error importing RPi.GPIO! This is probably because you need superuser privileges.')
delta = datetime.timedelta(microseconds=100000)
global last_electric_ping
last_electric_ping = datetime.datetime.now()
GPIO.setmode(GPIO.BCM)
GPIO.setup(14, GPIO.IN)
def electric_ping(channel):
if GPIO.input(14):
global last_electric_ping
now = datetime.datetime.now()
if delta + last_electric_ping <= now:
print(delta + last_electric_ping, end=" ")
print('ELECTRIC')
last_electric_ping = now
GPIO.add_event_detect(14, GPIO.RISING, callback=electric_ping)
while True:
continue
GPIO.cleanup()
Transmission code:
import time
from pi_switch import RCSwitchSender
sender = RCSwitchSender()
sender.enableTransmit(15) # use WiringPi pin 0
num = 1
while True:
time.sleep(1)
print("Woei!")
sender.sendDecimal(num, 24)
num += 1
Roll the drums:
Apparently I ran into a numbering issue; The BCM pin numbering says physical pin 8 is GPIO14, which is nice;
Now three guesses which number wiringPi gives to physical pin number 8... yes, number 15! Which is the one I'm trying send data to in the second script;
Now excuse while I go slap myself with a brick in the corner over there...

Tell when Bluetooth module connects on Arduino

I'm working on a project with Android and Arduino and am trying to figure out how on the Arduino side to tell if the Bluetooth is connected or not.
I'm using one of these Bluetooth Modules to connect. I know I can send a command through Android, but I'm trying to have an action happen automatically when they connect and not have to run a background application on the Android if possible.
Using the module supplied and nothing else you cannot: notice the module has four connectors:
Power (Vcc)
Ground
Tx (send)
Rx (receive)
Given this interface the only way to determine whether the bluetooth module is paired is to send something to the paired device and have it respond in such as way that your Arduino knows that it is connected. For instance, if your Android program always responds with "Hi there!" when it receives a string "Hello?", then by seingin "Hello?" your Arduino will know that it is paired with your Android phone/tablet. Your Arduino could poll (send the interrogation string) every minute (or every five seconds) to see if it is paired with your device.
There is a better way, but it will require some soldering on your part. If your module is HC-03/HC-05-based, then the PIO9 pin is the "paired indicator LED" (see datasheet here). You could connect that pin to an Arduino input pin and read the level: reading digital 1 will indicate that the device is paired, while reading digital 0 will indicate that it is not. It is possible, though not certain, that the pin on your module labeled STATE is exactly this kind of a pin, i.e. it indicates the paired status. Unfortunately. this pin it isn't connected to the header, so you'll have to solder a wire to the correctponding pad to connect it to your Arduino. You should test it first by connecting a multimeter in voltage mode to that pad and measure the potential between that pad and ground in paired and non-paired state. If this is the pin that responds to the paired state then you are golden. It might be that it indicates power (like the HC-03/05 PIO8 whilc blinks when on). If it turns out that the STATE pin is not the pairing status, then you should request a datasheet from your supplier, and use that to find the status LED connection: one is likely to exist. Once you found the correct pad, verify its function using the voltmeter again. Then solder a wire to that connection and read it from your Arduino.
IMPORTANT: Make sure that your Arduino never puts out a digital 1 on the Arduino pin connected to the bluetooth module status pin: these bluetooth modules run on 3.3V, and connecting any unprotected pins to 5V will be damaging. The Vcc and Txd pins are voltage shifted in the module you bought, but the LED/Status lines are likely not to be. So if the Arduino pin connected to "status" on your Bluetooth module is configured as output and you digitalWrite(HIGH) to it, you will likely damage the Bluetooth module.
Unfortuntaely, the HC-05 will switch states when paired, but won't output a 1 until it's actually connected to something.
For instance, I can unpair my phone from the HC-05, pair again, and then the LED will change state, but the output of the STATE pin is still 0. If I open up an app, and connect to the device manually then the LED, and STATE pin will change state. The LED will periodically blink twice, and the STATE pin outputs a 1 to the Arduino.
If you would like to read the the value of the STATE pin, connect a wire to any of the inputs to the arduino, and code Serial.println(digitalRead(inputPin)); inputPin being the wire to the input of the Arduino.
I've been fighting this thing for months, and have yet to find a way to make this thing automatically connect to my phone. It won't even allow for me to connect to it from my phone to the HC-05 unless I download an app onto my Android. It's possible to bind the HC-05 to a certain address, but even this did not work for me. I want to mess with the "AT+CLASS" command, but the documentation behind the instruction has hindered me thus far.
From the HC-05 datasheet we see that the connection status depends on the output from PI09. Apparently sending "AT+BIND?" to the module will return the status of PI08 & PI09 in the form,
"+ POLAR=PI08,PI09" however this makes no sense to me because in order to get this you must enter AT mode and entering AT mode will disrupt the paired connection, hence it will always send PI09 marked as "not connected".
THUS in order to see if the connection is still live from the arduinos POV I can only see 2 feasible ways:
Program arduino to, every so often, send a "hello?" and if it doesn't receive the expected "Hi back" response, then it is to assume that it isn't connected.
Connect PI09 to an arduino input pin and read it's value whenever you want to check if the connection is live or not
AT+STATE? will return the current state of the connection. Yes you will need to enter at mode, that is done by bringing up pin 11 HIGH on the HC05 module. It does require soldering but it's kinda worth it. It then allows full AT control of the device, then set it LOW to return it to normal working mode.
Another option, which I don't fully understand, is the AT+MPIO? command, which returns the state of all the pins in some strange masked format I don't understand yet.
I use the first option above so that I can terminal (Bluetooth) from my phone to the HC05 and switch on a led/relay etc (ie bring up pin 2 to HIGH) on the HC05. This required entering AT mode (pin 11 HIGH), sending the command AT+PIO=2,1 and then setting pin 11 to LOW to return to normal working mode.
Note: I noticed I had to put a 200ms delay in between high and AT and LOW commands. Angela's solution is nice - I use a cheap XBEE Bluetooth module (HC-05 Bluetooth Bee Master & Slave Module with Bluetooth XBee for Arduino uk2015) 2 units(HC05/6) for 5Stg which are laid out in XBEE format - handy for the 3.3v.

Resources