Analogread mapping and delay

Hallo to all

I have a digital detector which traces the possitive cycle of a 50Hz signal. When oscillation is at possitive side then detector gives me a LOW value. When oscillation is negative, sensor gives me a HIGH value.

My purpose is:
When oscillation is at the possitive side, i would like to introduce a delay by a potentiometer after which a pulsetrain is coming out of my arduino pin4 which i called it just as "out".
For shake of space even i would like 12 pulses in a raw, i just present below one pulse of the train.
I'd like to ask if it looks normal to you, or if there is a hole in my logic.

Thank you.

const int sensor=3;
const int out=4;
int val=0; //sensor's output value
int analogPin=0; // setting delay d in analog input pin A0 by a potentiometer
int d=0; // Delay before pulse train. (0-20ms)

int x=20; // Pulse ON time in microseconds------------------------------------------------->
int y=200; // T pulse Period in microseconds (5KHz)---------------------------------------->

int z=y-x; // Pulse OFF time

void setup() {

pinMode(out, OUTPUT);
pinMode(sensor, INPUT);
digitalWrite(out, LOW);
d = map(d, 0, 1023, 0, 20); //mapping 0-1023 to 0-20ms

void loop() {
d=analogRead(analogPin); //setting delay d between 0-20ms
val=digitalRead(sensor);// detector's value determining possitive or negative cycle

if (val==LOW) {


digitalWrite(out, HIGH);// Those four lines present just one pulse after delay time of d.
digitalWrite(out, LOW);
else { digitalWrite(out, LOW);


You might want to take a look at the File->Examples->Digital->StateChangeDetection sketch. You probably want to start your pulse train when your signal changes state (From HIGH to LOW) not just run your pulse train multiple times when your signal is LOW (depends on how much time it takes to perform your pulsetrain vs. how fast the signal is changing)

You might also want to realize that you are not charged by the letter in variable names. One letter global variables are NOT a good idea.

Most of your comments are completely wrong. They may describe what the value is to be used for, but they do not describe what the code is doing. Comments that (uselessly) describe what the code is doing go at the end of the code. Useful comments that describe why the code is written this way go on separate lines BEFORE the code.

You seem to think that the d = map() call in setup is somehow binding the value do to that code. It is NOT. Your comments, in loop() then, make no sense.