1

enter image description here

I am making serial port communication device from a genious guy's work instructables.com.

It will measure the distance of the hamster's running in a day or month.

Using 4, 6 pin of the serial port cable, if the hamster runs, the device can count the numbers how many time did she run.

When I run the py file with Python27 like below, some errors occure. "python hamster-serial.py progress.txt"

I cannot understand what's going on. I am using windows8 and Python2.7 version.

Could you check my source, please?

import datetime
import serial
import sys

# Check for commandline argument. The first argument is the the name of the program.
if len(sys.argv) < 2:
  print "Usage: python %s [Out File]" % sys.argv[0]
  exit()

# Open the serial port we'll use the pins on and the file we'll write to.
ser = serial.Serial("/dev/ttyS1")

# Open the file we're going to write the results to.
f = open(sys.argv[1], 'a')

# Bring DTR to 1. This will be shorted to DSR when the switch is activated as the wheel turns.
ser.setDTR(1)

# The circumferance of the wheel.
circ = 0.000396 # miles
# Total distance traveled in this run of the program.
distance = 0.0

print "%s] Starting logging." % datetime.datetime.now()
start = datetime.datetime.now()

# This function a period of the wheel to a speed of the hamster.
def toSpeed(period):
  global circ
  seconds = period.days * 24 * 60 * 60 + period.seconds + period.microseconds / 1000000.
  return circ / (seconds / 60. / 60.)
  
# Waits for the DSR pin on the serial port to turn off. This indicates that the
# switch has turned off and the magnet is no longer over the switch.
def waitForPinOff():
  while ser.getDSR() == 1:
    1 # Don't do anything while we wait.

# Waits for the DSR pin on the serial port to turn on. This indicates that the
# switch has turned on and the magnet is current over the switch.
def waitForPinOn():
  while ser.getDSR() == 0:
    1 # Don't do anything while we wait.

# The main loop of the program.
while 1:
  waitForPinOn()
  
  # Calculate the speed.
  end = datetime.datetime.now()
  period = end - start
  start = end
  speed = toSpeed(period)
  # Increment the distance.
  distance = distance + circ
  
  waitForPinOff()
  
  # We'll calculate the time the switch was held on too so but this isn't too useful.
  hold = datetime.datetime.now() - start
 
  # If the switch bounces or the hamster doesn't make a full revolution then
  # it might seem like the hamster is running really fast. If the speed is
  # more than 4 mph then ignore it, because the hamster can't run that fast.
  if speed < 4.0:
    # Print out our speed and distance for this session.
    print "%s] Distance: %.4f miles Speed: %.2f mph" % (datetime.datetime.now(), distance, speed)
      
    # Log it to and flush the file so it actually gets written.
    f.write("%s\t%.2f\n" % (datetime.datetime.now().strftime("%D %T"), speed))
    f.flush()
    
Clara Kim
  • 13
  • 4

1 Answers1

0

Well, ser = serial.Serial("/dev/ttyS1") is for a linux machine, on windows you'll need something like ser = serial.Serial("COM1") (you can check what COM do you need in the device manager).

As a side note,

def waitForPinOff():
   while ser.getDSR() == 1:
      1 # Don't do anything while we wait.

Will eat you CPU. You are better of with:

def waitForPinOff():
   while ser.getDSR() == 1:
      time.sleep(1) # Don't do anything while we wait.
Aruj
  • 82
  • 1
  • 10
  • Wow!! Unbelievable! Just now, you save my life...in my the most important moment! I am really appreciate you! – Clara Kim Aug 02 '16 at 02:18
  • I think, it is succeeded! Now I will reserch and investigate. Thanks for your great help! – Clara Kim Aug 02 '16 at 05:40
  • >>> 2016-08-02 14:38:34.145000] Starting logging. Traceback (most recent call last): File "C:\Python27\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 326, in RunScript exec codeObject in __main__.__dict__ File "C:\Python27\hamster-serial.py", line 54, in speed = toSpeed(period) File "C:\Python27\hamster-serial.py", line 31, in toSpeed return circ / (seconds / 60. / 60.) ZeroDivisionError: float division by zero – Clara Kim Aug 02 '16 at 05:40
  • Your func runs end right after start. Can you explain the inputs your system has? What is the requirement for 1 and 0? Also, assuming the switch is on when you run the code, your start and end will be equal. – Aruj Aug 02 '16 at 08:25
  • OK, you should change `seconds = period.days * 24 * 60 * 60 + period.seconds + period.microseconds / 1000000` to `seconds = period.days * 24 * 60 * 60 + period.seconds + period.microseconds / 1000000.0` so the result wont be rounded to integer. Currently a result smaller than one second returns 0. – Aruj Aug 02 '16 at 10:47
  • Thank you for your great help! I will be so happy to learn and study Python! – Clara Kim Aug 03 '16 at 02:56
  • >>> 2016-08-03 21:22:46.808000] Starting logging. 2016-08-03 21:22:55.574000] Distance: 0.0053 miles Speed: 2.16 mph Traceback (most recent call last): File "C:\Python27\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 326, in RunScript exec codeObject in __main__.__dict__ File "C:\Python27\hamster-serial.py", line 70, in f.write("%s\t%.2f\n" %(datetime.datetime.now().strftime("%D %T"), speed)) ValueError: Invalid format string – Clara Kim Aug 03 '16 at 12:24
  • IT's almost done! the last valueError is the file write. I am studying and trying to do by myself but it is still difficult! Thanks Aruj!! – Clara Kim Aug 03 '16 at 12:26
  • You have a reference for strftime formats (here)[https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior]. You probably want something like `"%s\t%.2f\n" %(datetime.datetime.now().strftime("%d/%m/%y %H:%M:%S"), speed)` – Aruj Aug 03 '16 at 13:40
  • Arju!! Finally, I got the perfect result! – Clara Kim Aug 06 '16 at 02:03
  • 06/08/16 11:02:03 2.76 06/08/16 11:02:04 2.85 06/08/16 11:02:05 2.77 06/08/16 11:02:05 2.28 06/08/16 11:02:06 2.94 06/08/16 11:02:06 3.80 06/08/16 11:02:06 3.80 06/08/16 11:02:11 1.13 06/08/16 11:02:12 1.72 06/08/16 11:02:13 2.12 06/08/16 11:02:14 1.98 06/08/16 11:02:14 2.28 06/08/16 11:02:15 2.23 06/08/16 11:02:15 2.53 06/08/16 11:02:16 2.28 06/08/16 11:02:17 2.40 06/08/16 11:02:17 2.47 06/08/16 11:02:18 2.47 06/08/16 11:02:18 3.80 06/08/16 11:02:20 2.28 06/08/16 11:02:21 1.06 06/08/16 11:02:22 1.79 – Clara Kim Aug 06 '16 at 02:03
  • It is my progress.txt – Clara Kim Aug 06 '16 at 02:03
  • I found that the cause of the error was the setting of magnetic reed switch! – Clara Kim Aug 06 '16 at 02:04
  • I am so appreciated to you and the original source programmer! – Clara Kim Aug 06 '16 at 02:04
  • And also you can see my work in my website! kimyongim.com/220777899822 Please, give me any advice any time! Thank you again, Arju! – Clara Kim Aug 07 '16 at 04:11