pwm: Initialize new shared memory
authorArjen Baart <arjen@andromeda.nl>
Sun, 26 Apr 2020 09:05:07 +0000 (11:05 +0200)
committerArjen Baart <arjen@andromeda.nl>
Sun, 26 Apr 2020 09:05:07 +0000 (11:05 +0200)
src/pwm.c

index 9aae3e5..8bdc7d4 100644 (file)
--- a/src/pwm.c
+++ b/src/pwm.c
@@ -52,6 +52,7 @@ void setup_io();
 #define OUTPUT_BLUE  15
 #define OUTPUT_WHITE  4
 
+const int N_COLORS    = 4;      // The number of LED colors
 
 int main()
 {
@@ -69,20 +70,35 @@ int main()
    key = SHM_KEY;
 
     /*
-     * Locate the segment.
+     * Create the shared memory segment if it does not exist yet.
      */
-   if ((shmid = shmget(key, sizeof(struct pwm) * 5, 0666)) < 0) {
-      perror("shmget");
-      exit(1);
-   }
+   if ((shmid = shmget(key, sizeof(struct pwm) * (N_COLORS + 1), 0666)) < 0)
+   {
 
-    /*
-     * Now we attach the segment to our data space.
-     */
-   if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
-      perror("shmat");
-      exit(1);
+      if ((shmid = shmget(key, sizeof(struct pwm) * (N_COLORS + 1), IPC_CREAT | 0666)) < 0)
+      {
+          perror("shmget");
+          exit(1);
+      }
+
+      //   Now we attach the new segment to our data space.
+      if ((shm = shmat(shmid, (const void *)NULL, 0)) == (void *) -1)
+      {
+          perror("shmat");
+          exit(1);
+      }
    }
+   else
+   {
+      //   Now we attach the existing segment to our data space.
+      if ((shm = shmat(shmid, (const void *)NULL, 0)) == (void *) -1)
+      {
+          perror("shmat");
+          exit(1);
+      }
+   }
+
+   signals = (struct pwm *)shm;
 
    // Set up gpi pointer for direct register access
    setup_io();
@@ -103,14 +119,6 @@ int main()
    fd[2] = OUTPUT_BLUE;
    fd[3] = OUTPUT_WHITE;
 
-   signals = (struct pwm *)shm;
-
-/*
-   for (i=0; i < 5; i++)
-   {
-      printf("Interval = %d, output = %d\n", signals[i].interval, signals[i].output);
-   }
-*/
 
    int repeat = 80000;