Showing posts with label Temperature. Show all posts
Showing posts with label Temperature. Show all posts

Friday, October 25, 2019

Naturally, Blogger Changed Something

Of course blogger changed how the blog appears ! That led to a mess of my background image tileing and messing things up in the appearance. After some messing around I managed to get it appearing somewhat reasonable, but had to change the background picture. I've used the same one for years and years now, but so be it; I can update with the times ... sort of.

I kind of like the look, and will stay with it for while, or until google gets a bug up their butt and changes things again.

Yes, I'm still alive. I haven't been blogging because I got myself involved with local politics and have been up to my ears in that effort for many months. I do get in a technical project once in a while, but haven't had the time to write them up.

I'll put them on the blog at some point, since they may be interesting to some people out there. Here's a quick list off the top of my head of the things I've been into that haven't surfaced here yet.

1. A horrible problem with my XBee network. My end devices would leave the network and not rejoin. That meant that some of the critical ones that controlled the AIR CONDITIONING didn't update the thermostats that control the temperature. Hot house or cold house depending on where it quit working. The thermostats protected me against using power during the Peak period, so the power bill didn't get out of hand, however it was painful to deal with. I have it mostly fixed, there's still one strangeness that I have to work on to get everything back to working reliably though.

2. I still have the parts for monitoring my 220V devices piled up with an enclosure, and haven't done anything else with them. They stare at me mournfully each time I walk through the garage. I'll get to them as soon as I can. To see that project's beginnings look here <link>.

3. Stumbled across a really cool phone from the crank-to-call days. I fully plan to put this thing in service. I may have to update a few parts, but maybe I can hide them inside. There's a lot of these out there, so I'm not going to worry much about the value afterwards, but I do want to keep it as original as possible. Here's some pictures of the phone; notice it has a BRASS earpiece !


It's an Australian model, but the parts are easily found to update it. This phone was updated over the years that it was in service. The crank was disconnected and the handle lost (or taken by the phone guy that did the work) the earpiece and mouthpiece elements were changed and finally the dial was added. It is really fun to play around with. I hope I can get the ringer to work; that would be great.

Might want a switch though.

3. Stupid AcuRite 5n1 weather station channel A died. Now I have to set it up for channel C since I that's the only way it will work. Sigh, don't happen to know what the frequency is for channel C would you? If you want to look at this project, it's all under 'Weather' in the list on the right side top of the page.

4. The battery life of my XBee end device temperature sensors has been a little over 5 months consistently. That's not as much as I calculated, but it's still pretty good. I'm getting tired of buying AA cells though. They're not expensive, but when you have a half dozen devices that run on three of them each, it can get annoying replacing them. I always seem to be out of the darn things.

So, I'm looking at those Li-Ion cells that sell pretty cheaply on Amazon. They seem to last forever, have close to 4 VDC output when full and are really fast to recharge. I have a bunch that I use in flashlights around the house and one installed in a sensor being tested (for months, these things take time). I suspect I'll be switching over to them on all the battery devices; they're just great since you can always have one charged up for replacement and don't have to run to Walmart because the AC crapped out.

And Etc. See, I'm still at it, just don't have the time to gather the graphs, pictures, measurements and such that it takes to make a coherent blog post about these things.

But, like the Terminator, "I'll be back."



Saturday, July 14, 2018

Thermostats, Location, Location, Location

When I was researching supercooling as a way of limiting my power bill I kept getting readings and such that just didn't make sense. One side of my house was comfortable, the other ... not so much. Sure it was the sunny side this time of year, but it has really good windows and good curtains. The only two major problem areas were a couple of windows that faced directly into the after noon sun.

I fixed those years ago with reflective insulation that I put in for the summer and (sometimes) take out for the winter. It's easy to work with and will last forever if I just give them a little attention every once in a while. I wandered around the room and noticed that the interior walls were about 2 degrees warmer than the rest of the house and there was heat getting in through the foundation.

The sun bearing down on the exposed slab foundation would heat up the concrete slab and transmit heat inside the house. That's something that might go unnoticed if I had carpeting, but the tile felt warmer as you approached the wall.

So, basically, it was like any other house on the sunny side. Why was my AC running all the time and having little impact on that room?

A little background: I have a house shaped like an "L" and two AC units. The one on the north is a 3 ton and the one on the south is a 5 ton. Both of them going could cool the house, but when they cycle, it doesn't seem to handle it. I had two thermostats that were located by the AC 'experts' that did my house and were in the top middle of the price range. I replaced them with highly programmable thermostats that were in the high range of prices. These wouldn't do the job of handling peak periods well, so I got a high priced "learning' version. It was crap.

The learning thermostats only learn what the programmer wants them to learn, and it was great at anticipating my needs. It decided I liked the AC on at 07:00 and off at night ... exactly the opposite of what I wanted. They tried to predict what temperature I wanted the house at and must have been born in Nova Scotia because they wanted to keep it at around 65F.

I sent those things back before the 30 day refund period was up. What a waste.

Then, I built my own <link>; I could control them any way I wanted to. Over the years I tried recirculating the air around the house with them, experimented with differing hysteresis curves, used various smoothing algorithms on the temperature readings, etc. Basically, I tried everything I could think of to get the environment the way I wanted it.

Nothing worked very well. I would still wake up with the bedroom running around 85F at night.

But, during my experimenting with supercooling the house (look at the posts on supercooling by using the contents search on the top right of the page) I noticed a whole bunch of things that really shouldn't be happening. First the south AC unit was short cycling. Short cycling is where the AC comes on and then shuts off in seconds or minutes. This is NOT a good thing.

Cycling like this can radically shorten the lifetime of any motor driven device. It causes undue wear on the bearings to be jammed up by the quick start of the motors. It can cause fan blades to slip and that scores the shaft. The air start up can loosen vents and cause rattles. Basically all the things that destroy devices like this. This behavior can also cause a room to be too cold and then too hot within minutes.

The very most expensive AC units start slow and ramp up to speed, they will run slowly to keep the air moving, they even open and close vents based on the need for cooling in a particular area. But, I'm not Bill Gates; these things are way out of my price range.

So, I started looking for the cause of this situation on my south AC. TLDR (too long didn't read) the thermostat was in the wrong place. The thermostat was in a hallway like most of the thermostats in the world close to an overhead air return for the AC. Over half the air for the house went through that return. The temperature would drop rapidly in that location when the AC turned on and cause shut off in a matter of a couple of minutes. Then it would rise rapidly back up because it was only the breeze that cooled it off and repeat the cycle.

Another factor was that I run in and out of the garage a lot. Each time warm air would hit the thermostat and cause the same problem. Add to that the garage is on the other side of the wall and it doesn't have AC. When it heated up, the wall was warmer than the air in the house; cycle started all over again. Obviously, the thermostat had to be moved to get better performance.

Based on this research, I modified the house code to save the activity of the two AC units and looked at them for a day to see how bad it was. It was pretty bad. Here's a chart of my findings on the first day for the south AC unit:


The tall vertical stripes are when the compressor was running, and the jagged line down the middle was the temperature the thermostat was reading. Each shaded long vertical strip is the compressor chewing up power and wearing itself out. Here's a closeup of a couple of them from the middle of the chart:


The stair steps in the temperature is due to the granularity of my recording the data. I only mess with one degree changes, so it comes out like this. So, you can easily tell that the hysteresis is three degrees and it takes very little time to overcome that with the AC unit essentially blowing down the hallway from all the rooms. Similarly, the temperature will shoot back up in a similar fashion because that short a cooling interval doesn't really cool anything except the air the it is blowing around. The gap in the middle is because the cumulative impact of a series of cooling cycles finally does cool things down a little.

When I looked at the North thermostat, it was a different set of environmental factors that added up to a different problem. This thermostat was in a short hallway outside the master bedroom (my room darn it) while the AC unit was venting into that room. There were also a couple of vents that dumped air into the rest of the house to aid there as well. When I looked at it, it looked like this:


Same things on the graph, compressor run period and temperature recorded by the thermostat. Notice the compressor runs a lot even though the temperature isn't changing? Part of that problem is that the thermostat isn't really looking at the AC activity, it's looking at a completely different area. The rest of the problem is that the two vents into the rest of the house are letting almost a great a volume of air get out there as it allows inside MY ROOM.

Fine ! I gotta move the thermostats, but where the heck am I going to put them? Also, it's a real pain to move a thermostat. I don't have a real attic, it's an area that is totally filled with insulation about two feet tall. I really, really don't want to go up there --- ever. I could carve out the wall and move the thermostat and then patch up the wall. That's equally unlikely to happen. Instead I experimented with really long hysteresis values. I was up to 10 degrees at one point. That solution was not satisfactory. I also tried running the fan longer to make sure the air got moved. That didn't work well either; it actually made the problem worse.

Then, I thought about it a bit. I had these temperature sensors <link> all over the house, why couldn't I just use them instead of the temperature sensor inside the thermostat? There wasn't a single reason why not except I would have to change some code in a few places. I took all the code out of the south thermostat related to reading temperature and reorganized it a bit. Now, it would receive the temperature forwarded by the house controller from any of the temperature sensors around the house.  I chose a room where the sensor was on an inside wall away from any breeze from the AC directly. The sensor gets air circulation, it just wasn't directly in the cool air path.

Now, I was ready to test the newly modified south thermostat. The one that was banging the compressor to death with short cycles. Let's see what this accomplished:


Now, that's more like it. Granted, it was a stormy day and not our usual 100+ temperatures, but look, it wasn't short cycling any more. There are long periods of AC activity and the temperature rises slowly instead of a few seconds at a time. This may look like I'm actually using more power, but I'm not. It's actually about the same because the gaps are longer as well. the big thing was that I wasn't tearing the guts out of my AC.

I did the same thing with similar results to the North AC, except I also closed off the vents to the rest of the house. Now my bedroom cools down pretty quickly and stays that way for a while.


Notice that it isn't on all the stinking time blowing air where it isn't needed? The big gap is the 'demand' period where the AC isn't allowed to run 15:00 to 20:00. After the down time, it kicked on and recovered a little after midnight.

The beauty of this is that I can build a couple of temperature sensors specifically for the AC units and put them anywhere I want. If I want priority in the bedroom, put the sensor by the bed. If I want it for the shower, put it just outside; you get the idea. Basically, this is a priority system now that allows me to carry the priority anywhere I want.

<rant>
I hereby copyright this idea !! Anyone is welcome to do anything similar; heck steal my code if you want, but you commercial shark guys out there better get permission to use this. It's real annoying when you find your code, stolen right off the site and only perfunctorily changed in a book that sells for $35 a copy at a book store. I'm looking for new ideas and find my old ones on the shelf...sigh. I have found my code and ideas all over the web and almost every single time it's attributed; that makes me feel good. When someone is selling it, not so much. This stuff is supposed to be free dog gone it.
</rant>

Anyway, the jury is still out on this idea. I need to watch it over time and see if there are problems with the devices talking to each other, getting out of hand unexpectedly, actually working the same way over time. That kind of thing. One thing I did notice though is that a web only version where there is no control station nearby sucks. It's really nice to be able to lower or raise the temperature by pushing a button on the wall instead of starting up a browser and working through pages to get to it. Now, this could be a cheap tablet, and old phone, or something like that if you want to get fancy, but a nearby control is nice. I like buttons.

Also, it's a good thing to have a display that shows everything is working OK. I'm currently using the display on the thermostats, but it could be anything that you can see when wandering aimlessly around the house looking for the car keys. This also helps with the, "It's too hot." comments. You can point to the thermostat and show them that it's only 80 and not hot at all. Folk visiting from the East do this all the time.

Another thing I learned is that AC 'experts' are not to be trusted. These things were professionally installed and came highly recommended. They put one thermostat outside the room it was needed in and the other in a breezy hallway next to the air intake and a garage door. In retrospect, I may be to blame somewhat for not asking enough questions, but these were experts hired for their knowledge and experience. I don't have a suggestion on how to handle this problem except to get two or three experts to present proposals and pick their brains. If you are Bill Gates and can afford to do that kind of thing. I even blogged about the unreliability of 'experts' a couple of times; my experiences are not good with them. Of course, now that I can put the temperature sensor anywhere I want, it doesn't matter as much.

See what happens when you start automating your house? Ideas may come slowly, but actually doing them is entirely possible.

Oh, this is another post that will attract attention from the spammers. If you post advertising in a comment, it will be quietly deleted. Usually the same day. So, don't bother advertising your AC repair company here.

Wednesday, August 23, 2017

Room Temperature Sensor; got to use the 3D printer for real

I used my 3D printer on a real project, the room temperature sensor. I spent a ton of time messing around with various drawing tools and learning a little about slicing software, but didn't actually do anything that could be considered useful. Unless you count a stand for my Star Trek Enterprise that I have on the kitchen window sill:


I got the files for the stand off Thingiverse <link> and just printed it. Thingiverse is wonderful for getting things that other people have worked on, but it isn't the same as coming up with your own idea and stepping through the entire process.

I decided on the basics of an enclosure for the sensor weeks ago, but it took a while to decide on a tool to use to design it, then the actual design process. I tested a couple of enclosure ideas for a few weeks and finally, a couple of days ago, put four more of the sensor electronics together and printed enclosures for all of them. I have five areas of the house being monitored and recorded in my home database that I can chart and examine.


Yes, they follow each other really well over the period charted, but remember, a temperature change of a small amount will make a room feel hot. It's interesting to watch this phenomenon. One room is 75F and the next is 78F, not enough to matter, but it feels really hot in the warmer room. It doesn't help much to put a thermometer in the warmer room so you can see the actual temperature; you just think the thermometer is wrong. Strange.

Here's what the entire assembly looks like on the wall:


It consists of a base plate that you mount to the wall and a cover that slides over the base to protect the wiring. Here's the two pieces before mounting:


Most of the engineers out there could have drawn this up in about 10 minutes, but frankly, this process was tough. Every little item had to be measured and thought out carefully. I had many, many test prints of sections to see if various things actually fit together. I kept running into little unexpected problems. The plastic would be a little too rough in some spots and pieces wouldn't fit together. The model would glue itself to the base of the printer and it flatly refused to come off. I didn't put holes in the sensor PC board and had to come up with a mounting solution for it. How tall EXACTLY should a stand off be for the various pieces?

Most of this stuff was trial and error. Lots of errors. Just look at the pile of various attempts that will go in the trash after I post this:


One thing I discovered towards the end of the project was that I could cut the model and only print part of it. That was a real time saver. I could print the section I was trying to settle on and test it without waiting hours for the printer to finish the entire thing. I didn't read about using this capability anywhere on the web. Lots of folk talked about cutting the model, but didn't mention how it could be used to test a section of it. I guess most folk use 3D printers to make single piece items.

It's surprising how many little things creep up and have to be solved. The battery holder:

was initially a bit of a problem. I didn't want to mount it flat to the base plate because the mounting screws would go through the plastic, so I put in a couple of standoffs for the two screws that go through the holes in the middle of the assembly. Of course, that made it rock on the screws when I messed with the batteries. I solved that by putting in four more standoffs that kept it from moving.

Th circuit board with the electronics on it didn't have holes for mounting screws (oops).



So I had to work out special standoffs that could hold the board in place. Of course I didn't have washers that would fit the standoffs, so I just printed them as part of the base. Here's what the base wound up looking like after I solved these problems:


The battery holder has six standoffs two of them for actual mounting and the others to keep it steady. The standoffs for the PC board have a cutout for the board and I use little washers to hold it down securely:


The little dark spot in the center-left is a moth that was attracted to the heat and became part of one of the sensors. Note to self: close the printer door stupid.

I slid the lid up on one of the sensors so I could show off the construction of the assemblies:


If you zoom in on the picture you'll be able to see the mounting arrangement more closely. They were simple to install since they only take two #6 drywall screws and the entire device doesn't weigh much.

This project has been a lot of fun over the last couple of years. Yes, YEARS. And it isn't finished yet. I still want to use the sensors to replace the two house thermostats by taking the readings of each room and turning on heat, cool, or just fans to control the internal environment. I want to chart the outside temperature along with the rooms to see how it affects things as the day passes from season to season (notice, I only have two seasons here: nice and too-darn-hot). I may even create outdoor sensors to measure the wall temperature on some of the outside walls. That will prove the insulation effectiveness.

Who knows what I'll do with this in the future.


Wednesday, September 7, 2016

Simple Temperature and Humidity Sensor

Anyone that plays with little computers has seen articles about the DHT11 or DHT22 sensors. They're clever little humidity and temperature sensors that don't require calibration and measure the two factors we all complain about when discussing the weather: temperature and humidity.

I've seen them, but actually never worked with one because, here in the desert, the humidity seldom gets out of the 20's. I've messed with a number of temperature sensors, but humidity didn't interest me much. That changed when my daughter and her husband bought a new house.

It's (the house) one of the new energy efficient homes that is really well sealed up and even has solar panels. The energy efficiency actually works, they use a lot less energy than I do per square foot and the place is comfortable in all kinds of weather. The big drawback is getting smells and moisture OUT of the house.

Suppose you're cooking dinner and have a couple of pots boiling on the stove, and the teenager takes one of those 20 minute showers they're famous for. The water build up in the house is huge. If the temperature outside is hovering around 20F, you can't really just open some doors and windows to air it out, so the water builds up until it becomes pretty uncomfortable. The steel front door starts to condense water and it runs down into a small puddle on the floor. The glass on the skylite (double paned, but covered with snow) starts to condense water and it drips on you when you stand under it. The solution is simple, air the place out and get rid of the moisture.

No, the fan over the stove doesn't help much. She turns it on, but naturally the steam misses most of the hood and goes for the ceiling. Those fans and hoods over the stove aren't very useful. They need to be bigger and have an actual FAN in them, not one of those six inch noise makers. If I have to listen to a fan, it really should actually be doing something.

I suggested they measure the humidity and see what is going on, so they can decide which of several methods they need to try to remove the water floating around, but my daughter had another idea, "Dad, why don't you make me one?"

OK, I can do that:


I got to try out the I2C input serial LCD displays and the sensor. It was a fun little project that took about three hours rounding up all the right libraries to make the devices talk. It took me a heck of a lot more time ordering and receiving the pieces. Of course, I already had the Arduino, cable, and sensor, but the display and sensor came from way far away.

It just works; no messing around with calibration or strange problems.

It's raining a bit today

Yes, I know you can buy these things for a few buck off Amazon or whatever, but where's the fun in that? Also, I managed to make a deal where I build it, and they figure out an enclosure that suits their taste. That was totally evil of me. The hardest part of this kind of project is enclosing it inside something and making it look nice, and I totally passed the buck on that part.

Total win for me. Plus, the kids can say, "Grandpa built that."


Monday, November 2, 2015

Battery Operated Temperature Sensor: The Batteries Died

The previous entry on this project is here <link>.

I worked on this project earlier this year and put it into daily service back in April. The batteries died last night (this morning) at 4:00 AM, earlier than expected. They lasted 5.5 months and had the same rapid decline to 2.7 volts that I saw when I was running it in accelerated mode to understand how to do this.

Basically they coasted along dropping a little over time and then just dived, relatively speaking over a couple of weeks to a level where it wouldn't work anymore. This seems to be the normal behavior of alkaline batteries, so nothing new.

I am disappointed that it took less than six months to die though, but it died two days after my TV remote control died and I changed those batteries around the same time as this device. I remember because of the coincidence of having the remote need batteries around the same time as I started the long term test on the sensor. Could be the life of the cheap batteries I'm using.

The device was set for 115 seconds off and 5 seconds on and I can easily change that to a much longer off period if I need to, but I'm not sure I want to. Having the temperature available at two minute intervals is nice and fits with my longer term plans for temperature control in the house.

On the reliability front, this thing has worked day after day without a hiccup. I use it to turn off the bedroom and outside lights when I go to bed every day and sometimes just to show it off. Never gave me a problem unless the controller it talks to was having problems because I changed something there. It's still a bunch of components on a proto board though. I couldn't find an enclosure to fit it that I liked and decided to wait until I could buy a 3D printer to make something for it.

My tractor and the terraforming work around the house ate up the money I was setting aside for the printer and that has been postponed until I finish that stuff. Keeping flood water out of my house and repairing ruts in the driveway will always take precedence.

I put some more of the exact same batteries in it, and it's beside the bed again doing exactly what it's supposed to. I'll check on it from time to time and see what develops over the next six months or so.

Maybe by then I'll have an enclosure for it.

Friday, April 24, 2015

Battery Operated Temperature Sensor: OK, Let's Build This Thing

The previous post in this series is here <link>.

Well, I've been testing, trying new ideas and even added a button to this thing for the last several weeks. I don't think I'm going to learn anything new in the short term, so I decided to solder everything down and turn it into a package that I can actually use.

I got some of these:


Those of you that have been following this project understand now why I wanted to confine the parts to half a breadboard. I can put all the parts on this and then have something I can put in some kind of enclosure. I stripped all the parts off the breadboard and put them on the new board.


Yep, I got the regulator, XBee, Arduino Mini Pro, sensor, and a push button on there. I mounted the active components in sockets so they'd be easy to change if I needed to. I also put a plug on the battery pack so I can unplug it if needed. I still have the monitor circuit for watching the battery level, that way I can tell when the batteries are starting to go flat.

It's a nice little package, even if I do have to say so myself. If I put the battery underneath the board, it is pretty compact as well:


I think I'll put it in a travel container for a bar of soap to play with it around the house for a few months. Here's the schematic for the final result:



I'm going to the 3V version of the MCP1700 as soon as they come in from Mouser. Those little devices are perfect for battery applications. The 3V version (opposed to the 3.3V) worked well with this combination of components because the battery drops to just under 2.9V before it shuts off. That way I've dropped the batteries down to a volt each, and there's essentially nothing left in there.

Notice the voltage divider on the battery input? That combination of values works well to monitor the battery voltage, but I had to calibrate it in the code. It's pretty easy, get your meter, measure the battery voltage and then adjust the code until you get the same reading ... done. This will hold essentially forever, but if you want to check it yearly or so, it's easy.

This particular device (there WILL be others) is going beside my bed. I'll have the temperature of my bedroom as well as a button to turn the light off eliminating the X10 controller I have there now. Remember, this is a smart device, I can program it to do other things over time, and probably will. I think having one in the guest room with a door sensor attached would be fun. I may put one in the attic to monitor the heat up there, and one hooked to a moisture sensor out in the garage would be great for keeping track of the water heater.

How long will the batteries last? I don't know exactly, but it should be many months, a little less than a year. I can't measure the power usage, it's too low for anything I have. I removed the led from the Arduino board and feed the power behind the power regulator, so I have no losses there. I suspect it's using around 10 micro amps when asleep and not much when it's running. I'm going to set it to 5 seconds awake and 115 seconds asleep which will cut the drain in half compared to the level I ran it at in testing. If it runs down too soon, there's still several things I can do, but they won't actually gain me very much. Slower clock speed, mosfet switch for the power to the sensor and XBee, that kind of thing. The one thing that will really increase the time between battery changes is to simply use four batteries. The regulator I used can take it and it's not much more space. I'll try the three battery setup for as long as it runs to get a feel for what's going on.

My new NAS came in and is installed, so I guess I'll move on to something on it now. I'll build more of these as time permits, I have enough XBees for a bunch.

The next entry on this project is here <link>

Friday, April 17, 2015

Battery Powered Temperature Sensor: Remote Control Added

The previous post in this series is here <link>.

So, I crawled into bed the other night and reached over to turn off the light and it didn't work. Poked the X10 control button several times and nothing. Crap! I had to get out of bed, go to another room and turn off the light from there. The next morning I replaced the button battery in the control and everything was fine again.

But this got me to thinking; this is the only X10 device I have left from years ago and it's time to think about doing something different. X10 failed completely in my house except for the room farthest away from everything else and it has been flaky for some time now. But, how would I implement a remote control that can just hang on the wall for months and get used maybe once a day?

Put a button on my battery operated temperature sensor! It's still in testing, but it appears to be working great, All I'd need to do is put a button on it and cause an XBee message to be sent to my house controller and then I can choose some switch device to put on the light circuit and have my button beside the bed. It would measure the temperature periodically and just wait for a button press to send the signal.

Sure, I could use my cell phone with the (brand spanking new) app I made for the house, A tablet, or a web browser. I could even call my neighbor and tell them to turn the light off for me, but I want a simple button on the nightstand that I can press without any hassle and turn the silly light off. But, how to do it without draining the battery?

Interrupts, yes, that's the ticket.

Remember from the previous (ton) of posts on this device, I put the device to sleep for 55 seconds at a time and wake it up for 5 seconds to transmit the battery level and temperature, all I should have to do is to hook a button to an interrupt pin and add some code to send a message to the house controller. At the controller I can add some code to do anything I have a controller for. I could open the garage door with it if I want to.

So, a few hours later after about 25 false starts, I got it working. I connected a little switch between pin 2 and ground of the Arduino board I'm using and it causes an interrupt which breaks the arduino out of sleep and then I just send the normal temperature message which now includes a new field to indicate that the button was pushed. At the house controller, I parse out the field, look at the value and do whatever I program in.

The reason it took several tries to get it working was because I was making it too hard. I thought I'd have to have a lot of special code to support the interrupt and proceeded down that path. It turned out the JeeLab routine I'm using for sleep already supports other interrupts, and all I had to do was check a variable and add a simple interrupt handler and everything worked ... well mostly.  Here's a code fragment showing how I sensed that the button had been pressed:

 if (millis() - savedmillis > AWAKETIME){
    Serial.print("was awake for ");
    Serial.println(millis() - savedmillis);
    delay(100); // delay to allow the characters to get out
    savedmillis = millis();
    digitalWrite(xbeeSleepReq, SLEEP); // put the XBee to sleep
    while (digitalRead(xbeeCTS) != SLEEP){} // Wait 'til it actually goes to sleep
    unsigned long timeSlept = 0;
    int result = 1;
    while (timeSlept < SLEEPTIME){
      attachInterrupt(0, buttonThing, LOW);
      result = Sleepy::loseSomeTime((unsigned int)7000);
      if (result == 0) // this is something other than a watchdog
        break;
      timeSlept = (millis() - savedmillis);
    }
    Serial.print("was asleep for ");
    Serial.println(millis() - savedmillis);
    savedmillis = millis();
    if (result == 0)
      Serial.println("Woke up on a button press");
    digitalWrite(xbeeSleepReq, AWAKE); // wake that boy up now
    sendStatusXbee();
  }

I simply look at the return value from loseSomeTime() and if it's 0, then some interrupt other than the watchdog timer happened. I print a message for debugging and go to the XBee send code. The trick is in the interrupt handler:

// This is for the remote control buttons
void buttonThing(){
  sleep_disable();
  buttonPressed = true;
  detachInterrupt(0);
}

The variable 'buttonPressed' is simply a global variable that I set to true and look at in the XBee send routine. If the variable is true, I set a new field in the mesage to say so, if it's false, I say 'nothing' in the field. I'll eventually work out what would be the best thing to put in the message, but that parts easy once you get it working. Notice that I attachInterrupt() for interrupt zero, which means button two on the Arduino, just before going to sleep, and detach it after the button is pressed. That prevents multiple interrupts from button bounce. The disadvantage to doing it this way is that it won't respond to a button press during the 5 seconds the board is awake. I don't currently consider this a problem, but that might change if I want to use it for something else.

So, now if I push the button, it gets an interrupt on pin 2, breaks out of sleep, sends the temperature and an indicator that the button was pushed to the house controller. The house controller records the temperature, then looks at the new field and does whatever I want.

The Xbee send code looks like this

void sendStatusXbee(){
  xbeeReadyWait(); // Make sure the XBee is ready

  char *command;
  if (buttonPressed)
    command = "toggle";
  else
    command = "nothing";
  buttonPressed = false;
  sprintf(Dbuf, "{\"%s\":{\"name\":\"%s\",\"temperature\":\"%s\",\"command\":\"%s\",\"voltage\":\"%s\"}}\n", 
            deviceType, // this happens to be a temperature sensor
            deviceName, // originally read from the XBee
            dtostrf(readTemp(), 4, 1, t),
            command,
            dtostrf(readVcc(), 5, 3, v) // This is a text conversion of a float
            );
  Serial.print(Dbuf); // notice this is only for the serial port
  sendXbee(Dbuf);     // out to the XBee
  Serial.println("Message sent");
}

Not much to it, just a field called 'command' in the JSON string that I can look at when the message comes in. Currently I'm sending the word 'toggle' if the button was pressed and 'nothing' if it wasn't; I love being able to read the messages, so that was descriptive enough for me.

There's another interrupt pin on the Arduino, pin 3, and I can use that also for two buttons. Maybe an on-off toggle. I could also multiplex it by putting a keypad on there. First button wakes up the Arduino and then watch for letters, digits, whatever and compose a more complex command. For now, It's just a button that turns off my bedside lights. 

Tomorrow though, it'll be a button that turns off the bedside light, turns off the outside lights, sets the thermostat to the temperature I use at night, closes the garage doors (if left open), and maybe turns off the water heater power. Call it my 'going to bed now' button.

Now, a bit about the sensor testing. I had to put in a voltage divider to measure the input power because it was driving me nuts monitoring the power after the regulator. To do this, use really high value resistors for the divider and then a .1 cap on the analog pin to ground to lower the impedance. The arduino has an input impedance of around 10K on the input pins, and if your external circuitry is too high, it will give the wrong readings. The easiest way to overcome this problem and still not use very much power is to use a cap. I used 10 Meg and 1 Meg, which put my quiescent current below a micro amp, that should be fine.

So watching it run on the almost dead batteries I installed, it started failing at around 3.6 volts. The regulator on the Pro Mini I'm using was junk. First, it didn't regulate well, the voltage wandered around 3.9 V and eventually dropped off to nothing when the supply went to 3.6. This is not what the spec sheet says. Fine, I have a solution to that, I'll just put a MCP1700 regulator in place and started it back up. Take a look at the specs for the MCP1700, it's a totally awesome low current, low dropout regulator designed for this kind of thing.The new regulator worked great and I've been running with 'dead' batteries for several days now.

I did kind of mess up though. I should have ordered a different MCP1700. I chose the 3.3V version, and I think I should have gone for a lower voltage. Fortunately, they cost me 37 cents each, so I haven't lost much money if I decide to go lower. I'll know more when I hit the cut off point on the 3.3V and how it performs when I bottom out the batteries.

Just for giggles, here's a picture of it right now:


I thought it was a mess of wires a few weeks ago, now you can't see some of the components for the wires connecting things. I haven't tried to condense it yet, I'll get to that later. The new switch is between the batteries and the other stuff so I can get to it. I plan on actually using it for a while to be sure it will do the job for me.

Overall though, this little bundle of wires has really performed well. This learning curve has actually been fun and gave me ideas for other things I can build around the house. Remember, it currently senses temperature, it could easily sense anything else you want to throw at it. Suppose you put a pressure pad in front of the driveway, you could tell when someone pulled in. A light sensor to tell you if the lights in the shed were left on. A moisture sensor beneath the water heater to tell you if it started leaking. An air flow sensor in one of the ducts running through the ceiling. All of these things could be at my beck and call.

One more step in my quest to conquer the world.

The next post in this series is here <link>.

Wednesday, April 1, 2015

Battery Operated Temperature Sensor, yet another revision.

Previous post on this project is here <link>.

This little project has certainly taken on a life of its own. I've been at this for several weeks now watching what goes on with batteries and various components and software. My latest set of revisions is almost a start-over.

I removed the Ardweeny I was using and replaced it with an Arduino Pro Mini. The little Pro Mini is designed for folk that want the power of an Arduino without the bells and whistles. There's no place to plug in wires, no screw holes to mount it, take a look:


The disadvantage is that it has an LED and a voltage regulator on it. Voltage regulators waste power by having a ground reference and a small amount of current through it that can run my batteries down. However, this regulator is a SE5509BALG and it has a ground current of  only 21 uA, so that may not be a problem. I've run across folk that pull the regulator out to decrease the current draw, but I need some kind of regulator to supply the XBee with 3 volts. More on that later.

The LED is no problem, I can just pull it off the board if I can see it well enough.

I also switched from the TMP36 temperature sensor to an 18B20 one wire device. The reason I didn't start with the 18B20 was that I didn't have one to try. During the testing of battery operation, I ordered some and decided that now was the time to try them out. My decision to switch was partly curiosity and partly laziness. When I tested my code on the Pro Mini, I found a problem with the analog to digital converters. It seems when you switch them around to read the processor voltage, they don't settle out correctly on the different version of the 328 chip on the Pro Mini. I was going to research the problem and work around it, but realized that the one-wire 18B20 didn't need analog conversion, it's all digital. Problem solved.

Then, I went to three batteries. All the experiments indicated that I just didn't have enough voltage range to get long battery life. The AA batteries supply power very well all the way down to about 0.9V, and then they drop off pretty rapidly. With two batteries, that means I can't get close to the maximum capabilities of the batteries because my circuitry drops out at just under 2.8V. I can only drag the batteries down to 1.4V each and that means I'm wasting almost half a volt of useful power.

Using three batteries and a 0.9V limit I can drag most of the power out of the AA batteries and do useful things with it.

Now do you see why I need the voltage regulator? Three AA batteries will give me 4.5 volts and a very hot XBee. With the low dropout, low current voltage regulator on the Pro Mini, I should be able to get a long period of life before I have to change the batteries and still power the XBee just fine.

This is what it looks like right now:


I tried to hide the LED so the picture would be clearer. The 18B20 is on top, bent over a bit so it can catch whatever breeze may happen along. I used the same rubber band, but it may have to be replaced soon, starting to dry out and crack. Things are really crowded on purpose, I'm trying to keep all the circuitry on a half sized protoboard. At some point I'm going to solder all this stuff down and actually use it.

So, it's in service right now measuring temperature every minute and sending it to my house controller. I loaded it with dead batteries from the previous attempts. Not only is that saving me money, it should also die more quickly from draining the batteries. Similarly, I left the LED in to consume more power to get to that point. Battery operated tests take a long time to learn what happens at the end if you don't do something like that to hurry things along.

The compromise is that the processor voltage is after the voltage regulator. That means my measured voltage is going to be level until the batteries are nearing the drop out point. I could get around that with some clever rewiring, or a separate regulator for the XBee, but this test may give me all the information I need. I'm just going to look for a level voltage reading until the end where the voltage regulator drop out happens. With the LED running, it shouldn't take too long. If it does take too long, I'll think a bit about a voltage divider from the unregulated voltage to give me a sample measurement. If anyone's interested the code will be in GitHub in about an hour or so.

More later.

The next post in this series is here <link>

Saturday, March 14, 2015

Battery Operated Temperature Sensor - Still learning about the TMP36

The previous entry on this project is here <link>

After I found out about the open emitter problem in reading a TMP36 <link> and tried it out for a longer period of time I noticed there were still some glitches in the readings. Don't misunderstand, these were tiny and represented no real problem, but I wanted to settle it down as much as possible.

Yes, obsessive, compulsive about this I am.

I recorded a ton of readings from the chip and looked them over. The problem seems to come from simple outlier readings that happen from time to time.  Every sensor has outlier readings, it's just part of reality, and there are methods of fixing this problem. Naturally, I took the easy way out. I simply read the sensor 15 times in a row into an array, sort them, and average the middle five. This way the outliers wind up at the bottom or top of an array and get excluded from the sort. Here's the code:

#define READSIZE 15

float readTemp2(){
  int readings[READSIZE];
  int reading=0;
  
  for (int i = 0; i < READSIZE; i++){
    readings[i] = analogRead(tmpInput);
  }
  // Now sort the list to put the outliers at the beginning and end
  sort(readings, READSIZE);
  // grab the middle 5 and average them
  for (int i = READSIZE / 2 - 2; i < READSIZE / 2 + 3 ; i++){
    reading +=(readings[i]);
  }
  reading /= 5;
  //reading = analogRead(tmpInput);
  float voltage =  (reading * 1.1) / 1024;
  float tempC = (voltage - 0.5) * 100;
  float tempF = (tempC * 9.0 / 5.0) + 32.0;
  return(tempF);
}

void sort(int a[], int size) {
  for(int i=0; i<(size-1); i++) {
    for(int o=0; o<(size-(i+1)); o++) {
      if(a[o] > a[o+1]) {
        int t = a[o];
        a[o] = a[o+1];
        a[o+1] = t;
      }
    }
  }
}

This smoothed the reading right out and made for a very nice graph. In the fragment of readings charted below you can see how well this works:


This little piece of data is when I had the sensor outside, brought it in the warmer house, then took it back outside. Notice the shape of the curve? Classic ramp up and back down similar to the response shape of an inductor. This is the thermal resistance of the plastic case on the sensor, wires, etc, and is a far cry from the erratic reading I used to get.

The TMP36 turn out to be a really nice little device when used correctly with my new filtering. I'll eventually look at removing the power from the sensor when I put the Arduino to sleep, but I don't expect much of an increase in battery life since the quiescent current of the sensor is claimed at 50uA. Every little bit helps since I plan on running these things forever.

The next entry on this project is here <link>

Sunday, March 1, 2015

Battery Operated Temperature Sensor - Now About Battery Life

The previous entry on this project is here <link>.

I'm still working on my battery operated sensor and have been testing it for battery life and stability. I've learned a thing or two. First, this is absolutely possible, but not like the various tutorials out there lead you to believe; I'll never be able to get years of battery life like they imply, Second, I'll never be able run a battery completely down.

There's a number of reasons for this, but it will take some explaining. I've been saving the data I'm gathering and some things are noteworthy. Here's a graph of the data I've accumulated so far:


For this, only pay attention to the black line, I'll address the temperature (blue) later. Notice that it starts off around 2.9 volts, that's because I didn't get to uploading the data until the battery had dropped some, then there's some chatter where it started to drop to 2.8 volts and a long string of 2.8 volts until it jumps up. What happened was I only kept one digit to the right of the decimal and the chatter is where it was close to the rounding point, 2.85 volts. Then, because it quit transmitting just after noon on the 26th, I have a straight line until I changed the batteries on the 28th.

So the jump and relatively rapid decline is where I changed the battery and the code to a 50 second on versus 10 second off rate. I wanted data faster than a week at a time. I also added code to sense that it stopped transmitting and drop the reading. This way the battery getting too low would be readily apparent. I learned two things from this: use more precision, and heavier drain to get experience in a shorter amount of time.

Now about the weird temperature readings. After a couple of days of watching the temperature inside, I got bored with the flat line and took it outside. That's what the cyclic activity is from the 20th to the 23rd is.  The drops are experiments I did with the temperature sensor. Things settled down in the temperature sensor before the 26th, but I did still move it around the house some.

Now, take a look at this chart. This is the period after I changed the batteries and was using 50sec on, 10 sec off timing:


No, the batteries didn't last long, but that was my objective for this test. Notice that the device quit when the batteries dropped to 2.754 volts; that makes perfect sense when you think about it a bit. All electronics have some cut off point where they just quit working, for this combination of components, that's the cut off point. The temperature sensor is only good down to 2.7 volts and the processor is over-clocked as it is since I'm running it at the full 16Mhz, and lowered voltage.

What this means is that the rating of the battery doesn't mean much. These things have roughly 1600-1800 mah, but since the device dies at 2.75 volts, I'm only getting a portion of that. Don't make the mistake of thinking you can get all the power out of a battery, the lower voltage will step up and bite you.

There's a lot I can do to extend the battery's usefulness now that I know where it dies. First, I can adjust the sleep-awake factor. It turns out I need less than 10 seconds to take a reading and send it. I could probably drop it as low as 2 seconds. That will mean 58 seconds of sleep where it is drawing microamps of power to keep the timer running. I could add a battery and make it a three battery device. With three batteries I would start out with close to 4.65 volts, giving me almost two volts of range before it quit. This would mean a voltage regulator, but there are low current versions of them that would work. Ideas like a boost power supply aren't going to work because they take a lot of power just to run them. I'd get more out of the batteries, but it would mostly go to supporting the boost supply. I could lower the clock speed on the processor, but that makes timing and other things much more complex.

The test also told me that the battery voltage declines relatively rapidly from 3.1 down to 2.8 where it hangs in for a long period of time. Most of the current I got out of the battery was at this voltage.

Now, I'm going to set it up again for a shorter awake time and keep the code in that indicates when it dies and see what happens while I wait for a nice regulator to come in the mail. Then I'll test it with three batteries and regulation to see how that works out. I don't really want to use three batteries in each device, but I'll take the best road when I know more. Batteries are cheap in bulk, and I'd rather use more if it means the device will last longer.

Some of you will wonder, "Other devices can last a year or more on two batteries, what's the big deal?" Well, that's true, but they're activated by something. The smoke detector you have is asleep most of the time, and awakened by an external signal. For something like a door sensor, I could put it to sleep for several minutes at a time and wake up to send a message saying it was still alive. It would also wake up on a change in level of the actual sensor; I could probably get a year out of something like that. It's a different ball game. I want to monitor the temperature often enough to be of value, but not constantly. Once a minute is fine and maybe once every couple of minutes, but longer is something I'll have to think about.

More later as I get more experience.

The next entry on this project is here <link>

Monday, February 23, 2015

Battery Operated Temperature Sensor - Smarter TMP36

Last post <link> about my project to create a useful battery operated temperature sensor I whined a while about the flaky behavior of the TMP36 sensor.  I'm not the only person that has had this problem.  A simple search with Google will turn up person after person that has fought this problem. People have tried intricate filtering techniques, averaging, continuous averaging, everything they can think of to settle this device down. In the post I used the average of ten readings to get mine.

Even with that, I had some trouble.  This is on a battery supply, so there's no ripple or chatter from a buck supply, very low noise. I thought it could be the XBee transmission, so I added a little time delay to keep the XBee from transmitting at the same time as the reading. Nothing seemed to help Then, it occurred to me that I'd had a TMP36 setting outside hooked to an XBee using a pretty noisy wall wart for a supply continuously for a couple of years and never noticed a problem with it.

What's up with that? Why did it work on a fence post and not in my house?

I drug out the remains of the fence post temperature sensor from the box I'd tossed it into and thought about it a bit. I had put a voltage divider between the output of the TMP36 and ground to extend the range of the reading. Since I was using a tiny reference voltage, the max temperature I could read would be 120F and I needed more than that to have an outside sensor here in AZ (Don't try telling me to move, winters here are wonderful). Could the device need a load on the output?

I looked up a datasheet on the TMP36 and looked at the schematic on the device; the device has an open emitter output. I had never noticed that before because I was looking at tutorials and such and they all showed the TMP36 feeding directly into the input of an Arduino or other MPU.

I had to try it.  I dragged out a bag of resistors and took a look at the maximums of the TMP36 and settled for a 47K resistor, and grabbed a .01ufd capacitor and added them to the circuitry of the board. Everything worked fine, but I still had the averaging in the code, so I removed that and put the board back in service.

That seems to do it. The little temperature sensor is chugging away giving me nice stable readings. It hasn't been in service for very long, but I usually got a spike in the reading in that amount of time. Just to be clear on what I did, here's a schematic:


The .01ufd cap is as close to the chip as I can get it as is the resistor. I simply plugged them into the breadboard.

Could it be that all the tutorials out there are wrong ? I went looking again and never found a place where someone pointed this out. There were long discussions on the time it takes the input cap on the A/D converter to charge, a myriad of algorithms on smoothing (some of them mine), etc. Then, I stumbled across another person that came up with this <link>, Dr. Monk found the exact same thing. I was a little embarassed until I noticed that he posted on the 16th of this month, after I started this particular project and well after my other attempts, so I was right in line with his discovery. Great minds think alike (slowly).

I'm going to watch this over time, but it brings this little temperature sensor back as a very real possibility. I'm also going to try another sensor the DS18B20 since it comes in a cool waterproof housing as well as the TO-92.  I even want to experiment with a bimetal sensor that is heat resistant for monitoring food.

I can't believe I missed this for YEARS.

Edit: I finally got this sensor under complete control with some additional work on the software detailed here <link>.

The next part of this project is here <link>

Wednesday, February 18, 2015

Battery Operated Temperature Sensor

This project will take a long time to complete, but I wanted to post about it because it's a nice project for a person starting off in Home Automation.  I do a number of things in this project that can lead to even more projects later; this could be the first step for a person that wants to take control of their house without the huge expense of one of the ready made systems out there.

The story begins after I installed my new barometer out on the fence <link>, I was looking at the temperature sensor that I removed <link> and thought, "It would be cool to have temperature sensors that I could put anywhere around the house."  It would be nice to see the temperature in the hot parts of the house and maybe move some air in there when company is around. If I used a sensor from one of those oven temperature probes, I could watch a roast from anywhere; this could be useful ... so I built one.

I wanted to be able to power it with batteries and be able to read the output on a monitoring XBee, so that would mean a processor of some kind and a lot of learning about low power techniques. Low power pretty much leaves out a normal Arduino, they have power regulators on them and those things constantly consume power; they also get warm and that would mess with the temperature readings. I decided to use one of my Ardweenys.  If you're not familiar with these, here's what they look like:
They're not the tiniest Arduino derivative, but they are really close.  The beauty of these devices is that they have a tiny footprint and no unnecessary components to use power. I don't have to come up with a design for supporting the processor and can just use the device.

Since the new device was going to be battery powered, I would need to somehow monitor the battery level so I could change them when needed.  Did you know that the atmega328p can monitor its own power?  Yep, it can, you just have to be good with google to find out how.  There's also a temperature monitor in there so you can keep track of the heat generated.  I don't actually need that, but it would be fun to do it. Here's the code I used to capture the processor temperature and supply voltage:

/*
These two routines use the atmega328 built in thermometer and VCC measurement techniques
This way I can get the supply voltage to see how the batteries are doing, as well as grab
the temperature of the chip.  It may need calibration, but it's free
*/
float readTemp(){
  long result; // Read temperature sensor against 1.1V reference
  ADMUX = _BV(REFS1) | _BV(REFS0) | _BV(MUX3);
  delay(20); // Wait for Vref to settle - 2 was inadequate
  ADCSRA |= _BV(ADSC); // Convert
  while (bit_is_set(ADCSRA,ADSC));
  result = ADCL;
  result |= ADCH<<8;
  result = (result - 125) * 1075;
  return (result / 10000.0) * 1.8 + 32.0; // I want degrees F
}

float readVcc(){
  long resultVcc; // Read 1.1V reference against AVcc
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  delay(20); // Wait for Vref to settle
  ADCSRA |= _BV(ADSC); // Convert
  while (bit_is_set(ADCSRA,ADSC));
  resultVcc = ADCL;
  resultVcc |= ADCH<<8;
  resultVcc = 1126400L / resultVcc; // calculate AVcc in mV
  return (resultVcc / 1000.0); // but return volts
}


The units (Fahrenheit and Volts) are just my choice, Feel free to use degrees C and millivolts if you want to.  These routines ONLY work on certain of the Atmel processsors, but I'm only going to be using the 328, so that's not a problem.

Next I need a temperature sensor. I've already worked with the tmp36 a lot, and I have one of them on hand, so I went with it. I really can't recommend the tmp36 though; the things are skittish and have to be catered to a bit.  I've found with a lot of experimenting that stabilizing the power supply a lot and reading them several times in a row and taking an average will give a good reading.  Since I can read it 10 times and take an average in a few microseconds, that should work just fine. The power supply noise will only be a problem while I debug it because it will run on batteries.

Edit: I beat the interaction with this sensor. I can get nice readings that seem to be very accurate without too much trouble, the solution is both hardware and software and is described here <link> and here <link>.

/*
Reading a tmp35 chip to get temperature.
These devices are a little flakey. If the power has even a tiny
bit of noise, they give erratic readings. So, filter them as
best you can and then take several readings and average them.
*/
float readTemp2(){
  int total = 0;
  for (int i = 0; i < 10; i++){
    total += analogRead(0);
  }
  int reading = total / 10;
  float voltage =  (reading * 1.1) / 1024;
  float tempC = (voltage - 0.5) * 100;
  float tempF = (tempC * 9.0 / 5.0) + 32.0;
  return(tempF);
}

I've used this type of code several times for various experiments and it seems to work pretty well. There's other techniques, but they're much more complex. I'll try this for a while and see how it holds up in actual operation over time.

Of course, since it's me, there will be an XBee in there to transmit to my House Controller. I've never tried to get the power down low on an XBee, so this should be interesting. Notice how 'interesting' and 'frustrating' often mean the same thing? This time, there really wasn't any problem. I wanted the processor to control the XBee, so all I needed to do was set the XBee up for a pin controlled sleep and the processor could control it through a digital pin.

One of the cool things about sleep and processors is that the GPIO pins retain their state when you put them to sleep.  So, you set a pin high and put the processor to sleep, the pin stays high. That was a bit of a surprise at first, but it makes sense when you think about it a bit. This makes it really simple to put the XBee to sleep, just:

#define SLEEP HIGH

      digitalWrite(xbeeSleepReq, SLEEP); // put the XBee to sleep

I used a #define for SLEEP because I kept forgetting which state I needed to set the pin to.

The idea is that the processor starts, initializes the XBee and sets up anything else needed, then goes to sleep.  Sometime later it wakes up, takes a temperature reading, sends it, then goes back to sleep. Repeat forever, or at least until the batteries die.

Now, all I have to do is learn how to put the 328 to sleep. Yep, there's thousands of blog posts and tutorials out there on how to do this. Tons of examples of setting registers and shifting bits to control internal counters and such. Yuck! I really don't want to spend a few days learning the ins and outs (pun intended) of the 328P registers, I want to use them. JeeLabs to the rescue. Jean-Claude Wippler of JeeLab has created a nice library that includes a function to handle sleep without having to learn a ton of marginally useful register manipulation. However, I need to wake it up also; it's not very useful to put it to sleep and just leave it there. I can't do my usual technique of asynchronous timers in this instance because the timers won't run when the 328 is asleep, so I have to rely on the milli() function. Here's the code I came up with to control the sleep-awake cycle including putting the 328 to sleep.

  if (millis() - savedmillis > AWAKETIME){
    Serial.print("was awake for ");
    Serial.println(millis() - savedmillis);
    delay(100); // delay to allow the characters to get out
    savedmillis = millis();
    unsigned long timeSlept = 0;
    while (timeSlept < SLEEPTIME){
      digitalWrite(xbeeSleepReq, SLEEP); // put the XBee to sleep
      Sleepy::loseSomeTime((unsigned int)1000);
      timeSlept = (millis() - savedmillis);
      digitalWrite(xbeeSleepReq, AWAKE); // wake that boy up now
    }
    Serial.print("was asleep for ");
    Serial.println(millis() - savedmillis);
    savedmillis = millis();
    sendStatusXbee();
  }

AWAKETIME and SLEEPTIME can be changed to limit battery usage while still leaving enough time for the XBee to stabilize and complete the transaction. I'll have to experiment with this over time to find some balance based on real-life experience.  But notice how easy it was to put the board to sleep for a timed period?  One litle call to loseSomeTime() with the length of time I want to sleep was all there was to it.

A problem crept in this technique though.  Since the board is asleep, it isn't counting milliseconds, so the JeeLab library estimates the duration and bumps the millisecond timer to get it close to being correct. The problem comes when an interrupt happens. When something interrupts, the board wakes up to handle the interrupt, and when using SoftwareSerial to get an additional emulated serial port, you get interrupts. That's why I keep my own count and repeat the loop to sleep some more when this happens. In practice, I lose time this way, but it's been less than a second in the testing I've done so far. The timing doesn't have to be perfect, just good enough and this seems to fit the bill nicely.

So, I do some initialization, go to sleep, wake up, send the status and go back to sleep. I based the code on the XBee example I gave in a previous post for the barometer <link> I have outside. I had to take out some stuff and add others, but the code is sorta, mostly the same. I still have the command handling in there in case I need it.

Now, armed with enough hardware to get this project started I cobbled together a setup on a protoboard and started putting it together.


Yes, that messy lump of wires is my temperature sensor.  It takes up less than half a full sized breadboard, and has a few locations to spare.  There were a number of things that crept into the project that after getting it going I didn't expect.  For example, when the board is asleep too long, the XBee coordinator forgets about it. What happens is that the coordinator expects some interaction with every XBee on the network periodically, and if it doesn't get it, it removes the entry from its table of devices. So, on the first few tries, the temperature sensor couldn't connect when it woke up and I got error 22 or 24 depending on what was going on at the time.  A significant amount of time later I had a pretty good solution; just change the timeout on the coordinator for this item to be significantly larger than the sleep time on the temperature sensor.  I decided to make it three minutes and give it a try since I can change it later. The complication to this is that you have to change it for the coordinator and all the routers on the network.  Fine, I just fired up XCTU and used the remote command capability to update the various XBees one at a time.  The values I used in this case were:

SP = 7D0
SN = 9

The SP parameter evaluates to 20 seconds and the SN parameter means do it 9 times. Three minutes on a device that reports once a minute should be fine.  If extended testing indicated that I needed to change it, I'd just have to do the change over again. Not too bad.

Another thing was that I tried sending too soon after waking up the XBee.  The XBee takes a small amout of time to get itself going well enough to respond to send requests or commands, so I had to enable the CTS (clear to send) capability and hook it up to a 328 pin.  After doing that all I had to do was hang in a loop until the CTS signal changed and then I could send to my hearts content.  To set the parameter use the value:

D7 = 1

And my simple solution to monitoring it before sending was:

void sendXbee(const char* command){
  ZBTxRequest zbtx = ZBTxRequest(Destination, (uint8_t *)command, strlen(command));
  while (digitalRead(xbeeCTS) == SLEEP){} // just hang up and wait 
  xbee.send(zbtx);
}

I just hang in a while loop until the pin goes low.  It was nice how the #define I came up with worked in this case.

I decided to play around with it hooked to a battery and rewired the mess until it looked a little better and this is the device as it exists right now:


Maybe it isn't any less messy after all.  I did get to use my rubber band though.  And yes, I use cheap batteries. No, I don't expect you to be able to trace the wires from this.  Here's a Fritzing image of it:


Note that the black thing is NOT a 328 chip, it's an Ardweeny, I couldn't find a Fritzing part for the Ardweeny that worked.  And, for my 'more advanced' readers:


Once again, it isn't a 328, it's an Ardweeny, and of course I'll give you the code, it's in GitHub already with my other Arduino projects and examples <link> it's called RoomTemp; I also added Jeelib so I wouldn't have to keep track of changes to it. But remember, I'm not done with this yet.

I'll have to monitor the battery usage over time and make adjustments or changes as necessary, bugs may show up, or I may get a brilliant idea. The eventual goal is to have them in several of my rooms as well as a couple to play with.  I may even carry out my threat to hook one to the barbecue for monitoring steaks. I'm monitoring this on my Raspberry Pi house controller, but not doing anything with the readings yet.  Here's a sample of the output I'm using:

{u'Temp1': {u'ptemperature': u'79.4', u'temperature': u'73.9', u'voltage': u'3.0'}}
{u'Temp1': {u'ptemperature': u'79.4', u'temperature': u'73.9', u'voltage': u'3.0'}}
{u'Temp1': {u'ptemperature': u'79.4', u'temperature': u'73.7', u'voltage': u'3.0'}}
{u'Temp1': {u'ptemperature': u'79.2', u'temperature': u'73.7', u'voltage': u'3.0'}}
{u'Temp1': {u'ptemperature': u'79.4', u'temperature': u'73.7', u'voltage': u'3.0'}}
{u'Temp1': {u'ptemperature': u'79.4', u'temperature': u'73.9', u'voltage': u'3.0'}}
{u'Temp1': {u'ptemperature': u'79.4', u'temperature': u'73.7', u'voltage': u'3.0'}}

I'm using a JSON string and the 'ptemperature' value is the processor temperature I mentioned above, the voltage is taken from the processor also. Of course you can change the code and use any format you want to in the message.

Have fun.

The next part of this project is here <link>.