Read data from a DDSU666 using RS485 - python

I have tried my luck with these codes to read the data from the DDSU666-H and it seems that I am able to read data, but I don't know what to do with it. In theory it is a list of data, but I am not able to understand what I am receiving or how to translate it into something I can use
import serial # import the module
def banner_bottom():
print(' +-------------------------------------------+')
print(' | SPACE |')
print(' +-------------------------------------------+')
COM_Port = serial.Serial('COM3')
COM_Port.baudrate = 9600 # set Baud rate
COM_Port.bytesize = 8 # Number of data bits = 8
COM_Port.parity = 'N' # No parity
COM_Port.stopbits = 1 # Number of Stop bits = 1
COM_Port.setRTS(1) #RTS=1,~RTS=0 so ~RE=0,Receive mode enabled for MAX485
COM_Port.setDTR(1) #DTR=1,~DTR=0 so DE=0,(In FT232 RTS and DTR pins are inverted)
#~RE and DE LED's on USB2SERIAL board will be off
RxedData = COM_Port.readline()
print(' ',RxedData, '\n')
COM_Port.close() # Close the Serial port
banner_bottom()# Display the bottom banner
Output:
b'\x7f~\xbb\xff\xfb\xe3=\x7f~_cuI_\x0e\x7f~\xbb\xff\xfb\xe3=\x7f~_]\xd3V\'\t\x7f~\xbb\xff\xfb\xe3=\x7f~__\x07\xf5tU\x7f~\xbb\xff\xfb\xe3=\x7f~_[y\x8d\xba\x00\x7f~\xbb\xff\xfb\xe3=\x7f~_YsGe\x18\x7f~\xbb\xff\xfb\xe3=\x7f~_Y\xe3\x06n\x16\x7f~\xbb\xff\xfb\xe3=\x7f~__O]I\x1d\x7f~\xbb\xff\xfb\xe3=\x7f~_ao\xff\xf0\x05\x7f~\xbb\xff\xfb\xe3=\x7f~_co-O\x10\x7f~\xbb\xff\xfb\xe3=\x7f~__\x15\x117\x03\x7f~\xbb\xff\xfb\xe3=\x7f~__!-\xc9/\x7f~\xbb\xff\xfb\xe3=\x7f~__}\xed|\x00\x7f~\xbb\xff\xfb\xe3=\x7f~_c\xb7+\xda\x00\x7f~\xbb\xff\xfb\xe3=\x7f~_e\x8f"U\x01\x7f~\xfd\xff\xfb]\x1a\x7f~_W\xaf\x08\x975\x00\x7f~\xfd\xff\xfb]\x1a\x7f~_W\xaf\x08\x975\x00\x7f~\xfd\xff\xfb]\x1a\x7f~_W\xaf\x08\x975\x00\x7f~\xbb\xff\xfb\xe3=\x7f~_]\xd3V\'\t\x7f~\xbb\xff\xfb\xe3=\x7f~__\xd9\xadb\x08\x7f~\xbb\xff\xfb\xe3=\x7f~__\xc5[P\x05\x7f~\xbb\xff\xfb\xe3=\x7f~__\x91\xfef\x00\x7f~\xbb\xff\xfb\xe3=\x7f~_c3\xb3T\x0f\x7f~\xbb\xff\xfb\xe3=\x7f~_e\xbd\x01\xb0\x03\x7f~\xbb\xff\xfb\xe3=\x7f~_e?y\x84\x19\x7f~\xbb\xff\xfb\xe3=\x7f~_\xe349\xac\n'
Code 2:
#!/usr/bin/env python3
import serial
port = 'COM3'
ComPort = serial.Serial(port)
ComPort.baudrate = 9600
ComPort.bitesize = 8
ComPort.parity = 'N'
ComPort.stopbits = 1
dataIn=ComPort.read(6)
print(dataIn)
ComPort.close()
Ouput:
b'\x7f~\xbb\xff\xfb\xe3'
I've tried to translate the output into something I can understand, but I haven't been able to see anything either.
binary_data = b'\x7f~\xbb\xff\xfb\xe3'
aa = binary_data.hex()
print(aa)
#OUT: 7f7ebbfffbe3
bb = ''.join(['%02x' % b for b in binary_data])
print(bb)
#OUT: 7f7ebbfffbe3
s = binary_data.decode('cp855')
print(s)
#OUT:~╗ чÑ
What can I try to resolve this?

Related

pi won't read values from MCP3424

when I try to read data from a MCP3424 ADC, I get unexpected, wrong results. I know the device is connected, butthe results I'm reading are wrong
I write to channels 3 and 4 of the ADC. When I read the result back, the data in the config register doesn't match what I programmed
import smbus
import time
# Get I2C bus
bus = smbus.SMBus(1)
# I2C address of the device
MCP3425_DEFAULT_ADDRESS = 0x68
# MCP3425 Configuration Command Set
MCP3425_CMD_NEW_CNVRSN = 0x80 # Initiate a new conversion(One-Shot Conversion mode only)
MCP3425_CMD_MODE_CONT = 0x10 # Continuous Conversion Mode
MCP3425_CMD_MODE_ONESHOT = 0x00 # One-Shot Conversion Mode
MCP3425_CMD_SPS_240 = 0x00 # 240 SPS (12-bit)
MCP3425_CMD_SPS_60 = 0x04 # 60 SPS (14-bit)
MCP3425_CMD_SPS_15 = 0x08 # 15 SPS (16-bit)
MCP3425_CMD_GAIN_1 = 0x00 # PGA Gain = 1V/V
MCP3425_CMD_GAIN_2 = 0x01 # PGA Gain = 2V/V
MCP3425_CMD_GAIN_4 = 0x02 # PGA Gain = 4V/V
MCP3425_CMD_GAIN_8 = 0x03 # PGA Gain = 8V/V
MCP3425_CMD_READ_CNVRSN = 0x00 # Read Conversion Result Data
MCP3425_CMD_CH4 =0x60
MCP3425_CMD_CH3 =0x40
class MCP3425():
def __init__(self):
self.config_command()
def config_command(self):
"""Select the Configuration Command from the given provided values"""
CONFIG_CMD4 = (MCP3425_CMD_CH4| MCP3425_CMD_MODE_CONT | MCP3425_CMD_SPS_60 | MCP3425_CMD_GAIN_2)
bus.write_byte(MCP3425_DEFAULT_ADDRESS, CONFIG_CMD4)
CONFIG_CMD3 = (MCP3425_CMD_CH3| MCP3425_CMD_MODE_CONT | MCP3425_CMD_SPS_240 | MCP3425_CMD_GAIN_1)
bus.write_byte(MCP3425_DEFAULT_ADDRESS, CONFIG_CMD3)
print ('-C-', CONFIG_CMD4, CONFIG_CMD3)
def read_adc(self, channel):
"""Read data back from MCP3425_CMD_READ_CNVRSN(0x00), 2 bytes
raw_adc MSB, raw_adc LSB"""
data = bus.read_i2c_block_data(MCP3425_DEFAULT_ADDRESS, (MCP3425_CMD_READ_CNVRSN | channel), 3)
print (channel, data)
# Convert the data to 12-bits
raw_adc = ((data[0] & 0x0F) * 256) + data[1]
if raw_adc > 2047 :
raw_adc -= 4095
return {'r' : raw_adc}
#from MCP3425 import MCP3425
mcp3425 = MCP3425()
while True :
adc = mcp3425.read_adc(MCP3425_CMD_CH4)
print ("Digital Value of Analog Input 4: %d "%(adc['r']))
adc = mcp3425.read_adc(MCP3425_CMD_CH3)
print ("Digital Value of Analog Input 3: %d "%(adc['r']))
print (" ********************************* ")
time.sleep(0.8)
I write 117 (01110101)to channel 4, and 80 (01010000) to channel 3 config registers. Which means for both channels I should get 3 bytes back: 2 data bytes and one config register byte
this is the printout I'm getting, no values read (Ch4+ is connected to voltage divider (2.5v), Ch4- and Ch3- are connected to ground, Ch3+ is floating) and byte 3 is just the address, not the Config register
-C- 117 80
96 [0, 0, 96]
Digital Value of Analog Input 4: 0
64 [0, 0, 64]
Digital Value of Analog Input 3: 0
*********************************
now it took some time but I found the issue.
The trick was that the MCP3434 is not a 4-channel ADC, but a single ADC with an 4-input multiplexer. Once I realized that, the schematic from the datasheet was obvious. It is just not explained very well in the description on how to handle dataflow on the I2C bus.
So you can not configure two ADC's to measure in parallel but when you need to read more channels you have to
1) configure/start channel 1
2) read data
3) configure/start channel 2
4) read data
the read data step is thus channel independant.

sending hex data over serial port with checksum

I am new to python and I am trying to write a code to send hex serial data to a radio and receive hex data in response. radio_init_buf variable store the hex data to be sent. The last two bytes with store checksum. radio_init_buf[3] tells the size.
import sys
import glob
import numpy as np
import serial
class serial_communication():
PORT = 'COM2'
# RETURN_VALUE = None
def list_serial_ports(self):
""" Lists serial port names
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list of the serial ports available on the system
"""
if sys.platform.startswith('win'):
ports = ['COM%s' % (i + 1) for i in range(0,10)]
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
# this excludes your current terminal "/dev/tty"
ports = glob.glob('/dev/tty[A-Za-z]*')
elif sys.platform.startswith('darwin'):
ports = glob.glob('/dev/tty.*')
else:
raise EnvironmentError('Unsupported platform')
result = []
for port in ports:
try:
s = serial.Serial(port)
s.close()
result.append(port)
except (OSError, serial.SerialException):
pass
return result
def serial_open(self):
self.ser = serial.Serial()
self.ser.baudrate = 9600
self.ser.port = sc.PORT
self.ser.parity = serial.PARITY_NONE
self.ser.stopbits = serial.STOPBITS_ONE
self.ser.bytesize = serial.EIGHTBITS
self.ser.writeTimeout = 1000
self.ser.timeout = 1000
try:
self.ser.open()
print("Port OPENED")
self.initialize(self.ser)
except Exception as e:
print("error opening serial port: " + str(e))
exit()
return self.ser
def checksum(self, crc_packet, crc_packet_length):
crc_table= np.array([0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040],dtype=np.uint16)
saved_crc_byte1 = crc_packet[crc_packet_length - 1]
saved_crc_byte2 = crc_packet[crc_packet_length - 2]
crc_packet[crc_packet_length - 1] = 0
crc_packet[crc_packet_length - 2] = 0
crc = 0
for crc_loop in range(0,crc_packet_length):
crc = (crc >> 8) ^ crc_table[(crc ^ crc_packet[crc_loop]) & 0xFF]
def initialize(self,serial_port):
ser = serial_port
if ser.isOpen():
print("Initialising...")
try:
ser.flushInput() # flush input buffer, discarding all its contents
ser.flushOutput() # flush output buffer, aborting current output
# and discard all that is in buffer
# write data
#f = open('F:/output.txt', 'wb')
radio_init_buf = np.array([0xAA, 0x00, 0x00, 0x08, 0x09, 0x32, 0x0, 0x0],dtype=np.uint8)
#radio_init_buf="\xAA\x00\x00\x08\x09\x32\x00\x00"
print(radio_init_buf)
self.checksum(radio_init_buf,radio_init_buf[3])
print(radio_init_buf)
ser.write(radio_init_buf)
serial.time.sleep(0.5) # give the serial port sometime to receive the data
#return_value = ser.read(7)
print(return_value)
print("Initialisation Complete")
#comm Link Check
print("Communication Link Checking..")
comm_check_buf = np.array([0xAA, 0x06, 00, 6, 0x0B, 0x70],dtype=np.uint8)
ser.write(comm_check_buf)
print("Link Check Complete")
#clear non-volatile memory
clear_nvm_buf = np.array([0xAA, 0x82, 00, 7, 1, 0, 0],dtype=np.uint8)
self.checksum(clear_nvm_buf, clear_nvm_buf[3])
ser.write(clear_nvm_buf)
#ser.close()
except Exception as e1:
print ("error communicating...: " + str(e1))
ser.close()
else:
print("cannot open serial port ")
sc = serial_communication()
print(sc.list_serial_ports())
sc.serial_open()
When i run the code i get:
['COM1', 'COM2', 'COM3']
Port OPENED
Initialising...
[170 0 0 8 9 50 0 0]
[170 0 0 8 9 50 0 0]
b'\xaa\x90\x00\x12\x01\x0c\x00'
Initialisation Complete
Communication Link Checking..
Link Check Complete
Instead of [170 0 0 8 9 50 0 0], i want the hex data.
Also, it is not returning radio_init_buf with checksum. The result after calling checksum is same.
Displaying in hex:
for n in radio_init_buf:
print("{:#x}".format(n), end='')
print()
{:#x} - a format string, #: adds the 0x prefix, x: presentation will be in hex,
In one line:
print(("{:#x} "*len(radio_init_buf)).format(*radio_init_buf))
It creates a string of length len(radio_init_buf).
In *radio_init_buf , '*' unpacks the list.

Adafruit ADC and Python AttributeErrors

I'm new to Python and currently working on a project on my Pi 3 mod b. I use an Adafruit ADC1015 to convert analogue signal. However, even if i have the code to get some volt measurments, i get an error of " AttributeError: 'int' object has no attribute 'readADCSingleEnded'".
To explain that, the python script i'm trying to run is the following:
#!/usr/bin/python
import time, signal, sys
from Adafruit_ADS1x15 import ADS1x15
def signal_handler(signal, frame):
print 'You pressed Ctrl+C!'
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
ADS1015 = 0x00
ADS1115 = 0x01
gain = 4096 # +/- 4.096V
sps = 250 # 250 samples per second
# Initialise the ADC using the default mode (use default I2C address)
# Set this to ADS1015 or ADS1115 depending on the ADC you are using!
adc = ADS1015(ic=ADS1015)
# Read channel 0 in single-ended mode using the settings above
volts=adc.readADCSingleEnded(0, gain, sps) / 1000
# To read channel 3 in single-ended mode, +/- 1.024V, 860 sps use:
# volts = adc.readADCSingleEnded(3, 1024, 860)
print "%.6f" % (volts)
The "ADS1x15" file we import contains the following code related to the error:
# Constructor
def __init__(self, address=0x48, ic=__IC_ADS1015, debug=False):
# Depending on if you have an old or a new Raspberry Pi, you
# may need to change the I2C bus. Older Pis use SMBus 0,
# whereas new Pis use SMBus 1. If you see an error like:
# 'Error accessing 0x48: Check your I2C address '
# change the SMBus number in the initializer below!
self.i2c = Adafruit_I2C(address)
self.address = address
self.debug = debug
# Make sure the IC specified is valid
if ((ic < self.__IC_ADS1015) | (ic > self.__IC_ADS1115)):
if (self.debug):
print "ADS1x15: Invalid IC specfied: %h" % ic
return -1
else:
self.ic = ic
# Set pga value, so that getLastConversionResult() can use it,
# any function that accepts a pga value must update this.
self.pga = 6144
def readADCSingleEnded(self, channel=0, pga=6144, sps=250):
"Gets a single-ended ADC reading from the specified channel in mV. \
The sample rate for this mode (single-shot) can be used to lower the noise \
(low sps) or to lower the power consumption (high sps) by duty cycling, \
see datasheet page 14 for more info. \
The pga must be given in mV, see page 13 for the supported values."
# With invalid channel return -1
if (channel > 3):
if (self.debug):
print "ADS1x15: Invalid channel specified: %d" % channel
return -1
# Disable comparator, Non-latching, Alert/Rdy active low
# traditional comparator, single-shot mode
config = self.__ADS1015_REG_CONFIG_CQUE_NONE | \
self.__ADS1015_REG_CONFIG_CLAT_NONLAT | \
self.__ADS1015_REG_CONFIG_CPOL_ACTVLOW | \
self.__ADS1015_REG_CONFIG_CMODE_TRAD | \
self.__ADS1015_REG_CONFIG_MODE_SINGLE
# Set sample per seconds, defaults to 250sps
# If sps is in the dictionary (defined in init) it returns the value of the constant
# othewise it returns the value for 250sps. This saves a lot of if/elif/else code!
if (self.ic == self.__IC_ADS1015):
config |= self.spsADS1015.setdefault(sps, self.__ADS1015_REG_CONFIG_DR_1600SPS)
else:
if ( (sps not in self.spsADS1115) & self.debug):
print "ADS1x15: Invalid pga specified: %d, using 6144mV" % sps
config |= self.spsADS1115.setdefault(sps, self.__ADS1115_REG_CONFIG_DR_250SPS)
# Set PGA/voltage range, defaults to +-6.144V
if ( (pga not in self.pgaADS1x15) & self.debug):
print "ADS1x15: Invalid pga specified: %d, using 6144mV" % sps
config |= self.pgaADS1x15.setdefault(pga, self.__ADS1015_REG_CONFIG_PGA_6_144V)
self.pga = pga
# Set the channel to be converted
if channel == 3:
config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_3
elif channel == 2:
config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_2
elif channel == 1:
config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_1
else:
config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_0
# Set 'start single-conversion' bit
config |= self.__ADS1015_REG_CONFIG_OS_SINGLE
# Write config register to the ADC
bytes = [(config >> 8) & 0xFF, config & 0xFF]
self.i2c.writeList(self.__ADS1015_REG_POINTER_CONFIG, bytes)
# Wait for the ADC conversion to complete
# The minimum delay depends on the sps: delay >= 1/sps
# We add 0.1ms to be sure
delay = 1.0/sps+0.0001
time.sleep(delay)
# Read the conversion results
result = self.i2c.readList(self.__ADS1015_REG_POINTER_CONVERT, 2)
if (self.ic == self.__IC_ADS1015):
# Shift right 4 bits for the 12-bit ADS1015 and convert to mV
return ( ((result[0] << 8) | (result[1] & 0xFF)) >> 4 )*pga/2048.0
else:
# Return a mV value for the ADS1115
# (Take signed values into account as well)
val = (result[0] << 8) | (result[1])
if val > 0x7FFF:
return (val - 0xFFFF)*pga/32768.0
else:
return ( (result[0] << 8) | (result[1]) )*pga/32768.0
I believed this would run smmothly, as it is a part something that is related to the ADC, but i haven't managed to solve this problem, even if i tried a lot.
Found it. Line
adc = ADS1015(ic=ADS1015)
Should be
adc = ADS1x15(ic=ADS1015)

Python - calculations with more than one splited serial data

I use Arduino to receive data from sensors (4 types of data : humidity, temperature, photocell and milliseconds)
Datas comes like this : xx xx xx xxxx in the serial buffer. (data space data space etc...)
I split this line in order to isolate each data because I want to make individual calculations for each sensor.
Calculation for each sensor consist on : ((latest_data) - (data_of_previous_line), latest_data) in order to get a tuple for each sensor. I want all the sensors tuples appearing in the same line.
Doing this with 1 sensor and 1 method (calculate()) is working fine but it doesn't work if I add a second sensor in sensors() object !
QUESTION : how to make all this working with at least 2 sensors data ?
(the code below is working perfectly with 1 "splited" sensor data).
Thanks in advance.
class _share:
def __init__(self):
self.last_val = [0 for i in range(2)]
def calculate(self, val):
self.last_data = val
self.last_val = [self.last_data] + self.last_val[:-1]
diff = reduce(operator.__sub__, self.last_val)
print (diff, val)
return (diff, val)
share = _share()
ser = serial.Serial('/dev/ttyS1', 9600, timeout=0.1)
def sensors():
while True:
try:
time.sleep(0.01)
ser.flushInput()
reception = ser.readline()
receptionsplit = reception.split()
sensor_milli = receptionsplit[3]
sensor_pho_1 = receptionsplit[2]
sensor_tem_1 = receptionsplit[1]
sensor_hum_1 = receptionsplit[0]
int_sensor_milli = int(sensor_milli)
int_sensor_pho_1 = int(sensor_pho_1)
int_sensor_tem_1 = int(sensor_tem_1)
int_sensor_hum_1 = int(sensor_hum_1)
a = int_sensor_milli
b = int_sensor_pho_1
c = int_sensor_tem_1
d = int_sensor_hum_1
return str(share.calculate(b))
except:
pass
time.sleep(0.1)
f = open('da.txt', 'ab')
while 1:
arduino_sensor = sensors()
f.write(arduino_sensor)
f.close()
f = open('da.txt', 'ab')
You need to use different share instance for each sensor otherwise the calculations will be wrong. So use share_a, share_b, share_c and share_d for a, b, c and d respectively for example. Now if I understand this correctly, you can return all the sensors at once by changing your return to:
return [ str(share_a.calculate(a)), str(share_b.calculate(b)), str(share_c.calculate(c)), str(share_d.calculate(d)) ]
The above would return a list containing all 4 sensors and then in your main method you can change to:
arduino_sensor = sensors()
sensor_string ="a:%s b:%s c:%s d:%s"%( arduino_sensor[0], arduino_sensor[1], arduino_sensor[2], arduino_sensor[3] )
print sensor_string # single line screen print of all sensor data
f.write( sensor_string )
I hope that is helpful.

Multiplex address and data to show string of letters over parallel port

A month ago, i asked this about multiplexing a string of numbers with 4 7-segment displays. But now, I'm trying to update the code to multiplex a string of letters using 7 7-segment displays in python.
This is the new circuit. When i send data using the parallel port, the Latch Enable receives the most significant bit (pin 9). In the second latch, the Latch Enable receives it also but negated, that is the reason of the 7404.
That is either address is set (/LE==False) or data is set (/LE=True).
This is what I'm trying to do. The 'X' represents that the 7-segment display is off. But can't archive it.
XXXXXXX
XXXXXXS
XXXXXST
XXXXSTA
XXXSTAC
XXSTACK
XSTACKX
STACKX0
TACKX0V
ACKX0V3
CKX0V3R
KX0V3RF
X0VERFL
0VERFL0
VERFL0W
ERFL0WX
RFL0WXX
FL0WXXX
L0WXXXX
0WXXXXX
WXXXXXX
XXXXXXX
That would be the output for the string "STACK 0V3RFL0W".
Also the past code:
import sys
import parallel
class Display(object):
def __init__(self):
'''Init and blank the "display".'''
self.display = [' '] * 4
self._update()
def setData(self,data):
'''Bits 0-3 are the "value".
Bits 4-7 are positions 0-3 (first-to-last).
'''
self.display = [' '] * 4
value = data & 0xF
if data & 0x10:
self.display[0] = str(value)
if data & 0x20:
self.display[1] = str(value)
if data & 0x40:
self.display[2] = str(value)
if data & 0x80:
self.display[3] = str(value)
self._update()
def _update(self):
'''Write over the same four terminal positions each time.'''
sys.stdout.write(''.join(self.display) + '\r')
if __name__ == '__main__':
p = Display()
pp=parallel.Parallel()
nums = raw_input("Enter a string of numbers: ")
# Shift over the steam four-at-a-time.
stream = 'XXXX' + nums + 'XXXX'
data = [0] * 4
for i in range(len(stream)-3):
# Precompute data
for pos in range(4):
value = stream[i+pos]
data[pos] = 0 if value == 'X' else (1<<(pos+4)) + int(value)
# "Flicker" the display...
for delay in xrange(1000):
# Display each position briefly.
for d in data:
pp.setData(d)
# Clear the display when done
p.setData(0)
Algorithm outline:
string = "07831505"
while True:
for i in range(7):
# switch display `i` on
notlatch.set(True)
data.set(1 << i)
notlatch.set(False)
time.sleep(<very little>)
notlatch.set(True)
# display character on display `i`
data.set(char_to_7segment(string[i]))
time.sleep(0.01)

Categories

Resources