Part 1 - Building a data logger.

 

"Dad, can we build a foundry?" my son asked, Who wouldn't be captivated by the allure of fire and molten metal? This is how this project started. We collected aluminum cans, purchased materials and mixed plaster. Our foundry consists of a steal bucket with an insulating layer of sand and plaster. The interior is lined with refractory cement to prevent cracking and a lid to keep the heat inside. The source of energy is coal and we use a hair dryer to provide forced air via a steel pipe placed into a hole in the side.


In our first few firings we easily melted aluminum and lead. We later attempted to melt copper but with a melting point of 1984 degF, we were not successful. How close did we get we wondered? As someone who has been working with OSIsoft PI and real-time data for many years I found it a bit unsettling not knowing. There were many unanswered questions. What was our average operating temperature, our max and min temperatures, and how much did our temperatures fluctuate? These are questions that high frequency, real time data easily provides the answers too.

We purchased online an Arduino Uno and MAX6675 thermocouple. I’ve owned a Raspberry PI for several years. It came as a kit that included a breadboard, resistors and a few LEDs. I did a bit of research to find an Arduino circuit drawing and the code to test the MAX6675. After several iterations of an Arduino program for the MAX6675, I had temperature readings coming into the Arduino serial monitor. The controller was programmed to send a temperature reading every two seconds. This was awesome, well, until it wasn’t. The data continuously inched to the top of the serial monitor then disappeared forever never to be analyzed.

I wanted to capture this data and store it to a text file so I wrote a .NET console application (see code below) to read the serial data from the Arduino coming into the USB port of my Windows laptop. As each value was read, it was time stamped and sent to a file formatted as comma separated values (CSV). At this point I was done until I realized that having a laptop outside in the hazardous conditions the foundry created was a better use case for the Raspberry PI.

// C# Program to read serial port and write to text file
using System;
using System.Text;
using System.IO.Ports;
using System.IO;

namespace SerialPort2Textfile
{
    class Program
    {
        static void Main(string[] args)
        {
            //Make sure that no other application (arduino monitor) 
   //are not reading data from Port 3
            string WORKINGDIR = Directory.GetCurrentDirectory();
            string OUTPUTFILE = WORKINGDIR + "\\" + "TemperatureData.csv";
            StreamWriter fs = new StreamWriter(OUTPUTFILE, true);
            fs.WriteLine("TIMESTAMP,VALUE");
            fs.Close();

            SerialPort serialPort = new SerialPort("COM3");

            serialPort.BaudRate = 9600;
            serialPort.Parity = Parity.None;
            serialPort.StopBits = StopBits.One;
            serialPort.DataBits = 8;
            serialPort.Handshake = Handshake.None;
            serialPort.RtsEnable = true;

            serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

            serialPort.Open();

            Console.WriteLine("Press any key to end");
            Console.WriteLine();
            Console.ReadKey();
            serialPort.Close();
        }

        private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;

            //Open file stream
            string WORKINGDIR = Directory.GetCurrentDirectory();
            string OUTPUTFILE = WORKINGDIR + "\\" + "TemperatureData.csv";
            StreamWriter fs = new StreamWriter(OUTPUTFILE, true);

            //string indata = sp.ReadExisting();
            string indata = sp.ReadLine();
            string curTime = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString();

            fs.Write(curTime + "," + indata);  // write to file
            Console.WriteLine(curTime + "," + indata);  //write to console

            fs.Close();
        }
    }
}


Output from the Console Application

The Raspberry PI is much smaller and more expendable than a laptop. My plan was to put the Arduino and Raspberry PI in a shoebox (its case) with no other peripherals. In this use case the Python script needs to start automatically on startup when the Raspberry PI was plugged in outside. This required a one line change to the Raspberry PI boot config file. This was a perfect example to demonstrate to my son how devices are created, assembled and packaged. Below is the Python 2 script to read the USB port and log the data to a text file.

# Python2 script to read serial port (usb)

import serial
import datetime
import time

baudrate = 9600
portaddr = "/dev/ttyACM0"
filename = "temperatureData.txt" # output file
filemode = 'a'   #append


text_file = open(filename,filemode)
text_file.write("Timestamp,value\r")

ser = serial.Serial(portaddr,baudrate)

# read and discard first line of data
x=ser.readline() # first line of data is not complete

while 1:
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
x=ser.readline()
print(st + "," + x)  # print to screen
text_file.write(st + "," + x)
text_file.flush()

text_file.close()
ser.close

 

One sensor is providing values to a controller and is managed by a computer. How hard would this be to control something based on temperature readings? As it turns out, this is what the Arduino and Raspberry PI do well. The Arduino logic is easy to learn and implement. In a control system you may open a valve or turn on a motor based on sensor values. I don't have valves or motors but I do have LEDs. The Arduino web site has a nice tutorial on Arduino logic and how to assign pins as input or output and to turn them on and off. I put together the following program to provide LED indications as the foundry reached different temperatures levels. The LEDs are simply placeholders for what could be a switch to oscillate the hair dryer from high to low to maintain an optimum temperature range in the foundry to reduce coal usage.Below is the final code used on the Arduino.

 

// Final Arduino script for foundry controller
#include <max6675.h>

int thermoDO = 4;
int thermoCS = 5;
int thermoCLK = 6;

int ledPin = 13;    // power on
int ledPinMin = 8;  // led when Min temp reached
int ledPinMax = 12; // led when Max temp reached

float curReading = 32;  // current reading of thermocouple

MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);
int vccPin = 3;
int gndPin = 2;
  
void setup() {
  pinMode(ledPin, OUTPUT); // set pin 13 as an output for led
  pinMode(ledPinMin, OUTPUT); // set pin 8 as an output for led
  pinMode(ledPinMax, OUTPUT); // set pin 12 as an output for led
  
  Serial.begin(9600);

  // use Arduino pins 
  pinMode(vccPin, OUTPUT); 
  digitalWrite(vccPin, HIGH);
  pinMode(gndPin, OUTPUT); 
  digitalWrite(gndPin, LOW);
  
  // wait for MAX chip to stabilize
  delay(2000);
}

void loop() {
  // Turn on LED as temperature climbs

   digitalWrite(ledPin, HIGH); // turn on power led
    
   Serial.println(thermocouple.readFahrenheit());
   delay(2000);

   curReading = thermocouple.readFahrenheit();

    if (curReading >= 1500) 
    {
      digitalWrite(ledPinMax, HIGH); // turn on red led
      digitalWrite(ledPinMin, HIGH); // turn on yellow led
    }
    else if (curReading >= 1000)
    {
      digitalWrite(ledPinMax, HIGH); // turn on red led
    }
    else if (curReading >= 500)
    {
      digitalWrite(ledPinMin, HIGH); // turn on yellow led
    }
    else 
    {
      digitalWrite(ledPinMax, LOW); // turn off led
      digitalWrite(ledPinMin, LOW); // turn off led
    }
   
}


After operating the foundry with the thermocouple we learned that our max temperature was 1875 deg F (the device max). The operating temperature once everything was warmed up was between 1400 and 1600 deg F and we run the blower on high a majority of the time. This is more heat than is necessary for working with aluminum and an energy cost savings may be realized if we manage the blower speed with our mini DCS.

OSIsoft PI is a great tool to collect, store and visualize real-time data. In Part 2 We graduate from writing data to text files to pushing the values from the Raspberry PI to OSIsoft PI using the Web API (rPI to PI) and join the Internet of Things.

 

Part 2 - Raspberry PI to PI using the PI Web API

 

As a follow up, we were able to melt copper by switching from charcoal to black smith coal. Below is a picture of the foundry and a copper ingot.

foundry.pngcopper.png