diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index f85a23cd..878056ac 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -22,11 +22,51 @@ This document will introduce you to the repository's structure and how the PiSto
- A remote control is available, which is particularly useful on a mobile device. There is a joystick to move your robot (using motors B and C). There are also sliders to set the LED colors.
- Log files are also accessible from the web interface
+
+## Coordinate systems
+
+| | | |
+| --- | :---: | --- |
+| x=320
y=0 | | x=0
y=0 |
+| | TS
(readings from touchscreen X/Y registers) | |
+| x=320
y=240 | | x=0
y=240 |
+
+| | | |
+| --- | :---: | --- |
+| x=0
y=320 | | x=0
y=0 |
+| | Screen
(drawing to TFT) | |
+| x=240
y=320 | | x=240
y=0 |
+
+| | | |
+| --- | :---: | --- |
+| x=0
y=0 | | x=320
y=0 |
+| | Rotation 3
(right-side-up) | |
+| x=0
y=240 | | x=320
y=240 |
+
+| | | |
+| --- | :---: | --- |
+| x=320
y=240 | | x=0
y=240 |
+| | Rotation 1
(up-side-down) | |
+| x=320
y=0 | | x=0
y=0 |
+
+| | | |
+| --- | :---: | --- |
+| x=0
y=320 | | x=0
y=0 |
+| | Rotation 0
(Bank A up) | |
+| x=240
y=320 | | x=240
y=0 |
+
+| | | |
+| --- | :---: | --- |
+| x=240
y=0 | | x=240
y=320 |
+| | Rotation 2
(Bank B up) | |
+| x=0
y=0 | | x=0
y=320 |
+
+
## Repository files
### setup
#### Suggestions
-- When developing, hard link the source files from `/home/pi/PiStorms/...` to their destinations from `setup.sh` ([script](https://gist.github.com/seth10/e41a091ef56d0044474e82f3541755e4))
+- When developing, hard link the source files from `/home/pi/PiStorms/...` to their destinations from `setup.sh`. You can wget this [script](https://gist.githubusercontent.com/seth10/e41a091ef56d0044474e82f3541755e4/raw/PiStorms_Development.sh) to `/home/pi/PiStorms/.git/hooks/post-checkout`.
```bash
b=`grep homefolder /usr/local/mindsensors/conf/msdev.cfg | cut -d"=" -f2 | cut -c 2-`
for f in 'MSDriver.py' 'MSBrowser.py' 'psm_shutdown' 'swarmserver' 'pistorms-diag.sh'; do sudo ln -f $b/sys/$f /usr/local/bin/$f; done
diff --git a/artwork/artwork-for-images.png b/artwork/artwork-for-images.png
old mode 100755
new mode 100644
diff --git a/artwork/river-bank.jpg b/artwork/river-bank.jpg
old mode 100755
new mode 100644
diff --git a/programs/00-About_Me.py b/programs/00-About_Me.py
index 9bf6a8fe..95cb946e 100644
--- a/programs/00-About_Me.py
+++ b/programs/00-About_Me.py
@@ -76,7 +76,7 @@ def get_ip_address(ifname):
except:
psm.screen.termPrintAt(7," wlan0 : not present")
- if( psm.isKeyPressed() == True or psm.screen.checkButton(0,0,320,320)):
+ if( psm.isKeyPressed() == True or psm.screen.isTouched()):
psm.screen.termPrintln("")
psm.screen.termPrintln("Exiting to menu")
exit = True
diff --git a/programs/30-DataVisualization/02-Polar.py b/programs/30-DataVisualization/02-Polar.py
new file mode 100644
index 00000000..78f77a7c
--- /dev/null
+++ b/programs/30-DataVisualization/02-Polar.py
@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+#
+# Copyright (c) 2017 mindsensors.com
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 2 as
+# published by the Free Software Foundation.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+#
+#mindsensors.com invests time and resources providing this open source code,
+#please support mindsensors.com by purchasing products from mindsensors.com!
+#Learn more product option visit us @ http://www.mindsensors.com/
+#
+# History:
+# Date Author Comments
+# 06/15/17 Seth Tenembaum Initial development
+#
+
+# This program demonstrates using a polar graph
+# to show the AbsoluteIMU's compass heading.
+
+from PiStorms import PiStorms
+psm = PiStorms()
+psm.screen.termPrintln("Please wait a moment")
+psm.screen.termPrintln("as matplotlib loads...")
+psm.screen.termPrintln("")
+psm.screen.termPrintln("Press and hold GO briefly")
+psm.screen.termPrintln("to stop the program running.")
+
+import matplotlib
+matplotlib.use("AGG")
+import matplotlib.pyplot as plt
+import numpy as np
+import tempfile
+from mindsensors import ABSIMU
+
+plt.figure(figsize=(4,3), dpi=80)
+plt.title('AbsoluteIMU Compass Heading')
+
+data = np.empty(0)
+sub = plt.subplot(projection='polar')
+sub.set_theta_direction(-1)
+sub.set_rticks([]) # hide ticks
+tau = 2*np.pi
+
+imu = ABSIMU()
+psm.BAS1.activateCustomSensorI2C()
+image = tempfile.NamedTemporaryFile()
+
+while not psm.isKeyPressed():
+ h = imu.get_heading()
+ data = np.append(data, \
+ np.interp(h, [0,360], [0,tau]))
+ r = np.arange(len(data))
+ plt.plot(data, r, color="blue")
+ plt.savefig(image.name, format="png")
+ psm.screen.fillBmp(0,0, 320,240, image.name)
+
diff --git a/programs/45-Utils/05-BatteryVolt.py b/programs/45-Utils/05-BatteryVolt.py
index fe08d117..c204d228 100644
--- a/programs/45-Utils/05-BatteryVolt.py
+++ b/programs/45-Utils/05-BatteryVolt.py
@@ -53,7 +53,7 @@
psm.led(1,255,0,0)
psm.led(2,255,0,0)
lastled = 3
- if(psm.screen.checkButton(0,0,320,320)):
+ if(psm.screen.isTouched()):
psm.screen.termPrintln("")
psm.screen.termPrintln("Exiting to menu")
psm.led(1,0,0,0)
diff --git a/programs/50-CameraDemos/00-TakeSelfie.py b/programs/50-CameraDemos/00-TakeSelfie.py
index d643ba5c..fadee35f 100644
--- a/programs/50-CameraDemos/00-TakeSelfie.py
+++ b/programs/50-CameraDemos/00-TakeSelfie.py
@@ -53,7 +53,7 @@
time.sleep(1)
psm.screen.termPrintAt(9, "Touch the screen to exit")
- if (psm.screen.checkButton(0,0,320,320)):
+ if (psm.screen.isTouched()):
psm.screen.clearScreen()
psm.screen.termPrintAt(9,"Exiting to menu")
time.sleep(0.5)
diff --git a/programs/50-CameraDemos/03-CensorFaces.py b/programs/50-CameraDemos/03-CensorFaces.py
index 7ce2517a..81666f2b 100644
--- a/programs/50-CameraDemos/03-CensorFaces.py
+++ b/programs/50-CameraDemos/03-CensorFaces.py
@@ -76,7 +76,7 @@
elif (len(faces)) == 1:
psm.screen.termPrintAt(8, " Found {0} face!".format(len(faces)))
- if (psm.screen.checkButton(0,0,320,320)):
+ if (psm.screen.isTouched()):
psm.screen.clearScreen()
psm.screen.termPrintAt(9,"Exiting to menu")
time.sleep(0.5)
diff --git a/programs/50-CameraDemos/03-IsolateFaces.py b/programs/50-CameraDemos/03-IsolateFaces.py
index 2b039628..7242e5d9 100644
--- a/programs/50-CameraDemos/03-IsolateFaces.py
+++ b/programs/50-CameraDemos/03-IsolateFaces.py
@@ -86,7 +86,7 @@
elif (len(faces)) == 1:
psm.screen.termPrintAt(8, " Found {0} face!".format(len(faces)))
- if (psm.screen.checkButton(0,0,320,320)):
+ if (psm.screen.isTouched()):
psm.screen.clearScreen()
psm.screen.termPrintAt(9,"Exiting to menu")
time.sleep(0.5)
diff --git a/programs/50-MotorDemos/04-Motor-ShowPos.py b/programs/50-MotorDemos/04-Motor-ShowPos.py
index d70015a3..6df20a9b 100644
--- a/programs/50-MotorDemos/04-Motor-ShowPos.py
+++ b/programs/50-MotorDemos/04-Motor-ShowPos.py
@@ -61,7 +61,7 @@
#
# check if screen touched.
#
- if(psm.screen.checkButton(0,0,320,320)):
+ if(psm.screen.isTouched()):
# if scren was touched,
psm.BAM1.resetPos()
time.sleep(.001)
diff --git a/programs/50-SensorDemos/01-EV3-InfraredSensor.py b/programs/50-SensorDemos/01-EV3-InfraredSensor.py
index 41d833f1..72c09b9c 100644
--- a/programs/50-SensorDemos/01-EV3-InfraredSensor.py
+++ b/programs/50-SensorDemos/01-EV3-InfraredSensor.py
@@ -89,7 +89,7 @@
psm.screen.termPrintln("Exiting to menu")
doExit = True
change = 0
- if(psm.screen.checkButton(0,0,320,320)): #Change mode if screen is tapped
+ if(psm.screen.isTouched()): #Change mode if screen is tapped
count = count + 1
if ( count > 2):
count = 0
diff --git a/programs/50-SensorDemos/04-EV3-ColorSensor.py b/programs/50-SensorDemos/04-EV3-ColorSensor.py
index a9a907d1..33af64f4 100644
--- a/programs/50-SensorDemos/04-EV3-ColorSensor.py
+++ b/programs/50-SensorDemos/04-EV3-ColorSensor.py
@@ -75,7 +75,7 @@
#
# check if screen touched.
#
- if(psm.screen.checkButton(0,0,320,320)):
+ if(psm.screen.isTouched()):
# if screen was touched,
# reset BAS1 touch count
count = count + 1
diff --git a/programs/50-SensorDemos/04-EV3-TouchSensor.py b/programs/50-SensorDemos/04-EV3-TouchSensor.py
index 0f8dce67..0ec65c08 100644
--- a/programs/50-SensorDemos/04-EV3-TouchSensor.py
+++ b/programs/50-SensorDemos/04-EV3-TouchSensor.py
@@ -73,7 +73,7 @@
#
# check if screen touched.
#
- if(psm.screen.checkButton(0,0,320,320)):
+ if(psm.screen.isTouched()):
# if scren was touched,
# reset BAS1 touch count
psm.BAS1.resetTouchesEV3()
diff --git a/programs/50-SensorDemos/04-NXT-LightSensor.py b/programs/50-SensorDemos/04-NXT-LightSensor.py
index 886ad04f..775623d1 100644
--- a/programs/50-SensorDemos/04-NXT-LightSensor.py
+++ b/programs/50-SensorDemos/04-NXT-LightSensor.py
@@ -71,7 +71,7 @@
#
# check if screen touched.
#
- if(psm.screen.checkButton(0,0,320,320)):
+ if(psm.screen.isTouched()):
# if scren was touched,
if ( reflectiveMode == False):
reflectiveMode = True
diff --git a/programs/50-SensorDemos/04-NXT-TouchSensor.py b/programs/50-SensorDemos/04-NXT-TouchSensor.py
index 260f8073..b8ef430c 100644
--- a/programs/50-SensorDemos/04-NXT-TouchSensor.py
+++ b/programs/50-SensorDemos/04-NXT-TouchSensor.py
@@ -73,7 +73,7 @@
#
# check if screen touched.
#
- if(psm.screen.checkButton(0,0,320,320)):
+ if(psm.screen.isTouched()):
# if scren was touched,
# reset BAS1 touch count
psm.BAS1.resetTouchesNXT()
diff --git a/programs/50-SensorDemos/40-EV3ColorSensor.py b/programs/50-SensorDemos/40-EV3ColorSensor.py
index 500b2387..aa983b57 100644
--- a/programs/50-SensorDemos/40-EV3ColorSensor.py
+++ b/programs/50-SensorDemos/40-EV3ColorSensor.py
@@ -78,7 +78,7 @@
psm.screen.termPrintln("Exiting to menu")
doExit = True
change = 0
- if(psm.screen.checkButton(0,0,320,320)): #Change mode if screen is tapped
+ if(psm.screen.isTouched()): #Change mode if screen is tapped
count = count + 1
if ( count > 2):
count = 0
diff --git a/programs/50-SensorDemos/40-EV3Gyro.py b/programs/50-SensorDemos/40-EV3Gyro.py
index 4b644159..fa21bf4b 100644
--- a/programs/50-SensorDemos/40-EV3Gyro.py
+++ b/programs/50-SensorDemos/40-EV3Gyro.py
@@ -69,7 +69,7 @@
psm.screen.termPrintln("Exiting to menu")
doExit = True
change = 0
- if(psm.screen.checkButton(0,0,320,320)): #Change mode if screen is tapped
+ if(psm.screen.isTouched()): #Change mode if screen is tapped
count = count + 1
if ( count > 1):
count = 0
diff --git a/programs/50-SensorDemos/40-EV3InfraredSensor.py b/programs/50-SensorDemos/40-EV3InfraredSensor.py
index 5f8f3f1f..ec1081a3 100644
--- a/programs/50-SensorDemos/40-EV3InfraredSensor.py
+++ b/programs/50-SensorDemos/40-EV3InfraredSensor.py
@@ -87,7 +87,7 @@
psm.screen.termPrintln("Exiting to menu")
doExit = True
change = 0
- if(psm.screen.checkButton(0,0,320,320)): #Change mode if screen is tapped
+ if(psm.screen.isTouched()): #Change mode if screen is tapped
count = count + 1
if ( count > 2):
count = 0
diff --git a/programs/50-SensorDemos/40-EV3Ultrasonic.py b/programs/50-SensorDemos/40-EV3Ultrasonic.py
index 3f50e5a5..ea532c84 100644
--- a/programs/50-SensorDemos/40-EV3Ultrasonic.py
+++ b/programs/50-SensorDemos/40-EV3Ultrasonic.py
@@ -79,7 +79,7 @@
psm.screen.termPrintln("Exiting to menu")
doExit = True
change = 0
- if(psm.screen.checkButton(0,0,320,320)): #Change mode if screen is tapped
+ if(psm.screen.isTouched()): #Change mode if screen is tapped
count = count + 1
if ( count > 2):
count = 0
diff --git a/programs/50-SensorDemos/40-NXTLightSensor.py b/programs/50-SensorDemos/40-NXTLightSensor.py
index 74b3b649..efaba7b4 100644
--- a/programs/50-SensorDemos/40-NXTLightSensor.py
+++ b/programs/50-SensorDemos/40-NXTLightSensor.py
@@ -74,7 +74,7 @@
psm.screen.termPrintln("Exiting to menu")
doExit = True
change = 0
- if(psm.screen.checkButton(0,0,320,320)): #Change mode if screen is tapped
+ if(psm.screen.isTouched()): #Change mode if screen is tapped
count = count + 1
if ( count > 1):
count = 0
diff --git a/programs/50-SensorDemos/40-TouchSensor.py b/programs/50-SensorDemos/40-TouchSensor.py
index 3d7113f8..fb508a07 100644
--- a/programs/50-SensorDemos/40-TouchSensor.py
+++ b/programs/50-SensorDemos/40-TouchSensor.py
@@ -73,7 +73,7 @@
psm.screen.termPrintAt(4, msg2)
- elif(psm.screen.checkButton(0,0,320,320)):
+ elif(psm.screen.isTouched()):
#
# check if screen touched.
#
diff --git a/programs/60-Games/04-GoButton.py b/programs/60-Games/04-GoButton.py
index 92a0485b..27f3a6ed 100644
--- a/programs/60-Games/04-GoButton.py
+++ b/programs/60-Games/04-GoButton.py
@@ -45,7 +45,7 @@
psm.screen.termPrintAt(5, "GO Button is = " +str(psm.isKeyPressed()))
psm.screen.termPrintAt(6, "Press Count = " +str(psm.getKeyPressCount()))
- if (psm.screen.checkButton(0,0,320,320)):
+ if (psm.screen.isTouched()):
psm.screen.termPrintln(" ")
psm.screen.termPrintln("Exiting .....")
exit = True
diff --git a/programs/60-Games/04-Paint.py b/programs/60-Games/04-Paint.py
index 2c0c0386..a37003d8 100644
--- a/programs/60-Games/04-Paint.py
+++ b/programs/60-Games/04-Paint.py
@@ -20,8 +20,7 @@
if psm.isF4Pressed():
color = (0, 0, 255)
- tsx, tsy = psm.screen.getTouchscreenValues()
- if (tsx, tsy) != (0, 0):
- x = psm.screen.TS_To_ImageCoords_X(tsx,tsy)
- y = psm.screen.TS_To_ImageCoords_Y(tsx,tsy)
+ if psm.screen.isTouched():
+ x = psm.screen.TS_To_ImageCoords_X(psm.screen.x, psm.screen.y)
+ y = psm.screen.TS_To_ImageCoords_Y(psm.screen.x, psm.screen.y)
psm.screen.fillRect(x-1, y-1, 2, 2, fill=color)
diff --git a/programs/folder.png b/programs/folder.png
old mode 100755
new mode 100644
diff --git a/programs/leftarrow.png b/programs/leftarrow.png
old mode 100755
new mode 100644
diff --git a/programs/missing.png b/programs/missing.png
old mode 100755
new mode 100644
diff --git a/programs/ms-logo-w320-h240.png b/programs/ms-logo-w320-h240.png
old mode 100755
new mode 100644
diff --git a/programs/python.png b/programs/python.png
old mode 100755
new mode 100644
diff --git a/programs/refresh.png b/programs/refresh.png
deleted file mode 100644
index 6249b9c5..00000000
Binary files a/programs/refresh.png and /dev/null differ
diff --git a/programs/refresharrow.png b/programs/refresharrow.png
new file mode 100644
index 00000000..254325cc
Binary files /dev/null and b/programs/refresharrow.png differ
diff --git a/programs/returnarrow.png b/programs/returnarrow.png
new file mode 100644
index 00000000..4989a5d2
Binary files /dev/null and b/programs/returnarrow.png differ
diff --git a/programs/rightarrow.png b/programs/rightarrow.png
old mode 100755
new mode 100644
diff --git a/programs/touch_sensor_tutorial.py b/programs/touch_sensor_tutorial.py
index 93e917b7..36ceb74d 100644
--- a/programs/touch_sensor_tutorial.py
+++ b/programs/touch_sensor_tutorial.py
@@ -48,7 +48,7 @@
numTouch = psm.BBS1.numTouchesEV3()
psm.screen.termReplaceLastLine(str(touch) + " " + str(numTouch))
- if(psm.screen.checkButton(0,0,320,320)):
+ if(psm.screen.isTouched()):
psm.screen.termPrintln("")
psm.screen.termPrintln("Exiting to menu")
doExit = True
diff --git a/programs/uparrow.png b/programs/uparrow.png
old mode 100755
new mode 100644
diff --git a/programs/utils/01-Calibrate.py b/programs/utils/01-Calibrate.py
index 077991b5..26aedd38 100644
--- a/programs/utils/01-Calibrate.py
+++ b/programs/utils/01-Calibrate.py
@@ -23,176 +23,15 @@
# Date Author Comments
# 05/25/16 Deepak Initial development.
# 12/21/16 Seth Rewrite for new touchscreen calibration strategy
+# 06/26/17 Seth Instruct user to contact support
#
-from __future__ import division # for decimal division
-import os # to check if cache file exists, possibly launch a painting program, and restart the browser
-import ConfigParser # to get PiStorms home folder if launching paint
-import time # to periodically decrement calibration confirmation countdown
-import sys # to exit if GO button is not pressed to confirm beginning calibration
-import json # to write calibration values to cache file
-from mindsensorsUI import mindsensorsUI
-from PiStormsCom import PiStormsCom
+from PiStorms import PiStorms
-if PiStormsCom().GetFirmwareVersion() < 'V3.00':
- os.system("sudo python " + os.path.join(os.path.dirname(os.path.realpath(__file__)), "01-Calibrate_old.py"))
- sys.exit(0)
+psm = PiStorms()
-#########
-# Setup #
-#########
+m = [ "Touch Screen Calibration",
+ "Calibration is disabled in this relese. If you need assistance, please contact mindsensors support at: support@mindsensors.com"
+ ]
+psm.screen.showMessage(m, wrapText=True)
-# the browser needs to be stopped and restarted to read the new touchscreen values when calibration finishes
-os.system("/etc/init.d/MSBrowser.sh stop")
-
-# avoid 'Failed to read touchscreen calibration values' popup from mindsensorsUI if the touchscreen calibration values cache file doesn't exist
-if not os.path.isfile('/tmp/ps_ts_cal'):
- open('/tmp/ps_ts_cal', 'w').write('{}')
-
-# modeled after PiStorms class
-s = mindsensorsUI("PiStorms", 3) # screen
-psc = PiStormsCom() # commmunications
-comm = psc.bankA # short hand
-
-# how many samples to take and average when capturing touchscreen values
-# 200 takes about a second
-CALIBRATION_POINTS_COUNT = 200
-
-# what percent to push the crosshairs from the edges of the screen
-# 0 is the exact corner, 0.5 is the center
-INSET_PERCENT = 0.25
-
-
-
-#############################
-# Introduce program to user #
-#############################
-if not (len(sys.argv) > 1 and str(sys.argv[1]) == "force"):
- s.termGotoLine(0)
- s.termPrintln("Touch Screen Calibration Program")
- s.termPrintln("")
- s.termPrintln("You should only calibrate if you")
- s.termPrintln("notice your touchscreen being")
- s.termPrintln("inaccurate.")
- s.termPrintln("")
- s.termPrintln("If you still want to calibrate,")
- s.termPrintln("press the GO button")
-
- countdown = 10
- startKeyPressCount = psc.getKeyPressCount()
- while countdown > 0 and psc.getKeyPressCount() == startKeyPressCount:
- s.termReplaceLastLine("within %d second%s" % (countdown, 's' if countdown > 1 else ''))
- time.sleep(1)
- countdown = countdown - 1
-
- if psc.getKeyPressCount() == startKeyPressCount:
- sys.exit(0) # note: MSBrowser will automatically restart
-
-s.clearScreen()
-s.dumpTerminal()
-s.termGotoLine(0)
-s.termPrintln("Touch and hold the stylus")
-s.termPrintln("PRECISELY on each crosshair.")
-s.termPrintln("")
-s.termPrintln("Don't move the stylus until")
-s.termPrintln("the crosshair moves to the")
-s.termPrintln("next point.")
-s.termPrintln("")
-s.termPrintln("Press the GO button to continue.")
-startKeyPressCount = psc.getKeyPressCount()
-while psc.getKeyPressCount() == startKeyPressCount: time.sleep(0.1)
-
-
-
-##########################
-# Get calibration values #
-##########################
-
-def getPoints():
- x = []
- y = []
- for i in range(CALIBRATION_POINTS_COUNT):
- x.append(s.RAW_X())
- y.append(s.RAW_Y())
- x = sum(x)/len(x)
- y = sum(y)/len(y)
- return (x, y)
-
-# x and y coordinates for center of crosshair, l is the length of lines, f is the fill color
-def drawCrosshair(x, y, l, f):
- s.fillRect(x-l, y, l*2, 0, fill=f, display=False)
- s.fillRect(x, y-l, 0, l*2, fill=f)
-
-def getCalibrationValues(x, y):
- LENGTH = 10
- FILL = (0,255,0)
-
- s.clearScreen()
- drawCrosshair(x, y, LENGTH, FILL)
- startKeyPressCount = psc.getKeyPressCount()
- while psc.getKeyPressCount() == startKeyPressCount: time.sleep(0.1)
- return getPoints()
-
-p = INSET_PERCENT
-rx4, ry4 = getCalibrationValues(320*(1-p), 240*p) # top-right
-rx1, ry1 = getCalibrationValues(320*p, 240*p) # top-left
-rx3, ry3 = getCalibrationValues(320*(1-p), 240*(1-p)) # bottom-right
-rx2, ry2 = getCalibrationValues(320*p, 240*(1-p)) # bottom-left
-rx5, ry5 = getCalibrationValues(320*0.5, 240*0.5) # center
-s.clearScreen()
-
-x1 = rx1-(rx5-rx1)*p*4
-y1 = ry1-(ry5-ry1)*p*4
-x2 = rx2-(rx5-rx2)*p*4
-y2 = ry2+(ry2-ry5)*p*4
-x3 = rx3+(rx3-rx5)*p*4
-y3 = ry3+(ry3-ry5)*p*4
-x4 = rx4+(rx4-rx5)*p*4
-y4 = ry4-(ry5-ry4)*p*4
-
-#print (int(rx1), int(ry1)), (int(rx2), int(ry2)), (int(rx3), int(ry3)), (int(rx4), int(ry4)), (int(rx5), int(ry5))
-#print (int(x1), int(y1)), (int(x2), int(y2)), (int(x3), int(y3)), (int(x4), int(y4))
-
-
-
-########################################
-# Write calibration values to PiStorms #
-########################################
-
-oldBAS1type = psc.BAS1.getType()
-psc.BAS1.setType(psc.BAS1.PS_SENSOR_TYPE_NONE)
-
-# write to temporary memory
-for offset, value in enumerate([x1,y1,x2,y2,x3,y3,x4,y4]):
- comm.writeInteger(psc.PS_TS_CALIBRATION_DATA + 0x02*offset, value)
-
-comm.writeByte(psc.PS_Command, psc.E) # unlock permanent memory
-comm.writeByte(psc.PS_Command, psc.w) # copy from temporary memory to permanent memory
-
-timeout = time.time() + 1 # wait for up to a second
-while comm.readByte(psc.PS_TS_CALIBRATION_DATA_READY) != 1 and time.time() < timeout: time.sleep(0.01) # wait for ready byte
-# if it failed there is no need to show an error message here, it will already show below
-
-# check if write succeeded
-def calibrationEqual(offset, value):
- return comm.readInteger(psc.PS_TS_CALIBRATION_DATA + 0x02*offset) == int(value)
-
-psc.BAS1.setType(oldBAS1type)
-
-#for i in range(8): print comm.readInteger(psc.PS_TS_CALIBRATION_DATA + i*2)
-
-if all([ calibrationEqual(offset, value) for offset, value in enumerate([x1,y1,x2,y2,x3,y3,x4,y4]) ]):
- print 'Successfully wrote calibration values to PiStorms'
- # write the calibration values to the cache file and recreate the mindsensorsUI object to load them
- json.dump(dict( (v,eval(v)) for v in ['x1','y1','x2','y2','x3','y3','x4','y4'] ), open('/tmp/ps_ts_cal', 'w'))
- s = mindsensorsUI("PiStorms", 3)
- res = s.askQuestion(['Success', 'Wrote calibration values', 'to PiStorms'], ['Paint', 'Exit'])
- if res == 0:
- config = ConfigParser.RawConfigParser() # modeled after parts of MSBrowser
- config.read('/usr/local/mindsensors/conf/msdev.cfg')
- os.system("sudo python " + os.path.join(config.get('msdev', 'homefolder'),"programs","60-Games","04-Paint.py"))
-else:
- print 'Error writing calibration values to PiStorms'
- s.showMessage(['Error', 'Failed to write calibration values', 'to PiStorms'])
-
-# note: MSBrowser will automatically restart
diff --git a/programs/utils/01-Calibrate_old.py b/programs/utils/01-Calibrate_old.py
deleted file mode 100644
index 914ae064..00000000
--- a/programs/utils/01-Calibrate_old.py
+++ /dev/null
@@ -1,128 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright (c) 2016 mindsensors.com
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-#
-#mindsensors.com invests time and resources providing this open source code,
-#please support mindsensors.com by purchasing products from mindsensors.com!
-#Learn more product option visit us @ http://www.mindsensors.com/
-#
-# History:
-# Date Author Comments
-# 05/25/16 Deepak Initial development.
-#
-
-import time, sys
-from PiStorms import PiStorms
-
-psm = PiStorms()
-
-width=320
-height=240
-
-opt1 = ""
-
-if ( len(sys.argv) > 1 ):
- opt1 = str(sys.argv[1])
-
-psm.resetKeyPressCount()
-
-if ( opt1 != "force" ):
- psm.screen.termPrintAt(1, "Touch Screen Calibration Program")
- psm.screen.termPrintAt(3, "You should only calibrate if you")
- psm.screen.termPrintAt(4, "upgraded PiStorms Firmware.")
- psm.screen.termPrintAt(6, "Do you still want to calibrate?")
- psm.screen.termPrintAt(7, "To Confirm 'Yes':")
-
- doCalibrate = False
- count = 11
- oldKeyPressCount = psm.getKeyPressCount()
- while ( count > 0 ):
- psm.screen.termPrintAt(8, "press GO button within " + str(count) +" seconds")
- count = count - 1
- newKeyPressCount = psm.getKeyPressCount()
- if ( newKeyPressCount > oldKeyPressCount ):
- count = 0
- doCalibrate = True
- time.sleep(1)
-
- if ( doCalibrate == False ):
- psm.screen.disp.clear()
- psm.screen.termPrintAt(8, "Not calibrating ...")
- quit()
-
-psm.screen.disp.clear()
-psm.screen.termPrintAt(1, "Touch Screen Calibration Program")
-psm.screen.termPrintAt(3, "On next screen, touch and hold")
-psm.screen.termPrintAt(4, "stylus PRECISELY on the")
-psm.screen.termPrintAt(5, "Cross-Hair and Press GO button.")
-psm.screen.termPrintAt(6, "Then follow on screen instructions.")
-psm.screen.termPrintAt(8, "Press GO button to continue")
-doExit = False
-while (doExit == False):
- if(psm.isKeyPressed() == True): # if the GO button is pressed
- doExit = True
-time.sleep(2)
-
-draw = psm.screen.disp.draw()
-w = width/4
-h = height/4
-
-psm.screen.disp.clear()
-draw.line((h-10, w, h+10, w), fill=(0,255,0))
-draw.line((h, w-10, h, w+10), fill=(0,255,0))
-psm.screen.disp.display()
-
-psm.screen.termPrintAt(7, "Touch & Hold Stylus")
-psm.screen.termPrintAt(8, "on the Cross-Hair")
-psm.screen.termPrintAt(9, "And press the GO button")
-doExit = False
-while (doExit == False):
- if(psm.isKeyPressed() == True): # if the GO button is pressed
- if ( psm.screen.isTouched() ):
- time.sleep(1)
- psm.psc.bankA.writeByte(psm.psc.PS_Command, psm.psc.E)
- time.sleep(0.1)
- psm.psc.bankA.writeByte(psm.psc.PS_Command, psm.psc.t)
- time.sleep(0.1)
- doExit = True
- else:
- psm.screen.termPrintAt(8, "Screen not touched!!")
-
-psm.screen.disp.clear()
-psm.screen.termPrintAt(8, "Do it again at new position")
-w = (width/4)*3
-h = (height/4)*3
-draw.line((h-10, w, h+10, w), fill=(0,255,0))
-draw.line((h, w-10, h, w+10), fill=(0,255,0))
-psm.screen.disp.display()
-
-doExit = False
-while (doExit == False):
- if(psm.isKeyPressed() == True): # if the GO button is pressed
- if ( psm.screen.isTouched() ):
- time.sleep(1)
- psm.psc.bankA.writeByte(psm.psc.PS_Command, psm.psc.E)
- time.sleep(0.1)
- psm.psc.bankA.writeByte(psm.psc.PS_Command, psm.psc.T)
- time.sleep(0.1)
- doExit = True
- else:
- psm.screen.termPrintAt(8, "Screen not touched!!")
-
-psm.screen.disp.clear()
-psm.screen.termPrintAt(8, "Calibration complete")
-time.sleep(1)
-quit()
diff --git a/setup/MSBrowser.sh b/setup/MSBrowser.sh
old mode 100644
new mode 100755
index 1ae76194..fd165c74
--- a/setup/MSBrowser.sh
+++ b/setup/MSBrowser.sh
@@ -60,13 +60,15 @@ case "$1" in
;;
restart|reload|force-reload)
sudo kill -9 `ps -ef | grep MSBrowser.py |grep -v grep| cut -c11-16`
- rm /var/lock/msbrowser
+ rm -f /var/lock/msbrowser
+ rm -f /var/lock/ili9341
do_start
exit 3
;;
stop)
sudo kill -9 `ps -ef | grep MSBrowser.py |grep -v grep| cut -c11-16`
- rm /var/lock/msbrowser
+ rm -f /var/lock/msbrowser
+ rm -f /var/lock/ili9341
;;
status)
do_status
diff --git a/setup/MSDriver.sh b/setup/MSDriver.sh
old mode 100644
new mode 100755
diff --git a/setup/MSWeb.sh b/setup/MSWeb.sh
old mode 100644
new mode 100755
diff --git a/setup/SwarmServer.sh b/setup/SwarmServer.sh
old mode 100644
new mode 100755
diff --git a/setup/setup.sh b/setup/setup.sh
old mode 100644
new mode 100755
index 6fd1d683..191d79ed
--- a/setup/setup.sh
+++ b/setup/setup.sh
@@ -200,7 +200,8 @@ sudo cp -p ../programs/folder.png /usr/local/mindsensors/images/
sudo cp -p ../programs/leftarrow.png /usr/local/mindsensors/images/
sudo cp -p ../programs/rightarrow.png /usr/local/mindsensors/images/
sudo cp -p ../programs/uparrow.png /usr/local/mindsensors/images/
-sudo cp -p ../programs/refresh.png /usr/local/mindsensors/images/
+sudo cp -p ../programs/refresharrow.png /usr/local/mindsensors/images/
+sudo cp -p ../programs/returnarrow.png /usr/local/mindsensors/images/
sudo cp -p ../programs/missing.png /usr/local/mindsensors/images/
sudo cp -p ../artwork/* /usr/local/mindsensors/images/
sudo chmod a+r /usr/local/mindsensors/images/*
diff --git a/sys/MSBrowser.py b/sys/MSBrowser.py
index 2b6ce385..5f448ff8 100644
--- a/sys/MSBrowser.py
+++ b/sys/MSBrowser.py
@@ -51,73 +51,20 @@ def getProgramDir():
dir = "/home/pi/PiStorms/programs"
# normalize the path that was provided to remove any trailing slash.
return os.path.normpath(dir)
-def getDeviceType():
- deviceID = config.get("msdev", "device")
- if (deviceID == "PiStorms"):
- return 1
- elif (deviceID == "SensorShield"):
- return 2
- elif (deviceID == "SRVController"):
- return 3
- else:
- logging.error("Unknown device in configuration file, exiting...")
- sys.exit(1)
def getRotation():
if (os.getenv("PSREVERSE", "0") == "1"):
return 3
else:
return config.getint("msdev", "rotation")
def initScreen():
- if (psc.GetFirmwareVersion() < "V3.00"):
- try:
- bootmode = mindsensors_i2c(0xEA>>1)
- bootmode.readbyte()
- scrn = mindsensorsUI(deviceName, rotation, device=deviceType)
- scrn.termPrintAt(4, "PiStorms in fw upgrade mode")
- return scrn
- except:
- return mindsensorsUI(deviceName, rotation, device=deviceType)
- else:
- # load touchscreen calibration values from PiStorms and write to cache file
- ts_cal = None
- ts_cal_error = None
- ts_null = {u"x1": 0, u"y1": 0, u"x2": 0, u"x3": 0, u"y3": 0, u"y2": 0, u"y4": 0, u"x4": 0}
- try:
- oldBAS1type = psc.BAS1.getType()
- psc.BAS1.setType(psc.BAS1.PS_SENSOR_TYPE_NONE)
- psc.bankA.writeByte(psc.PS_Command, psc.l) # copy from permanent memory to temporary memory
- timeout = time.time() + 1 # wait for up to a second
- while (psc.bankA.readByte(psc.PS_TS_CALIBRATION_DATA_READY) != 1): # wait for ready byte
- time.sleep(0.01)
- if (time.time() > timeout):
- raise TypeError() # same as failure from readInteger
- ts_cal = { "x1": psc.bankA.readInteger(psc.PS_TS_CALIBRATION_DATA + 0x00),
- "y1": psc.bankA.readInteger(psc.PS_TS_CALIBRATION_DATA + 0x02),
- "x2": psc.bankA.readInteger(psc.PS_TS_CALIBRATION_DATA + 0x04),
- "y2": psc.bankA.readInteger(psc.PS_TS_CALIBRATION_DATA + 0x06),
- "x3": psc.bankA.readInteger(psc.PS_TS_CALIBRATION_DATA + 0x08),
- "y3": psc.bankA.readInteger(psc.PS_TS_CALIBRATION_DATA + 0x0A),
- "x4": psc.bankA.readInteger(psc.PS_TS_CALIBRATION_DATA + 0x0C),
- "y4": psc.bankA.readInteger(psc.PS_TS_CALIBRATION_DATA + 0x0E) }
- psc.BAS1.setType(oldBAS1type)
- except TypeError: # failed readInteger
- ts_cal_error = ["Touchscreen Error", "Failed to load", "touchscreen calibration values"]
- except IOError: # failed open in json.dump
- ts_cal_error = ["Touchscreen Error", "Failed to write", "touchscreen calibration values"]
- except:
- ts_cal_error = ["Touchscreen Error", "An unknown error occurred", "while attempting to load", "touchscreen calibration values"]
- json.dump(ts_cal or ts_null, open("/tmp/ps_ts_cal", "w"))
-
- scrn = mindsensorsUI(deviceName, rotation, device=deviceType)
- if ts_cal == ts_null:
- scrn.askQuestion(["Screen not calibrated.", "No touchscreen calibration values",
- "were found. Press GO to calibrate."], ["Press GO to continue..."], touch=False, goBtn=True)
- os.system("sudo python {}.py force".format(os.path.join(PROGRAM_DIRECTORY, "utils", "01-Calibrate")))
- return mindsensorsUI(deviceName, rotation, device=deviceType) # recreate with new calibration values
- if ts_cal_error is not None:
- logging.error('\n'.join(ts_cal_error))
- scrn.askQuestion(ts_cal_error, ["Press GO to continue..."], touch=False, goBtn=True)
- return scrn
+ try:
+ bootmode = mindsensors_i2c(0xEA>>1)
+ bootmode.readbyte()
+ scrn = mindsensorsUI(deviceName, rotation)
+ scrn.termPrintAt(4, "PiStorms in fw upgrade mode")
+ return scrn
+ except:
+ return mindsensorsUI(deviceName, rotation)
def listPrograms(directory):
allFiles = os.listdir(directory)
beginsWithNum = filter(lambda i: i[:2].isdigit(), allFiles)
@@ -213,12 +160,14 @@ def drawItemButton(folder, file, i):
scrn.drawButton(50, 50+(i%FILES_PER_PAGE)*45, width=320-50*2, height=45, text=file, image=icon, display=False)
def drawRightArrow():
scrn.drawButton(320-50, 0, 50, 50, image="rightarrow.png", text="", display=False, imageX=320-50+8)
+def drawReturnArrow():
+ scrn.drawButton(320-50, 0, 50, 50, image="returnarrow.png", text="", display=False, imageX=320-50+8)
def drawLeftArrow():
scrn.drawButton(0, 0, 50, 50, image="leftarrow.png", text="", display=False, imageX=8)
def drawUpArrow():
scrn.drawButton(0, 0, 50, 50, image="uparrow.png", text="", display=False, imageX=8)
-def drawRefresh():
- scrn.drawButton(0, 0, 50, 50, image="refresh.png", text="", display=False, imageX=8)
+def drawRefreshArrow():
+ scrn.drawButton(0, 0, 50, 50, image="refresharrow.png", text="", display=False, imageX=8)
def drawExclamation():
scrn.fillBmp(230, 7, 34, 34, "Exclamation-mark-icon.png", display=False);
def drawBatteryIndicator(*ignored):
@@ -240,24 +189,15 @@ def drawBatteryIndicator(*ignored):
def rightArrowPressed():
return scrn.checkButton(320-50, 0, 50, 50)
-def leftArrowPressed(index, filesPerPage):
- return (scrn.checkButton(0, 0, 50, 50) and index >= filesPerPage)
-def upArrowPressed(stack):
- return (scrn.checkButton(0, 0, 50, 50) and len(stack) > 1)
-def refreshPressed(stack):
- return (scrn.checkButton(0, 0, 50, 50) and len(stack) == 1)
+def leftArrowPressed():
+ return scrn.checkButton(0, 0, 50, 50)
def exclamationPressed():
return scrn.checkButton(218, 5, 38, 38)
def itemButtonPressed(folder, files, index, filesPerPage):
for i in getPageOfItems(files, index, filesPerPage):
if scrn.checkButton(50, 50+(i%filesPerPage)*45, 320-50*2, 45):
- item = os.path.join(folder, files[i])
- isFolder = os.path.isdir(item)
- if not isFolder:
- return (item+".py", False)
- else:
- return (item, True)
- return (False, None)
+ return os.path.join(folder, files[i])
+ return False
def getPageOfItems(files, index, filePerPage):
if (index+filePerPage-1 > len(files)-1):
return range(INDEX, len(files))
@@ -267,9 +207,8 @@ def getPageOfItems(files, index, filePerPage):
if __name__ == "__main__":
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
mutex = open("/var/lock/msbrowser", "w+")
- try:
- os.chmod("/var/lock/msbrowser", 0666)
- except OSError: pass
+ # allow lock to be modified without sudo permissions
+ os.chown("/var/lock/msbrowser", 1000, 1000) # pi's UID, GID
try:
flock(mutex, LOCK_EX | LOCK_NB)
except IOError:
@@ -282,7 +221,6 @@ def getPageOfItems(files, index, filePerPage):
configFile = "/usr/local/mindsensors/conf/msdev.cfg"
config = getConfig()
PROGRAM_DIRECTORY = getProgramDir()
- deviceType = getDeviceType()
deviceName = socket.gethostname()
rotation = getRotation()
psc = PiStormsCom()
@@ -309,50 +247,56 @@ def getPageOfItems(files, index, filePerPage):
for i in getPageOfItems(FILES, INDEX, FILES_PER_PAGE):
drawItemButton(FOLDER, FILES[i], i)
- drawRightArrow()
+ if len(FILES) <= FILES_PER_PAGE:
+ pass # don't draw a right arrow if there's only one page
+ elif INDEX >= len(FILES) - FILES_PER_PAGE:
+ drawReturnArrow()
+ else:
+ drawRightArrow()
+
if INDEX >= FILES_PER_PAGE:
drawLeftArrow()
elif len(stack) > 1:
drawUpArrow()
else:
- drawRefresh()
+ drawRefreshArrow()
- if newMessageExists() or updateNeeded():
+ exclamation = newMessageExists() or updateNeeded()
+ if exclamation:
drawExclamation()
drawBatteryIndicator()
while True:
- if exclamationPressed():
+ if exclamation and exclamationPressed():
promptUpdate()
break
- if rightArrowPressed():
+ if len(FILES) > FILES_PER_PAGE and rightArrowPressed():
newIndex = INDEX + FILES_PER_PAGE
if newIndex > len(FILES)-1:
newIndex = 0
stack[-1][2] = newIndex
break
- if leftArrowPressed(INDEX, FILES_PER_PAGE):
- stack[-1][2] = INDEX-4 if INDEX >= 4 else 0
- break
- if upArrowPressed(stack):
- stack.pop()
- break
- if refreshPressed(stack):
- stack[-1][1] = listPrograms(PROGRAM_DIRECTORY)
- break
-
- item, isFolder = itemButtonPressed(FOLDER, FILES, INDEX, FILES_PER_PAGE)
- if item and isFolder:
- stack.append([item, listPrograms(item), 0])
+ if leftArrowPressed():
+ if INDEX >= FILES_PER_PAGE: # left arrow
+ stack[-1][2] = INDEX-4 if INDEX >= 4 else 0
+ elif len(stack) > 1: # up arrow
+ stack.pop()
+ else: # refresh arrow
+ stack[-1][1] = listPrograms(PROGRAM_DIRECTORY)
+ scrn.clearScreen() # some visual feedback that the refresh happened
break
- if item and not isFolder:
- print("Running program " + item)
- exitStatus = runProgram(item)
- if exitStatus != 0:
- scrn.showMessage(["Error!", "The program stopped with exit status {}. " \
- "You might want to access the Logs tab in the PiStorms Web Interface " \
- "to check for a stacktrace.".format(exitStatus)], wrapText=True)
+ item = itemButtonPressed(FOLDER, FILES, INDEX, FILES_PER_PAGE)
+ if item:
+ if os.path.isdir(item): # folder
+ stack.append([item, listPrograms(item), 0])
+ else: # python program
+ print("Running program {}.py".format(item))
+ exitStatus = runProgram(item+".py")
+ if exitStatus != 0:
+ scrn.showMessage(["Error!", "The program stopped with exit status {}. " \
+ "You might want to access the Logs tab in the PiStorms Web Interface " \
+ "to check for a stacktrace.".format(exitStatus)], wrapText=True)
break
except KeyboardInterrupt:
logging.info("Quitting MSBrowser")
diff --git a/sys/MS_ILI9341.py b/sys/MS_ILI9341.py
index 45e46332..da837bbf 100644
--- a/sys/MS_ILI9341.py
+++ b/sys/MS_ILI9341.py
@@ -41,6 +41,8 @@ def __init__(self, dc, spi, rst=None, gpio=None, width=Adafruit_ILI9341.ILI9341_
self.y = -1
self.store = False
self.mutex = open("/var/lock/ili9341", "w+")
+ # allow lock to be modified without sudo permissions
+ os.chown("/var/lock/ili9341", 1000, 1000) # pi's UID, GID
# PIL.ImageDraw.Draw creates an object that draws in-place, so the mutex is required
def draw(self):
diff --git a/sys/PiStorms.py b/sys/PiStorms.py
index 7a8d7866..586786f3 100644
--- a/sys/PiStorms.py
+++ b/sys/PiStorms.py
@@ -77,7 +77,6 @@
## @package PiStorms
# This module contains classes and functions necessary for the use of PiStorms from mindsensors.com
-Dev_PiStorms = 1
## PiStormsSensor: This class provides functions for configuration, reading, and writing of sensors for use with PiStorms.
# @remark
diff --git a/sys/PiStormsCom.py b/sys/PiStormsCom.py
index e3dc5abb..07100bba 100644
--- a/sys/PiStormsCom.py
+++ b/sys/PiStormsCom.py
@@ -24,14 +24,9 @@
# July 2015 Henry Initial Authoring
from mindsensors_i2c import mindsensors_i2c
-import time, math
-import sys,os
-import ctypes
-import random
-import json # for new touchscreen functionality
+import time, numpy
class PSSensor():
-
PS_SENSOR_TYPE_NONE = 0
PS_SENSOR_TYPE_SWITCH = 1
PS_SENSOR_TYPE_ANALOG = 2
@@ -50,22 +45,26 @@ class PSSensor():
PS_SENSOR_TYPE_EV3_SWITCH = 18
PS_SENSOR_TYPE_EV3 = 19
+ PS_SENSOR_COLOR_NONE = 0
+ PS_SENSOR_COLOR_BLACK = 1
+ PS_SENSOR_COLOR_BLUE = 2
+ PS_SENSOR_COLOR_GREEN = 3
+ PS_SENSOR_COLOR_YELLOW = 4
+ PS_SENSOR_COLOR_RED = 5
+ PS_SENSOR_COLOR_WHITE = 6
+ PS_SENSOR_COLOR_BROWN = 7
- PS_EV3CACHE_READY = 0
- PS_EV3CACHE_ID = 1
- PS_EV3CACHE_READY = 2
- PS_EV3CACHE_READY = 3
- PS_EV3CACHE_READY = 4
-
-
+ SE_None = 0
+ SE_Front = 1
+ SE_Left = 2
+ SE_Right = 3
- sensornum = 0
- def __init__(self,bank,num):
+ def __init__(self, bank, num=0):
self.bank = bank
self.sensornum = num
self.type = self.PS_SENSOR_TYPE_NONE
self.EV3Cache = [ 0, [0]*16, 0, 0, [0]*32 ] # ready, ID[16], mode, length, data[32]
- def setType(self,type):
+ def setType(self, type):
if(type != self.type):
self.type = type
if(self.sensornum == 1):
@@ -79,28 +78,24 @@ def getType(self):
def EV3Retrieve(self):
if(self.sensornum == 1):
self.EV3Cache[0] = self.bank.readByte(PiStormsCom.PS_S1EV_Ready)
- self.EV3Cache[1] = self.bank.readArray(PiStormsCom.PS_S1EV_SensorID,16)
+ self.EV3Cache[1] = self.bank.readArray(PiStormsCom.PS_S1EV_SensorID, 16)
self.EV3Cache[2] = self.bank.readByte(PiStormsCom.PS_S1EV_Mode)
self.EV3Cache[3] = self.bank.readByte(PiStormsCom.PS_S1EV_Length)
- self.EV3Cache[4] = self.bank.readArray(PiStormsCom.PS_S1EV_Data,32)
+ self.EV3Cache[4] = self.bank.readArray(PiStormsCom.PS_S1EV_Data, 32)
if(self.sensornum == 2):
self.EV3Cache[0] = self.bank.readByte(PiStormsCom.PS_S2EV_Ready)
- self.EV3Cache[1] = self.bank.readArray(PiStormsCom.PS_S2EV_SensorID,16)
+ self.EV3Cache[1] = self.bank.readArray(PiStormsCom.PS_S2EV_SensorID, 16)
self.EV3Cache[2] = self.bank.readByte(PiStormsCom.PS_S2EV_Mode)
self.EV3Cache[3] = self.bank.readByte(PiStormsCom.PS_S2EV_Length)
- self.EV3Cache[4] = self.bank.readArray(PiStormsCom.PS_S2EV_Data,32)
+ self.EV3Cache[4] = self.bank.readArray(PiStormsCom.PS_S2EV_Data, 32)
def isTouchedEV3(self):
self.setType(self.PS_SENSOR_TYPE_EV3_SWITCH)
- #self.EV3Retrieve()
- #return self.EV3Cache[4][0] == 1
if(self.sensornum == 1):
return self.bank.readByte(PiStormsCom.PS_S1EV_Data) == 1
if(self.sensornum == 2):
return self.bank.readByte(PiStormsCom.PS_S2EV_Data) == 1
def numTouchesEV3(self):
self.setType(self.PS_SENSOR_TYPE_EV3_SWITCH)
- #self.EV3Retrieve()
- #return self.EV3Cache[4][1]
if(self.sensornum == 1):
return self.bank.readByte(PiStormsCom.PS_S1EV_Data+1)
if(self.sensornum == 2):
@@ -108,85 +103,71 @@ def numTouchesEV3(self):
def resetTouchesEV3(self):
self.setType(self.PS_SENSOR_TYPE_EV3_SWITCH)
if(self.sensornum == 1):
- self.bank.writeByte(PiStormsCom.PS_S1EV_Data + 1,0)
+ self.bank.writeByte(PiStormsCom.PS_S1EV_Data+1, 0)
if(self.sensornum == 2):
- self.bank.writeByte(PiStormsCom.PS_S2EV_Data + 1,0)
+ self.bank.writeByte(PiStormsCom.PS_S2EV_Data+1, 0)
def setModeEV3(self, mode):
if(self.sensornum == 1):
- self.bank.writeByte(PiStormsCom.PS_S1EV_Mode,mode)
+ self.bank.writeByte(PiStormsCom.PS_S1EV_Mode, mode)
if(self.sensornum == 2):
- self.bank.writeByte(PiStormsCom.PS_S2EV_Mode,mode)
+ self.bank.writeByte(PiStormsCom.PS_S2EV_Mode, mode)
def distanceIREV3(self):
self.setType(self.PS_SENSOR_TYPE_EV3)
self.setModeEV3(0)
- #self.EV3Retrieve()
- #raw1 = self.EV3Cache[4][0]
- #raw2 = self.EV3Cache[4][1]
- #return ctypes.c_short(raw1 | (raw2*256)).value
if(self.sensornum == 1):
return self.bank.readInteger(PiStormsCom.PS_S1EV_Data)
if(self.sensornum == 2):
return self.bank.readInteger(PiStormsCom.PS_S2EV_Data)
- def rawIREV3(self,mode):
+ def rawIREV3(self, mode):
self.setType(self.PS_SENSOR_TYPE_EV3)
self.setModeEV3(mode)
- #self.EV3Retrieve()
- #return self.EV3Cache[4]
if(self.sensornum == 1):
return self.bank.readByte(PiStormsCom.PS_S1EV_Data)
if(self.sensornum == 2):
return self.bank.readByte(PiStormsCom.PS_S2EV_Data)
- def headingIREV3(self,channel):
+ def headingIREV3(self, channel):
self.setType(self.PS_SENSOR_TYPE_EV3)
self.setModeEV3(1)
- #return ctypes.c_byte(self.rawIREV3(1)[(channel-1)*2]).value
if(self.sensornum == 1):
- return self.bank.readByteSigned(PiStormsCom.PS_S1EV_Data + ((channel-1)*2))
+ return self.bank.readByteSigned(PiStormsCom.PS_S1EV_Data + (channel-1)*2)
if(self.sensornum == 2):
- return self.bank.readByteSigned(PiStormsCom.PS_S2EV_Data + ((channel-1)*2))
- def distanceRemoteIREV3(self,channel):
+ return self.bank.readByteSigned(PiStormsCom.PS_S2EV_Data + (channel-1)*2)
+ def distanceRemoteIREV3(self, channel):
self.setType(self.PS_SENSOR_TYPE_EV3)
self.setModeEV3(1)
- #return ctypes.c_byte(self.rawIREV3(1)[((channel-1)*2)+1]).value
if(self.sensornum == 1):
- return self.bank.readByte(PiStormsCom.PS_S1EV_Data + (((channel-1)*2)+1))
+ return self.bank.readByte(PiStormsCom.PS_S1EV_Data + ((channel-1)*2)+1)
if(self.sensornum == 2):
- return self.bank.readByte(PiStormsCom.PS_S2EV_Data + (((channel-1)*2)+1))
- def remoteLeft(self,channel):
+ return self.bank.readByte(PiStormsCom.PS_S2EV_Data + ((channel-1)*2)+1)
+ def remoteLeft(self, channel):
self.setType(self.PS_SENSOR_TYPE_EV3)
self.setModeEV3(2)
- #remote = self.rawIREV3(2)[channel-1]
if(self.sensornum == 1):
remote = self.bank.readByte(PiStormsCom.PS_S1EV_Data + (channel-1))
if(self.sensornum == 2):
remote = self.bank.readByte(PiStormsCom.PS_S2EV_Data + (channel-1))
- if(remote == 0 or remote == 3 or remote == 4):
+ if(remote in [0, 3, 4]):
return 0
- if(remote == 1 or remote == 5 or remote == 6):
+ if(remote in [1, 5, 6]):
return 1
- if(remote == 2 or remote == 7 or remote == 8):
+ if(remote in [2, 7, 8]):
return -1
- def remoteRight(self,channel):
+ def remoteRight(self, channel):
self.setType(self.PS_SENSOR_TYPE_EV3)
self.setModeEV3(2)
- #remote = self.rawIREV3(2)[channel-1]
if(self.sensornum == 1):
remote = self.bank.readByte(PiStormsCom.PS_S1EV_Data + (channel-1))
if(self.sensornum == 2):
remote = self.bank.readByte(PiStormsCom.PS_S2EV_Data + (channel-1))
- if(remote == 0 or remote == 1 or remote == 2):
+ if(remote in [0, 1, 2]):
return 0
- if(remote == 3 or remote == 7 or remote == 5):
+ if(remote in [3, 5, 7]):
return 1
- if(remote == 4 or remote == 6 or remote == 8):
+ if(remote in [4, 6, 8]):
return -1
def distanceUSEV3cm(self):
self.setType(self.PS_SENSOR_TYPE_EV3)
self.setModeEV3(0)
- #self.EV3Retrieve()
- #raw1 = self.EV3Cache[4][0]
- #raw2 = self.EV3Cache[4][1]
- #return ctypes.c_short(raw1 | (raw2*256)).value
if(self.sensornum == 1):
return self.bank.readInteger(PiStormsCom.PS_S1EV_Data)
if(self.sensornum == 2):
@@ -194,10 +175,6 @@ def distanceUSEV3cm(self):
def distanceUSEV3in(self):
self.setType(self.PS_SENSOR_TYPE_EV3)
self.setModeEV3(1)
- #self.EV3Retrieve()
- #raw1 = self.EV3Cache[4][0]
- #raw2 = self.EV3Cache[4][1]
- #return ctypes.c_short(raw1 | (raw2*256)).value
if(self.sensornum == 1):
return self.bank.readInteger(PiStormsCom.PS_S1EV_Data)
if(self.sensornum == 2):
@@ -205,8 +182,6 @@ def distanceUSEV3in(self):
def presenceUSEV3(self):
self.setType(self.PS_SENSOR_TYPE_EV3)
self.setModeEV3(2)
- #self.EV3Retrieve()
- #return self.EV3Cache[4][0] == 1
if(self.sensornum == 1):
return self.bank.readByte(PiStormsCom.PS_S1EV_Data) == 1
if(self.sensornum == 2):
@@ -214,8 +189,6 @@ def presenceUSEV3(self):
def rawGyro(self, mode):
self.setType(self.PS_SENSOR_TYPE_EV3)
self.setModeEV3(mode)
- #self.EV3Retrieve()
- #return self.EV3Cache[4]
if(self.sensornum == 1):
return self.bank.readByte(PiStormsCom.PS_S1EV_Data)
if(self.sensornum == 2):
@@ -223,10 +196,6 @@ def rawGyro(self, mode):
def gyroAngleEV3(self):
self.setType(self.PS_SENSOR_TYPE_EV3)
self.setModeEV3(0)
- #raw = self.rawGyro(0)
- #raw1 = raw[0]
- #raw2 = raw[1]
- #return ctypes.c_short(raw1 | (raw2*256)).value
if(self.sensornum == 1):
return self.bank.readIntegerSigned(PiStormsCom.PS_S1EV_Data)
if(self.sensornum == 2):
@@ -234,10 +203,6 @@ def gyroAngleEV3(self):
def gyroRateEV3(self):
self.setType(self.PS_SENSOR_TYPE_EV3)
self.setModeEV3(1)
- #raw = self.rawGyro(1)
- #raw1 = raw[0]
- #raw2 = raw[1]
- #return ctypes.c_short(raw1 | (raw2*256)).value
if(self.sensornum == 1):
return self.bank.readIntegerSigned(PiStormsCom.PS_S1EV_Data)
if(self.sensornum == 2):
@@ -245,8 +210,6 @@ def gyroRateEV3(self):
def reflectedLightSensorEV3(self):
self.setType(self.PS_SENSOR_TYPE_EV3)
self.setModeEV3(0)
- #self.EV3Retrieve()
- #return self.EV3Cache[4][0]
if(self.sensornum == 1):
return self.bank.readByte(PiStormsCom.PS_S1EV_Data)
if(self.sensornum == 2):
@@ -254,25 +217,13 @@ def reflectedLightSensorEV3(self):
def ambientLightSensorEV3(self):
self.setType(self.PS_SENSOR_TYPE_EV3)
self.setModeEV3(1)
- #self.EV3Retrieve()
- #return self.EV3Cache[4][0]
if(self.sensornum == 1):
return self.bank.readByte(PiStormsCom.PS_S1EV_Data)
if(self.sensornum == 2):
return self.bank.readByte(PiStormsCom.PS_S2EV_Data)
- PS_SENSOR_COLOR_NONE = 0
- PS_SENSOR_COLOR_BLACK = 1
- PS_SENSOR_COLOR_BLUE = 2
- PS_SENSOR_COLOR_GREEN = 3
- PS_SENSOR_COLOR_YELLOW = 4
- PS_SENSOR_COLOR_RED = 5
- PS_SENSOR_COLOR_WHITE = 6
- PS_SENSOR_COLOR_BROWN = 7
def colorSensorEV3(self):
self.setType(self.PS_SENSOR_TYPE_EV3)
self.setModeEV3(2)
- #self.EV3Retrieve()
- #return self.EV3Cache[4][0]
if(self.sensornum == 1):
return self.bank.readByte(PiStormsCom.PS_S1EV_Data)
if(self.sensornum == 2):
@@ -285,8 +236,6 @@ def readNXT(self):
def isTouchedNXT(self):
self.setType(self.PS_SENSOR_TYPE_SWITCH)
self.setModeEV3(0)
- #self.EV3Retrieve()
- #return self.EV3Cache[4][0] == 1
if(self.sensornum == 1):
return self.bank.readByte(PiStormsCom.PS_S1EV_Data) == 1
if(self.sensornum == 2):
@@ -294,81 +243,53 @@ def isTouchedNXT(self):
def numTouchesNXT(self):
self.setType(self.PS_SENSOR_TYPE_SWITCH)
self.setModeEV3(0)
- #self.EV3Retrieve()
- #return self.EV3Cache[4][1]
if(self.sensornum == 1):
return self.bank.readByte(PiStormsCom.PS_S1EV_Data + 1)
if(self.sensornum == 2):
return self.bank.readByte(PiStormsCom.PS_S2EV_Data + 1)
def resetTouchesNXT(self):
if(self.sensornum == 1):
- self.bank.writeByte(PiStormsCom.PS_S1EV_Data+1,0)
+ self.bank.writeByte(PiStormsCom.PS_S1EV_Data+1, 0)
if(self.sensornum == 2):
- self.bank.writeByte(PiStormsCom.PS_S2EV_Data+1,0)
+ self.bank.writeByte(PiStormsCom.PS_S2EV_Data+1, 0)
def lightSensorNXT(self, active=True):
if(active):
self.setType(self.PS_SENSOR_TYPE_LIGHT_ACTIVE)
else:
self.setType(self.PS_SENSOR_TYPE_LIGHT_INACTIVE)
self.setModeEV3(0)
- #self.EV3Retrieve()
- #return (self.EV3Cache[1][0]<<8 ) +self.EV3Cache[0]
if(self.sensornum == 1):
return self.bank.readInteger(PiStormsCom.PS_S1EV_Ready)
if(self.sensornum == 2):
return self.bank.readInteger(PiStormsCom.PS_S2EV_Ready)
-
- def SumoEyes(self, long = True):
- self.SE_None = 0
- self.SE_Front = 1
- self.SE_Left = 2
- self.SE_Right = 3
+ def SumoEyes(self, long=True):
if(long):
self.setType(self.PS_SENSOR_TYPE_LIGHT_INACTIVE)
else:
self.setType(self.PS_SENSOR_TYPE_LIGHT_ACTIVE)
self.setModeEV3(0)
- #self.EV3Retrieve()
- #if self.SumoEyesisNear(465, 30,(self.EV3Cache[1][0]<<8 ) +self.EV3Cache[0] ):
if(self.sensornum == 1):
- if(self.SumoEyesisNear(465, 30, (self.bank.readInteger(PiStormsCom.PS_S1EV_Ready)))):
- return self.SE_Front
- #if self.SumoEyesisNear(800, 30, (self.EV3Cache[1][0]<<8 ) +self.EV3Cache[0] ):
- elif(self.SumoEyesisNear(800, 30, (self.bank.readInteger(PiStormsCom.PS_S1EV_Ready)))):
- return self.SE_Left
- #if self.SumoEyesisNear(555, 30, (self.EV3Cache[1][0]<<8 ) +self.EV3Cache[0] ):
- elif(self.SumoEyesisNear(555, 30, (self.bank.readInteger(PiStormsCom.PS_S1EV_Ready)))):
- return self.SE_Right
- else:
- return self.SE_None
+ comet = self.bank.readInteger(PiStormsCom.PS_S1EV_Ready)
if(self.sensornum == 2):
- if(self.SumoEyesisNear(465, 30, (self.bank.readInteger(PiStormsCom.PS_S2EV_Ready)))):
- return self.SE_Front
- #if self.SumoEyesisNear(800, 30, (self.EV3Cache[1][0]<<8 ) +self.EV3Cache[0] ):
- elif(self.SumoEyesisNear(800, 30, (self.bank.readInteger(PiStormsCom.PS_S2EV_Ready)))):
- return self.SE_Left
- #if self.SumoEyesisNear(555, 30, (self.EV3Cache[1][0]<<8 ) +self.EV3Cache[0] ):
- elif(self.SumoEyesisNear(555, 30, (self.bank.readInteger(PiStormsCom.PS_S2EV_Ready)))):
- return self.SE_Right
- else:
- return self.SE_None
-
- def SumoEyesisNear(self,reference, delta, comet):
- if (comet > (reference - delta)) and (comet < (reference + delta)):
- return True
+ comet = self.bank.readInteger(PiStormsCom.PS_S2EV_Ready)
+ def isNear(reference, delta, comet):
+ return (comet > (reference - delta)) and (comet < (reference + delta))
+ if(isNear(465, 30, comet)):
+ return self.SE_Front
+ elif(isNear(800, 30, comet)):
+ return self.SE_Left
+ elif(isNear(555, 30, comet)):
+ return self.SE_Right
else:
- return False
-
- def colorSensorRawNXT(self, smode = 13):
+ return self.SE_None
+ def colorSensorRawNXT(self, smode=13):
self.setType(smode)
self.setModeEV3(0)
self.EV3Retrieve()
return self.EV3Cache[0:1] + self.EV3Cache[1]
- def colorSensorNXT(self, smode = 13):
+ def colorSensorNXT(self, smode=13):
self.setType(smode)
self.setModeEV3(0)
- #self.EV3Retrieve()
- #return self.EV3Cache[0]
if(self.sensornum == 1):
return self.bank.readByte(PiStormsCom.PS_S1EV_Ready)
if(self.sensornum == 2):
@@ -381,11 +302,9 @@ def colorSensorGreenNXT(self):
return self.colorSensorRawNXT(self.PS_SENSOR_TYPE_COLORGREEN)[0]
def colorSensorBlueNXT(self):
return self.colorSensorRawNXT(self.PS_SENSOR_TYPE_COLORBLUE)[0]
- def analogSensor(self): #untested
+ def analogSensor(self): # untested
self.setType(self.PS_SENSOR_TYPE_ANALOG)
self.setModeEV3(0)
- #self.EV3Retrieve()
- #return self.EV3Cache[0]
if(self.sensornum == 1):
return self.bank.readByte(PiStormsCom.PS_S1EV_Ready)
if(self.sensornum == 2):
@@ -394,66 +313,42 @@ def activateCustomSensorI2C(self):
self.setType(self.PS_SENSOR_TYPE_CUSTOM)
-
class PSMotor():
-
- #bank = 0
- motornum = 0
- def __init__(self, bank, num):
+ def __init__(self, bank, num=0):
self.bank = bank
self.motornum = num
-
def pos(self):
if(self.motornum == 1):
return self.bank.readLongSigned(PiStormsCom.PS_Position_M1)
-
elif(self.motornum == 2):
return self.bank.readLongSigned(PiStormsCom.PS_Position_M2)
-
def resetPos(self):
if(self.motornum == 1):
self.bank.writeByte(PiStormsCom.PS_Command, 114)
-
elif(self.motornum == 2):
self.bank.writeByte(PiStormsCom.PS_Command, 115)
-
def setSpeedSync(self, speed):
- ctrl = 0
- ctrl |= PiStormsCom.PS_CONTROL_SPEED
- speed = int(speed)
- array = [speed, 0, 0, ctrl]
- self.bank.writeArray( PiStormsCom.PS_Speed_M1, array)
- self.bank.writeArray( PiStormsCom.PS_Speed_M2, array)
+ ctrl = PiStormsCom.PS_CONTROL_SPEED
+ array = [int(speed), 0, 0, ctrl]
+ self.bank.writeArray(PiStormsCom.PS_Speed_M1, array)
+ self.bank.writeArray(PiStormsCom.PS_Speed_M2, array)
# issue command 'S'
- self.bank.writeByte(PiStormsCom.PS_Command,PiStormsCom.S)
-
+ self.bank.writeByte(PiStormsCom.PS_Command, PiStormsCom.S)
def floatSync(self):
self.bank.writeByte(PiStormsCom.PS_Command,PiStormsCom.c)
-
def brakeSync(self):
- # Break while stopping; command C
+ # issue command 'C', break while stopping
self.bank.writeByte(PiStormsCom.PS_Command,PiStormsCom.C)
-
-
- def setSpeed( self, speed):
+ def setSpeed(self, speed):
if(speed == 0):
self.float()
return
-
- ctrl = 0
- ctrl |= PiStormsCom.PS_CONTROL_SPEED
-
- #print speed
- speed = int(speed)
-
-
- ctrl |= PiStormsCom.PS_CONTROL_GO
+ ctrl = PiStormsCom.PS_CONTROL_SPEED | PiStormsCom.PS_CONTROL_GO
+ array = [int(speed), 0, 0, ctrl]
if (self.motornum == 1):
- array = [speed, 0, 0, ctrl]
- self.bank.writeArray( PiStormsCom.PS_Speed_M1, array)
+ self.bank.writeArray(PiStormsCom.PS_Speed_M1, array)
if (self.motornum == 2):
- array = [speed, 0, 0, ctrl]
- self.bank.writeArray( PiStormsCom.PS_Speed_M2, array)
+ self.bank.writeArray(PiStormsCom.PS_Speed_M2, array)
def brake(self):
if(self.motornum == 1):
self.bank.writeByte(PiStormsCom.PS_Command, PiStormsCom.A)
@@ -465,90 +360,67 @@ def float(self):
if(self.motornum == 2):
self.bank.writeByte(PiStormsCom.PS_Command, PiStormsCom.b)
def hold(self):
- ctrl = 0
- ctrl |= PiStormsCom.PS_CONTROL_BRK
- ctrl |= PiStormsCom.PS_CONTROL_ON
- #ctrl |= PiStormsCom.PS_CONTROL_RELATIVE
- ctrl |= PiStormsCom.PS_CONTROL_TACHO
- ctrl |= PiStormsCom.PS_CONTROL_GO
-
+ ctrl = PiStormsCom.PS_CONTROL_BRK | \
+ PiStormsCom.PS_CONTROL_ON | \
+ PiStormsCom.PS_CONTROL_TACHO | \
+ PiStormsCom.PS_CONTROL_GO
if(self.motornum == 1):
self.bank.writeArray(PiStormsCom.PS_SetPoint_M1, [0,0,0,0])
self.bank.writeByte(PiStormsCom.PS_CMDA_M1, ctrl)
else:
self.bank.writeArray(PiStormsCom.PS_SetPoint_M2, [0,0,0,0])
self.bank.writeByte(PiStormsCom.PS_CMDA_M2, ctrl)
-
- def runSecs(self,secs,speed, brakeOnCompletion = False):
- ctrl = 0
- ctrl |= PiStormsCom.PS_CONTROL_SPEED
- ctrl |= PiStormsCom.PS_CONTROL_TIME
+ def runSecs(self, secs, speed, brakeOnCompletion=False):
+ ctrl = PiStormsCom.PS_CONTROL_SPEED | \
+ PiStormsCom.PS_CONTROL_TIME | \
+ PiStormsCom.PS_CONTROL_GO
if(brakeOnCompletion):
ctrl |= PiStormsCom.PS_CONTROL_BRK
- ctrl |= PiStormsCom.PS_CONTROL_GO
+ array = [speed, secs, 0, ctrl]
if(self.motornum == 1):
- array = [speed,secs,0,ctrl]
self.bank.writeArray(PiStormsCom.PS_Speed_M1,array)
if(self.motornum == 2):
- array = [speed,secs,0,ctrl]
self.bank.writeArray(PiStormsCom.PS_Speed_M2,array)
-
def status(self):
if(self.motornum == 1):
return self.bank.readByte(PiStormsCom.PS_Status_M1)
if(self.motornum == 2):
return self.bank.readByte(PiStormsCom.PS_Status_M2)
- def statusBit(self, bitno = 0):
- return (self.status() >> bitno) & 1
+ def statusBit(self, bitno=0):
+ return ((self.status() >> bitno) & 1) == 1
def isBusy(self):
- return self.statusBit(0) == 1 or self.statusBit(1) == 1 or self.statusBit(3) == 1 or self.statusBit(6) == 1
+ return any(map(self.statusBit, [0,1,3,6]))
def waitUntilNotBusy(self, timeout=-1):
while(self.isBusy()):
- time.sleep(.01)
+ time.sleep(0.01)
timeout -= 1
if(timeout == 0):
return 1
- if(timeout <-5):
+ if(timeout < -5):
timeout = -1
- pass
return 0
def isStalled(self):
- return self.statusBit(7) == 1
+ return self.statusBit(7)
def isOverloaded(self):
- return self.statusBit(5) == 1
- def runDegs(self,degs,speed = 100,brakeOnCompletion = False, holdOnCompletion = False):
- # holdOnCompletion is not supported on LEGO motors.
- holdOnCompletion = False
- ctrl = 0
- ctrl |= PiStormsCom.PS_CONTROL_SPEED
- ctrl |= PiStormsCom.PS_CONTROL_TACHO
- ctrl |= PiStormsCom.PS_CONTROL_RELATIVE
+ return self.statusBit(5)
+ def runDegs(self, degs, speed=100, brakeOnCompletion=False, holdOnCompletion=False):
+ # holdOnCompletion is not supported on LEGO motors, ignored
+ ctrl = PiStormsCom.PS_CONTROL_SPEED | \
+ PiStormsCom.PS_CONTROL_TACHO | \
+ PiStormsCom.PS_CONTROL_RELATIVE | \
+ PiStormsCom.PS_CONTROL_GO
if(brakeOnCompletion):
ctrl |= PiStormsCom.PS_CONTROL_BRK
- if(holdOnCompletion):
- ctrl |= PiStormsCom.PS_CONTROL_BRK
- ctrl |= PiStormsCom.PS_CONTROL_ON
- ctrl |= PiStormsCom.PS_CONTROL_GO
-
b4 = (degs/0x1000000)
b3 = ((degs%0x1000000)/0x10000)
b2 = (((degs%0x1000000)%0x10000)/0x100)
b1 = (((degs%0x1000000)%0x10000)%0x100)
-
- # b1 = degs & 0xFF
- # b2 = (degs >>8) & 0xFF
- # b3 = (degs >>16) & 0xFF
- # b4 = (degs >> 24) & 0xFF
-
+ array = [b1, b2, b3, b4, speed, 0, 0, ctrl]
if(self.motornum == 1):
- array = [b1, b2, b3, b4, speed, 0, 0, ctrl]
self.bank.writeArray(PiStormsCom.PS_SetPoint_M1, array)
if(self.motornum == 2):
- array = [b1, b2, b3, b4, speed, 0, 0, ctrl]
self.bank.writeArray(PiStormsCom.PS_SetPoint_M2, array)
-
## Reads the values of the PID control registers
- # @param self The object pointer.
def ReadPerformanceParameters(self):
try:
b0 = self.bank.readInteger(PiStormsCom.PS_P_Kp)
@@ -559,13 +431,11 @@ def ReadPerformanceParameters(self):
b5 = self.bank.readInteger(PiStormsCom.PS_S_Kd)
b6 = self.bank.readByte(PiStormsCom.PS_PassCount)
b7 = self.bank.readByte(PiStormsCom.PS_PassTolerance)
- array = [b0, b1, b2, b3, b4, b5, b6, b7]
- return array
+ return [b0, b1, b2, b3, b4, b5, b6, b7]
except:
print "Error: Could not read PID values"
return []
-
- def SetPerformanceParameters(self, Kp_tacho, Ki_tacho, Kd_tacho, Kp_speed, Ki_speed, Kd_speed, passcount, tolerance):#untested
+ def SetPerformanceParameters(self, Kp_tacho, Ki_tacho, Kd_tacho, Kp_speed, Ki_speed, Kd_speed, passcount, tolerance): # untested
Kp_t1 = Kp_tacho%0x100
Kp_t2 = Kp_tacho/0x100
Ki_t1 = Ki_tacho%0x100
@@ -580,13 +450,16 @@ def SetPerformanceParameters(self, Kp_tacho, Ki_tacho, Kd_tacho, Kp_speed, Ki_sp
Kd_s2 = Kd_speed/0x100
passcount = passcount
tolerance = tolerance
- array = [Kp_t1 , Kp_t2 , Ki_t1, Ki_t2, Kd_t1, Kd_t2, Kp_s1, Kp_s2, Ki_s1, Ki_s2, Kd_s1, Kd_s2, passcount, tolerance]
+ array = [Kp_t1, Kp_t2, Ki_t1, Ki_t2, \
+ Kd_t1, Kd_t2, Kp_s1, Kp_s2, \
+ Ki_s1, Ki_s2, Kd_s1, Kd_s2, \
+ passcount, tolerance]
self.bank.writeArray(PiStormsCom.PS_P_Kp, array)
+
## PiStormsCom: this class provides communication functions for PiStorms.
-# do not use this class directly in user programs, instead use functions provided by LegoDevices or MsDevices class.
+# Do not use this class directly in user programs, instead use functions provided by the LegoDevices or MsDevices classes.
class PiStormsCom(object):
-
PS_SENSOR_TYPE_NONE = 0
PS_SENSOR_TYPE_SWITCH = 1
PS_SENSOR_TYPE_ANALOG = 2
@@ -620,12 +493,6 @@ class PiStormsCom(object):
PS_SENSOR_MODE_NXT_LIGHT_AMBIENT = 0
PS_SENSOR_MODE_NXT_COLOR_COLOR = 0
- PS_EV3CACHE_READY = 0
- PS_EV3CACHE_ID = 1
- PS_EV3CACHE_READY = 2
- PS_EV3CACHE_READY = 3
- PS_EV3CACHE_READY = 4
-
PS_A_ADDRESS = 0x34
PS_B_ADDRESS = 0x36
@@ -663,6 +530,7 @@ class PiStormsCom(object):
PS_PassTolerance = 0x6B
PS_ChkSum = 0x6C
PS_BattV = 0x6E
+
# Sensor 1
PS_S1_Mode = 0x6F
# EV3
@@ -683,9 +551,7 @@ class PiStormsCom(object):
PS_S1C_G_raw = 0x76
PS_S1C_B_raw = 0x77
PS_S1C_N_raw = 0x78
- # Touchscreen Calibration
- PS_TS_CALIBRATION_DATA_READY = 0x70
- PS_TS_CALIBRATION_DATA = 0x71
+
# Sensor 2
PS_S2_Mode = 0xA3
# EV3
@@ -706,24 +572,35 @@ class PiStormsCom(object):
PS_S2C_G_raw = 0xAA
PS_S2C_B_raw = 0xAB
PS_S2C_N_raw = 0xAC
+
+ ## Touchscreen x- and y-axis registers
+ PS_TSX = 0xE3
+ PS_TSY = 0xE5
+
+ # Touchscreen Calibration
+ PS_TS_CALIBRATION_DATA_READY = 0x70
+ PS_TS_CALIBRATION_DATA = 0x71
+
# LED
PS_R = 0xD7
PS_G = 0xD8
PS_B = 0xD9
+
# Buttons
PS_KeyPress = 0xDA
PS_Key1Count = 0xDB
PS_Key2Count = 0xDC
- PS_CONTROL_SPEED = 0x01
- PS_CONTROL_RAMP = 0x02
- PS_CONTROL_RELATIVE = 0x04
- PS_CONTROL_TACHO = 0x08
- PS_CONTROL_BRK = 0x10
- PS_CONTROL_ON = 0x20
- PS_CONTROL_TIME = 0x40
- PS_CONTROL_GO = 0x80
- #Supported I2C commands
+ PS_CONTROL_SPEED = 0x01
+ PS_CONTROL_RAMP = 0x02
+ PS_CONTROL_RELATIVE = 0x04
+ PS_CONTROL_TACHO = 0x08
+ PS_CONTROL_BRK = 0x10
+ PS_CONTROL_ON = 0x20
+ PS_CONTROL_TIME = 0x40
+ PS_CONTROL_GO = 0x80
+
+ # Supported I2C commands
R = 0x52
S = 0x53
a = 0x61
@@ -739,37 +616,28 @@ class PiStormsCom(object):
w = 0x77
l = 0x6C
-
bankA = mindsensors_i2c(PS_A_ADDRESS >> 1)
bankB = mindsensors_i2c(PS_B_ADDRESS >> 1)
- BAM1 = PSMotor(bankA,1)
- BAM2 = PSMotor(bankA,2)
- BBM1 = PSMotor(bankB,1)
- BBM2 = PSMotor(bankB,2)
+ BAM1 = PSMotor(bankA, 1)
+ BAM2 = PSMotor(bankA, 2)
+ BBM1 = PSMotor(bankB, 1)
+ BBM2 = PSMotor(bankB, 2)
- BAS1 = PSSensor(bankA,1)
- BAS2 = PSSensor(bankA,2)
- BBS1 = PSSensor(bankB,1)
- BBS2 = PSSensor(bankB,2)
+ BAS1 = PSSensor(bankA, 1)
+ BAS2 = PSSensor(bankA, 2)
+ BBS1 = PSSensor(bankB, 1)
+ BBS2 = PSSensor(bankB, 2)
def __init__(self):
try:
self.bankA.readByte(self.PS_BattV)
except:
- print "could not connect to pistorms"
+ print "Could not connect to PiStorms."
else:
self.bankA.writeByte(self.PS_Command,self.R)
self.bankB.writeByte(self.PS_Command,self.R)
- self.ts_cal = None # signified firmware version older than V3.00, use old touchscreen methods
- if self.GetFirmwareVersion() >= 'V3.00':
- # read touchscreen calibration values from cache file
- try:
- self.ts_cal = json.load(open('/tmp/ps_ts_cal', 'r'))
- except IOError:
- print 'Touchscreen Error: Failed to read touchscreen calibration values in PiStormsCom.py'
-
def Shutdown(self):
self.bankA.writeByte(self.PS_Command,self.H)
@@ -781,58 +649,43 @@ def command(self, cmd, bank):
def battVoltage(self):
try:
- return self.bankA.readByte(self.PS_BattV)*.040
+ return self.bankA.readByte(self.PS_BattV)*0.04
except:
return 0
- ## Read the firmware version of the i2c device
def GetFirmwareVersion(self):
try:
- ver = self.bankA.readString(0x00, 8)
- return ver
+ return self.bankA.readString(0x00, 8)
except:
return "ReadErr"
- ## Read the vendor name of the i2c device
def GetVendorName(self):
try:
- vendor = self.bankA.readString(0x08, 8)
- return vendor
+ return self.bankA.readString(0x08, 8)
except:
return "ReadErr"
- ## Read the i2c device id
def GetDeviceId(self):
try:
- device = self.bankA.readString(0x10, 8)
- return device
+ return self.bankA.readString(0x10, 8)
except:
return "ReadErr"
- ## Read the features from device
def GetDeviceFeatures(self):
try:
- features = self.bankA.readString(0x18, 8)
- return features
+ return self.bankA.readString(0x18, 8)
except:
return "ReadErr"
- def led(self,lednum,red,green,blue):
-
- try:
- if(lednum == 1):
-
- array = [red, green, blue]
- self.bankA.writeArray(self.PS_R, array)
- if(lednum == 2):
- array = [red, green, blue]
- self.bankB.writeArray(self.PS_R, array)
- except AttributeError:
- self.led(lednum,red,green,blue)
- time.sleep(.001)
+ def led(self, lednum, red, green, blue):
+ array = [red, green, blue]
+ if(lednum == 1):
+ self.bankA.writeArray(self.PS_R, array)
+ if(lednum == 2):
+ self.bankB.writeArray(self.PS_R, array)
+ time.sleep(0.001)
def isKeyPressed(self):
- x = 0
try:
x = self.bankA.readByte(self.PS_KeyPress)
return int(0x01&x)
@@ -841,52 +694,11 @@ def isKeyPressed(self):
def getKeyPressValue(self):
try:
- if self.ts_cal == None:
- return (self.bankA.readByte(self.PS_KeyPress))
-
- # if self.ts_cal doesn't exist because it failed to load touchscreen calibration values in __init__, the surrounding try/except block here will handle returning 0 as the default/error value
- x1 = self.ts_cal['x1']
- y1 = self.ts_cal['y1']
- x2 = self.ts_cal['x2']
- y2 = self.ts_cal['y2']
- x3 = self.ts_cal['x3']
- y3 = self.ts_cal['y3']
- x4 = self.ts_cal['x4']
- y4 = self.ts_cal['y4']
-
- x = self.bankA.readInteger(0xE7) # current x
- # x1 and x2 are the left-most calibration points. We want to take whichever value is furthest right, to give the maximum touch area for the software buttons that make sense. x4 is the right-top calibration point. If x4 > x1 then 0 is towards the left so the the greater value of x1 and x2 will be the rightmost. If not, then high numbers are towards the left so we the lesser value of x1 and x2 will be rightmost.
- # We don't take a calibration point in the left gutter, so we have to assume 200 is the greatest reasonable width of this area. If the current touched x point is right of the border, then it is on the touchscreen so return 0 (because none of the software buttons are being pressed). If the value is between the border and 200 points left of that, continue on as the touch point is in the software button area, If the value is further than 200 points left of the border, it is likely an erroneous error caused by the touchscreen not being touched.
- if x4 > x1: # lower values left
- xborder = max(x1, x2) # where the touchscreen ends and the software buttons begin
- if not xborder+100 > x > xborder-200:
- return 0
- else: # greater values left
- xborder = min(x1, x2)
- if not xborder-100 < x < xborder+200:
- return 0
-
- y = self.bankA.readInteger(0xE9) # current y
- # the lower and greater of the two left-most y calibration values
- # TODO: does this assume the screen is not flipped vertically? Be sure to test this
- ymin = min(y1, y2)
- ymax = max(y1, y2)
- yQuarter = (ymax-ymin)/4 # a quarter of the distance between the two y extremes
-
- if y < ymin + 0 * yQuarter:
- return 0 # too low
- if y < ymin + 1 * yQuarter:
- return 8
- if y < ymin + 2 * yQuarter:
- return 16
- if y < ymin + 3 * yQuarter:
- return 24
- if y < ymin + 4 * yQuarter:
- return 40
- if y >= ymin + 4 * yQuarter:
- return 0 # too high
-
- return 0 # some other weird error occured, execution should not reach this point
+ x, y = self.getTouchscreenCoordinates()
+ if x > 300 and y > 0:
+ return [8, 16, 24, 40][(y-1)/(240/4)]
+ else:
+ return 0
except:
return 0
@@ -898,13 +710,30 @@ def getKeyPressCount(self):
def resetKeyPressCount(self):
try:
- self.bankA.writeByte(self.PS_Key1Count,0)
+ self.bankA.writeByte(self.PS_Key1Count, 0)
except:
pass
def ping(self):
self.bankA.readByte(0x00)
+ def getTouchscreenCoordinates(self):
+ sampleSize = 3
+ tolerance = 3
+ x = [0]*sampleSize
+ y = [0]*sampleSize
+ try:
+ for i in range(sampleSize):
+ x[i] = self.bankA.readInteger(self.PS_TSX)
+ y[i] = self.bankA.readInteger(self.PS_TSY)
+ except:
+ print "Failed to read touchscreen"
+ return (0, 0)
+ if (numpy.std(x) < tolerance and numpy.std(y) < tolerance):
+ return (int(numpy.mean(x)), int(numpy.mean(y)))
+ else:
+ return (0, 0)
+
if __name__ == '__main__':
psc = PiStormsCom()
print "Version = "+ str(psc.GetFirmwareVersion())
@@ -912,7 +741,7 @@ def ping(self):
print "Device = "+ str(psc.GetDeviceId())
try:
while(True):
- print psc.battVoltage()
+ print psc.battVoltage()
print psc.BAS1.SumoEyes(True)
print psc.BAS2.colorSensorNXT()
print psc.BBS1.lightSensorNXT(True)
@@ -934,10 +763,12 @@ def ping(self):
psc.BBM2.hold()
time.sleep(5)
+
psc.BAM1.float()
psc.BAM2.float()
psc.BBM1.float()
psc.BBM2.float()
+
time.sleep(1)
except KeyboardInterrupt:
@@ -945,15 +776,3 @@ def ping(self):
psc.BAM2.float()
psc.BBM1.float()
psc.BBM2.float()
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/sys/mindsensorsUI.py b/sys/mindsensorsUI.py
index 2a2d0513..a03d298b 100644
--- a/sys/mindsensorsUI.py
+++ b/sys/mindsensorsUI.py
@@ -29,9 +29,8 @@
# 10/7/16 Seth Battery indicator, line methods
# 1/25/17 Seth Additional dialog options
-from mindsensors_i2c import mindsensors_i2c
from PiStormsCom import PiStormsCom
-import time, math, os, sys
+import time, os, sys, math
import Image, ImageDraw, ImageFont
import textwrap
import MS_ILI9341 as TFT
@@ -39,31 +38,13 @@
import Adafruit_GPIO as GPIO
import Adafruit_GPIO.SPI as SPI
-# for new touchscreen functionality
-import json
-
## @package mindsensorsUI
# This module contains classes and functions necessary for use of LCD touchscreen on mindsensors.com products
-Dev_PiStorms = 1
-Dev_SensorShield = 2
-
## mindsensorsUI: this class provides functions for touchscreen LCD on mindsensors.com products for read and write operations.
-# There is no need to initialize this class unless using the LCD screen alone. Normal initialization will be performed automatically with initialization of the Device on which the screen is used.
+# There is no need to initialize this class unless using the LCD screen alone. Normal initialization will be performed automatically when instantiating a PiStorms object.
class mindsensorsUI():
-
- ## Default Device I2C Address
- PS_ADDRESS = 0x34
- ## Touchscreen X-axis Register. Will return an unsigned integer reading (0-340)
- PS_TSX = 0xE3
- ## Touchscreen Y-axis Register. Will return an unsigned integer reading (0-440)
- PS_TSY = 0xE5
- ## Touchscreen Y-axis Raw Register.
- PS_RAWX = 0xE7
- ## Touchscreen Y-axis Raw Register.
- PS_RAWY = 0xE9
-
## Constant to specify black color
PS_BLACK = (0,0,0)
## Constant to specify blue color
@@ -87,10 +68,6 @@ class mindsensorsUI():
PS_SCREENHEIGHT = 320
### @cond Doxygen_ignore_this
- #PS_XMIN = 0x5A
- #PS_XMAX = 0x5C
- #PS_YMIN = 0x5E
- #PS_YMAX = 0x60
## Constant to specify terminal mode
PS_MODE_TERMINAL = 0
## Constant to specify pop-up mode
@@ -116,8 +93,8 @@ class mindsensorsUI():
## Variable of default draw arrow state
drawArrowsbool = False
- touchIgnoreX = 0
- touchIgnoreY = 0
+ x = 0
+ y = 0
### @endcond
## Initialize the UI device.
@@ -132,35 +109,17 @@ class mindsensorsUI():
# ...
# screen = mindsensorsUI()
# @endcode
- def __init__(self, name = "PiStorms", rotation = 3, device = Dev_PiStorms):
- if device == Dev_SensorShield:
- self.PS_ADDRESS = 0x16
- self.PS_TSX = 0x56
- self.PS_TSY = 0x58
- self.i2c = mindsensors_i2c(self.PS_ADDRESS >> 1)
+ def __init__(self, name = "PiStorms", rotation = 3):
+ self.comm = PiStormsCom()
self.disp.begin()
self.clearScreen()
self.disp.command(ILI9341_INVOFF)
- try:
- self.touchIgnoreX = self.TS_X()
- self.touchIgnoreY = self.TS_Y()
- self.calibrateTouched()
- except:
- pass
-
- if(rotation > 0 and rotation < 4):
+
+ if(rotation in range(4)):
self.currentRotation = rotation
self.refresh()
self.myname = name
- #self.drawDisplay(name, display = False)
-
- self.ts_cal = None # signifies firmware version older than V3.00, use old touchscreen methods
- if self.i2c.readString(0x00, 8) >= 'V3.00':
- # read touchscreen calibration values from cache file
- try:
- self.ts_cal = json.load(open('/tmp/ps_ts_cal', 'r'))
- except IOError:
- print 'Touchscreen Error: Failed to read touchscreen calibration values in mindsensorsUI.py'
+ #self.drawDisplay(name, display=False)
## Dumps the screen buffer
# @param self The object pointer.
@@ -185,12 +144,6 @@ def setMode(self, mode = 0):
def getMode(self):
return self.currentMode
- ## Sets the expected X,Y when the screen is not touched to their current values (Experienced users)
- # @param self The object pointer.
- def calibrateTouched(self):
- self.touchIgnoreX = self.TS_X()
- self.touchIgnoreY = self.TS_Y()
-
## Draw a rectangle with rounded edges on the screen (rotated to screen)
# @param self The object pointer.
# @param x The upper left x coordinate of the rectangle.
@@ -210,24 +163,26 @@ def fillRoundRect(self, x, y, width, height, radius, fill = (255,255,255), displ
## Calculates the x-coordinate of the screen upon rotation (INTERNAL USE ONLY)
# @param self The object pointer.
- # @param x The x-coordinate.
- # @param y The y-coordinate.
- def screenXFromImageCoords(self, x = 0,y = 0):
- currentRotation = self.currentRotation
- if(currentRotation == 0):
+ # @param x x value in the current rotation's coordinate system
+ # @param y y value in the current rotation's coordinate system
+ # @return x value for the corresponding point in the display's coordinate system (for writing to TFT)
+ def screenXFromImageCoords(self, x, y):
+ cr = self.currentRotation
+ if(cr == 0):
return x
- if(currentRotation == 1):
+ if(cr == 1):
return self.PS_SCREENWIDTH-y
- if(currentRotation == 2):
+ if(cr == 2):
return self.PS_SCREENWIDTH-x
- if(currentRotation == 3):
+ if(cr == 3):
return y
- ## Calculates the y-coordinate of the screen upon rotation(INTERNAL USE ONLY)
+ ## Calculates the y-coordinate of the screen upon rotation (INTERNAL USE ONLY)
# @param self The object pointer.
- # @param x The x-coordinate.
- # @param y The y-coordinate.
- def screenYFromImageCoords(self, x = 0,y = 0):
+ # @param x x value in the current rotation's coordinate system
+ # @param y y value in the current rotation's coordinate system
+ # @return y value for the corresponding point in the display's coordinate system (for writing to TFT)
+ def screenYFromImageCoords(self, x, y):
cr = self.currentRotation
if(cr == 0):
return y
@@ -240,33 +195,35 @@ def screenYFromImageCoords(self, x = 0,y = 0):
## Calculates display x-coordinate from touchscreen values, adjusted for rotation (INTERNAL USE ONLY)
# @param self The object pointer.
- # @param x The x-coordinate.
- # @param y The y-coordinate.
+ # @param x x value in the touchscreen's coordinate system (read from registers)
+ # @param y y value in the touchscreen's coordinate system (read from registers)
+ # @return x value for the corresponding point in the current rotation's coordinate system
def TS_To_ImageCoords_X(self, x, y):
cr = self.currentRotation
if(cr == 0):
- return x
- if(cr == 1):
return y
+ if(cr == 1):
+ return x
if(cr == 2):
- return self.PS_SCREENWIDTH-x
+ return self.PS_SCREENWIDTH-y
if(cr == 3):
- return self.PS_SCREENHEIGHT-y
+ return self.PS_SCREENHEIGHT-x
## Calculates display y-coordinate from touchscreen values, adjusted for rotation (INTERNAL USE ONLY)
# @param self The object pointer.
- # @param x The x-coordinate.
- # @param y The y-coordinate.
+ # @param x x value in the touchscreen's coordinate system (read from registers)
+ # @param y y value in the touchscreen's coordinate system (read from registers)
+ # @return y value for the corresponding point in the current rotation's coordinate system
def TS_To_ImageCoords_Y(self, x, y):
cr = self.currentRotation
if(cr == 0):
- return y
+ return x
if(cr == 1):
- return self.PS_SCREENWIDTH-x
+ return self.PS_SCREENWIDTH-y
if(cr == 2):
- return self.PS_SCREENHEIGHT-y
+ return self.PS_SCREENHEIGHT-x
if(cr == 3):
- return x
+ return y
## Displays rotated text (INTERNAL USE ONLY)
# @param self The object pointer.
@@ -339,105 +296,6 @@ def showArrows(self, refresh = True):
if(refresh):
self.refresh()
- ## Determines if button in a pop-up window is pressed (Experienced users)
- # @param self The object pointer.
- # @param xbuff The x-coordinate buffer.
- # @param ybuff The y-coordinate buffer.
- # @param buttHeight The height of the button.
- def calculateButton(self, xbuff, ybuff, buttHeight):
- for n in range(len(self.buttonText)):
- numButts = len(self.buttonText)
- room = self.screenWidth()-(xbuff + ybuff)
- xlb = (room/numButts)*n + xbuff
- ylb = self.screenHeight() - (ybuff + buttHeight)
- xub = xlb + (room/numButts)
- yub = ylb + buttHeight
-
- axlb = self.screenXFromImageCoords(xlb,ylb)
- aylb = self.screenYFromImageCoords(xlb,ylb)
- axub = self.screenXFromImageCoords(xub,yub)
- ayub = self.screenYFromImageCoords(xub,yub)
-
- if(axubaxlb and tsy>aylb and tsy max(x1,x2,x3,x4) \
- or y < min(y1,y2,y3,y4) \
- or y > max(y1,y2,y3,y4):
- return (0, 0)
-
- def distanceToLine(x0, y0, x1, y1, x2, y2): # point and two points forming the line
- return float( abs( (y2-y1)*x0 - (x2-x1)*y0 + x2*y1 - y2*x1 ) ) / math.sqrt( (y2-y1)**2 + (x2-x1)**2 )
-
- # http://math.stackexchange.com/a/104595/363240
- try:
- dU0 = int(float( distanceToLine(x, y, x1, y1, x2, y2) )/(y2-y1)*320)
- dV0 = int(float( distanceToLine(x, y, x1, y1, x4, y4) )/(x4-x1)*240)
-
- dU1 = int(float( distanceToLine(x, y, x4, y4, x3, y3) )/(y3-y4)*320)
- dV1 = int(float( distanceToLine(x, y, x2, y2, x3, y3) )/(x3-x2)*240)
-
- x = float( dU0 )/(dU0+dU1) # 0 to 1
- y = float( dV0 )/(dV0+dV1) # 0 to 1
-
- #return int(320*x), int(240*y)
- return int(240*y), 320-int(320*x) # for compatibility
-
- except ZeroDivisionError:
- return (0, 0)
-
- tolerance = 5
-
- x1, y1 = getReading()
- x2, y2 = getReading()
-
- if abs(x2-x1) < tolerance and abs(y2-y1) < tolerance:
- return (x2, y2)
- else:
- return (0, 0)
-
## Reads the x-coordinate of the touchscreen press
# @param self The object pointer.
# @remark
@@ -447,14 +305,7 @@ def distanceToLine(x0, y0, x1, y1, x2, y2): # point and two points forming the l
# x = screen.TS_X()
# @endcode
def TS_X(self):
- if self.ts_cal != None:
- return self.getTouchscreenValues()[0]
- else:
- try:
- return self.i2c.readInteger(self.PS_TSY)
- except:
- print "Could not read Touch Screen X"
- return -1
+ return self.x
## Reads the y-coordinate of the touchscreen press
# @param self The object pointer.
@@ -464,59 +315,24 @@ def TS_X(self):
# y = screen.TS_Y()
# @endcode
def TS_Y(self):
- if self.ts_cal != None:
- return self.getTouchscreenValues()[1]
- else:
- try:
- return self.i2c.readInteger(self.PS_TSX)
- except:
- print "Could not read Touch Screen Y"
- return -1
+ return self.y
- ## Reads the raw touchscreen x-value (INTERNAL USE ONLY)
- # @param self The object pointer.
- def RAW_X(self):
- try:
- return self.i2c.readInteger(self.PS_RAWX)
- except:
- print "Could not read Raw Touch Screen X"
- return -1
-
- ## Reads the raw touchscreen y-value (INTERNAL USE ONLY)
- # @param self The object pointer.
- def RAW_Y(self):
- try:
- return self.i2c.readInteger(self.PS_RAWY)
- except:
- print "Could not read Raw Touch Screen Y"
- return -1
-
- ## Detects touchscreen presses and prevents false positives
+ ## Detects touchscreen presses and prevents false positives,
+ # updates self.x and self.y if pressed.
# @param self The object pointer.
# To use this function in your program:
# @code
# ...
- # touch = screen.isTouched()
+ # if (screen.isTouched())
+ # print "Touched at {},{}".format(screen.x, screen.y)
# @endcode
def isTouched(self):
- if self.ts_cal != None:
- return self.getTouchscreenValues() != (0, 0)
-
- time.sleep(0.001)
- firstTry = self.touchIgnoreX == self.TS_X() and self.touchIgnoreY == self.TS_Y()
- secondTry = self.touchIgnoreX == self.TS_X() and self.touchIgnoreY == self.TS_Y()
- thirdTry = self.touchIgnoreX == self.TS_X() and self.touchIgnoreY == self.TS_Y()
- # return (not firstTry) and (not secondTry) and (not thirdTry)
- # Modified
- x = self.TS_X() # before everything else for speed
- y = self.TS_Y()
-
- touch = (not firstTry) and (not secondTry) and (not thirdTry)
- if touch:
- self.disp.x = x
- self.disp.y = y
- self.disp.store = True
- return touch
+ x, y = self.comm.getTouchscreenCoordinates()
+ if x == 0 and y == 0:
+ return False
+ self.x = x
+ self.y = y
+ return True
## Clears the LCD screen to defualt black
# @param self The object pointer.
@@ -919,48 +735,41 @@ def refresh(self):
# @param self The object pointer.
# @param x The upper left x-coordinate of the button.
# @param y The upper left y-coordinate of the button.
- # @param width The width of the button. Optional, defaults to 150.
- # @param height The height of the button. Optional, defaults to 50.
+ # @param width The width of the button.
+ # @param height The height of the button.
# @remark
# To use this function in your program:
# @code
# ...
- # button = screen.checkButton(0,0,50,50)
+ # button = screen.checkButton(0, 0, 50, 50)
# @endcode
- def checkButton(self, x, y, width = 150, height = 50):
- if(self.isTouched()):
- axlb = self.screenXFromImageCoords(x,y)
- aylb = self.screenYFromImageCoords(x,y)
- axub = self.screenXFromImageCoords(x + width,y + height)
- ayub = self.screenYFromImageCoords(x + width,y + height)
-
- if(axubaxlb and tsy>aylb and tsy
-
@@ -229,7 +228,6 @@ function redirectRestart() {window.location = "./reboot.php";}
});
$("#stop_br").click(function(){$.get(api+"stopbrowser", function(data){});notify("Success","Signal to stop browser sent","success");});
$("#start_br").click(function(){$.get(api+"startbrowser", function(data){});notify("Success","Signal to start browser sent","success");});
-$("#calibrate_btn").click(function(){$.get(api+"calibrate", function(data){});notify("Success","Calibration started","success");});
$("#needs-update-tooltip").click(function() {
window.open("https://github.com/mindsensors/PiStorms");
diff --git a/www/web_api/MSWeb.py b/www/web_api/MSWeb.py
index a3bb4c37..c81011de 100644
--- a/www/web_api/MSWeb.py
+++ b/www/web_api/MSWeb.py
@@ -254,14 +254,6 @@ def startbrowser():
print "Started Browser"
return "1"
-@app.route("/calibrate", methods=['GET', 'OPTIONS'])
-@crossdomain(origin='*')
-def calibrate():
- stopbrowser()
- os.system("python " + os.path.join(home_folder, "programs", "utils", "01-Calibrate.py"))
- startbrowser()
- return "1"
-
@app.route("/getapacheerrors", methods=['GET', 'OPTIONS'])
@crossdomain(origin='*')
def getapacheerrors():