Using Arduino Nano Every, I wanted to build a R-2R DAC. So I started with a program which converts decimal numbers to binary numbers. These could be then used for setting a number of pins high or low. So I have a code which converts an entered decimal number to an array of binary ones and displays the result. The decimal numbers are inserted from the serial monitor.
When I enter the first number (it has to be 0...1023) for conversion it works as it is meant to. After entering the second number it displays a mirrored ?-sign, after entering the third number it displays the desired result, and after entering the fourth number it doesn't return anything. After that it returns the desired output after every second entry, i.e. it always skips one entry.
I suspected some remnants in the serial buffer and added a cycle at the end which should read the buffer until it is empty. But it doesn't change anything... I think it might be something really simple but somehow I haven't managed to figure it out. Could somebody tell me what is causing such behavior?
This is the code:
#include <stdio.h>
#include <math.h>
uint8_t bitsCount = 10; //1023 corresponds to 1111111111
char str[10 + 1];
String rec;
int num;
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available() == 0) {}
rec = Serial.readString();
num = rec.toInt();
uint8_t i = 0;
while (bitsCount--)
str[i++] = bitRead(num, bitsCount) + '0';
str[i] = '\0';
Serial.println( "******" );
Serial.println("Inserted: " + rec);
Serial.println(str);
for (int i = 0; i <= 9; i++) {
Serial.println(str[i]-'0');
}
// Char (just a single character) to int: int someInt = someChar - '0';
Serial.print("Sum of the last three bits: ");
Serial.println((str[9]-'0' + str[8]-'0' + str[7]-'0'));
//Empty the buffer
while (Serial.available() > 0) {Serial.read();}
}
Thanks for any help!