示例#1
0
文件: uart.cpp 项目: eu07/maszyna
uart_input::uart_input()
{
    conf = Global.uart_conf;

    if (sp_get_port_by_name(conf.port.c_str(), &port) != SP_OK)
        throw std::runtime_error("uart: cannot find specified port");

    if (sp_open(port, SP_MODE_READ_WRITE) != SP_OK)
        throw std::runtime_error("uart: cannot open port");

	sp_port_config *config;

    if (sp_new_config(&config) != SP_OK ||
		sp_set_config_baudrate(config, conf.baud) != SP_OK ||
		sp_set_config_flowcontrol(config, SP_FLOWCONTROL_NONE) != SP_OK ||
		sp_set_config_bits(config, 8) != SP_OK ||
		sp_set_config_stopbits(config, 1) != SP_OK ||
		sp_set_config_parity(config, SP_PARITY_NONE) != SP_OK ||
		sp_set_config(port, config) != SP_OK)
        throw std::runtime_error("uart: cannot set config");

	sp_free_config(config);

    if (sp_flush(port, SP_BUF_BOTH) != SP_OK)
        throw std::runtime_error("uart: cannot flush");

    old_packet.fill(0);
    last_update = std::chrono::high_resolution_clock::now();
}
int Arduino_connect(const char *serialPortName, int baudrate)
{
    struct sp_port_config *serialPortConfiguration;
    enum sp_return r;

    if(serialPort) sp_free_port(serialPort);

    // Find the specified serial port
    if(sp_get_port_by_name(serialPortName, &serialPort) != SP_OK)
    {
        fprintf(stderr, "Cannot find the serial port\n");
        return 0;
    }

    // Open the serial port
    if(sp_open(serialPort, SP_MODE_READ_WRITE) != SP_OK)
    {
        fprintf(stderr, "Cannot open the serial port\n");
        return 0;
    }

    // Configure the serial port
    sp_new_config(&serialPortConfiguration);
    sp_set_config_baudrate(serialPortConfiguration, 9600);
    sp_set_config_parity(serialPortConfiguration, SP_PARITY_NONE);
    sp_set_config_bits(serialPortConfiguration, 8);
    sp_set_config_stopbits(serialPortConfiguration, 1);
    sp_set_config_flowcontrol(serialPortConfiguration, SP_FLOWCONTROL_NONE);

    if(sp_set_config(serialPort, serialPortConfiguration) != SP_OK)
    {
        fprintf(stderr, "Cannot configure the serial port\n");
        return 0;
    }

    sp_free_config(serialPortConfiguration);

    return 1;
}