Search code examples
msp430contiki

C - How to receive from the serial port for the device side (z1 mote)


I am trying to communicate with a z1 mote that is connected to my PC directly by using pyserial. What I am looking to do is to write to the mote, and upon receiving the command, the mote should reply the current reading for temperature, for example.

Python side can be something like this (iinm)

import serial
ser = serial.Serial(0)  
ser.write("hello")      # the mote will receive the message and do something 

but I have no clue how to receive the message in the z1 mote side that uses C. Is there a special method to receive the commands or do I have to create my own?

Any tips and hints are a greatly appreciated.


Solution

  • If you want to just receive newline-terminated strings, Contiki already has functionality for that. Just wait for serial_line_event_message event in your protothread's loop:

    #include "contiki.h"
    #include "dev/serial-line.h"
    
    PROCESS(main_process, "main process");
    AUTOSTART_PROCESSES(&main_process);
    
    PROCESS_THREAD(main_process, ev, data)
    {
        PROCESS_BEGIN();
        for(;;) {
            PROCESS_WAIT_EVENT();
    
            if (ev == serial_line_event_message && data != NULL) {
               printf("got input string: '%s'\n", (const char *) data);
            }
        }
        PROCESS_END();
    }
    

    If on the other hand you want to customize the reception (e.g. to allow binary data, or to use custom framing, or to include checksums) you need to handle the input at the level of individual characters. Define and set a UART callback on the right UART (on the Z1 platform USB is connected to UART 0, but the number and the exact name of the function are platform-dependent). An example serial input handler function:

    static int serial_input_byte(unsigned char c)
    {
        printf("got input byte: %d ('%c')\n", c, c);
    }
    

    And then put this in your initialization code:

    uart0_set_input(serial_input_byte);