richrarobi
Posts: 271
Joined: Sun Feb 08, 2015 1:13 pm

Re: Using an Arduino as a slave I/O board

Mon Feb 09, 2015 9:32 pm

I got the i2c to work on pi - with a HMC5883L - the arduino is still separately available for flashy things (LED), wiggly things (Servo) and possibly twiddly things - (Pots)

Arduino is currently controlled through the serial port to Standard Firmata.
Being a stubborn type I will persist in the Nanpy route - I have a hankering to compare the two methods

richrarobi
Posts: 271
Joined: Sun Feb 08, 2015 1:13 pm

Re: Using an Arduino as a slave I/O board

Tue Feb 10, 2015 1:09 pm

I thought this should be shared (it might be important):
I decided to try connecting everything from the pi via i2c. Connected it up using an i2c level shifter (without linking power leads across the device), I found that the Arduino lights up with no power applied to it. I didn't want to have this because I don't want to overload the power supplies on the pi. Disconnect quickly! Check with multimeter - found that the i2c level shifter is passing through 3 volts to the 5v side. (this doesn't seem right! But the circuit diagrams I've seen do show the 5v lines linked. (Nasty? I don't like it! They will have to go in the bin.
Note that the UART level shifter doesn't do that. With that I can power up the Arduino entirely separately than the PI, so only the serial data wires connect.
edit:
BUT I just noticed my UART level shifter is one of those that does i2c as well.....so get the right one!

richrarobi
Posts: 271
Joined: Sun Feb 08, 2015 1:13 pm

Re: Using an Arduino as a slave I/O board

Fri Feb 13, 2015 11:05 pm

OK, I am converted! I prefer nanpy!! (Using 0.9.2 too!)
Took all day (and all evening to make the code work!!!!)
This code shows how to address the serial port with nanpy (not USB)
The git approach for getting the firmware doesn't work, (kicks me out, maybe I need to login to their site?) downloaded the tarball with windows, sftp'd it to PI to make, then brought back the code directory to windows using filezilla, to write sketch to the Arduino (I am only using command line on the PI's so no Arduino sketching on there.
It looks like I only have a single line LCD....writes message to LCD and flashes LED on pin 2. (I tagged leads onto the Sainsmart shield to connect with the UART pins on py (through level shifter)).
Hope this is of use to someone... Now I need a list of nanpy modules and the parameters.

Code: Select all

import sys, traceback
from time import sleep
from  nanpy import Arduino, Lcd, ArduinoApi, SerialManager

conn = SerialManager(device='/dev/ttyAMA0')
a = ArduinoApi(connection=conn)
a.pinMode(2, a.OUTPUT)

lcd = Lcd([8,9,4,5,6,7],[16,2], connection=conn)
lcd.printString("It nearly  works!", 0, 0)

while True:
   try:
      print 'going high'
      a.digitalWrite(2, a.HIGH)
      sleep(1)

      print 'going low'
      a.digitalWrite(2, a.LOW)
      sleep(1)

   except KeyboardInterrupt:
       a.digitalWrite(2, a.LOW)
       lcd.printString(16*" ", 0, 0)
       print "program stopped"
       sys.exit(0)

mr.kyawzinlattt
Posts: 1
Joined: Wed Oct 22, 2014 7:08 pm

Re: Using an Arduino as a slave I/O board

Sat Feb 14, 2015 5:51 am

How can I install the driver to RPi if I need to use driver library files for some sensors attached to Arduino?

tonygo2
Posts: 93
Joined: Sun Aug 28, 2011 2:50 pm
Location: Leicester, UK

Re: Using an Arduino as a slave I/O board

Sat Feb 14, 2015 4:29 pm

by richrarobi » 14 Feb 2015 00:05

OK, I am converted! I prefer nanpy!! (Using 0.9.2 too!)
Took all day (and all evening to make the code work!!!!)
How did you get 0.9.2 to work? Can you add a SIMPLE guide to the last bit after downloading the git to uploading to the Arduino?

I thought the Rx and Tx serial went through the USB connection, in effect like joining directly but taking care of the voltage changes.

richrarobi
Posts: 271
Joined: Sun Feb 08, 2015 1:13 pm

Re: Using an Arduino as a slave I/O board

Sat Feb 14, 2015 5:55 pm

First last... see grotty picture attached (serial port is ttyAMA0, I think USB of pi is ttyACM0) The serial port is normally allocated to serial login - for those who might want to attach an old fashioned terminal - you have to remove it from the boot process to use it.
pi02arduinosainsLCD3.jpg
pi02arduinosainsLCD3.jpg (59.64 KiB) Viewed 5302 times
yellow/green leads at top left go to pi pins 3 and 5
white lead is digital pin 2 and goes to my LED
red and black that go under the LCD panel go to 5v and ground on far side of Ardu.
red and black on the rpi at left side are 3.3volt (don't mix power!!)
the little board is a level shifter (I now realize I soldered my pins on the wrong side! - still works...)
the yellow / blue go to 0 and 1 on Arduino (you have to swap rx/tx i.e. transmit to the receive on other end)

I will write some notes on the install - I need notes anyway for myself !!

richrarobi
Posts: 271
Joined: Sun Feb 08, 2015 1:13 pm

Re: Using an Arduino as a slave I/O board

Sat Feb 14, 2015 6:14 pm

mr.kyawzinlattt wrote:How can I install the driver to RPi if I need to use driver library files for some sensors attached to Arduino?
Sorry, I sort of jumped over your post.
I think the answer is that with Nanpy (or Firmata) installed on Arduino you use that interface on the PI also to address all your devices attached to Ardu. You have to write programs on the Pi that address the Nanpy (or Firmata) across the wire to Ardy. So you have to install compatible software on both sides of the wires.

If you only have simple devices, that are all the same, you can have a simple sketch for the microcode and write code on the pi to drive them. You may be able to combine sketches for different devices? Looks hard.
A bit mind bending I fear!
RichR

User avatar
Onira
Posts: 237
Joined: Tue Oct 02, 2012 6:24 pm
Location: Poland

Re: Using an Arduino as a slave I/O board

Sat Feb 14, 2015 6:48 pm

I would like to ask the same thing.
tonygo2 helped me to install nanpy-0.8
because version 0.9 was crashing

so HOW did you get 0.9.2 working?
Cogito ergo sum

richrarobi
Posts: 271
Joined: Sun Feb 08, 2015 1:13 pm

Re: Using an Arduino as a slave I/O board

Sat Feb 14, 2015 8:20 pm

No pressure then?
Here's the firmware bit:-
Plan B to get the nanpy firmware by a roundabout route because the normal route didn't work (I think they forgot to make it public):

On a windows pc, firefox browser, search for Nanpy. The first one up is https://pypi.python.org/pypi/nanpy
on that page, find the files in blue choose nanpy-firmware-v0.9.2.tar.gz and download it to your windows box.

That tar file is a waste of space on windows, so with an ftp program (I did use psftp from the putty suite, but it is 'orrible command line stuff) - so install Filezilla on your windows box if you haven't got it already. Use filezilla to just transfer the untouched tar.gz file across to your Pi home directory.

Once it is there, you might need to move it to the Nanpy directory or not (I don't think it matters):-
mv nanpy-firmware-v0.9.2.tar.gz nanpy/nanpy-firmware-v0.9.2.tar.gz

then as normal:

tar -xvf nanpy-firmware-v0.9.2.tar.gz
cd nanpy-firmware
./configure.sh

That should have done it. Now we need to install it on the Arduino. (I am using command line on P so don't have the ino gui). Note You COULD run this on PI, Linux or wherever you do your sketchbook stuff.

This what I did.
Back on Windows:
using FileZilla (again)
Copy the whole Nanpy directory from the firmware directory to under your "sketchbook" directory,
start your Arduino IDE, open Sketchbook/Nanpy, select "Upload"
(Then spend the rest of the evening getting some code to work).

(Warning - I haven't changed anything, but I read that you should edit cfg.h to get the libraries you want) - I bet TonyGo2 has the info? Mine seemed to work untouched so I assume it includes all the standard bits.

richrarobi
Posts: 271
Joined: Sun Feb 08, 2015 1:13 pm

Re: Using an Arduino as a slave I/O board

Sat Feb 14, 2015 10:03 pm

Nanpy0.9.2
I followed my notes to install on pi-01 (a model B used as Internet radio) - once it was connected properly ( !!! ) it worked (only flashing an LED, but it did flash) - again through the serial UART..

seems like a good idea to do these:
sudo apt-get update
sudo apt-get upgrade

if you want the serial port....
carefully
follow the guide on www.raspberrypi-spy.co.uk/2013/12/free- ... rial-port/

What is needed is a list of requirements - like what do you need to install?

Lots of Libraries on your Pi:-
I don't think it matters what the order is as long as they are there when you need them!

the following is the ino sketchbook stuff - I don't use it because I am on command line only on the Pi.
sudo apt-get install arduino

because I want to use serial I did this one:
sudo apt-get install python-serial

before you use pip, you need install it

sudo apt-get install python-pip
then:
sudo pip install RPi.GPIO
What is that used for? package to control gpio on the pi. Probably not needed for Nanpy.

the following is needed for i2c interface on pi - not needed for Nanpy
sudo apt-get install python-smbus

the next line didn't work, so resort to the web again as per the previous post to get the file from the nanpy0.9.2 web site.
wget http://pypi.python.org/packages/source/ ... 9.2.tar.gz

tar -xvf nanpy-v0.9.2.tar.gz
cd nanpy
sudo python setup.py install

probably a good idea to reboot:
sudo reboot

RichR
p.s. What exactly do you mean by crashing out?

User avatar
Onira
Posts: 237
Joined: Tue Oct 02, 2012 6:24 pm
Location: Poland

Re: Using an Arduino as a slave I/O board

Sun Feb 15, 2015 9:26 am

I followed the tutorial http://www.instructables.com/id/Arduino ... net-Radio/
but nanpy-0.7 code described there was playing the radio script for about 15 - 50 minutes
and then the script was crashing

then when tried to update to nanpy-0.9 it didn't upload on an Arduino board

but tonygo2 helped me to build nanpy-0.8 and atm code works for like about a week
I stop radio when going off to work and when come back I just turn it on til I go to bed
then every next day doing the same it's still working :)
Cogito ergo sum

richrarobi
Posts: 271
Joined: Sun Feb 08, 2015 1:13 pm

Re: Using an Arduino as a slave I/O board

Sun Feb 15, 2015 1:29 pm

I didn't use his script, it was too convoluted for my liking, I just used the install as guidance. I have been using direct commands to mpc from a remote ssh session to control the daemon. Now that the Arduino and LCD panel are working (Nanpy 0.9.2 on both Pi's) , I have begun work on a radio script of my own. I plan to use the lcd panel buttons, stop, start, etc. Might take a day (or twenty), though. I intend to make it so I can leave the Arduino off if I want. (Need to detect it is there.) More questions than answers! :?

One comment about my Nanpy install notes: It is possible that a relevant library may have already been present so wasn't needed for this install. But, I don't think that is the case. If a library shows up missing for you, let me know, we can compare.

RichR

User avatar
Onira
Posts: 237
Joined: Tue Oct 02, 2012 6:24 pm
Location: Poland

Re: Using an Arduino as a slave I/O board

Sun Feb 15, 2015 3:02 pm

Then please share your script if you have any ;)
I'm going to stay with the one that is working for me with nanpy-0.8
I am just too dumb to write anything myself :|
Cogito ergo sum

richrarobi
Posts: 271
Joined: Sun Feb 08, 2015 1:13 pm

Re: Using an Arduino as a slave I/O board

Mon Feb 16, 2015 9:02 pm

First the bad news (?!) - I have decided to ditch the lcd panel from the Arduino. Reason: - It takes up three quarters of the Ardy functionality, and sits there using power. Also when you drive the LCD with the PI it takes a lot of processing time, especially waiting for scrolling. If you want buttons it seems you have to poll. Not exactly real time, is it? I thought about the functions. Arduino for real world things, lights, servos, pots, etc, Pi to control it all. But, user interface? Well the best solution nowadays has to be a web interface!! So out with the panel and in with the web server (lighttpd). (the mpc/mpd and web server are mostly autonomous - all I have to do is put data somewhere for display on the web page, and send commands to control the mpd on another page. (see below in the code) :)
For the record, If anyone WANTS to use an lcd panel, here is some code that should work (using uart connection still).

Code: Select all

import os
import sys, traceback
import time

from time import sleep, strftime
from  nanpy import Arduino, Lcd, ArduinoApi, SerialManager, OneWire

# for the UART pins connection
conn = SerialManager(device='/dev/ttyAMA0')
a = ArduinoApi(connection=conn)
# the flashing LED commented out
#a.pinMode(2, a.OUTPUT)

# set pin 10 (backlight) LOW for safety
a.pinMode(10, a.OUTPUT)
a.digitalWrite(10, a.LOW)
# Never set backlight to HIGH (bug in some shields can burn Arduino)

# for the buttons on panel use analogue read 
a.pinMode(14, input)
lcd = Lcd([8,9,4,5,6,7],[16,2], connection=conn)

# params are character and line
lcd.setCursor(10,1)
# with the text only it will print at the current cursor
lcd.printString("Hello")
# or specify the start position
lcd.printString("Rich!", 0, 0)

# how to drive the radio daemon (not a program, just examples for now)
#os.system("mpc clear")
#os.system("mpc add <playlist.txt")
#os.system("mpc playlist")
#os.system('mpc play ' + str(7))
#os.system('mpc stop')
os.system('mpc status')

# this works but is very slow
def scrollText( blurb, line ):
   if len(blurb) > 16:
     oldText = blurb
     blurb = blurb + " "
     for i in range (0, len(blurb)):
      lcd.printString( blurb[i:(i+16)], 0, line )
      time.sleep( 0.35 )
     lcd.printString( oldText[:16], 0, line )
   else:
     lcd.printString( blurb, 0, line )

# error code possibly a bit iffy
def getKey():
   try:
      val = a.analogRead(14)
      if val == 1023:
         return "NONE"
      elif val < 100:
         return "RIGHT"
      elif val < 150:
         return "UP"
      elif val < 330:
         return "DOWN"
      elif val < 510:
         return "LEFT"
      elif val < 750:
         return "SELECT"
      else:
         return "ERR"
   except:
      print "Keyboard error"
      sys.exit(-1)

x = 0

while True:
   try:
      x = x + 1
      lcd.printString(16 * " ", 0,0)
# counting in first row
      lcd.printString(x, 0, 0 )
#scroll  output in line 1
#      scrollText("some very long text that won't fit on the screen", 1)
      sleep (1)

   except KeyboardInterrupt:
       lcd.printString(16*" ", 0, 0)
       lcd.printString(16*" ", 0, 1)
#       a.digitalWrite(10, a.LOW)
       print
       print "program stopped"
       sys.exit(0)

User avatar
Onira
Posts: 237
Joined: Tue Oct 02, 2012 6:24 pm
Location: Poland

Re: Using an Arduino as a slave I/O board

Tue Feb 17, 2015 6:51 am

Yes
I want to use internet radio without using a PC
so that's why I'm interested in having LCD and buttons :)
Cogito ergo sum

Sw0rdMast3R
Posts: 1
Joined: Tue Feb 17, 2015 3:28 pm

Re: Using an Arduino as a slave I/O board

Tue Feb 17, 2015 3:33 pm

Hi guys,

Would it be possible to have two Arduino slaves connected to a single RPi and talk to them as illustrated using nanpy?? The examples I managed to find are for communicating between a single Arduino and RPi.

Thanks in advance!

richrarobi
Posts: 271
Joined: Sun Feb 08, 2015 1:13 pm

Re: Using an Arduino as a slave I/O board

Tue Feb 17, 2015 3:52 pm

I don't think Nanpy implements interrupts (yet?), so the keyboard would have to be read by a polled approach - possibly a separate code thread? I will have to read the python manual!!
Have you considered tagging one of those Arduino keypads to your Pi GPIO? Maybe I will try that.

RichR
p.s. No Arduino found
A bit of error checking code for your perusal

Code: Select all

conn = SerialManager(device='/dev/ttyAMA0', timeout = 1)
try:
   a = ArduinoApi(connection=conn)
except :
   print "No Arduino found"
   sys.exit(0)

User avatar
Onira
Posts: 237
Joined: Tue Oct 02, 2012 6:24 pm
Location: Poland

Re: Using an Arduino as a slave I/O board

Tue Feb 17, 2015 5:31 pm

Arduino keypad to RPi?
but there are connections direct to Arduino (it's a shield)

Or am I not understanding? :roll:


EDIT
or maybe something like that http://www.dx.com/p/chuangzhuo-raspberr ... ite-292375 ??
I can get it in my country and it's not expensive.
Cogito ergo sum

richrarobi
Posts: 271
Joined: Sun Feb 08, 2015 1:13 pm

Re: Using an Arduino as a slave I/O board

Tue Feb 17, 2015 7:46 pm

I was thinking more something like this (but it doesn't have interrupts either, so you maybe don't gain anything),
Could interrupts be added somehow? It's an option, though.

http://www.mikronauts.com/raspberry-pi/ ... nd-python/

Or even this (He wants a better way, too!):
http://www.instructables.com/id/Using-a ... /?ALLSTEPS

User avatar
Onira
Posts: 237
Joined: Tue Oct 02, 2012 6:24 pm
Location: Poland

Re: Using an Arduino as a slave I/O board

Tue Feb 17, 2015 8:23 pm

but if using RPi (GPIOs) only for LCD do we really need interrupts? ;)
Cogito ergo sum

richrarobi
Posts: 271
Joined: Sun Feb 08, 2015 1:13 pm

Re: Using an Arduino as a slave I/O board

Tue Feb 17, 2015 10:09 pm

Have you seen this? re startup time of pi + arduino

http://www.raspberrypi.org/forums/viewt ... 0&p=446771

richrarobi
Posts: 271
Joined: Sun Feb 08, 2015 1:13 pm

Re: Using an Arduino as a slave I/O board

Wed Feb 18, 2015 1:03 am

This is very scary. Using threaded classes and sockets to scan the keypad on the LCD panel.
A background thread polls the hardware and sends messages via sockets (it is local but could be REMOTE to another system!!) to the listener (in this case it could be the radio app...) - the LCD keypad is now out of the trash. :roll:
cpu usage drops from around 90% with direct polling to around 6% using threads!!!!!
Has taken (us) all evening, and still needs a little refinement.
That dratted reset button is in a stupid place - it might get un-soldered!

Code: Select all

#!/usr/bin/python
import os, sys, threading, time, socket
from nanpy import ArduinoApi, SerialManager

connectionObj = SerialManager (device = '/dev/ttyAMA0', timeout = 1)
pollingFrequency = 0.06

try:
	arduinoObj = ArduinoApi(connection=connectionObj)
	print "Connected to Arduino :)"
except:
	error = sys.exc_info()[0]
	print "Error connecting to Arduino: %s" % error
	sys.exit()

class MonitorKeypress(threading.Thread):
	def __init__(self):
		threading.Thread.__init__(self)
		self.hasChanged = False
		self.keyValue = None

	def run(self):

		# set up socket connection for sending keypressess
		client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
		try:
			client.connect(('localhost',2727))
		except:
			print "Keypress client failed :("
			sys.exit()

		while True:
			# get the keypress voltage
			try:
				value = arduinoObj.analogRead(14)
				if value == 1023:
					if self.keyValue is not None:
						self.keyValue = None
						# client.send("None")
				elif value < 100:
					if self.keyValue is not "Right":
						self.keyValue = "Right"
						client.send("Right")
				elif value < 150:
					if self.keyValue is not "Up":
						self.keyValue = "Up"
						client.send("Up")
				elif value < 330:
					if self.keyValue is not "Down":
						self.keyValue = "Down"
						client.send("Down")
				elif value < 510:
					if self.keyValue is not "Left":
						self.keyValue = "Left"
						client.send("Left")
				elif value < 750:
					if self.keyValue is not "Select":
						self.keyValue = "Select"
						client.send("Select")
			except:
				error = sys.exc_info()[0]
				print "Error reading keyboard: %s" % error
				sys.exit()

			# sleep to preserve CPU cycles
			time.sleep(pollingFrequency)

# set up server for listening to keypresses
server = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # reuse the same port
try:
	server.bind(('',2727))
except:
	print "Keypress server failed :("
	sys.exit()
server.listen(2)
print "Keypress server listening..."

# set up thread for polling the hardware and sending them to the server
hardware = MonitorKeypress()
hardware.setDaemon(True)
hardware.start()

# listening for keypresses!
(channel, details) = server.accept()
print "Keypress client connected:", details[0], ", port:", details[1]

# receiving data... :)
while True:
	key = channel.recv(32)
	if key == "Up":
		print "Up up and away!!!"
RichR

richrarobi
Posts: 271
Joined: Sun Feb 08, 2015 1:13 pm

Re: Using an Arduino as a slave I/O board

Wed Feb 18, 2015 8:43 am

Would it be possible to have two Arduino slaves connected to a single RPi and talk to them as illustrated using nanpy?? The examples I managed to find are for communicating between a single Arduino and RPi.
Cannot see why not, if you use named connections. A different object for each one. Be very careful how you power the devices.

RichR

User avatar
Onira
Posts: 237
Joined: Tue Oct 02, 2012 6:24 pm
Location: Poland

Re: Using an Arduino as a slave I/O board

Wed Feb 18, 2015 5:53 pm

richrarobi wrote:This is very scary. Using threaded classes and sockets to scan the keypad on the LCD panel.
A background thread polls the hardware and sends messages via sockets (it is local but could be REMOTE to another system!!) to the listener (in this case it could be the radio app...) - the LCD keypad is now out of the trash. :roll:
cpu usage drops from around 90% with direct polling to around 6% using threads!!!!!
Has taken (us) all evening, and still needs a little refinement.
That dratted reset button is in a stupid place - it might get un-soldered!

...

RichR
Like I said before I'm a bit dumb and all this is kinda hard for me to understand... but am tryin' ;)


BTW... Shouldn't we start an other topic with Arduino+LCD?
Cogito ergo sum

richrarobi
Posts: 271
Joined: Sun Feb 08, 2015 1:13 pm

Re: Using an Arduino as a slave I/O board

Wed Feb 18, 2015 6:38 pm

Have you tried knitting? Seriously, It is MUCH harder than programming. I do find object programming quite difficult. I started when programs were sensible instructions in a row.
Good point about the LCD. Don't know. Maybe it is done? Try this, it actually controls the radio daemon (mostly just the code at the end) - playlist is just a list of streams and not a real playlist (see end of post). It is easy to forget that it is all going through Nanpy - it just works.

Code: Select all

#!/usr/bin/python
import os, sys, threading, time, socket
from time import sleep
from nanpy import ArduinoApi, SerialManager, Lcd

connectionObj = SerialManager (device = '/dev/ttyAMA0', timeout = 1)
pollingFrequency = 0.06

try:
	arduinoObj = ArduinoApi(connection=connectionObj)
	print "Connected to Arduino :)"
except:
#	error = sys.exc_info()[0]
#	print "Error connecting to Arduino: %s" % error
        print "Error connecting to Arduino: %s"
	sys.exit()

class MonitorKeypress(threading.Thread):
	def __init__(self):
		threading.Thread.__init__(self)
		self.hasChanged = False
		self.keyValue = None

	def run(self):

		# set up socket connection for sending keypressess
		client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
		try:
			client.connect(('localhost',2727))
		except:
			print "Keypress client failed :("
			sys.exit()

		while True:
			# get the keypress voltage
			try:
				value = arduinoObj.analogRead(14)
				if value == 1023:
					if self.keyValue is not None:
						self.keyValue = None
						# client.send("None")
				elif value < 100:
					if self.keyValue is not "Right":
						self.keyValue = "Right"
						client.send("Right")
				elif value < 150:
					if self.keyValue is not "Up":
						self.keyValue = "Up"
						client.send("Up")
				elif value < 330:
					if self.keyValue is not "Down":
						self.keyValue = "Down"
						client.send("Down")
				elif value < 510:
					if self.keyValue is not "Left":
						self.keyValue = "Left"
						client.send("Left")
				elif value < 750:
					if self.keyValue is not "Select":
						self.keyValue = "Select"
						client.send("Select")
			except:
				error = sys.exc_info()[0]
				print "Error reading keyboard: %s" % error
				sys.exit()

			# sleep to preserve CPU cycles
#			time.sleep(pollingFrequency)
                        sleep(pollingFrequency)

# set up server for listening to keypresses
server = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # reuse the same port
try:
	server.bind(('',2727))
except:
	print "Keypress server failed :("
	sys.exit()
server.listen(2)
print "Keypress server listening..."

# set up thread for polling the hardware and sending them to the server
hardware = MonitorKeypress()
hardware.setDaemon(True)
hardware.start()

# listening for keypresses!
(channel, details) = server.accept()
print "Keypress client connected:", details[0], ", port:", details[1]

st = 1
maxst = 9
volume = 75

lcd = Lcd([8,9,4,5,6,7],[16,2], connection=connectionObj)
lcd.printString(16*" ", 0, 0)
lcd.printString(16*" ", 0, 1)


# receiving data... :)
while True:
    key = channel.recv(32)
    if key == "Up":
#        print "Volume Up"
         volume = volume + 5
         if volume > 90: volume = 90
         os.system("mpc volume " + str(volume))

    if key == "Down":
#        print "Volume Down"
        volume = volume - 5
        if volume < 10: volume = 10
        os.system("mpc volume " + str(volume))

    if key == "Select":
        os.system("mpc clear")
        os.system("mpc add <playlist.txt")
        os.system("mpc playlist")
        os.system("mpc play 1")
        os.system("mpc volume " + str(volume))
        lcd.printString("station " + str(st), 0, 0 )

    if key == "Left":
        st = st - 1
        if st < 1: st = 1
        os.system("mpc play " + str(st))
        lcd.printString("station " + str(st), 0, 0 )

    if key == "Right":
        st = st + 1
        if st > maxst: st = maxst
        os.system("mpc play " + str(st))
        lcd.printString("station " + str(st), 0, 0 )

cat playlist.txt
http://stream.kgnu.net:8000/KGNU_live_high.mp3
mms://wmlive.bbc.co.uk/wms/england/lrstoke
http://stream2.hippynet.co.uk:8067/
http://wwoz-sc.streamguys.com/wwoz-hi.mp3
http://sj128.hnux.com
http://simplexstream.com:8506
mms://ysj00ms01s0.aliant.net/CJCB
http://208.92.54.5:80/CFMJAMAAC_SC
http://mp1.somafm.com:8800

RichR

Return to “Interfacing (DSI, CSI, I2C, etc.)”