Subversion Repositories Code-Repo

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
223 Kevin 1
import serial
2
 
3
def twos_comp(val, bits):
4
	'''Convert given value from two's complement to integer'''
5
	if ((val & (1 << (bits-1))) != 0):
6
		val = val - (1 << bits)
7
	return val
8
 
9
if __name__ == '__main__':
10
	print("Attempting to connect to serial port...")
11
	# Connect to specified serial port
12
	ser = serial.Serial()
13
	ser.baudrate = 115200
14
	ser.port = "COM3"
15
	ser.timeout = 3 # Three second timeout
16
	try:
17
		ser.open()
18
		print("Connected to serial port.")
19
		# Loop reading in data from the sensor
20
		while(1):
224 Kevin 21
			s = ser.read(21)
223 Kevin 22
			# Ensure that the data properly ends in a newline
224 Kevin 23
			if s[20] == ord('\n'):
223 Kevin 24
				# Read in accelerometer data and convert from two's compliment
25
				A_X = ((s[1] << 8) | s[0])
26
				A_Y = ((s[3] << 8) | s[2])
27
				A_Z = ((s[5] << 8) | s[4])
28
				A_X_N = twos_comp(A_X, 16) >> 4
29
				A_Y_N = twos_comp(A_Y, 16) >> 4
30
				A_Z_N = twos_comp(A_Z, 16) >> 4
31
 
32
				# Read in gyroscope data and convert from two's compliment
33
				G_Y = (s[7] << 8) | s[6]
34
				G_X = (s[9] << 8) | s[8]
35
				G_Z = (s[11] << 8) | s[10]
36
				G_X_N = twos_comp(G_X, 16)
37
				G_Y_N = twos_comp(G_Y, 16)
38
				G_Z_N = twos_comp(G_Z, 16)
39
 
40
				# Read in magnetometer data and convert from two's compliment
41
				M_X = ((s[13] << 8) | s[12])
42
				M_Y = ((s[15] << 8) | s[14])
43
				M_Z = ((s[17] << 8) | s[16])
44
				M_X_N = twos_comp(M_X, 16)
45
				M_Y_N = twos_comp(M_Y, 16)
46
				M_Z_N = twos_comp(M_Z, 16)
47
 
224 Kevin 48
				# Read in battery status
49
				B_H = s[18]
50
				B_L = s[19]
51
 
223 Kevin 52
				# Print out the processed data
224 Kevin 53
				print("A: %-6i %-6i %-6i   G: %-6i %-6i %-6i   M: %-6i %-6i %-6i   B: %u.%u" % \
54
					(A_X_N, A_Y_N, A_Z_N, G_X_N, G_Y_N, G_Z_N, M_X_N, M_Y_N, M_Z_N, B_H, B_L))
223 Kevin 55
			else:
56
				break
57
	except:
58
		pass
59
	ser.close()