Arduino is giving a weird output when using toInt() - arduino

I'm trying to convert a string to an integer (which is actually a binary number) so that I can output the DEC value, but where the answer SHOULD be 63 (00111111), it's giving me -19961 as an output? It would be great if someone can help me correctly convert the string to an int :)
// C++ code
//
const int button = 13;
int buttonPressed = 0;
int counter = 0;
int myInts[] = {0, 0, 1, 1, 1, 1, 1, 1};
void setup()
{
Serial.begin(9600);
pinMode(button, INPUT);
}
void loop()
{
buttonPressed = digitalRead(button);
if (buttonPressed == HIGH){
counter = count();
//rial.println(counter);
}
else{
Serial.println("Button not pressed");
}
delay(1000);
}
int count()
{
String myString = ""; //Empty string for constructing
int add = 0;
int i = 0;
//Should add all the values from myInts[] into a string
while(i < 8){
myString = String(myString + myInts[i]);
Serial.println(add);
delay(1000);
add++;
i++;
}
Serial.println(myString);
int myNumber = myString.toInt(); //Convert the string to int
Serial.println(myNumber, DEC); //Should print 63 in this case
return add;
}

Your code currently does the following:
Concatenates all your integers together to make a string "00111111"
Attempts to convert it (as a string holding a base 10 integer) to the integer 111,111 (one hundred eleven thousand, one hundred eleven)
Hits integer overflow. The range of an Arduino int is -32768 to 32767 (65536 possible values), so the number you really have is 111111 - 2*65536 = -19961.
I don't believe that there's an overload of Arduino's ToInt that converts a binary string to an integer. Depending on the C++ support in Arduino, you may be able to use std::stoi as described here.
Instead, you may choose to do the conversion yourself - you can keep track of a number sum, and at each loop iteration, double it and then add the next bit:
int sum = 0;
for(int i = 0; i < 8; i++) {
sum *= 2;
sum += myInts[i];
// print and delay if you want
}
Over the eight iterations, sum ought to have values 0, 0, 1, 3, 7, 15, 31, and finally 63

Related

Arduino - How to convert double to HEX format

I have an arudino code where I get some temperature reading:
double c1 = device.readCelsius();
Serial.println(c1);
The output is for example: 26.23
What I need is to get this converted to 2623 and then to HEX value so I get: 0x0A3F
Any clue?
I guess your float values always get numbers up to two decimal. So, you can just multiply the value which you read from sensor with a 100.
decimalValue = 100 * c1
And then you can use this small code for converting the decimal value to HEX.
Thanks to GeeksforGeeks
You can find the full tutorial here
// C++ program to convert a decimal
// number to hexadecimal number
#include <iostream>
using namespace std;
// function to convert decimal to hexadecimal
void decToHexa(int n)
{
// char array to store hexadecimal number
char hexaDeciNum[100];
// counter for hexadecimal number array
int i = 0;
while (n != 0) {
// temporary variable to store remainder
int temp = 0;
// storing remainder in temp variable.
temp = n % 16;
// check if temp < 10
if (temp < 10) {
hexaDeciNum[i] = temp + 48;
i++;
}
else {
hexaDeciNum[i] = temp + 55;
i++;
}
n = n / 16;
}
// printing hexadecimal number array in reverse order
for (int j = i - 1; j >= 0; j--)
cout << hexaDeciNum[j];
}
// Driver program to test above function
int main()
{
int n = 2545;
decToHexa(n);
return 0;
}

How to print a number on with HT1632 only accepting text

I just bought a 8x32 lattice board (led matrix) and I control it with Arduino. The problem is that I can only use text with the library I got on github. But not numbers, how can I do it?
I'm going to put the code below, the code of the scrolling text and the part of the code in the library that specifies the function used to set the text.
The arduino code that program the scrolling text is here:
#include <HT1632.h>
#include <font_5x4.h>
#include <images.h>
int i = 0;
int wd;
char disp[] = "Hello, how are you?";
int x = 10;
void setup() {
HT1632.begin(A5, A4, A3);
wd = HT1632.getTextWidth(disp, FONT_5X4_END, FONT_5X4_HEIGHT);
}
void loop() {
HT1632.renderTarget(1);
HT1632.clear();
HT1632.drawText(disp, OUT_SIZE - i, 2, FONT_5X4, FONT_5X4_END,
FONT_5X4_HEIGHT);
HT1632.render();
i = (i + 1) % (wd + OUT_SIZE);
delay(100);
}
The library code that specifies the printing of the text is this:
void HT1632Class::drawText(const char text[], int x, int y, const byte font[],
int font_end[], uint8_t font_height,
uint8_t gutter_space) {
int curr_x = x;
char i = 0;
char currchar;
// Check if string is within y-bounds
if (y + font_height < 0 || y >= COM_SIZE)
return;
while (true) {
if (text[i] == '\0')
return;
currchar = text[i] - 32;
if (currchar >= 65 &&
currchar <=
90) // If character is lower-case, automatically make it upper-case
currchar -= 32; // Make this character uppercase.
if (currchar < 0 || currchar >= 64) { // If out of bounds, skip
++i;
continue; // Skip this character.
}
// Check to see if character is not too far right.
if (curr_x >= OUT_SIZE)
break; // Stop rendering - all other characters are no longer within the
// screen
// Check to see if character is not too far left.
int chr_width = getCharWidth(font_end, font_height, currchar);
if (curr_x + chr_width + gutter_space >= 0) {
drawImage(font, chr_width, font_height, curr_x, y,
getCharOffset(font_end, currchar));
// Draw the gutter space
for (char j = 0; j < gutter_space; ++j)
drawImage(font, 1, font_height, curr_x + chr_width + j, y, 0);
}
curr_x += chr_width + gutter_space;
++i;
}
}
You need to look at snprintf. This allows you to format a string of characters just like printf. It allows you to convert something like a int into a part of a string.
an example:
int hour = 10;
int minutes = 50;
char buffer[60];
int status = snprintf(buffer, 60, "the current time is: %i:%i\n", hour, minutes);
buffer now contains:"the current time is: 10:50" (and several empty characters past the \0).

8 bits representation

My question will be Arduino specific, I wrote a code that turns array of characters (text) into binary string, but the problem is that the binary representation is not 8 bits, its sometimes 7 bits, 6 bits or even 1 bit representation (if you have a value of 1 as decimal). I'm using String constructor String(letter, BIN) to store the binary representation of letter in a string.
I would like to have a 8 bits representation or even a 7 bits representation.
String text = "meet me in university";
String inbits;
byte after;
byte bits[8];
byte x;
char changed_char;
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println("Press anything to begin");
inbits = convertToBits(text);
}
String convertToBits(String plaintext)
{
String total,temp;
total = String(plaintext[0],BIN);
total = String(total + " ");
for (int i=1;i<plaintext.length();i++)
{
temp = String (plaintext[i],BIN);
total = String(total + temp);
total = String(total + " ");
}
Serial.println(total);
return total;
}
If the length of the argument string is less then 8, prepend "0"s until it is 8 bits long.
You could do something similar to the following:
void PrintBinary(const std::string& test)
{
for (int c = 0; c < test.length(); c++)
{
unsigned bits = (unsigned)test[c];
for (int i = 0; i < 8; i++)
{
std::cout << ((bits >> (7 - i)) & 1U);
}
std::cout << " ";
}
}
Modifying the above example to use String and Serial.println instead of std::string and std::cout should be trivial. I don't own an arduino to test with so I couldn't modify your code and test if the above is possible in the environment you work in but I assume it is.
PrintBinary("Hello"); //Output: 01001000 01100101 01101100 01101100 01101111
String(letter, BIN) doesn't zero pad the string. You have to do it yourself.
You need to prepend the 0 character until your binary string is 8 characters long.
String convertToBits(String plaintext)
{
String total, temp;
total = "";
for (int i=0; i<plaintext.length(); i++)
{
temp = String (plaintext[i], BIN);
while (temp.length() < 8)
temp = '0' + temp;
if (i > 0)
total = String(total + " ");
total = String(total + temp);
}
Serial.println(total);
return total;
}

Converting ASCII to int in Arduino

I am trying to get user input from the serial monitor to turn a stepper motor according to the input. However my code returns the ASCII value rather than the original input.
#include <Stepper.h>
Stepper small_stepper(steps_per_motor_revolution, 8, 10, 9, 11);
void setup() {
// Put your setup code here, to run once:
Serial.begin(9600);
Serial.println("Ready");
}
void loop() {
// Put your main code here, to run repeatedly:
int Steps2Take = Serial.read();
Serial.println(Steps2Take); // Printing
if (Steps2Take == -1)
Steps2Take = 0;
else {
small_stepper.setSpeed(1000); // Setting speed
if (Steps2Take > 0)
small_stepper.step(Steps2Take * 32);
else
small_stepper.step(-Steps2Take * 32);
delay(2);
}
}
Just use the .toInt() function.
You should read the string from your serial and after that convert it to integer.
Serial.print(Serial.readString().toInt());
You could do this three ways! Notice, if the number is greater than 65535 then you have to use a long variable. With decimals use float variable.
You can use the toInt(), or toFloat() which require a String type variable. Heads up as the toFloat() is very time consuming.
// CODE:
String _int = "00254";
String _float = "002.54";
int value1 = _int.toInt();
float value2 = _float.toFloat();
Serial.println(value1);
Serial.println(value2);
// OUTPUT:
254
2.54
You could use the atoi. The function accepts a character array and then converts it to an integer.
// CODE:
// For some reason you have to have +1 your final size; if you don't you will get zeros.
char output[5] = {'1', '.', '2', '3'};
int value1 = atoi(output);
float value2 = atof(output);
Serial.print(value1);
Serial.print(value2);
// OUTPUT:
1
1.23
If you had a Character Array and and wanted to convert it to a string because you didn't know the length...like a message buffer or something, I dunno. You could use this below to change it to a string and then implement the toInt() or toFloat().
// CODE:
char _int[8];
String data = "";
for(int i = 0; i < 8; i++){
data += (char)_int[i];
}
char buf[data.length()+1];
data.toCharArray(buf, data.length()+1);
If it is just a "type-conversion" problem, you can use something like this:
int a_as_int = (int)'a';
or
#include <stdlib.h>
int num = atoi("23"); //atoi = ascii to integer
as it was point out here.
Does it solve the problem?

Arduino - Strange behavior converting HEX to RGB

I'm trying to convert a HEX color code to RGB but when I run the code on Arduino, it doesn't pick up the RED.
Am I doing something wrong?
On a C++ compilator works just fine.
void setup() {
Serial.begin(115200);
String hexstring = "B787B7";
int number = (int) strtol( &hexstring[1], NULL, 16);
int r = number >> 16;
int g = number >> 8 & 0xFF;
int b = number & 0xFF;
Serial.print("red is ");
Serial.println(r);
Serial.print("green is ");
Serial.println(g);
Serial.print("blue is ");
Serial.println(b);
}
void loop() {
}
When I ran your code I still was not picking up red's value.
However using MAC's same code
long number = (long) strtol( &hexstring[1], NULL, 16 );
to
long number = (long) strtol( &hexstring[0], NULL, 16 );
I hope this helps someone struggling with RGB and HEX values
Your number should be of type long as type int is coded on 16 bits and cannot take value above 32,767.
void setup() {
Serial.begin(115200);
String hexstring = "B787B7";
long number = (long) strtol( &hexstring[1], NULL, 16);
int r = number >> 16;
int g = number >> 8 & 0xFF;
int b = number & 0xFF;
Serial.print("red is ");
Serial.println(r);
Serial.print("green is ");
Serial.println(g);
Serial.print("blue is ");
Serial.println(b);
}
void loop() {
}

Resources