Controlling MDrive 23 with Python under Linux - arduino

MDrive 23 motor takes commands from a terminal, and I got it to work with screen program:
screen /dev/ttyUSB0
Is this is called a serial terminal? I'm unfamiliar with the details of the connection, but feel like I should be able to use PySerial to send the commands.
I tried:
import serial
ser = serial.Serial('/dev/ttyUSB0', 19200)
ser.isOpen() # Returns True
ser.write('ma 100000\r\n') # Does nothing...
ser.inWaiting() # Returns 0
ser.close()
I didn't know how to set the other init variables, like:
parity = serial.PARITY_ODD,
stopbits = serial.STOPBITS_TWO
bytesize = serial.SEVENBITS
I'm going to try guessing some values next... The documentation is lame, but it mentions MODBUS TCP and Mcode.
How do I set these and are there any syntax errors in my snippet?
I know how to send arguments to the Serial object, but I do not know what values are typical.

The other parameters to the Serial constructor are set in a similar way as port and baudrate:
ser = serial.Serial(port = '/dev/ttyUSB0', baudrate=19200, bytesize=serial.SEVENBITS, parity=serial.PARITY_ODD, stopbits=serial.STOPBITS_TWO)
ser.write('whatever')
ser.flush() # wait for data to be written
ser.close()
Edit: It seems the default settings are 9600 baud, 8 bits, no parity and 1 stop bit. In addition no flow-control is used. That would be equivalent to:
ser = serial.Serial(port = '/dev/ttyUSB0', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, xonxoff=False, rtscts=False, dsrdtr=False)
As all values, except port, are set to their defaults, you may use:
ser = serial.Serial(port = '/dev/ttyUSB0')
The last thing to worry about is which (read) timeout to set. This is measured/set in seconds (float allowed) and sets how long a read() command will block before returning what has been read.

Related

RS232 Serial communication with PR4000 controller from MKS

I am trying to establish a serial connection via an RS232 port on the PR4000 controller from MKS. This controller is connected to a pressure gauge, and I try to read the pressure from my PC with the following script:
import time
import serial
import bitarray
ba = bitarray.bitarray()
# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
port='COM7',
baudrate=9600,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.SEVENBITS
)
#ser.isOpen()
print ('Enter your commands below.\r\nInsert "exit" to leave the application.')
data_in=0
while True :
data_in = input(">> ")
if data_in == 'exit':
ser.close()
break
else:
ser.write((data_in).encode('utf-8'))
out = ''
time.sleep(0.1)
while ser.inWaiting() > 0:
out = ser.read(ser.inWaiting()).decode('utf8')
if out != '':
print (out)
This code is inspired from this post :
Full examples of using pySerial package
you can find the doc of the controller here :
https://www.idealvac.com/files/manuals/PR4000_InstructionManual.pdf
The interface chapter start at page 43.
basically, the RS interface works with an requests and answers syntax.
example of answer :
RT,ON : set the remote on the controller.
?RT : ask for the state of the remote mode.
I managed to establish the connection with hyper terminal
But with python, I've tried to enter the commands and I can't have any answers, the serial buffer is empty.
Do you think the problem is in the format of the requests ?
Do you think the problem is in the format of the requests ?
A command to the device needs to be terminated with a carriage return character. Suggest you append a CR character (i.e. '\r') to data_in before it is sent.
Refer to the code that inspired your version for an example.

Raspberry pi - Arduino communication

I've designed a tachometer using an arduino setup and I get the output values(rpm), but since I don't have an wifi module, I've connected my arduino and raspberry pi 4 using usb. I can read the rpm value in the pi terminal. But now I need to send these data to an adafruit io page. How do I write the code to read the data from the usb port of my pi in real-time? I've written a script which can print it on the webpage but each time I've to write a value. It would be really helpful if i can get the answers. I'm new to coding and just exploring these.
from Adafruit_IO import*
ADAFRUIT_IO_USERNAME = '******'
ADAFRUIT_IO_KEY = '**********************'
aio = Client(ADAFRUIT_IO_USERNAME,ADAFRUIT_IO_KEY)
try:
test = aio.feeds('test')
except RequestError:
test_feed = Feed(name='test')
test_feed = aio.create_feed(test_feed)
val = 4
aio.send('test',val)
The below code is an example of what will work in Python, assuming your USB is connected at /dev/tty.usbmodem14201:
import serial
ser = serial.Serial('/dev/tty.usbmodem14201', baudrate=9600) # NB set your baudrate to the one you are using!
ser.flushInput()
while True: #constant loop to get readings in real time
ser_bytes = ser.readline() #read the incoming message
decoded_bytes = ser_bytes[0:len(ser_bytes)-2].decode("utf-8") #decode it
print(decoded_bytes) # print out what you got or, alternatively, make a web call to Adrafruit

Cannot set receiver phone number using AT+CMGS="XXXXXXXXX" returns error 325

I am using SIM808 to send SMS to a perticuar number. But when trying to set the number using AT+CMGS=XXXXXXX returns +CMS ERROR:325. I have set the AT+CSCS to GSM but still no luck.The following is the code:
import serial
import os, time
# Enable Serial Communication
port = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=1)
# Transmitting AT Commands to the Modem
# '\r\n' indicates the Enter key
port.write('AT'+'\r\n')
rcv = port.read(10)
print rcv
port.write('AT+CMGF=1\r\n')
time.sleep(10)
rcv = port.read(10)
print rcv
port.write('AT+CMGS=\'9912345678\'\r\n')
time.sleep(2)
port.write('test msg')
time.sleep(2)
port.write(chr(26))
rcv = port.read(10)
print rcv
port.flush()
SIM808 expects that AT+CMGS command should enclose the mobile/cell number in double quotes. You have provided escape sequence for single quote.
Your code should be :
port.write("AT+CMGS=\"9912345678\"\r\n")
instead of
port.write('AT+CMGS=\'9912345678\'\r\n')
Because you are providing single quotes escape sequence you get +CMS ERROR:325 error.
While providing mobile/cell number it is an good practice to include country code (in your case +91).

Write and read from a serial port

I am using the following python script to write AT+CSQ on serial port ttyUSB1.
But I cannot read anything.
However, when I fire AT+CSQ on minicom, I get the required results.
What may be the issue with this script?
Logs:
Manual Script
root#imx6slzbha:~# python se.py
Serial is open
Serial is open in try block also
write data: AT+CSQ
read data:
read data:
read data:
read data:
Logs:
Minicom console
1. ate
OK
2. at+csq
+CSQ: 20,99
3. at+csq=?
OKSQ: (0-31,99),(99)
How can I receive these results in the following python script?
import serial, time
#initialization and open the port
#possible timeout values:
# 1. None: wait forever, block call
# 2. 0: non-blocking mode, return immediately
# 3. x, x is bigger than 0, float allowed, timeout block call
ser = serial.Serial()
ser.port = "/dev/ttyUSB1"
ser.baudrate = 115200
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
ser.timeout = None #block read
#ser.timeout = 0 #non-block read
ser.timeout = 3 #timeout block read
ser.xonxoff = False #disable software flow control
ser.rtscts = False #disable hardware (RTS/CTS) flow control
ser.dsrdtr = False #disable hardware (DSR/DTR) flow control
ser.writeTimeout = 2 #timeout for write
try:
ser.open()
print("Serial is open")
except Exception, e:
print "error open serial port: " + str(e)
exit()
if ser.isOpen():
try:
print("Serial is open in try block also")
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
ser.write("AT+CSQ")
time.sleep(1)
# ser.write("AT+CSQ=?x0D")
print("write data: AT+CSQ")
# print("write data: AT+CSQ=?x0D")
time.sleep(2) #give the serial port sometime to receive the data
numOfLines = 1
while True:
response = ser.readline()
print("read data: " + response)
numOfLines = numOfLines + 1
if (numOfLines >= 5):
break
ser.close()
except Exception, e1:
print "error communicating...: " + str(e1)
else:
print "cannot open serial port "
You have two very fundamental flaws in your AT command handling:
time.sleep(1)
and
if (numOfLines >= 5):
How bad are they? Nothing will ever work until you fix those, and by that I mean completely change the way you send and receive command and responses.
Sending AT commands to a modem is a communication protocol like any other protocols, where certain parts and behaviours are required and not optional. Just like you would not write a HTTP client that completely ignores the responses it gets back from the HTTP server, you must never write a program that sends AT commands to a modem and completely ignores the responses the modem sends back.
AT commands are a link layer protocol, with with a window size of 1 - one. Therefore after sending a command line, the sender MUST wait until has received a response from the modem that it is finished with processing the command line, and that kind of response is called Final result code.
If the modem uses 70ms before it responds with a final result code you have to wait at least 70ms before continuing, if it uses 4 seconds you have to wait at least 4 seconds before continuing, if it uses several minutes (and yes, there exists AT commands that can take minutes to complete) you have to wait for several minutes. If the modem has not responded in an hour, your only options are 1) continue waiting, 2) just give up or 3) disconnect, reconnect and start all over again.
This is why sleep is such a horrible approach that in the very best case is a time wasting ticking bomb. It is as useful as kicking dogs that stand in your way in order to get them to move. Yes it might actually work some times, but at some point you will be sorry for taking that approach...
And regarding numOfLines there is no way anyone in advance can know exactly how many lines a modem will respond with. What if your modem just responds with a single line with the ERROR final result code? The code will deadlock.
So this line number counting has to go completely away, and instead your code should be sending a command line and then wait for the final result code by reading and parsing the response lines from the modem.
But before diving too deep into that answer, start by reading the V.250 specification, at least all of chapter 5. This is the standard that defines the basics of AT command, and will for instance teach you the difference between a command and a command line. And how to correctly terminate a command line which you are not doing, so the modem will never start processing the commands you send.

Re. pcm3002 configured for 16 bit data transfers

I am trying to do a loopback program (get data in, and send it out
without any processing) on a 5416 DSK. I am using the on board
PCM3002 codec and it is configured for 16-bit data transfer. I also
have McBSP2 configured for 16-bit receive/transfer. The following are
the register values for McBSP2 and PCM3002 codec,
McBSP2 registers:
SPCR1 = 0x2020 (also tried SPCR1 = 0x2000)
SPCR2 = 0x0000
RCR1 = 0x0040
RCR2 = 0x0041
XCR1 = 0x0040
XCR2 = 0x0040 (also tried XCR2 = 0x0041, and 0x0042)
PCR = 0x000C
PCM3002 registers:
Register0 = 0x01FF
Register1 = 0x03FF
Register2 = 0x0482
Register3 = 0x0600
The CPLD codec clock register is configured for a 24 KHz
sampling rate. I don't need to configure SRGR because the CPLD on
board provides the frame sync signal. I am sure that rest of my
configuration is correct, because I am able configure PCM3002
McBSP2 for a 20-bit transfer/receive loopback program and it works
fine. Can somebody please tell me what is wrong here? Any help will
be appreciated.

Resources