<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Raspberry Pi Projects Archives | Teach Me Microcontrollers!</title>
	<atom:link href="https://www.teachmemicro.com/category/projects/raspberry-pi-projects/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.teachmemicro.com/category/projects/raspberry-pi-projects/</link>
	<description>Microcontroller Tutorials and Resources</description>
	<lastBuildDate>Mon, 18 May 2026 12:07:16 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.3</generator>

<image>
	<url>https://www.teachmemicro.com/wp-content/uploads/2019/04/blue-icon-65x65.png</url>
	<title>Raspberry Pi Projects Archives | Teach Me Microcontrollers!</title>
	<link>https://www.teachmemicro.com/category/projects/raspberry-pi-projects/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Raspberry Pi Pico Access Control System Using the Elecrow Pico Advanced Kit</title>
		<link>https://www.teachmemicro.com/raspberry-pi-pico-access-control-system-using-the-elecrow-pico-advanced-kit/</link>
		
		<dc:creator><![CDATA[Roland Pelayo]]></dc:creator>
		<pubDate>Sun, 17 May 2026 11:02:02 +0000</pubDate>
				<category><![CDATA[Raspberry Pi Projects]]></category>
		<guid isPermaLink="false">https://www.teachmemicro.com/?p=11485</guid>

					<description><![CDATA[<p>Access control systems are commonly used in offices, schools, laboratories, apartments, and industrial facilities. At the center of these systems is a controller that decides whether a person is allowed to enter, controls the door lock, and monitors alarm inputs. In this tutorial, I will build a small access control system using a Raspberry Pi &#8230;</p>
<p>The post <a href="https://www.teachmemicro.com/raspberry-pi-pico-access-control-system-using-the-elecrow-pico-advanced-kit/">Raspberry Pi Pico Access Control System Using the Elecrow Pico Advanced Kit</a> appeared first on <a href="https://www.teachmemicro.com">Teach Me Microcontrollers!</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Access control systems are commonly used in offices, schools, laboratories, apartments, and industrial facilities. At the center of these systems is a controller that decides whether a person is allowed to enter, controls the door lock, and monitors alarm inputs.</p>
<p>In this tutorial, I will build a small access control system using a Raspberry Pi Pico and several modules from the <a href="https://www.elecrow.com/raspberry-pi-pico-advanced-kit-with-pico-board-32-modules-and-32-detailed-projects-lessons.html?idd=5"><strong>Elecrow Raspberry Pi Pico Advanced Kit</strong></a>. The system can read an RFID card, accept a PIN from a keypad, show messages on an LCD, control a solenoid lock through a relay, and respond to fire and tamper alarm inputs.</p>
<p>This is not meant to replace a real commercial access control panel, but it is a very good learning project if you want to understand how access control logic works at the microcontroller level.</p>
<p><span id="more-11485"></span></p>
<hr />
<h2>Project Overview</h2>
<p>The Raspberry Pi Pico will act as the main controller. It will accept access requests from two sources:</p>
<ol>
<li>An RFID card scanned through the RC522 RFID module</li>
<li>A PIN entered through a membrane keypad</li>
</ol>
<p>If the card UID or PIN is valid, the Pico activates a relay driver. The relay then powers a solenoid lock for a few seconds to simulate unlocking a door.</p>
<p>The system also monitors two alarm inputs:</p>
<ol>
<li><strong>Fire alarm input</strong></li>
<li><strong>Tamper alarm input</strong></li>
</ol>
<p>When the fire alarm is triggered, the door is released and the buzzer sounds. This simulates a real access control system where doors may be released during emergency conditions.</p>
<p>When the tamper alarm is triggered, the system keeps the door locked and sounds the buzzer. This simulates someone trying to force open or tamper with the door or panel.</p>
<h3>About the Elecrow Raspberry Pi Pico Advanced Kit</h3>
<p><img decoding="async" class="aligncenter" src="https://media-cdn.elecrow.com/media/webp_image/catalog/product/cache/b6b9577937e6a96f50e53ddc42983628/r/a/raspberry_pico_advanced_kit_package_11.21.webp" alt="raspberry pi pico" /></p>
<p>For this project, I used modules from the <a href="https://www.elecrow.com/raspberry-pi-pico-advanced-kit-with-pico-board-32-modules-and-32-detailed-projects-lessons.html?idd=5">Elecrow Raspberry Pi Pico Advanced Kit</a>. The kit includes a Raspberry Pi Pico, breadboards, LEDs, an RGB module, sound sensor, PIR motion sensor, photoresistor module, passive buzzer, vibration sensor, magnetic spring module, soil moisture sensor, potentiometer, servo, joystick, RC522 RFID module, 4-digit display, traffic light module, rotary encoder, 1602 LCD, temperature and humidity sensor, raindrops module, flame sensor, OLED module, membrane keypad, smart car parts, ultrasonic sensor, infrared remote, and several other accessories.</p>
<p><img decoding="async" class="aligncenter" src="https://media-cdn.elecrow.com/media/webp_image/catalog/product/cache/b6b9577937e6a96f50e53ddc42983628/r/a/raspberry_pico_advanced_kit_1_n.webp" /></p>
<p>For this access control project, I will use the parts that make sense for a small door controller:</p>
<ul>
<li>Raspberry Pi Pico</li>
<li>RC522 RFID module</li>
<li>Membrane keypad</li>
<li>1602 LCD module</li>
<li> Passive buzzer</li>
<li>LEDs (traffic light module)</li>
<li>Flame sensor or button for fire alarm simulation</li>
<li>Vibration sensor for tamper detection</li>
</ul>
<p>I will also use an external solenoid lock and relay driver. These are not driven directly by the Pico because a solenoid needs more current than a GPIO pin can provide.</p>
<hr />
<h2>How the System Works</h2>
<p>Here is the basic block diagram of the project:</p>
<pre><a href="https://www.teachmemicro.com/wp-content/uploads/2026/05/raspberry-pi-pico-access-control.avif"><img data-dominant-color="e7e9e7" data-has-transparency="false" style="--dominant-color: #e7e9e7;" loading="lazy" decoding="async" class="aligncenter size-full wp-image-11486 not-transparent" src="https://www.teachmemicro.com/wp-content/uploads/2026/05/raspberry-pi-pico-access-control.avif" alt="" width="724" height="543" srcset="https://www.teachmemicro.com/wp-content/uploads/2026/05/raspberry-pi-pico-access-control.avif 724w, https://www.teachmemicro.com/wp-content/uploads/2026/05/raspberry-pi-pico-access-control-300x225.avif 300w" sizes="auto, (max-width: 724px) 100vw, 724px" /></a></pre>
<p>The Pico continuously checks the system inputs. In normal standby mode, the LCD asks the user to scan a card or enter a PIN.</p>
<p>If access is granted, the relay turns on and the solenoid unlocks for a short time. If access is denied, the buzzer gives an error sound and the red LED turns on.</p>
<p>The fire alarm and tamper alarm have higher priority than normal card or PIN access.</p>
<hr />
<h2>Features of This Project</h2>
<p>This project includes the following features:</p>
<ul>
<li>RFID card access using the RC522 module</li>
<li>PIN access using a membrane keypad</li>
<li>LCD status messages</li>
<li>Solenoid lock control using a relay driver</li>
<li>Buzzer feedback</li>
<li>LED status indicators</li>
<li>Fire alarm input</li>
<li>Tamper alarm input</li>
<li>Optional door contact monitoring</li>
<li>MicroPython code for beginners</li>
</ul>
<hr />
<h2>Required Components</h2>
<p>Most of the components used in this project are included in the <strong>Elecrow Raspberry Pi Pico Advanced Kit</strong>. I also added a solenoid lock and relay driver to make the project closer to a real access control setup.</p>
<table class="w-fit min-w-(--thread-content-width)">
<thead>
<tr>
<th class="last:pe-10">Component</th>
<th class="last:pe-10">Purpose</th>
</tr>
</thead>
<tbody>
<tr>
<td>Raspberry Pi Pico</td>
<td>Main controller</td>
</tr>
<tr>
<td>RC522 RFID module</td>
<td>Reads RFID cards</td>
</tr>
<tr>
<td>Membrane keypad</td>
<td>PIN entry</td>
</tr>
<tr>
<td>1602 LCD module</td>
<td>Displays system status</td>
</tr>
<tr>
<td>Passive buzzer</td>
<td>Alarm and feedback sound</td>
</tr>
<tr>
<td>Red LED</td>
<td>Access denied / alarm indicator</td>
</tr>
<tr>
<td>Green LED</td>
<td>Access granted indicator</td>
</tr>
<tr>
<td>Yellow LED</td>
<td>Standby / warning indicator</td>
</tr>
<tr>
<td>Flame sensor or button</td>
<td>Fire alarm input</td>
</tr>
<tr>
<td>Vibration sensor</td>
<td>Tamper alarm input</td>
</tr>
<tr>
<td>Relay driver module</td>
<td>Controls the solenoid lock</td>
</tr>
<tr>
<td>Solenoid lock</td>
<td>Door lock output</td>
</tr>
<tr>
<td>External power supply</td>
<td>Powers the solenoid lock</td>
</tr>
</tbody>
</table>
<p>You can also use a servo motor instead of a solenoid lock if you want a safer beginner version of the project. However, using a relay and solenoid makes the project feel closer to a real access control system.</p>
<hr />
<h2>Important Safety Note About Solenoid Locks</h2>
<p>The Raspberry Pi Pico <strong>cannot directly drive a solenoid lock</strong>. A solenoid usually requires more voltage and current than a Pico GPIO pin can provide.</p>
<p>The correct setup is:</p>
<pre><code>Pico GPIO → Relay Driver Input → Relay Contact → Solenoid Power</code></pre>
<p>The Pico only controls the relay input. The solenoid must have its own power supply.</p>
<p>Also, make sure the Pico ground and relay module ground are connected together, unless you are using a fully isolated relay module.</p>
<p>If your relay board or solenoid driver does not already include flyback protection, you should add a diode across the solenoid coil to protect the circuit from voltage spikes.</p>
<p>For a real door access system, use proper certified hardware. This tutorial is only for learning and prototyping.</p>
<hr />
<h2>Pin Connections</h2>
<p>The exact pins can be changed in the code, but I will use this pin assignment for the tutorial.</p>
<h3>RC522 RFID Module to Raspberry Pi Pico</h3>
<p>The RC522 uses SPI communication.</p>
<table>
<thead>
<tr>
<th>RC522 Pin</th>
<th>Raspberry Pi Pico Pin</th>
</tr>
</thead>
<tbody>
<tr>
<td>SDA / SS</td>
<td>GP17</td>
</tr>
<tr>
<td>SCK</td>
<td>GP18</td>
</tr>
<tr>
<td>MOSI</td>
<td>GP19</td>
</tr>
<tr>
<td>MISO</td>
<td>GP16</td>
</tr>
<tr>
<td>RST</td>
<td>GP20</td>
</tr>
<tr>
<td>3.3V</td>
<td>3V3</td>
</tr>
<tr>
<td>GND</td>
<td>GND</td>
</tr>
</tbody>
</table>
<p>Do not connect the RC522 to 5V. The RC522 module works with 3.3V logic.</p>
<hr />
<h3>I2C LCD to Raspberry Pi Pico</h3>
<p>This tutorial assumes that the 1602 LCD has an I2C backpack.</p>
<table>
<thead>
<tr>
<th>LCD Pin</th>
<th>Raspberry Pi Pico Pin</th>
</tr>
</thead>
<tbody>
<tr>
<td>VCC</td>
<td>VBUS or 5V</td>
</tr>
<tr>
<td>GND</td>
<td>GND</td>
</tr>
<tr>
<td>SDA</td>
<td>GP4</td>
</tr>
<tr>
<td>SCL</td>
<td>GP5</td>
</tr>
</tbody>
</table>
<p>Most I2C LCD backpacks work at 5V, but the I2C pull-ups may also pull SDA and SCL to 5V. Many hobby modules work in practice, but the safer method is to use a level shifter or power the backpack in a way that keeps the I2C lines at 3.3V.</p>
<p>If your LCD has 16 pins instead of 4 pins, then it is probably a parallel LCD and will need different wiring and a different library.</p>
<hr />
<h3>Keypad to Raspberry Pi Pico</h3>
<p>For a 4x4 membrane keypad:</p>
<table>
<thead>
<tr>
<th>Keypad Line</th>
<th>Pico Pin</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1</td>
<td>GP6</td>
</tr>
<tr>
<td>Row 2</td>
<td>GP7</td>
</tr>
<tr>
<td>Row 3</td>
<td>GP8</td>
</tr>
<tr>
<td>Row 4</td>
<td>GP9</td>
</tr>
<tr>
<td>Column 1</td>
<td>GP10</td>
</tr>
<tr>
<td>Column 2</td>
<td>GP11</td>
</tr>
<tr>
<td>Column 3</td>
<td>GP12</td>
</tr>
<tr>
<td>Column 4</td>
<td>GP13</td>
</tr>
</tbody>
</table>
<p>If you are using a 4x3 keypad, you can modify the keypad map and remove one column.</p>
<hr />
<h3>Relay Driver and Solenoid Lock</h3>
<table>
<thead>
<tr>
<th>Relay Module Pin</th>
<th>Pico / Supply Connection</th>
</tr>
</thead>
<tbody>
<tr>
<td>IN</td>
<td>GP14</td>
</tr>
<tr>
<td>VCC</td>
<td>5V or relay module required voltage</td>
</tr>
<tr>
<td>GND</td>
<td>GND</td>
</tr>
</tbody>
</table>
<p>The solenoid is connected through the relay contacts, not directly to the Pico.</p>
<p>A simple wiring idea is:</p>
<pre><code>Solenoid Power +  → Relay COM
Relay NO          → Solenoid +
Solenoid -        → Solenoid Power -</code></pre>
<p>When the relay turns on, the solenoid receives power and unlocks.</p>
<p>Some relay modules are active-low. This means the relay turns on when the Pico output is LOW instead of HIGH. I will make this configurable in the code.</p>
<hr />
<h3>Buzzer and LEDs</h3>
<table>
<thead>
<tr>
<th>Part</th>
<th>Pico Pin</th>
</tr>
</thead>
<tbody>
<tr>
<td>Buzzer</td>
<td>GP15</td>
</tr>
<tr>
<td>Green LED</td>
<td>GP21</td>
</tr>
<tr>
<td>Red LED</td>
<td>GP22</td>
</tr>
<tr>
<td>Yellow LED</td>
<td>GP26</td>
</tr>
</tbody>
</table>
<p>Use current-limiting resistors for the LEDs.</p>
<hr />
<h3>Alarm Inputs</h3>
<table>
<thead>
<tr>
<th>Alarm Input</th>
<th>Suggested Component</th>
<th>Pico Pin</th>
</tr>
</thead>
<tbody>
<tr>
<td>Fire alarm input</td>
<td>Flame sensor DO or push button</td>
<td>GP27</td>
</tr>
<tr>
<td>Tamper alarm input</td>
<td>Vibration sensor or magnetic sensor</td>
<td>GP28</td>
</tr>
<tr>
<td>Door contact, optional</td>
<td>Magnetic spring module</td>
<td>GP2</td>
</tr>
</tbody>
</table>
<p>For beginner testing, I recommend using push buttons first. Once the logic works, you can replace the buttons with the flame sensor and tamper sensor.</p>
<p>This is my setup on a breadboard. I didn't use the relay + solenoid lock yet; the red LED on the middle of the breadboard will serve as the indicator that the lock released or not.</p>
<p><a href="https://www.teachmemicro.com/wp-content/uploads/2026/05/raspberry-pi-pico-access-control-setup.avif"><img data-dominant-color="d3d4d7" data-has-transparency="false" style="--dominant-color: #d3d4d7;" loading="lazy" decoding="async" class="aligncenter size-full wp-image-11510 not-transparent" src="https://www.teachmemicro.com/wp-content/uploads/2026/05/raspberry-pi-pico-access-control-setup.avif" alt="Raspberry Pi Pico Access Control Setup" width="869" height="652" srcset="https://www.teachmemicro.com/wp-content/uploads/2026/05/raspberry-pi-pico-access-control-setup.avif 869w, https://www.teachmemicro.com/wp-content/uploads/2026/05/raspberry-pi-pico-access-control-setup-300x225.avif 300w, https://www.teachmemicro.com/wp-content/uploads/2026/05/raspberry-pi-pico-access-control-setup-768x576.avif 768w" sizes="auto, (max-width: 869px) 100vw, 869px" /></a></p>
<hr />
<h2>Installing MicroPython on the Raspberry Pi Pico</h2>
<p>Before uploading the code, install MicroPython on the Raspberry Pi Pico. You can download the latest UF2 file in the <a href="https://micropython.org/download/RPI_PICO/">official MicroPython website</a>.</p>
<ol>
<li>Hold the <strong>BOOTSEL</strong> button on the Pico.</li>
<li>Connect the Pico to your computer using a USB cable.</li>
<li>Release the BOOTSEL button.</li>
<li>The Pico should appear as a USB drive.</li>
<li>Copy the MicroPython UF2 file to the Pico.</li>
<li>Open Thonny.</li>
<li>Select the MicroPython interpreter for Raspberry Pi Pico.</li>
</ol>
<p>Once this is done, you can run MicroPython code on the Pico using Thonny.</p>
<hr />
<h2>Required MicroPython Libraries</h2>
<p>This project needs libraries for:</p>
<ul>
<li>RC522 RFID module</li>
<li>I2C LCD</li>
</ul>
<p>For the RC522, you need a file named:</p>
<pre><code>mfrc522.py</code></pre>
<p>For the I2C LCD, you need files such as:</p>
<pre><code>lcd_api.py
pico_i2c_lcd.py</code></pre>
<p>You can find the mfrc522.py in <a href="https://github.com/kevinmcaleer/pico-rfid">this library</a>, while the I2C LCD files are in <a href="https://github.com/T-622/RPI-PICO-I2C-LCD">this library</a>.</p>
<p>Upload these files to the Raspberry Pi Pico using Thonny. You can place them directly on the Pico or inside a <em>/lib</em> folder.</p>
<p>&nbsp;</p>
<hr />
<h2>Testing the RFID Reader First</h2>
<p>Before combining all parts, it is better to test the RFID reader alone. This helps you get the UID of your RFID card.</p>
<p>A card UID may look something like this:</p>
<pre><code>12 AB 34 CD</code></pre>
<p>You will later place this UID inside the list of authorized cards.</p>
<p>In the final code, the authorized cards are stored here:</p>
<pre><code>AUTHORIZED_CARDS = [
    z"&gt;"12 AB 34 CD",
    z"&gt;"A1 B2 C3 D4"
]</code></pre>
<p>Replace these values with your actual card UID.</p>
<hr />
<h2>System Behavior</h2>
<p>The system has several operating conditions.</p>
<h3>Idle Mode</h3>
<p>In idle mode, the LCD shows:</p>
<pre><code>PICO ACCESS
SCAN CARD/PIN</code></pre>
<p>The system waits for an RFID card or keypad input.</p>
<hr />
<h3>Access Granted</h3>
<p>If the card or PIN is valid:</p>
<pre><code>ACCESS GRANTED
DOOR UNLOCKED</code></pre>
<p>The green LED turns on, the buzzer gives a short beep, and the relay unlocks the solenoid for a few seconds.</p>
<hr />
<h3>Access Denied</h3>
<p>If the card or PIN is invalid:</p>
<pre><code>ACCESS DENIED
TRY AGAIN</code></pre>
<p>The red LED turns on and the buzzer gives an error sound.</p>
<hr />
<h3>Fire Alarm</h3>
<p>If the fire alarm input is triggered:</p>
<pre><code>FIRE ALARM!
DOOR RELEASED</code></pre>
<p>The door unlocks and the buzzer sounds repeatedly.</p>
<p>This is done because many access control systems release doors during emergency conditions. Again, this project is only a simulation.</p>
<hr />
<h3>Tamper Alarm</h3>
<p>If the tamper input is triggered:</p>
<pre><code>TAMPER ALARM!
SYSTEM LOCKED</code></pre>
<p>The system sounds the buzzer and flashes the red LED. The door remains locked.</p>
<hr />
<h2>Event Priority</h2>
<p>The Pico should not treat all events equally. Alarm inputs should have higher priority than normal access requests.</p>
<p>For this project, I use this priority:</p>
<table>
<thead>
<tr>
<th>Priority</th>
<th>Event</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Fire alarm</td>
<td>Unlock door and sound alarm</td>
</tr>
<tr>
<td>2</td>
<td>Tamper alarm</td>
<td>Keep locked and sound alarm</td>
</tr>
<tr>
<td>3</td>
<td>Valid RFID or PIN</td>
<td>Unlock door temporarily</td>
</tr>
<tr>
<td>4</td>
<td>Invalid RFID or PIN</td>
<td>Deny access</td>
</tr>
<tr>
<td>5</td>
<td>Idle</td>
<td>Wait for input</td>
</tr>
</tbody>
</table>
<p>Fire alarm has the highest priority because it is a safety-related condition.</p>
<hr />
<h2>Final MicroPython Code</h2>
<p>Upload the required libraries first, then save the following code as</p>
<pre><code>main.py</code></pre>
<p>on the Raspberry Pi Pico.</p>
<p>This code assumes:</p>
<ul>
<li>RC522 uses SPI0</li>
<li>LCD uses I2C0</li>
<li>Keypad is 4x4</li>
<li>Relay output is active-high by default</li>
<li>Fire and tamper inputs are active-low using pull-up resistors</li>
</ul>
<p>If your relay module is active-low, change:</p>
<pre><code>RELAY_ACTIVE_HIGH = True</code></pre>
<p>to:</p>
<pre><code>RELAY_ACTIVE_HIGH = False</code></pre>
<p>Here is the complete code:</p>
<pre><code>from machine import Pin, PWM, I2C, SPI
from time import sleep, ticks_ms, ticks_diff

# ------------------------------------------------------------
# Optional libraries
# ------------------------------------------------------------
# These imports depend on the library files you uploaded.
# If your library uses different class names, adjust these lines.

try:
    from mfrc522 import MFRC522
except ImportError:
    MFRC522 = None

try:
    from pico_i2c_lcd import I2cLcd
except ImportError:
    I2cLcd = None


# ------------------------------------------------------------
# User settings
# ------------------------------------------------------------

AUTHORIZED_CARDS = [
    "C3 A4 13 29",
    "12 AB 34 CD",
    "A1 B2 C3 D4"
]

AUTHORIZED_PIN = "1234"

ALARM_CHECK_INTERVAL_SECONDS = 5
UNLOCK_TIME_SECONDS = 3

RELAY_ACTIVE_HIGH = True

LCD_I2C_ADDR = 0x27
LCD_ROWS = 2
LCD_COLS = 16


# ------------------------------------------------------------
# Pin assignments
# ------------------------------------------------------------

# RFID RC522 SPI pins
RFID_SCK_PIN = 18
RFID_MOSI_PIN = 19
RFID_MISO_PIN = 16
RFID_CS_PIN = 17
RFID_RST_PIN = 20

# LCD I2C pins
LCD_SDA_PIN = 4
LCD_SCL_PIN = 5

# Keypad pins
ROW_PINS = [6, 7, 8, 9]
COL_PINS = [10, 11, 12, 13]

# Outputs
RELAY_PIN = 14
BUZZER_PIN = 15
GREEN_LED_PIN = 21
RED_LED_PIN = 22
YELLOW_LED_PIN = 26

# Inputs
FIRE_INPUT_PIN = 27
TAMPER_INPUT_PIN = 28
DOOR_CONTACT_PIN = 2


# ------------------------------------------------------------
# Hardware setup
# ------------------------------------------------------------

green_led = Pin(GREEN_LED_PIN, Pin.OUT)
red_led = Pin(RED_LED_PIN, Pin.OUT)
yellow_led = Pin(YELLOW_LED_PIN, Pin.OUT)

relay = Pin(RELAY_PIN, Pin.OUT)

buzzer = PWM(Pin(BUZZER_PIN))
buzzer.duty_u16(0)

fire_input = Pin(FIRE_INPUT_PIN, Pin.IN, Pin.PULL_UP)
tamper_input = Pin(TAMPER_INPUT_PIN, Pin.IN, Pin.PULL_UP)
door_contact = Pin(DOOR_CONTACT_PIN, Pin.IN, Pin.PULL_UP)

row_pins = [Pin(pin, Pin.OUT) for pin in ROW_PINS]
col_pins = [Pin(pin, Pin.IN, Pin.PULL_UP) for pin in COL_PINS]

key_map = [
    ["1", "2", "3", "A"],
    ["4", "5", "6", "B"],
    ["7", "8", "9", "C"],
    ["*", "0", "#", "D"]
]

# LCD setup
lcd = None

if I2cLcd is not None:
    try:
        i2c = I2C(0, sda=Pin(LCD_SDA_PIN), scl=Pin(LCD_SCL_PIN), freq=400000)
        lcd = I2cLcd(i2c, LCD_I2C_ADDR, LCD_ROWS, LCD_COLS)
    except Exception as e:
        print("LCD init failed:", e)
        lcd = None
else:
    print("LCD library not found. LCD output disabled.")

# RFID setup
rfid = None

if MFRC522 is not None:
    try:
        # This constructor may be different depending on your mfrc522.py library.
        # Some libraries use:
        # rfid = MFRC522(spi_id=0, sck=18, miso=16, mosi=19, cs=17, rst=20)
        #
        # If this line fails, check the documentation of your RC522 library.
        rfid = MFRC522(
            spi_id=0,
            sck=RFID_SCK_PIN,
            miso=RFID_MISO_PIN,
            mosi=RFID_MOSI_PIN,
            cs=RFID_CS_PIN,
            rst=RFID_RST_PIN
        )
    except Exception as e:
        print("RFID init failed:", e)
        rfid = None
else:
    print("MFRC522 library not found. RFID disabled.")


# ------------------------------------------------------------
# Helper functions
# ------------------------------------------------------------

def set_relay(active):
    if RELAY_ACTIVE_HIGH:
        relay.value(1 if active else 0)
    else:
        relay.value(0 if active else 1)


def lock_door():
    set_relay(False)


def unlock_door():
    set_relay(True)


def all_leds_off():
    green_led.off()
    red_led.off()
    yellow_led.off()

def pad_lcd_text(text, width=16):
    text = str(text)[:width]

    while len(text) &lt; width:
        text += " "

    return text

last_lcd_line1 = None
last_lcd_line2 = None

def lcd_message(line1, line2=""):
    global last_lcd_line1, last_lcd_line2

    line1 = str(line1)[:16]
    line2 = str(line2)[:16]

    # Do not refresh the LCD if the message did not change
    if line1 == last_lcd_line1 and line2 == last_lcd_line2:
        return

    print(line1, line2)

    last_lcd_line1 = line1
    last_lcd_line2 = line2

    if lcd is None:
        return

    lcd.move_to(0, 0)
    lcd.putstr(pad_lcd_text(line1, 16))

    lcd.move_to(0, 1)
    lcd.putstr(pad_lcd_text(line2, 16))


def beep(freq=2000, duration=0.1):
    buzzer.freq(freq)
    buzzer.duty_u16(30000)
    sleep(duration)
    buzzer.duty_u16(0)


def beep_success():
    beep(1800, 0.08)
    sleep(0.05)
    beep(2200, 0.08)


def beep_error():
    for _ in range(3):
        beep(600, 0.12)
        sleep(0.08)


def beep_alarm():
    beep(1200, 0.15)
    sleep(0.08)


def is_fire_alarm_active():
    # Active-low input
    return fire_input.value() == 0


def is_tamper_active():
    # Active-low input
    return tamper_input.value() == 0


def is_door_open():
    # This depends on your magnetic switch module.
    # For this example, LOW means door open.
    return door_contact.value() == 0


# ------------------------------------------------------------
# Keypad functions
# ------------------------------------------------------------

def scan_keypad():
    for row_index, row in enumerate(row_pins):
        for r in row_pins:
            r.value(1)

        row.value(0)

        for col_index, col in enumerate(col_pins):
            if col.value() == 0:
                sleep(0.05)  # debounce

                if col.value() == 0:
                    key = key_map[row_index][col_index]

                    while col.value() == 0:
                        sleep(0.01)

                    return key

    return None


# ------------------------------------------------------------
# RFID functions
# ------------------------------------------------------------

def uid_to_string(uid):
    return " ".join("{:02X}".format(byte) for byte in uid)


def read_rfid_card():
    if rfid is None:
        return None

    try:
        (stat, tag_type) = rfid.request(rfid.REQIDL)

        if stat == rfid.OK:
            (stat, uid) = rfid.SelectTagSN()

            if stat == rfid.OK:
                return uid_to_string(uid)

    except Exception as e:
        print("RFID read error:", e)

    return None


# ------------------------------------------------------------
# Access control actions
# ------------------------------------------------------------

def grant_access(source):
    all_leds_off()
    green_led.on()

    lcd_message("ACCESS GRANTED", source)
    beep_success()

    unlock_door()
    sleep(UNLOCK_TIME_SECONDS)
    lock_door()

    green_led.off()
    lcd_message("DOOR LOCKED", "SCAN CARD/PIN")
    sleep(1)


def deny_access(reason):
    all_leds_off()
    red_led.on()

    lcd_message("ACCESS DENIED", reason)
    beep_error()

    red_led.off()
    sleep(1)

def sound_alarm_cycle(duration_seconds, fire_mode=False):
    start_time = ticks_ms()

    while ticks_diff(ticks_ms(), start_time) &lt; duration_seconds * 1000:
        if fire_mode:
            red_led.toggle()
            yellow_led.toggle()
        else:
            red_led.toggle()
            yellow_led.off()

        beep_alarm()
        sleep(0.2)

    buzzer.duty_u16(0)

def handle_fire_alarm():
    all_leds_off()

    lcd_message("FIRE ALARM!", "DOOR RELEASED")
    unlock_door()

    while True:
        sound_alarm_cycle(ALARM_CHECK_INTERVAL_SECONDS, fire_mode=True)

        if not is_fire_alarm_active():
            break

        lcd_message("FIRE ALARM!", "STILL ACTIVE")

    all_leds_off()
    lock_door()
    lcd_message("FIRE CLEARED", "DOOR LOCKED")
    sleep(1)


def handle_tamper_alarm():
    all_leds_off()

    lcd_message("TAMPER ALARM!", "SYSTEM LOCKED")
    lock_door()

    while True:
        sound_alarm_cycle(ALARM_CHECK_INTERVAL_SECONDS, fire_mode=False)

        if not is_tamper_active():
            break

        lcd_message("TAMPER ALARM!", "STILL ACTIVE")

    all_leds_off()
    lcd_message("TAMPER CLEARED", "SCAN CARD/PIN")
    sleep(1)


def handle_forced_door():
    all_leds_off()
    red_led.on()

    lcd_message("DOOR FORCED!", "ALARM ACTIVE")
    lock_door()

    # Sound alarm for a few seconds
    start_time = ticks_ms()

    while ticks_diff(ticks_ms(), start_time) &lt; 5000:
        red_led.toggle()
        beep_alarm()
        sleep(0.2)

    all_leds_off()
    lcd_message("SCAN CARD/PIN", "")
    sleep(1)


# ------------------------------------------------------------
# Main program
# ------------------------------------------------------------

def main():
    entered_pin = ""
    last_idle_update = 0

    lock_door()
    all_leds_off()

    lcd_message("PICO ACCESS", "SCAN CARD/PIN")
    yellow_led.on()

    door_was_unlocked_by_system = False

    while True:
        # Highest priority: fire alarm
        if is_fire_alarm_active():
            handle_fire_alarm()
            entered_pin = ""
            lcd_message("PICO ACCESS", "SCAN CARD/PIN")
            yellow_led.on()
            continue

        # Second priority: tamper alarm
        if is_tamper_active():
            handle_tamper_alarm()
            entered_pin = ""
            lcd_message("PICO ACCESS", "SCAN CARD/PIN")
            yellow_led.on()
            continue

        # Optional forced door detection
        # This is basic logic only. A real system needs better door timing rules.
        if is_door_open() and not door_was_unlocked_by_system:
            handle_forced_door()
            entered_pin = ""
            lcd_message("PICO ACCESS", "SCAN CARD/PIN")
            yellow_led.on()
            continue

        # RFID access
        uid = read_rfid_card()

        if uid is not None:
            print("Card UID:", uid)

            if uid in AUTHORIZED_CARDS:
                yellow_led.off()
                door_was_unlocked_by_system = True
                grant_access("RFID CARD")
                door_was_unlocked_by_system = False
            else:
                yellow_led.off()
                deny_access("INVALID CARD")

            lcd_message("PICO ACCESS", "SCAN CARD/PIN")
            yellow_led.on()
            entered_pin = ""
            sleep(0.5)
            continue

        # Keypad access
        key = scan_keypad()

        if key is not None:
            print("Key:", key)

            if key == "*":
                entered_pin = ""
                lcd_message("ENTER PIN:", "")
                beep(1200, 0.05)

            elif key == "#":
                if entered_pin == AUTHORIZED_PIN:
                    yellow_led.off()
                    door_was_unlocked_by_system = True
                    grant_access("PIN ENTRY")
                    door_was_unlocked_by_system = False
                else:
                    yellow_led.off()
                    deny_access("WRONG PIN")

                entered_pin = ""
                lcd_message("PICO ACCESS", "SCAN CARD/PIN")
                yellow_led.on()

            elif key in "0123456789":
                if len(entered_pin) &lt; 8: entered_pin += key lcd_message("ENTER PIN:", "*" * len(entered_pin)) beep(1500, 0.04) # Refresh idle display occasionally if ticks_diff(ticks_ms(), last_idle_update) &gt; 3000 and entered_pin == "":
            lcd_message("PICO ACCESS", "SCAN CARD/PIN")
            yellow_led.on()
            last_idle_update = ticks_ms()

        sleep(0.05)


main()
</code></pre>
<hr />
<h2>How the Code Works</h2>
<p>The code starts by defining the authorized cards and PIN:</p>
<pre><code>AUTHORIZED_CARDS = [
    "12 AB 34 CD",
    "A1 B2 C3 D4"
]

AUTHORIZED_PIN = "1234"</code></pre>
<p>You need to replace the sample RFID UIDs with the actual UIDs of your cards.</p>
<p>The system also defines how long the door will unlock:</p>
<pre><code>UNLOCK_TIME_SECONDS = 3</code></pre>
<p>This means that when access is granted, the solenoid is released for 3 seconds.</p>
<p>There is also another delay for when the fire alarm or tamper alarm is triggered:</p>
<pre><code>ALARM_CHECK_INTERVAL_SECONDS = 5</code></pre>
<p>This means that the buzzer will stay in alarm mode for 5 seconds before checking the states of the sensor again.</p>
<hr />
<h2>Relay Control</h2>
<p>The relay is controlled by this function:</p>
<pre><code>def set_relay(active):
    if RELAY_ACTIVE_HIGH:
        relay.value(1 if active else 0)
    else:
        relay.value(0 if active else 1)</code></pre>
<p>This is useful because some relay modules turn on when the input pin is HIGH, while others turn on when the input pin is LOW.</p>
<p>If your relay works backward, simply change this line:</p>
<pre><code>RELAY_ACTIVE_HIGH = True</code></pre>
<p>to:</p>
<pre><code>RELAY_ACTIVE_HIGH = False</code></pre>
<hr />
<h2>LCD Messages</h2>
<p>The function below prints messages to both the LCD and the Thonny shell:</p>
<pre><code>def lcd_message(line1, line2=z"&gt;""):
    print(line1, line2)

    if lcd is None:
        return

    lcd.clear()
    lcd.move_to(0, 0)
    lcd.putstr(line1[:16])

    lcd.move_to(0, 1)
    lcd.putstr(line2[:16])</code></pre>
<p>The</p>
<pre><code>[:16]</code></pre>
<p>part makes sure that the message fits on a 16-column LCD.</p>
<hr />
<h2>Reading the Keypad</h2>
<p>The keypad is scanned row by row. Each row is pulled LOW one at a time, and the Pico checks which column also becomes LOW.</p>
<pre><code>def scan_keypad():
    for row_index, row in enumerate(row_pins):
        for r in row_pins:
            r.value(1)

        row.value(0)

        for col_index, col in enumerate(col_pins):
            if col.value() == 0:
                sleep(0.05)

                if col.value() == 0:
                    key = key_map[row_index][col_index]

                    while col.value() == 0:
                        sleep(0.01)

                    return key

    return None</code></pre>
<p>The small delay is used for basic button debounce.</p>
<hr />
<h2>RFID Access Logic</h2>
<p>The RFID function returns the UID of a scanned card:</p>
<pre><code>uid = read_rfid_card()</code></pre>
<p>Then the main loop checks whether the UID is in the list of authorized cards:</p>
<pre><code>if uid in AUTHORIZED_CARDS:
    grant_access("RFID CARD")
else:
    deny_access("INVALID CARD")</code></pre>
<p>This is the simplest way to handle RFID authorization in a beginner project.</p>
<hr />
<h2>PIN Access Logic</h2>
<p>The keypad allows the user to enter a PIN. The</p>
<pre><code>*</code></pre>
<p>key clears the input, while the</p>
<pre><code>#</code></pre>
<p>key submits it.</p>
<pre><code>if key == "*":
    entered_pin = ""

elif key == "#":
    if entered_pin == AUTHORIZED_PIN:
        grant_access("PIN ENTRY")
    else:
        deny_access("WRONG PIN")</code></pre>
<p>This is similar to how many keypad-based access systems work.</p>
<hr />
<h2>Fire Alarm Logic</h2>
<p>The fire alarm input has the highest priority. If it is active, the system immediately runs this function:</p>
<pre><code>handle_fire_alarm()</code></pre>
<p>Inside that function, the door is unlocked:</p>
<pre><code>unlock_door()</code></pre>
<p>Then the buzzer and LEDs continue until the fire alarm input clears.</p>
<p>This behavior simulates an emergency door release.</p>
<hr />
<h2>Tamper Alarm Logic</h2>
<p>The tamper alarm works differently from the fire alarm. When tamper is detected, the system keeps the door locked:</p>
<pre><code>lock_door()</code></pre>
<p>Then it sounds the buzzer and flashes the red LED.</p>
<p>This simulates a forced access or panel tamper condition.</p>
<hr />
<h2>Door Contact Logic</h2>
<p>The optional door contact can detect if the door was opened without a valid unlock command.</p>
<p>In this tutorial, the logic is simplified:</p>
<pre><code>if is_door_open() and not door_was_unlocked_by_system:
    handle_forced_door()</code></pre>
<p>In a real access control system, this part would usually include a delay timer. For example, after access is granted, the door is allowed to open for a few seconds. If it stays open too long, the controller may trigger a “door held open” alarm.</p>
<p>You can add this as an advanced improvement.</p>
<hr />
<h2>Video</h2>
<p>Here's the project in action:<br />
<iframe loading="lazy" src="https://drive.google.com/file/d/1t0qkxlgHkuYVN1Nwjg1UlPogPIhFxE2y/preview" width="640" height="480"></iframe></p>
<p>Again, I didn't include the relay and solenoid lock for this video. The red LED lighting up means the door is unlocked. Replacing the red LED with the relay module and solenoid lock combination opens the lock when the LED is on.</p>
<h2></h2>
<h2>Testing the Project</h2>
<p>Test the project in stages. Do not connect everything at once.</p>
<h3>Step 1: Test the LCD</h3>
<p>Upload a simple LCD test first and confirm that the LCD can display text.</p>
<h3>Step 2: Test the Keypad</h3>
<p>Print each key to the Thonny shell. Make sure every key is detected correctly.</p>
<h3>Step 3: Test the RFID Reader</h3>
<p>Scan your card and copy the UID from the shell.</p>
<p>Then place the UID inside:</p>
<pre><code>AUTHORIZED_CARDS = [
    "YOUR CARD UID HERE"
]</code></pre>
<p>Step 4: Test the Relay Without the Solenoid</p>
<p>Before connecting the solenoid, test the relay with only the relay module connected. You should hear the relay click when access is granted.</p>
<h3>Step 5: Test the Solenoid Lock</h3>
<p>Once the relay works, connect the solenoid to its external power supply through the relay contacts.</p>
<p>Do not power the solenoid from the Pico.</p>
<h3>Step 6: Test Fire and Tamper Inputs</h3>
<p>Use push buttons first. Once the logic works, replace the buttons with the flame sensor, magnetic sensor, or vibration sensor.</p>
<hr />
<h3>RFID Reader Not Detected</h3>
<p>Check the SPI wiring carefully. The most common mistake is swapping MOSI and MISO.</p>
<p>Also make sure the RC522 is powered from 3.3V, not 5V.</p>
<h3>LCD Shows Nothing</h3>
<p>Try adjusting the contrast potentiometer on the I2C backpack.</p>
<p>If the LCD still does not work, scan for the I2C address. Some LCD backpacks use 0x27, while others use 0x3F.</p>
<p>Change this line if needed:</p>
<pre><code>LCD_I2C_ADDR = 0x27</code></pre>
<h3>Relay Works Backward</h3>
<p>Change:</p>
<pre><code>RELAY_ACTIVE_HIGH = True</code></pre>
<p>to:</p>
<pre><code>RELAY_ACTIVE_HIGH = False</code></pre>
<h3>Buzzer Is Too Weak</h3>
<p>The passive buzzer may need a transistor driver if you want it to be louder. For simple breadboard testing, direct GPIO control is usually enough.</p>
<h3>Solenoid Resets the Pico</h3>
<p>This usually means the solenoid is causing voltage drops or electrical noise.</p>
<p>Use a separate power supply for the solenoid, connect grounds properly, and add flyback protection if needed.</p>
<hr />
<h2>Improving the Project</h2>
<p>There are many ways to improve this project.</p>
<p>You can add an enrollment mode where an admin card allows new cards to be registered. You can also save authorized cards in the Pico’s flash memory so they are not hardcoded in the program.</p>
<p>Another useful improvement is event logging. The Pico can record events such as:</p>
<pre><code>ACCESS GRANTED - RFID
ACCESS DENIED - INVALID CARD
ACCESS GRANTED - PIN
FIRE ALARM
TAMPER ALARM
DOOR FORCED</code></pre>
<p>If you use a Raspberry Pi Pico W instead of a regular Pico, you can add a simple web dashboard. This dashboard can show the latest access events and alarm status.</p>
<p>You can also add a real-time clock module to timestamp each event.</p>
<hr />
<h2>Final Thoughts</h2>
<p>This Raspberry Pi Pico access control project combines several important embedded system concepts into one practical build. It uses SPI for RFID, GPIO scanning for the keypad, I2C for the LCD, PWM for the buzzer, and digital outputs for the relay and LEDs.</p>
<p>The best part is that the project behaves like a small version of a real access control controller. It accepts credentials, controls a lock, displays status messages, and responds to alarm inputs.</p>
<p data-is-last-node="" data-is-only-node="">For beginners, MicroPython makes the project easier to understand because the code is readable and the system logic is clear. For a production access control device, I would normally use C or C++ for better structure, timing, and reliability. But for learning how the system works, MicroPython is a very good starting point.</p>
<p>The nice thing about using a kit like the Elecrow Raspberry Pi Pico Advanced Kit is that the project can be expanded easily. After getting the RFID and keypad access working, you can add more modules from the same kit, such as the OLED display, PIR motion sensor, vibration sensor, magnetic spring module, infrared receiver, or ultrasonic sensor.</p>
<p>This makes the project more than just a one-time RFID door lock demo. It becomes a small platform for learning how real embedded control systems handle inputs, outputs, alarms, and user feedback.</p>
<p>The post <a href="https://www.teachmemicro.com/raspberry-pi-pico-access-control-system-using-the-elecrow-pico-advanced-kit/">Raspberry Pi Pico Access Control System Using the Elecrow Pico Advanced Kit</a> appeared first on <a href="https://www.teachmemicro.com">Teach Me Microcontrollers!</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>How to Auto Hide Windows Apps Using Raspberry Pi Pico</title>
		<link>https://www.teachmemicro.com/how-to-auto-hide-windows-apps-using-raspberry-pi-pico/</link>
		
		<dc:creator><![CDATA[Roland Pelayo]]></dc:creator>
		<pubDate>Wed, 16 Oct 2024 01:00:16 +0000</pubDate>
				<category><![CDATA[Raspberry Pi Projects]]></category>
		<guid isPermaLink="false">https://www.teachmemicro.com/?p=7361</guid>

					<description><![CDATA[<p>In this project, I will show you how to automatically switch between tabs or hide applications on a Windows computer using a Raspberry Pi Pico and a proximity sensor. By detecting the presence of a person in front of the sensor, we will trigger events in a C# application that can change tabs, minimize apps, &#8230;</p>
<p>The post <a href="https://www.teachmemicro.com/how-to-auto-hide-windows-apps-using-raspberry-pi-pico/">How to Auto Hide Windows Apps Using Raspberry Pi Pico</a> appeared first on <a href="https://www.teachmemicro.com">Teach Me Microcontrollers!</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In this project, I will show you how to automatically switch between tabs or hide applications on a Windows computer using a <strong>Raspberry Pi Pico</strong> and a <strong>proximity sensor</strong>. By detecting the presence of a person in front of the sensor, we will trigger events in a <strong>C# application</strong> that can change tabs, minimize apps, or hide sensitive information when someone approaches.</p>
<p><span id="more-7361"></span></p>
<p>This tutorial will walk you through the hardware setup, coding the Raspberry Pi Pico to detect proximity, and integrating the proximity sensor data into a Windows app.</p>
<h2>Components Required</h2>
<ol>
<li><strong>Raspberry Pi Pico</strong></li>
<li><strong>HC-SR04 Ultrasonic Sensor</strong> (or any other proximity sensor)</li>
<li><strong>Breadboard and Jumper Wires</strong></li>
<li><strong>USB Cable</strong> (for connecting Raspberry Pi Pico to your computer)</li>
<li><strong>Windows PC with Visual Studio</strong> (for C# app development)</li>
</ol>
<h2>Wiring the Raspberry Pi Pico and the Proximity Sensor</h2>
<p>We will use the HC-SR04 sensor to detect a person's presence. The sensor has four pins: <strong>VCC</strong>, <strong>GND</strong>, <strong>TRIG</strong>, and <strong>ECHO</strong>.</p>
<h3>Wiring:</h3>
<ul>
<li><strong>VCC</strong> to Raspberry Pi Pico's <strong>3.3V</strong> pin</li>
<li><strong>GND</strong> to Raspberry Pi Pico's <strong>GND</strong> pin</li>
<li><strong>TRIG</strong> to <strong>GPIO 15</strong></li>
<li><strong>ECHO</strong> to <strong>GPIO 14</strong></li>
</ul>
<p>This setup allows the Pico to receive distance measurements from the sensor.</p>
<h2>Programming the Raspberry Pi Pico</h2>
<h3>MicroPython Code for Proximity Detection</h3>
<p>We will use MicroPython to program the Raspberry Pi Pico. The code will continuously check the distance from the sensor and send the proximity data over a serial connection to the Windows PC.</p>
<p>Install MicroPython on the Pico by following the <a rel="noopener" target="_new" href="https://www.raspberrypi.com/documentation/microcontrollers/micropython.html"><span>official</span><span> guide</span></a>, then use Thonny IDE for programming.</p>
<div class="dark bg-gray-950 contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative">
<div class="overflow-y-auto p-4" dir="ltr">
<div class="hcb_wrap">
<pre class="prism undefined-numbers lang-python" data-lang="Python"><code>from machine import Pin, time_pulse_us
import utime

# Initialize pins for sensor
trig = Pin(15, Pin.OUT)
echo = Pin(14, Pin.IN)

def measure_distance():
    # Send pulse
    trig.low()
    utime.sleep_us(2)
    trig.high()
    utime.sleep_us(10)
    trig.low()

    # Measure response time
    pulse_time = time_pulse_us(echo, 1)
    distance_cm = (pulse_time / 2) / 29.1 # Speed of sound = 29.1 us/cm
    return distance_cm

while True:
    distance = measure_distance()
    print(distance)
    utime.sleep(1)</code></pre>
</div>
</div>
</div>
<p>This code calculates the distance using the ultrasonic sensor and prints the value over the serial interface.</p>
<h3>Flashing the Code</h3>
<ol>
<li>Save the above code as <em>main.py</em> in Thonny IDE.</li>
<li>Connect the Raspberry Pi Pico to your computer via USB.</li>
<li>Run the script. You should see distance readings in the Thonny IDE’s console.</li>
</ol>
<h2>Creating the C# Application</h2>
<p>Now that the Pico is sending distance data, we will create a C# application that listens to the serial port and responds by switching tabs or hiding apps when a person is detected.</p>
<h3>Setting Up the C# Application</h3>
<ol>
<li>Open <strong>Visual Studio</strong> and create a new <strong>Windows Forms App</strong> (or WPF if preferred).</li>
<li>Add the following <strong>NuGet packages</strong>:
<ul>
<li><em>System.IO.Ports</em> for handling serial communication</li>
</ul>
</li>
</ol>
<h3>C# Code to Listen for Sensor Data</h3>
<p>Here's the basic C# code that connects to the Pico via the serial port and changes tabs or minimizes applications based on the proximity data.</p>
<div class="hcb_wrap">
<pre class="prism undefined-numbers lang-csharp" data-lang="C#"><code>using System;
using System.IO.Ports;
using System.Runtime.InteropServices;
using System.Diagnostics;

class Program
{
    private static SerialPort _serialPort;

    // Import the necessary WinAPI functions
    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    [DllImport("user32.dll")]
    static extern bool SetForegroundWindow(IntPtr hWnd);

    [DllImport("user32.dll")]
    static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll")]
    static extern int GetWindowText(IntPtr hWnd, System.Text.StringBuilder text, int count);

    // Constants for showing or hiding the window
    const int SW_HIDE = 0;
    const int SW_SHOW = 5;

    static void Main(string[] args)
    {
        Console.WriteLine("Starting the serial port listener...");

        // Configure SerialPort
        _serialPort = new SerialPort("COM3", 9600);
        _serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
        _serialPort.Open();

        Console.WriteLine("Listening for data on COM3... Press any key to exit.");
        Console.ReadKey();

        //Close serial port before exiting
        if (_serialPort.IsOpen)
        {
            _serialPort.Close();
        }
    }

    private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        string data = _serialPort.ReadLine();
        if (double.TryParse(data, out double distance))
        {
            Console.WriteLine($"Distance received: {distance} cm");

            // If person is detected (e.g., distance less than 50 cm)
            if (distance &lt; 50) { // Switch to the next window or minimize the current console SwitchTabsOrMinimize(); } } } private static void SwitchTabsOrMinimize() { IntPtr currentForegroundWindow = GetForegroundWindow(); // Get the title of the current window const int nChars = 256; System.Text.StringBuilder windowTitle = new System.Text.StringBuilder(nChars); GetWindowText(currentForegroundWindow, windowTitle, nChars); // Check if there is a current window by inspecting the length of the window title if (windowTitle.ToString().Length &gt; 0)
        {
            // Hide the window
            ShowWindow(currentForegroundWindow, SW_HIDE);
            Console.WriteLine("Window is hidden.");

            // Find the next window to bring to the foreground
            IntPtr nextWindowHandle = GetNextWindowInTaskList();

            if (nextWindowHandle != IntPtr.Zero)
            {
                // Bring the next window to the foreground
                SetForegroundWindow(nextWindowHandle);
                Console.WriteLine("Switched to another application.");
            }
            else
            {
                Console.WriteLine("No other window found to switch to.");
            }
        }
        else
        {
            Console.WriteLine("The active window is not Chrome.");
        }
    }

    private static IntPtr GetNextWindowInTaskList()
    {
        IntPtr nextWindowHandle = IntPtr.Zero;

        // Simulate pressing Alt+Tab by finding the next process with a window
        Process[] processes = Process.GetProcesses();
        foreach (var process in processes)
        {
            if (process.MainWindowHandle != IntPtr.Zero &amp;&amp; process.MainWindowHandle != GetForegroundWindow())
            {
                nextWindowHandle = process.MainWindowHandle;
                break;
            }
        }

        return nextWindowHandle;
    }
}

</code></pre>
</div>
<h3>Explanation of Code</h3>
<ul>
<li>The <em>SerialPort</em> is set up to listen on the COM port connected to the Pico.</li>
<li>When data (the distance) is received from the Pico, the application checks if the value is below a threshold (e.g., 50 cm) to determine if someone is near the sensor.</li>
<li>If a person is detected, the application switches tabs in a <code>TabControl</code>. If the last tab is reached, the app minimizes.</li>
</ul>
<h3>Running the C# Application</h3>
<ol>
<li>Compile and run the C# application in Visual Studio.</li>
<li>Place your hand near the sensor and observe the tabs switching or the application minimizing.</li>
</ol>
<p>To use the Raspberry Pi Pico with C++ (Arduino), we need to install the Arduino core for the Pico, configure the sensor, and write the code in the Arduino IDE. Here's the conversion of the original MicroPython code to C++ using the Arduino framework.</p>
<h3>Setting Up Arduino IDE for Raspberry Pi Pico</h3>
<p>Before we write the C++ code, make sure the Raspberry Pi Pico is ready for Arduino development. Follow these steps:</p>
<ol>
<li>Open the <strong>Arduino IDE</strong>.</li>
<li>Go to <strong>File &gt; Preferences</strong>, and in the "Additional Boards Manager URLs" field, add:
<div class="dark bg-gray-950 contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative">
<div class="sticky top-9 md:top-[5.75rem]"></div>
<div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-ruby"><span class="hljs-symbol">https:</span>/<span class="hljs-regexp">/github.com/earlephilhower</span><span class="hljs-regexp">/arduino-pico/releases</span><span class="hljs-regexp">/download/global</span><span class="hljs-regexp">/package_rp2040_index.json<br />
</span></code></div>
<div dir="ltr"></div>
</div>
</li>
<li>Go to <strong>Tools &gt; Board &gt; Boards Manager</strong>, search for  Raspberry Pi Pico, and install the package by <strong>Earle Philhower</strong>.</li>
</ol>
<p>After this, you'll be able to select the Raspberry Pi Pico as a board from <strong>Tools &gt; Board &gt; Raspberry Pi RP2040 &gt; Raspberry Pi Pico</strong>.</p>
<h3> C++ Code for Proximity Detection</h3>
<p>Here’s the Arduino C++ code for the Raspberry Pi Pico using an HC-SR04 ultrasonic sensor. This code will measure the distance and send the data over the serial port to the Windows PC.</p>
<div class="hcb_wrap">
<pre class="prism undefined-numbers lang-csharp" data-lang="C#"><code>#define TRIG_PIN 15  // GPIO 15 for Trigger
#define ECHO_PIN 14  // GPIO 14 for Echo

void setup() {
  Serial.begin(9600); // Initialize serial communication
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
}

void loop() {
  long duration, distance_cm;

  // Clear the TRIG_PIN by setting it LOW
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);

  // Trigger the sensor by setting TRIG_PIN HIGH for 10 microseconds
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  // Read the ECHO_PIN, returns the sound wave travel time in microseconds
  duration = pulseIn(ECHO_PIN, HIGH);

  // Calculate the distance in cm (Speed of sound = 343 m/s or 29.1 us/cm)
  distance_cm = (duration / 2) / 29.1;

  // Send the distance data over Serial to the PC
  Serial.println(distance_cm);

  // Delay for a bit before the next measurement
  delay(1000);
}
</code></pre>
</div>
<h3>Explanation of the Code:</h3>
<ul>
<li><strong>TRIG_PIN</strong> is set to GPIO 15, and <strong>ECHO_PIN</strong> is set to GPIO 14. These pins connect to the sensor's <strong>TRIG</strong> and <strong>ECHO</strong> respectively.</li>
<li>In the <em>setup()</em> the <strong>TRIG_PIN</strong> is set to OUTPUT and the <strong>ECHO_PIN</strong> to INPUT.</li>
<li>The <em>loop()</em> function:
<ul>
<li>Sends a 10 microsecond pulse to the TRIG pin to trigger the sensor.</li>
<li>Uses <em>pulseIn()</em> to measure the time it takes for the echo to return.</li>
<li>The distance is calculated by dividing the duration by 2 (since the sound wave travels to the object and back) and dividing by 29.1 (speed of sound in microseconds per centimeter).</li>
<li>The calculated distance is printed via <em>Serial.println()</em> to send the data to the connected Windows PC.</li>
</ul>
</li>
</ul>
<h3>Uploading the Code</h3>
<ol>
<li>In the Arduino IDE, select <strong>Tools &gt; Board &gt; Raspberry Pi RP2040 &gt; Raspberry Pi Pico</strong>.</li>
<li>Select the correct COM port under <strong>Tools &gt; Port</strong>.</li>
<li>Upload the code to the Raspberry Pi Pico by pressing the <strong>Upload</strong> button.</li>
</ol>
<h3>Testing the Proximity Detection</h3>
<p>Once the code is uploaded, open the <strong>Serial Monitor</strong> in the Arduino IDE (Ctrl+Shift+M). Place an object in front of the sensor, and you should see the distance readings being displayed.</p>
<p>These readings can now be used in the C# app to switch tabs or perform other actions as discussed in the previous steps.</p>
<h2>Further Testing and Adjustments</h2>
<p>You can adjust the distance threshold for detecting presence based on your needs. If you want more advanced behavior, you could:</p>
<ul>
<li>Add conditions for hiding or locking sensitive applications when a person is detected.</li>
<li>Use other types of proximity sensors for better accuracy.</li>
</ul>
<p>You can also integrate other actions, like muting the system audio or triggering specific actions based on the proximity data.</p>
<h2>Conclusion</h2>
<p>Using a Raspberry Pi Pico with a proximity sensor and a simple C# application, you can automate the management of Windows apps, switching tabs or hiding applications based on proximity detection. This setup is perfect for privacy-conscious users or those looking to add some automation to their desktop environment.</p>
<p>The post <a href="https://www.teachmemicro.com/how-to-auto-hide-windows-apps-using-raspberry-pi-pico/">How to Auto Hide Windows Apps Using Raspberry Pi Pico</a> appeared first on <a href="https://www.teachmemicro.com">Teach Me Microcontrollers!</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Empower Your Raspberry Pi Projects with SunFounder PiPower</title>
		<link>https://www.teachmemicro.com/empower-your-raspberry-pi-projects-with-sunfounder-pipower/</link>
		
		<dc:creator><![CDATA[Roland Pelayo]]></dc:creator>
		<pubDate>Fri, 30 Jun 2023 01:02:47 +0000</pubDate>
				<category><![CDATA[Raspberry Pi Projects]]></category>
		<category><![CDATA[Data Collection]]></category>
		<category><![CDATA[Portable Projects]]></category>
		<category><![CDATA[Power Interruptions]]></category>
		<category><![CDATA[Power Supply]]></category>
		<category><![CDATA[Raspberry Pi]]></category>
		<category><![CDATA[Remote Projects]]></category>
		<category><![CDATA[SunFounder PiPower]]></category>
		<category><![CDATA[Uninterruptible Power Supply]]></category>
		<category><![CDATA[UPS]]></category>
		<guid isPermaLink="false">https://www.teachmemicro.com/?p=6143</guid>

					<description><![CDATA[<p>For enthusiasts and creators working with Raspberry Pi, the joy of bringing an idea to life is often met with the challenge of maintaining a consistent power supply. This is where SunFounder PiPower comes in to save the day, offering uninterrupted power supply (UPS) specifically designed for your Raspberry Pi projects.  Meet SunFounder PiPower  SunFounder &#8230;</p>
<p>The post <a href="https://www.teachmemicro.com/empower-your-raspberry-pi-projects-with-sunfounder-pipower/">Empower Your Raspberry Pi Projects with SunFounder PiPower</a> appeared first on <a href="https://www.teachmemicro.com">Teach Me Microcontrollers!</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><span>For enthusiasts and creators working with <a href="https://www.win-source.net/products/detail/raspberry-pi/raspberry-pi-4-model-b-4gb.html">Raspberry Pi</a>, the joy of bringing an idea to life is often met with the challenge of maintaining a consistent power supply. This is where SunFounder PiPower comes in to save the day, offering uninterrupted power supply (UPS) specifically designed for your Raspberry Pi projects.</span><span> </span><span id="more-6143"></span></p>
<h3><strong>Meet SunFounder PiPower</strong></h3>
<p><span> </span><span>SunFounder PiPower is an ingenious solution crafted to ensure your Raspberry Pi projects never lose their pulse. The package comes complete with a 12V2A power adapter, a 12V to 5V converter, a 7.4V 2600mAh lithium battery, and a USB cable. This combination guarantees a steadfast power supply, even in the face of power outages.</span></p>
<p><img loading="lazy" decoding="async" src="https://www.teachmemicro.com/wp-content/uploads/2023/06/pipower-compatibility.jpg" alt="" width="601" height="596" class="size-full wp-image-6146 aligncenter" srcset="https://www.teachmemicro.com/wp-content/uploads/2023/06/pipower-compatibility.jpg 601w, https://www.teachmemicro.com/wp-content/uploads/2023/06/pipower-compatibility-300x298.jpg 300w, https://www.teachmemicro.com/wp-content/uploads/2023/06/pipower-compatibility-150x150.jpg 150w" sizes="auto, (max-width: 601px) 100vw, 601px" /></p>
<p><span> </span><span>PiPower is a game-changer for projects that require constant power. Whether your project involves data collection, web servers, or scripts that don't automatically restart upon boot, integrating a UPS such as PiPower can immensely enhance your project's resilience and reliability.</span></p>
<p>&nbsp;</p>
<h3><span><strong>PiPower: More than Just a UPS</strong></span></h3>
<p><span>Beyond providing uninterrupted power, PiPower also brings the gift of portability to your projects. It's the ideal companion for remote projects such as a weather station, compact robot, or remote camera system. PiPower allows you to monitor the battery's voltage, power, current, and remaining capacity, making it a go-to choice for portable projects.</span></p>
<p><span> </span></p>
<h3><strong>Simplified Setup and Adaptability</strong></h3>
<p><span> </span><span>Getting your PiPower up and running with your Raspberry Pi is straightforward and hassle-free. The SunFounder PiPower is engineered for a smooth setup, so you can concentrate on what truly matters - creating and innovating.</span></p>
<p><span> </span></p>
<h3><strong>Protect Your Projects with PiPower</strong></h3>
<p><span> </span><span>Every Raspberry Pi enthusiast knows the risk of power interruptions leading to data corruption, particularly if your project is writing on the SD card at the moment of power loss. With PiPower, you can put these worries aside, knowing your projects are shielded from such mishaps.</span></p>
<p><span> </span></p>
<h3><strong>The Bottom Line</strong></h3>
<p><span> </span><span>In the vast universe of Raspberry Pi, where your creativity is your only limit, don't let power interruptions hinder your innovation. With SunFounder PiPower, power interruptions become a relic of the past. It's more than just a power supply; it's a trustworthy ally for your Raspberry Pi projects.</span></p>
<p><span> </span><span>Secure your projects' integrity, enhance their portability, and let your imagination soar. Choose SunFounder PiPower for your Raspberry Pi today! Ready to empower your projects? <a href="https://www.sunfounder.com/products/power-pack?_pos=1&amp;_sid=6bd8a848c&amp;_ss=r&amp;ref=v0f84isi">Get your SunFounder PiPower here</a>!</span></p>
<p><span> </span></p>
<p><span>_(Note: For detailed instructions or assistance with the SunFounder PiPower, consider reaching out to SunFounder's support or community forums.)_</span></p>
<p><span> </span></p>
<p><span>*Disclaimer: This post aims to provide an overview of the SunFounder PiPower. It's not sponsored by or affiliated with SunFounder.*</span></p>
<p>The post <a href="https://www.teachmemicro.com/empower-your-raspberry-pi-projects-with-sunfounder-pipower/">Empower Your Raspberry Pi Projects with SunFounder PiPower</a> appeared first on <a href="https://www.teachmemicro.com">Teach Me Microcontrollers!</a>.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>RFID Login System with Raspberry Pi</title>
		<link>https://www.teachmemicro.com/rfid-login-raspberry-pi/</link>
					<comments>https://www.teachmemicro.com/rfid-login-raspberry-pi/#respond</comments>
		
		<dc:creator><![CDATA[Roland Pelayo]]></dc:creator>
		<pubDate>Wed, 16 Jan 2019 04:38:39 +0000</pubDate>
				<category><![CDATA[Raspberry Pi Projects]]></category>
		<guid isPermaLink="false">https://www.teachmemicro.com/?p=2753</guid>

					<description><![CDATA[<p>Wouldn't it be cool if you built your own card login system just like in hotels? Because RFID modules are now easy to get, this is now very possible. This Raspberry Pi RFID project of mine is a simple login system that reads cards and tags. Every time a user taps his or her card, &#8230;</p>
<p>The post <a href="https://www.teachmemicro.com/rfid-login-raspberry-pi/">RFID Login System with Raspberry Pi</a> appeared first on <a href="https://www.teachmemicro.com">Teach Me Microcontrollers!</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Wouldn't it be cool if you built your own card login system just like in hotels? Because RFID modules are now easy to get, this is now very possible. This Raspberry Pi RFID project of mine is a simple login system that reads cards and tags. Every time a user taps his or her card, his name and current date and time are saved to an SQL database. This project could be useful for login systems in establishments. And by using a Raspberry Pi, a lot of possible features could be added. </p>
<p><span id="more-2753"></span></p>



<h3 class="wp-block-heading"><strong>Materials</strong></h3>



<p class="wp-block-paragraph">I will be using the popular <a href="https://www.win-source.net/products/detail/nxp/rc522.html">MFRC522</a> RFID module:</p>



<figure class="wp-block-image"><img decoding="async" src="https://maker.pro/storage/nw3luwq/nw3luwqcFHWLRtdeldcq8iNFWoR2oWB583vrg5SK.jpeg" alt="" /></figure>



<p class="wp-block-paragraph">My module comes with a card and a tag plus some male headers. This module can be interfaced using UART, I2C, or SPI. I will be using SPI with Python for this project following this <a href="https://www.teachmemicro.com/using-rfid-with-raspberry-pi-zero/" target="_blank" rel="noreferrer noopener">RFID Raspberry Pi</a> tutorial.</p>



<p class="wp-block-paragraph">Powering the project is a Raspberry Pi 2 B+. However, it's compatible with older and newer PIs as long as they are running the latest <a href="https://www.raspberrypi.org/downloads/raspbian/" target="_blank" rel="noreferrer noopener">Raspbian Stretch</a> (March 2018).  </p>



<p class="wp-block-paragraph">Other necessary things needed for this project are female-to-female jumper wires and an internet connection.</p>



<h3 class="wp-block-heading"><strong>Building Instructions</strong></h3>



<p class="wp-block-paragraph"><strong>Enable SPI<br /></strong>As mentioned, I communicated with the RFID module through SPI. Since SPI is not enabled by default on the RPi, I needed to turn it on via <em>raspi-config</em>:</p>



<pre class="theme:shell-default-copy lang:sh decode:true wp-block-preformatted">sudo raspi-config</pre>



<p class="wp-block-paragraph">In the raspi-config interface, I selected <strong>Interfacing Options</strong> and then selected <strong>SPI</strong>. After answering yes to the prompt, I rebooted the RPi to save changes.</p>



<pre class="theme:shell-default-copy lang:sh decode:true wp-block-preformatted">sudo reboot</pre>



<p class="wp-block-paragraph">I needed to check if SPI is indeed enabled. This is done by opening <em>config.txt</em></p>



<pre class="theme:shell-default-copy lang:sh decode:true wp-block-preformatted">sudo /boot/config.txt</pre>



<p class="wp-block-paragraph">Then I searched for the line that says:</p>



<pre class="theme:shell-default-copy lang:sh decode:true wp-block-preformatted">dtparam=spi=on</pre>



<p class="wp-block-paragraph">If this line is commented out, then SPI is now enabled. </p>



<h3 class="wp-block-heading"><strong>SPI for Python</strong></h3>



<p class="wp-block-paragraph">There are a number of handy python libraries for using the SPI interface.  I used <strong>SPI-Py</strong>. To download this library, just enter the commands:</p>



<pre class="theme:shell-default-copy lang:sh decode:true">git clone https://github.com/lthiery/SPI-Py.git</pre>



<p class="wp-block-paragraph">Once downloaded, <em>cd</em> to the folder and run the included <em>setup.py</em> script</p>



<pre class="theme:shell-default-copy lang:sh decode:true">cd SPI-Py sudo python setup.py install</pre>



<p class="wp-block-paragraph">This installs the SPI-Py library and is now usable in the Python environment.</p>



<h3 class="wp-block-heading"><strong>Installing the RFID Library</strong></h3>



<p class="wp-block-paragraph">My Raspberry Pi is now SPI-ready! Next, I installed the RFID library by Mario Gomez.</p>



<pre class="theme:shell-default-copy lang:sh decode:true">git clone https://github.com/mxgxw/MFRC522-python.git</pre>



<p class="wp-block-paragraph">This library uses the following connection:</p>



<div class="wp-block-image">
<figure class="aligncenter"><img decoding="async" src="https://maker.pro/storage/oXDufSl/oXDufSlfs7bk5ap2wnov5WdJ5GxiZdbihFaTqnTs.jpeg" alt="" /></figure>
</div>



<p class="wp-block-paragraph">I've created a Fritzing diagram for those who prefer it:</p>



<div class="wp-block-image">
<figure class="aligncenter"><img decoding="async" src="https://maker.pro/storage/py7vGsd/py7vGsdKSTZiqcA30mRPQM9VpfrQ4UI0OpHyFlTW.jpeg" alt="" /></figure>
</div>



<p class="wp-block-paragraph">To test if everything's working as expected, I ran the included <em>Read.py</em> script:</p>



<pre class="theme:shell-default-copy lang:sh decode:true">python Read.py</pre>



<p class="wp-block-paragraph">Tapping the included RFID card shows the UID, size, and data for a specific sector for that card. It looks like this:</p>



<pre class="theme:shell-default-copy lang:sh decode:true">Card read UID: 22,81,46,91 
Size: 8 
Sector 8 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]</pre>



<p class="wp-block-paragraph">This library allows me to view sector 8 which has 16 bytes of free space. I can use this space to save data but for now, I will be only using the UID as a unique identifier for the card.</p>



<h3 class="wp-block-heading"><strong>Installing MySQL to Save Data</strong></h3>



<p class="wp-block-paragraph">To complete my login system, I need to install mySQL and modify the Read.py code so that the time and name of the user are saved to a database every time the card is tapped into the module.</p>



<p class="wp-block-paragraph">Here's how I installed mySQL server:</p>



<pre class="theme:shell-default-copy lang:sh decode:true">sudo apt-get install mysql-server --fix-missing</pre>



<p class="wp-block-paragraph">Once installed, I needed to create a database with two tables: <em>user</em> and <em>log</em>. The user table records all RFID card uid and the corresponding user names. The log table records the time and date when a user taps a card. </p>



<p class="wp-block-paragraph">After the database and tables were created, I inserted dummy data into the <em>user</em> table.</p>



<pre class="code is-collapsible" data-annotation-id="11737"><code class="shell hljs">| uid           | fname   | lname    |
|---------------|---------|----------|
| 22,81,46,91   | Reed    | William  |
| 189,202,5,139 | Bird    | Clarence |
| 144,99,134,21 | Johnson | Earl     |</code></pre>



<p class="wp-block-paragraph">To be able to access the mySQL database through Python, I installed <strong>python-mysqldb</strong>:</p>



<pre class="theme:shell-default-copy lang:sh decode:true ">sudo apt-get install python-mysqldb</pre>



<p class="wp-block-paragraph">That's about it for the software prerequisites.  Since the system logs the current date and time, my Raspberry Pi must be synced with my local time. This is done automatically in newer Raspbian distributions. I followed these steps:</p>



<p class="wp-block-paragraph" style="padding-left: 30px;">1. sudo raspi-config</p>



<p class="wp-block-paragraph" style="padding-left: 30px;">2. Internationalization options</p>



<p class="wp-block-paragraph" style="padding-left: 30px;">3. Change Time Zone</p>



<p class="wp-block-paragraph" style="padding-left: 30px;">4. Select geographical area</p>



<p class="wp-block-paragraph" style="padding-left: 30px;">5. Select city or region.</p>



<p class="wp-block-paragraph" style="padding-left: 30px;">6. Reboot your pi.</p>



<p class="wp-block-paragraph">Now, I just needed to edit <em>Read.py</em> to this:</p>



<p class="wp-block-code"><code></code></p>
<pre class="theme:shell-default-copy lang:sh decode:true "><code>#!/usr/bin/env python 
# -*- coding: utf8 -*- 
# # Copyright 2018 Roland Pelayo 
# # This file is based on Read.py from MFRC522-Python library by Mario Gomez 
# MFRC522-Python is a simple Python implementation for 
# the MFRC522 NFC Card Reader for the Raspberry Pi. 
import RPi.GPIO as GPIO 
import MFRC522 
import signal 
import MySQLdb 
from time import gmtime, strftime 
from datetime import date 
continue_reading = True

# String variables for names 
firstname = "" 
lastname = "" 

# Create DB object 
db = MySQLdb.connect("localhost","root", "", "rfiddb") 

# Capture SIGINT for cleanup when the script is aborted 
def end_read(signal,frame): 
     global continue_reading 
     print "Ctrl+C captured, ending read." 
     continue_reading = False 
     GPIO.cleanup() 

# Hook the SIGINT 
signal.signal(signal.SIGINT, end_read) 

# Create an object of the class MFRC522 
MIFAREReader = MFRC522.MFRC522() 

# Welcome message 
print "Welcome to the MFRC522 data read example" 
print "Press Ctrl-C to stop." 

# This loop keeps checking for chips. If one is near it will get the UID and authenticate 
while continue_reading: 
# Scan for cards 
     (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL) 
# If a card is found 
     if status == MIFAREReader.MI_OK: 
        print "Card detected" 
pass 

# Get the UID of the card 
     (status,uid) = MIFAREReader.MFRC522_Anticoll()
# If we have the UID, continue 
     if status == MIFAREReader.MI_OK: 
# Print UID 
        _uid = str(uid[0]) + "," + str(uid[1]) + "," + str(uid[2]) + "," + str(uid[3]) print _uid 
# Create DB cursor 
        cur = db.cursor(); 
# Check if UID is in DB 
        cur.execute("SELECT * FROM users WHERE uid = %s" , (_uid,)) 
# Read data 
        for row in cur.fetchall(): 
           firstname = str(row[1]) 
           lastname = str(row[2])
# Read time and date 
           _currTime = strftime("%H:%M:%S",gmtime()) 
           _currDate = date.today().strftime("%Y-%m-%d") 
# Send out a greeting to print name and date 
           print "Hello " + firstname + " " + lastname print _currDate + " " + _currTime 
# Insert every login into database 
        try: 
          try: 
               cur.execute("INSERT INTO log (uid,fname,lname,_date,_time) VALUES (%s,%s,%s,%s,%s)", (_uid,firstname,lastname,_currDate,_currTime)) 
               db.commit() 
          except (db.Error, db.Warning) as e: 
               print(e) 
          finally: 
               print "Successful" 
               cur.close() 
# This is the default key for authentication 
        key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF] 
# Select the scanned tag 
        MIFAREReader.MFRC522_SelectTag(uid) 
# Authenticate 
        status = MIFAREReader.MFRC522_Auth(MIFAREReader.PICC_AUTHENT1A, 8, key, uid) 
# Check if authenticated 
        if status == MIFAREReader.MI_OK:
           MIFAREReader.MFRC522_Read(8) 
           MIFAREReader.MFRC522_StopCrypto1() 
        else:
           print "Authentication error" 
           db.close()</code></pre>



<p class="wp-block-paragraph">There are other things printed on the terminal that are not useful for this project. Thus, I decided to edit the MFRC522.py script. You can download my version of this script on my <a href="https://github.com/kurimawxx00/rfid_raspberry_pi_mysql/blob/master/MFRC522.py" target="_blank" rel="noreferrer noopener">repository.</a></p>



<p class="wp-block-paragraph">If you want to replicate this project, all the files are found <a href="https://github.com/kurimawxx00/rfid_raspberry_pi_mysql" target="_blank" rel="noreferrer noopener">here</a>. Just follow all the steps here for the software requirements. Note that the edited Read.py is now named <strong>Login.Py.</strong> To run, just <em>cd</em> to the folder I linked to and run this command:</p>
<pre class="theme:shell-default-copy lang:sh decode:true "><code>sudo python Login.py</code></pre>





<p class="wp-block-paragraph">I've created a video showing the steps for running the project. Note that it's assumed that you have already installed the software prerequisites as presented above.</p>

<p><iframe loading="lazy" width="560" height="315" src="https://www.youtube.com/embed/zs2MWqt2FQI" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="allowfullscreen" frameborder="0"></iframe></p>
<p>The post <a href="https://www.teachmemicro.com/rfid-login-raspberry-pi/">RFID Login System with Raspberry Pi</a> appeared first on <a href="https://www.teachmemicro.com">Teach Me Microcontrollers!</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.teachmemicro.com/rfid-login-raspberry-pi/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 

Served from: www.teachmemicro.com @ 2026-10-27 00:12:32 by W3 Total Cache
-->