Arduino or c++ working with array in parameter of function - c++

void setup() {
Serial.begin(9600);
printArr([64,67]);
}
void loop() {}
void printArr(byte nilai[]) {
for (byte c = 0; c < length(nilai); c++) {
Serial.println(nilai[c]);
}
}
I expect the program print char of number 64 and 67 in ASCII since it was iterated in array, but instead the compiler give me error
C:\Users\User\Documents\Arduino\sketch_apr18a\sketch_apr18a.ino:10:24: note: suggested alternative: 'long'
for (byte c = 0; c < length(nilai); c++) {
^~~~~~
long
exit status 1
expected identifier before numeric constant

A solving can be:
void setup() {
Serial.begin(9600);
byte arr [] = {64,67};
printArr(arr, 2);
}
void loop() {}
void printArr(byte *nylai, unsigned d) {
for (byte c = 0; c < d; c++) {
Serial.println(*(nylai + c * sizeof(byte)));
}
}

Related

How an enum is convert when it is out of index in C

In C++, I see
#include <iostream>
typedef enum {
NORMAL = 0,
EXTENDED
} CyclicPrefixType_t;
void func (CyclicPrefixType_t x) {
if(x < NORMAL){
printf ("lower\n");
}else{
printf ("higher\n");
}
}
int main (void) {
//MUST CAST OR WE GET ERROR
CyclicPrefixType_t cpType = CyclicPrefixType_t(NORMAL - 1);
func (cpType);
return 0;
}
Run the code on C++
Expected: lower > It is OK
But in C,
#include <stdio.h>
typedef enum {
NORMAL = 0,
EXTENDED
} CyclicPrefixType_t;
void func (CyclicPrefixType_t x) {
if(x < NORMAL){
printf ("lower\n");
}else{
printf ("higher\n");
}
}
int main (void) {
//NO NEED TO CAST
CyclicPrefixType_t cpType = (NORMAL - 1);
func (cpType);
return 0;
}
Run the code on C
Actually Result: Higher >
It is NOT OK
In this case, (-1) is automatically cast to another value.
Anyone can tell me which value is here and how it is converted to
Because if you print it(%d), It will still (-1)

How do I sort structures (consisting of several different elements) using qsort?

Specifically it's about a list in a .txt file,"char Name"(jmeno) "char Surname"(prijmeni) "float Average"(prumer) --> students with average of their grades (grading 1-5), sorted with qsort according to the average.
My code so far looks like this:
FILE *otevriSoubor(char *jmeno, char* mode)
{
FILE *soubor;
soubor = fopen(jmeno, mode);
if (!soubor)
{
printf("spatne jmeno souboru\n");
system("PAUSE");
exit(1);
}
return soubor;
}
int srovnaniprumeru(const void *a, const void *b)
{
int c = ((Student *) a)->prumer;
int d = ((Student *) b)->prumer;
if (c > d) return -1;
if (c < d) return 1;
return 0;
}
int main(void)
{
typedef struct
{
char jmeno[MAXDELKA];
char prijmeni[MAXDELKA];
float prumer;
} Student;
qsort(bakaweb, 5, sizeof(Student), srovnaniprumeru);
system("PAUSE");
return 0;
}
You are on the right track. Here are areas for improvement:
Your code is incomplete: you do not read the student details. You can use fscanf() for that.
You sort based on the conversion of the grades to int. This might be incorrect if the grades are not whole numbers.
Complete your code and fix your sorting function this way:
int srovnaniprumeru(const void *a, const void *b) {
float c = ((const Student *)a)->prumer;
float d = ((const Student *)b)->prumer;
if (c > d) return -1;
if (c < d) return 1;
return 0;
}

Arduino: overriding Print class problems

I am trying to make a library for redirection of data printed to Print class. I am unfortunately stuck on error that reads
error: cannot declare variable 'diagData' to be of abstract type 'PrintToString'
note: because the following virtual functions are pure within 'PrintToString'
note: virtual size_t PrintToString::write(uint8_t)
I tried several variations of how to implement this but with no luck. (Sourced from the internet)
Links
Print class: github.com/ Print.h and Print.cpp
My code
PrintToString.h
#ifndef PRINT_TO_STRING_H
#define PRINT_TO_STRING_H
#include <Arduino.h>
class PrintToString : public Print
{
private:
String* data;
public:
PrintToString();
~PrintToString();
String* results();
void clear();
size_t write(uint8_t) = 0;
size_t write(const uint8_t* buffer, size_t size);
};
#endif
PrintToString.cpp
#include "PrintToString.h"
PrintToString::PrintToString()
{
data = new String();
}
PrintToString::~PrintToString()
{
delete data;
data = NULL;
}
String* PrintToString::results()
{
return data;
}
void PrintToString::clear()
{
delete data;
data = new String();
}
size_t PrintToString::write(const uint8_t* buffer, size_t size)
{
size_t n = 0;
while (size--)
{
if (data->concat(*buffer++))
n++;
else
break;
}
return n;
}
TestSketch.ino (I have left out content of all the constants)
#include <ESP8266WiFi.h>
#include <PrintToString.h>
const char* WIFI_SSID
const char* WIFI_PASS
const char* API_HOST
const uint16_t API_PORT
const uint16_t LOCAL_UDP_PORT
WiFiUDP UDPClint;
PrintToString diagData;
uint64_t packetNumber = 0;
void setup()
{
WiFi.begin(WIFI_SSID, WIFI_PASS);
UDPClint.begin(LOCAL_UDP_PORT);
while (WiFi.status() != WL_CONNECTED)
delay(500);
WiFi.printDiag(diagData);
sendStringPacket(diagData.result());
diagData.clear();
}
void loop()
{
delay(1000);
}
void sendStringPacket(String payload)
{
UDPClint.beginPacket(API_HOST, API_PORT);
uint64_t thisPNumber = packetNumber++;
String thisPNumberStr;
while (thisPNumber > 0)
{
uint8_t digit = thisPNumber % 10;
thisPNumberStr.concat(digit);
thisPNumber /= 10;
}
UDPClint.write(';');
for (uint64_t i = 0; i < payload.length(); i++)
UDPClint.write(payload.charAt(i));
UDPClint.endPacket();
}
This is because this class has a pure virtual function here:
size_t write(uint8_t) = 0;
A class with a pure virtual function cannot be instantiated. So method write(uint8_t) must be somehow implemented in your code.
EDIT: Consider making use of the code you used in sendStringPacket() for write(uint8_t). You may be able to redirect output without using sendStringPacket(diagData.result()); statement.

qualified-id in declaration before '=' token / object counter variable

I'm trying to count how many instances or the class mole2 there are and store the number in a public static variable called mole_count.
mole2.h
#ifndef mole2_h
#define mole2_h
#include "Arduino.h"
class mole2 {
public:
mole2(int input, int output);
void popUp();
void popdown();
boolean moleBrainThinkPopUpNow();
void setUpTimer(int up_timer);
boolean didMoleGetHit();
void setRecoveryTimer(int recovery_timer);
void decrementRecoveryTimer();
boolean dosePlayerMistMole();
void moleReset();
int input, output;
static int mole_count;
static int odds_of_poping;
private:
boolean _is_popped = false;
int _up_timer = 0;
int _recovery_timer = 0;
};
#endif
mole2.cpp
#include "Arduino.h"
#include "mole2.h"
int mole2::odds_of_poping = 10;
mole2::mole2(int input, int output) {
input = input;
output = output;
int mole2::mole_count = mole2::mole_count + 1;
pinMode(input, INPUT);
pinMode(output, OUTPUT);
}
void mole2::popUp() {
_is_popped = true;
digitalWrite(input, HIGH);
}
void mole2::popdown() {
_is_popped = false;
digitalWrite(input, LOW);
}
boolean mole2::moleBrainThinkPopUpNow() {
if (_recovery_timer == 0 && _is_popped == false && rand() % odds_of_poping == 1) {
popUp();
return true;
}
else {
return false;
}
}
void mole2::setUpTimer(int up_timer) {
_up_timer = up_timer;
}
boolean mole2::didMoleGetHit() {
if (_is_popped == true && digitalRead(input) == HIGH) {
popdown();
_up_timer = 0;
return true;
}
else {
return false;
}
}
void mole2::setRecoveryTimer(int recovery_timer) {
_recovery_timer = recovery_timer;
}
void mole2::decrementRecoveryTimer() {
if (_recovery_timer > 0) {
_recovery_timer--;
}
}
boolean mole2::dosePlayerMistMole() {
if (_is_popped == true && _up_timer > 0) {
_up_timer--;
}
if (_is_popped == true && _up_timer == 0) {
popdown();
return true;
}
else {
return false;
}
}
void mole2::moleReset() {
popdown();
_up_timer = 0;
_recovery_timer = 0;
}
FullError
Arduino: 1.6.12 (Windows 7), Board: "Arduino/Genuino Uno"
C:\Users\Strings\Documents\Arduino\libraries\mole2\mole2.cpp: In constructor 'mole2::mole2(int, int)':
C:\Users\Strings\Documents\Arduino\libraries\mole2\mole2.cpp:9:25: error: qualified-id in declaration before '=' token
int mole2::mole_count = mole2::mole_count + 1;
^
exit status 1
Error compiling for board Arduino/Genuino Uno.
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
First this:
int mole2::mole_count = mole2::mole_count + 1;
has no sense: you're declaring something and assigning it to its value + 1
Anyway, you already declared mole_count in your class. Since you're in the constructor, you're in the mole2 class already (the "qualified-id" bit comes from here), so you just have to do:
mole_count++;
Also, you have to declare storage for the variable in the .cpp class & initialize it:
int mole2::mole_count = 0;
You have to do the same thing as with odds_of_poping:
Definition:
int mole2::mole_count = 0; // initialization can be ommited as static variables are initialized to the default value
and later just increment: ++mole_count;
int mole2::mole_count has already been defined. This is trying to make another int mole2::mole_count. Lose the int and assign to the pre-existing variable.
You also need to allocate storage for and initialize mole_count. Place
int mole2::mole_count = 0; // replace 0 if starting with more than 0 mole2s
in somewhere around
int mole2::odds_of_poping = 10;
in mole2.cpp
Also watch out for
input = input;
output = output;
The compiler doesn't know whether you want to use the passed parameter input or the class's input so it will pick the closest defined input, the parameter, on both sides of the = . Refrain from reusing the same variable names in the same places at the same times.
This can be resolved by explicitely stating
this->input = input;
this->output = output;
Or (my favourite!) by using the member initializer list
mole2::mole2(int input, int output): input(input), output(output) {
But to prevent other confusion you should still not repeat the names.

Passing Arrays In a Library Arduino

I am trying to write a library that reads 5 variables, then sends them through the serial port to a bluetooth reciever, I am getting a number of errors and I am not sure where to go from here, do I need to implement pointers?
Here is the Arduino code....
#include <serialComms.h>
serialComms testing;
void setup()
{
Serial.begin(9600);
}
char data[] = {1,2,3,4,5,6};
void loop()
{
for(int t = 0;t<6;t++)
{
data[t] = data[t]++;
}
testing.updateUser(data);
delay(250);
}
serialComms.cpp
#include <Arduino.h>
#include <serialComms.h>
void serialComms::init()
{
// This is where the constructor would be...right now we are too stupid to have one
}
void serialComms::readAllBytes() // Target Pin,Values
{
}
void serialComms::assignBytes()
{
for(int t = 0;t<5;t++)
{
digitalWrite(12,HIGH);
delay(250);
digitalWrite(12,LOW);
}
}
void serialComms::updateUser(char t[])
{
Serial.write(t,5);
}
serialComms.h
#ifndef serialComms_h
#define serialComms_h
/* serialComms Class */
class serialComms
{
public:
serialComms() {};
void init();
void readAllBytes(); // Will be used to create the array --> two variables for now...
void assignBytes();
void updateUser(char t[]);
};
#endif
Here are the errors that I am getting...
- serialComms.cpp:28: error: initializing argument 1 of 'virtual size_t Print::write(const uint8_t*, size_t)'
-
- serialComms.cpp:28: error: invalid conversion from 'char*' to 'const uint8_t*'
- serialComms.cpp: In member function 'void serialComms::updateUser(char*)':
- serialComms.cpp:27: error: expected primary-expression before ']' token
Example:
void setup()
{
Serial.begin(9600);
char string_array[] = "hello";
char data_array[] = {1,2,3,4,5,6};
unsigned char data_array_uchar[] = {21,22,23,24,25,26};
uint8_t uint8_array[] = {11,12,13,14,15,16};
char alpha_array[] = {0x41,0x42,0x43,0x44,0x45,0x46};
// take note that sizeof() is a precompile command... number of places/size of each place.
updateUserPrint(string_array);
updateUserWrite(data_array, sizeof(string_array));
updateUserWriteUchar(data_array_uchar, sizeof(data_array_uchar));
updateUserWriteUchar(uint8_array, sizeof(uint8_array));
updateUserWriteUint(uint8_array, sizeof(string_array));
updateUserAlpha(alpha_array, sizeof(string_array));
}
void updateUserPrint(char *s)
{ //note a string aka array of char's is ended with a null.
Serial.print(s); // this can detect.
Serial.println();
}
void updateUserWrite(char *t, size_t len)
{ //note an array of int's is not ended with a null. so you need to know how long it is.
for (int n = 0; n < len ; n++) {
Serial.print(t[n],DEC);
Serial.print(",");
}
Serial.println();
}
void updateUserWriteUchar(unsigned char *t, size_t len)
{ //note an array of int's is not ended with a null. so you need to know how long it is.
for (int n = 0; n < len ; n++) {
Serial.print(t[n],DEC);
Serial.print(",");
}
Serial.println();
}
void updateUserWriteUint(uint8_t *t, size_t len)
{ //note an array of int's is not ended with a null. so you need to know how long it is.
for (int n = 0; n < len ; n++) {
Serial.print(t[n],DEC);
Serial.print(",");
}
Serial.println();
}
void updateUserAlpha(char *t, int len)
{ //note an array of int's is not ended with a null. so you need to know how long it is.
for (int n = 0; n < len ; n++) {
Serial.write(t[n]);
}
Serial.println();
}
produces the following:
hello
1,2,3,4,5,6,
21,22,23,24,25,26,
11,12,13,14,15,16,
11,12,13,14,15,16,
ABCDEF
Serial.write can only send constant strings like
Serial.write(“hello”);
That is why the error error: invalid conversion from 'char*' to 'const uint8_t*'
use as
char temp[max_length];
sprintf(temp,"%s",t);
Serial.write(temp);