serial communication error for loop

MRAB python at mrabarnett.plus.com
Tue Mar 13 21:15:44 EDT 2018


On 2018-03-14 00:23, Dhileepan Kumar wrote:
> 
> #!/usr/bin/python
> 
> import serial
> import MySQLdb
> while True:
> #establish connection to MySQL. You'll have to change this for your database.
> 	dbConn = MySQLdb.connect("localhost","root","1234","ifet") or die ("could not connect to database")
> 	#open a cursor to the database
> 	cursor = dbConn.cursor()
> 
> 	device = 'com3' #this will have to be changed to the serial port you are using
> 	arduino = serial.Serial(device, 9600)
> 
> 
> 	try:
> 	  data = arduino.readline()  #read the data from the arduino
> 	  if not data.strip():
> 	   continue
> 	  pieces = data.split("\t")  #split the data by the tab
> 	  #Here we are going to insert the data into the Database
> 	  try:
> 		cursor.execute("INSERT INTO answer1 (voltage,current) VALUES (%s,%s)", (pieces[0],pieces[1]))
> 		dbConn.commit() #commit the insert
> 		cursor.close()  #close the cursor
> 	  except MySQLdb.IntegrityError:
> 		print "failed to insert data"
> 	  finally:
> 		cursor.close()  #close just incase it failed
> 	except:
> 	  print "Failed to get data from Arduino!"
> 
> ................................................................................
> it is my program.if do not use while true loop successfully run but can't get a continues data from arduino so i have decide to using while loop  but if using while loop shows some error
> 
> 
> (project) C:\Users\DHILEEPAN\project\project>python mysql.py
> Traceback (most recent call last):
>    File "mysql.py", line 13, in <module>
>      arduino = serial.Serial(device, 9600)
>    File "C:\Users\DHILEEPAN\Envs\project\lib\site-packages\serial\serialwin32.py", line 31, in __init_
>      super(Serial, self).__init__(*args, **kwargs)
>    File "C:\Users\DHILEEPAN\Envs\project\lib\site-packages\serial\serialutil.py", line 240, in __init_
>      self.open()
>    File "C:\Users\DHILEEPAN\Envs\project\lib\site-packages\serial\serialwin32.py", line 62, in open
>      raise SerialException("could not open port {!r}: {!r}".format(self.portstr, ctypes.WinError()))
> serial.serialutil.SerialException: could not open port 'com3': WindowsError(5, 'Access is denied.')
> 
> please any one fix this
> 
It cannot open the port the second time because the port is already open 
from the first time.

You have put too much inside the loop. It should be more like:
# open database and serial
while True:
     # do read and insertion
# close database and serial

Even better, use the 'with' statement, which is neater:

with <open database>:
     with <open serial>:
         while True:
             # do read and insertion



More information about the Python-list mailing list