You are on page 1of 7
HP Prime Programming Program output of a Maurer rose and a famous hat demo from 1981 computer ads, BP Pie =O x | BaP Pine =n x Calculator Skine Edt Help Calculator Skins Eat Help HP Prime Graphing Calculator i mea See acide) Code: - Code: python or 1. Laptop or Calculator? I work in a lab and for years laptops have ruled. They pushed out calculators, which decades earlier did the same to slide rules. For the sort of work I do, I realize that the Prime can almost replace laptops for many needs. We do a lot of DSP with 1/Q (in-phase/quadrature) sampled signals, While the Prime has the horsepower to do a decent amount of that ‘work, the vital need stopping it from being more generally useful is that itis an ordeal to get signals onto it and results off of it, Itneeds wifi or Bluetooth for that and I doubt we'll see it because of potential use for cheating in educational settings. Yet, to be professionally useful it really must be networked. While its use is therefore greatly limited it's not useless. A powerful feature that makes it attractive for small jobs is programming, and we have two choices on the Prime: PPL and python. PPL Is well documented in the Prime user's manual and many web pages. Using information from the manual and some examples online I wrote a small program to try out PPL. Learning to use menus was the main reason for writing a small program that mimies Spirograph, Here is Spirograph PPI code that can be dropped into the HP Prime Programs folder visible from the HP Prime Connectivity Kit. Python on the Prime is more challenging because in late 2023 there is no formal HP python documentation. Additional information on the surface of revolution, the green hat, shown at the top of this page is on the hat page just below the spirograph curves up top. The program can be dropped into your Programs folder via the Connectivity Kit or the ‘unzipped app into the Application Library folder for a full-fledged app. (For some unknown reason you must hit the ‘Clear’ soft button after starting the app.) 2. Python Lessons Learned Since formal HP documentation is yet to be written, I list a few things I've leamed through googling and a good bit of trial and error, An important discovery is that the subroutine hpprine.eval('") is a way to get at PPL commands that don't have python equivalents. In particular, it allows easy access to menu-oriented subroutines so that you don’t have to write your own. The paragraphs below all have the caveat that these are solutions I found. Please let me know if there are better ones, 2.1 Library Changes 2.1.1 Miero- and HP-python Libraries Libraries are an important part of python's usefulness. The names of libraries and subroutines in each can be found on the Prime itself in the python app’s CMDS menu, They are reproduced for firmware 2.1.14730 (2023 04 13) in thi 2.1.2 numpy Numpy (NUMetic PYthon) is a large library and unsurprisingly not part of micropython. Nevertheless, itis hard living without it. Your numpy vectors and matrices must be rewritten to use the Prime's linalg.matrix and will of course be constrained to what linalg routines exist. 2.2 Program Format Every python program that is not based on the Python App needs a PPL (Prime Programming Language) wrapper: PYTHON PPLwrapper (Your python program goes here.) ‘END EXPORT myProg() BEGIN PYTHON(PPLwrapper); END; The name you use rather than PPLurapper is unimportant because the name that will show up under Programs is nyProg. 2.3 Screen Tap Events User taps on the sereen are categorized as mouse events in the Prime. The user manual has details on the MOUS! call. I simply reuse the following subroutines in each of my programs requiring mouse input: import hpprine as h def mouseClear(): # Clear out old, waiting mouse events while h.eval( ‘mouse(1)')>=0: pass def mousept(): # ait forever for a screen touch while True: h.eval(‘wait(@.1)') # Throttle i/o loop 1,42 = heeval (‘mouse’) # Touch info for Fingers 1 and 2. Af len(f1) > @: # Got 2 finger touch! return #1,42 # [x,y,xOrig,yOrig, type], [x,y,x0rig,yOrig, type] nouseClear clears out any outstanding mouse events that we don't care about. If no events are waiting a -1 is returned and is why output of 0 or more is checked for. MOUSE(1) returns the x coordinate of a tap that would have been retumed. mouse?t is useful when your program must wait until there is a screen touch, for example when a soft menu choice is required. It retums data for both finger touches, The second finger data will be empty in the case of a single finger touch, 2.4 Pop Up Menu Pop up menus can be created using the PPL subroutine CHOOSE(): import hpprine as h € = h.eval(“choose(x, "Title", hoce 1","Cholce 2", "Choice 3")') The first parameter to CHOOSE() must be a single capitalized letter. As far as I can tell, you can treat it as a dummy variable because the user's choice is eval('s return value. The return value begins with 1 (not 0). 2.5 Soft Menu The PPL routine DRAWMENU is an easy way to display custom menus. To act on a user press is a short sequence: + Wait on a mouse press using mousePt(, above. ‘+ Determine which button was pressed with softPick(), below. ‘Handle button function accordingly. The full code s equence for a program's main loop might be: import hpprine as h def main(): while True: heeval(‘drawmenu("iten", “Item”, "Item2", "rten3", m= mousePt() # Get user screen’ tap coordinates. b= softPick(m) # -1 if not a soft menu tap. if b == 0: dortend() elif b == 1: dottent() elif b == dortena() elif b == 3: dotten3() elif b == a: dottend() elif b == 5: dortens() +) "Etens")") Determining which soft button is pushed is easy keeping in mind that the six soft buttons are $3x20 pixels and the screen is 320x240 pixels. def softPick(pt): # pt is [x, y, xOrig, yOrig, type] xy = pt[e), ptt] Af yc220: return -1 # Not in soft menu region. return x//53 # Return button number @ to 5. 2.6 User Input As with other menu related functionality, a PPL subroutine is used to obtain user input: import hpprine as ih dLm,f Hz = h.eval("input({0,F), \ "Ereespace Loss", {"ist=","Freq="}, \ {"Distance, m", “Frequency, Hz"}); \ {0,F}") Line breaks are used for clarity. Importantly, eval() returns a list that is the same length as the list which is the first argument to input). In the above example the first arg is {D,F} meaning that eval() will return a list of length 2. The second input( arg is pop up menu title and the third arg is the list of labels shown by each input box. The last arg of input() are more detailed help messages shown the bottom of the Prime's screen when each input box is highlighted. A ssemicolon ends the input() call and is followed by the list of variable values that user inputted, This list can be ‘thought of as the return value of the PPL statements. In this example, inputs D and F are assigned to d_m and f_Hz, which are used in subsequent python code. 2.7 User Output (2.7.1 Present To Screen’ It is necessary sometimes to build up a string to pass to a PPL subroutine via eval(). For example, suppose I have built up a string in variable s that I would like to present on the screen’ import hpprine as cond = ‘msgbox("%: h.eval(cnd) 2.7.2 Move To Prime Environment As far as I can tell, itis only possible to export variables associated with an App. PPL's EXPORT command does not seem useable via hpprime.eval(). Creating an app is only a very little bit more involved than writing a program, but still :st to devote a full section to it, 2.8 Creating an App Creating a python app is easy, but as mentioned earlier, you lose the tight integration with the Prime that is (only?) possible via HP PPL. In particular, PPL subroutines START(), RESETO, Info(), Symb0), Plot), Num() and Setup ‘counterparts of the last three can be implemented so that when those physical and soft buttons on the calculator are pressed, your subroutines are executed. I have not succeeded in doing the same in python, However, python has great appeal and step one is to create an empty app based on python: 1. Press Apps button. 2. Press Python icon. 3. Press Save soft menu item, 4, Rename the App. ‘Now move on to add files and an icon. The icon is what shows up on the list of Apps and seems to be 38x38 pixels. To add files and icon start up the Connectivity Kit. Under Applications you'll see your new app and right click on its name: [6B HP connectivity Kit File Edit Window Help SBdd ° ae (caters ax aw ¥ [Medes \/ Progam \/ info \/ Fes \/Varabes \ ‘This some info about 1981 Hat. > BB Advanced Graphing > IB ate Streamer > B explorer For each python and other needed files you must click ‘Add file’ and navigate to it, And same for your custom icon after clicking ‘Add app icon’. After your code has been added to the app you simply choose it from the App icon list and then the soft menu 'Start' option. No doubt it will run bug free fitst try because you are an expert coder! :-) Here is a demo program you ean add to an app: inport hpprime as h def wain( h.eval ("AVars(“MyVar") ieval(‘avars(*Myvar2") hleval(‘Avars(*syvar3") nohveval("AVars (*HyVvar' coh. eval ‘AVars (*HyVar’ seh.eval(‘AVars("HyWar3")") h.eval("print") # Clear screen. "1234 is now type Xs" % str(type(n))) =(3y4) is now type Xs" X str(type(c))) nike" is now type Xs‘ % ste(type(s))) print('Press + to end dero.") while True: heval(‘wait(®.2)") # Throttle i/o loop. 4H Retrieve mouse & keyboard events. beh.eval("getkey’) # Keyboard button press, -1 if none since last call. #1,f2sh.eval('mouse") # Finger 1, finger 2 touch data. Af len(F1)>0: # Finger touch sensed. # Mouse data: [x,y,xOrig,yOrig, type]. print(’You touched (%d,%d)' % (F1[@],f1[1]), ef Af len(#2)>0: # Two Finger touch. print(" and (%4,%4)' % (#2[0],#2(2])) else: print() if <1: # No button pressed. continue print("You pressed button %d" % b) if b==50: # + button exits demo. print(‘slan!") break main() Finally, you must create the app's main program. I find it easiest to simply import my code and not otherwise put code here: [BB HP Connectivity Kit File Edit Window Help "8 di ° om | clus ex |A@ ~ +B uPPine © Applaton Libary i vi hat1981 vmne sort hat 19 ening hat oy 1 ieongng > Variables > BB Advanced Graphing The first roughly ten lines of main() show how you can share app results externally. This is necessary if you want to ‘work with program results outside the program. I save an int, complex and string. The first three lines of output show what is retrieved HP Prime Graphing Calculator Brann ne G,4) is now type "Mike” is now type fou touched (287,225) fou pressed button 26 (ou pressed button 50 an! de and we sce that all is well, though int becomes float. After the program runs, switch to CAS where you can retrieve and work with the results of your program: HP Prime Graphing Calculator FES 11981 Hat BB |[ivodes feadvanced Graphing >||2Program »fiMyvar Function lemyvar2 Explorer lsmyvar3| Finance jsPython Triangle Solver feParametric simpli The infinite loop in the program above shows how to handle button pushes and screen touches. Screen touch data is returned for two fingers. You can try this demo code on your real Prime. Depending on your computer the two finger events might or might not register. The WAIT(0.2) ensures that I/O is only done 5 times a second, Next, both mouse and keyboard events are retrieved. If keyboard button number is «1 then no button was pushed since la MOUSE returns ({),[J] then no screen touch happened since last check. The User Manual describes how GETKEY works and provides a useful diagram showing button numbering, For this demo code the "+" button stops the demo. 2.9 HOME/PPL Bug AVars() appears to be the only way to move share results from an app for further use outside the program. However, ‘there is a parsing bug in PPL when in the HOME environment. If there is a plus sign in the exponent, a valid construct, itresults in an error. For example, 2e1 is parsed properly but 2e+1 incorrectly yields an error message. Short of a bug, fix, and Moravia didn't reply to my email, here is an easy solution: def nunToavars(varNane, val) end = ‘AVars("Xs"):=%.11e" % (varNane, val) # Prime has 12 sig figs. cnd = cnd.replace('+', '') # HOME/PPL’ can't parse exponents with '+". heeval (end) To move a value out of the app to a variable named 'solution’, your python program calls nuaToavars: numtoavars(‘solution’, eyNunber) 3. Feedback Wanted The preceding has been gleaned from trial and error, emailing knowledgeable people like Eddie Shore, the User Manual's section on PPL and a good bit of general web searching. I'm certain, therefore, that there are better ways of doing some of the things I presented. If you can improve the above, please get in touch! Many thanks, Mike Markowski, nike. ab3ap@gnail.con

You might also like