From decimal ASCII number to int character - arduino

I want to read a file from an SD card that contains integers. The reading function returns decimal ASCII values between 48 to 57 which corresponds to the characters '0' to '9'. How can I save this character as an integer? This is the code I have now. If I run this code and read '0' from the file, access will be 48 and c as well.
char c;
String chat_id;
int access;
int getaccess(String chat_id) {
String a = "Gebruikers/" + chat_id + ".txt";
if (!SD.exists(a.c_str())) {
return 0;
} else {
myFile = SD.open("Gebruikers/" + chat_id + ".txt");
if (myFile) {
Serial.println("Getting the access number");
access = myFile.read();
myFile.close();
Serial.println("done.");
c = access + 0;
return c;
} else {
Serial.println("error opening " + nummer + ".txt");
}
}
}

If you are reading single digits, then just subtract 48 form the ASCII code and you'll get the number.
Most commonly written as:
int oneDigitNumber = someAsciiCode - '0';

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;
}

Extract numbers from AT command in Arduino

So I'm doing an AT command and the reply is
AT+CGDCONT?
+CGDCONT: 1,"IP","hologram","0.0.0.0",0,0,0,0
+CGDCONT: 13,"IP","hologram","0.0.0.0",0,0,0,0
+CGDCONT: 14,"IP","hologram","0.0.0.0",0,0,0,0
OK
I need to get the numbers out of this that are written before the "IP" (for this example they are 1,13,14). The numbers range from 1-24 as do the number of lines.
I was reading the reply from the command and saving it as a String with
String input;
SerialAT.println("AT+CGDCONT?");
delay(500);
if (SerialAT.available()) {
input = SerialAT.readString();
Serial.println(input);
}
Right now I am reading the stream reply and saving it as a String. The String is then cut at the newline (\n) and stored pieces in an array. After that, I have it read the array and stop once it hits a "," which is right after the number. Then it identifies the section that contains ": " which is right before the number and gets the index position of the ": " and uses that to take a substring of what is left which is just the number.
So for the example that I have, it would put the first row into the array looking like this
+CGDCONT: 1,"IP","hologram","0.0.0.0",0,0,0,0
It would be read one char at a time until the first "," is identified like this
+
+C
+CG
+CGD
+CGDC
+CGDCO
+CGDCON
+CGDCONT
+CGDCONT:
+CGDCONT:
+CGDCONT: 1
then the position of ": " would be identified and for this example, it would be 9. So everything after the 9th position inside of the array would be the output which is 1.
This is working flawlessly and I have even sent in garbled text before the +CGDCONT: because sometimes that's what the modem replies if it didn't have time to fully process the command and it has always fed me the numbers out correctly.
My code for this is
String input;
SerialAT.println("AT+CGDCONT?");
delay(500);
if (SerialAT.available()) {
input = SerialAT.readString();
Serial.println(input);
} else {
Serial.println("Failed to get PDP!");
}
const int numberOfPieces = 10;
String pieces[numberOfPieces];
int counter = 0;
int lastIndex = 0;
for (int i = 0; i < input.length(); i++) {
if (input.substring(i, i + 1) == "\n") {
pieces[counter] = input.substring(lastIndex, i);
lastIndex = i + 1;
counter++;
}
if (i == input.length() - 1) {
pieces[counter] = input.substring(lastIndex, i);
}
}
input = "";
counter = 0;
lastIndex = 0;
String readString, data;
int D;
int PDPcounter = 0;
for ( int i = 0; i < numberOfPieces; i++) {
for ( int x = 0; x < pieces[i].length(); x++) {
char c = pieces[i][x]; //gets one byte from buffer
Serial.println(readString);
if (c == ',') {
if (readString.indexOf(": ") >= 0) {
data = readString.substring((readString.indexOf(": ") + 1));
D = data.toInt();
Serial.println(D);
PDP[PDPcounter] = D;
Serial.print("PDPcounter = "); Serial.println(PDPcounter);
PDPcounter++;
readString = "";
data = "";
break;
}
readString = "";
data = "";
}
else {
readString += c;
}
}
}
At the very end, I try and read the contents of the PDP array with
for ( int i = 0; i < 10; i++) {
Serial.print(i);
Serial.print(" - ");
Serial.println(PDP[i]);
}
and I am getting the following
0 - 1
1 - 13
2 - 14
3 - 0
4 - 0
5 - 0
6 - 0
7 - 0
8 - 0
9 - 0
which is exactly what I need.
I guess the only help that I need now is code cleanup recommendations.

how to split a string into words in arduino?

I have a string in arduino
String name="apple orange banana";
Is it possible to store each item in an array arr
so that
arr[0]="apple"
arr[1]="orange" ......etc
if not store them in individual variables?
How to split a string using a specific delimiter in Arduino? I believe this would help you, you could do a while loop like:
int x;
String words[3];
while(getValue(name, ' ', x) != NULL){
words[x] = getValue(name, ' ', x);
}
Using this function:
// https://stackoverflow.com/questions/9072320/split-string-into-string-array
String getValue(String data, char separator, int index)
{
int found = 0;
int strIndex[] = {0, -1};
int maxIndex = data.length()-1;
for(int i=0; i<=maxIndex && found<=index; i++){
if(data.charAt(i)==separator || i==maxIndex){
found++;
strIndex[0] = strIndex[1]+1;
strIndex[1] = (i == maxIndex) ? i+1 : i;
}
}
return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}
If you know your list length and the max characters per list item, you could do
char arr[3][6] = {"apple", "orange", banana"};
edit: if you are looking for something like String arr[3] you aren't going to get it because of how memory is managed with the C language

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;
}

android hexToByteArray signed to unsigned

I've got the following function to make a conversion from a Hex String to a Byte array. Then, I calculate the Checksum:
private String CalcChecksum (String message) {
/**Get string's bytes*/
//byte[] bytes = DatatypeConverter.parseHexBinary(message.replaceAll("\\s","")).getBytes();
message = message.replaceAll("\\s","");
byte[] bytes = hexToByteArray(message);
byte b_checksum = 0;
for (int byte_index = 0; byte_index < bytes.length; byte_index++) {
b_checksum += bytes[byte_index];
}
int d_checksum = b_checksum; //Convert byte to int(2 byte)
int c2_checksum = 256 - d_checksum; //Hacer complemento a 2
String hexString = Integer.toHexString(c2_checksum); //Convertir el entero (decimal) a hexadecimal
return hexString;
}
public static byte[] hexToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16));
}
return data;
}
Making some test, for example for the hex value "e0", the hexToByteArray is getting the value "-32". So the final returning value in the CalcChecksum is "17a".
What I need is to get unsigned values in the hexToByteArray function. This is because i need to send the Checksum in a hexString to a MCU where the Checksum is calculated with unsigned values, so isntead of get the "-32" value, it gets "224" and the final hex value is "7a" instead of "17a".
i think that doing some kind of conversion like when the byte result is a negative value, do something like 255 + "negative value" + 1. This will convert "-32" into "224".
The problem is that i'm trying to do it, but i'm having some errors making the conversions between bytes, int, etc...
So, how could i do?
For the moment, I think that this can be the solution.
Just including in the CalcChecksum function the next code after int d_checksum = b_checksum;:
if (d_checksum < 0) {
d_checksum = 255 + d_checksum + 1;
}

Resources