I have a small piece of code here that I hope to run on Arduino. Basically what this code is doing is, it takes a nibble from the user, appends a startbit
to it, and transmits the code through a transmitter module. The receiver end receives the bits and checks if startbit
is being received. If startbit
is not being received, then it prints out whatever was transmitted. If startbit
is received, then it doesn't print the startbit, just the nibble all in one line.
My question is: is it convention/clever to use the bool array or should I not do that? Second, is there a way to make my code more efficient? Where can I clean it up? Also, is my code legible or very convoluted?
#include <Arduino.h>
#include <WirelessComm.h>
int tx_pin;
int rx_pin;
WirelessComm::WirelessComm(int rxPin, int txPin)
{
pinMode(rxPin, INPUT);
tx_pin = txPin;
rx_pin = rxPin;
}
int countDigit(long n)
{
int count = 0;
while (n > 0)
{
n /= 10;
count++;
}
return count;
}
void getDigit(bool *data, long num)
{
int cd = countDigit(num);
long shift = 1;
for (int i = 0; i < cd; i++)
{
data[i] = (num / shift) % 10;
shift *= 10;
}
}
int WirelessComm::writeTx(long nibble)
{
int i;
bool data[11]; // warning: I didn't check for buffer overrun!
int32_t startBit = 110101L; // larger than 32767, so cannot be in int
if(nibble != 0)
{
int sbLen = countDigit(startBit);
for (int i = 0; i < (int)(sizeof(data) / sizeof(data[0])); i++)
data[i] = 0;
getDigit(data, startBit);
getDigit(data + sbLen, nibble);
}
else
return -1;
for(i = 0; i < 10; i++)
{
if(data[i] == 1)
{
digitalWrite(tx_pin, HIGH);
}
else
{
digitalWrite(tx_pin, LOW);
}
}
return 1;
}
int WirelessComm::readRx(long nibble)
{
bool first = 0;
bool second = 2; //initially set to some random value
bool third = 2;
bool fourth = 2;
bool fifth = 2;
bool sixth = 2;
bool counter = 0;
bool val = 0;
while(true)
{
first = digitalRead(rx_pin);
if(first == 1);
{
second = digitalRead(rx_pin);
if(second == 1)
{
third = digitalRead(rx_pin);
if(third == 0)
{
fourth = digitalRead(rx_pin);
if(fourth == 1)
{
fifth = digitalRead(rx_pin);
if(fifth == 0)
{
sixth = digitalRead(rx_pin);
if(sixth == 1)
{
while(counter < 4)
{
val = digitalRead(rx_pin);
Serial.print(val);
counter++;
}
Serial.println();
}
else
Serial.println(first);
first = digitalRead(rx_pin);
}
else
Serial.println(first);
first = digitalRead(rx_pin);
}
else
Serial.println(first);
first = digitalRead(rx_pin);
}
else
Serial.println(first);
first = digitalRead(rx_pin);
}
else
Serial.println(first);
first = digitalRead(rx_pin);
}
else
Serial.println(first);
first = digitalRead(rx_pin);
}
}
if(third = 0)
.