Can't read data from OBD2 serial port connection on Raspberry Pi - raspberry-pi

I'm currently working on a raspberry pi project for school where I read data from an OBD2 to usb censor in my car.
When I'm using Screen to connect to the serial port everything works fine, but when I try to do it in python the serial.readline() returns an empty string.
Does anybody know how I can retrieve data from the serial port in python?
I've tried about every option available.
import serial
ser = 0
#Function to Initialize the Serial Port
def init_serial():
global ser
ser = serial.Serial()
ser.baudrate = 38400
ser.port = '/dev/ttyUSB0'
ser.timeout = 1
ser.open() #Opens SerialPort
# print port open or closed
if ser.isOpen():
print 'Open: ' + ser.portstr
#Function Ends Here
init_serial()
temp = raw_input('Type what you want to send, hit enter:\r\n')
ser.write(temp) #Writes to the SerialPort
while 1:
bytes = ser.readline() #Read from Serial Port
print bytes #Print What is Read from Port

You may not be sending valid data to get a response. I believe the ODB2 interface uses the AT command set. Sending AT\n may be a good starting point.
I'm using a Bluetooth ODB2 interface and found that the serial baudrate was fixed. Using any other baudrate failed to correctly get data.
I recommend testing from putty or other terminal that supports serial ports, until you get the device to respond correctly. Then use valid settings to troubleshoot your code.

You're not sending a \r\n with your command, ELM327 requires a new line character at the end of a command.

Related

OSError micropython

I get OSError on esp8266. First request is successful but second and more are failed with OSError, I dont know why. Can you help me?
Edit: I solved it. I wrote the solution at the end of the codes.
import network
name, password="wifiname", "passwordd"
wlan = network.WLAN(network.STA_IF)
wlan.active(True) # activate the interface
wlan.scan() # scan for access points
wlan.isconnected() # check if the station is connected to an AP
wlan.connect(name, password) # connect to an AP
wlan.config('mac') # get the interface's MAC address
wlan.ifconfig() # get the interface's IP/netmask/gw/DNS addresses
ap = network.WLAN(network.AP_IF) # create access-point interface
ap.active(True) # activate the interface
ap.config(essid='ESP-AP') # set the ESSID of the access point
print('Wifi connected! My IP:', wlan.ifconfig()[0])
import urequests
import time
while 1:
try:
t1=time.time()
r=urequests.get('https://saitamatechnoo.web.app/')
t2=time.time()
print(r.status_code, 'Time:', t2-t1)
except OSError:
print('error')
Guys, I solved it. It works with socket and we should close every socket after using it.
For example:
r=urequests.get('https://saitamatechnoo.web.app/')
print(r.status_code)
r.close()

Can I transmit serial data only using a data cable via Raspberry pi 0 w's USB port?

I have been recently trying to find out a way whether I can send serial data (large file like image data) only through the Rpi w 0's micro USB port using ttyGS0. But when I searched online I only found ways of setting up headless through serial and other stuff which was no what I wanted. But I did follow the tutorial half way
I went to '/boot/config.txt' and set 'dtoverlay=dwc2' at the end of the file after leaving a line
I went to '/boot/cmdline.txt' and did put 'modules-load=dwc2,g_serial' after 'rootwait' leaving a space
Thinking I could just use the /dev/ttyGS0 in my serial program on the Rpi and send the data the data was being sent but on my PC when I tried to access my Rpi which was on comport 12 it said port not found and couldn't open it. But it was showing up in the device manager as 'PI USB to Serial(COM12)'
Then I wondered whether it would be possible at all to access Rpi's com port this way.
If that's the case, I want to know if there is any other way to access the Rpi's USB port only using the USB cable
Note
I don't want to use Rpi's USB as a way of logging ie. 'headless setup'. I just want to receive serial data like an Arduino.
I don't want to use the GPIO pins (I tried) as they can only send limited characters at a time and I want to send an image file. Very quickly.
I don't have any serial converters at hand so i could route it to the arduino and use /dev/ttyUSB0
then read it on PC. I just only want to use the USB cable.
In case this info is required:-
my pc is a probook 6560b running windows 7
things i found while testing and stuff:-
I did do -lsusb command but i dint find my device on that list
I tried the 'ls /dev/ttyGS0' and i found '/dev/ttyGS0'
I checked many forums and some guys were asiking to use this command 'dmesg | grep tty'and show them the code . So i performed it i dont understand what alot in the piece of text means but if it would be helpfull i pasted it here:-
pi#aloypi:~ $ dmesg | grep tty
[ 0.000000] Kernel command line: coherent_pool=1M 8250.nr_uarts=1 snd_bcm2835.enable_compat_alsa=0 snd_bcm2835.enable_hdmi=1 bcm2708_fb.fbwidth=1366 bcm2708_fb.fbheight=768 bcm2708_fb.fbswap=1 smsc95xx.macaddr=B8:27:EB:6D:50:77 vc_mem.mem_base=0x1ec00000 vc_mem.mem_size=0x20000000 console=tty1 root=PARTUUID=4ab8bcad-02 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait modules-load=dwc2,g_serial
[ 0.001496] printk: console [tty1] enabled
[ 2.543414] 20201000.serial: ttyAMA0 at MMIO 0x20201000 (irq = 81, base_baud = 0) is a PL011 rev2
[ 2.561791] 20215040.serial: ttyS0 at MMIO 0x20215040 (irq = 53, base_baud = 50000000) is a 16550
[ 6.716694] systemd[1]: Created slice system-getty.slice.
i also tried this one 'dmesg | grep dwc2' out of curiosity and got this but i cant say anything judging it so ya
pi#aloypi:~ $ dmesg | grep dwc2
[ 0.000000] Kernel command line: coherent_pool=1M 8250.nr_uarts=1 snd_bcm2835.enable_compat_alsa=0 snd_bcm2835.enable_hdmi=1 bcm2708_fb.fbwidth=1366 bcm2708_fb.fbheight=768 bcm2708_fb.fbswap=1 smsc95xx.macaddr=B8:27:EB:6D:50:77 vc_mem.mem_base=0x1ec00000 vc_mem.mem_size=0x20000000 console=tty1 root=PARTUUID=4ab8bcad-02 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait modules-load=dwc2,g_serial
[ 2.379190] dwc_otg: version 3.00a 10-AUG-2012 (platform bus)
[ 2.386185] dwc_otg: FIQ enabled
[ 2.386205] dwc_otg: NAK holdoff enabled
[ 2.386219] dwc_otg: FIQ split-transaction FSM enabled
[ 2.386245] Module dwc_common_port init
[ 2.968203] modules-load=dwc2,g_serial
[ 8.344134] dwc2 20980000.usb: supply vusb_d not found, using dummy regulator
[ 8.367130] dwc2 20980000.usb: supply vusb_a not found, using dummy regulator
[ 8.626751] dwc2 20980000.usb: EPs: 8, dedicated fifos, 4080 entries in SPRAM
[ 8.647109] dwc2 20980000.usb: DWC OTG Controller
[ 8.653810] dwc2 20980000.usb: new USB bus registered, assigned bus number 1
[ 8.726672] dwc2 20980000.usb: irq 33, io mem 0x20980000
[ 8.787097] usb usb1: Manufacturer: Linux 5.10.17+ dwc2_hsotg
[ 9.371395] dwc2 20980000.usb: bound driver g_serial
[ 194.158373] dwc2 20980000.usb: new device is high-speed
[ 194.189677] dwc2 20980000.usb: new device is high-speed
[ 194.225164] dwc2 20980000.usb: new address 3
Ok looks like i made some progress
till now I did this
I went to '/boot/config.txt' and set 'dtoverlay=dwc2' at the end of the file after leaving a line
I went to '/boot/cmdline.txt' and did put 'modules-load=dwc2,g_serial' after 'rootwait' leaving a space
I did this 'sudo nano /etc/rc.local' and placed 'modeprobe g_serial use_acm=0' before 'exit 0'
Then i performed this command 'sudo systemctl stop getty#ttyGS0.service'
and then this 'sudo systemctl disable getty#ttyGS0.service'
(i think disabling getty#ttyGS0.service and puting 'modeprobe g_serial use_acm=0' in the folder metioned above allowed rpi and pc to comunicate but then again i can be wrong )
then perfored a 'sudo reboot'
this seemed to solve my problem
but i have one more problem now
whatever is sent from the rpi i can only recieve in the coolterm serial port reading software
i cant seem to use read the port from processing for some reason
(im using processing to later read the image file being sent)
here is my current serial reading program in processing
import processing.serial.*;
Serial myPort; // Create object from Serial class
String val; // Data received from the serial port
void setup()
{
myPort = new Serial(this, "COM13", 115200);
}
void draw()
{
if ( myPort.available() > 0)
{ // If data is available,
val = myPort.readStringUntil('\n'); // read it and store it in val
}
if (val!=null)
{
println(val); //print it out in the console
}
}
i kinda am stuck here :P
EDIT
welp nevermind i solved it
i finally finally got it working yaaaaaaaayyy
OK now remember all who seek for the answer when using /dev/ttyGS0 it uses the CTS and RTS protocall
(now idk if it can be disabled but please lemme know you guys)
Its like the pi asks your pc wether it is cleared to send the data and when the pc says yeah ok send the data the pi sends it
so whenever your using this method please enable rts or cts
this is what i used in processing to recieve the data
import processing.serial.*;
Serial myPort;
void setup()
{
//remember to set the COM port to which your pi is set
size(200, 200);
myPort = new Serial(this, "COM13", 115200);
}
void draw()
{
if ( myPort.available() > 0)
{
if(myPort.getCTS()==true){
myPort.setRTS(true);
print(myPort.read());
}
}
}
i hope this is of loadsa help to you guys but if there is some correction needed please lemme know yall:D
thanks

In QT how can I detect when a USB port switches from serial mode to DFU when connected to an STM32

I have a Qt5.12.4 MinGw64 app where I want to catch a USB event. In Windows 10 the MS driver for STM/USB emits error messages and I can use that as a trigger. Inelegant but it works, until I try to run it in a Win7-8.1 app where the driver is a third party STM driver with a VCP wrapper. I am thinking I need to adopt libusb to try and catch the ports change of state, but I am at a loss as how to proceed. I can see the port info in Device Manager, I just dont know how to get to it. Some of the questions going through my head....
1) Can I just make an OS call to read the port info? (if so, how?)
2) Can libusb and QSerialport co-exist on the same port?
3) What calls to LibUSB1.0 do I make to query the port status?
4) Is there a Windows cli utility like lsusb (wmic??) where I could scrape the data?
5) Which solution is likely to be the best cross platform solution?
I am using this trigger to start dfuse as a process that does a firmware update automatically on my STM board.
I have looked over the libusb1.0 docs but I do not understand just how I can use it. If that is correct solution, an example of how to query the Com port data and state would be most appreciated.
I tried using qDebug() to print out all of the serialportInfo data, while in serial or DFU state, but there is nothing there that is useful that I can use as a trigger.
USB serial mode = Serial port info is: ("COM3", "USB Serial Device", "Microsoft", "00000000001A", "\\.\COM3", "483", "5740", "1", " no data", "1")
USB DFU mode = Serial port info is: ("COM3", "N/A", "N/A", "N/A", "\\.\COM3", "N/A", "N/A", "no data", " no data", "no data")
I need some direction as to how to grab this port info so I dont really have any code that matters, but I am including an excerpt of my working process function.
This code works just fine to actually perform the firmware load. I just need a way to actually trigger it from a USB port change of state
void updateDevice_Dialog::update_firmware(QString fileName)
{
qDebug() << "Updating firmware: " << fileName ;
QDir dir;
ui->progress_label->setText("Preparing to update Firmware .....");
if(dir.setCurrent(QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation)+"/firmware"))
{
QSettings settings;
QString comPort = settings.value("USBPort").toString();
ui->progress_label->setText("Setting port to: "+comPort+" and starting download .....");
ui->avr_progressBar->setValue(0);
ui->avr_progressBar->setRange(0,100);
ui->avr_progressBar->setHidden(false);
progress_steps = 0; //reset avrProcess line output counter;
qDebug() << "Starting process for stm-dfu on serial port: " << comPort;
connect(avr_Process,SIGNAL(error(QProcess::ProcessError)),this,SLOT(process_error(QProcess::ProcessError)));
connect(avr_Process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(process_finished(int,QProcess::ExitStatus)));
connect(avr_Process,SIGNAL(readyReadStandardOutput()),this,SLOT(process_readLine()));
connect(avr_Process,SIGNAL(errorOccurred(QProcess::ProcessError)),avr_Process,SLOT(kill()));
connect(avr_Process,SIGNAL(error(QProcess::ProcessError)),ui->avr_progressBar,SLOT(close()));
QString dfu_command = "\""+QCoreApplication::applicationDirPath()+"/Tools/\"dfusecommand -c -d --v --fn "
"\""+QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation)+"/firmware/\""+fileName;
qDebug().noquote() << "dfu command string is: "<< dfu_command << " Current dir is: " << dir.currentPath();
avr_Process->start(dfu_command);
avr_Process->waitForFinished(20000);
}
}
From the perspective of the host system, rebooting the microcontroller into DFU will look like the original device was disconnected, and a completely different device was plugged in shortly afterwards.
If you need to watch for this, set up a libusb hotplug callback so that you'll be notified when the DFU device is attached.

Connecting Raspberry Pi to Unity via Bluetooth

I want to connect my Raspberry Pi to unity via Bluetooth (I am writing an app that in the future will use the phone to connect to the Pi via Bluetooth).
How do I do that ? I was not able to find the answer on SO or anywhere else.
How do I transfer data via Bluetooth ?
How do I do that ? I was not able to find the answer on SO or anywhere else.
I googled it and found this
How do I transfer data via Bluetooth ?
This might help link
Or you could write a python script similar to this
# Uses Bluez for Linux
#
# sudo apt-get install bluez python-bluez
#
# Taken from: https://people.csail.mit.edu/albert/bluez-intro/x232.html
# Taken from: https://people.csail.mit.edu/albert/bluez-intro/c212.html
import bluetooth
def receiveMessages():
server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
port = 1
server_sock.bind(("",port))
server_sock.listen(1)
client_sock,address = server_sock.accept()
print "Accepted connection from " + str(address)
while True:
data = client_sock.recv(1024)
print "received [%s]" % data
#client_sock.close()
#server_sock.close()
def sendMessageTo(targetBluetoothMacAddress):
port = 1
sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
sock.connect((targetBluetoothMacAddress, port))
sock.send("hello!!")
sock.close()
def lookUpNearbyBluetoothDevices():
nearby_devices = bluetooth.discover_devices()
for bdaddr in nearby_devices:
print str(bluetooth.lookup_name( bdaddr )) + " [" + str(bdaddr) + "]"
lookUpNearbyBluetoothDevices()
receiveMessages()
Code Description: It looks up for available Bluetooth devices and receives messages from the first Bluetooth device which initiates the connection. It sends messages to target Bluetooth device as per mac address specified in function arguments.
Reference: Link

Arduino doesn't listen to data sent via virtual serial port until Serial Monitor has been opened

I have a BotBoarduino (a Duemilanove with a few extras) that I'm trying to communicate with using a Perl script. If I open the Serial Monitor from the Arduino IDE, I can send and receive data without a problem. Following this, my Perl script can communicate without any problems. However, if the Arduino is disconnected then reconnected to the PC, the Arduino doesn't seem to listen to commands sent from my Perl script until Serial Monitor is opened again.
I also tried using PuTTY to communicate with the Arduino, and this works the same way as Serial Monitor from the Arduino IDE - the Arduino doesn't listen to my Perl script until the connection has been opened once.
Here is a sample of the way I'm communicating with the Arduino using Perl:
#!perl -w
use Win32::SerialPort;
my $PortName = "COM4";
my $sendData = "c";
### SERIAL PORT SETUP ###
my $PortObj = new Win32::SerialPort($PortName) or die "Can't open $PortName: $^E\n";
$PortObj->baudrate(115200);
$PortObj->parity("none");
$PortObj->databits(8);
$PortObj->stopbits(1);
#$PortObj->dtr_active(1);
#$PortObj->rts_active(0);
#$PortObj->handshake("xoff");
$PortObj->lookclear();
$PortObj->write($sendData);
$PortObj->close();
I have commented out the dtr_active, rts_active and handshake bits. I played around with these settings as they were mentioned as possible culprits somewhere.
Also, I have used a 120 Ohm resistor to stop the Arduino from auto-resetting as described here.
Does anyone have any suggestions for the settings needed to get the Arduino to listen to my Perl program without having to open PuTTY/Serial Monitor first?
Turns out I wasn't saving the serial port settings, as described in a thread on the Arduino Forum. Adding $PortObj->write_settings(); after setting the serial port parameters got rid of the problem. My final Perl code that worked was:
#!perl -w
use Win32::SerialPort;
use strict;
use warnings;
$| = 1; #enable autoflush
my $PortName = "COM4";
my $sendData = "o";
### SERIAL PORT SETUP ###
my $PortObj = new Win32::SerialPort($PortName) or die "Can't open $PortName: $^E\n";
$PortObj->baudrate(57600);
$PortObj->parity("none");
$PortObj->databits(8);
$PortObj->stopbits(1);
$PortObj->write_settings(); #very important!
$PortObj->write($sendData);
$PortObj->close() || warn "\nClose failed\n";