Girgitt / PJON-python

Pythonic interface to PJON communication protocol.
Other
26 stars 4 forks source link

How to communicate with Arduino through serial port #9

Open dontsovcmc opened 5 years ago

dontsovcmc commented 5 years ago

I can't understand is it possible to talk with Arduino board through serial port?

I want to send command to Arduino and hadn't seen "received packet" in Python

Python code.

from pjon_python.base_client import PjonBaseSerialClient
import time

pjon_cli = PjonBaseSerialClient(1, '/dev/tty.wchusbserial1420', 9600)
pjon_cli.start_client()

def receive_handler(payload, packet_length, packet_info):
    print "received packet from device %s with payload: %s" % (packet_info.sender_id, payload)

pjon_cli.set_receive(receive_handler)

while True:
    pjon_cli.send(44, 'B')
    print "send B"
    time.sleep(5)

Arduino code:

#define PJON_INCLUDE_TSA true
#include <PJON.h>

PJON<ThroughSerialAsync> bus(44);

void receiver_function(uint8_t *payload, uint16_t length, const PJON_Packet_Info &packet_info) {
  if(payload[0] == 'B') {
    digitalWrite(13, HIGH);
    delay(30);
    digitalWrite(13, LOW);
    bus.reply("B", 1);
  }
};

void setup() {
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);

  Serial.begin(9600);

  bus.strategy.set_serial(&Serial);
  bus.set_receiver(receiver_function);
  bus.begin();
};

void loop() {
  bus.update();
  bus.receive();
};
  1. I cant' understand what are FakeSerial, FakeRedis?!
Girgitt commented 4 years ago

Hi @dontsovcmc, there is no "receive packet" function - there is receive_handler instead which is called each time the pjon_cli receives a valid packet. The handler method is registered with pjon_cli.set_receive(receive_handler). It is the handler method where you put your custom code to deal with the received packet - in the example device ID and payload are printed to screen.

FakeSerial and FakeRedis are classes used in unit tests to replace external dependencies (e.g. serial port or Redis server).