Question

When i execute the python script it connects and do not display any texts back, on other hand the server is always doing this statement only: if(incomingState != state) { }

How to make sure python is sending int type incomingState = 0 or 1 with or without \n or \r\n ? because the C code is not receiving correctly yet

Any idea please.

python_toserver.py:

import serial
import time
#ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=0)
ser = serial.Serial('/dev/ttyACM0' , 9600, timeout=0)
#ser.open()
ser.write('1')

while True:
  data = ser.read(1024)
  if len(data) > 0:
    print 'Got:', data.encode("hex")    
  time.sleep(0.5)
ser.close()

server_c.c:

#define LED1 2

int state = LOW;
char incomingByte = 0;

void setup() {
  Serial.begin(9600);
  pinMode(LED1, OUTPUT);
}

void loop() {

  if (Serial.available() > 0) {

    int incomingState = (Serial.read() == '1');
    Serial.print("I received: ");
    Serial.println(incomingState, DEC);

    if(incomingState != state) { 
      state = incomingState;
      digitalWrite(LED1, HIGH); 
      Serial.print("Setting LED as: ");
      Serial.println(state);
    } else {
      Serial.print("Doing nothing. LED already: ");
      Serial.println(state);
    }

  }

}

EDIT: Tried:

py:

import serial
import time
ser = serial.Serial('/dev/ttyACM0' , 9600, timeout=0)
#ser.write('\x01')

while True:
  data = ser.read(1024)
  if len(data) > 0:
    #print 'Got:', data.encode("hex")    
    print 'Got: ', data
    ser.write('\x01')
  time.sleep(0.5)
ser.close()

c:

#define LED1 2

int state = LOW;
char incomingByte = 0;

void setup() {
  Serial.begin(9600);
  pinMode(LED1, OUTPUT);
  Serial.print("connected");
}

void loop() {

  if (Serial.available() > 0) {

    int incomingState = (Serial.read() == '1');
    Serial.print("I received: ");
    Serial.println(incomingState, DEC);

    if(incomingState != state) {
      state = incomingState;
      digitalWrite(LED1, HIGH); 
      Serial.print("Setting LED as: ");
      Serial.println(state);
    } else {
      Serial.print("Doing nothing. LED already: ");
      Serial.println(state);
    }

  }

}

Then i get reply:

Got:  connected
Got:  I received: 0
Doing nothing. LED already: 0

Got:  I received: 0
Doing nothing. LED already: 0

Got:  I received: 0
Doing nothing. LED already: 0

Got:  I received: 0
Doing nothing. LED already: 0

Got:  I received: 0
Doing nothing. LED already: 0

Got:  I received: 0
Doing nothing. LED already: 0

Got:  I received: 0
Doing nothing. LED already: 0
Was it helpful?

Solution

Here, you have passed data to the serial port, a single byte with a value of 1:

ser.write('\x01')

But then in the server code, you compare this byte (received as a char) to the ascii character constant '1', which describes a byte with a value of 49:

int incomingState = (Serial.read() == '1');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top