# Adafruit Kegomatic

## Overview

http://www.youtube.com/watch?v=IaD-7yJCroQ

The Adafruit Kegomatic is a team project by everyone at Adafruit! We wanted to see how we could augment a kegerator with cool hardware from the Adafruit store and make it active online.  
  
Our first experiment was to hook up a liquid flow meter and have the keg tweet every time someone drinks from it! Follow [@AdafruitKegBot](https://twitter.com/adafruitkegbot "Link: https://twitter.com/adafruitkegbot")for updates.  
  
For now the keg has birch beer, but we'll be getting a beer beer kegerator soon and will mod that one up as well!

![](https://cdn-learn.adafruit.com/assets/assets/000/010/537/medium800/projects_inside-unaltered-kegerator.jpg?1376692414)

![](https://cdn-learn.adafruit.com/assets/assets/000/010/538/medium800/projects_adakeg-dispenses-birch-beer.jpg?1376692511)

![](https://cdn-learn.adafruit.com/assets/assets/000/011/289/medium800/projects_kegbot_twitter_header.jpg?1380301462)

# Adafruit Kegomatic

## Bill of Materials

Adafruit hardware:

- [Raspberry Pi](http://www.adafruit.com/products/998)
- [Liquid flow meter](http://www.adafruit.com/products/828) (plastic not brass, which could make the tasty beverage taste funny)
- [HDMI monitor](http://www.adafruit.com/products/1033)
- [Mini wifi module](http://www.adafruit.com/products/814)
- [Mini wireless keyboard](http://www.adafruit.com/products/922)

Other hardware:

- [Kegco kegerator](http://www.kegco.com/kegerators/index.html) or modded fridge
- keg of birch beer (better for testing than alcoholic beer!)
- 2x liquid lines (one to mod and a backup)
- small CO2 tank with regulator and air hose
- teflon tape
- 2x barb -\> threaded connector that matches interior diameter of the liquid line and threads on the flow meter ([A customer](https://github.com/adafruit/Kegomatic/issues/5#issuecomment-323128472) has reported success with [this barb fitting from US Plastics](https://www.usplastic.com/catalog/item.aspx?itemid=27795) and [unions](http://www.homedepot.com/p/Homewerks-Worldwide-1-2-in-PVC-Slip-x-Slip-Union-511-14-12-12H/204202875) from Home Depot)
- 2x hose clamps

![](https://cdn-learn.adafruit.com/assets/assets/000/010/539/medium800/projects_closeup-keg-junction.jpg?1376693284)

![](https://cdn-learn.adafruit.com/assets/assets/000/010/540/medium800/projects_gasketed-hole.jpg?1376693388)

![](https://cdn-learn.adafruit.com/assets/assets/000/010/943/medium800/projects_DSC_3027.jpg?1379011283)

Thanks to Snoegoer Co. in Minnesota for making and donating this sweet tap, we'll be putting it on our next kegerator!

# Adafruit Kegomatic

## Prototype Circuit

![](https://cdn-learn.adafruit.com/assets/assets/000/010/603/medium800/projects_DSC_3023.jpg?1377205784)

You can hook the sensor up to an [Arduino using our sample code](https://github.com/adafruit/Adafruit-Flow-Meter), or read on for the Raspberry Pi setup.

![](https://cdn-learn.adafruit.com/assets/assets/000/010/604/medium800/projects_DSC_3025.jpg?1377205879)

Test the flow meter by blowing into it (there's an arrow on the meter to show you the correct flow direction).  
  
When it's working to your satisfaction, flush it with soapy water to clean it before installing in your kegbot.

# Adafruit Kegomatic

## Install Flow Meter

![](https://cdn-learn.adafruit.com/assets/assets/000/010/600/medium800/projects_DSC_3019.jpg?1377204541)

It helps to have two liquid tubes, in case you break one but still want to access your beer. Cut the liquid line with a pair of sharp scissors.

![](https://cdn-learn.adafruit.com/assets/assets/000/010/945/medium800/projects_DSC_3304.jpg?1379012060)

Insert the barbed connectors into the cut ends of the tubes and secure with hose clamps.

![](https://cdn-learn.adafruit.com/assets/assets/000/012/959/medium800/projects_keg-flow-meter-teflon-tape.jpg?1387302361)

Thread the flow meter into the connectors (don't forget the teflon tape)-- now the liquid will go through the flow meter!

Cut off the flow meter's connector, strip the three wires inside, and solder on a long extension for each wire, enough to go from your keg tube, outside the keg, to the output display. We made ours about four feet long.  
  
To connect each wire, tin the stripped ends, then position the two wire ends together and remelt the solder. Slide on pieces of heat shrink tubing to insulate the solder joints.

![projects_DSC_3012.jpg](https://cdn-learn.adafruit.com/assets/assets/000/010/602/medium640/projects_DSC_3012.jpg?1377204777)

![projects_keg-flow-meter-extend-wires.jpg](https://cdn-learn.adafruit.com/assets/assets/000/012/960/medium640/projects_keg-flow-meter-extend-wires.jpg?1387303057)

![](https://cdn-learn.adafruit.com/assets/assets/000/011/279/medium800/projects_DSC_3301.jpg?1380299163)

Run the extension wires out the back of the fridge so they can be hooked up to the RasPi/Arduino/system of your choice.

# Adafruit Kegomatic

## Raspberry Pi Code

![](https://cdn-learn.adafruit.com/assets/assets/000/012/962/medium800/projects_tony-kegbot-screen.jpg?1387303333)

The code for this project is on GitHub.   
  
[https://github.com/adafruit/Adafruit\_Learning\_System\_Guides/tree/master/Kegomatic](https://github.com/adafruit/Adafruit_Learning_System_Guides/tree/master/Kegomatic)

After you've set up your pi, log in or ssh in, and get ready to set up some stuff. First, we'll download the kegbot code. You can download all the code by clicking the green button below.

[Download the source code](https://github.com/adafruit/Adafruit_Learning_System_Guides/tree/master/Kegomatic)
or use:

```
git clone https://github.com/adafruit/Adafruit_Learning_System_Guides/tree/master/Kegomatic/Kegomatic.git
```

We'll need to install Python's setup tools in order to make it easier to install the pre-requisites for our Twitter code.

```
sudo -i
wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py -O - | python

```

Next, we will install a whole bunch of pre-requisites. Execute these one line at a time and look for errors. If you don't see any, you're good to go.

```
sudo easy_install twitter
sudo easy_install simplejson
sudo easy_install httplib2
sudo easy_install python-oauth2
```

And that's it for setup... now the code should work... let's take a look at what it does!

```
#!/usr/bin/python
import os
import time
import math
import pygame, sys
from pygame.locals import *
import RPi.GPIO as GPIO
from twitter import *
```

The above lines are all the imports we need... we need the twitter API for twittering, the GPIO library so we can use the GPIO pins, pygame so we can make this a fun windowed application, math so we can do some math stuff, time so we can do accurate timing, and os so we can run things at the os level.  
  
Next, we'll need to initialize the twitter account:

```
t = Twitter( auth=OAuth(OAUTH_TOKEN, OAUTH_SECRET, CONSUMER_KEY, CONSUMER_SECRET) )
```

First, go set up a Twitter app [here](https://apps.twitter.com/app/new "Create an Application"). &nbsp;You will need to be logged in to Twitter from whatever account you would like to do the kegomatic tweeting.

Then, come back to the code, and replace OAUTH\_TOKEN, OAUTH\_SECRET, CONSUMER\_KEY, and CONSUMER\_SECRET with the actual values from your twitter account app page.  
  
After that, we will need to initialize the GPIO pins...

```
boardRevision = GPIO.RPI_REVISION
GPIO.setmode(GPIO.BCM) # use real GPIO numbering
GPIO.setup(22,GPIO.IN, pull_up_down=GPIO.PUD_UP)
```

The next several lines are there to set up pygame, the windowed context, and various global variables we will need throughout the program...

```
# set up pygame
pygame.init()

# set up the window
VIEW_WIDTH = 0
VIEW_HEIGHT = 0
pygame.display.set_caption('KEGBOT')

# set up the flow meter
pouring = False
lastPinState = False
pinState = 0
lastPinChange = int(time.time() * 1000)
pourStart = 0
pinChange = lastPinChange
pinDelta = 0
hertz = 0
flow = 0
litersPoured = 0
pintsPoured = 0
tweet = ''

# set up the colors
BLACK = (0,0,0)
WHITE = (255,255,255)

windowSurface = pygame.display.set_mode((VIEW_WIDTH,VIEW_HEIGHT), FULLSCREEN, 32) 
FONTSIZE = 48
LINEHEIGHT = 52
basicFont = pygame.font.SysFont(None, FONTSIZE)
```

Next comes the renderThings() function, which draws all of our updated data to the screen...

```
def renderThings(lastPinChange, pinChange, pinDelta, hertz, flow, pintsPoured, pouring, pourStart, tweet, windowSurface, basicFont):
  # Clear the screen
  windowSurface.fill(BLACK)
  
  # Draw LastPinChange
  text = basicFont.render('Last Pin Change: '+time.strftime('%H:%M:%S', time.localtime(lastPinChange/1000)), True, WHITE, BLACK)
  textRect = text.get_rect()
  windowSurface.blit(text, (40,1*LINEHEIGHT))
  
  # Draw PinChange
  text = basicFont.render('Pin Change: '+time.strftime('%H:%M:%S', time.localtime(pinChange/1000)), True, WHITE, BLACK)
  textRect = text.get_rect()
  windowSurface.blit(text, (40,2*LINEHEIGHT))
  
  # Draw PinDelta
  text = basicFont.render('Pin Delta: '+str(pinDelta) + ' ms', True, WHITE, BLACK)
  textRect = text.get_rect()
  windowSurface.blit(text, (40,3*LINEHEIGHT))
  
  # Draw hertz
  text = basicFont.render('Hertz: '+str(hertz) + 'Hz', True, WHITE, BLACK)
  textRect = text.get_rect()
  windowSurface.blit(text, (40,4*LINEHEIGHT))

  # Draw instantaneous speed
  text = basicFont.render('Flow: '+str(flow) + ' L/sec', True, WHITE, BLACK)
  textRect = text.get_rect()
  windowSurface.blit(text, (40,5*LINEHEIGHT))

  # Draw Liters Poured
  text = basicFont.render('Pints Poured: '+str(pintsPoured) + ' pints', True, WHITE, BLACK)
  textRect = text.get_rect()
  windowSurface.blit(text, (40,6*LINEHEIGHT))
  
  # Draw Pouring
  text = basicFont.render('Pouring: '+str(pouring), True, WHITE, BLACK)
  textRect = text.get_rect()
  windowSurface.blit(text, (40,7*LINEHEIGHT))

  # Draw Pour Start
  text = basicFont.render('Last Pour Started At: '+time.strftime('%H:%M:%S', time.localtime(pourStart/1000)), True, WHITE, BLACK)
  textRect = text.get_rect()
  windowSurface.blit(text, (40,8*LINEHEIGHT))
  
  # Draw Tweet
  text = basicFont.render('Tweet: '+str(tweet), True, WHITE, BLACK)
  textRect = text.get_rect()
  windowSurface.blit(text, (40,9*LINEHEIGHT))

  # Display everything
  pygame.display.flip()
```

Now we begin the main loop, which will loop forever (until we quit the program). The first thing we need to do at the beginning of the loop every time is to figure out how much time has passed since the last time we ran the loop. To do that, we get need to get the current time. We also need to know if the pin is set high or low right now, so we can start counting the time between pulses of the flow meter.

```
# main loop
while True:
  currentTime = int(time.time() * 1000)
  if GPIO.input(22):
    pinState = True
  else:
    pinState = False
```

We also have a small amount of keyboard handling code, so that the user can press the escape key to exit the program.

```
# Handle keyboard events
  for event in pygame.event.get():
    if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
      pygame.quit()
      sys.exit()
```

Now, this next if statement is a doozie, so bear with me...   
  
If the pin state is high and is not the same as it was last time through the loop (so that the pin staying high doesn't result in a steady stream of clicks as the loop runs over and over) then we enter pouring mode. While in pouring mode, we figure out how much time has passed between this click and the last click of the flow meter, and use that to calculate the flow. Once we have the number of milliseconds between the last click and now, we can figure out the hertz of the meter, divide that by the rate expected of the flow meter to get 1 liter per second of flow, and convert the result from liters to pints. This (very small) number represents the amount of beer that has been poured during this time through the loop.

```
# If we have changed pin states low to high...
  if(pinState != lastPinState and pinState == True):
    if(pouring == False):
      pourStart = currentTime
    pouring = True
    # get the current time
    pinChange = currentTime
    pinDelta = pinChange - lastPinChange
    if (pinDelta &lt; 1000):
      # calculate the instantaneous speed
      hertz = 1000.0000 / pinDelta
      flow = hertz / (60 * 7.5) # L/s
      litersPoured += flow * (pinDelta / 1000.0000)
      pintsPoured = litersPoured * 2.11338
```

This next if statement is a little shorter... it says that if we are pouring, and we notice that our sensor has been idle for more than 3 seconds, then we can assume that we are no longer pouring, and it's time to calculate how big the pour was and tweet it. After we do that, we should reset the amount poured so the next guy can begin his pour.

```
if (pouring == True and pinState == lastPinState and (currentTime - lastPinChange) &gt; 3000):
    # set pouring back to false, tweet the current amt poured, and reset everything
    pouring = False
    if (pintsPoured &gt; 0.1):
      pourTime = int((currentTime - pourStart)/1000) - 3
      tweet = 'Someone just poured ' + str(round(pintsPoured,2)) + ' pints of root beer in ' + str(pourTime) + ' seconds'
      t.statuses.update(status=tweet)
      litersPoured = 0
      pintsPoured = 0
```

Finally, we must draw everything to the screen, and update the time variables so that we can accurately measure time the next time we go through the loop.

```
  renderThings(lastPinChange, pinChange, pinDelta, hertz, flow, pintsPoured, pouring, pourStart, tweet, windowSurface, basicFont)
  lastPinChange = pinChange
  lastPinState = pinState
```

To run this code, run the following:

```
sudo python kegbot.py
```

That should bring up a window with the bot statistics, and then you can start pouring and tweeting!


## Featured Products

### Liquid Flow Meter -  Plastic 1/2" NPS Threaded

[Liquid Flow Meter -  Plastic 1/2" NPS Threaded](https://www.adafruit.com/product/828)
Measure liquid/water flow for your solar, computer cooling, or gardening project using this handy basic flow meter. This sensor sit in line with your water line, and uses a pinwheel sensor to measure how much liquid has moved through it. The pinwheel has a little magnet attached, and...

In Stock
[Buy Now](https://www.adafruit.com/product/828)
[Related Guides to the Product](https://learn.adafruit.com/products/828/guides)
### Raspberry Pi Model B 512MB RAM

[Raspberry Pi Model B 512MB RAM](https://www.adafruit.com/product/998)
Adafruit ships the **Raspberry Pi Model B 512MB RAM** as of 10/18/2012.  
  
The Raspberry Pi® is a single-board computer developed in the UK by the Raspberry Pi Foundation with the intention of stimulating the teaching of basic computer science in schools. The Raspberry...

No Longer Stocked
[Buy Now](https://www.adafruit.com/product/998)
[Related Guides to the Product](https://learn.adafruit.com/products/998/guides)
### Adafruit Assembled Pi Cobbler Breakout + Cable for Raspberry Pi

[Adafruit Assembled Pi Cobbler Breakout + Cable for Raspberry Pi](https://www.adafruit.com/product/914)
Now that you've finally got your hands on a [Raspberry Pi® Model B](http://www.raspberrypi.org/), you're probably itching to make some fun embedded computer projects with it. What you need is an add on prototyping Pi Cobbler from Adafruit, which can break out all those...

No Longer Stocked
[Buy Now](https://www.adafruit.com/product/914)
[Related Guides to the Product](https://learn.adafruit.com/products/914/guides)
### Breadboarding wire bundle

[Breadboarding wire bundle](https://www.adafruit.com/product/153)
75 flexible stranded core wires with stiff ends molded on in red, orange, yellow, green, blue, brown, black and white. These are a major improvement over the "box of bent wires" that are sometimes sold with breadboards, and faster than stripping your own solid core wires. Makes...

In Stock
[Buy Now](https://www.adafruit.com/product/153)
[Related Guides to the Product](https://learn.adafruit.com/products/153/guides)
### Miniature WiFi (802.11b/g/n) Module: For Raspberry Pi and more

[Miniature WiFi (802.11b/g/n) Module: For Raspberry Pi and more](https://www.adafruit.com/product/814)
Make your Internet of Things device cable-free by adding WiFi. Take advantage of the Raspberry Pi and Beagle Bone's USB port to add a low cost, but high-reliability wireless link. We tried half a dozen modules to find one that works well with the Pi and Bone without the need of recompiling...

No Longer Stocked
[Buy Now](https://www.adafruit.com/product/814)
[Related Guides to the Product](https://learn.adafruit.com/products/814/guides)
### Adafruit Pi Dish for Raspberry Pi - Includes Breadboard

[Adafruit Pi Dish for Raspberry Pi - Includes Breadboard](https://www.adafruit.com/product/942)
By popular demand! We now have a way to attach a Raspberry Pi computer to a plastic 'dish' with a full-sized breadboard. We designed it carefully to make it as easy as possible to attach and detach the Pi. There are two ways to mount the Pi onto the plate, so you can flip it around for...

No Longer Stocked
[Buy Now](https://www.adafruit.com/product/942)
[Related Guides to the Product](https://learn.adafruit.com/products/942/guides)

## Related Guides

- [Adafruit TCS3430 / TCS34303 Ambient Tri-Stimulus Color Sensor](https://learn.adafruit.com/adafruit-tcs3430-tcs34303-ambient-tri-stimulus-color-sensor.md)
- [Adafruit USB Host BFF](https://learn.adafruit.com/adafruit-usb-host-bff.md)
- [I2C/SPI LCD Backpack](https://learn.adafruit.com/i2c-spi-lcd-backpack.md)
- [RGB LCD Shield](https://learn.adafruit.com/rgb-lcd-shield.md)
- [Introducing Trinket](https://learn.adafruit.com/introducing-trinket.md)
- [Adafruit DS2482S-800 8 Channel I2C to 1-Wire Bus Adapter](https://learn.adafruit.com/adafruit-ds2482s-800-8-channel-i2c-to-1-wire-bus-adapter.md)
- [Severence-Inspired Lumon Bluetooth Speaker](https://learn.adafruit.com/bluetooth-speaker.md)
- [Mouse and Keyboard Control Using TinyUSB and BLE](https://learn.adafruit.com/mouse-and-keyboard-control-using-tinyusb-and-ble.md)
- [PicoDVI Arduino Library: Video Out for RP2040 Boards](https://learn.adafruit.com/picodvi-arduino-library-video-out-for-rp2040-boards.md)
- [Adafruit QT Py ESP32-S3](https://learn.adafruit.com/adafruit-qt-py-esp32-s3.md)
- [Introducing ItsyBitsy 32u4](https://learn.adafruit.com/introducting-itsy-bitsy-32u4.md)
- [ItsyBitsy ESP32 wFL case](https://learn.adafruit.com/itsybitsy-esp32-wfl-case.md)
- [Adafruit STEMMA Reflective Photo Interrupt Sensor](https://learn.adafruit.com/adafruit-stemma-reflective-photo-interrupt-sensor.md)
- [Computer Space Mini Arcade](https://learn.adafruit.com/computer-space-mini-arcade.md)
- [WiFi Weather Station](https://learn.adafruit.com/wifi-weather-station-arduino-cc3000.md)
