Using Raspberry Pi
Pharmaceuticals prescribed by physicians are important, but they need to be taken according to a proper schedule to be effective. In this article, Devlin describes his Raspberry-Rx Prescription Reminder project, a network-accessible, Wi-Fi connected, Raspberry Pi-based device that alerts a person when a particular medication should be administered. It also keeps a log of the actual times when medications were administered.
It’s been said that television is a “vast wasteland,” but the commercials are sometimes educational. Watching some of these will convince you that there’s a pill to cure nearly every affliction, but the practical problem is that drugs need to be administered on a schedule. Some older people are prescribed so many drugs that it’s often hard for them to remember which drugs should be taken when. My elderly mother had a small plastic tub filled with pill bottles and eyedropper bottles with medications that needed to be administered at different times during the day. Fortunately, a younger family member lived with her and helped with the dosage schedule.
Even younger people take many prescription drugs. I’m on a regimen of a daily baby aspirin and cholesterol medication that most men my age are advised to do. As another preventative, I’m taking a once-a-day multivitamin/multi-mineral supplement. And I’ve also taken antibiotic and anti-inflammatory medications after dental surgery.
My mother’s experience and my own lesser struggle with taking pills on time inspired me to devise the network-accessible appliance presented here. This device reminds me to take a drug at its intended time, and it also keeps a record of what was taken when. This is an automated system that should be as accurate as but more convenient than using a smartphone alarm, as many people do.
A medical appliance is quite a step up from the flashing light and beeper boxes normally built by hobbyists. While my device doesn’t do something extreme—like zap my brain with electricity—there’s always a potential for harm. One adage of the early days of computers was that anything that can go wrong can go wrong faster with computers. Fortunately, anyone with the skill to build this device would realize when something isn’t right—just as when I know that something is wrong when my smartphone alarm tells me to take a drug at the wrong time. The same is true for the system presented here. Due care is required in using any type of reminder system.
The US FDA has decided to encourage the development of low-risk medical apps, because these have the potential to enhance personal health. Apps that keep track of medications and provide user-configured reminders for improved medication adherence are one type encouraged by the FDA. There is also an exemption from regulation for non-commercial apps used for research. As a precaution, I contacted the FDA about this prescription drug reminder device. They replied that since it wasn’t being commercialized, they weren’t involved. They also didn’t see any problem with my publishing this article.
I call my prescription drug reminder device the Raspberry-Rx, since a Raspberry Pi Zero W module is a principal part of its circuitry. The device, as shown in Figure 1, operates quite simply. Light-emitting diodes are located in front of a row of eight shallow wells designed to hold pill bottles in their standard large (1-3/4″) and smaller (1-1/4″) sizes. So that there will be no confusion, a label identifies the drug associated with its well. When it’s time to take a particular drug, the LED will light, and there will be an optional short reminder beep. Phototransistors are mounted below each bottle, so a signal is generated to extinguish the LED when a bottle is removed. The Raspberry Pi keeps track of the dosage schedule, and it also generates a log of when the bottles were removed.
The Raspberry Pi Zero W has built-in Wi-Fi connectivity, so it was easy to program the device to modify the dosage schedule and read the dosage log by a web browser interface. To do this, the Raspberry Pi needs to have a web server with a PHP interface enabled. There’s also a supervisory program written in PHP that interfaces the Raspberry Pi to another circuit board having a Microchip Technology PIC microcontroller (MCU) that controls the LEDs and phototransistors. A screenshot of the web browser interface for managing the dosage schedule is shown in Figure 2.
I did the Raspberry Pi software development with a monitor, keyboard and mouse connected directly to the module. The Raspberry Pi has just one available micro USB port, so I used an inexpensive USB hub to connect the keyboard and mouse. I also needed an HDMI adapter to go from the mini HDMI on the module to a standard HDMI cable. The Raspberry-Rx operates without having these connected, so they were removed after development. There’s a common complaint that the Raspberry Pi boards seem to be inexpensive, but it takes a lot of extras to make them work. The USB hub and HDMI adapter I needed for this project are useful devices, and they were removed after development. With all that in mind, I wasn’t concerned about their added cost.
The hardware is implemented by a PIC MCU and a Raspberry Pi Zero W board—each doing what it does best. The PIC handles the GPIO, including analog-digital conversion. And the Raspberry Pi does timekeeping, file management, computation, functions as a web server and provides Wi-Fi connectivity. To keep things simple, all communication between these two subsystems is by a simple serial interface. The serial interface also allows the PIC subsystem to be interfaced easily with another computer of your choice, and it can be built into a stand-alone system without a network interface.
The PIC module’s schematic diagram (Figure 3) is extremely simple, because most of the heavy lifting is done in software. For easy development, I included a connection for an in-circuit serial programmer (ICSP), but the PIC firmware found on the Circuit Cellar article code download webpage shouldn’t need to be modified, and the ICSP connector can be eliminated. The circuitry is powered by a 5 V supply, which is also the voltage requirement for the Raspberry Pi. The circuit board layout includes a USB type-A connector to couple the supply voltage to the Raspberry Pi through a short USB cable.
The PIC interfaces to the Raspberry Pi GPIO connector using a serial interface. As can be seen, this requires just a few of its 40 GPIO pins. Because the PIC is a 5 V device, level-shifting circuitry around Q1 and Q2 is needed to interface it to the 3.3 V Raspberry Pi. The Raspberry Pi is mounted on the PIC circuit board using this connector, which means that the header pins are soldered on the bottom of the Raspberry Pi board. I suggest that you buy the Pi without a connector, and solder your own onto the back side. Otherwise, a short cable can connect the two if you have a Pi with a pre-soldered connector on the front side.
Also connected to the 40-pin connector is a pushbutton switch at J4 that allows a gentle shutdown of the Raspberry Pi by shorting pins 5 and 6. Although Linux systems are usually robust against power failures—as my desktop computer has proven time and again—this shutdown should be done before removing power from the Raspberry-Rx. Some software modification is needed to enable this shutdown mode, as explained later in this article. Connection to the LEDs and phototransistors is done by two additional connectors (Figure 4). An external 20 MHz clock is used to keep good timing for the serial port while the PIC does its many other tasks. Table 1 and Table 2 list the connections, and Figure 5 shows the PCB layout. A SIP resistor pack was used for the 10 kΩ pull-up resistors for the phototransistors. You can simulate a SIP with a bunch of vertical resistors connected at one end.
The PIC 16F886 MCU has 8,192 words of program memory, which leaves room to implement many functions. It also has 256 bytes of EEPROM for data storage, and this is used to store the dosage schedule. Table 3 shows the serial commands accepted by the PIC module, and Figure 6 is a portion of the underside of the Raspberry-Rx showing the GPIO connection of the Pi Zero to the PIC circuit board and the power connection through the USB-A connector and a 6″ adapter cable.
Raspbian is the premier operating system for the Raspberry Pi. The Raspberry-Rx uses Raspbian GNU/Linux 9.4 (stretch), which was the current version at the time of development. This must be loaded onto a MicroSD card from another PC. Don’t bother ordering an SD card pre-loaded with what’s called NOOBS. When I tried this, it seemed to require network access to configure, and the network interface (password and such) was not configurable. Perhaps I was too much of a “noob” to figure it out.
While this article offers a few prescient tips relevant to this application, it can’t include all the information you need to manage a Linux system. Many Internet resources are available to guide you through some necessary housekeeping, such as network connection, to get you to the point at which you can edit configuration files and download some necessary software. Among the programs you need to install are the Apache2 web server and its PHP interface:
sudo apt-get update
sudo apt-get install apache2
sudo apt-get install libapache2-mod-php
There are instructions on many Internet websites for checking that this installation went well. While this allows PHP interaction with a web browser, you need an additional program to run PHP programs from a command line:
sudo apt-get install php5-cli
At this point, some optional utility programs, such as the terminal program CuteCom, would be useful. One editor program that I enjoy using is KWrite. When you’re editing a file of known file type, such as a PHP file, this editor highlights the language syntax. To implement the off pushbutton at GPIO pins 5 and 6, you need to add the following line to the /boot/config.txt file:
While we’re on the topic of file modification, it’s useful to point out a common problem that novices have when using Linux: file permissions. Generally, if you can’t create, read or write some file or folder, it’s because you aren’t permitted. You can view file permissions in the file manager, and you can change the permissions as the root user by prefixing commands with sudo. Permission is an involved topic that’s better left to Internet sources.
I’ve found that the easiest way to edit files and change permissions is to open a file manager instance as the administrative user. This is easily done by executing the following on the command line:
Right clicking on a file or folder will give you a way to change its permissions. You can also open a file in the Leafpad text editor the same way. Since we need the serial port, and we might want to use an SSH network connection, enable SSH and the serial port in the Interfaces tab of the Raspberry Pi Configuration menu item.
The firmware on the PIC acts in cooperation with a supervisory program in PHP that runs on the Raspberry Pi. I enjoy programming in PHP for several reasons. First, it has a syntax close to that of the C programming language. Second, it has myriad built-in functions that make many programming tasks easier. As an example of this, I once needed to calculate what’s called the Levenshtein distance between strings, and PHP had a built-in function to do that . Finally, it allows a programmable interface in Web browser pages.
The only thing that PHP lacks for this application is an interface with the serial port of the Raspberry Pi. To accomplish this, I needed to write a short Python script that’s called from the supervisory program using the PHP exec() command. This Python script—along with the PHP supervisory program—should be loaded into a newly created directory, Rx, at /home/pi/Rx. At this point you should use the CuteCom terminal program at port /dev/ttyS0 (9,600 baud, 8 data bits, one stop bit, no parity bit and a single carriage return character following each command) to verify operation of the PIC subsystem. The home/pi/Rx/ folder should also contain the Python script for the serial interface and symbolic links to the dosage schedule file and log file, as explained later. Then you should open a terminal in the Rx directory and run the PHP supervisory program from the command line by executing the following:
If there are any problems, you’ll get error messages in the terminal to guide you.
Since normal device operation has the Raspberry Pi working without a keyboard or monitor, it’s necessary to start the supervisory program automatically when Raspbian starts. This is accomplished by adding the following to the end of the /etc/rc.local file before its exit command:
php /home/pi/Rx/raspberry_Rx.php &
Because we’re calling the supervisory program from a directory (/etc) that’s different from its location (/home/pi/Rx), all file references in the supervisory program must have an absolute file path. After application of power, it takes a little less than a minute for the Raspbian operating system to load, at which time you’ll see the LEDs on the Raspberry-Rx cycle on and off. At that point the device is operational.
You update the dosage schedule of the Raspberry-Rx and view the log of when medications were taken using a web browser. The wireless network interface is configured using Network Options in the graphical configuration obtained with the terminal command sudo raspi-config. After that, you can get the Raspberry Pi IP address by executing ifconfig from the command line, or using the nmap command on another Linux machine on your home network. These will output something like the following, from which I found the 192.168.1.253 IP address of my Raspberry-Rx:
Nmap scan report for
Host is up (0.053s latency)
You can set a static IP address if you want, although that takes some effort. However, I’ve found that the assigned IP address of my Raspberry Pi doesn’t change, which is a likely consequence of the circuit being on all the time, and the router giving its connections a long lease life.
Webpages are served from the /var/www/html/ folder, where the following files should be placed: Rx.php, Rx_log.php, Rx_data.csv, and Rx_log.txt. Rx_data.csv and Rx_log.txt are dummy files that are needed to prevent errors when the PHP supervisory program is looking for them initially. These files are in the /var/www/html/ folder, and our program is run from /home/pi/Rx/, so we need to add symbolic links from one folder to the other. This is accomplished by the following commands:
sudo ln -s /home/pi/Rx/Rx_data.csv
sudo ln -s /home/pi/Rx/Rx_log.txt
WEB BROWSER INTERFACE
Although it’s easiest to use the browser interface programs that I’ve written, you can access the Raspberry Pi using the secure shell (SSH) from a terminal. For my system with my IP address, this is accomplished in Linux with the following command:
ssh -X -l pi 192.168.1.253
Once you’ve connected with the Raspberry Pi, you can open a graphical instance of the file manager by typing pcmanfm. I’ve always found that graphical interfaces make life a lot easier.
You can also copy programs to and from the Raspberry pi using the secure copy protocol (SCP). On my system, I use the following commands for my Raspberry-Rx at IP address 192.168.1.253:
scp /local_folder/local_filename [email protected]:/pi_folder/pi_filename
scp [email protected]:/pi_folder/pi_filename /local_folder/local_filename
I access the dosage editor using the IP address of my Raspberry-Rx (192.168.1.253) by typing the following in the location box of my Firefox web browser:
To make things simple, the time granularity is 15 minutes, so valid minutes are 00, 15, 30 and 45. A screenshot of the editor page appeared earlier as Figure 2. Likewise, the log file is accessed at:
A screenshot of this is shown in Figure 7.
A FEW CAVEATS
Although most pill bottles now have child-proof caps, all medications—including the medications on this device—should be placed out of reach of children. Also, the web browser pages are not password protected and are not secure. That means that anyone on your home network can access these pages. Since the Raspberry-Rx isn’t Internet-connected, it isn’t really a part of the Internet of Things (IoT) that we’re hearing a lot about—but hackers might be able to access it nonetheless. Some programmer more experienced that I am might be able to secure the application so that it might be safely Internet accessible.
Unlike a desktop computer, the Pi-Zero doesn’t have an internal real-time clock. You need a network connection to get the time, or you can easily add a battery-powered real-time clock (RTC) to the Pi-Zero, using instructions available on the Internet. As long as the device has network access at boot-up, network time protocol (NTP) will set the clock initially and the Raspberry Pi will maintain the time accurately for many days using internal timekeeping. If a wireless network connection is not established at boot, the Raspberry-Rx will signal the fault by beeping at you. As an added measure, the dosage editor webpage shows the time from the Raspberry Pi clock.
Removal of a pill bottle is detected when the intensity of light at its phototransistor exceeds a threshold, so that won’t happen in a dark room. Taking medications in the dark isn’t likely, since we can’t see what we’re taking, so this shouldn’t be a problem. However, many pill bottles are translucent, so some light will leak through even when the bottle is in place. This means that either the threshold needs to be adjusted to take this into account, or a small piece of opaque tape can be placed on the bottom of problematic bottles. I’ve found that such light-blocking tape isn’t required for any pill bottle in my uniformly lighted bathroom. If you pull a bottle and the LED isn’t extinguished, you either need more room light or a different threshold.
Some medications need to be refrigerated. In that case, the pill bottle in the Raspberry-Rx serves as a reminder to take the particular medication, and not the place where the actual medication is kept. Some eyedropper bottles are small, so they would need to be placed in a pill bottle for reliable operation of the Raspberry-Rx.
For detailed article references and additional resources go to:
Reference  as marked in the article can be found there.
PUBLISHED IN CIRCUIT CELLAR MAGAZINE • APRIL 2019 #345 – Get a PDF of the issueBecome a Sponsor