Collecting sensor data from arduino using python

Data collection is the first step of any machine learning or data analysis project. Data is in abundance all around us, all we need is a proper apparatus to capture and use it.

For a fun personal project, I recently wanted to analyze the temperature of a car cabin to see how and what affects the generation of heat and how distributed is it inside.

For the project I used an arduino mega board and lm35 temperature sensors. Lm35 returns an analog value to the arduino representative of the corresponding temperature. 10 such sensors were used and I needed a mechanism to record the data of the sensors into a csv file (although the process will be same for storing the data in a database too, only the tasks of the functions will change).

For achieving the task, I used python to read the data serially from arduino, and store it in a csv file. The actual process of creating and storing the data took less than 20 lines of code.

We first load into arduino the code to read the sensor values in analog and the perform a Serial.write(finalValue) to pass it onn serially to the system. Make sure the baud rate in arduino and the laptop is same. following code was used to read the values of the ten sensors and concatenate them into a single string which is then passed on serially.

The above code is quite standard analog read.

The next part of the job is to attach the arduino to a system serially and be able to read the data and store it.

In python to read the data over serial, we use the python serial module. We will also need the csv module to handle csv files and the datetime module to have the timestamp of the data recorded.

Following function is used to create a new csv file by taking the name and the column names from the user.

quite simple right?

now that the new file has been created, the next step is to be able to read the data and write the read data in the csv file along with the timestamp. The following methods are used to write to csv and read data from arduino respectively.

The lm35 temperature sensor takes a 5V input and following are the pins for output and ground.

And executing the readData method creates a nice csv file with the data received by arduino form the sensors. We can even make the collection remote which does not require to be physically present to take readings.



Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store