TeensyPi Networked Temperature Controller

Homebrew Talk - Beer, Wine, Mead, & Cider Brewing Discussion Forum

Help Support Homebrew Talk - Beer, Wine, Mead, & Cider Brewing Discussion Forum:

This site may earn a commission from merchant affiliate links, including eBay, Amazon, and others.
redbenn said:
Had a similar issue this morning as I did previously where my sensors stopped updating. Happened after having it unplugged for a day. The LED on the Teensy board was pretty dull, I am wondering if it was trying to process too much after reboot?

I am reloading everything again, I don't think it is the RasPi, though I am reloading that as well. When plugged the Teensy in to external power to reload, the LED was still dim... I reloaded the Teensy and it rebooted, the LED went to bright.

Is there a way to access the Teensy when I SSH into the RasPi?

I use the Teeny 3.0 D13 LED to show the status of the D8 serial flow line. When the Teensy 3.0 is interrogating the chips, it disables serial communication, and the LED goes out. Since the Teensy 3.0 spends most of its time monitoring the chips, the LED typically very dim, with intermittent flashes when processing a serial command.

To see anything on the Teensy 3.0, you'll have to plug a USB cable between your computer and the USB port on the Teensy 3.0, fire up the IDE, enable the debug defines in the .ino code, load the code into the Teensy 3.0 board, and enable the IDE's serial monitor.

The web updates are done via Javascript, you might try firing up your brower's javascript debugger, and look for problems there.
 
I use the Teeny 3.0 D13 LED to show the status of the D8 serial flow line. When the Teensy 3.0 is interrogating the chips, it disables serial communication, and the LED goes out. Since the Teensy 3.0 spends most of its time monitoring the chips, the LED typically very dim, with intermittent flashes when processing a serial command.

To see anything on the Teensy 3.0, you'll have to plug a USB cable between your computer and the USB port on the Teensy 3.0, fire up the IDE, enable the debug defines in the .ino code, load the code into the Teensy 3.0 board, and enable the IDE's serial monitor.

The web updates are done via Javascript, you might try firing up your brower's javascript debugger, and look for problems there.

My Teensy spends most of it's time flashing....fairly quickly.

EDIT: I still seem to only be able to get good data on 1 of the 2 sensors connected. The "bad" sensor reads 31. In reviewing the code it looks like this might be a result of the variable "raw" not having a value so in the temp conversion equation only the + 31 portion is being displayed. I have checked all cable pin orientations and have tried each sensor individually to insure they are functional.
 
My Teensy spends most of it's time flashing....fairly quickly.

EDIT: I still seem to only be able to get good data on 1 of the 2 sensors connected. The "bad" sensor reads 31. In reviewing the code it looks like this might be a result of the variable "raw" not having a value so in the temp conversion equation only the + 31 portion is being displayed. I have checked all cable pin orientations and have tried each sensor individually to insure they are functional.

You may have a chip whose resolution timing is outside of the norm. Try increasing the value of tempReadDelay in the Teensy 3.0 code to a larger value, say 250. If that corrects the problem, then start reducing the value until the result again becomes unstable, then bump it up to the last usable value.
 
You may have a chip whose resolution timing is outside of the norm. Try increasing the value of tempReadDelay in the Teensy 3.0 code to a larger value, say 250. If that corrects the problem, then start reducing the value until the result again becomes unstable, then bump it up to the last usable value.

Excellent, I will try that.
 
I picked up this relay board to control 3 solenoids and 3 heat pads, SainSmart 8-Channel 5V Relay Module for Arduino DSP AVR PIC ARM.

Relay came today, I hooked it up to 2 of my switches which were in an action. Everything worked great, when the switch activated, it activated the relay.

Also got COSM working with a PHP cronjob.

Waiting on my heat tape and solenoids, then going to test out the actions to see how they dial in temp, and if I may need to try out the PID library.

Thanks for the help so far.
 
Last edited by a moderator:
Relay came today, I hooked it up to 2 of my switches which were in an action. Everything worked great, when the switch activated, it activated the relay.

Also got COSM working with a PHP cronjob.

Waiting on my heat tape and solenoids, then going to test out the actions to see how they dial in temp, and if I may need to try out the PID library.

Thanks for the help so far.

I have that exact board, now I just need a few switches to put it in action
 
Relay came today, I hooked it up to 2 of my switches which were in an action. Everything worked great, when the switch activated, it activated the relay.

Also got COSM working with a PHP cronjob.

Waiting on my heat tape and solenoids, then going to test out the actions to see how they dial in temp, and if I may need to try out the PID library.

Thanks for the help so far.

Don't forget to share the code...
 
All sensors working!! I ended up playing around with the location of the pull up resistor. Maybe with my long connection lead I need to experiment with a different value.

In any case is working and I have dynamic DNS setup also.

Thanks for putting up with all my questions and for the outstanding work. Maybe I'll play around with those Steel Chrome gauges now :)
 
One of the changes I did was install VSFTPD so I could FTP into the TeensyPi. This allowed me to access the htdocs easier.

I did this as [email protected], as that is the owner ove the /var/www folder. I got the instructions from here.

Code:
Type in "sudo apt-get install vsftpd" and hit Return / Enter
Now type in "sudo nano /etc/vsftpd.conf" and hit Return / Enter

Search through the file and change the following lines:
anonymous_enable=YES Change To anonymous_enable=NO
#local_enable=YES Change To local_enable=YES
#write_enable=YES Change To write_enable=YES

Also, add a line to the bottom of the file:
force_dot_files=YES

Save the file.

Now restart the FTP server with "sudo servce vsftpd restart"
 
Next was to create an account on COSM which will log the data. I followed this guide from adafruit for the most part.

Once you have an account, click the blue button to set up a feed:
cosm-add-feed.gif


Select Arduino, and name it, tag it, etc.

cosm-something-else.gif


You will need the API Key from the code generated and your Feed ID for later.
 
This is where I diverged from the Adafruit tutorial, as I know PHP so this was easier for me...

You will need the PHP-Curl library installed to post/get from COSM. You may have to install this if it is not already on the Raspberry Pi. To check to see if it is installed, create a new PHP file named phpinfo.php in your /var/www/htdocs folder with the text:
Code:
phpinfo()

Then open the file in your web browser and go to teensypi.local/phpinfo.php. Search for "curl" in the text, if nothing comes up, then you will have to install the library.

From the command line, type in:
Code:
sudo apt-get install php5-curl
This will update some of the php5 libraries that were installed, and now install curl. Once it is finished installing, restart the webserver
Code:
sudo service apache2 restart
 
I added a table to the MySQL database called cosm.

Log into phpmyadmin at http://teensypi.local/phpmyadmin/. Go to the TeensyPi database.

Click on the SQL link and paste the following code:
Code:
CREATE TABLE IF NOT EXISTS `cosm` (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `chipid` varchar(50) NOT NULL,
  `cosmfeedid` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=18 ;

Click GO, this will create your cosm table. I have this to check if a datastream for a chip has already been created.
 
Next download the COSM (formally known as Pachube) PHP library from here: https://github.com/MunGell/PachubeAPI. Then upload the PachubeAPI.php file to your /var/www/htdocs directory.

This will create functions that make it easy to get/post data from/to COSM.

Next create a new PHP file in your /var/www/htdocs directory called cosm.php.

This will be the file we will use to post our data to COSM.

Most of the code is taken from updateStatus.php to get the data from the chips.

Here is the code for cosm.php
Code:
<?php


include('PachubeAPI.php');
$pachube = new PachubeAPI("YOUR_API_KEY"); // replace with your API KEY
      $feed = YOUR_FEED_ID;  //replace with your Feed ID
      
      $user = "USER_NAME";  //replace with your username


  include_once("makeASocket.php"); //allows us to read the chips
  include_once("accessDatabase.php"); //accesses the MySQL database
  $tempStr="";
  $switchStr="";
  $unusedStr="";
  $switchjStr="";
  

  $newSocket = makeASocket($service_port, $address);
  $in = $getAllStatus."\n";
  socket_write($newSocket, $in, strlen($in));
  $chipX = socket_read($newSocket, $socBufSize);
  socket_close($newSocket);

  $status=explode(",", $chipX);
  $count = count($status);

// Query to get chip name and id. This will create the elements $cosmid and $temp for the COSM API
  
  for($x=0,$y=0,$z=0;$x<$count;$x++)
  {   
    $query = "select * from chipNames where id='".$x."'";
    $result = mysqli_query($link, $query);
    $row = mysqli_fetch_row($result);
    mysqli_free_result($result);
    if(is_numeric($status[$x]) === TRUE)
    {
      $query2 = "SELECT * FROM cosm where chipid = '". $row[1] . "'";
      
      $result2 = mysqli_query($link,$query2);
      $row2 = mysqli_fetch_row($result2);
      mysqli_free_result($result2);
      $cosmid = $row2[2];
      

      
      $temp = $status[$x];
//debug text
      //echo "<br><br>" . $cosmid. ": "; 
      //echo $temp;
//end debug text
    
//call the $pachube function from PachubeAPI.php, and update the data stream
      $pachube->updateDatastream("csv", $feed, $cosmid, $temp);
    }
}
?>

If you would like to track your switches as well, add the following code after this line:
Code:
//call the $pachube function from PachubeAPI.php, and update the data stream
      $pachube->updateDatastream("csv", $feed, $cosmid, $temp);
    }

Code:
else if((($trimStr = trim($status[$x])) === "N") || (($trimStr = trim($status[$x])) === "F") ){
$query2 = "SELECT * FROM cosm where chipid = '". $row[1] . "'";

$result2 = mysqli_query($link,$query2);
$row2 = mysqli_fetch_row($result2);
mysqli_free_result($result2);
$cosmid = $row2[2];

if ($status[$x]=="N") {$temp = 1;} else {$temp = 0;}


//echo "<br><br>" . $cosmid. ": ";
//echo $temp;
//$pachube->updateDatastream("csv", $feed, $cosmid, $temp);
$pachube->updateDatastream("csv", $feed, $cosmid, $temp);
}
 
You will also have to modify updateNames.php. This will add the ability to create COSM datafeeds when a new chip is named. I set it up to tie the chip address to the feed as opposed to the chip ID since they will move around IDs, but the address will stay the same.

First add references to the PachubeAPI, insert this code in between the php tags near the:

Code:
  <?php 
      include_once("makeASocket.php");
      include_once("accessDatabase.php");
      include_once("header.html");
      $h2Header = "<font color=\"blue\">Update Names</font>";
      $tempAddrStr = "";
      $switchAddrStr = ""; 
      

     //INSERT PACHUBE CODE HERE
    ?>

Code:
      include("PachubeAPI.php"); 
      $pachube = new PachubeAPI("YOUR_API_KEY");
      $feed = YOUR_FEED_ID;
      $user = "YOUR_USERNAME";


Next add a query that will check to see if the chip is a DS18B20. Then it checks if there is already a COSM feed create, if not it will create the feed.

Insert the code after this block of code updating the chip names:
Code:
 $chipAddress = $_POST["address$updateCnt"];
                $result = mysqli_query($link,$query);
                $escapedName = mysqli_real_escape_string ($link , $_POST["name$updateCnt"]);
                $query = "update chipNames set address='".$chipAddress."', name='".$escapedName."' where id='".$updateCnt."'";
                $result = mysqli_query($link,$query);
/*
                if($result === FALSE)
                {
                  echo "query failed";
                }else{
                  echo "query success";
                }
                echo "<br />result = ".$result."<br />";
*/

Insert this code:
Code:
if(substr($chipAddress,0,4)=='0x28') {
                
                  $query2 = "SELECT * FROM cosm where chipid = '" . $chipAddress . "'";
                  $result2 = mysqli_query($link,$query2);
                  if(mysqli_num_rows($result2)==0){
                    $data = $escapedName . "," . (int)hexdec(substr($chipAddress,-4));
                     $feedname =  preg_replace('/\s+/', '', $escapedName);
                    $data = preg_replace('/\s+/', '', $escapedName) . ",0";
                    $pachube->createDatastream("csv", $feed, $data);
                    
                    $query3 = "INSERT INTO cosm (id, chipid, cosmfeedid) VALUES (NULL, '" . $chipAddress . "', '" . $feedname . "')";
                    $result3 = mysqli_query($link,$query3);

                    $h3Header= $h3Header . "<br><br>COSM datastream created for ". $data;
                    
                    } else
                    {
                      $h3Header= $h3Header . "<br>COSM datastream already exists for " . $escapedName;
                    }

If you would like to track your switches as well, delete the first line:
Code:
if(substr($chipAddress,0,4)=='0x28') {
and also the last } in this section to get this code:
Code:
$query2 = "SELECT * FROM cosm where chipid = '" . $chipAddress . "'";
                  $result2 = mysqli_query($link,$query2);
                  if(mysqli_num_rows($result2)==0){
                    $data = $escapedName . "," . (int)hexdec(substr($chipAddress,-4));
                     $feedname =  preg_replace('/\s+/', '', $escapedName);
                    $data = preg_replace('/\s+/', '', $escapedName) . ",0";
                    $pachube->createDatastream("csv", $feed, $data);
                    
                    $query3 = "INSERT INTO cosm (id, chipid, cosmfeedid) VALUES (NULL, '" . $chipAddress . "', '" . $feedname . "')";
                    $result3 = mysqli_query($link,$query3);

                    $h3Header= $h3Header . "<br><br>COSM datastream created for ". $data;
                    
                    } else
                    {
                      $h3Header= $h3Header . "<br>COSM datastream already exists for " . $escapedName;

I also added the $h3Header to show the status was updated.

In the next block of code here, you need to add the $h3Header below the $h2Header

Code:
<tr>
              <td align=\"center\" colspan=\"2\" border=\"2\">
                <h2>".$h2Header."</h2>
                <h3>".$h3Header."</h3>
              </td>
              </tr>


That should be it, next up we will create the cronjob to run every 5 minutes to update the COSM feeds.
 
One of the changes I did was install VSFTPD so I could FTP into the TeensyPi. This allowed me to access the htdocs easier.

I did this as [email protected], as that is the owner ove the /var/www folder. I got the instructions from here.

Code:
Type in "sudo apt-get install vsftpd" and hit Return / Enter
Now type in "sudo nano /etc/vsftpd.conf" and hit Return / Enter

Search through the file and change the following lines:
anonymous_enable=YES Change To anonymous_enable=NO
#local_enable=YES Change To local_enable=YES
#write_enable=YES Change To write_enable=YES

Also, add a line to the bottom of the file:
force_dot_files=YES

Save the file.

Now restart the FTP server with "sudo servce vsftpd restart"

Pretty sure that sftp is already ensbled in the RPi, as I use Filezilla to upload and download files to/from the TeensyPi all the time.

My development machine is running CentOS 6.3, and I can connect directly to files on the TeensyPi with the "Connect To Server" option on the "Places" menu.
 
Pretty sure that sftp is already ensbled in the RPi, as I use Filezilla to upload and download files to/from the TeensyPi all the time.

My development machine is running CentOS 6.3, and I can connect directly to files on the TeensyPi with the "Connect To Server" option on the "Places" menu.

Ahh, could have been because I was trying to connect via FTP instead of directly mounting the TeensyPi. I use Transmit on OS X Mountain Lion.
 
Ahh, could have been because I was trying to connect via FTP instead of directly mounting the TeensyPi. I use Transmit on OS X Mountain Lion.

OK. I've got an old 17" MacBook Pro running Snow Leopard, but haven't used it lately. Might be time to fire it up and see what works.
 
To create the cronjob to update the cosm feed, we need to update crontab with the timing to run the job, the location of PHP, and the location of our cosm.php file we want to run.

For me PHP was located at /usr/bin/php. You can verify yours by typing find php from the command line.

To access crontab, from the command line type crontab -e

Scroll all the way to the bottom and enter:
Code:
*/5 * * * * /usr/bin/php /var/www/htdocs/cosm.php
Then exit and save.

The */5 is telling the cronjob to run every 5 minutes. You could change that to something else if you wanted it to run more/less frequently.

If you click on your feed in COSM, then click the gear and go to debug, you can monitor the API calls to see if your cronjob is running successfully.

2mCupSA.png


This shows my requests every 5 minutes

8I6jpY2.png
 
I noticed that you're monitoring just the temp sensors. Any reason not to have the option to monitor switch status as well? I'm assuming that you would just have a simple on/off chart.
 
I noticed that you're monitoring just the temp sensors. Any reason not to have the option to monitor switch status as well? I'm assuming that you would just have a simple on/off chart.

Yes, that could be done as well. We wouldn't want the 0x28 filter for the MySQL table/cosm feed creation. We could then send a 0 or 1 to cosm to track if the switch is on. I will look into adding that later tonight.
 
Nicely done redbenn.

From the File Browser in Linux I can sftp in by entering:
sftp://teensypi@TEENSY_IP:22/initial/dir/you/want
In the window, you should be prompted for your password...it's nice because you can open the remote files locally for editing this way.

I have setup dynamic DNS so I can play from work too :)

EDIT: There is a nested IF in one of your blocks of code that I think leaves the block one curly brace short

Code:
if(substr($chipAddress,0,4)=='0x28') {
                
                  $query2 = "SELECT * FROM cosm where address = '" . $chipAddress . "'";
                  $result2 = mysqli_query($link,$query2);
                  if(mysqli_num_rows($result2)==0){
                    $data = $escapedName . "," . (int)hexdec(substr($chipAddress,-4));
                     $feedname =  preg_replace('/\s+/', '', $escapedName);
                    $data = preg_replace('/\s+/', '', $escapedName) . ",0";
                    $pachube->createDatastream("csv", $feed, $data);
                    
                    $query3 = "INSERT INTO cosm (id, chipid, cosmfeedid) VALUES (NULL, '" . $chipAddress . "', '" . $feedname . "')";
                    $result3 = mysqli_query($link,$query3);

                    $h3Header= $h3Header . "<br><br>COSM datastream created for ". $data;
                    
                    } else
                    {
                      $h3Header= $h3Header . "<br>COSM datastream already exists for " . $escapedName;
                    }
 [COLOR="Red"]}[/COLOR]
 
Have two problems on the COSM, probably related:
1) The sql statement inserts the same sensors into the cosm table that already exist. The code appears check for this so I'm not sure what is causing it.
2) There are no results being sent to COSM.
 
Have two problems on the COSM, probably related:
1) The sql statement inserts the same sensors into the cosm table that already exist. The code appears check for this so I'm not sure what is causing it.
Is it inserting them the first time, then if you update the names it will insert the same record again? Same address in the ChipID column in the cosm table?

2) There are no results being sent to COSM.
Were the cosm feeds created when you updated the names? If so, does anything post to cosm if you access cosm.php directly from your web browser?
 
Is it inserting them the first time, then if you update the names it will insert the same record again? Same address in the ChipID column in the cosm table?

Yes, I have 2 sensors and it will insert both into the cosm table each time I submit an update even if I don't change the name (cosmfeedid).

Were the cosm feeds created when you updated the names? If so, does anything post to cosm if you access cosm.php directly from your web browser?

I can confirm the cosm.php executes by uncommenting your debug lines, i.e. the cosm page shows my cosmfeedid and the temp. If I comment out the debug lines and refresh cosm.php it just displays a blank page (I assume that is correct) but nothing gets posted to the COSM site.
 
Yes, I have 2 sensors and it will insert both into the cosm table each time I submit an update even if I don't change the name (cosmfeedid).

Ah, found the problem... on the updateNames.php this line
Code:
if(substr($chipAddress,0,4)=='0x28') {

                  $query2 = "SELECT * FROM cosm where address = '" . $chipAddress . "'";
Should be:
Code:
if(substr($chipAddress,0,4)=='0x28') {

                  $query2 = "SELECT * FROM cosm where chipid = '" . $chipAddress . "'";


It should look for the chipid field not address. I have updated the guides to reflect this. I would delete your cosm datastreams (go into your feed, then click edit, remove the streams and click save), and delete the table records and try again w/ update names.
 
Ah, found the problem... on the updateNames.php this line
Code:
if(substr($chipAddress,0,4)=='0x28') {

                  $query2 = "SELECT * FROM cosm where address = '" . $chipAddress . "'";
Should be:
Code:
if(substr($chipAddress,0,4)=='0x28') {

                  $query2 = "SELECT * FROM cosm where chipid = '" . $chipAddress . "'";


It should look for the chipid field not address. I have updated the guides to reflect this. I would delete your cosm datastreams (go into your feed, then click edit, remove the streams and click save), and delete the table records and try again w/ update names.

Alright, that fixed the database duplication problem, still am not seeing a COSM feed...I'll keep working it
 
Alright, that fixed the database duplication problem, still am not seeing a COSM feed...I'll keep working it

try this code on the update
Code:
$pachube->_debugStatus($pachube->updateDatastream("csv", $feed, $cosmid, $temp));

instead of
Code:
$pachube->updateDatastream("csv", $feed, $cosmid, $temp);

This will run a debug on the cosm update.
 
try this code on the update
Code:
$pachube->_debugStatus($pachube->updateDatastream("csv", $feed, $cosmid, $temp));

instead of
Code:
$pachube->updateDatastream("csv", $feed, $cosmid, $temp);

This will run a debug on the cosm update.

The results are:
Access forbidden!Access forbidden!

EDIT: the owner/group for cosm and PachubeAPI is teensypi/teensypi, does that need to be www-data in both cases?
 
Almost :) Now I get "Feed ID or some other parameter does not exist." I updated the Feed ID in both files for the new key pair so I'll see if I missed something else

EDIT: I am seeing feeds in the COSM API Debugger. The Response Body contains "I'm sorry we are unable to find the feed you are looking for."
 
Almost :) Now I get "Feed ID or some other parameter does not exist." I updated the Feed ID in both files for the new key pair so I'll see if I missed something else

EDIT: I am seeing feeds in the COSM API Debugger. The Response Body contains "I'm sorry we are unable to find the feed you are looking for."

The feed id is just a numerical value, make sure you don't have quotes around it in the code.
 
If I wanted to test out using the Arduino PID library in place of the actions, would I need to modify void softSerialProcess() and void updateChipStatus(int x)?
 
If I wanted to test out using the Arduino PID library in place of the actions, would I need to modify void softSerialProcess() and void updateChipStatus(int x)?

Depends on how complicated you want to make it. Looking at the Relay Output Example, it seems to me that you could put the code in the loop() into a function that's called in the Teensy 3.0 loop() replacing the
Code:
Input = analogRead(0);
with
Code:
Input = (double) chip[x].status;

and

Code:
if(Output > now - windowStartTime) digitalWrite(RelayPin,HIGH);
  else digitalWrite(RelayPin,LOW);

with

Code:
if(Output > now - windowStartTime) setSwitchState(x,ds2406PIOAoff);
  else setSwitchState(x,ds2406PIOAon);

Just as a test you could hard code the values for the thermometer and switch, put all of the setup in the setup() and let it rip.
 
While redbenn's version of graphing software using COSM works just fine, I prefer to keep my info in-house.

To that end, I created a database table to track enabled actions and display the output on a local web page.

First I created a new table in phpmyadmin for the teensypi database:

Code:
CREATE TABLE IF NOT EXISTS `actionGraph` (
  `id` int(11) NOT NULL,
  `time` bigint(20) NOT NULL,
  `temp` int(11) NOT NULL,
  `tcTemp` int(11) NOT NULL,
  `tcSwitch` enum('ON','OFF','NONE') NOT NULL,
  `thTemp` int(11) NOT NULL,
  `thSwitch` enum('ON','OFF','NONE') NOT NULL,
  KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

and installed GnuPlot

Code:
sudo apt-get install gnuplot

Then I created the files:
graphActions.php
plotData.php

updated:
updateActionStatusWithMySQL.php

and downloaded:
PHP_GnuPlot.php

All of the code is available at my github directory

I then added a cron entry:
Code:
* * * * * /usr/bin/php /var/www/htdocs/graphActions.php

To update the action status to the MySQL table once a minute.

Now when I go to my Action Status page:
Graph01.png


You will see a "GRAPH" button. Clicking on that will greate a graph:
Graph02.png


That will show you the temperature and setpoints. If you change your trigger points, the graph will reflect that. I plan to add some viewing granularity, but I think that's enough for today.
 
Back
Top