Kotan Code 枯淡コード

In search of simple, elegant code

Menu Close

Tag: IoT

Project ZK: Full Remote Control and Spin Test

In my last post, I introduced you to Project ZK, my attempt at a miniature drone version of my armored Jeep. Getting the motors working and the initial wiring set up was a huge milestone, and I am really looking forward to the kinds of fun stuff I will get to do with this project in the future.

Recently, I altered the code of the Spark Core a little bit so that I could send it maneuver instructions like “turn left” and “turn right”. I didn’t realize it at first, but the Spark Core is limited to only four remotely invocable cloud methods. This meant that I couldn’t create a single method for every maneuver, so instead I had to create a single “command” method that accepts strings like:

LEFTTURN:25

Where the first term is the maneuver code and the second term is a parameter – in this case, speed.

Take a look at my spin test here:

This is my first attempt at utilizing all four motors to do a coordinated maneuver. Overall I think it turned out well. The slippery floor and ultra-low crawling speed make for a lot of wheel slipping and inconsistent grip, but this is really the only way that you can get 4 motors to turn left like this. I am thinking of experimenting with making the turn direction move backwards a few ticks slower than the non-turn direction moves forward, just to see if that helps make the turn a little smoother. That said, the turning capability is sufficient for now and I’m going to be moving on to bigger and better things. Eventually, I’ll be doing a field test where I rig up an Android app to control the bot and set it loose on an RC rock crawler course.

If you’re interested in following the code I write as I go, you can check out the project-zk project on Github here.

Project ZK: First Motor Test

This is the first of my blog posts on a project that I currently call “Project ZK”. In addition to being into the Internet of Things, programming, and all things tech, I also spend a lot of time off-roading in my heavily armored and modified Jeep – the “Zombie Killer”. The off-roading, rock-crawling drone that I intend to build is inspired by the zombie killer Jeep, which is why I’ve decided to call this “Project ZK”. Jeeps are often referred to by a 2-or-3-letter designation such as TJ, YJ, JK, etc. My big 4-door zombie killer is a JK, and so I’ve decided to label my little drone a “ZK”.

After experimenting with some small IoT projects, I decided to dip my toe into the deep end of the pool and get a 4WD chassis from Actobotics. I bought the kit from ServoCity, a site that should be banned purely for its addictive nature. I could spend all day on that site and never get bored.

The Actobotics chassis (and the corresponding plethora of accessories) gave me that same feeling I got when I was a kid working on the Erector sets (remember those??), only this time it’s an erector set for robots. You can get all kinds of channels, mounting accessories, bolts, and other equipment so you can add modules and things to your project without the need to start custom cutting aluminum or plastic.

Once I got it assembled and I acquired two RoboClaw 2x30A motors, I was ready to manipulate the motor controllers with my Spark Core. The only problem was I needed some serious wiring done, and I was in over my head. I didn’t know what gauge wires to use, didn’t know the best way to set up the motor controllers to be controlled as a serial bus, etc. For this, I turned to a good friend who runs the Heli Flight Center – this place is basically drone heaven.

With his expert guidance and skills, we were able to locate the two RoboClaw motors down inside the protected plastic portion of the chassis, wired them up to each other, set it up for LIPO battery supplied power, and even made some small Y cables to allow a single set of TX/RX wires coming out of the Spark Core TX/RX pins to manipulate the controllers via Packet Serial (more on the code in an upcoming post).

With this all in place, I was finally able to get enough code working to allow an internet-triggered motor self test to happen. To me, this is the drone hardware equivalent of “hello world”. Now that I know it can be told how to move, the real fun begins. Here’s a quick video showing the chassis in action during the self test:

Internet of Things: Spark Core Day 2 – Temp and Humidity

In my previous post, I took a look at how to wire up a Spark Core with a very simple analog temperature sensor. I decided to try and upgrade this to use a new sensor, a DHT22, which provides both analog temperature and analog humidity. It does this over the same pin, so reading the values is not only annoying, but it’s so ugly that I had to go searching for someone’s DHT Spark library.

Here’s a look at my prototype wiring:

Spark Core with DHT22 Temperature and Humidity Sensor

Spark Core with DHT22 Temperature and Humidity Sensor

What’s going on here is I’m running the 3.3v power to the far left pin (as you’re facing it) of the DHT22. I run the analog input wire from the second leg to the D2 pin of the Spark Core, and also use a 10k resistor between that pin’s wire and power. This is yet another example of where I have no idea why something works, but there is a magical special sauce recipe here at play. I don’t know why I need that 10k resistor where it is, but I do. Without it, the value of the temp and humidity alternates between 0 and 99999. I think that because of the fact that reading values from the sensor is timing based, you can screw up the timing if the voltage isn’t crisp, clean, and at a specific value. In other words, noisy or excess voltage messes up the timing, which messes up the reading of the sensor values.

I liken this to someone sending the temperature value at night with a flashlight using morse code…except that the recipient blinks at exactly the same time as the sender turns on the flashlight… making it seem like nothing is being transmitted.

In my opinion, this is asinine. The way the code works is it sets the analog pin high, then waits 250ms. It then performs a series of reads on that same pin, spaced by microseconds, pulling a single byte at a time, with a microsecond delay between reads of bytes. This just feels like too much busywork, but my perspective is from years of using high-level software libraries, not low-level hardware. Maybe Arduino folks are used to this kind of thing, but for me, this is 2015, and even cheapass $2 sensors should be able to emit analog results without being so sensitive to timing issues. Of course, since no one has been able to explain why this wiring works the way it does, this is pure conjecture.

Anyway, I then set up two Spark cloud variables so that I can query the value of my sensor remotely from anywhere in the world (provided I have Internet access on said remote, bond-villain island):

Spark.variable("temperature", &t, DOUBLE);
Spark.variable("humidity", &h, DOUBLE);

With these variables in place, I just update them about every second or so inside my loop() function. Also anecdotally, I discovered that you can’t really access the value faster than once per second, because that can also cause problems. And with everything else I’ve found related to this – nobody can seem to agree on the proper wiring or proper code for interfacing with this, nor can people agree on how fast you should access the value. There’s nothing I dislike more than crap that works, but nobody knows why or how it works. Magic bothers me.

While debugging this code, I encountered a number of variants in both wiring and code that resulted in either non-existent or erroneous measurement values. To debug it, I used the Spark core’s serial functions, which allow me to print out values to the “serial port”. The serial port, in this case, is a virtual com port that is created when a Spark Core (that has firmware on it that calls Serial.begin(baudrate)) is plugged into a USB host. If your Spark Core firmware never invokes Serial.begin, then this virtual COM port will not be created when the device is plugged into your computer’s USB port.

In my case, since I’m on a mac, plugging this Spark into my USB created a virtual com port at /dev/tty.usb(stuff) where (stuff) will vary depending on your system, so just look at your directory for tty.usb*.

To watch the output being sent from the Spark on this serial line (on a Mac), just issue this command at the terminal prompt:

screen /dev/tty.usb(Stuff) 9600

Now you can watch the trace/debug output from your core. I’ve found this particular troubleshooting method to be invaluable.

Internet of Things: Spark Core Day 2 – Internet Thermometer

In my first blog post relating to using a Spark Core, I was controlling LEDs from my phone over the Internet, essentially using the cloud to control lights. It still boggles my mind to think that something I built (hardware! from a software guy!) could attach itself to WiFi, and allow itself to be remotely (and securely!) controlled from a handheld device. Fantastic!

In my slow and steady quest to determine how I can use Spark Cores to take over the world and become a James Bond Supervillain, my next step was to figure out how to rig up an analog sensor, as shown in the picture below:

Spark Core with a Temperature Sensor

Spark Core with a Temperature Sensor

I used the temperature sensor that comes in the Spark “maker kit”, which is basically a Spark Core (the Photons ship next month) in a box along with a pile of sensors, jumper wires, resistors, capacitors, and other doo-dads. Following the example that Spark has up on their website, I rigged up the breadboard as follows:

  • 3.3* power pin to the left leg of the temp sensor (there’s a 3.3V and a 3.3*V, and Spark’s instructions indicate that 3.3* gives you a cleaner power, but there’s no explanation beyond that. As a software guy, I have no idea what the hell that means, so I remain in lemming mode and do as I am told without question).
  • GND to the right leg of the temp sensor
  • Analog pin A7 to the middle leg of the sensor.

So I rigged all this up, flipped the switch, and much to my surprise, I got a temperature reading. However, the reading was around 140C, which is actually pretty damn hot. I thought it was something I screwed up, so I wiggled wires, touched the sensor, and burned the living shit out of my finger. So, my reading was accurate. 140C felt about right as I stuck my finger in a tub of butter.

I quickly unplugged the Spark and let the breadboard sit for about 10 minutes to cool down. Once it had cooled, I checked and re-checked the instructions on Spark’s website and compared my work. It all looked good, except the rounded edge of the temp sensor was facing the wrong way. I flipped it around and turned the Spark back on.

No heat. This time, nothing heated up. I checked the temp reading and got 11C. Checked again, got 23C. Checked again and got 12C. I kept checking and I kept getting widely varied readings. But, I wasn’t burning the house down, so that’s a bonus.

From this I can only gather that the temperature sensor has a specific positive and negative leg and I had them reversed. Of course, none of this is labeled on the sensor, nor is it mentioned on the Spark website examples. I’m sure electronics guys know this, but absolute newbs like myself are likely to catch themselves on fire if people don’t mention these crucially important details. It’s also pretty damn annoying if the sensor can only accept positive in one place and that place isn’t labeled.

So now, with my temp sensor no longer dangerous, I followed Spark’s instructions and added a .01u capacitor to the breadboard rail between pin A7 and ground. They say that this stabilizes the erratic or “noisy” readings from the temperature sensor. However, they don’t tell me why this works, or why this sensor might need it and others won’t, or why a .01u capacitor works but a .1u capacitor will cause the sensor not to provide any data at all. This crap infuriates me! I need to know how crap works and why it works, not just that it works. I question everything, and dislike when answers are not readily available.

Now, after correcting the polarity (I couldn’t help but laugh at the irony that I had literally solved a problem by reversing the polarity in classic Star Trek fashion) I was able to query the temperature of my sensor using the cloud.

An Internet thermometer!!! Next step – world domination.

Internet of Things: An Internet Button with a Spark and a Pi

The other day I decided that I needed to get out of my new comfort zone of controlling LEDs over the web (that crap never gets old, trust me.. I toggle those lights all day long, so much so that it annoys my family). My next project was going to involve input. From what I could tell, the easiest form of input is a button. So, I rigged up a button to my breadboard and Raspberry Pi, as shown in the following picture:

Button on a Raspberry Pi's GPIO Board

Button on a Raspberry Pi’s GPIO Board

Wiring:

I first put the button on the breadboard so that it straddled the empty canyon in the middle, which means each of the sets of legs (I’m sure experts would call them terminals or something cooler than “legs”) are on separate sides of the breadboards. This is important so we don’t allow current to flow between two legs in the same row. I then ran a jumper wire from Pin 24 on the cobbler (you could use Pin 24 right on the GPIO, too) to one of the top terminals on the button. Then I connected the 3V3 power pin from the cobbler to the positive power bus on the breadboard.

I connected one of the button’s terminals to the power bus and the other terminal right above that to ground with a 10K resistor. From what little this software guy knows about how this all works, the button input works by letting us query whether the button is connected to the 3.3V source or to ground. Things get ugly and messy if it is floating somewhere in between, what us software guys would jokingly call a “tri-state boolean”. So, we put a resistor on the terminal to connect the input side of the switch to ground. One lesson I have learned that seems to apply here is that electricity follows the path of least resistance, so when we push down on the button, current will flow to the input pin and not to ground (which is a path of much higher (10K, actually) resistance. The main reason for the resistor is we want all of the current to flow to the input pin, so it detects full voltage and not some fuzzy state in-between ground and 3.3V.

I like to think of resistors as dams that slow or control the flow of water. I realize this could be a stupid analogy, but, I’m a software guy.

Finally I ran a jumper from the cobbler’s GND to the ground rail on the breadboard.

Next it was time to write some Python code that did something useful when I pushed the button. In my case, I wanted to wait for the first detected button press and then send an HTTP request out through the Spark Cloud to my Spark Core, which would tell the spark core to light up … An internet button!

Here’s a rough sketch of the Python I used:

import RPi.GPIO as GPIO
import time
import os

GPIO.setmode(GPIO.BCM)
GPIO.setup(24, GPIO.IN)

while True:
    inputValue = GPIO.input(24)
    time.sleep(0.3)
    print("Pushed a button!!")
    os.exit()

The sleep in there was there to keep the poller from detecting multiple presses while the button is held down. Polling for the button state is a kind of fuzzy thing that chafes my deterministic software engineering side, but I know there are better ways to code for this that I’ll likely get to in the future.

So, I now had my code and I executed it on my Raspberry Pi. I pushed my button, the message went out over the cloud, and the lights on my Spark Core lit up!! I squealed with geek joy, and am now plotting my next project: exposing an analog sensor to the cloud.

 

Internet of Things: Spark Core Day 1 – Controlling LEDs via the Cloud

In my last post I went through my initial experience in unboxing, configuring, wiring, and coding for the Raspberry Pi 2. Overall that experience was positive, though I still think that companies like Adafruit need to be aware of the fact that when you sell something labeled a “Starter Kit”, and market it for educators and kids, that shit should work out of the box. There’s absolutely no excuse for shipping outdated SD cards 2 months after the latest version of Raspbian that is required to work with GPIO.

Anyway, next up on my list of Internet of Things experiments was the Spark Core. This thing is mind-blowingly remarkable: It’s a tiny little microcontroller that has a built-in WiFi antenna, but more importantly, it is backed by the Spark Cloud, which allows the device to phone home, be remotely addressable, remotely flashable, and expose its own firmware as a cloud-based API. It makes every single one of my geeky senses tingle.

My unboxing experience was pretty straightforward – I opened the box, saw the tiny microcontroller and it’s accompanying breadboard, and I squealed with joy. I immediately ripped the LEDs and resistors out of the previous Raspberry Pi 2 cobbler prototype and stuck them into the Core’s breadboard.

I then opened up a web browser to start coding the firmware for the Core. That’s right, the core can be flashed remotely over the webfrom anywhere, using a browser. You really need to sit back and take a moment to let that concept marinate a minute. This ain’t your old fashioned microcontroller where you have to plug it to a special EPROM burner to flash it. This thing is absolute genius. It is a thing of beauty, and technologically badass.

Using the Wiring programming language (should be familiar to anyone who has written code for an Arduino before), I then wrote a bunch of code to expose functions to the cloud that turn on and off a red LED and a green LED. The picture below shows the Spark Core and its breadboard with my LEDs off:

Spark Core with LEDs Off

Spark Core with LEDs Off

And this shows the same thing after I have used my iPhone to send the secure HTTP messages that manipulate my core via the cloud:

Spark Core with LEDs On

Spark Core with LEDs On

To recap: From unboxing to the point where I could control my Spark Core over the web, from anywhere, to remotely manipulate LEDs via the cloud… took me about an hour and a half. There are no words to describe how freaking amazing that is.

I can’t wait to start messing with sensors and inputs and branch out from just LED control!

Internet of Things: Raspberry Pi 2 Day 1 – Controlling LEDs

When I was 10 years old, I visited my grandfather’s house a lot. I remember these visits like they were yesterday, even though they were *cough* years ago. I used to sit in awe of his garage. The man was a maker before that term had the connotation it does today. He had oscilloscopes, wiring diagrams neatly tacked to walls, thousands of little drawers filled with tiny little pieces that I didn’t recognize then but I know today as the basics of electronics – resistors, lights, buttons, soldering wire, and myriad components.

He had patents for devices he invented like the Kensico Air Mite – a device that could listen to the radio traffic of planes as they flew overhead. When I was bored, instead of sitting me in front of the TV, he sat me in the middle of his garage with a hammer, nails,  and wood and said, “Build something“. So much of what makes me the man I am today was inspired by him, including my insatiable desire to build something.

So when I opened by Raspberry Pi 2 (the quad core, 1GB RAM successor to the original) I was excited. It took me back to those days in my grandfather’s garage, making crap I knew wouldn’t work but it didn’t matter. The fun was in the building, in the act of creating something new with my own hands, my own intellect.

I fired it up with the install image that shipped from Adafruit, I wrote 4 lines of Python code, and then I was hit in the face like a kid on Christmas morning who got a lump of coal instead of that He-Man figure he’d been waiting for all year. The console rejected my code, complaining that “This module can only be run on a Raspberry Pi!“. I am running a Raspberry Pi you shitforbrains! I yelled at my tiny little computer. When the white-hot rage finally cooled enough to allow me to type, I hit the interwebs and found that even though these devices are supposed to be shipping to kids and educators and beginners, most of them ship with horribly outdated boot images that don’t even work properly with the GPIO boards (I’ll discuss that later, but that’s basically the thing that lets you control devices and components… you know, the reason I bought the Pi2). Shame on you, Adafruit. That’s just pure laziness. I downloaded NOOBS (New Out of the Box Software) from here and created my own replacement boot image on an SD card. The first “normal” teenager who has to do that is going to walk away and never finish.

Now, with my new (properly functioning) boot image in hand, I connect up my breadboard as shown in the following picture:

Raspberry Pi 2 Wiring with a Cobbler and Breadboard

Raspberry Pi 2 Wiring with a Cobbler and Breadboard

For those of you who don’t know what’s going on here, I’ll explain. The rest of you can skip the next few paragraphs.

A breadboard is basically a replacement for soldering. Instead of permanently connecting the pins on your Raspberry Pi’s GPIO (General Purpose I/O) board to LEDs, motors, and sensors… you can just plug stuff into the breadboard for prototyping. What you see in the picture above is a ribbon cable (basically 26 wires stuck together) coming off the GPIO board and sticking it into the breadboard. This basically lets me act as though all those pins are connected directly to the breadboard.

The ribbon cable is hiding it but I have male-to-male jumper wires plugged into the breadboard holes adjacent to the pins in the cobbler (the chip at the end of the cable) for pins 7, 11, and 13. In my case, I’m using the board numbering system for pins which starts with pin 1 at the top left, pin 2 top right, and so on until pin 26 at bottom right. There are other, more complicated, numbering systems that have more meaning to actual hardware people but I’m not really a hardware guy so I’m using the “easy mode” numbering system.

From pin 7, I run a jumper wire to the same row as where I have plugged in the positive (long leg) lead on the end of my red LED. I run a similar wire from pin 11 to the row where I have the positive leg of the green LED. Finally, I hook up the blue LED to pin 13. I then run a resistor from the negative leg to the ground (the black vertical rail on the far edge of the breadboard). Because I have this same ground rail plugged into a ground pin on the cobbler (pin 6 in this case), this is allowing me to complete the circuit. The resistors are, according to more hardware-oriented people than myself, there to drain off excess current so it doesn’t, and I quote, “set the Pi2 on fire”.

As an aside, I chose 7,11, and 13 because they are valid to be used as output. Pin 9 cannot be used as output.

So, with my bread board hooked up and a complete circuit created, I power on my Pi and get into a console mode and I create the following Python file:

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.OUT)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)

GPIO.output(7, True)
time.sleep(1)
GPIO.output(7, False)
GPIO.output(11, True)
time.sleep(1)
GPIO.output(11, False)
GPIO.output(13, True)
time.sleep(1)
GPIO.output(13, False)

This essentially lights up each of the LEDs for 1 full second, and then turns it off and moves on to the next LED in the line, lighting it up for 1 second, etc.

If you take a look at the following video (QuickTime MOV file), you’ll see a short clip of this in action.

Raspberry Pi 2 LEDs in Action

You might be looking at this and thinking, big deal, this moron turned on some LEDs. Anybody can do that. And, you would be right. Anyone can do that. THAT is the point. The point is that for under $100 of consumer-grade, publicly available parts with no prior knowledge of electronics, hardware, or software, someone can get to the point where they’re writing code that manipulates external components in short order.

While turning on LEDs from a Raspberry Pi might not seem to be that important, the fact that I can write code that can interact with hardware and do so on a remarkably cheap, ultra-portable device with full networking capability is ground-breaking. This is my first foray into the world of The Internet of Things, and I’m pretty damn excited.