Reading signal from virtual serial port

Published by Jorge on

Note: this post was rescued from my older blog and added it here on Aug 2018. Pinguino project is no longer being developed but the same approach can be used with any Arduino board.

Here I upload the code for a simple task with pinguino: executing a script when you push a button on a circuit.

Documentation: Serial port guide by Michael R. Sweet  – unistd.hread function.

Circuit: simple push-button circuit with a pull-down resistor so when you push you get 5 volts and the led turns on.
Microcontroller: Sends a 1 by virtual serial port when you push the button or a 0 each five seconds.

 Output: The program prints what it gets from the port and if it gets a 1 it executes a script.

sketch

Here is the source code:

Code(1): Signal reading by serial port:

/* Serial app.
 * Opens a serial port and if reads a one executes
 * the script you have typed
 * (C) 7/2012 Jorge A. Cortés http://en.jorgeacortes.com
 */
#include    /* Standard input/output definitions */
#include   /* String function definitions */
#include    /* File control definitions */
#include    /* Error number definitions */
#define N 8		/* Buffer length */
#define L 256	/* Command and path length */
int open_port(void);

int main()
{
  char buf[N],com[L];
  size_t nbytes;
  ssize_t bytes_read;
  int fd;
  nbytes = sizeof(buf);
  printf("\nSerial app.\nType script (ex:sh /dir/to/script/):");
  fgets(com,L,stdin);
  fd=open_port();
  while(fd!=-1)
  {
    bytes_read = read(fd, buf, nbytes);
    fprintf(stdout,"\nOutput:%s",buf);
    if(buf[0]=='1') //If we recieve one executes the command
      system(com);
  }
  printf
  (	  "*******************"
	"\n**Exiting program**"
	"\n*******************"
  );
  return 0;
}

int open_port(void)
{
  /*
   * 'open_port()' - Open serial port typed.
   * Returns the file descriptor on success or -1 on error.
   */
  char dir[L]; // Port path
  int fd; /* File descriptor for the port */
  printf("Type the port path:");
  fgets(dir,L,stdin);
  dir[strlen(dir)-1]='\0'; // delete return
  fd = open(dir, O_RDWR | O_NOCTTY | O_NDELAY);
  if (fd == -1)
  { //Could not open the port.
    perror("open_port: Unable to open");
    printf("Path introduced:%s\n",dir);
  }
  else
    fcntl(fd, F_SETFL, 0);
  return (fd);
}

Code (2): Basic signal sending by the virtual serial port for pinguino PIC:

/* Basic data sending with virtual serial port.
 * If we have HIGH it sends a 1 and waits 2.5 seconds.
 * Otherwise it sends a 0 after 2.5 seconds.
 */
#define P 5	/* Pin to use */

void setup()
{
	pinMode(P,INPUT);
}
void loop()
{
    int c=0;
    while(c<25)
    {
        c++;
        delay(100); // 100ms if not pressed, then will be 2500ms.
        if(digitalRead(P))
        {
            CDC.printf("1");
            delay(2500);
            c=25; // Restart.
        }
    }
    CDC.printf("0");
}

If you want to read more like this, subscribe to my newsletter or follow me on Twitter