This code is supposed to send information by sending pulses on railPin with lengths depending on the values in toSend. sendBit() is supposed to wait about 55 or 95 μs for the high part of the pulse, and then sendBits() is supposed to wati for the remaining part of the 106 or 200 μs after sendBit has run. I uploaded this to an arduino nano, and every pulse seems to come out as about 12μs long. My guess is that it doesn't stop at the whiles that are supposed to stop execution until the time is up("probably problematic while nr.1 and nr.2"). Am I correct or is there some other problem? How can my code be fixed?
#define buttonPin1 6
#define railPin 3
#define button1IsPullup true
void setup() {
if(button1IsPullup){
pinMode(buttonPin1,INPUT_PULLUP);
}
else{
pinMode(buttonPin1,INPUT);
}
if(button2IsPullup){
pinMode(buttonPin2,INPUT_PULLUP);
}
else{
pinMode(buttonPin2,INPUT);
}
pinMode(railPin,OUTPUT);
pinMode(LEDPin, OUTPUT);
}
static int sendLength = 57;
static bool ToSend[] = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0, 0,0,0,0,0,0,1,1, 0, 0,0,1,1,1,1,1,1, 0, 1,1,1,1,1,1,1,1 ,0 ,1,1,0,0,0,0,1,1 ,1 };
static byte OnMask = B00000001 << railPin;
static byte OffMask= (B11111110 << railPin) | (B11111111 >> (8-railPin));
void loop()
{
SendBits();
while(digitalRead(buttonPin1) == button1IsPullup);
}
void SendBits()
{
unsigned long snp;
unsigned long bitLength;
for(int i = 0; i < sendLength;i++){
snp = micros();
bitLength = ToSend[i] ? 106:200;
SendBit(ToSend[i]);
while(snp < micros()-bitLength);//probably problematic while nr.1
}
}
void SendBit(bool value){
unsigned long highLenth = (value) ? 55 : 95;
unsigned long snp1 = micros();
PORTD = PORTD | OnMask;
while(snp1 < micros() - highLenth); //probably problematic while nr.2
PORTD = PORTD & OffMask;
}