Establishing Serial Communication b/t Beaglebone Black (RevC, Deb) and Arduino Mega - python

I'm trying to establish serial communications between a Beaglebone Black and Arduino Mega, but I'm having issues getting this to work, particularly on the Beagle's side. I keep getting this error message:
Traceback (most recent call last):
File "/var/lib/cloud9/IBID 2.0 /data stream test (1).py", line 35, in <module>
sensorValue += ser.read('UART1') #add more for more pins
File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 449, in read
buf = os.read(self.fd, size-len(read))
TypeError: unsupported operand type(s) for -: 'str' and 'int'
in response to trying to run this code:
import Adafruit_BBIO.UART as UART
import serial
UART.setup('UART1')
name = raw_input('name your file: ')
final_name = os.path.join(/sequence of files and folders/, name + '.txt')
data = open(name + '.txt', 'a+')
ser = serial.Serial(port = "/dev/ttyO1", baudrate=9600, timeout = 1000)
sensorValue = 0
header = 'Sensor 1 output'
data.write(str(header))
data.write(str('\n'))
while True:
ser.open()
sensorValue += ser.read('UART1')
data.write(sensorValue)
I'm using the cloud 9 IDE to program the Beaglebone to receive incoming data from a sensor hooked up to the Arduino (via logic converter.) The error code is mystifying me, to say the least. The links it provides aren't leading me to anything (no files found) in the IDE. I haven't been able to find much [on how to resolve this error.]

On this line
sensorValue += ser.read('UART1')
you are calling serial.Serial.read(size=1) with type str as an argument. The method takes an int.

Related

Pyserial - COM disconnection and reconnection possible?

new to Python but it really makes fun to work with :-)
Using the pyserial lib and works fine so far. BUT...
...is there a way to ignore the following problem: During a serial communication I disconnect the COM-cable for a short time. I got the following errormessage then:
**Traceback (most recent call last):
File "C:\Users\greulich\PycharmProjects\arduino_serial\main.py", line 48, in <module>
functions.receiveWithStartMarkers()
File "C:\Users\greulich\PycharmProjects\arduino_serial\functions.py", line 30, in receiveWithStartMarkers
receivedChar = serialPort.read(1) # read 1 byte
File "C:\Users\greulich\PycharmProjects\arduino_serial\venv\lib\site-packages\serial\serialwin32.py", line 275, in read
raise SerialException("ClearCommError failed ({!r})".format(ctypes.WinError()))
serial.serialutil.SerialException: ClearCommError failed (PermissionError(13, 'Das Gerät erkennt den Befehl nicht.', None, 22))**
My code looks like that:
while serialPort.is_open is True and newData is False:
#try:
receivedChar = serialPort.read(1) # read 1 byte
print(str(date.time()) + ' >>> ' + 'I got the following byte: ' + str(receivedChar))
I opened up port initially in that module:
try:
serialPort = serial.Serial('COM12', 115200)
except:
print('COM-Port not available!')
print('Will exit not the Python program!')
exit() #quits the complete Python program
serialPort.timeout = 3
Is there a way to define kind of a timeout until this error will hit me where the user has the chance to reconnect the cable?
In a nutshell: I want to be able to disconnect the com cable for a short time and connect it again without an error showing :-)
Thanks,
Markus

OSError: [Errno 5] Input/output error on Raspberry PI GPS shield Python

I have a Raspberry PI 3 and a GSM/GPRS/GNSS HAT.
I want to read the GPS data from the device with Python.
I have used the example code from the documentation, and rewrote it a bit.
It was working for a couple of hours perfectly, but one time when I rebooted the Raspberry(I have rebooted it before and it was working fine) it started throwing this after a couple of successful reads:
Traceback (most recent call last):
File "/home/ubuntu/gps.py", line 90, in listenForGpsInfo
while ser.inWaiting() > 0:
File "/usr/lib/python3/dist-packages/serial/serialutil.py", line 594, in inWaiting
return self.in_waiting
File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 531, in in_waiting
s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str)
OSError: [Errno 5] Input/output error
here is my code:
def listenForGpsInfo(callback):
ser = serial.Serial("/dev/ttyS0",baudrate=115200)
W_buff = [b"AT+CGNSPWR=1\r\n", b"AT+CGNSSEQ=\"RMC\"\r\n", b"AT+CGNSINF\r\n", b"AT+CGNSURC=2\r\n", b"AT+CGNSTST=1\r\n"]
ser.write(W_buff[0])
ser.flushInput()
data = ""
num = 0
while True:
time.sleep(utils.GPS_INTERVAL_IN_SECONDS)
try:
while ser.inWaiting() > 0:
data += ser.read(ser.inWaiting()).decode()
print(data)
if data != "":
if num < len(W_buff)-1:
print(num)
ser.write(W_buff[num+1])
num =num +1
else:
ser.write(W_buff[2])
if "+CGNSINF" in data:
data = str(data)
gpsInfo = parseGpsData(findInfoLine(data))
if(gpsInfo is not None):
callback(gpsInfo)
data = ""
except Exception as e:
if ser != None:
ser.close()
traceback.print_exc()
listenForGpsInfo(callback)
return
Here is the documentation of the serial commands: https://www.waveshare.com/w/upload/3/3d/SIM868_GNSS_Application_Note_V1.00.pdf
I tried a lot of things, but I couldn't solve it.
Couple of things I have tried:
Restarting the device
Detaching and Attaching the shield
Only sending the AT+CGNSPWR=1\r\n and the AT+CGNSINF\r\n commands
chmod 666 /dev/ttyS0
I had ubuntu on the raspberry and when I installed raspberry os the error went away.

Arduino Python connect or disconnect message

How could I make an if/else condition about the status of myAarduino? If the status of my Arduino is connected, I want to have a Connected Message. If not, message is Disconnected.
import serial
serialTransferRate = 115200
arduinoPort = '/dev/tty.usbmodem411'
def connectToArduino():
arduino = serial.Serial(arduinoPort, serialTransferRate)
if(arduino.timeout == None):
print ("connected")
else:
print ("disconnected")
arduino = connectToArduino()
The error code below:
File "python", line 12, in <module>
File "python", line 6, in connectToArduino
SerialException: [Errno 2] could not open port /dev/tty.usbmodem411: [Errno
2] No such file or directory: '/dev/tty.usbmodem411'
The indentation should be like this, also you must use == for a comparison in an if statement and not = (which would be for assigning a value):
def connectToArduino():
try:
arduino = serial.Serial(arduinoPort, serialTransferRate)
except:
print 'disconnected'
else:
print 'connected'
arduino = connectToArduino()
The indentation in python is essential. Only things that would be placed in {} in other languages (e.g. C/C++) can and must be indented. If you indent just random code there will be the error message: unexpected indentation.

Python scapy prn send rcv error

I am following this book called violent python and in CH5 it goes over making a script to find the mac address of an iphone wifi side. And check if bluetooth is on by incrementing the last bytes by one. Basically find an iphone that has bluetooth in hidden mode.
I am confused why the script errors out like that. What can I do to prevent this error in the future?
Here is the script below:
#!/usr/bin/python
# -*- coding: utf-8 -*-
from scapy.all import *
from bluetooth import *
def retBtAddr(addr):
btAddr=str(hex(int(addr.replace(':', ''), 16) + 1))[2:]
btAddr=btAddr[0:2]+":"+btAddr[2:4]+":"+btAddr[4:6]+":"+\
btAddr[6:8]+":"+btAddr[8:10]+":"+btAddr[10:12]
return btAddr
def checkBluetooth(btAddr):
btName = lookup_name(btAddr)
if btName:
print '[+] Detected Bluetooth Device: ' + btName
else:
print '[-] Failed to Detect Bluetooth Device.'
def wifiPrint(pkt):
iPhone_OUI = 'd0:23:db'
if pkt.haslayer(Dot11):
wifiMAC = pkt.getlayer(Dot11).addr2
if iPhone_OUI == wifiMAC[:8]:
print '[*] Detected iPhone MAC: ' + wifiMAC
btAddr = retBtAddr(wifiMAC)
print '[+] Testing Bluetooth MAC: ' + btAddr
checkBluetooth(btAddr)
conf.iface = 'wlan1mon'
sniff(prn=wifiPrint)
Error message i receive:
sudo python 10-iphoneFinder.py
Traceback (most recent call last):
File "10-iphoneFinder.py", line 34, in <module>
sniff(prn=wifiPrint)
File "/home/rb/.local/lib/python2.7/site-packages/scapy/sendrecv.py", line 620, in sniff
r = prn(p)
File "10-iphoneFinder.py", line 26, in wifiPrint
if iPhone_OUI == wifiMAC[:8]:
TypeError: 'NoneType' object has no attribute '__getitem__'
In Scapy, the addr2 field in the Dot11 layer is a conditional field, so it may have a value of None when the sniffed packet has no such field.
Here is how we could write the wifiPrint() function:
IPHONE_OUI = 'd0:23:db:'
def wifiPrint(pkt):
if Dot11 in pkt:
wifiMAC = pkt[Dot11].addr2
if wifiMAC is not None and wifiMAC.startswith(IPHONE_OUI):
print '[*] Detected iPhone MAC: ' + wifiMAC
btAddr = retBtAddr(wifiMAC)
print '[+] Testing Bluetooth MAC: ' + btAddr
checkBluetooth(btAddr)
As a side note, the script is not really well coded, to say the least. Maybe it's not a good idea to learn Scapy (or even Python) from it.

PySerial client unable to write data

I'm trying to write a python program which can communicate over a serial interface using PySerial module as follows:
import serial
if __name__ == '__main__':
port = "/dev/tnt0"
ser = serial.Serial(port, 38400)
print ser.name
print ser.isOpen()
x = ser.write('hello')
ser.close()
print "Done!"
But if I execute the above I get the following error:
/dev/tnt0
True
Traceback (most recent call last):
File "/home/root/nested/test.py", line 15, in <module>
x = ser.write('hello')
File "/usr/local/lib/python2.7/dist-packages/serial/serialposix.py", line 518, in write
raise SerialException('write failed: %s' % (v,))
serial.serialutil.SerialException: write failed: [Errno 22] Invalid argument
I referred to the pyserial documentation and according to that this should work without an issue. Please let me know what i'm doing wrong in this.
TIA!
For some reason, in order to use the module tty0tty, you need to open both /dev/tnt0 and /dev/tnt1, or any of the other pairs (e.g /dev/tnt2 and /dev/tnt3).
The code below works:
import time
import serial
def main():
vserial0 = serial.Serial(port='/dev/tnt0', baudrate=9600, bytesize=8, parity=serial.PARITY_EVEN, stopbits=1)
vserial1 = serial.Serial(port='/dev/tnt1', baudrate=9600, bytesize=8, parity=serial.PARITY_EVEN, stopbits=1)
n_bytes = 0
while n_bytes == 0:
vserial0.write('test')
n_bytes = vserial1.inWaiting()
time.sleep(0.05)
print vserial1.read(n_bytes)
if __name__ == '__main__':
main()
/dev/tntX are emulated port pairs, and to perform a successful read or write you need to open both ports from a pair.
Think of it as a pipe - if one end is closed, you will be not able to push the data through.

Categories