How to send serial signal with Python? [duplicate] - python

This question already has answers here:
Directly send signals to USB using Python
(2 answers)
Closed 10 months ago.
I am trying to create a USB device that vibrates whenever a key is pressed on the computer it is connected to. I have a working Python script that detects key presses, but I need it to send a signal to a USB device (which hasn’t been made yet). How would I go about this?

This may help a little bit: Directly send signals to USB using Python
To minimize what might be helfup:
Controlling components like LEDs from devices like Arduino and Raspberry Pi are done using GPIO pins. In contrast, USB is designed for data transfer and not for maintaining more constant high or low signals like GPIO. It also consumes different voltage and current levels than GPIO pins and could potentially damage components meant for GPIO.
However, you can get USB to GPIO adapters for this purpose (see here for an example discussion on these options).
In terms of Python, you can use packages such as PyUSB or the libusb Python wrapper to control/transfer data/communicate with USB devices (such as the USB to GPIO adapters). The companies providing the adapters might also have designed their own easy-to-use Python package to wrap around a lower-level driver (probably written in C). See this USB controlled LED device as an example with its own Python driver. The drivers are just software programs that take in relatively simple commands from the user for what they want a device to do. They then encapsulate the lower-level complexities required for following a protocol to communicate the user's intention to the USB device and controlling the USB port at the lowest possible software level.

Using pyserial you can read from a serial device and also write to it.
import serial
ser = serial.Serial('/dev/ttyUSB0') # open serial port
ser.write(b'hello') # this would depend on the protocol for the USB device
ser.close() # close port

Related

How to program a atMega328p MCU with a Raspberry Pi 4 (Python)

I been looking everywhere online for this exact configuration but can't find much.
I want to program my AtMega328p MCU (its on a breadboard) using Python from my Raspberry Pi 4 but I am not sure how to check if communication is going on between them? I have the MISO, MOSI, SCLK, and CE0 pins from the Pi connected to the MISO, MOSI, SCK, SS pins on the AtMega328p respectively.
I understand I have to use SPI communication, however how can I exactly send data from the Raspberry Pi to the MCU to ensure there is communication between the two? Maybe some code to send to the MCU and receive it back? I been using the SPI Dev Python libraries but can't find much info on it. Thank you in advance!!
To load code onto the AVR (program it), you want to use existing software like avrdude that already speaks the AVR ISP protocol. avrdude already has support for using the RPi SPI headers - just use the linuxspi programmer type.
Here's an article by the author that explains it (although there are probably more recent articles if you search around) http://kevincuzner.com/2013/05/27/raspberry-pi-as-an-avr-programmer/
Is there a reason you want to do this from Python specifically? Or are you referring to communicating between the uC firmware and some Python code on the Pi?

Running functions on bluetooth pair request

I've recently been learning electric circuitry using arduino and am looking to implement some changes to my Raspberry Pi application.
I used this outdated tutorial a few years ago to create my pi bluetooth receiver which is working well at the moment (https://www.instructables.com/id/Turn-your-Raspberry-Pi-into-a-Portable-Bluetooth-A/) but one downfall of this out-dated tutorial is that bluetooth connections have to be accepted via the screen (which is off because bluetooth speakers do not have screens).
My plan: use a button to accept bluetooth connections and use a flashing green LED to indicate a connection request.
How can I create a script that 'listens' for bluetooth pairing requests and run python code accordingly when its listening? With this, how can I connect to the bluetooth to accept a pair request?
I'm not too familiar with Raspberry Pi script placement, but am familiar with Python and know how I can connect to GPIO.
Thanks :)
What you are searching for is called a Bluetooth Agent. You need to use an official linux bluetooth protocol stack BlueZ. There is documentation describing the Agent API link. It uses DBus for communication. You need to invoke the following steps:
Create a bluetooth agent written in python and publish it at certain DBus object path. Your agent must implement org.bluez.Agent1 interface as described in Agent API doc.
Then you need to register this agent by calling RegisterAgent method from Agent API. Here you will provide the DBus path where your agent is located and also you will provide the capability in your case "DisplayYesNo" (LED as a display for pairing request, and button with some timeout for implementing Yes/No).
Also register your agent as a default agent by calling RequestDefaultAgent
Now if you try to pair with your device the appropriate function in your agent will be called (I think for your use case it will be RequestAuthorization) If you want to accept the pairing you will just return from this function, if you want to reject the pairing you must throw a DBus error inside this function.
As a starting point for you I would suggest you to look at this simple python Agent: https://github.com/pauloborges/bluez/blob/master/test/simple-agent
It implements all the functionality you need so just update it according to your needs.
Have fun :)
Have you tried using this Python library ? It lists Raspberry Pi support
Additionally, here's some info on listening for incoming Bluetooth connections:
Bluetooth programming in Python follows the socket programming model.
This is a concept that should be familiar to almost all network
programmers, and makes the transition from Internet programming to
Bluetooth programming much simpler. Example 3-2 and Example 3-3 show
how to establish a connection using an RFCOMM socket, transfer some
data, and disconnect.
import bluetooth
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 ",address
data = client_sock.recv(1024)
print "received [%s]" % data
client_sock.close()
server_sock.close()
An RFCOMM BluetoothSocket used to accept incoming connections must be
attached to operating system resources with the bind method. bind
takes in a tuple specifying the address of the local Bluetooth adapter
to use and a port number to listen on. Usually, there is only one
local Bluetooth adapter or it doesn't matter which one to use, so the
empty string indicates that any local Bluetooth adapter is acceptable.
Once a socket is bound, a call to listen puts the socket into
listening mode and it is then ready to accept incoming connections.
...
Source

Modbus sniffing using python

I have 2 devices communicating with each other using Modbus and I would like to sniff this communication line using Python for logging purposes. I have connected my computer to the communication bus via a Modbus dongle, but I don't know how I can actually read the data.
I have used Pymodbus before, but I don't think that would work in this case since it only allows for master or slave devices (as far as I know)
Are there any other libraries that I can use for my purpose? Would it be possible for me to implement something like a read only socket on the COM port that doesn't interfere with existing communication on the bus?
Thank you!
You can try a MODBUS simulator like this one: It has an option to see the activity on the bus.
If you want to use another python MODBUS I recommend using modbus_tk. It has an example on how to create an MODBUS simulator. But to be able sniff the packets sent to other devices you will need to do some modifications to disable the automatic response.
If the only thing you want to do is to see the activity on the bus I recommend the first option.
I hope this helps you.
[Edit]:To be more specific you will need to download the following software : Modbus Poll - MODBUS slave simulator(which works on Windows) and plug your MODBUS dongle in the port you intend to use. After you do all the settings for the serial communications go to the Display tab and click on Communication. You will be able to see the traffic on the line.

Reading Analog Data from sensor connected to USB (Python)

I may be confusing a few concepts here so any help is appreciated.
Q1: Is it possible to attach any sensor in the world to the USB on my computer as long as it gives me analog data, and read its output? (e.g. pH, temperature, oxygen sensor etc as long as it gives me analog data)
Q2: If so, then what is the simplest way in python for me read such data.
Comment: I am trying to bypass using PLC's, and trying to see if I can get the output from the sensor directly to the PC. (I do not have drivers for these sensors)
Actual Need: I have an oxygen sensor connected to my computer via a USB. The oxygen sensor is able to send out analog data. The obvious way is to go through a PLC. However, I would like a solution which by-passes PLC's so I can connect the sensor directly to my PC via USB.
The USB port on your computer cannot read analog data because USBs work with digital signals. You would need an analog-to-digital converter (ADC).
as #digitaLink answered, it is not possible directly via USB and yes, the obvious way is to use a PLC.
I would go the PLC way - in fact, I did it a few times in the past - and start with an Arduino and later develop a custom PCB, put it in a box and done.
Another possibility is to use a raspberry pi (or similar SBC), which has the GPIOs you can use for analog read.
Edit: there is another possibility.
The sensor you use now is _very_likely_ a PLC in itself, that is, the sensor is attached to a microcontroller that uses the USB port for serial communication. Now, the drivers you are missing do nothing else but decode the data coming through the serial port. Take a look inside your harware and try to find out what components there are in.
So what you could do is to try to find out how to communicate with the sensor via a serial terminal. It is probably possible to monitor serial communication (although I must admit, I don't know how to do that), reverse engineer the code and write your own driver in python. You could learn a lot from this, even if you don't succeed.

Detect Arduino port in Python [duplicate]

This question already has answers here:
Python to automatically select serial ports (for Arduino)
(4 answers)
Closed 6 years ago.
I am using an Arduino for sensing using Python 2.7 on Windows XP, but the non-static nature of the USB-to-serial port translation is giving me a headache. With a physical serial port there is no issue hard coding the port position, but the Arduino is moving around based on what is or is not plugged in at the time of object instantiation. Is there some way in Python for me to just get the port address during each object initialization and pass it to PyVISA or pySerial?
I also suggest a handshake but do it the other ay round.
Just READ for input from the all Serial ports before starting your program. As you turn up the Device you can make it send something like an ON signal. when your code detects the ON signal on that port then do a handshake.
In pySerial there is a quite hidden way to check for VID/PID on all serial ports (at least on Windows).
Just find the VID/PID of the Arduino in port properties adn put it into the python code.
Of course this won't work if you have multiple Arduino connected (same VID/PID)
import serial.tools.list_ports
for port in list(serial.tools.list_ports.comports()):
if port[2].startswith('USB VID:PID=1234:5678'):
#here you have the right port
I recommend a handshaking signal and scanning all the ports. For example, send "whoru" from your python script to the arduiono and have code on the arduiono that responds with "arduino" when it detects "whoru" on the serial port. This way, you scan the ports, send the handshake, and when you get the proper response you know which port the arduino is on.

Categories