Arduino code:
this code is provided communication between sensor gy-521 and arduino. I read data by the command "1", after 1000 samples arduino is waited for new command for read data.
Arduino code works well in arduino port.
#include<Wire.h>
const int MPU=0x68;
int16_t AcX,AcY,AcZ;
unsigned long time;
bool allow = false;
//int incom = 0;
void setup(){
Wire.begin();
Wire.beginTransmission(MPU);
Wire.write(0x6B);
Wire.write(0);
Wire.endTransmission(true);
Serial.begin(19200);
while (!Serial);// wait for serial port to connect. Needed for native USB port only
}
void loop(){
if (allow){ //if allow == true, read data
for (int i = 0; i < 1000; i++){
Wire.beginTransmission(MPU);
Wire.write(0x3B);
Wire.endTransmission(false);
Wire.requestFrom(MPU,12,true);
AcX=Wire.read()<<8|Wire.read();
AcY=Wire.read()<<8|Wire.read();
AcZ=Wire.read()<<8|Wire.read();
time = millis();
Serial.print(time);Serial.print(",");Serial.print(AcX);Serial.print(",");Serial.print(AcY);Serial.print(",");Serial.println(AcZ);
delay(0);
}
Serial.println(0); //see UPD.3
allow = false;
}
}
void serialEvent() {
while (Serial.available()){ //wait for command
int incom = Serial.read() - '0';
Serial.println(incom);
if (incom == 0){ //if 0 - stop
allow = false;
delay(100);
}
if (incom == 1){ //if 1 - read data
allow = true;
delay(100);
}
}
}
Python code:
def sensors(self):
self.arduino_port_sensor.reset_input_buffer() #clear buffer
self.arduino_port_sensor.write(str(1).encode()) #send command to arduino - read data
main_array = []
pbar = tqdm(total=self.time_observation) #just to see the progress
while True:
values = self.arduino_port_sensor.readline().decode().rstrip().replace(" ", "") #read data, some manipulation for cleaning
main_array.append(values)
pbar.update(1)
if values == '': #if data is empty
print('!!!!')
continue
if values == '0': #see UPD.3
break
pbar.close()
...bla bla...
I call this function time to time, then in some step, arduino stops sending data -- it sends empty string.
It looks like:
PS. In this code I use 2 ports: for sensor and for motor, 2 different arduino. The principe of working second arduino with motor the same, but it works without any problem (I just send command with "action" to arduino with motor, and then receive answer "received back")
Question: what's wrong with python? how to fix this problem?
UPD
Initialization:
arduino_port_sensor = serial.Serial('/dev/tty.usbmodem143101', 19200, timeout = 1)
UPD.2
It receive command - "1" - read data, the interruption occurs while reading data:
UPD.3
Also i changed the code of arduino -- added the "0" after loop.
UPD.4
If I recall this function after arduno stopped sending data, I get this: