1

In Terminal its working but not working using python code.

My Code:

import serial
from time import sleep

ser = serial.Serial ("/dev/ttyS0")   
while True:
    received_data = ser.read()             
    sleep(0.03)

    data_left = ser.inWaiting()            
    received_data += ser.read(data_left)

    ser.write(received_data)  

I'm trying to serial communication from Raspbian using Python to Arduino but I'm getting some permission issues like:

 %Run New.py
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 265, in open
    self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
PermissionError: [Errno 13] Permission denied: '/dev/ttyS0'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/pi/Downloads/New.py", line 4, in <module>
    ser = serial.Serial ("/dev/ttyS0")    #Open port with baud rate
  File "/usr/lib/python3/dist-packages/serial/serialutil.py", line 236, in __init__
    self.open()
  File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 268, in open
    raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg))
serial.serialutil.SerialException: [Errno 13] could not open port /dev/ttyS0: [Errno 13] **Permission denied:** '/dev/ttyS0'

If I try to communicate using terminal echo "Hello" > /dev/ttyS0 it's working. Only with the python code its creating problem.

tlfong01
  • 4,384
  • 3
  • 9
  • 23
  • I have answered with a full list of a complete, minimal, verifiable python program for your reference. This is another post your may find useful - https://raspberrypi.stackexchange.com/questions/96271/data-packet-of-hex-values-sent-over-serialIn the post I mentioned, I also suggest methods to do the hardware debugging. Please feel free if you wish me to test other things for you. Good luck to your project. – tlfong01 Apr 15 '19 at 08:40
  • Hello. Have you tried running python with `sudo` (or run the script directly with `sudo python /home/pi/Downloads/New.py`)? Could you add the output from `ls -l /dev/ttyS0` and `groups` to your answer? – Roger Jones Apr 15 '19 at 16:05

1 Answers1

1

I'm trying to serial communication from Raspbian using Python to Arduino communicate using terminal echo working,only with the python creating problem.

I have written a little python test program to do the following:

  1. Repeat sending characters.
  2. Loop back.

You may like to compare yours with my working program.

My serial test program

The full listing is here.

# uart_test06 tlfong01 2019apr08hkt1603 ***

# Computer = Rpi3B+
# Linux    = $ hostnamectl = raspberrypi Raspbian GNU/Linux 9 (stretch) Linux 4.14.34-v7+ arm 
# Python   = >>> sys.version = 3.5.3 Jan 19 2017

# Test 1   - repeatWriteBytes() - UART port repeatedly send out bytes.  
# Function - Repeat many times sending bytes, pause after each bytes.

# Test 2   - loopBackTest() - UART port send and receive bytes.
# Function - Send one bytes to TX, wait some time (Note 1), then read bytes back from RX. 
# Setup    - Connet Tx pin to Rx pin to form a loop.

# Note 1
# Bolutek BlueTooth BC04 needs at least 10mS to respond

from   time import sleep
import serial

serialPort0 = serial.Serial(port = '/dev/serial0',
        baudrate = 9600,
        parity = serial.PARITY_NONE,
        stopbits = serial.STOPBITS_ONE,
        bytesize = serial.EIGHTBITS,
        timeout= 1)

def setSerialPortBaudRate(serialPort, baudrate):
    serialPort.baudrate = baudrate
    return

def serialPortWriteBytes(serialPort, writeBytes):
    serialPort.write(writeBytes)
    return

def serialPortReadBytes(serialPort, maxBytesLength):
    readBytes = serialPort.read(maxBytesLength)
    return readBytes

def serialPortWriteWaitReadBytes(serialPort, writeBytes, maxBytesLength, waitTime):
    serialPort.flushInput()
    serialPort.flushOutput()
    serialPort.write(writeBytes)
    sleep(waitTime) 
    readBytes = serialPortReadBytes(serialPort, maxBytesLength)
    print('        bytes written = ', writeBytes) 
    print('        bytes read    = ', readBytes)
    return readBytes

def repeatWriteBytes(serialPort, writeBytes, pauseTimeBetweenBytes, repeatCount):
    print('       Begin repeatWriteOneByte(), ...')   
    for i in range(repeatCount):
        serialPortWriteBytes(serialPort, writeBytes)                
        sleep(pauseTimeBetweenBytes)
    print('       End   repeatWriteOneByte().')
    return

def serialPortLoopBack(serialPort, writeBytes, maxBytesLength, waitTime): 
    print('        Begin serialPortLoopBack() [Remember to connect Tx to Rx!] , ...')
    serialPortWriteWaitReadBytes(serialPort, writeBytes, maxBytesLength, waitTime)     
    print('        End   serialPortLoopBack(), ...')
    return

setSerialPortBaudRate(serialPort0, 9600)
#repeatWriteBytes(serialPort0, b'AT\r\n', 0.01, 200000000)
serialPortLoopBack(serialPort0, b'AT\r\n', 32, 0.030)

''' Sample output  tlfong01 2019apr0801
>>> 
=== RESTART: /home/pi/Python_Programs/test1193/uart_test02_2019apr0801.py ===
        Begin serialPortLoopBack() [Remember to connect Tx to Rx!] , ...
        bytes written =  b'AT\r\n'
        bytes read    =  b'AT\r\n'
        End   serialPortLoopBack(), ...
>>>
'''

# End

Sometimes the serial setting gets corrupted. Remember to check from time to time that:

  1. Serial port is enabled

  2. Serial console is DISABLED

serial setting

tlfong01
  • 4,384
  • 3
  • 9
  • 23
  • I just run your code and still it shows the same error. serial.serialutil.SerialException: [Errno 13] could not open port /dev/serial0: [Errno 13] Permission denied: '/dev/serial0' – Ragul Murugan Apr 16 '19 at 09:42
  • 1
    There is sometimes a conflict between python serial and serial console. You may like to check that immediately after you have the permission denied error message, serial console is still DISABLED. Refer to the picture I just appended to my answer. – tlfong01 Apr 16 '19 at 12:41