My Pi Description

My Experiences With the Raspberry Pi -- Tracking My Learning -- My Pi Projects

Sunday, June 15, 2014

DS18B20 Temperature Project For Gertboard/Arduino

Some time ago I became rather fascinated with the Maxim/Dallas DS18B20 temperature sensor. I bought a couple and connected them to my Pi. This blog has tracked my progress with the little device, starting with the four posts of June of 2013:
Then, the October, 2013 post: Finally, the November, 2013 addition:
That project became very useful and I learned a lot. However, I had a couple of issues. I did not think it was suitable to tie up a general purpose microprocessor (the Pi) with a connection to a couple of sensors. I was disappointed that the driver did not support all functionality of the device like choice of resolution. There also seemed to be a stability issue. About half of the measurements resulted in a CRC failure requiring measurement repetition.
I thought the sensors should really connect to a microcontroller like the ATmega328P. Once programmed, the microcontroller could be lifted off the programmer and placed in its own circuit board in an enclosure. I did this for my camera remote control project back in January of this year.
Thus was born my concept for a very involved project. Here are the design parameters I set for myself:
  1. Connect multiple sensors to an ATmega328P microcontroller.
  2. Design for a hypothetical industrial application where many DS18B20 temperature sensors may be employed.
  3. Store the 8 bit ROM code and a 12 character (max) description for up to 50 devices.
  4. Use the ATmega's 1 kbyte of EEPROM to store the ROM codes and descriptions.
  5. Use the Arduino IDE to develop the code.
  6. The "programmer" will be the Gertboard connected to the Raspberry Pi.
  7. Write my own 1-Wire interface library incorporating all of the DS18B20's functions found in its data sheet.
  8. Remove the ATmega microcontroller from the programmer and install it on a circuit board within an enclosure.
  9. Connect a 16 character by 2 line LCD display to the microcontroller to display temperature and device number.
  10. Connect several switches to the microcontroller for simple menu control.
  11. The microcontroller and the Pi to communicate wirelessly.
  12. The Pi will serve as a "front end", with a menu driven choice of operations to be carried out by the microcontroller.
  13. Temperature measurements returned by the microcontroller to be graphed by the Pi using RRDtool.
I've been working on items 1 - 7.
If you are interested in this project it is important to be familiar with the DS18B20 device and the 1-Wire interface. Maxim has an excellent data sheet describing the functionality, programming commands, and timing requirements. It can be found here.
I wrote my own 1-Wire library for Arduino/Gertboard. You may ask why since the Arduino IDE comes with a 1-Wire library already included. I simply wanted the challenge of doing it. I also wanted to present the library to others with code and comments that anyone can understand. However, if you use the Arduino built-in functions like pinMode(), digitalWrite(), and digitalRead() to control your microcontroller I should tell you that I do not! I use ATmega direct register programming. I have tutorial at this blog entry that explains the difference and how to use direct register programming.
My 1-Wire library only covers the DS18B20 temperature device. If it covered all of the Maxim devices, I would have to purchase one of each and test that it works with my library. I'm not going to do that - I'm only interested in the temperature sensors. There are a couple of other temperatures sensors and they probably will work with my library. Actually, there does not seem, to me, to be a reason to use any of the other Maxim temperature sensors. I could not see any advantage to them. At present, my library is not quite complete. Here is the status of the functions I have completed. The names are taken from the command names in the data-sheet:
  • Initialization - Done
  • Search Rom - Done
  • Read Rom - Done
  • Match Rom - Done
  • Skip Rom - Done
  • Alarm Search - Done (updated July 3)
  • Convert T - Done (updated June 18)
  • Write Scratchpad - Done
  • Read Scratchpad - Done
  • Copy Scratchpad - - Done (updated June 22)
  • Recall E2 - - Done but not tested (updated June 22)
  • Read Power Supply - - Done (updated June 22)>
  • Compute CRC (this function is not listed as a separate command in the data sheet) - Done
I have not incorporated parasitic power. This really only effects Convert T at this time. I will get to that after I sort through my supply of old parts and find a suitable transistor to pull up the bus connection to Vcc. When that occurs, I will augment Convert T to handle parasitic power. I plan to complete the four functions I have not started. I have incorporated parasitic power into the project as of June 18.

A disappointment with the Gertboard and the ATmega EEPROM

I simply could not store data in the ATmega's EEPROM when the ATmega is installed on the Gertboard. After writing to an EEPROM address, a read of that address always resulted in reading 11111111 - which is the cleared state. I spent about a week trying various programs. Nothing worked.
I explained my problem on the Classic Gertboard section of the Raspberry Pi forum. A very knowledgeable fellow from the Netherlands really tried his best to help me out. We had quite a few conversations on the forum. Gert van Loo, the developer of the Gertboard chimed in a couple of times. I really thank them for their help. Ultimately, nothing worked for me. I think the one person who could have solved the problem, Gordon Henderson of Gordon Projects, did nor respond to my email. Gordon developed the means to use the Arduino IDE with the Gertboard.
I really wanted this EEPROM access to work so I purchased an Arduino Uno, mainly just to see if my code would work at all. I connected the Arduino to the Pi and used the same Arduino IDE as I used with the Gertboard and it all just worked. My guess as to why it does not work with the Gertboard is the difference in how a sketch is uploaded to the ATmega chip. With the Arduino, one selects "Upload", but with the Gertboard, "Upload Using Programmer" is used. I have a feeling that the latter clears the EEPROM (writes all 1's to all bytes) before uploading. Now, one of my design parameters has changed. The project is off the Gertboard and onto the Arduino. Furthermore, my Arduino is now disconnected from the Pi and connected to my Windows PC. I take advantage of the much faster environment, ease of printing, and easier access to my githup repository allowed by the PC.
As of this time, I have the library mostly written, as I discuss above. I wrote several Arduino sketches to check out the library and make the sensors useful. Now, everything runs on the Arduino - the Raspberry Pi is not involved. I have not added the lcd device - that will be next.

Github Repository - Library and Sketch Files

I spent about a day learning about github and created a repository for this project. The repository can be found here.
The repository includes three libraries:
  1. EEPROM_Functions library - functions used to read from and write to the ATmega EEPROM.
  2. InputFromTerminal library - to input floating point or integer numbers from the serial monitor.
  3. One_wire_DS18B20 library - all the ROM Commands and DS18B20 Functions as called out in the DS18B20 data sheet.
In the repository, the directory "DS18B20_Temperatur_Sensor" contains the sketches to read temperature, scan for new devices, and manage the devices in EEPROM, etc. They include the following individual sketches:
  • "Read_Temperature" - Asks user what devices to run, number of measurements, and time between measurements. Function determines if devices are connected using parasitic power. Measurements are made accordingly. User has the option to print out the temperature limits as well as the resolution along with the temperature. Once the run is made, displays the average of all measurements for each device. If there were any CRC errors or initialization errors, the number of these are reported. If a device is connected using parasitic power, when the device is undergoing the convert temperature process, a transistor pulls the 1-wire data line up to Vcc. The time for this "hard pullup: is dictated by the data sheet for the resolution programmed into the device's scratchpad. For devices not connected by parasitic power, when undergoing temperature conversion, the device, itself, informs the bus when the conversion is done.
  • "Scan_for_Alarms" - Scans the 1-wire bus to see if any device's temperature is out of limits. If so, displays that information to the user. This function must determine if the device is connected using parasitic power.
  • "Find_New_Device" - Scans the 1-wire bus to see if any device has been added. If so, asks user for a description which is stored in ATmega EEPROM along with the ROM code. Asks user to input upper and lower temperature limits and resolution. These are stored within the device's scratchpad and the device's EEPROM
  • Devices_On_The_Bus - Uses library search_rom() to report to the user all devices it finds on the 1-Wire bus along with their ROM codes. It also reports the result of the CRC of the ROM codes.
  • "Devices_in_EEPROM" - Displays all devices in the EEPROM along with their descriptions.
  • "Edit_Stored_Information" - Reports to user the ROM code, description, upper and lower temperature limits and resolution for each device on the 1-wire bus. Asks user which device to change and what to change. Changes are made accordingly, and stored.
  • "Remove_Device_From_EEPROM" - Allows user to remove ROM code and description for any device from the ATmega EEPROM. This does not remove information from the device's scratchpad or the device's EEPROM.
I had hoped to combine all of the above sketches into one sketch with a menu that allowed the user to select the functionality that each individual sketch provided. I actually created that sketch but when compiled, I found I exceeded the memory space allowed for variables. I exceeded the memory space due to the large amount of text associated with print statements. I felt these print statements are more important than a menu driven capability so I abandoned that approach. It is necessary to bring up, compile, and run each sketch individually.
Also, at the top level of the repository there is the directory "EEPROM Sketches". Under here you will find several sketches used to manipulate data in the ATmega EEPROM. These sketches were used to assist with other code development and troubleshooting.

Couple of Final Comments

As I said, previously, it was very common to have CRC errors when controlling these sensors from the Raspberry Pi. After making many thousands of measurements, with the Arduino controlling the sensors, I have received no initialization or CRC failures.
Just to reiterate, everything is written for the Arduino IDE. They are in the repository in such a manner that they can be downloaded directly. The libraries will have to be placed into your Arduino\libraries directory for them to be recognized.
My next blog entries will delve into details of some of my code.

Tuesday, May 13, 2014

Arduino Libraries - DON'T DO THAT!

Don't do what? Well, lets lead up to the answer to that question.
I wrote a fairly long library .cpp file (and, of course its .h file). It worked just fine in my sketch. But, I decided to make some changes. Not wanting to lose what I had (I knew it worked) I made copies of both the .h and .cpp files, appending "save" to the file name for each of the two files. I had four files: something.h, something_save.h, something.cpp, and something_save.cpp. All four files were under home/pi/sketchbook/libraries. I wanted to minimize the changes to my sketch (.ino file). Therefor, I did not want to change any of the function names in the library files. I made my changes, and compiled the sketch. The result: I received a list of compiler errors that went on and on and on.
To illustrate what happened, I repeated the sequence of events with a really small, and trivial example:
The only differences I made were to append a "+ 1" to "c = a + b" in the original .cpp file, just to make something different, and to append "_save" and "_SAVE" to the top lines of the bottom two files. I compiled the sketch and you can see what occured:
That's a lot of error messages for a tiny example sketch. I know it's a little hard to read the error messages because of the red text. Here is what it says:
Mylibraries/ridicules.cpp.o: In function RIDICULES::addNumbers(int, int)':
/home/pi/sketchbook/libraries/Mylibraries/ridicules.cpp:8 multiple definition of RIDICULES::RIDICULES()'
Mylibraries/ridicules_.cpp.o:/home/pi/sketchbook/libraries/Mylibraries/ridicules_save.cpp:8> first defined here
Those three messages are repeated three times. Please note I created a directory under home/pi/sketchbook/libraries called "Mylibraries". I stick my libraries there to separate them from the ones that came pre-installed with the IDE.
Note what I have colored red. This is reference to my ridicules_save.cpp file. My sketch does not reference "ridicules_save". Why is "ridicules_save" part of the build? To start to understand things, I did a search for the object files (".o") referenced in the compiler errors. I knew they were not in the Mylibraries directory. Here is what I found:
Note that all of these object files were created at the same time. They are all created every time you compile.
The IDE generates an object file (with an .o extension) of every .cpp file it finds in Mylibraries. It also makes an object file of .cpp files not in the sketch/libraries path. These ".o" files are needed to support Arduino functionality. There are other .cpp files in the sketch/libraries path that are skipped. This includes, for example, OneWire.cpp. Perhaps these are not included because I have never compiled a sketch using them.
I would have thought the IDE would only make an object file of the .cpp files you call for in your sketch and not all the others in your directory. But it does, so now that we know we can answer that question at the top:
Don't have more than one .cpp file with functions that have the same name in the libraries directory. If you need to keep copies of older versions of library files stick them in a directory outside of /home/pi/sketchbook/libraries.
By the way, you can have two files with addNumber() functions, just not two RIDICULES::addNumbers functions. Make one VERY_RIDICULES::addNumbers and you will be OK.

Tuesday, March 18, 2014

Writing An Arduino Library

My last post included a script for controlling the angle of rotation of a small dc servo. That script expects the user to input a floating point number from the terminal. I wanted that script to concentrate on the servo code, so to avoid encumbering the script with the process of handling the user's input, I put the input handling code into a library. Never having created a library, I wanted to learn how that is done. I read several tutorials but they all seemed rather simplistic. One of my concerns was how to pass values between the code that uses the library and the library functions themselves. I started with simple functions and built on those until I arrived at the function I needed for the servo
When you use the Arduino "Serial.read()" function to read from your terminal, you get only one character from each call. If you need more than one character, you need successive reads and a way to put those characters together into something meaningful. You also need to know when the last character was entered and some way to deal with characters entered in error. My servo script wants the user to input positive or negative floating point numbers of indeterminate length.
Note added June 22, 2014 concerning the last paragraph. If you use an Arduino instead of the Gertboard, you can use the serial monitor provided by the Arduino IDE. This serial monitor works quite differently. Rather than only returning one character for each call, it buffers your key presses and returns all of the characters when you hit "enter". In switching my next project from the Gertboard to the Arduino I had to modify the library created below to accommodate this change. See my post of June 15, 2014.

Final Script

Figure 1 below is my final script to control the servo. This is the same as in my previous post. The leading comments in that script were all about making the servo work so I removed them here. This script uses the library I wrote. You cannot see any of the details associated with inputting the floating point number. Only two lines, 2, 4, and 26 deal with the library:
FIGURE 1: Final Script - Without Leading Comments

Getting Started Making A Library

First, you develop the code, as usual, in a script using the Arduino IDE. Identify the parts of the code that will eventually be part of your library: functions, commands, and variables. Make sure there is test code that thoroughly tests the soon-to-be library. Compile and upload this script to make certain it will run properly. Try to break the code by changing conditions.
My test code is the code to control the servo. Figure 2 is my script. I call it my all inclusive script because it contains everything, in one script: the code to input numbers and code to control the servo:
Figure 2: Original All Inclusive Script - No Leading Comments
Most of the code (lines 3 to 68) deals with inputting the floating point number and just a few lines with the servo control.
The code to handle inputting the number accepts any digit, accepts a minus sign only if it is the first character, accepts one, and only one, decimal point, and accepts the backspace key to make a correction. All other characters are ignored. The function returns the floating point number to the calling code. This is not a perfect solution. I don't have a way to correct individual characters. When the backspace key is pressed, a space prints on the terminal after the last character, and the entire number must be entered from scratch.
I think it is pretty clear how the code works so I won't dwell on the details. We have two functions "termNumb()" and "clearVars()", and several variables. "clearVars()" is only called from "termNumb(). "termNumb()" is called from the program in line 91. The variables (lines 3 - 5), one int, three floats, and three boolean are needed by both functions so are global.

Now We Give The Code Some Class

Now that the code is working and tested as thoroughly as possible, it is time to define a class. We will tie those soon-to-be library functions to that class as well as those global variables we spoke about above. This script still contains the test code for controlling the servo. Figure 3 is the new script:
Figure 3: The Script With Class
At the top we create a class called "TERMNUMB". A class defines a data type (like an int or float). Elements you give that class are available to use when you use this class in other code. The elements of our data type, "TERMNUMB", are three functions (or methods): "TERMNUMB()", "termNumb()" and "clearVars()" and seven variables. The first two functions are declared as "Public" meaning they can be accessed by other code outside of the code that implements the class. The function "clearVars()" and the seven variables are declared as "Private" which means they are not known to code that call this class, but are seen by the functions declared in the class. There is no need for "clearVars()" to be public since it is only called from "termNumb()"
The functions "termNumb()" and "clearVars()" are the same as seen in the original, all inclusive, script as seen in Figure 2. "TERMNUMB() is new and is a special type of function called a constructor. Notice it has no return type and its name is exactly the same as the name of the class. The constructor is the first thing you see in the code below the class creation.
Note the function "termNumb()" has a float return type. When called, the function will return a floating point number to the calling program.
"TERMNUMB" class also declares seven variables and these variables, as indicated above, are declared as private. Notice these are the same variables declared in Figure 2, the all inclusive script above. I have added an underscore to the names of these variables. This differentiates them from variables that are declared within the functions themselves (like inChar).
Now that the class is created we define the three functions referenced in the class. The first function to be defined (line 14) is the constructor introduced above. Notice, in this example, there is no code associated with this function. The purpose of this function is to create an instance of the class "TERMNUMB". The way we associate "TERMNUMB()" to our class "TERMNUMB" is to use this strange syntax "::". The structure "::" is called the scope resolution operator and it says that "TERMNUMB()" is within the scope of class "TERMNUMB". The same must be done for our two other functions. "clearVars()" in the all inclusive script (Figure 2) becomes "TERMNUMB::clearVars()". "termNumb()" becomes "TERMNUMB::termNumb()".
The code from lines 17 through 78 define the implementation of our two functions "TERMNUMB::clearVars()" and "TERMNUMB::termNumb()". The code is nearly identical to the code in the all inclusive script (Figure 2) lines 7 - 68. The only differences are in the function names, just discussed, and the underscore attached to the names of the private variables.
We have created a class and defined the workings of the functions in that class. Now it's time to use it in our code to control our servo. Like declaring any type of variable, such as an int or float, we declare our class. This is done in line 80. We are declaring "inFromTerm" to be of type "TERMNUMB". One of the elements in "inFromTerm" is the function "termNumb()". That is exactly what we need to get the floating point number that becomes the angle our servo is to steer to. All of the work we have done culminates in line 102. The variable "angle" will be the return value from member "termNumb()" of data type "inFromTerm".
Make sure you compile and upload this code. Test it to make sure it works as desired.

Making the Library Files

The hard work is done. What remains is to create two files. These two files will constitute the library. Essentially, they will be cut-and-pasted from file in Figure 3 above. The first file is the header file with a .h extension. The second is the object file that has a .cpp extension.
Unfortunately, you can not make these files from the Arduino IDE because it only allows you to save a file with an .ino extension. You will have to use one of the text editors available with your Linux distribution like nano, vi, or leafpad to create, edit, and save the two files.

Header File

Figure 4, below, is the header file:
Figure 4: Header File InputNumbFromTerminal.h
As you can see, lines 22 - 31, in the header file, are exactly the same as lines 3 - 12 in Figure 3 above. Note we have added some comments to describe how the class will function.
Lines 17, 18, and 33 prevent "TERMNUMB" from defining multiple times and from creating duplication in the final binary file. Those lines assure that the class will only be created if it had not been created before. This is standard practice when creating header files.
Line 20 is absolutely necessary if your object code uses any of the special Arduino functions available from the Arduino IDE. In our case, that includes "Serial.read()" and "Serial.print()". If you have a pre Arduino 1.0 IDE you would use WProgram.h instead of Arduino.h.

Object File

The object file follows:
Figure 5: Object File InputNumbFromTerminal.cpp
The object file,Figure 5, "InputNumbFromTerminal.cpp" is the implementation of the class "TERMNUMB". Lines 4 - 68 are exactly the same as lines 14 - 78 in Figure 3 above. In lines 1 and 2, we include the two header files: Arduino.h (WProgram.h for pre Arduino 1.0 IDE), and the header file we just created, InputNumbFromTerminal.h.
Notice that the variables declared in lines 3 - 5 in the original, all inclusive, script (Figure 2) are not declared in the object file. Instead, these are the private variables declared in the header file. In the object file, they appear with the same names except they include the underscore as their last character.
None of the code to control the servo can be found in either the header or object files. No test software is included. That is why the testing is done before making the library files.

The Header and Object Files Are Now Created - What's Next

The library, consisting of the header and object files, must be placed in the correct location in your file structure. For the RaspberryPi, all user libraries must go into the "/home/pi/Sketchbook/libraries/" directory or a subdirectory of "home/pi/Sketchbook/libraries/".
VERY IMPORTANT:Once your files are located within the proper directory structure, you must close your Arduino IDE and any files open in the Arduino IDE. Only then, when you reopen the Arduino IDE, can your library be accessed by other code.

Putting It All Together - Revisiting The Final Sketch

I'm going to repeat the final sketch here in Figure 6 showing how we use the library to input the floating point number.
Figure 6: Final Script - Without Leading Comments
To access the library to input the floating point number we include the header file. This is done in line 2. Note we have declared "inFromTerm" to be of the data type "TERMNUMB". We also used "inFromTerm" in the code Figure 3. We did not have to use the same name. If we had called it something else in the final sketch we would need to match that name in line 26.

Quick Example Of Passing Values To A Library

Before I developed a library, I was not certain how you pass values to a library and how you pass a value from a library. The library above shows how the latter is done, but not the former. I have a really simple library that accepts two integers from a calling program, adds them together and prints the result to the terminal. The following are the header file, the object file, and the script using the library:
Figure 7: Header File
Figure 8: Object File
Figure 9: Script Calling The Library
Note, unlike in the library created above, we actually have some code within the constructor REALSIMPLE::REALSIMPLE().
I hope this tutorial has been helpful.

Thursday, March 6, 2014

Gertboard - Pulse Width Modulation - Servo Control

This is really a continuation of my last post. This post carries Pulse Width Modulation further by considering the control of a servo.
There are two types of small servos: a standard type and continuous type. This post describes the standard servo. This is the servo I purchased from Adafruit.
The standard servo has a shaft that rotates to a desired position and stops rotating once that position is attained. It can rotate 180°, or 90° in each direction from a neutral position.
It has a DC motor that connects through a series of gears to the shaft of a potentiometer, a device producing a variable electrical resistance. An extension of the potentiometer shaft is the output shaft of the servo. The set of gears between the motor and the potentiometer significantly reduces the speed of the motor and significantly increases its torque.
As the motor turns the potentiometer shaft, the resulting change in resistance produces a change in voltage. Let's call this voltage "A". Another voltage is produced that comes from translating the width of input pulses to voltage. The input pulses come from your ATmega microcontroller and represent the desired shaft position of the servo. Let's call this voltage "B". Voltages "A" and "B" are compared in a feedback circuit within the servo. As long as voltage "A" does not equal voltage "B", the feedback circuit produces a voltage to turn the motor either CW or CCW. When the motor has rotated the potentiometer to the point where the voltage "A" equals voltage "B", the control circuit stops the motor. As long as voltage "B" does not change, the output shaft will not rotate. A small servo usually can prevent a fair amount of external torque from turning the shaft.
Photo Found On Several Sites Servo As Found On Adafruit's Website
The other type is the continuous servo. This type turns continuously and the PWM controls the direction and speed of rotation. This may be a good alternative to a toy motor as it will be geared down for a more manageable speed range.
The ATmega328P will produce the pulses required by the servo using its Pulse Width Modulation features. In my last post, controlling a DC motor, the pulse repetition frequency was not very critical. This is not the case with the servo. The servo requires a pulse repetition frequency of 50Hz. We need a pulse every 20ms. The pulse duration is also specified and is in the range of 0.5ms. to 2.5ms. All the documentation I had seen for this type of servo specified the range to be 1.0ms. to 2.0ms. My particular servo, purchased from Adafruit, did not come with a data sheet, but apparently has better resolution than the typical unit. Programming from 1.0ms. to 2.0ms. did not turn the shaft 180°. Programming from 0.5ms. to 2.5ms. (confirmed by my oscilloscope) did produce 180° of rotation.
Forget about using the Arduino AnalogWrite() function. This function provides a fixed frequency of either 490Hz or 980Hz depending on the I/O pin. We need 50Hz. for servos.
The discussion below describes my system with a 12MHz clock frequency, and my servo that has a 0.5ms. to 2.5ms. pulse duration range. If your system is different you will have to make the appropriate adjustments.
The first decision we have to make is what timer/counter and prescaler value to use. The decision will be based on having adequate resolution of the angle of rotation. Since we know the frequency of pulse repetition we can rearrange the formula found in my last post. This gives us two unknowns: the maximum count and the prescaler value.
pulse repetition freq = clock speed / (2 * prescaler * max count)
Substituting the known values:
50 = 12,000,000 / (2 * prescaler * max count)
Rearranging and simplifying:
max count = 120,000 / prescaler
The range in pulse width is 2.0ms (2.5ms. at +90° minus 0.5ms. at -90°). This is one tenth of the 20ms. pulse repetition rate (1/50 x 1000). Therefore, the range of programmable count values is one tenth of the maximum count. The rotation resolution is the range of motion of the servo, 180°, divided by the count range. This is summarized below:
Prescaler Max Count Pulse Width Count Range Rotation Resolution
1 120,000 N/A N/A
8 15,000 1500 0.12°
64 1875 187.5 0.96°
256 468.8 46.8 3.84°
1024 117.2 11.7 15°
From the chart above we can eliminate the prescaler value of 1 because the ATmega328 does not provide a timer/counter that can count to 120,000 (65535 or 255). The only way to employ an eight bit timer/counter (timer/counter 0, or 2) is to use the prescaler value of 1024 - the only choice where the maximum count is under 255. However, the resolution of 15° is poor. This means that we will use timer/counter 1 because it can count to 65535. We should go for the best resolution which means that we will use the divide by 8 prescaler. This gives a resolution of 0.12° per count
Next we select the mode. We will select mode 8, the "Phase and Frequency Correct PWM" mode. The value of the maximum count will be programmed into register 1CR1.
The script I wrote is below and the details of register programming is included within the comments. The script requires you to open a terminal window on the host computer - the Raspberry Pi in my case. You are asked to input a floating point number which is the desired degrees of rotation from the middle position. The script accepts values from -90° to +90°. Once it rotates the servo shaft to the angle you requested, it will ask for your input, again.
Inputting a number from the terminal is not a trivial endeavor. The terminal handles one character at a time and it is up to the programmer to make sense of those characters. I did not want the script to be encumbered with the handling of the character inputs so I wrote a library to do that task. I wanted to learn how to do that, anyway, having not done that before. There are only three lines dealing with the character input: line 35 where we include the library dot h file, line 37 where we create an instance of the class created in the library, and line 59 where we call the function to get our number. My next post will report on creating that library function.
The servo has three pins, two go the battery to power the device, and provide a ground reference, and the third is the control pin which receives the output from the ATmega328. Don't forget to connect the ground pin from the battery to one of the grounds of the Gertboard.
The script:

Monday, March 3, 2014

Gertboard - Pulse Width Modulation - DC Motor Control

This post is about using the ATmega328P microcontroller for Pulse Width Modulation. While the subject is covered pretty well in the device's data sheet, some clarification and simplification is in order. This is my intention here. Please have the datasheet available. It can be found here. Select the first pdf file.

What is Pulse Width Modulation

If you landed on this page you probably know, so this explanation will be really short. While you can control a DC motor by controlling the voltage it is connected to, it is usually more precise and actually easier to control the motor by repeatedly turning it off and on. The motor responds to the average time the voltage is applied. You apply the motor voltage as a string of pulses with a defined frequency and a defined pulse width. If the duration of the pulse is half of the duration between pulses, the PWM will be 50% and the motor should turn at 1/2 speed.

To Drive A DC Motor

My last blog entry used Timer/Counter 1 in Normal mode to produce a timed delay. The timed delay function only had to use the timer/counter to do one thing: count up to a value and issue an interrupt. Pulse width modulation has two requirements. It must establish a frequency of pulse repetition and control the width of the pulses. While interrupts can be generated, PWM typically controls the logic level of a pin, or pins, that connect to external devices. Let's start with the dc motor being that external device.
We have plenty of options to consider. The first is whether we can use an eight bit timer/counter or do we need a 16 bit timer/counter. The answer is we probably don't need all of that resolution to control a dc motor. We can use ATmega's timer/counter 0 or 2 - both 8 bit circuits. Let's use timer/counter 0.
Next we need to decide between two major PWM modes. One mode gives twice the maximum frequency of pulse repetition as the other. This "Fast PWM Mode" operates by having the counter count up, and when it reaches its upper value, the counter starts over at zero. If you were to graph count against time, you would see a sawtooth wave. The other mode, "Phase Correct PWM Mode" has the counter count up, and when it reaches its upper value, count down at the same rate. When the count reaches 0 it counts up again. Graphing this looks like a triangular wave. See my graphic below.
Why are there two modes? If you never change the motor speed, either mode is fine. If you do change the motor speed, the Phase Correct PWM mode always has the center of the pulse at exactly the same place in time (if you keep the pulse repetition frequency the same and only change the pulse width). When changing the speed in Fast PWM the center of the pulse will move. Phase correct PWM results in a smooth transition in speed, while Fast PWM is more abrupt. Motors like the former over the latter. My example will use the Phase Correct PWM
With that settled, we have to deal with the frequency of pulse repetition. I don't know enough about DC motors to say what is the best frequency of pulse generation. I guess if the frequency is too low, the motor could lose speed between pulses. I don't know if there is a down side of too high a frequency. The higher frequency could limit the resolution of the speed differences we can program. This will be clear soon. The frequency of pulse repetition rate is determined as follows:
Pulse repetition frequency = clock speed divided by the prescaler and divided again by the maximum count set into the timer counter and finally divided by 2
My clock speed is 12MHz and the possible prescaler values are 1, 8, 64, 256, 1024 (allowable values for timer/counter 0). The lower the prescaler value the higher the frequency. The lower the count also gives you higher frequency. A little drawing is in order here:
The slope of the triangular waveform is determined by the clock frequency and the prescaler value. The clock frequency is your system clock so is not a variable. The prescaler value is, however, programmable. The horizontal line at the top, "Frequency" is controllable by your program and represents the maximum count in the timer/counter. It should be clear that changing the maximum count changes the pulse repetition. If you lower the count, the peaks of the triangles move to the left decreasing the time between pulses. Generally, when you decide on a pulse repetition rate, you would keep that constant.
The lower horizontal line, "Pulse Width", represents the width of the pulses. Typically, this value changes during your application. For example, if your project is a car with dc motors controlling two wheels, you frequently alter the speed of the car. And, you could steer the car by differentially changing the speed of each motor. Therefore, the width of the pulses frequently change. The graphic above should make it clear how the width of the pulses are changed. Lower the horizontal line and the width of each pulse decreases (assuming the we are talking about the positive going rectangle).
Note that the count for the "Pulse Width" must be less than the "Frequency" count. The "Frequency" count then determines the resolution of the pulse width modulation. If the "Frequency" count is the maximum allowed, which is 255 for timer/counter 0, each count will correspond to a pulse modulation increment of about 0.4%. If you lowered that "Frequency" count to 10, you would only be able to program PWM in 10% increments.
There is another programmable selection. The "Resulting Pulses" in the graphic are the result of selecting: clear (go low) on a compare match when counting up, and set (go high) on a compare match when counting down. The compare match value is represented in the above graphic by the line "Pulse Width". You can also program the opposite action: set on a compare match when counting up, and clear on a compare match when counting down. If you program that option, the "Resulting Pulses" waveform would be turned upside down.

Putting It Together In a Script

I did a small sample project where I control a toy DC motor. Since my ATmega328P resides on my Gertboard, I connect the motor and a 6V battery (4 AA's) to the BD6222HFP H-Bridge motor controller. This isolates the motor and it's power source from the PI and the Gertboard. My project increases the motor speed from off to full on, decreases the speed to off, changes the direction of the motor, increases the speed to the max and reduces it to off again. This action is repeated continuously.
There are only two timer/counter 0 modes for Phase Correct PWM, mode 1 and mode 5. My project uses mode 5. Compare register OCR0A controls the "Frequency". If I use mode 1, the "Frequency" count would be fixed to 255. Using mode 5, I can select any value from 0 to 255. As it so happens, I chose 255 anyway. If I had two motors to control, I would choose mode 1. In that case, compare register OCR0A controls one motor and OCR0B controls the other. Pulse repetition frequency would be the same for both motors but each would have it's own PWM percentage. They could turn in the same or opposite direction from each other.
The pulse repetition frequency of this project is 12,000,000 / (2 * 64 * 255) = 368 repetitions per second.
The H-Bridge takes two inputs. One input gets the pulses from pin PD5 while the other input comes from pin PD7. PD7 will determine the direction of rotation just like reversing the leads to the motor. When PD7 is low, we will select clear on a compare match when counting up, and set on a compare match when counting down. When PD7 is high we select set on a compare match when counting up, and clear on a compare match when counting down. You can picture how this works by considering how you would stop the motor. The motor stops if both PD5 (PWM = 0%) and PD7 are the same polarity.
The script below has a lot of comments (more comments than code) so I think the details are well presented within the script.

Wednesday, February 12, 2014

Gertboard - Creating Delay Function With Timer/Counter

My last blog post mentioned that the Arduino built-in delayMicroseconds() function was very inaccurate. The error was a whopping 50% when measured with an oscilloscope. As I wanted to investigate some of the intricacies of the ATmega328P registers I thought to write my own delay function.

Counter - Timer Features of the ATmega328P

There is tons of information on the web about using the ATmega timer/counters so the following will be a bit sketchy. The datasheet is a must to have available when talking about the ATmega functions. However, the datasheet is rather terse so sometimes you have to read between the lines, experiment like I am doing, or read of someone else's experience like you are doing here.
There are three timer/counters on the chip: 0, 1, and 2, They all have somewhat different features. Timer/counter 0, and 2, are eight bit counters so can only count up to a maximum of 255 (28). Timer/counter 1, has a 16 bit counter so can count up to 65535 (216).
Timer/counters 0 and 2 are almost identical. It seems that the intended use for timer/counter 2 is as a real-time clock. It kind of assumes that a 32 kHz watch crystal is connected to pin TOSC1. However, on the Gertboard, and most Arduinos (as far as I know) The 12 or 16 MHz resonator is already connected to that pin. Timer/counter 2 does have six prescaler (clock divider) selections while 0. and 1 have five.
Timer/counter 0 and 2, with their eight bit counters are well suited for controlling motors by pulse width modulation (PWM) while timer/counter 1 is best for servos and things my delay project. Timer/counter 0 and 2 have four modes of operation, a "Normal" mode, a "Clear Timer On Compare Match Mode" (CTC), and two pulse width modulator modes. Timer/counter 1 has all the modes of the other two with an additional PWM mode.
In all but two of the modes, the counters in the timer/counter circuit count up with each clock pulse received. When it reaches either its maximum value (255 or 65535), or a value you program, it starts over from zero. For pulse width modulation, you use the counter to establish a period of time. But, that only gives you half of what is necessary to control motor speed. For each time period, you need to control the percentage of time that you provide voltage to your motor. To provide that functionality, each timer/counter has two comparators (8 bit for 0 and 2, and 16 bits for timer/counter 1). You program a value into a comparator and when the count in the counter matches that value, the state of the I/O pin associated with the Timer/counter/comparator changes. When the counter reaches it's top value and returns to zero, the state of the I/O pin changes again. This results in two changes of state in each counter cycle (OFF to ON, and ON to OFF or ON to OFF, and OFF to ON). There are two modes where the counter counts down as well as up. Here, the state of the I/O pin changes when the counter count matches the comparator while counting up to its maximum value and matches it again on its way down to zero.
Since there are two comparators, each timer/counter can control two I/O pins. You can control two motors or two servos from each timer/counter circuit. The period (cycle time) would be the same for each because there is only one counter. However, each I/O can have its own percentage of ON/OFF time (because each has its own comparator).
Beyond controlling I/O pins, the Timer/counters can be programmed to issue internal interrupts. That is the feature I use for my delay script. Each of the three timer/counters has three interrupts. For the modes where the counter only counts up, and then resets to zero, an interrupt is issued when the counter overflows - when it reaches its maximum value (255 or 65535). At the next clock pulse the counter resets to zero and the overflow flag interrupt is issued. For the two modes where the counter counts up and then down, the overflow interrupt is issued when the counter reaches the bottom (zero). The interrupt routine you write will clear that flag.
The timer/counter can also be programmed to issue an internal interrupt when the counter count matches the comparator value. Since there are two comparators for each timer/counter, each has two of these interrupts.

My Counter Project

My code:
I use the timer/counter 1 in Normal mode and do not connect to either I/O pin. I don't use the comparator. I use the overflow flag interrupt. When my function is called, I do the following:
  1. The circuit only works for delays up to just over 5 seconds. If more is asked for, the maximum is substituted for the passed value.
  2. The most advantageous prescaler is selected depending upon the passed value. The lowest value possible is used to give the maximum resolution.
  3. The value of the count to be programmed into the time/counter 1 counter is calculated.
  4. A value of 1 is passed into the GPIOR0 register.
  5. Interrupts are turned off
  6. The two control registers associated timer/counter 1 are cleared assuring that the clock will not be connected to the counter (Counter will not count).
  7. The counter is programmed with the value calculated in step 3.
  8. Timer/counter Overflow Flag Interrupt is enabled.
  9. The prescaler is selected according to the variable "msk". This starts the clock. The clock now starts to count up with from the value we programmed into it (step 7.).
  10. Interrupts are enabled.
  11. We go into an endless loop waiting for the interrupt.
  12. The interrupt is issued one clock pulse after the counter reaches its maximum value of 65535.
  13. Processing enters the interrupt service routine which clears the interrupt.
  14. The value of GPIOR0 is set to zero.
  15. The prescaler is set to None value which stops the clock
  16. The Overflow Flag Interrupt is disabled.
  17. We exit the interrupt service routine and go back into the endless loop.
  18. Since GPIOR0 is now not 1, we exit the endless loop and the function.
The prescaler divides the 12MHz clock. For example, if the prescaler is set to 8, it takes eight clock cycles of the 12MHz clock to send one clock pulse to the counter. The available prescale values are None, 1, 8, 64, 256, and 1024. NONE disconnects the clock from the counter. If the prescaler is set to 1, it takes 65536 / 12MHz or 5461.3 microseconds to count from 0 to 65536 (65536 is equivalent to 0). The maximum delay for the function is obtained when the prescaler is 1024 and the variable "count" is 0, which would be 65536 x 1024 / 12MHz which is 5592405.3 microseconds or 5.5924053 seconds. Any value passed to the function greater than 5592405.3 is set to 5592405.3. I guess I could have extended the time indefinitely by waiting for multiple occurrences of the interrupt before exiting the endless loop. I saw no need to do that because the built-in delay() function is pretty accurate.
In step 3. above, I make use of the GPIOR0 register, one of three general purpose I/O registers. These registers can be used to store any information. I use it here instead of using another variable. If I had used a variable, instead, that variable would had to be declared as volatile. If I had written line 75 as "while (somevariable == 1);", and had not declared "somevariable" as volatile, the compiler would have thought the line did nothing except create an endless loop and would have eliminated it. The use of the register is kind of handy.
There are control bits that need to be programmed: Four WGM1 (waveform generator mode) bits, and two sets of two COM1 (Compare Output Mode) bits. One set of COM1 bits correspond to each comparator circuit. In this application, WGM1 is programmed to 0b0000, which selects Normal mode. Both COM1 sets are programmed to 0b00, which disconnects the two I/O pins associated with timer/counter 1 from the two timer/counter 1 waveform generator circuits. The four COM1 bits, and the lower two bits of WGM1 are part of the TCCR1A register (other two bits are not used). Therefore, TCCR1A is programmed to 0. The two higher order WGM1 bits are bits 3 and 4 of the TCCR1B register. Bits 0, 1, and 2 of TCCR1B are devoted to the prescaler. The value in the variable "msk" is used to program these bits. The range of possible values of "msk" is only be 0b00000001 through 0b00000101 (1 through 5), which keeps the bits 3 through 7 as a "0".
The overflow interrupt is selected to be enabled when interrupts are enabled. The prescaler is loaded with the value in "msk" which starts the counter counting up from the value in "count". Interrupts are enabled and we enter the endless loop. When the counter overflows (next clock after reaching 65535) the interrupt occurs and we leave the endless loop and enter the interrupt service routine. The interrupt service routine changes the value of GPIOR0 and stops the counter from counting. We leave the interrupt service routine and return to the endless loop. Since GPIOR0 is no longer 1, we leave the loop and leave the del() function.
In the next blog post I will discuss PWM. using the timer/counter features of the ATmega328P.

Sunday, January 19, 2014

Gertboard - Programming With ATmega Registers

Arduino IDE Built-in Functions Vrs. Direct Register Programming

Functionally, what is the difference between this script:
and this script:
Answer: NOTHING
Note: In the sketches discussed here, to see if the LEDs on the Gertboard are ON or OFF, PB0 is connected to BUF1, PB1 to BUF2, PB2 to BUF3, PB3 to BUF4, PB4 to BUF5, and PB5 to BUF6.
Both scripts turn LEDs on the Gertboard ON and OFF. First, LEDs 1, 3, and 5 are ON with 2, 4, and 6 OFF. One second later, 1, 3, and 5 are OFF, and 2, 4, and 6 are ON. One second later, the process repeats itself, on and on. The first script uses functions built into the Arduino IDE. While the second script uses the Arduino IDE delay() function, the LEDs are controlled by writing directly to microcontroller registers. The second script is sure a lot shorter and takes up about half of the space in memory. I must admit that it does use a little trick that I'll discuss later. That trick can not be used with the first script. I tried to shorten the first script by using for loops and if/else statements in lines 12 - 27. I gave up because it didn't seem to save lines of code.
The built-in functions that are part of the Arduino IDE are a convenient way to interface with the ATmega I/O pins. The second script shows another method, and that is to communicate directly with registers within the microcontroller associated with those I/O pins. Registers are eight bit bytes that are addressable within the ATmega memory space. In most cases, each bit of a register can be either read or written to. Each bit, or a combination of bits control some function or produce some effect. Before you can deal with these registers you need knowledge of what the registers do. That knowledge comes from the ATmega datasheet from Atmel.
If you are not concerned about writing a few more lines of code or how many bytes get loaded into the microcontroller, what other reasons would there be for programming ATmegta registers? Here are a few reasons:
  • IT'S EASY TO DO. There is a library include file, iom328p.h for the ATmega328P, that defines all of the registers and register pins in exactly the same way that they are named in the datasheet. For example, in the second sketch, the line "DDRB=0b00111111;" correlates directly to 13.4.3 on page 92 of the datasheet. This is the datadirection register for port B. Writing a 1 to the lower six bit positions makes pins PB0 to PB5 outputs. "PORTB=0b00101010;" correlates to 13.4.2 on page 92. This will make PB1, PB3, and PB5 logic high, turning on their respective LEDs. The first line of that second script, "#include <avr/io.h>" looks to see what ATmega chip you are using and, in our case, the ATmega328P. When the script is compiled, the definitions in iom328p.h are used to figure out the locations within the ATmega to access.
  • There are things you can do that are not supported by the built-in functions. For example, even though you can do PWM to control a motor using analogWrite(), you are stuck with one frequency - about 490Hz. If your motor would rather work at 10khz, you can program the counter registers. There are a lot more things you can do or develop yourself. For instance, I wish to develop my own 1-Wire interface for use with my DS18B20 temperature sensors.
  • I found that the function delayMicroseconds() produces delays that area about 2/3 of the correct values. I noticed this first with my camera remote control project. I was looking for a pulse width of 284usec but had to program delayMicroseconds(415) to get 284usec. Testing with an oscilloscope, from a desired delay of 10 to 3000usec, I consistently measured about 67% of the desired value (the delay() function is pretty accurate). So, I plan to write my own function for microsecond delays. There are two 8 bit counter/timers and a 16 bit counter/timer accessible by registers that can be utilized.
  • For me, I like getting closer to the hardware when programming. It makes me feel more in control.
  • Gives me a chance to use those fun bitwise operators like OR, AND, and EXCLUSIVE OR and shift bigs right and shift bits left.
  • Here are most of the ATmega functions that are accessible through registers:
    • I/O Pins, both content, data direction, and pull-up resistors for inputs
    • The various counter timer registers and prescallers for 8 and 16 bit counter/timers. These also control the PWM oscillator functions at the I/O pins
    • SPI control, status, and data registers
    • Registers for the serial communications using the USARTs
    • Registers for the 2-Wire serial interface
    • Analog comparator
    • A to D converter
    • Interrupts
I said I like to use bitwise operators, and the EXCLUSIVE OR operator is the trick I used to make that second script so short. Line 7 turned three of the six LEDs on (PB1, PB3, and PB5). Line 12 is going to toggle those LEDs that are ON to OFF and those that are OFF to ON.
Line 12 uses a compound operator. Recall that =+ is a compound operator. The expression A =+ 1 is the equivalent to A = A + 1. In our line 12, the compound operator is =^ which is an EXCLUSIVE OR. It is the equivalent of PORTB = PORTB ^ 0b001111. The EXCLUSIVE OR compares two bits. If they are the same (both 0 or both 1) the result is a 0. If they are different, the result is a 1. Let's apply that to PORTB which we will assume is 00101010. Putting one number under the other let's see what we get:
  00101010 PORTB
  00111111 EXCLUSIVE OR with this binary number
  00010101 NEW PORTB value
Let's do that again:
  00010101 PORTB
  00111111 EXCLUSIVE OR with this binary number
  00101010 NEW PORTB value
Note we are back to where we started. I hope you can see that this operation will toggle the six LEDs ON and OFF.

Another Sketch Writing To I/O Pins

I would like to introduce another sketch. This one uses four bitwise operators. Between the two sketches we will have used all of the bitwise operators except for the shift right.
This sketch uses the same six LEDs on the Gertboard except only one LED is lit at any one time. It starts with all LEDs OFF, then lights each LED for one second starting with the LED connected to pin PB0. Each LED, down the line, is ON for one second. One second after PB5 is lit, the sequence starts over again at PB0.
Let's take a look at line 12. Here we have two bitwise operators, an OR compound operator, |=, and a SHIFT LEFT, operator, <<. If you are not familiar with this type of notation it surely looks strange.
Line 12 means we are going to take the current contents of the register PORTB, the register connected to pins PB0 through PB5, and OR them with some value so that PORTB is changed. I'll talk about what OR means in a minute. For now, the question is: what is that value we are going to use to change the contents of PORTB? Why, it is (1 << PORTB0), of course. What?? What does that mean? If you look into the include file, iom328p.h, (called by avr/io.h, the first line in the sketch) you will find that PORTB0 is defined as 0. In like manner, PORTB5 is defined as 5. You can see the pattern here. So, (1 << PORTB0) becomes (1 << 0). That means we take the number 1 and shift it left 0 times. That seems to make even less sense. It begins to make sense, however, if we look at 1 as 00000001. Nothing much happens to it if we shift it 0 times as in line 12 of the sketch. But, what about similar line 32. This means we shift 1 left by 5. Just move that 1 over 5 places to the left. This new value now becomes 00100000. Get it?
Now, we can talk about the OR operator. When we OR two binary digits, if either digit is a 1, the resulting value is a 1. A 0 result only corresponds to both digits being 0. So, if we started out with PORTB as 0b00000000 (all LEDs OFF) let's apply sketch line 12 and see what happens.
  00000000 PORTB
  00000001 OR with this binary number
  00000001 NEW PORTB value
This obviously turns the LED connected to PB0 ON, and that is the only one on. Now we wait one second and move on to sketch line 15, which is similar to line 12, except that the |= is replaced by &=, the AND compound operator. And, (1 << PORTB0) is now: !(1 << PORTB0). The exclamation point is the NOT symbol, for negation, another bitwise operator. We know that (1 << PORTB0) is 00000001. What then is !(00000001)? The answer is 11111110. Every bit is changed to its complement (1 becomes 0, 0 becomes 1).
The AND bitwise operator takes two bits and if either is a 0, or both are 0, the result will be a 0. The only way to get a 1 is if both bits are 1. So let's AND the contents of PORTB, 00000001, with 11111110:
  00000001 PORTB
  11111110 AND with this binary number
  00000000 NEW PORTB value
This turns the PB0 LED OFF. Obviously we could have written PORTB = 0; with the same effect, but what is the learning value in that? If you follow the logic you can see where sketch line 16, and beyond, turns the LED connected to PB1 one, for a second, before turning it off, and turning the next LED on, etc., etc.
Controlling those LEDs the way I did in that last sketch is rather silly. Lines 12 through 35 could have been written as:
PORTB = 0b00000001;
DELAY(1000);
PORTB = 0b00000010;
DELAY(1000);
      .
      .
      .
PORTB = 0b00100000;
DELAY(1000);
So why did I write all of that extra code? I wanted to illustrate the use of those bitwise functions because they are invaluable when writing to registers and memory. They are an elegant way of accessing individual bits in a field of other bits (our field is 8 bits because all ATmega registers are eight bits long). It's a way of altering some bits while leaving other bits alone. You could keep track of all the bits in a register at all times, but sometimes that is not possible. Other processes, either hardware or software, could change some bits in a register. You only want to access the bits you want to change and leave the others alone.
As you can see from what we have done before, if you wish to make a bit a 1, or assure it is a 1, OR it with a 1. OR the bits you don't want to change with a 0. Look at the example above.
If you wish to make a bit a 0, or assure it is a 0, AND it with a 0 and AND the others with a 1 to leave them alone. If you wish to toggle a bit, changing it from a 0 to a 1, or a 1 to a 0, EXCLUSIVE OR it with a 1, and EXCLUSIVE OR the others with a 0. If you study the examples above you can see how that works.

Sketch To Read From I/O Pins

I talked about writing to I/O pins in the previous sketches, so my last sketch shows an example of reading the logic level of an I/O pin:
This sketch sets pins PC0 to PC5 as inputs. Writing to PORTC will determine if an internal pull-up resistor will be connected to the pin. Writing a 1, connects the pull-ups. So writing 3F, in hexidecimal, writes a 1 to the lower 6 bits of the register.
Every second, the script sends the contents of PINC to the serial monitor running on the Pi. If PORTC is the register that outputs a logic level to the port C I/O pins, PINC is the register that records the logic level of external inputs of the port C I/O pins. If nothing is connected to an external pin, the internal pull-up resistor will set a logic 1 in the corresponding PINC register bit. If you connect that pin to ground, a logic 0 will be set in the register bit. Using the BIN built-in constant, will send the contents of the register in binary format.
If there is nothing connected to any of the port C pins, you will see:
  111111
  111111
  111111
etc.
However, if you connect PC0 to ground, for example, you will see:
  111110
  111110
etc. for as long as the ground is connected.

Wrapup

I hope this has been informative and if you are a beginner that you learned somethings useful.