Railway barriers are physical barriers that are used to prevent vehicles or pedestrians from crossing a railway track at an undesignated location. These barriers are typically made of steel or concrete, and are used to block access to the track while trains are passing through. The barriers can be raised or lowered depending on the state of the track, and are typically controlled by a signal system that receives information from trains about their location and speed. The barriers can be operated either manually or automatically, and are typically used in areas where there is a high risk of accidents, such as in urban areas or near level crossings. They also can be used to protect wildlife or people crossing the tracks in rural areas.
Simulating the functioning of railway barriers with ESP32 is a project that involves using an ESP32 microcontroller to control the movement of a model railway barrier. The ESP32 is a low-cost, low-power microcontroller board that has built-in WiFi and Bluetooth capabilities. It has a powerful processing capability, and can be programmed using the Micropython.
In this project, the ESP32 can be connected to a motor that controls the movement of the barrier, and programmed to raise and lower the barrier based on input from sensors or other devices. For example, you can use infrared sensors or ultrasonic sensors to detect the approaching of a train, and use this information to trigger the barrier to lower. Alternatively, you can use a push button or other input device to manually control the barrier’s movement. The ESP32 can also be programmed to communicate with other devices wirelessly, such as a remote control, a smartphone, or a computer, to control the barrier, or to receive status updates from the barrier.
In this project we will realize a system that simulate the operation of automatic barriers for railways trains.
We will design this system using:
two ultrasonic sensors hc-sr04 for the detection of the arrival of the train.
two servomotors to lower or raise the barriers
ESP32 card
An ESP32 card is a type of microcontroller card that is based on the ESP32 microcontroller. It is a small, compact, and powerful device that can be used to control various electronic devices, and it can be programmed using the Arduino Integrated Development Environment (IDE) and the ESP-IDF (ESP32 IoT Development Framework) .
HC-SR04 ultrasonic sensor
The HC-SR04 ultrasonic sensor is a low-cost and widely used sensor that can be used to detect the approaching of a train in a railway barrier system. This sensor uses an ultrasonic transducer to emit a sound wave and measure the time it takes for the wave to bounce back after hitting an object.
The HC-SR04 has four pins: VCC, Trig, Echo, and GND. The VCC pin is connected to the power supply, typically 5V for ESP32. The Trig pin is used to trigger the sensor to emit a sound wave, and the Echo pin is used to receive the reflected wave. The GND pin is connected to ground.
In a railway barrier system, the HC-SR04 ultrasonic sensor can be placed along the track to detect the approaching of a train. The sensor emits a sound wave by sending a signal to the Trig pin, and waits for the Echo pin to receive the reflected wave. By measuring the time delay between the signal and the echo, the sensor can calculate the distance to the train. When the train is detected within a certain range, the sensor sends a signal to the barrier control system which then triggers the barrier to lower.
A servo motor can be used to control the movement of a railway barrier by providing precise control over the position of the barrier. A servo motor is a type of actuator that uses a closed-loop control system to control the position of a shaft or other mechanical component.
A typical servo motor consists of a DC motor, a gear train, a position sensor (such as a potentiometer), and control electronics. The control electronics use the position feedback from the sensor to adjust the motor’s power and direction in order to move the shaft to the desired position.
In a railway barrier system, the servo motor can be connected to the barrier and controlled by the barrier control system to raise and lower the barrier. The control system can be programmed to move the servo to specific positions, corresponding to the barrier being fully raised or fully lowered. The servo can also be programmed to move the barrier to intermediate positions, for example, to partially lower the barrier for a slow-moving train.
The use of a motor servo in the railway barrier system allows for precise control of the barrier’s position, and also provides the ability to make fine adjustments to the barrier’s position in case of any errors. It’s important to choose a servo motor that has the appropriate torque and power rating to move the barrier smoothly and efficiently.
Supply power module
A supply power module is a device that is used to provide a stable and regulated power supply to a circuit or system. In the context of an ESP32 based railway barrier system, a 5V/3.3V supply power module can be used to provide a stable voltage to the microcontroller and the other electronic components of the system, such as the ultrasonic sensors, servo motor, and control electronics.
LEDs
LEDs (light-emitting diodes) can be used in a railway barrier system to indicate the state of the barrier and provide visual cues to the users. LEDs can be used to indicate when the barrier is in the raised or lowered position, when a train is approaching, or when a fault or error has occurred.
For example, a green LED can be used to indicate that the barrier is in the raised position, and a red LED can be used to indicate that the barrier is in the lowered position.
The LEDs can be connected to the control system, and their state can be controlled using the ESP32 microcontroller. The LEDs can be connected to digital output pins of the ESP32 board, and the state of the LED can be controlled by writing a digital signal to the corresponding pin.
The use of LEDs in the railway barrier system can help to improve the usability and safety of the system by providing clear and visible cues to the users about the state of the barrier and any potential hazards. It’s important to choose LEDs that are visible under different lighting conditions, and that are durable and reliable.
test plate
A test plate is a device that is used to perform tests or experiments on a circuit or system. In the context of an ESP32 based railway barrier system, a test plate can be used to test and debug the system before it is deployed in a real-world setting.
A test plate typically includes a set of input and output connectors, such as push buttons, LEDs, and sensors, that can be used to simulate real-world inputs and observe the system’s response. It can also include power supply connectors and a power switch to enable the test plate to be powered on and off.
The test plate can be used to test the functionality of the system and its components, such as the microcontroller, the ultrasonic sensors, the servo motor, and the control electronics. For example, you can use the test plate to simulate a train approaching and observe the system’s response by lowering the barrier and turning on the yellow LED. You can also use the test plate to test the system’s reaction to different inputs or scenarios, such as manual operation, or a fault in the system.
connecting wires
Connecting wires are used to connect the various components of a circuit or system together. In the context of an ESP32 based railway barrier system, connecting wires are used to connect the microcontroller, sensors, actuators, LEDs and other devices to the control system and the power supply.
Connecting wires can be made of copper or other conductive materials and are typically coated with a plastic or rubber insulation to protect against electrical short circuits. They come in different sizes, lengths and colors, and often have a connector on each end to connect the wires to the components.
There are different types of connecting wires such as jumpers, DuPont wires, ribbon cable, etc. Jumpers are short wires that have connectors on both ends and are used to connect two points on a circuit board. DuPont wires are single wires with connectors on each end, they are commonly used to connect sensors and actuators to the control board. Ribbon cables are multi-conductor cables that are used to connect multiple devices to the control board.
Connecting wires play a critical role in the functioning of the railway barrier system, as they are responsible for transmitting the electrical signals and power between the various components of the system. It’s important to use the appropriate type of wire for the specific application and to ensure that the connections are secure and free of any damage to avoid any malfunction or system failure.
To do the assembly, we connected:
the VCC pin to the 3.3V pin of ESP32
the Trig pin to pin D5 of ESP32
the ECHO pin to pin D18 of ESP32
the GND pin to the GND pin of ESP32
For the second sound sensor HC-SR04:
the VCC pin to the 3.3V pin of ESP32
the Trig pin to pin D22 of ESP32
the ECHO pin to pin D23 of ESP32
the GND pin to the GND pin of ESP32
For the first servomotor:
red wire: power supply wire to be connected to the 5V terminal of the power supply module
brown wire: wire to connect to the GND pin of ESP32
Yellow: Positioning signal wire connected to pin D4 of ESP32
For the second servomotor:
red wire: power supply wire to be connected to the 5V terminal of the power supply module
brown wire: wire to connect to the GND pin of ESP32
Yellow: Positioning signal wire connected to pin D21 of ESP32
For LEDs:
the terminals (-) of the LEDs to GND of ESP32
the (+) terminal of the first red LED to pin D2 of ESP32
the (+) terminal of the second red LED to pin D19 of ESP32
Here are the micropython programs that allow you to:
calculate the distance between the HC-SR04 sensor and the detected object
raise or lower barriers
turn LEDs on or off
esp32-barrieres.py:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
import machine from hcsr04 import HCSR04 from machine import Pin from servo import Servo import utime sensor1 = HCSR04(trigger_pin=5,echo_pin=18,echo_timeout_us=1000000) sensor2 = HCSR04(trigger_pin=22,echo_pin=23,echo_timeout_us=1000000) servo1_pin = machine.Pin(4) servo2_pin = machine.Pin(21) my_servo1 = Servo(servo1_pin) my_servo2 = Servo(servo2_pin) led1=Pin(2,Pin.OUT) led2=Pin(19,Pin.OUT) i1=90 i2=90 while True: distance1 = sensor1.distance_cm() distance2 = sensor2.distance_cm() if distance1<4 and distance1>0: # If the hc-sr04 sensor detects the arrival of the train while i1 > 0: led1.value(1) # Turn on the red LED my_servo1.write_angle(i1) # lower the barrier utime.sleep_ms(10) i1-=1 else: # Absent from train while i1 < 90: led1.value(0) # Turn off the red LED my_servo1.write_angle(i1) # raise the barrier utime.sleep_ms(10) i1+=1 if distance2<4 and distance2>0: # If hc-sr04 sensor detects detecte the arrival of train while i2 > 0: led2.value(1) # Turn on the red LED my_servo2.write_angle(i2)# lower the barrier utime.sleep_ms(10) i2-=1 else: # en absent the train while i2 < 90: led2.value(0)# Turn off the red LED my_servo2.write_angle(i2) # raise the barrier utime.sleep_ms(10) i2+=1 |
servo.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
from machine import PWM import math # originally by Radomir Dopieralski http://sheep.art.pl # from https://bitbucket.org/thesheep/micropython-servo class Servo: """ A simple class for controlling hobby servos. Args: pin (machine.Pin): The pin where servo is connected. Must support PWM. freq (int): The frequency of the signal, in hertz. min_us (int): The minimum signal length supported by the servo. max_us (int): The maximum signal length supported by the servo. angle (int): The angle between the minimum and maximum positions. """ def __init__(self, pin, freq=50, min_us=600, max_us=2400, angle=180): self.min_us = min_us self.max_us = max_us self.us = 0 self.freq = freq self.angle = angle self.pwm = PWM(pin, freq=freq, duty=0) def write_us(self, us): """Set the signal to be ``us`` microseconds long. Zero disables it.""" if us == 0: self.pwm.duty(0) return us = min(self.max_us, max(self.min_us, us)) duty = us * 1024 * self.freq // 1000000 self.pwm.duty(duty) def write_angle(self, degrees=None, radians=None): """Move to the specified angle in ``degrees`` or ``radians``.""" if degrees is None: degrees = math.degrees(radians) degrees = degrees % 360 total_range = self.max_us - self.min_us us = self.min_us + total_range * degrees // self.angle self.write_us(us) |
hc-sr04.py:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
import machine, time from machine import Pin __version__ = '0.2.0' __author__ = 'Roberto S鐠嬶箯chez' __license__ = "Apache License 2.0. https://www.apache.org/licenses/LICENSE-2.0" class HCSR04: """ Driver to use the untrasonic sensor HC-SR04. The sensor range is between 2cm and 4m. The timeouts received listening to echo pin are converted to OSError('Out of range') """ # echo_timeout_us is based in chip range limit (400cm) def __init__(self, trigger_pin, echo_pin, echo_timeout_us=500*2*30): """ trigger_pin: Output pin to send pulses echo_pin: Readonly pin to measure the distance. The pin should be protected with 1k resistor echo_timeout_us: Timeout in microseconds to listen to echo pin. By default is based in sensor limit range (4m) """ self.echo_timeout_us = echo_timeout_us # Init trigger pin (out) self.trigger = Pin(trigger_pin, mode=Pin.OUT, pull=None) self.trigger.value(0) # Init echo pin (in) self.echo = Pin(echo_pin, mode=Pin.IN, pull=None) def _send_pulse_and_wait(self): """ Send the pulse to trigger and listen on echo pin. We use the method `machine.time_pulse_us()` to get the microseconds until the echo is received. """ self.trigger.value(0) # Stabilize the sensor time.sleep_us(5) self.trigger.value(1) # Send a 10us pulse. time.sleep_us(10) self.trigger.value(0) try: pulse_time = machine.time_pulse_us(self.echo, 1, self.echo_timeout_us) return pulse_time except OSError as ex: if ex.args[0] == 110: # 110 = ETIMEDOUT raise OSError('Out of range') raise ex def distance_mm(self): """ Get the distance in milimeters without floating point operations. """ pulse_time = self._send_pulse_and_wait() # To calculate the distance we get the pulse_time and divide it by 2 # (the pulse walk the distance twice) and by 29.1 becasue # the sound speed on air (343.2 m/s), that It's equivalent to # 0.34320 mm/us that is 1mm each 2.91us # pulse_time // 2 // 2.91 -> pulse_time // 5.82 -> pulse_time * 100 // 582 mm = pulse_time * 100 // 582 return mm def distance_cm(self): """ Get the distance in centimeters with floating point operations. It returns a float """ pulse_time = self._send_pulse_and_wait() # To calculate the distance we get the pulse_time and divide it by 2 # (the pulse walk the distance twice) and by 29.1 becasue # the sound speed on air (343.2 m/s), that It's equivalent to # 0.034320 cm/us that is 1cm each 29.1us cms = (pulse_time / 2) / 29.1 return cms |