Sunday, December 15, 2019

65: Measuring Kilowatt Hours *

I recently bought a plug-in hybrid Kia Niro. I was surprised to find out that while I could schedule when the car would charge and could modify that schedule from a phone app, nothing told me exactly how many kWh of power I was using. I kind of expected that the electric miles would be much cheaper than gas miles but I wanted to know exactly. The battery is supposedly 9.7 kWh. When fully charged, the dashboard display shows me that I have 24 electric miles. That's about right on the highway but around town and on 2-lane roads I get more like 30. Anyway, not finding what I wanted and having a spare Photon, I built the following (with necessary engineering help):

Outside                              Inside   

Sensor – power wire through the hole

The sensor is called a "current indicator." The serious programming is in the Photon. A proto program allowed us to plot the relationship of raw analog sensor values to Watts -- turned out to be a nice straight line. I tested my laptop 45w power charger, a 75w bulb, a 800w toaster and a 1200w clothing iron. The real program takes 40 current samples (1 ms apart) each minute. The maximum value is added to a sum for the hour. The sums for the latest 24 hours are copied to a Particle "variable". That variable is read by a Raspberry Pi -- which produces a summary like this (via a simple PHP program):

    Hr 16: 0.16
    Hr 17: 1.39
    Hr 18: 1.4
    Hr 19: 1.39
    Hr 20: 1.39
    Hr 21: 1.39
    Hr 22: 1.39
    Hr 23: 0.68

    Sat 12/14  kWh: 9.26, cost: $0.83


Michigan Consumers Energy kWh rates for electric vehicles
Oct thru May -- Off peak: .090, On: .103
Jun thru Sep -- Off peak: .085, On: .123

Peak hours: 11:00 up to 19:00

The record above runs from 4pm till midnight for December 14. So I'm paying nearly 3.5 cents per electric mile. At my local $2.60-ish gas per gallon and the Kia's 45 mpg in hybrid mode (under 6 cents per mile) I'm not saving a lot. Gas should be way more expensive. Of course, I only stand out in the cold to pump gas once every 900 miles. 

 I will be accumulating data and will update this page.

* 12/20: Turned out that the Photon interfered with my wireless garage door buttons. Moved it 15 feet away and to different circuit -- now works ok. But why? Very different wireless frequency.

Friday, June 21, 2019

64: Adding a WIFI Antenna to a Photon

I've been having trouble with Photons remaining connected to the cloud. This in a place where an iPhone is ok (1/2 bars). So I started recording signal strength with this line of code:

  int wf = WiFi.RSSI();

Note that if you don't assign the value to an int first it will be treated as unsigned in an sprintf function "%d". Bug!

Anyway, the signal values returned run like this: (good to poor strength range: 1 to –127)
  • -10 -- strong/right next to the modem,
  • up to -60 -- reliable signal,
  • up to -75 -- so-so,
  • over that -- unreliable.

According to Particle Docs, these STARTUP calls control antenna choices:

  //STARTUP(WiFi.selectAntenna(ANT_INTERNAL)); // selects the CHIP antenna, default?
 //STARTUP(WiFi.selectAntenna(ANT_EXTERNAL)); // selects the u.FL antenna
 //STARTUP(WiFi.selectAntenna(ANT_AUTO)); // only works with antenna attached?

Note those statements are all commented out because they seem ineffective. But the good news is that adding a simple/cheap antenna does work* -- to the tune of improving signal strength by 10 to 15.

Another Particle complaint: the Docs generally fail to specify default return values.

_________
* The tiny snap-on connector can be frustrating.

Tuesday, July 10, 2018

63: A Nasty Relay Board Insulation Problem

See my Raspberry Pi Blog post 118 (at dicks-raspberry-pi.blogspot.com). Seriously!

Wednesday, January 10, 2018

62: A Better Mousetrap (I mean breadboard)

Regardless of my resolve, my breadboards always end up a mess. And, if you've read my previous posts, you'll know I hate soldering. So I'm always looking for the secure but easier way to wire things. Here's my latest idea.

Imagine a breadboard where the pin holes on the normal top pass through to the mirror holes on the bottom (I tried with a current breadboard, but the metal row connectors get in the way).


Here's a rough sketch:
Anyway, with the mirrored breadboard, wiring can still be easily changed but the wires are protected. I'd be willing to pay a few extra $ for this breadboard.

Sunday, November 26, 2017

61: Hoop House Rollup Motors

I described this system back in post 56. I meant to get this done early in the summer but things got in the way. I had 4 hoops to do and would have preferred to just install one first to get the wrinkles out but because it was already September I did them all at once. And we got to experience the problems times 4.

Here's what the smartphone web page looks like at the moment:
                                                                                  
Hoop fmX Sidewalls:
9:50PM: Hoop Temp: 40°
Auto Temp: OFF
Motors: Left=DOWN, Right=DOWN
Weather: Temp: 38.8°, Wind: N 1.1 MPH

Change?
Auto Temp Mode: Turn ON

Both Sides: Roll UP

Left Side: Roll UP

Right Side: Roll UP

Stop Motor!

Reload Page
                                                                                  

Here's a pic of a motor and the 196' long rollup pipe:


In the web page: info above the word "Change" shows the current state of the system. If you click any of the next 4 items below that the wording will change accordingly.

Here are some of the problems I have run into:
1. We had to use WIFI extenders because of the distances involved. It took a few tries to get them placed properly.
2. Flakey Internet service caused me to add manual UP/DOWN buttons to the Photon system enclosures.
3. Two of the 4-port relays I use to switch the 24v DC between the wires to the motors have failed.
4. The ACS714 current sensors are a disappointment so far. The analog readings are inconsistent (as they are currently wired). This means that rollup/down operations have to use worst-case wait-times. Very irritating.
5. It turns out that the rotation settings on the motors have to be adjusted after a few up/down cycles. Perhaps because wrinkles in the plastic get smoothed out with the uniform running speed of the motors.
6. Adapting the motor shafts to the hoop rollup pipes was challenging.
7. Getting  "Auto Mode" to work properly was a trial. At first I had the auto UP temperature too close to the auto DOWN temperature. So, the sides roll up, temperature drops immediately and the sides roll back down; over and over. Placement of the temperature sensor is tricky and the UP/DOWN thresholds have to be over 15 degrees apart.
8. Local temperature and wind is boiled-down from wunderground.com for the zip code. It is updated every 15 minutes by a Raspberry Pi.
9. An Rpi running Particle-agent sends and receives messages (via publish/subscribe) from the Photon systems.

More to come.

Sunday, September 3, 2017

60: Particle Photon Esoteric Hints 
(must previously have installed particle-cli)

1. When your Photon is not ready to accept a new flash: If (as I do) sometimes purposely load a program that is meant to run without the cloud then you can have a problem when you need to flash new software -- because the Photon is not connected. The following info is in Particle Docs, but not all in one place.

a. To get back to "breathing cyan" so you can flash:

Hold down RESET and SETUP, release RESET and continue to hold down SETUP while the main status LED blinks magenta until it blinks yellow, then release.


b. Then load a sketch that exists as part of the particle-cli package. In Terminal app on Mac OS:

$ particle flash --usb tinker # Photon connected to USB (of course)

It's not that you want to use tinker. It's just harmless software that allows you to then flash your own code.

2. What if you want to set up a Photon for a wifi network that is elsewhere?

a. First, the device must be in "Listening Mode". To do this hold down the SETUP until the RGB LED blinks blue.

b. Of course the Photon must be plugged to a USB port. Here's the command:

$ particle setup --usb
(output back: blah, blah)
Claim code set. Now setting up Wi-Fi
...
Attempting to configure Wi-Fi on /dev/cu.XYZ
? SSID name-of-the-network
? Security Type WPA2 (selected, not typed)
? Cipher Type AES+TKIP (ditto)
? Wi-Fi Password your-pw
Done! Your device should now restart.
! It doesn't look like your Photon has made it to the cloud yet.
? What would you like to do? Check again to see if the Photon has connected
... (took a while)
> It looks like your Photon has made it happily to the cloud!

And so you've made it (with luck).

3. What about where several Photons are running the same program but you need to identify them individually? You could do this messily by using a C++ "#define" statement -- a 1 line source change for each Photon: pretty certain to lead to errors. A better way would be to get the Particle cloud to tell your program the device name that you gave the Photon. It would be nice if Particle provided a call like: "Particle.deviceName()" that returned the name as a char array. The good news is that you can get the name but it is not so straightforward. Here's code that works:

char DevName[20];
...
void getname(const char *topic, const char *data) {
    strcpy(DevName, data);
}

void setup() {
    ...
    Particle.subscribe("spark/device/name", getname);
    Particle.publish("spark/device/name");
    delay(5000); // DevName won't get filled in for several seconds
    ...
}

Note that while Particle lost use of the name "spark" a couple years ago they have never changed all of the sparks to particles. Not nice, Particle!

Wednesday, May 3, 2017

59: Particle Photon "Persistent Data"

Up till now I have handled the problem of getting data to persist between reboots by sending it daily to-and-from a Linux (Raspberry Pi) system. And I will continue to handle Daylight Savings that way. But now I'm going to try Particle's EEPROM memory storage scheme. The Photon provides 4096 bytes of flash RAM that presumably/seems-to persist between power outages. The hitch is that you have to manage storage space allocation on your own. So if you want to store a C++ int you have to know to offset the next variable by at least 4 bytes (higher number). Reminds me of my first assembly language compiler from 1961.

Here's a sample program.

#define VAR1 0 // first address in eeprom -- 32-bit int
#define VAR2 4 // leaving room for the previous value
int Var1;
int InitialValue = 123; // whatever...

void setup() {
EEPROM.get(VAR1, Var1); // copy from eeprom to RAM data
if(Var1 == -1) { // hex "FF"s first time, not initialized
   EEPROM.put(VAR1, InitialValue); // load starting value
   ...
}
 // might also want to check for reasonable "get" value!
}

void loop() {
// use or change eeprom values as needed
}

More/better info at--
https://docs.particle.io/guide/getting-started/intro/photon/
Search for "EEPROM".

Sunday, March 12, 2017

58: Time Change Season

March 12, 2017 (first day of daylight savings): I use Particle Photons to monitor and control things at my granddaughter's hoophouse. One Photon reports 3 temperature sensors, 2 soil moisture sensors and 1 humidity sensor. A second Photon (50 feet away) controls 2 irrigation valves. It also switches a powerful electric deer fence that surrounds the 12-acre volunteer-staffed garden area. The fence is turned on at 6pm and off at 7am -- eastern U.S. time, modified by daylight savings. Months ago, I complained to Particle that their built-in Time functions failed to provide a "daylight time" indicator. This is something that every UNIX or Linux system has provided for many years. Anyway, I was surprised recently to find a new (unadvertised, firmware v0.60 added) function "Time.isDST()" which is supposed to return 0 for Standard and 1 for Daylight. So last night I ran a program just to check on this new feature (my Photon running v0.61). Well, 2am came and went and Time.isDST() still returns 0 -- as it does now at 4pm. Luckily, I was still providing time zone info from a Linux computer that sends EST or EDT every day at 3am. (Has to be done every day because a power outage restart can happen at any time.

Friday, March 3, 2017

57: Photon Error Recovery

Recently I compiled and flashed source with an error not detected by the compiler (I accidentally backspaced away the proper length of a "char" array variable). When the program ran I had just 1 second until the program wrote too many characters into the variable. As it happens, this caused a "Hard Fault" (see Particle Docs Guide).

I fixed my source error but could not flash the new version--the Photon switched to blinking red too quickly. I eventually went through the "Safe Mode" actions (a few times). I had the "particle" command loaded on my iMac. The thing that finally worked (in Mac Terminal) was--

First, hold down both the SETUP and RESET buttons. Then release the RESET button and wait for the LED to blink YELLOW. Then:

$ particle update
$ particle flash --usb tinker # Photon wired to USB port!

I wasn't interested in tinker but it allowed me to flash my corrected code.

My advice: do the Safe Mode and skip directly to USB download. Save yourself an hour.

Friday, February 17, 2017

56: Hoop House Temperature Control

A hoop house is the plastic film version of what was once called a greenhouse. These things can be big: 30' by 200', for instance. They can get overheated in the sunshine. I have two granddaughters who have become farmers. Between them they have 4 hoop houses. The daily temperature range inside a hoop house can vary by 70F (e.g., 50F to 120F -- these places are not kind to electronics). Vents with fans are an obvious way to prevent overheating but that spins the electric meter. So the common way to control the temperature is to roll up the plastic film sides. This is generally done with hand cranks. But you have to be on-site to do it. There are also slow-rotating DC electric motors to do the cranking but generally you still still have to be there. I have built and programmed Photon microcontrollers to help keep track of things in a hoop house. This currently includes multiple temperature and humidity sensors, soil moisture sensors plus control of irrigation valves. The user interface is a smartphone oriented web page. For the moment, you can see this at http://afarm.farmiot.net

This saves my granddaughter some concern and some work but the big saving would be to automate the roll-up/roll-down of the hoop sides. So I bought a couple motors from China (the only place they are manufactured, I think). The instructions seemed to be from auto-translated Chinese. Nearly useless, but I mostly figured things out. The nicest feature of the motors is that they have a mechanical limit that protects against over rotating. The idea is that you set (by screwdriver) the physical number of rotations, then apply 24v to the red wire to rotate clockwise or 24v to the green wire for counterclockwise. There is no built-in feedback from the motors. Generally these things are controlled from a power supply that includes a simple 3-position switch:
clockwise / off / counterclockwise.
This power unit also contains an overload fuse: the roller can jam!

My current test setup includes the following:
2 rollup motors (rated 24v DC, 60 watts, about 3 rpm)
1 Power supply (120v AC to 24v DC, 150 watts)
1 4-relay opto-isolated switch
1 ACS714 Hall-effect current sensor (30 amp) spliced-in between the power supply and the switches
1 Temperature sensor
2 Override switches (down button, up button) in case of failure of Internet
UPS (battery backup) with enough juice to roll up or down
1 Particle Photon web-connected microcontroller (i.e., computer) that runs my test software

In small quantities, the motors are very pricy -- esp. shipping and "inspection" (whatever that means).

The ACS714 provides me some feed back from the motors. After extensive (time-consuming) testing, I can detect the following states:

a) motor running
b) motor stopped (the motor's mechanical dial stop setting reached)
c) motor jammed (my program will notice, turn the motor off and send a warning text message)

I still lack "real world" data about jamming since I won't actually install the first system until warmer weather.

Here's what I envision as the smartphone interface for 2 hoop houses/4 motors (subject to change):
password protected, of course

Tuesday, February 14, 2017

55: Use a Photon as an Arduino

"Arduino Mode": Who needs it? Well, I have -- a couple of times. Here are some reasons:

3. A Photon is a 32-bit computer. It is 2x+ faster and has 4x program memory. About the same footprint as an Arduino Nano.

2. Photon analog ports are 12 bits to Arduino's 10 bits = higher resolution readings.

1. Most important: So you can test a Photon setup before Internet has been installed. This is why I've needed Arduino-mode!

I recently had to try a Photon setup "out in the field" and ended up reprogramming it for a Nano. I commented out the Cloud stuff, re-did the analog values, found that I had an "int" overflow (changed it to "long". And had to move the breadboard wires to fit the Nano (and later back for the Photon).

So I complained to Particle and was advised to try MANUAL mode, like this--

SYSTEM_MODE(MANUAL); // this kludge has to be before setup()

void setup() {
    Serial.begin(9600); // you'll need to talk to it
    . . .
}

void loop() {

    . . .
    if(!Serial.available()) {
        delay(1000); // some number
        return;
    }
    // read a command
    ch = Serial.read(); // get 1st character
    if(ch == 'c') { // some value: switch back to connected
        // so you can later flash new code without reset
        Particle.connect();
    }
    . . .

So, for $19 you can have a bigger, better Nano.

Tuesday, January 31, 2017

54: Rangefinder Breakthrough?

Back in dicks-raspberry-pi.blogspot.com, post 68, I described my frustrations with rangefinders. I've moved on from my urge to create an electronic "white cane" for the visually impaired, but just maybe an adequate device is now available. It's described at
www.maxbotix.com/Ultrasonic_Sensors/MB7051.htm. Pricy though, over $150.

A secondary problem I mentioned in the old post was that an Arduino Nano wasn't fast enough to keep up with both the rangefinder and the 3-axis accelerometer. Well, if you replace the Nano with an equally small but faster Particle Photon that issue (probably) goes away.

Saturday, January 28, 2017

53: Particle Web IDE Failings

Complain, complain! I may have mentioned this before but I have an "issue" with Particle's browser-based program development. I'd give it an "A" for looks but lower marks for the rest.

The worst feature concerns error message feedback when you make a dumb mistake in source input (Sue me! I make mistakes). A recent example: for a 1-letter typo in a function name: 20 lines of error messages, none of which point out even the right line number. I've taken to copying such source to my on-line Raspberry Pi where I try to compile it with GCC; there, I can get a reasonable error message. Errors get an "F".

Another easy user mistake you can make: If you compile source meant for a Photon when the device you selected (usually left over from compiling days before) was a Raspberry Pi (or vice-versa) you get the usual slew of messages, none useful. Grade "D-".

When you have written 20 or so programs, the listing of their names can become an issue. Most recent sketch is always the bottom of the list (oldest to newest). You can't use alphabetical, newest to oldest, or best yet, be able to group them in folders. Grade "C-".

Saturday, December 17, 2016

52: About Particle Cloud for Raspberry Pi

I'm covering this in my RPi blog at:

http://dicks-raspberry-pi.blogspot.com/

See posts 108 through 110 (for the moment).

Saturday, December 3, 2016

51: Yet More About Relay Switches

I've discussed relays in earlier posts, but I keep learning more. I used 4 relays to swap cold/heat on a Peltier device. Now I need to switch polarity on 2 motors using a single Particle Photon. However, the Photon only has 8 digital GPIOs. My 4-relay plan would use all of them. So I asked around and came up with this arrangement:


This wiring works and takes only 2 GPIOs per motor. I tested with a multimeter. Here's a bit of code:

#define SW1  D1
#define SW2  D2
. . . 
void setup() {
   pinMode(SW1, OUTPUT);
   pinMode(SW2, OUTPUT);
. . .
}

void loop() {
. . .
    // blue wire +
   digitalWrite(SW1, HIGH);
   digitalWrite(SW2, LOW);
. . .
   // green wire +
   digitalWrite(SW2, HIGH);
   digitalWrite(SW1, LOW);
. . .
   // all OFF
   digitalWrite(SW1, LOW);
   digitalWrite(SW2, LOW);
. . .
}

Monday, November 28, 2016

50: Particle Cloud (Photon) Time Functions

PHP and C programmers, beware: day-of-week numbers start at 1 instead of Sunday==0. Also, there is no provision for Standard vs. Daylight time. At my granddaughter's farm, a Photon turns a powerful deer fence on and off. To keep from zapping workers, it is important that the schedule be reliable. I covered the Linux side of this at my Raspberry Pi blog (http://dicks-raspberry-pi.blogspot.com) post 91. Currently, (because of power-fail reboots) I execute a crontab statement every night at 4am (the code from post 91). If the UNIX/Linux world can keep the time change straight, then Particle could, too.


Saturday, November 12, 2016

49: IoT* for Farming

As I have mentioned in earlier posts I have put some Particle Photons to real work. Between them, my grandkids have 6 hoop houses (hoop houses are the plastic film version of the old greenhouses). So far I've only worked on one of them. I started out with a single Photon handling both the sensors and the switches. That was a mistake. The long-ish wiring runs were unreliable and the cables cost more ($90) than an extra Photon ($19).


So right now the 2 Photons work as follows:

Sensor-Photon: Connects to 2 soil moisture sensors**, 2 DS18B20 temperature sensors (stuck in ground for soil temperature), 1 DHT22 temperature/humidity sensor*** 3' off the ground.

Control-Photon: Keeps track of time, permits smartphone controls of 2 irrigation valves and a deer fence (enclosing 12 acres around the hoop house; normally on an automatic schedule, but can be overridden).

100 miles away, a Raspberry Pi running Linux keeps track of the Photons. This is mostly handled by tasks scheduled by the cron program. Note that I had planned to use a Raspberry Pi for all of this but the cloud access and Arduino-like ability with analog sensors made me choose Photons for the hoop house computers.

The main link to the Photons is a web page (optimized for smartphone) that reports on the sensors and allows control of the switches.

BTW: Turning things on and off requires login/password.

My next challenge is to provide web control for rolling up the sides of the hoop house. The hoop can be cooled by exhaust fans but that just runs up the electric bill. Rolling up the long sides of the house is effective and cheaper. My trial China-manufactured motors are being a chore to program (instruction manual computer-translated from Chinese?). This will be the main labor saver of my system, since the internal temperature will be controllable from a distance.

--------
* IoT (Internet of Things): This term doesn't really work for me.

** To avoid shorting out, the fork-shaped sensors wiring had to be coated in non-conductive caulk.

*** As mentioned in earlier posts, apparently humidity sensors stop working at 100% RH (I've tried several kinds). I finally had to put the DHT22 in a box with a tiny fan blowing on it. It still quits working at 100% but recovers in a few hours.

Friday, November 11, 2016

48: Particle.io Cloud Interface for Raspberry Pi

Among my "IoT computers" or "smart controllers"* (needs a better name) are 7 processors from Particle: 1 Core (now superseded by Photons), 5 Photons and 1 Electron.  Particle Photons are rather like souped-up Arduinos with built-in WIFI and cloud services. This cloud provides not only the expected variable/function and publish/subscribe services but other handy UNIX-like functions like date/time. Since the summer of 2015, I have had 2 Photons operating in the real-world in my farmer granddaughter's semi-automated hoop house. I had planned to use Raspberry Pi's for this but the Photon/cloud was just too handy. However, an RPi keeps track of things from 100 miles distance.

Anyway, back in August, I emailed Particle.io support that they should provide their cloud interface for the Raspberry Pi. I was probably not alone in this. And now, I just signed up for their beta-test RPi cloud interface. It should be very convenient for me and even if 1% of the 10M RPi's sign on, it should be a good deal for Particle.

---------
* I also have 4 Raspberry Pi model B (from earlyish to most recent) and 4 Arduino Nanos. To those not in-the-know, an RPi B is $35 (well, $50 with flash card, etc.); my Nanos cost $7 and Photons are $19. My Particle Electron (Photon with built-in cell modem) was time and $ wasted, for me.

Thursday, September 22, 2016

47: Did You Know?

—That your Arduino sketch can re-execute the setup function:

void setup() {
  . . .
  Serial.begin(9600);
  . . .
}

void loop() {
  // Some code
  . . .

}

So, if there is no serial connection when the Arduino powers up then the code will proceed to the loop. However, say you later connect to it with Coolterm (or equilalent command) then the setup will be executed again (for Serial.begin). I think it causes a hardware RESET.

Note that while a Particle Photon is Arduino-like, setup does not get re-executed in the above circumstance.

Probably doesn't matter, but it might.

Friday, September 9, 2016

46: Linear Stepper Motor -- More
-- revised 9/15/16 --

Below is a very messy circuit drawing for my Arduino setup. Should also work with Particle Photon or Raspberry Pi. It uses external 5V to power both the relay switch and the motor. The reason for the relay is that the steppers draw power constantly. So in my program when I want to move the linear screw I turn the power ON, delay(100), operate the stepper, delay(100) and turn the relay OFF. When you power a stepper off the rotor can move freely (no brakes). But with the linear screw that won't happen (its own friction). My cheap stepper has about a 3" movement. Even with counting steps, I will use a door/window sensor to recalibrate the initial position. I plan to use this to dispense dog treats. See post 41.

Revised: I bought a second EasyDriver and motor. They look exactly like the above. After the irritating soldering adventure I hooked it up to an Arduino Nano and loaded the same script that I used with the first pair. With the first set, 350 steps move the length of the spiral screw; the new one takes over 1500. No clue as to why.