I am building an IoT Application in android studio and I am using Chaquopy - Python SDK for android so my python script will run when I press the button in the android application but somehow I am receiving could not open port error like this.
Process: com.example.firebaseheartratemonitor, PID: 16761
com.chaquo.python.PyException: SerialException: [Errno 2] could not open port COM4: [Errno 2] No such file or directory: 'COM4'
at <python>.serial.serialposix.open(serialposix.py:325)
at <python>.serial.serialutil.__init__(serialutil.py:244)
My android code in Java:
if (!Python.isStarted()){
Python.start(new AndroidPlatform(this));
}
Python py = Python.getInstance();
PyObject module = py.getModule("get");
sendDataOverDisplay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PyObject pyObject = module.callAttr("main", heartrate);
sendData.setText(pyObject.toString());
}
});
My python code:
import serial
import time
def main(data):
with serial.Serial('COM4', 9600) as ser:
ser.open()
requiredData = data[0]
ser.write((requiredData).encode())
time.sleep(.01)
ser.close()
return requiredData
It's been a week and I could not figure out how to solve this error any leads would be appreciated.
"COM4" looks like a Windows serial port name, so that won't work on Android. Try using something like serial.tools.list_ports
to discover the correct name.
Also, even if you do use the correct name, your app probably still won't have permission to access the port directly. If you're running on a rooted device, you may be able to get pyserial to work by changing the permissions on the port's device file. On non-rooted devices, the only option I know of is to use the Java UsbManager
instead, perhaps with the help of a library like UsbSerial. You can still call these APIs from Python with the help of the Chaquopy Python API.