Why output is printed in asci code instead of integer ?dart - console

I don't know why output is printed in ascii code instead of integer value ,what wrong with my code ?
import 'dart:io';
void main() {
int n = 0;
print("input: ");
do {
n = stdin.readByteSync();
} while (n>1000 || n<0);
if (n % 4 == 0) {
print("output: ");
print(n);
n++;
} else {
print("output: ");
n--;
print(n);
}
}

Paste your code so it can be easier to help you.
I could have given you a fixed source code if you would have provided.
Instead, I'll try to explain:
Your stdin will be provided as a string, you read it as bytes so 5 will be come 35 as hex.
When you print it, my guess is that it will automatically be converted to a decimal value (53, and the output shows 52 because 53 % 4 = 1 and then to decrease with n-- before printing it so it become 52).
Those numbers like you said of the ASCII Table.
In order to fix it, make sure you have the string representation of the input (stdin). Then convert the value to integer: "2".toInt()
Edit:
I could have easily find the complete solution,
You need to get the stdin as a string first: readLineSync and convert it to int:
n = int.parse(stdin.readLineSync());
Note: Code not tested, but it's pretty straight forward.

Get the value as String using stdin.readLineSync() then parse it to int like below:
import 'dart:io';
void main() {
int n = 0;
print("input: ");
do {
n = int.parse(stdin.readLineSync());
} while (n>1000 || n<0);
if (n % 4 == 0) {
print("output: ");
print(n);
n++;
} else {
print("output: ");
n--;
print(n);
}
}

Related

Trying to extract longitude and latitude from gps using arduino and neo 6m module but the loop goes up to infinity

I'm new to arduino and trying to extract gps coordinate using neo 6m module using arduino but the loop is running till infinity. Can you please help me why it is not breaking.
void gpsEvent()
{
gpsString = "";
while (1)
{
while (gps.available() > 0) //Serial incoming data from GPS
{
char inChar = (char)gps.read();
gpsString += inChar;//store incoming data from GPS to temparary string str[]
i++;
// Serial.print(inChar);
if (i < 7)
{
if (gpsString[i-1] != test[i-1]) //check for right string
{
i = 0;
gpsString = "";
}
}
if (inChar == '\r')
{
if (i > 60)
{
gps_status = 1;
break;
}
else
{
i = 0;
}
}
}
if (gps_status)
break;
}
}
void get_gps()
{
gps_status = 0;
int x = 0;
while (gps_status == 0)
{
gpsEvent();
int str_lenth = i;
coordinate2dec();
i = 0;
x = 0;
str_lenth = 0;
}
}
I have called get_gps(); in the void setup() loop to initialize the system but the gpsEvent function which is used to extract the correct string from data is running till infinite can you pls help. The reference of the code is from https://circuitdigest.com/microcontroller-projects/arduino-based-accident-alert-system-using-gps-gsm-accelerometer
but have made few changes of my own but not in the programming for the gps module.
I think one of the errors is gpsString += inChar;.
This is not Python. You are adding the value of a character to a string pointer.
You should create a buffer with a maximum length, insert a char and check buffer overflow.
Also i seems not be defined. And in C is very bad practice to use global variables as you are doing. Keep one i in the function. Check again the string length.
In general, it seems you are using a language you do not know enough to write simple programs (string manipulation is basic on C). Either learn better C or look for a python implementation (or just link) of the gps library.

Arduino 'for' error

I have made a program for my Arduino which will sort an array of fifty random numbers in ascending or descending order, I think I have got it all right, but when I run it I get an error message "expected unqualified-id before 'for' ".
int array [50];
int i = 0;
void setup() {
Serial.begin(9600); // Load Serial Port
}
void loop() {
// put your main code here, to run repeatedly:
Serial.println ("Position " + array[i]);
delay (2000);
}
for (i <= 50) { <-----*Here is where the error highlights*--->
int n = random (251); // Random number from 0 to 250
array[i] = n;
i++;
}
// Bubble sort function
void sort (int a[], int size) {
for(int i=0; i<(size-1); i++) {
for(int o=0; o<(size-(i+1)); o++) {
if(a[o] > a[o+1]) {
int t = a[o];
a[o] = a[o+1];
a[o+1] = t;
}
}
}
}
I have annotated where the error is shown. I need to get past this to test my code, I have no clue on how to fix it!
You have written it wrong. There is pseudocode of for loop:
for(datatype variableName = initialValue; condition; operation){
//your in loop code
}
//Code wich will be executed after end of for loop above
In your case it will look like this:
for(int i = 0; i < 50 ; i++){
int n = random (251); // Random number from 0 to 250
array[i] = n;
}
Another thing is, that you are trying to iterate the array. The first index is 0. It means the last index is 49 not 50. If you try to access 50th index it will crash your program.
Last thing is, that the for loop we are talking about is out of any method. It will never be executed.
The for loop requires three parts to its parameters:
A variable to count iterations
A condition that must be true to continure
A increment factor
Each part should be separated by a semicolon
So your for loop should start out like this:
for(int i = 0;i <= 50; i++){
//code here
}
Official arduino For Loop Reference

Understand how data is retrieved from function

I've started learning C for Arduino for about 2 weeks. I have the following code and I don't understand how data is retrieved from function ReadLine. Also I don't understand how variable BufferCount affects the program and why it is used. I do know that it holds the number of digits the year have but that's about all I know about this variable.
From what I've learned so far a function is composed of:
function type specifier
function name
function arguments.
What I see in this program makes me think that the function can also return values using the argument part. I always thought that a function can only return a value that is the same type (int, boolean ...) as the type specifier.
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.avaible() > 0) {
int bufferCount;
int year;
char myData[20];
bufferCount = ReadLine (myData);
year = atoi(myData); //convert string to int
Serial.print("Year: ");
Serial.print(year);
if (IsLeapYear(year)) {
Serial.print(" is ");
} else {
Serial.print(" is not ");
}
Serial.println("a leap year");
}
}
int IsLeapYear(int yr) {
if (yr % 4 == 0 && yr % 100 != 0 || yr % 400 == 0) {
return 1; //it's a leap year
} else {
return 0;
}
}
int ReadLine (char str[]) {
char c;
int index = 0;
while (true) {
if (Serial.available() > 0) {
c = Serial.read();
if (c != '\n') {
str[index++] = c;
} else {
str[index] = '\0'; //null termination character
break;
}
}
}
return index;
}
The fundamental concept you are missing is pointers. In the case of a function like isLeapYear there, you'd be right about that parameter. It is just a copy of the data from whatever variable was passed in when the function gets called.
But with ReadLine things are different. ReadLine is getting a pointer to a char array. A pointer is a special kind of variable that holds the memory address of another variable. And it is true that in this case you are getting a local copy of the pointer, but it still points to the same location in memory. And during the function, data is copied not into the variable str, but to the memory location it points to. Since that is a memory location that belongs to a variable in the scope of the calling function, that actual variable's value will be changed. You've written over it in memory.

How to correctly use sscanf

I have to write an Arduino function to look up a number in the phone book. My code doesn't work because of the condition using sscanf. What am I doing wrong?
//read the phone book and put the good value in the string
void Read_ADMIN_PHONE_NUMBER(){
String ADMIN_PHONE_NUMBER;
delay(1000);
sendATcommand("AT+CPBS=\"SM\"", 500) ; //Select the SIM phonebook
sendATcommand("AT+CPBR=1,99", 100) ; // To read ALL phonebook +CPBR: 1,"690506990",129,"ANDROID"---- exemple de reponse copier du serial monitor
if (1 == sscanf(fonaInBuffer, "+CPBR: %*s", &ADMIN_PHONE_NUMBER)) {
Serial.println(F("*****"));
Serial.println(ADMIN_PHONE_NUMBER);
} else {
Serial.println(F("**bad***"));
}
delay(2000);
}
My problem come from the sscanf.I can't put fonaInBuffer in ADMIN_PHONE_NUMBER
void Read_ADMIN_PHONE_NUMBER(){
String ADMIN_PHONE_NUMBER;
delay(1000);
sendATcommand("AT+CPBS=\"SM\"", 500) ; //Select the SIM phonebook
sendATcommand("AT+CPBR=1,99", 100) ; // To read ALL phonebook like example: +CPBR:1,"690506990",129,"ANDROID"
if (1 == sscanf(fonaInBuffer, "+CPBR: %*s", &ADMIN_PHONE_NUMBER)) {
Serial.println(ADMIN_PHONE_NUMBER);
} else {
Serial.println(F("**bad***"));
}
delay(2000);
The * in %*s means 'do not assign', and such conversion specifications are not counted in the number of successful conversions. Therefore, the sscanf() call will return 0 always (unless the scanned string is empty; then it returns EOF) because there is no active conversion.
Remove the *, or replace it with a suitable number. If the ADMIN_PHONE_NUMBER is a char ADMIN_PHONE_NUMBER[123];, then the number you use should be (at most) 122: %122s — because sscanf() writes a null after the 122 characters if it reads 122 characters in a single 'word'. It is not clear what String ADMIN_PHONE_NUMBER; means — more precise advice cannot be given because of that.
Reducing your code to close to an MCVE (How to create a Minimal, Complete, and Verifiable Example?):
#include <stdio.h>
int main(void)
{
char buffer[] = "+CPBR: 1,\"690506990\",129,\"ANDROID\"";
char number[64];
int n = sscanf(buffer, "+CPBR: %63s", number);
printf("n = %d: number = [%s]\n", n, number);
n = sscanf(buffer, "+CPBR: %*d , \" %63[^\"]", number);
printf("n = %d: number = [%s]\n", n, number);
return 0;
}
Sample output:
n = 1: number = [1,"690506990",129,"ANDROID"]
n = 1: number = [690506990]
Take your pick as to which you want to use. I've been liberal with allowed white space in the sscanf conversion specifications. You can be less liberal if you prefer.

Convert String to HEX on arduino platform

I am doing a small parser that should convert a string into an Hexadecimal value,I am using arduino as platform but I am getting stack with it.
My string is data = "5449"
where each element is an char, so I would like to translate it to a HEX value like dataHex = 0x54 0x59, and finally those values should be translate to ASCII as dataAscii= TI
How can I do this?
I was thinking of splitting it into an char array with dataCharArray = 54 49 and later converting those values to the chars T and I, but I am not sure whether or not that is the best way.
Thanks in advance,
regards!
I don't have arduino installed in my PC right now, so let's hope the following works:
char nibble2c(char c)
{
if ((c>='0') && (c<='9'))
return c-'0' ;
if ((c>='A') && (c<='F'))
return c+10-'A' ;
if ((c>='a') && (c<='a'))
return c+10-'a' ;
return -1 ;
}
char hex2c(char c1, char c2)
{
if(nibble2c(c2) >= 0)
return nibble2c(c1)*16+nibble2c(c2) ;
return nibble2c(c1) ;
}
String hex2str(char *data)
{
String result = "" ;
for (int i=0 ; nibble2c(data[i])>=0 ; i++)
{
result += hex2c(data[i],data[i+1]) ;
if(nibble2c(data[i+1])>=0)
i++ ;
}
return result;
}

Resources