如何通过将arduino插入USB来执行命令

时间:2013-09-28 23:16:56

标签: arduino

这个想法是:

  1. 通过USB端口将arduino连接到PC(Windows 7,管理员已登录 in)
  2. 系统自动执行命令(例如:shutdown -s -t 3600)
  3. 是否可以在不使用主机上的代理应用程序的情况下进行此操作?

1 个答案:

答案 0 :(得分:0)

以下是两个代码片段,解决了这个问题的基本原理。首先,是一个发出“DIR”命令的草图。显然,这可能是任何命令。

    #include <stdio.h>

    uint8_t command[] = "dir\0";

    void setup() 
    {
     Serial.begin(9600);
     delay(10000);
     Serial.write(command, 4);
    }

    void loop() {}

其次,是读取COM5的C代码,并在收到字符串后发出命令。

/*
 * main.c
 *
 *  Created on: Sep 29, 2013
 *      Author: Jack Coleman
 *
 *  This software is for demonstration purposes only.
 *
 */

#include <stdio.h>
#include <Windows.h>

//
// create a console that accepts data
// from a com port and issues it as system commands.
//
void display_config(COMMCONFIG *config_comm)
{
    printf("BaudRate = ");
    switch (config_comm->dcb.BaudRate)
    {
       case CBR_9600 : printf("9600\n");
    }
    printf("Parity   = %d\n", config_comm->dcb.Parity);
    printf("StopBits = %d\n", config_comm->dcb.StopBits);
    printf("ByteSize = %d\n", config_comm->dcb.ByteSize);
    fflush(stdout);

}

main()  // Version 0
{
    HANDLE hCOM5;

    int   config_size;

    COMMCONFIG config_comm;

    int   retc;
    int   nr_read;

    char *comm_char;
    char  sysline[271];

    hCOM5 = CreateFile("COM5", GENERIC_READ, 0, 0,
                     OPEN_EXISTING, 0, NULL);
    if (hCOM5 <= 0)
    {
        printf("unable to open COM5");
        return;
    }

    GetCommConfig(hCOM5, &config_comm, &config_size);

    config_comm.dcb.BaudRate = CBR_9600;
    config_comm.dcb.Parity   = NOPARITY;
    config_comm.dcb.StopBits = ONESTOPBIT;
    config_comm.dcb.ByteSize = 8;

    retc = SetCommConfig(hCOM5, &config_comm, config_size);
    if (retc == 0)
    {
        printf("SetCommConfig failed.\n");
        return;
    }

    display_config(&config_comm);

    // wait here for a possible, initial
    // series of 0xFF.
    comm_char = sysline;
    do
    {
        ReadFile(hCOM5, comm_char, 1, &nr_read, NULL);

        printf("%x nr_read = %d\n", *comm_char, nr_read);
        fflush(stdout);

    } while (nr_read == 0);

    while (nr_read == 1)
    {
      if (*comm_char == 0x00)
      {
         printf("%s\n", &sysline[0]);
         fflush(stdout);

         system(&sysline[0]);
         break;

      } else {
          comm_char++;
      }

      ReadFile(hCOM5, comm_char, 1, &nr_read, NULL);

      printf("%02x\n", *comm_char);
      fflush(stdout);

    }

    return;
}

这是一个有趣的小编码问题。学到了几个教训:1)当通过串行线进行通信时,C程序将只等到Arduino传输第一个字节。有 no 同步字符作为数据传输的前言(也就是说,如果它们被系统代码删除了); 2)读取的字节数可以为零(0)。

这可以用来使用Arduino发出关闭命令吗?是的,但程序必须启动(即预定),然后等待Arduino发言。