Converting ASCII to int in Arduino - 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?

Related

Float variable to HEX in Arduino

I want to convert my float variables into HEX value like 0x00466 or etc. but when I try all the things that I saw in the internet my Serial Console just turns out crazy :D like "' #gA".
I tried this code below
float gyrox, gyroy, gyroz, accelx, accely, accelz, enlem, boylam, sicaklik, yukseklik, basinc;
byte ByteArray[11];
void setup() {
Serial.begin(9600);
gyrox = 1.5;
gyroy = 2.5;
gyroz = 2.0;
accelx = 5.3;
accely = 3.2;
accelz = 6.1;
enlem = 39.9250506;
boylam = 32.8369756;
sicaklik = 35.0;
yukseklik = 103.0;
basinc = 65.31455;
ByteArray[0]=(gyrox,HEX);
ByteArray[1]=(gyroy,HEX);
ByteArray[2]=(gyroz,HEX);
ByteArray[3]=(accelx,HEX);
ByteArray[4]=(accely,HEX);
ByteArray[5]=(accelz,HEX);
ByteArray[6]=(enlem,HEX);
ByteArray[7]=(boylam,HEX);
ByteArray[8]=(sicaklik,HEX);
ByteArray[9]=(yukseklik,HEX);
ByteArray[10]=(basinc,HEX);
}
void loop() {
Serial.println((char*)ByteArray);
}
and the result is ""(:D) I want the result like "0x000466 or anything likte HEX value" so what should I do?
You can cast the float to an array of bytes to get its internal representation. Then you can loop over all of the bytes and print each of them individually.
void printFloat(float const f)
{
// cast the float to an array of bytes
uint8_t const * const byteArray = (uint8_t const *)&f;
// print the start
Serial.print("0x");
// loop over the bytes, sizeof(f) tells us how many bytes make up the float
for (size_t idx = 0; idx != sizeof(f); ++idx)
{
// get the byte for this position
uint8_t const b = byteArray[idx];
// print a zero if b < 16,
// https://stackoverflow.com/questions/19127945/how-to-serial-print-full-hexadecimal-bytes
Serial.print(b>>4, HEX);
Serial.print(b&0x0F,HEX);
}
}
A float is 32 bits long (4 bytes). You can try this:
float f;
Serial.print("0x"); Serial.print(*(uint32_t*)&f, HEX);
If you really need leading zeroes, try this:
void hex_print(uint32_t x)
{
Serial.print("0x");
for (uint32_t mask = 0x0FFFFFFFul; mask && mask > x; mask >>= 4)
Serial.print('0');
Serial.print(x, HEX);
}
// calling as:
float f = 123.456f;
hex_print(*(uint32_t*)&f);

Arduino is giving a weird output when using toInt()

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

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).

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