Tuesday, August 28, 2012

Raspberry PI - Reading and Writing to GPIO Pins

Next step is to combine the GPIO Input and Output in to one program.

With the power to the rPI off, I used another jumper to tie header pin 18 to the input of a high impedance logic probe.

Then I powered up, logged in and nano's up the following program "switch_led.py"


#!/usr/bin/python
#
import time
import RPi.GPIO as GPIO
#
# to use Raspberry Pi board pin numbers
GPIO.setmode(GPIO.BOARD)
#
GPIO.setup(18, GPIO.OUT)
GPIO.setup(11, GPIO.IN)
#
count = 1
while (count < 100):
        input_value = GPIO.input(11)
        GPIO.output(18, input_value)
        print input_value
print ("End")

Then I ran it with

     $ sudo python switch_led.py

Now when the switch is turned on  and off, the led goes on and off. 

Congratulations, you now have a $35 programmable light switch. But once you can get digital data in and out of a program , the sky is the limit!



Eric Pierce VA3EP - See the Disclaimer in the Introduction

© Eric Pierce and "VA3EP Amateur Radio And Other Geek Pursuits", 1952-2099. Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and/or owner is strictly prohibited. Excerpts and links may be used, provided that full and clear credit is given to Eric Pierce and "VA3EP Amateur Radio And Other Geek Pursuits", with appropriate and specific direction to the original content.


Monday, August 27, 2012

Raspberry PI - Reading a GPIO Pin


The next thing that I wanted to do was READ a GPIO Pin.

This article assume that you have installed the software mentioned in
"Raspberry PI – Writing to GPIO Pins".

I connected the following circuit using jumper pins and a proto board (BE careful and do this with the power off, triple check before turning it on!!!!).



You cannot just hook the switch to a logic input, you have to actively pull it high and low (in most cases, won't get into that now). The 10K resistor acts as a "pullup" to pull pin 11 high when the switch is open, and draws only microamps of leakage current (it any).

When the switch is closed, pin 11 is pulled low to ground, drawing only about 0.3 milliamps from the rPI.
 
After checking the circuit, power up the rPI, log in and nano up the following program as "switch.py":

#!/usr/bin/python
#
import RPi.GPIO as GPIO
#
# to use Raspberry Pi board pin numbers
GPIO.setmode(GPIO.BOARD)
#
GPIO.setup(11, GPIO.IN)
#
count = 1
while (count < 100):
        input_value = GPIO.input(11)
        print input_value
print ("End")


Now run the program

     $ sudo python swith.py

You will see "True" scrolling to the screen when the switch is open, and "False" when it is closed.

By the way, the schematic was edited with a "free as in beer" schematic editor from www.expresspcb.com


Reference



Eric Pierce VA3EP - See the Disclaimer in the Introduction

© Eric Pierce and "VA3EP Amateur Radio And Other Geek Pursuits", 1952-2099. Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and/or owner is strictly prohibited. Excerpts and links may be used, provided that full and clear credit is given to Eric Pierce and "VA3EP Amateur Radio And Other Geek Pursuits", with appropriate and specific direction to the original content.

Sunday, August 26, 2012

Raspberry PI - Power Supply and USB Problems


Read an article on Slashdot that says the Raspberry Pi has some "problems".

The actual article seems a bit alarmist, to summarize the key information there and in the referenced articles:

1) The rPI gets flakey if you don't use a powerful enough power supply
2) The USB peripherals apparently can't deliver the 500–900 mA that the USB spec calls for (Ref 1)

The interesting thing is that I have observed both of these problems, but quickly figured them out and have had no issues since.

1) I tried powering the rPI from a couple of USB hubs with external power supplies that both said "1 AMP". On the first one, it would get part way through the boot process and reboot, getting stuck in a boot loop. On the second one, it would not even start the boot process. I fixed the issue by running the PI from a heavy duty 4 Amp analog open frame power supply  that I scrounged from some piece of junked gear (have to write a blog posting on the joys of scrounging junk :-)

2) I first tried a really old USB keyboard (a real "IBM" one - remember when they made PCs :-) and it acted flakey, repeating and missing characters. I swapped it out for a newer one, works fine. My conclusion is that the newer one drew less current and worked fine, although I did not measure it.

So to me all the alarmist postings are a bit of an overreaction, moral of the story is to use a GOOD beefy power supply that can deliver the 1 AMP the rPI needs (Ref 2) PLUS the combined current that the 2 USB peripherals need. Better still, use an external self powered hub for the USB peripherals.

References

1) http://en.wikipedia.org/wiki/USB

2) http://www.raspberrypi.org/phpBB3/viewtopic.php?f=29&t=14988



Eric Pierce VA3EP - See the Disclaimer in the Introduction

© Eric Pierce and "VA3EP Amateur Radio And Other Geek Pursuits", 1952-2099. Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and/or owner is strictly prohibited. Excerpts and links may be used, provided that full and clear credit is given to Eric Pierce and "VA3EP Amateur Radio And Other Geek Pursuits", with appropriate and specific direction to the original content.

Friday, August 24, 2012

Raspberry PI - More about Serial 3.3v, TTL and RS-232 levels


If you tried to implement the last blog post, one thing that those of you new to electronics may find strange is that when there is NO serial output, the level of the TXD pin is "high" - for the rPI GPIO pin this is around 3.3 volts. For a TTL level serial, this would be around 5 volts.  (Don't forget that you have to convert the 3.3 level to 5 if you are interfacing the rPI to TTL logic, as discussed elsewhere in this blog).

When the data is sent, the pin drops unasserted (see Ref 1)  for the "start" bit , then up and down for the 1's and 0's of the data (which may be ascii characters, see Ref 2), then back to asserted. The "asserted = 1" logic level is  3.3 or 5 volts, and the "unasserted = 0" logic level is 0 volts. This seems a bit strange, but that is how it works. More on that later down the page. 

Here is the waveform (from Ref 3):




There is also another standard for serial data, called RS-232. It is bipolar, with the positive level for the 0's and a negative for the 1's. The positive and negative voltage seings are 3 to 15 volts (Ref 4) 

There are off the shelf chips like the MAX232 (Ref 5) that facilitate the conversion to 3.3/5 and the bipolar signal. Some of these chips even use external capacitors to facilitate on board "charge pumps" to develop the +/- RS232 voltages from the 3.3 or 5 volt chip supply. 

Now here is the interesting part. The reason that the signal is held at the "asserted = 1" state when there is NO data is a holdover from the old days of mechanical Teleprinter/Teletypes (Ref 6):

" The "idle" condition of the circuit is a continuous marking state, with the start of a character signalled by a "start bit", which is always a space." 

This way, of the line connection was broken electrically, it would cause:

"a receiving teleprinter to cycle continuously". 

This would be a sign to the operator that the line was down. If it was the other way around, there would be no warning the line was down, and the op would wonder if it was just a quiet day or is there was really a problem.

Now the even more interesting part. This is apparently a carry over from old land line telegraph keys (Ref 7, 8):

" Straight keys used by telegraph operators also had a "shorting bar" that closed the electrical circuit when the operator was not actively sending messages. This was to complete the electrical path to the next station so that the sounder would operate, as in the operator receiving a message from the next town." 

So now you know the rest of the story. The state of the art SOC chip in your rPI uses a standard that can trace it's way directly back to the invention of telegraphy in 1836 (or earlier).  

References

1) http://en.wikipedia.org/wiki/ASCII 
2) http://en.wikipedia.org/wiki/Logic_level  
3) http://esd.cs.ucr.edu/labs/serial/serial.html
4) http://en.wikipedia.org/wiki/RS-232
5) http://en.wikipedia.org/wiki/MAX232  
6) http://en.wikipedia.org/wiki/Teleprinter 
7) http://en.wikipedia.org/wiki/Telegraph_key
8) http://www.linuxmisc.com/3-solaris/b1c64220ef83ca8a.htm



Eric Pierce VA3EP - See the Disclaimer in the Introduction

© Eric Pierce and "VA3EP Amateur Radio And Other Geek Pursuits", 1952-2099. Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and/or owner is strictly prohibited. Excerpts and links may be used, provided that full and clear credit is given to Eric Pierce and "VA3EP Amateur Radio And Other Geek Pursuits", with appropriate and specific direction to the original content.


Thursday, August 23, 2012

Raspberry PI - Serial Port Output

The next thing that I wanted to do is get a Python program talking to the serial port TXD pin on the GPIO header (Pin 8) . Using the info in ref 1, here is what to do to get serial output:
 
To keep from spawning a terminal login session on the header serial port, in  the file

      /etc/inittab

 Comment out the line (using nano as discussed in previous posts)

     # 2:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100

You can also stop boot up messages as per the reference, but I did not do this.

Then you need to re-boot (as the login process was spawned already, and will not be spawned until you boot with that line commented out)

    $ sudo shutdown -r now

I then found that you need to install this software package

    $ sudo apt-get install python-serial

When rebooted, log back in and nano up the following Python program as sertest.py (heavily based on ref 1, some neat tricks here, like the code to do a clean exit when you hit ^C on the controlling keyboard):

----------------------------------------------------------------
#!/usr/bin/env python
#
print ("Starting program")
import serial
import time
# import string
#
count = 1
test=serial.Serial("/dev/ttyAMA0",9600)
test.open()
teststring = "ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz"
#
try:
    while True:
                print count, teststring
                test.write(teststring)
                print "Waiting 1 second"
                time.sleep(1)
                count = count + 1
#
except KeyboardInterrupt:
    pass # do cleanup here
#
test.close()
----------------------------------------------------------------

Now run it as root (to get access to the metal):

  $ sudo python sertest.py

Observing the serial TXD (header pin 8) with the logic probe, you can see a data stream while the program is running. It works!


References:



Eric Pierce VA3EP - See the Disclaimer in the Introduction

© Eric Pierce and "VA3EP Amateur Radio And Other Geek Pursuits", 1952-2099. Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and/or owner is strictly prohibited. Excerpts and links may be used, provided that full and clear credit is given to Eric Pierce and "VA3EP Amateur Radio And Other Geek Pursuits", with appropriate and specific direction to the original content.



Raspberry Pi - Why 74HC14N (or other "buffer" Chip)?


** UPDATED Aug 28, 2012**

The reason for putting a buffer chip between the rPI GPIO pin and external electronics is not only convert the 3.3 to 5 volt (or other) logic levels, but protect it from mistakes like applying a high logic level when the chip is configured as an output (some chips are designed to handle this, other are not). Static discharges are also a concern. 

When I mentioned using a 74HC14N to interface to the rPI, reader commented "Amazing that because of these 'new' 3.3v parts we're having to resort to these old 74HCxx parts".

Yes, it IS an old part, but there is a LOT of inertia around 7400 class parts, and a LOT of derivative types like the 74HCXX parts. As this article states "Several generations of pin-compatible descendants of the original family have since become de-facto standard electronic components"

You can get the pinouts and more info for the 74HC14N here. Note that it is a "Hex inverter" which means that it has 6 inverters in the package, and as a bonus it has a Schmitt trigger input, which will tend to clean up slower transitioning signals is you are using them as an input buffer.

The author of the referenced article also stated that there are modern parts that will do the trick, but if you have the old parts hanging around in your junkbox, or you can get them from an eBay seller, then they are fine.

The other issue of course if getting standard DIP parts as so many new components are surface mount , and are difficult or impossible to breadboard with a proto board.

No matter how complex the main chips, unless you have a circuit specifically designed for a project, you always need some "glue chips" to interface things together.

Some of you have worked with Microchip PIC chips which seem quite robust (I have have accidentally drawn a static spark after walking across a dry rug from a screwdriver tip directly to a PIC I/O pin and it continued to work ok). I suspect that the PIC chips have a lot less (relative) complexity than the Broadcom SOC, so I also suspect that the PIC chips have more room to put I/O buffers, protection diodes, etc. which is needed for the type of apps they are used in.  The SOC is normally buried in a phone or tablet so probably brings out more or less the raw gate output, with less protection I imagine. 

So I am working very carefully around the rPI GPIO pins because of that  :-)
 

Reference:  

http://www.petervis.com/Raspberry_PI/Raspberry_Pi_GPIO_Header/Raspberry_Pi_GPIO_Header.html 

http://en.wikipedia.org/wiki/Electrostatic_discharge#Damage_prevention_in_electronics

http://en.wikipedia.org/wiki/7400_series

http://www.microchip.com/stellent/idcplg?IdcService=SS_GET_PAGE&nodeId=2551

http://en.wikipedia.org/wiki/Dual_in-line_package

http://en.wikipedia.org/wiki/Surface_mount


Eric Pierce VA3EP - See the Disclaimer in the Introduction

© Eric Pierce and "VA3EP Amateur Radio And Other Geek Pursuits", 1952-2099. Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and/or owner is strictly prohibited. Excerpts and links may be used, provided that full and clear credit is given to Eric Pierce and "VA3EP Amateur Radio And Other Geek Pursuits", with appropriate and specific direction to the original content.


Tuesday, August 21, 2012

Raspberry PI – Safely Interfacing to GPIO Pins


I screwed a rPI to an old breadboard I had, and bolted an old open frame analog +5, +/- 12 supply to the back and wired it all up.

In the last post I got a python program toggling all the I/O ports on and off at 1 second interval, will send out the code. At this point just measuring the result with a high impedance logic probe.

Next problem is interfacing the 3.3v rPI levels to the more common 5 v TTL. According to my research:

For 5=>3.3. you can use a simple 10k/20k resistor voltage divider. I have lots of resistors, just have to find them.

For 3.3=>5 This seems to be the cheapest alternative:
     http://www.datasheetcatalog.org/datasheet/philips/74HC14N.pdf

Blowing a $0.50 chip seems to be better than blowing a $35 rPI board :-)

For the next step I want to tie the rPI serial RXD/TXD to the TXD/RSD of a 40 pin PICAXE. Then write a very simple PICAXE program to allow me to use I/O pins on the PICAXE as an "expander" for lots of Digital I/O and Analog in, maybe even use a couple of pins to do PWM, which can be integrated to produce an Analog out. Want to use a simple human readable ascii protocol to marshal data and commands back and forth - http://www.amelek.gda.pl/avr/uisp/srecord.htm

That protocol is really meant for memory mapped data, but you can easily extend it to do commands, could even leave out the checksum.

You could always use a CSV format - http://en.wikipedia.org/wiki/Comma-separated_values - but the srecords would be easier to parse as they are more field oriented.

Probably make it totally polling based to start, i.e. the PICAXE monitors the serial port, the rPI sends data and/or a command, the PICAXE responds and reads and/or outputs the ports, and then the PICAXE sends back any data to the rPI. VERY simple.

Joke is that I once tied together 2 multi $100K ATC simulators using a similar technique (one sim for terminal airspace, the other for precision approach radar) - very simple and easy to test and debug. Nice thing about using a human readable ascii format is that you can hang a dumb terminal (emulator) off the lines to see what is going back and forth for development and debugging (if you slow down the back and forth to human readable speeds :-)

References:

http://www.petervis.com/Raspberry_PI/Raspberry_Pi_GPIO_Header/Raspberry_Pi_GPIO_Header.html





Eric Pierce VA3EP - See the Disclaimer in the Introduction

© Eric Pierce and "VA3EP Amateur Radio And Other Geek Pursuits", 1952-2099. Unauthorized use and/or duplication of this material without express and written permission from this blog’s author and/or owner is strictly prohibited. Excerpts and links may be used, provided that full and clear credit is given to Eric Pierce and "VA3EP Amateur Radio And Other Geek Pursuits", with appropriate and specific direction to the original content.