Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

python code updated to python 3 #46

Open
dComposer opened this issue Jan 3, 2021 · 4 comments
Open

python code updated to python 3 #46

dComposer opened this issue Jan 3, 2021 · 4 comments

Comments

@dComposer
Copy link

dComposer commented Jan 3, 2021

I updated autoPlay.py (Chapter 5, serialOrgan) for python 3 (and skipped the serialorgansongs.jottit.com lines since that site no longer exists) and added some notes for figuring out the current serial port. Thanks so much for this wonderful book!

## Scripting in python to drive the serial-port organ

## So far, the "protocol" is simple.  
## Python routine sends a note, waits for a return character, then sends next, etc.
## Organ listens for notes, when it gets one sends an 'N' to say it's ready
 
import serial

def playString(noteString, serialPort):
  for letter in noteString:
    print(letter)
    serialPort.write(letter.encode())
    returnValue = serialPort.read(1)
    
if __name__ == "__main__":

  import time
  from urllib.request import urlopen

  ## Need to consider alternatives for Mac / Windows
  ## list all serial ports being used: python -m serial.tools.list_ports
  PORT = "/dev/cu.usbserial-14130" # Change this to the current serial port being used
  BAUD = 9600

  s = serial.Serial(PORT, BAUD)
  s.flush()                     
  ## flush clears the buffer so that we're starting fresh
  ## More on serial buffers later.

  ## An intentional example.  You can use this for playing music on purpose.
  playString("f g h j k l ; ]'[", s)
  input("Press enter for next demo\n")

  ## A fun / stupid example.  You can just type stuff and see what comes out.
  playString("hello there, this is a random string turned into 'music'", s)
  input("Press enter for next demo\n")

  ## Website no longer alive... skipping:
  ## A really frivolous example.  Play websites!
  ## Bonus points for first person to tweet themselves a song.
  #print ("Downloading song data from http://serialorgansongs.jottit.com/...")
  #import re
  #contentFilter = re.compile(r'<p>(.*?)</p>')
  #songSite = urlopen("http://serialorgansongs.jottit.com/").read()
  #songText = contentFilter.findall(songSite)[0]
  #playString(songText, s)
 
  ## Or interactive
  mySong = input("\nType in your own song: ")
  playString(mySong, s)
@dComposer
Copy link
Author

dComposer commented Jan 9, 2021

I updated Chapter 6's bossButton.py for python 3. The only changes were to add the parenthesis to the print statements and to change the response logic from:
if response = 'X'
to:
if response = b'X'

## Simple demo
## Sits forever listening to serial port
## When you press button, opens website of your choosing.
## Extend this to many buttons and you'll have a physical
##  web-launcher.  

BOSS_SITE = "http://www.cartalk.com/content/boss-redirect"
## or perhaps more topical...
XKCD = "http://xkcd.com/353/"

## list all serial ports being used: python -m serial.tools.list_ports
SERIAL_PORT = "/dev/cu.usbserial-14130"
BAUD_RATE = 9600

import serial
import webbrowser

sp = serial.Serial(SERIAL_PORT, BAUD_RATE, timeout = 5)
sp.flush()
print("Boss Button")

while(1):                 # Sit and wait forever
    response = sp.read(1) # get one byte
    if response == b'O':
        print("Got OK Byte.  Waiting for button press.")
    elif response == b'X':
        print("Got Boss Byte!  Alarm!")
        webbrowser.open(BOSS_SITE)
    else:
        print("Got nothing.  Still waiting.")

@dComposer dComposer changed the title updated autoPlay.py (chapter 5: serialOrgan) for python 3 python code updated to python 3 Jan 9, 2021
@dComposer
Copy link
Author

dComposer commented Jan 10, 2021

Chapter 7's serialScope.py updated for python 3:

import serial

def readValue(serialPort):
    return(ord(serialPort.read(1)))

def plotValue(value):
    """ Displays the value on a scaled scrolling bargraph"""
    leadingSpaces = "-" * int(value*(SCREEN_WIDTH-3) / 255)
    print(f"{leadingSpaces} {value:03}")

def cheapoScope(serialPort):
    while(1):
        newValue = readValue(serialPort)
        plotValue(newValue)
        

if __name__ == "__main__":
    ## list all serial ports being used: python -m serial.tools.list_ports
    PORT = '/dev/cu.usbserial-14230' # update to whatever port is listed in serial.tools.list_ports
    BAUDRATE =  9600
    TIMEOUT = None
    SCREEN_WIDTH = 80

    ## Take command-line arguments to override defaults above
    import sys
    if len(sys.argv) == 3:
        port = sys.argv[1]
        baudrate = int(sys.argv[2])
    else:                        # nothing passed, use defaults 
        print ("Optional arguments port, baudrate set to defaults.")
        port, baudrate = (PORT, BAUDRATE)
        
    serialPort = serial.Serial(port, baudrate, timeout=TIMEOUT)
    serialPort.flush()
    cheapoScope(serialPort)

@hexagon5un
Copy link
Owner

Hiya! That's lovely! I'll roll those into the code.

(I haven't been doing as much maintenance on this codebase as I probably should. Thanks for helping out.)

@dComposer
Copy link
Author

My pleasure! As I convert more python code over I'll post them into this issue. Thanks for writing this great book!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants