Instructables

Interface Arduino to MySQL using Python

Featured
Picture of Interface Arduino to MySQL using Python
Here's a brief tutorial that should get you up and running interfacing your Adruino with a MySQL database. For the sake of this tutorial, I am assuming you know how to set up and use MySQL. This tutorial does not require much Python experience, but you will be required to install two Python libraries for this project.

Glad we're on the same page, let's get to it!
 
Remove these adsRemove these ads by Signing Up

Step 1: Downloading and Installing the Python Libraries

Picture of Downloading and Installing the Python Libraries
First I'll point you in the right direction for installing the required Python libraries. First you'll need to install the pySerial library. Simply put, the pySerial library allows your Python script to talk with the serial port in which the Arduino is connected. I.e. you can kind of think of it as a stream connecting the Arduino code to the Python code (insert other silly analogies here).

1. You can download the pySerial library here:
https://pypi.python.org/pypi/pyserial

2. For mac or linux users, download the file and extract it. Open terminal and cd into the extracted folder and run the following command:

python setup.py install

This will install the pySerial package. (screen shot below)

Next, we will install the library to allow Python to talk with MySQL called MySQLdb.
I just want to note, this step can be very annoying, but very rewarding once completed. I have included a guide for you to follow, but I recommend you have MySQL, python, and XCode(or the latest GCC) installed before you try and install MySQLdb.

1. download the library from source forge:
http://sourceforge.net/projects/mysql-python/?source=dlp

2. If you're lucky enough, you should just be able to download it, extract it, open Terminal, cd into the folder and run python setup.py install, just as you did before. If this works, you're awesome and you should awesome, but if not, this guide should help. Note, I had to do step 6 before step 3.

http://stackoverflow.com/questions/1448429/how-to-install-mysqldb-python-data-access-library-to-mysql-on-mac-os-x

florianagr12 hours ago

Hi,

your tutorial is great!!!

But i still have a problem.

My Sql database is empty.

I´m getting no error, only a warning:"Warning: Out of range value for column 'tempC' at row 1"

I only use one sensor: temerature sensor (DS18S20).

In my python code i only delete the humidity data

try:

cursor.execute("INSERT INTO weatherData (tempC) VALUE (%s)", (pieces[0]))

dbConn.commit() #commit the insert

cursor.close() #close the cursor

Nothing is happening in my Database.

What can be the reason.

Thanks for helping me

armorer2438 days ago

A little help, if you would be so kind. I am a python noob so please bear with me. This script seems to insert the data once and then exit. Is there a way for this to run as a loop over and over, inserting data every time it receives a new string?

mangopeach (author)  armorer2438 days ago

Hey there,

I haven't testing this, so just a warning, but a straightforward solution would be to put the the insertion in a loop and do an insert each time some data was read. Something along the lines of (just restart the loop if you don't have any input, so you don't try and insert null values into your database):

while True:

try:

data = arduino.readline() #read the data from the arduino

if not data.strip(): #did we get an empty line?

#could put a sleep(1) or something if you wanted to wait before trying to read again

continue #start the loop over

pieces = data.split("\t") #split the data by the tab

#Here we are going to insert the data into the Database

try:

cursor.execute("INSERT INTO weatherData (humidity,tempC) VALUES (%s,%s)", (pieces[0],pieces[1]))

dbConn.commit() #commit the insert

cursor.close() #close the cursor

except MySQLdb.IntegrityError:

print "failed to insert data"

finally:

cursor.close() #close just incase it failed

except:

print "Failed to get data from Arduino!"

Arizno1 month ago

There is a site that make the MySqldb install a breeze. Literally a few button clicks.

http://www.codegood.com/

armorer2431 month ago
Very useful! I set up my smoker to send it's data via wireless to my home server. Then using your 'ible it is logging it's data to a db. Last part is my internal webpage with live graphing I can access at work via VPN. I must say your tutorial gave me the exact starting point I needed to finish the project up. Thank you very much!
hard_candy3 months ago

I have to say, I find this tutorial very cool, but I'm having a couple of issues, hope you can help me.

I did everything you said with the difference that I'm using a RFID card reader to send data. The problem seems to be that my Python script never receives this data. I have tryed with a very simple code to send something from the Arduino to Python and I discovered that it just keeps looking for data (specificaly this line):

data = arduino.readline() #read the data from the arduino

but never goes forward and never prints the excepcion. Everything what is printed in the terminal is:

Trying... /dev/ttyXXX

And that is it. I don't know what is that due to. Could you help me?

Regards,
Estefanía

Ok, I found the problem. This is what I saw in the documentation (http://pyserial.sourceforge.net/shortintro.html#opening-serial-ports):

>>> ser = serial.Serial('/dev/ttyS1', 19200, timeout=1)
>>> x = ser.read() # read one byte
>>> s = ser.read(10) # read up to ten bytes (timeout)
>>> line = ser.readline() # read a '\n' terminated line
>>> ser.close()

as one can see, readline reads a '\n' terminated line and I was printing with Serial.print(val); then I changed it for Serial.println(val); and it worked :)

Regards,

Estefanía

alochmandy3 months ago
Thank's man. This looks like a real good solution. Can't wait to try it.
breather5 months ago
I don't understand the following point:
device = '/dev/tty.usbmodem1411' #this will have to be changed to the serial port you are using

I know what's mean /dev/ttyX on Linux but I don't understand in this point.
how can I know my serial port?

Thanks
sspence11 months ago
Why not run the mysql connector on the Arduino. No intermediary needed.

http://arduinotronics.blogspot.com/2013/04/introducing-mysql-connectorarduino.html
breather sspence5 months ago
That's an other possibility but I'm working with Arduino YUN and all of its possibilities so I'm really interesting on the option of this post.

Also the cost of a Arduino Yun is lower than a Wifi shield + Arduino board.
Hey do you know if there is any chance to use a wifiShield instead of EthernetShield?
Sure, no problem. TCP/IP is TCP/IP, no matter if cabled or wifi.
mangopeach (author)  sspence11 months ago
That's very cool! I hadn't come across that yet. That seems like a very good option with an ehternet shield. Thanks for the tip.
jatinbatra8 months ago
Take a bow :)
Jayefuu11 months ago
Useful! I'm using Python to interface mysql and a serial connected radio module at the moment.
Pro

Get More Out of Instructables

Already have an Account?

close

PDF Downloads
As a Pro member, you will gain access to download any Instructable in the PDF format. You also have the ability to customize your PDF download.

Upgrade to Pro today!