C code to control led (simple on and off)

Hi you all

I am trying to control led threw a c code (on linux for now).

In order to learn the environment a little bit i wrote a very very simple arduino code and c code:

int led = 13; // Pin 13
 
  void setup()
  {
      pinMode(led, OUTPUT); // Set pin 13 as digital out
 
     // Start up serial connection
   Serial.begin(9600); // baud rate
     Serial.flush();
 }
 
void loop()
{
     char input;
 // Read any serial input
     while (Serial.available() > 0)
     {
         input = Serial.read(); // Read in one char at a time
         if (input == '1')
            digitalWrite(led, HIGH); // on
         if (input == '0')
            digitalWrite(led, LOW); // off 
     }
     
}

all good with that code and been trying to control it threw serial monitor and all work just fine.

so, i wrote also a simple code that turn the led on and off with 2 second delay, but the led stays off and nothing happen.

#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

int main(int argc, char **argv)
{

FILE *fp = fopen("/dev/ttyACM0", "w");
 


while(1)
{
    
fprintf(fp,"1");
printf("1\n");
sleep(2);
fprintf(fp,"0");
sleep(2);
}

    return 0;
}

what am i doing wrong?
there is no way that this is so complicated, i spent to many hours on this :slight_smile:

thanks

What does sleep(2) do - sleep for 2 seconds or for 2 millisecs?

I presume you close the Serial Monitor before you try your C program?

...R

Please use code tags (</> button on the toolbar) instead of quote tags when you post code (or error/warning messages).

Robin2:
What does sleep(2) do - sleep for 2 seconds or for 2 millisecs?

I presume you close the Serial Monitor before you try your C program?

...R

in Linux its secs and Windows its millisecs (in windows its also Sleep and not sleep).

yes, the monitor was down. And also when the code first open the port, the led is blinking (due to setup section), so the code is opening the port correctly.

I assume the problem is with the data transfer over the serial port.

spetz:
I assume the problem is with the data transfer over the serial port.

I use linux, but I do my programming in Python or Ruby.

...R