pyserial code working on Windows (COM1) but not on Linux (/dev/ttyS0) - centos6

I am using python 3.6.
The following code works just fine on Windows 10 Pro:
import serial
import binascii
ser = serial.Serial("COM1") # "COM1" will be "/dev/ttyS0" on Linux
if ser.is_open == True:
print("COM open")
ser.baudrate = 2400
print('Port configuration:')
print('baudrate:',ser.baudrate)
print('parity:',ser.parity)
print('stopbits:',ser.stopbits)
print('bytesize:',ser.bytesize)
print('xonxoff:',ser.xonxoff)
print('timeout:',ser.timeout)
print()
print('sending...')
frame = bytearray()
frame.append(0x7e)
frame.append(0x03)
frame.append(0x02)
frame.append(0x21)
frame.append(0x00)
frame.append(0xa4)
ser.write(frame)
print(binascii.hexlify(frame))
print()
print('receiving...')
recv = ser.readline()
recv_len = len(recv)
print(binascii.hexlify(recv))
print()
ser.close()
if ser.is_open == False:
print("COM closed")
But it gets stuck at 'ser.readline()' when I run it under CentOS 6.8, as there was no cable attached to the port.
It looks like a trivial issue, but I cannot figure out what's wrong or missing.
If you cannot either, I hope the sample code can result useful to someone at least.

False problem. The code worked using ttyS1 instead of ttyS0 (I knew it was something trivial).
Anyway, very useful to check
cat /proc/tty/driver/serial
which shows tx/rx statistics and parameters as DTS, RTS, RI, etc. next to each port.
For example, next to the ttyS1 I noticed an 'RI' which was the same parameter that Hercules terminal on Windows showed me (graphically) when I tried to open COM1. Very intuitive to identify a serial port this way!

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.

data sending from jetson to arduino

It was successful to train from jet son-XAVIER and recognize it as cam. But I don't know how to send the information that jet son-XAVIER recognized in real time to Arduino. The objects we recognize are elk and wild boar. I know that I can only send 1 letter through communication, so elk will send e and wild boar to w. Is there a way to send it as soon as it recognizes it through real-time web cam?
There's not a lot of information here on your setup, but here's a possible solution:
I see the NVIDIA Jetson AGX Xavier module has USB-C ports.
Buy a USB-A to USB-C cable, and plug the Arduino directly in.
I'm not sure what program/language you're using with your trained model, but I'll guess that it's python for now.
You'll want to open a Serial connection to the arduino, and you can do this with pyserial:
https://pypi.org/project/pyserial/
You can send more than just one letter, you can send entire data streams. But, if you want to just send one letter, it will do that as well.
Here's the official documentation for how to communicate with an Arduino using Python:
https://create.arduino.cc/projecthub/ansh2919/serial-communication-between-python-and-arduino-e7cce0
If you're not using python, specify your language of choice, and we can look up and see if it has a serial library.
I have never used darknet but may be this can point you in the right direction.
I have used the library sugested by Bucky and I believe you could add the serial comunication to darknet.py. This is what I would do:
#Add this import at begining of the file darknet.py
import serial
#########################################################
#this is a mocked version of detect in darknet.py, assuming that the labels you used are "elk" and "wildboard". You should not add this lines to the file.
def detect():
res = []
res.append(("elk",0.98,(2,2,50,50)))
res.append(("wildboard",0.98,(2,2,50,50)))
return res
r = detect()
##########################################################
#Add this after the 'print r' at the end of the file darknet.py
ser = serial.Serial('/dev/ttyUSB0') # open serial port. You should check what serial port is assigned to your arduino.
for obj in r:
if obj[0]=="elk" and obj[1]>=0.9: #assuming 0.9 as the minimum confident for a detection
print "found elk"
ser.write('e') # you can send a string with just one letter
elif obj[0]=="wildboard" and obj[1]>=0.9:
print "found wildboard";
ser.write('w') # you can send a string with just one letter
ser.close() # close port

replicate Arduino's serial monitor on Scilab consol

If I use the Arduino IDE's Serial monitor I can read the pair of comma separated values as below:
I want to first replicate this behavior in SciLab terminal. I used the Serial Communication Toolbox:
h = openserial(7, "9600,n,8,1") // open COM7
disp(readserial(h))
closeserial(h)
which returns either empty or
, 169
228, 179
228,
228, 205
228, 209 228,
putting the disp(readserial(h)) in a while loop also doesn't help. Not only there are too many empty lines, if I stop the while loop it does not close the port (something like try-catch should be used I think). I would appreciate if you could help me know how I could get the same behavior as Arduino's serial monitor?
P.S. Next I want to plot these two values in realtime. So maybe using the csvTextScan function to split the string into two integers.
OK, after a couple of days struggling I figured this out. It turns out that SciLab doesn't have native serial communication functionality and the Toolbox developer has used TCL_EvalStr to run Tcl commands externally. I had to dig into the Tcl serial communication syntax (i.e. read, open, gets, fconfigure ... ), ask another question, get some help and then finally end up with a new function for the Toolbox which I have committed as a pull request:
function buf = readserialline(h)
tmpbuf = emptystr();
while tmpbuf == emptystr()
TCL_EvalStr("gets " + h + " ttybuf");
tmpbuf = TCL_GetVar("ttybuf");
end
buf = tmpbuf;
endfunction
now one can get the above behavior by running:
h = openserial(7, "9600,n,8,1") // open COM7
for ii = 1:40
disp(readserialline(h))
end
closeserial(h)
to read the serial port line by line and print it to the SciLab console. Now to parse the CSV data you may use:
csvTextScan(part(readserialline(h), 1:$-1), ',')
P.S.1. I have used a virtual Arduino board inside SimulIDE and used com0com to create virtual serial ports. More information here on SourceForge.
P.S.2. More discussion with Toolbox developer Aditya Sengupta here on Twitter.
P.S.3. More discussions here on Tcl Google group
P.S.4. A full demonstration plus instructions here on Reddit
P.S.5. For those who might end up here, I have decided to rewrite Aditya Sengupta's repository here with several improvements.

Gstreamer automation in STB (Set Top Box)

mates,I have a set top box which I am communicating through serial port.This box has Gstreamer media frame-work(linux platform and C language).
I am trying to automate Gstreamer i.e gst-launch,gst-inspect....there are also other frame work like Qt which I want to automate.
Following are my attempts toward this problems :
Attempt 1:
Tried using Pyserial and was successful toward working of it,but by using Pyserial I was able to access my port and communicate to my board,but I found no way to automate things.
import serial
import time
port = "COM1"
baud = 115200
ser = serial.Serial(port, baud,xonxoff=False, rtscts=False, dsrdtr=False,timeout=None)
ser.flushInput()
ser.flushOutput()
if ser.isOpen():
print(ser.name + ' is open...')
while True :
cmd = input("Enter command or 'exit':")
if cmd == 'exit':
ser.close()
exit()
else:
ser.write(cmd.encode() + b'\r\n' )
bytesToRead = ser.inWaiting()
out=ser.read(bytesToRead)
print(out.decode(),sep='')
Attempt 2 :
To have a communicator install in my board which can communicate to my box.
If this is correct ,I have no Idea how to proceed with this.
Any help toward STB automation will be greatly appreciated.

How to Read Data from Serial Port in R

I'm wanting to plot live data from the serial port. I figured R would be a good tool for the job. I'm stumbling on trying to read data from the serial port (COM4). I've verified the data is coming in through terra term (and close the session before trying R), but I can't seem to get anything in R.
I've checked a few places, including these threads:
How to invoke script that uses scan() on Windows?
How to include interactive input in script to be run from the command line
I've also found this old thread on the R forum:
https://stat.ethz.ch/pipermail/r-help/2005-September/078929.html
These have gotten me this far, but I can't seem to actually get any data into R from the serial port.
At this point I can stream in the data in excel using VBA, but I'd like to do it in R for some nicer live plotting and filtering of the data.
Edit: Thanks for the help so far. I just got it working while writing up this edit, so here's the code:
#
# Reset environment
#
rm(list = ls()) # Remove environemnent variables
graphics.off() # Close any open graphics
#
# Libraries
#
library(serial)
#
# Script
#
con <- serialConnection(name = "test_con",
port = "COM11",
mode = "115200,n,8,1",
buffering = "none",
newline = 1,
translation = "cr")
open(con)
stopTime <- Sys.time() + 2
foo <- ""
textSize <- 0
while(Sys.time() < stopTime)
{
newText <- read.serialConnection(con)
if(0 < nchar(newText))
{
foo <- paste(foo, newText)
}
}
cat("\r\n", foo, "\r\n")
close(con)
foo ends up being a long string with new lines the way I want them:
3181, -53120, -15296, 2,
3211, -53088, -15328, 2,
3241, -53248, -15456, 1,
3271, -53216, -15424, 2,
3301, -53184, -15488, 2,
3331, -53344, -15360, 1,
3361, -53440, -15264, 1,
Thanks again for all the help!
i am working with the serial-package (here) available on CRAN. This was developed to do exactly that what you need. Reading and sending data form and to RS232 etc. connections.
I do really recommend this, because "mode.exe" seems not to work for virtual COM-ports. See NPort-Server etc.
Teraterm and Windows use a different mechanism to configure serial devices.
Are your system connection settings ok compared to what is configured in teraterm?
Re-check the configuration parameter in teraterm and then use them to set your COM4: configuration in R.
system("mode COM4: BAUD=115200 PARITY=N DATA=8 STOP=1")
see mode /? on your command prompt for further parameters
it might also be helpful to read data character by character using readChar()
It sometimes happens that teraterm doesn't close RS232 connections properly.
I realize that this is from five years ago but I found that in your code you do not have a handshake called.
I am working with something similar where I use PUTTY instead of teraterm, where I could see all of the following inputs for my COM device.
my command is as follow:
con <-serialConnection(name="Prolific USB-to-Serial Comm Port(Com3)",
port="COM3",
mode="9600,n,8,1",
newline=0,
translation="lf",
handshake = 'xonxoff'
)

Resources