Category: Arduino

Coffee pot and sensorsLike most tech offices, we go through a lot of coffee during the day. We have about 15 people spread between 2 rooms upstairs, and a single coffee pot between us. Generally this means someone makes a pot early in the morning and it’s done by lunch time, when someone else makes another. The problem is that it’s difficult to time your coffee intake with a fresh pot. Wouldn’t it be great if we could get some kind of alert when the pot was ready?

How to get that notification was pretty straightforward: we use HipChat, a very well done message platform from the folks at Atlassian. Even better is that HipChat offers an extensive API, with the simplest method being something called Integrations. These provide a self-contained URL request to make to a particular room and alert all of its members. All I’d need to do is track the coffee pot cycle and send an alert at the appropriate time.

Choosing the hardware

The first step is determining what method to use for tracking the cycle. Looking around online, people have done similar things by looking at the weight of the pot, the level of coffee in the pot and the current consumed by the maker itself. I don’t want to deal with weight (yet) and I find level monitoring overly complicated so I decided on current. Ideally I would be able to determine the cycle based on either the on/off times or the actual current consumption.

I have amassed a pretty large collection of Arduinos at this point, so choosing that platform was pretty easy. I also wanted to have everything self contained as much as possible, which meant looking for something with the following capabilities:

  • Analog inputs for connecting the current sensor
  • Digital output for local monitoring (LED, LCD)
  • Network connectivity for sending a notification
  • Logging to collect enough current data to notice a pattern

The only Arduino that satisfies these requirements is the Arduino YUN. The YUN is different from other Arduinos in that it is actually two chips in one, with a standard ARM chip on one side running the Arduino bootloader and a dedicated Linux board on the other side to run more complex operations. The advantage of this setup is that you can collect sensor input on one side and transfer that to Linux for processing.

For actual sensor monitoring I decided on the SCT-013-010 non-invasive current sensor. This is a version of the fairly popular SCT series, has capacity up to 10A and provides scaled 1V output. That last point is important, because I find it simpler to take analog voltage input than creating a circuit to make the scaled current output provide meaningful data.

Finally I added in a 128×32 OLED LCD I had from a previous project, for local monitoring of the current consumption. With that in place, I might even notice a pattern by glancing at the screen.

Collecting the data

While the current sensor is technically “non-invasive”, it does require some wire hacking to work properly. It works on the principle that a voltage can be induced in a neighbouring wire through an electric field. However since it works with AC lines, that power fluctuates through both wires at opposite time, effectively cancelling each other out. The solution is to split your appliance wire apart and wrap the sensor around only one of them.

After assembling a circuit according to numerous other current tutorials (like the Open Energy Monitor project), I was receiving current data to the screen, but it did not appear very useful. In fact, this was what I call Road block #1. I was reading the current data as if it was DC, but since AC power is a wave, I was effectively reading a single point in the wave and not the proper current. Fortunately the solution was to better follow that tutorial, and use the Emonlib Arduino library. This library monitors the entire power wave and does the correct math to give you a current value in amps.

With the current readings accurate, I needed to log them somewhere for later processing. To do that I used a MicroSD card in the YUN along with the example sketch called DataLogger. I modified that script to only save current when the reading is 0.1A or higher and to create a new file every day to keep things organized. After a day in the office, I had useful data, but I immediately ran into Road Block #2.

Setting a minimum threshold of 0.1A seemed to make sense, but after seeing the power consumption through the cycle, our particular coffee marker consumes 0.17A at idle. With a logging interval of 1 second, I ended up collecting a row of data every second for 2 days! It was not very useful so I cleared the SD card, reset the threshold to 0.2A and tried again.
coffee-pot-consumption-list
This is the data that resulted from a day of coffee pot monitoring. The Arduino provided a column containing the current time and the current usage, plus a filtered current value I didn’t end up using. I imported the data into Excel and added the column to the right, which is the difference between any one row and the time above it. Since there is no data logged when the machine is off, it became very easy to see the gaps. I also added the conditional formatting to highlight rows that are more than 2 seconds.

Looking through the rows, I was able to find this pattern for a typical coffee cycle:

  • It idles at 0.17A (idle meaning plugged in but not actively brewing)
  • At the start of the brewing cycle, the current changes to approx. 7.5A for 8-10 minutes
  • The end of the brewing cycle is indicated by 25 seconds on and 25 seconds off, twice
  • Once brewed, it repeats a cycle of 15 seconds on, 2 minutes off until someone turns the power off

With such clearly defined points along the cycle, it turned out to be pretty straightforward to detect. The notable complication is that the times are not precise, and it might be on for 8 minutes instead of 10 or heat for 25 seconds instead of 15. I was somewhat disappointed that it did not cycle differently depending on the volume of coffee to heat. I was hoping that it would heat less as the coffee level dropped and I could determine how many cups remained.

Doing the math

To detect the brewing cycle, I set the Arduino timer to compare current usage every second. I stored the previous value and used that to save a time reference for when the current level went above the threshold (set to 6A). By comparing those values, I could get an event when the coffee maker turns on and off, while checking the time between the two. If the appliance is on for more than 8 minutes, that’s considered the actively brewing stage. After that, if there is an on period of less than 30 seconds, that would be the start of the heating stage. The message alert would go out at the end of the brewing stage. I started with a 10 minute brewing cycle but ended up changing it to 8 when I found that the heater wasn’t always consistent. It turned out to be pretty accurate, though!

Triggered by the 1 second timer is this method

First I receive a UNIX timestamp from the Linux processor. This makes comparing times easy. Next I set a few variables based on whether the current usage is above or below the threshold set at the start. This is important because events are generally only triggered when things change. The logEvent() method logs the event to the SD card for future comparison and sendEventMessage() sends a notification to a HipChat room I set up specifically for monitoring my projects.

The brewing cycle checking works by using the current mode and checking the time between when the coffee maker when on or off. If it’s determined to be on for more than a minute nonstop, it’s considered “brewing”. Once it turns off and the gap between events is more than 8 minutes, that’s the end of the brewing cycle and the method sendMessage() is triggered to actually send a HipChat notification. After that a short on/off cycle is checked to look for heating and if it goes off longer than 5 minutes, the coffee maker is idle. The trick is generally to not detect another stage in the cycle if that stage is currently active. That usually removes the issue of sending a message continuously instead of once.

Sending a message

The YUN provides multiple ways of sending an HTTP request, but the easiest thing is to trigger a bash script inside Linux, instead of using Arduino directly. Finding that out was the solution to Road block #3. Throughout the internet, keyboard warriors warn about using Arduino’s string object and how inefficient it is. I started by generating a cURL request with a single String object, but that never worked. It turns out that I ran up against what appeared to be a memory limitation inside Arduino that probably limits string length to 256 characters. The cURL command I wanted to run was about 260 and would exit without error, but without actually sending a message. The solution to that problem is to move the cURL command to a separate bash script on the SD card and trigger that script from Arduino instead.

The last problem was that cURL would try to verify the SSL certificate that HipChat was using but was unable to. While probably not proper, the easiest thing is to disable that check using the -k flag in the command. After that, I set up the monitor and 10 minutes after brewing started, this appeared in our All Teams chat:
hipchat-coffee-bot-message
After a few days of operation, it seems to be fairly accurate and people have responded well to the little machine we call Coffee Bot.

Next steps

As mentioned I was hoping to be able to retrieve coffee levels from the current interval but since our particular coffee maker doesn’t do that, I’ll have to add a scale. With weight data available, I could know right away that a new pot is brewing and how many cups are left. It would even be possible to make the HipChat integration accept requests to know how many cups are left. You could write /coffee cups to know the number or /coffee time to know how long it’s been heating.

We also have tea drinkers so it would be reasonably straightforward to add a tea pot sensor. That cycle is even easier because it is either on and heating or off.

Finally I might make the hardware collection a little prettier for the shelf by maybe 3D printing an enclosure and making a proper PCB but that’s now pretty far down my list of electronics projects.

Finished product
My apartment uses baseboard heaters and anyone who’s paid for hydro can tell you, they’re pretty inefficient. I wanted to collect some information about the inside conditions of my apartment so that I could better understand when and how to turn the heaters on. Normally a simple thermostat would do, or even a Nest, but my equipment is so basic, there is no read out available.

So I built my own. Here’s what I did.

In high level terms, I have an Arduino UNO using a WiFi shield and custom PCB connected to a DHT22 temperature and humidity sensor and photocell. This information is sent to data.sparkfun.com and is displayed in snapshot, table and graph form on my iPhone.

Setting up the Arduino

The components with the Arduino are all fairly well known, but I had not made anything with them together. Here are the parts and links to where to get them

I put them together on a breadboard and build the code. I can provide code if interested, but essentially I assembled individual modules in order to upload the data every 5 minutes. As far as the program goes, it’s laid out like this

  1. Include all libraries — this uses DHT, Timer, Wifi, SPI WifiClient, WifiServer and medianFilter
  2. Define base variables — Wifi shield configuration, website, pins, etc
  3. Create objects — Timer, client, server, filters
  4. run setup() — set pin modes, connect to Wifi and set the timers
  5. loop() only updates the timer
  6. Every 30 seconds all sensors are read and added to a filter
  7. Every 5 minutes the filtered data is sent to data.sparkfun.com

Creating a circuit

schematicA breadboard is fun for prototyping, but it wouldn’t look so good on a shelf, so I took the opportunity to test out a new PCB manufacturing website by building my own circuit. The pinouts of all components is fairly easily available online, or better yet, in EAGLE itself. The board doesn’t have many pieces, just some 0.1″ header holes, but the tricky bit is making sure that there are no pin conflicts with the Wifi shield.

Moving to a PCB

environmental_board
EAGLE provides a nice way to import a schematic to a board, and since I started with an Adafruit shield piece, there was a nice outline ready for me. At that point it was a matter of making sure that all traces have clean paths and there are 5V and GND planes.

1-IMG_7920
4-IMG_7930
3-IMG_7924
I tried a PCB service previously called OSHPark.com but was unhappy with the cost and lead time required. A friend pointed me towards dirtypcbs.com and that turned out to be a great choice. The name is basically entirely what you get: printed circuit boards at affordable prices, with a very reasonable 1 week lead time. I was also impressed with the shipping from China, as it was no more than an additional week with DHL. That’s 2 weeks for 10 custom boards.

Displaying it all on a phone

The data is sent to data.sparkfun.com, which provides a nice free way to store key-value data (eg. temperature=25,humidity=38, etc) and a way to retrieve it. During the day I work for a mobile software company, so building something to retrieve the data was fairly straightforward. I ended up with a way to view different properties in the latest data, table and graph form.
IMG_1565
This is the home page where the latest data point is displayed front and centre, along with the time it was retrieved. The time is relative, so a timer runs every second to indicate how old it is, but clicking the label shows the actual timestamp. Below that is some related information that might be useful: the 24 hour high value, 24 hour low value, and the current outside temperature according to forecast.io.
IMG_1569
Additionally the menu button at the top left presents a slide out “hamburger menu” that can switch between the different properties collected.
IMG_1570
The middle tab shows the last hour of data in table format and as you scroll downward, will load the next block from Core Data. In order to keep the actual internet request simple, the app retrieves the timestamp of the most recent datapoint and only requests points from Sparkfun that are after that. All points are stored in Core Data and loaded on demand.
IMG_1567
Finally the right most tab shows a graph of whatever property is displayed at the time, with options for last 4 hours, last day or last 4 days. At first I had last hour but I realized the data I was collecting wasn’t really changing in that time frame so it was largely useless.

For the most part the graphs are consistent, with my heater keeping the temperature at about 19-20C through the day. The light graph is very interesting because it clearly shows when the light goes off and how sunlight filters through the curtains in the morning.

Next plans

There’s one thing I’d change about the PCB design, and that would be to replace the fixed photo cell resistor with a potentiometer to adjust the threshold. Right now I’m using a 16k ohm (I think, something about 10k) and that produces a nice range between full bright and darkness, but it would be good to adjust as required.

With the data collected, I’d like to now make use of it somehow. You might notice how the board has 4 pins showing “relay” on it, which is so that I can connect an AC relay and control my lights or humidifier. Ultimately I’d like to work in some geocoding to my app so that I never come home to a dark apartment and have my light be smarter so that it doesn’t turn off while I’m still at my desk.

Tagged with: , , ,

Arduino, PowerSwitch Tail 2, humidifierMechatronics is described as the intersection between mechanical, electrical and computer engineering, and it covers just about anything that uses electronic signals to act on mechanical systems. It’s what I went to school for, and it’s where my hobby interests lie. The Arduino is a fantastic example of how people with limited experience can jump right into mechatronics projects. I’ve been tinkering with them for a few years, and decided to put the components I had to good use by taking a timid step to home automation.

Indoor humidity can affect the comfort level of a home pretty dramatically. Since warm air can hold far more moisture than cold air, the humidity inside during the winter falls dramatically. This drop can cause an increase in static electricity, sickness and dry, itchy skin. Too dry and a home can just feel downright uncomfortable. Too much humidity when the outside temperature is low can also cause condensation on the windows and mould growth. Some humidifiers have a built in control system to maintain the proper level of humidity, but what if yours doesn’t?

By combining an Arduino with a basic humidity sensor and relay, you can trigger your simple humidifier to only come on when needed.

Bill of Materials

With these pieces combined together, you can find the indoor temperature and humidity, and adjust the humidifier’s set point manually to achieve the proper moisture level.

Assembly

Complete breadboardHere are some links about connecting the different components that make up the system.

Additionally I have a few bonus status LEDs for displaying when the correct humidity has been reached (although you’ll be able to tell from whether the humidifier is on or off). The great part about the Arduino community is that most of the major components have libraries dedicated to their functions, so you can spend less time figuring out how the hardware works and more time thinking of projects.

Control System

The control system is the set of governing equations and parameters that determine what behaviour the system’s output should have. In this case, it takes in the current level of moisture in the air and tells the relay to switch the humidifier on or off. For that reason, it’s a type of control system called “closed-loop”, because turning the humidifier on will increase the sensor value and trigger it off.

There are many other different types of control systems but we’re fortunate that the main type in use here is called an “on-off controller” for its inability to adjust output values. Like a furnace, the humidifier can be either on or off, with the time in each state determining the magnitude of change. Compared to a PID controller, which uses error correction to maintain a system, the on-off controller is far simpler.

The complete source code is available to download below, but I’ll go through some of the important parts here.

Temperature and humidity outputEven in a relatively simple system such as this, it’s important to follow proper coding patterns. This means using the Model-View-Controller paradigm to retrieve sensor data and output to the screen and relay. In even simpler terms, it means storing the inputs as variables and refreshing the screen rapidly with those variables. For that, it’s a good idea to use something like a Timer class to handle running specific methods at an interval without blocking the main program.

With the button, I’m able to toggle between two states: normal and setting. Doing that is easy with enumerations.

Each time the button is clicked, the state of systemMode is changed, and the display is updated accordingly.

Toggling display modesThe ModeSetting value is where a new setpoint for the control system is entered. When TARGET is displayed on screen, the encoder LED flashes (again with another timer) and turning the encoder updates the value.

While the above links show a clear way of entering the new encoder value, here’s my function.

You only want to update the target value if the current mode is Setting and the new encoder value is different from the previous.

Whenever the system mode returns to normal, the controller checks if the current value is where it needs to be and updates the relay accordingly. However, it’s not as simple as turning the relay on when humidity is below the target and turning it off when it goes above. If that was the case, there would be far too much cycling. That means as the error approaches 0 (humidity reaches the target), the actual value could repeatedly go across the threshold and cause the humidifier to cycle on and off quickly. I’ve set the refresh rate to be 1 minute, but even that would be annoying if it cycled that quickly. To fix the problem, we need to introduce a control system property of hysteresis, which in simplified terms means making the humidifier stay on until it passes the target by a few percent, and not turning on until it’s a few points below the target. This way it cannot rapidly switch between the on and off states. In code, that might look something like this.

Here, the variable correct is the value of whether the system is currently at the desired level, and hysteresis is the percent of padding (2% here).

What this block is essentially saying, then, is “if the humidity is currently above the desired value, don’t turn on again until the humidity is below target – 2” or “if the humidity is currently below the desired value, stay on until the humidity rises to target + 2”. In this way, the system won’t turn on and off in quick succession.

Connect the PowerSwitch relay pins to ground and an Arduino 5V output, and set the state of the pin according to correct. Then sit back and listen to the satisfying click of the relay as computers do your job for you.

Controller and humidifier together

What’s next?

Since this current version requires you to set the target point on the humidifier manually, it’d be nice to make that automatic, too. But how? The problem is that indoor humidity is linked to outside temperature, as I mentioned above, so that means you need to find out the local temperature and adjust the humidity accordingly. That can be done any number of ways, like adding a WiFi or ethernet shield to the Arduino.

This is something I’m planning on doing, but I’m going a slightly different route so that I can build on it for more advanced home automation. By building an Xbee network, I can make nodes that act as sensors or outputs and connect them all to a central computer. Since I already have Ubuntu server, that part is taken care of. I can log data to the server and have it request local weather and tell this Arduino whether the humidifier should be on or off.

But the fun wouldn’t even need to stop there. By designing the network right, suddenly you can add other components to do things like turn lights or appliances on or off or alert you when a window is left open at night. Where will you take it?

Tagged with: , , , ,


After choosing a mechatronics option in my final year of mechanical engineering, I’ve gotten more interested in electronics and computer integration. Sure, I’ve done programming in the past (and present) but there is something very satisfying about writing code on a screen and having it perform an action in the real world. With that in mind, I ordered myself an Arduino microcontroller from Adafruit and have spent the last few weeks learning the ins and outs of some of the included components. So far I’ve hooked up some LEDs, a DC motor and a servo motor to the breadboard and watched them blink and spin. The kit contains bonus material, but you can also get just the board to save some money. It includes components like red and green LEDs, resistors, transistors, jumpers, and the previously mentioned DC and servo motors. Programming the board requires very straight forward C language knowledge. There are dozens, perhaps even hundreds of tutorials online to program nearly all functions of the board itself.

What is it used for?

You may be wondering what the real purpose of the board is, but there is no definite answer to that. In reality, Arduino, being an open source hardware project, has been used in numerous projects seen around the web. Any component that can be plugged into one of the pins can be controlled, which means people have used it to create secret knock opening doors, a radio controlled lawnmower, even a laser harp. This only scratches the surface. My plans, without giving too much away, include building a panoramic camera mount and adding radio controls to household/garage items (project details will be here when they are completed). If you have any interest at all in electronics, I suggest picking one up and learning about it.

Tagged with: , , , , ,