Raspberry PiでC言語を使ってArduinoとシリアル通信する

2018/04/19 00:05#ラジコン戦車1号

ArduinoにPWMのパルス幅を指定してシリアル通信で送るのをC言語でやりました。

Raspberry Pi

#include <stdio.h>   /* Standard input/output definitions */
#include <string.h>  /* String function definitions */
#include <unistd.h>  /* UNIX standard function definitions */
#include <fcntl.h>   /* File control definitions */
#include <errno.h>   /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <getopt.h>  // process commandline options


int main(int argc, char *argv[])
{
    int opt;
    char *port, *width;

    struct option long_options[] = {
        {"port", required_argument, NULL, 'p'},
        {"width", required_argument, NULL, 'w'}
    };

    while((opt = getopt_long(argc, argv, "", long_options, NULL)) != -1) {
        switch(opt) {
            case 'p':
                port = optarg;
                break;
            case 'w':
                width = optarg;
                break;
        }
    }


    if(port == NULL | width == NULL) {
        printf("--port [port] --width [pulse width]\n");
        return 0;
    }

    // open serialport
    int fd = open(port, O_RDWR | O_NOCTTY | O_NDELAY);
    if(fd < 0) {
        printf("Cannot open port\n");
        return 0;
    }

    struct termios options;

    // get current settings
    tcgetattr(fd, &options);

    // set baudrate to 115200
    cfsetispeed(&options, B115200);
    cfsetospeed(&options, B115200);

    // set new settings
    tcsetattr(fd, TCSADRAIN, &options);


    int n;
    unsigned int w;
    sscanf(width, "%d", &w);
    n = write(fd, &w, 2);

    close(fd);

    return 0;
}

Arduino

unsigned long ts;
unsigned int width = 1500;
char bytes[2];

void setup() {
    Serial.begin(115200);
    ts = micros();
    DDRB = DDRB | B00100000; // pin 13
}

void loop() {

    unsigned long t = micros() - ts;


    if (Serial.available() > 1) {
        Serial.readBytes(bytes, 2);
        width = (bytes[1] << 8) | (bytes[0] & 0xff);
    }

    if (t <= width) {
        PORTB = PORTB | B00100000;
    }
    else {
        PORTB = B00000000;
    }

    if (t >= 20000) {
        ts = micros();
    }
}