I can't print number inside an array in Arduino - arduino

I want to print value in an array (array name Array_index) which I write of variable name bit_1. But when I tried to enter inside this array, the value always show zero. Please advise me how to do a correct way in Arduino.
This is my code:
int test_number = 0;
unsigned int Array_index[] = {};
int bit_1 = 0;
int Andbit = 0;
int arrSize = 0;
void setup()
{
Serial.begin( 9600 );
}
void loop()
{
int count = 0;
test_number = random(10);
Serial.println(test_number);
for (bit_1 = 0; bit_1 <= 15; bit_1++)
{
Andbit = test_number & 1;
if (Andbit == 1)
{
Array_index[count] = bit_1;
//Serial.println(Array_index[count]);
count=count++;
}
else
{
}
test_number = test_number >> 1;
int arrSize = sizeof(Array_index) / sizeof( int );
Serial.println(arrSize);
for (int y = 0; y < arrSize; y++)
{
Serial.println(Array_index[y]);
}
}
while(1)
{
}
}

unsigned int Array_index[] = {}; is an array with 0 elements.
You should define it as unsigned int Array_index[16];.

Related

Maximum Xor between Two Arrays | Trie

Given two integer vectors A and B, we have to pick one element from each vector such that their xor is maximum and we need to return this maximum xor value from the function int Solution::solve(vector &A, vector &B).
I found out that the code below is not passing all the test cases when I'm declaring and initializing the head pointer globally right beneath the class Trienode. Why is that?
Code
class Trienode
{
public:
Trienode* left;
Trienode* right;
Trienode()
{
left=0;
right=0;
}
};
// Trienode* head = new Trienode;
int Max_Xor_Pair(Trienode* head, vector<int> B)
{
int n=B.size();
int max_xor=INT_MIN;
for(int i=0; i<n; i++)
{
int pair1 = B[i];
int pair2 = 0;
Trienode* curr=head;
for(int j=31; j>=0; j--)
{
int bit = (pair1>>j)&1;
if(bit)
{
if(curr->left)
curr=curr->left;
else
{
curr=curr->right;
pair2 += pow(2,j);
}
}
else
{
if(curr->right)
{
curr=curr->right;
pair2 += pow(2,j);
}
else
curr=curr->left;
}
}
int curr_xor = pair1 ^ pair2;
max_xor = max(max_xor, curr_xor);
}
return max_xor;
}
void Insert(Trienode* head, int num)
{
Trienode* curr=head;
for(int i=31; i>=0; i--)
{
int x = num;
int bit= (x>>i)&1;
if(bit)
{
if(!curr->right)
{
Trienode* temp = new Trienode;
curr->right=temp;
}
curr=curr->right;
}
else
{
if(!curr->left)
{
Trienode* temp = new Trienode;
curr->left=temp;
}
curr=curr->left;
}
}
}
int Solution::solve(vector<int> &A, vector<int> &B) {
Trienode* head = new Trienode;
for(int x:A)
Insert(head,x);
return Max_Xor_Pair(head,B);
}
Sample Input
A : [ 15891, 6730, 24371, 15351, 15007, 31102, 24394, 3549, 19630, 12624, 24085, 19955, 18757, 11841, 4967, 7377, 13932, 26309, 16945, 32440, 24627, 11324, 5538, 21539, 16119, 2083, 22930, 16542, 4834, 31116, 4640, 29659, 22705, 9931, 13978, 2307, 31674, 22387, 5022, 28746, 26925, 19073, 6271, 5830, 26778, 15574, 5098, 16513, 23987, 13291, 9162 ]
B : [ 18637, 22356, 24768, 23656, 15575, 4032, 12053, 27351, 1151, 16942 ]
When head is a global variable, and you don't have this line in Solution::solve:
Trienode* head = new Trienode;
...then head will retain its value after the first test case has finished, and so the second test case will not start with an empty tree. Each test case will add more nodes to the one tree. Of course this means that, except for the first test case, the tree rooted by head is not the intended tree.
To make the version with the global variable work, reset it in Solution::solve:
head->left = head->right = nullptr;
BTW, you should also initialise these members with nullptr (instead of 0) in your TrieNode constructor. This better reflects the intent.
You can also go with this approach:
Code:
struct Node {
Node* left;
Node* right;
};
class MaxXorHelper{
private : Node* root;
public :
MaxXorHelper() {
root = new Node();
}
void addElements(vector<int> &arr) {
for(int i=0; i<arr.size(); i++) {
Node* node = root;
int val = arr[i];
for(int j=31; j>=0; j--) {
int bit = (val >> j) & 1;
if(bit == 0) {
if(!node->left) {
node->left = new Node();
}
node = node->left;
}
else {
if(!node->right) {
node->right = new Node();
}
node = node->right;
}
}
}
}
int findMaxXor(vector<int> &arr) {
int maxXor = INT_MIN;
for(int i=0; i<arr.size(); i++) {
Node* node = root;
int val2 = 0;
int val1 = arr[i];
for(int j=31; j>=0; j--) {
int bit = (val1 >> j) & 1;
if(bit == 0) {
if(node->right) {
val2 |= (1 << j);
node = node->right;
} else{
node = node->left;
}
}
else {
if(node->left) {
node = node->left;
} else{
val2 |= (1 << j);
node = node->right;
}
}
}
int curXor = val1 ^ val2;
maxXor = max(maxXor, curXor);
}
return maxXor;
}
};
int Solution::solve(vector<int> &A, vector<int> &B) {
MaxXorHelper helper;
helper.addElements(A);
return helper.findMaxXor(B);
}

Problem with a Arduino exercise and state

In this part of the code, I need to turn on two leds if the button is pressed for a continuous period of time of over 2 seconds. I need this code for a complexer exercise but I can't understand why it won't pass to etat_choix. (code right below)
const int ledmode1 = 10;
const int ledmode2 = 11;
const int buttonin = 4;
const int eteint = 0;
const int etat_choix = 1;
bool etat = 0;
bool debut = 0;
bool old_buttonin = 0;
unsigned long temps = 0;
unsigned long time1 = 0;
void setup()
{
pinMode(ledmode1, OUTPUT);
pinMode(ledmode2, OUTPUT);
pinMode(buttonin,INPUT);
}
void loop() {
temps = millis();
if (etat == eteint){
old_buttonin = buttonin;
if (buttonin == HIGH and debut == 0) {
time1 = millis();
}
if (buttonin == HIGH) {
debut = 1;
}
else if (old_buttonin == HIGH and buttonin == LOW ){
debut = 0;
}
if ( temps > time1 + 2000 and debut == 1) {
etat = etat_choix;
time1 = 0;
debut = 0;
}
}
else if (etat == etat_choix) {
digitalWrite(ledmode1,HIGH);
digitalWrite(ledmode2,HIGH);
}

How to convert Ximea xiAPI camera data into QImage?

I have data from a camera in mono 8bit.
This is converted into an int vector using
std::vector<int> grayVector(size);
// convert / copy pointer data into vector: 8 bit
if (static_cast<XI_IMG_FORMAT>(format) == XI_MONO8)
{
quint8* imageIterator = reinterpret_cast<quint8*> (pMemVoid);
for (size_t count = 0; count < size; ++count)
{
grayVector[count] = static_cast<int>(*imageIterator);
imageIterator++;
}
}
Next, I need to convert this into a QImage. If I set the image format to QImage::Format_Mono the app crashes. With QImage::Format_RGB16 I get strippes, and with QImage::Format_RGB32 everything is black.
I would like to know how to do this the best, efficient and correct way?
// convert gray values into QImage data
QImage image = QImage(static_cast<int>(sizeX), static_cat<int>(sizeY), QImage::Format_RGB16);
for ( int y = 0; y < sizeY; ++y )
{
int yoffset = sizeY*y;
QRgb *line = reinterpret_cast<QRgb *>(image.scanLine(y)) ;
for ( int x = 0; x < sizeX ; ++x )
{
int pos = x + yoffset;
int color = grayVector[static_cast<size_t>(pos)];
*line++ = qRgb(color, color, color);
}
}
The conversion to int is unnecessary and you do it in a very inefficient way; all you need is to use the QImage::Format_Grayscale8 available since Qt 5.5 (mid-2015).
Anyway, what you really want is a way to go from XI_IMG to QImage. The default BP_UNSAFE buffering policy should be adequate - the QImage will do a format conversion, so taking the data from XiApi's internal buffer is OK. Thus the following - all of the conversions are implemented in Qt and are quite efficient - much better than most any naive code.
I didn't check whether some Xi formats may need a BGR swap. If so, then the swap can be set to true in the format selection code and the rest will happen automatically.
See also: xiAPI manual.
static QVector<QRgb> grayScaleColorTable() {
static QVector<QRgb> table;
if (table.isEmpty()) {
table.resize(256);
auto *data = table.data();
for (int i = 0; i < table.size(); ++i)
data[i] = qRgb(i, i, i);
}
return table;
}
constexpr QImage::Format grayScaleFormat() {
return (QT_VERSION >= QT_VERSION_CHECK(5,5,0))
? QImage::Format_Grayscale8
: QImage::Format_Indexed8;
}
QImage convertToImage(const XI_IMG *src, QImage::Format f) {
Q_ASSERT(src->fmt == XI_MONO16);
Q_ASSERT((src->padding_x % 2) == 0);
if (src->fmt != XI_MONO16) return {};
const quint16 *s = static_cast<const quint16*>(src->bp);
const int s_pad = src->padding_x/2;
if (f == QImage::Format_BGR30 ||
f == QImage::Format_A2BGR30_Premultiplied ||
f == QImage::Format_RGB30 ||
f == QImage::Format_A2RGB30_Premultiplied)
{
QImage ret{src->width, src->height, f};
Q_ASSERT((ret->bytesPerLine() % 4) == 0);
const int d_pad = ret->bytesPerLine()/4 - ret->width();
quint32 *d = (quint32*)ret.bits();
if (s_pad == d_pad) {
const int N = (src->width + s_pad) * src->height - s_pad;
for (int i = 0; i < N; ++i) {
quint32 const v = (*s++) >> (16-10);
*d++ = 0xC0000000 | v << 20 | v << 10 | v;
}
} else {
for (int j = 0; j < src->height; ++j) {
for (int i = 0; i < src->width; ++i) {
quint32 const v = (*s++) >> (16-10);
*d++ = 0xC0000000u | v << 20 | v << 10 | v;
}
s += s_pad;
d += d_pad;
}
}
return ret;
}
QImage ret{src->width, src->height, grayScaleFormat()};
const int d_pad = ret->bytesPerLine() - ret->width();
auto *d = ret.bits();
if (s_pad == d_pad) {
const int N = (src->width + s_pad) * src->height - s_pad;
for (int i = 0; i < N; ++i) {
*d++ = (*s++) >> 8;
} else {
for (int j = 0; j < src->height; ++j) {
for (int i = 0; i < src->width; ++i)
*d++ = (*s++) >> 8;
s += s_pad;
d += d_pad;
}
}
return ret;
}
QImage fromXiImg(const XI_IMG *src, QImage::Format dstFormat = QImage::Format_ARGB32Premultiplied) {
Q_ASSERT(src->width > 0 && src->height > 0 && src->padding_x >= 0 && src->bp_size > 0);
Q_ASSERT(dstFormat != QImage::Format_Invalid);
bool swap = false;
int srcPixelBytes = 0;
bool externalConvert = false;
QImage::Format srcFormat = QImage::Format_Invalid;
switch (src->fmt) {
case XI_MONO8:
srcPixelBytes = 1;
srcFormat = grayScaleFormat();
break;
case XI_MONO16:
srcPixelBytes = 2;
externalConvert = true;
break;
case XI_RGB24:
srcPixelBytes = 3;
srcFormat = QImage::Format_RGB888;
break;
case XI_RGB32:
srcPixelBytes = 4;
srcFormat = QImage::Format_RGB32;
break;
};
if (srcFormat == QImage::Format_Invalid && !externalConvert) {
qWarning("Unhandled XI_IMG image format");
return {};
}
Q_ASSERT(srcPixelBytes > 0 && srcPixelBytes <= 4);
int bytesPerLine = src->width * srcPixelBytes + src->padding_x;
if ((bytesPerLine * src->height - src->padding_x) > src->bp_size) {
qWarning("Inconsistent XI_IMG data");
return {};
}
QImage ret;
if (!externalConvert)
ret = QImage{static_cast<const uchar*>(src->bp), src->width, src->height,
bytesPerLine, srcFormat};
else
ret = convertToImage(src, dstFormat);
if (ret.format() == QImage::Format_Indexed8)
ret.setColorTable(grayScaleColorTable());
if (ret.format() != dstFormat)
ret = std::move(ret).convertToFormat(dstFormat);
if (swap)
ret = std::move(ret).rgbSwapped();
if (!ret.isDetached()) // ensure that we don't share XI_IMG's data buffer
ret.detach();
return ret;
}

Incremental index doesn't change at end of for loop

I want to interface Arduino with PLC to pull some information.
My problem is at Function 3: Set alarm flag / reset flag. This function is used to compare history value and present value. I tried to process some integer number (test_number) and process like binary 16 bits data for finding 1 at some bit. I found the for loop in Findbit function, which should repeat 16 times, runs infinitely. It does not change the incremental index (variable name bit_1) which is still stuck at 1.
This is my code :
int test_number_array[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int test_number = 0;
int bit_1 = 0;
int Andbit = 0;
const char* message;
int flagAlarm[2][16] = {};
int flagReset[2][16] = {};
void setup()
{
// put your setup code here, to run once:
Serial.begin( 9600 );
}
void loop()
{
// put your main code here, to run repeatedly:
for (int j = 1; j <= 2; j++)
{
for (int i = 1; i <= 2; i++) // Example with 2 modbus address
{
unsigned int address = 40000 + i;
Serial.print ("Modbus address = ");
Serial.println(address, DEC);
pull_data(i);
Serial.print("Test number is ");
Serial.println(test_number);
Findbit(i);
Serial.println("------------------------------------------------- ");
}
}
while (1)
{
}
}
// ---------------Function 1 : Function finding alarm bit-----------------//
void Findbit(int i)
{
for (bit_1 = 0; bit_1 <= 15; bit_1++)
{
Andbit = test_number & 1;
Serial.print("Test number (BINARY) is ");
Serial.println(test_number, BIN);
Serial.print("Check at bit number ");
Serial.println(bit_1);
Serial.print("And bit is ");
Serial.println(Andbit, BIN);
Serial.print("flagAlarm(Before1) = ");
Serial.println(flagAlarm[i][bit_1]);
Serial.print("flagreset(Before1) = ");
Serial.println(flagReset[i][bit_1]);
if (Andbit == 1) //found "1" pass into loop
{
flagAlarm[i][bit_1] = 1;
}
else
{
}
Serial.print("flagAlarm(Before2) = ");
Serial.println(flagAlarm[i][bit_1]);
Serial.print("flagreset(Before2) = ");
Serial.println(flagReset[i][bit_1]);
Set_reset_flag(i,bit_1);
test_number = test_number >> 1;
Serial.print("flagAlarm(After) = ");
Serial.println(flagAlarm[i][bit_1]);
Serial.print("flagreset(After) = ");
Serial.println(flagReset[i][bit_1]);
Serial.println(" ");
}
}
// -----------------------Function 2 : Pull data------------------------- //
int pull_data(int i)
{
i = i - 1;
test_number = test_number_array[i];
return test_number;
}
// -------------Function 3 : Set alarm flag / reset flag ---------------- //
void Set_reset_flag(int i, int bit_1)
{
Serial.print("i = ");
Serial.println(i);
Serial.print("bit_1 = ");
Serial.println(bit_1);
if (flagAlarm[i][bit_1] == 1 && flagReset[i][bit_1] == 0)
{
Serial.print("Alarm at bit ");
Serial.println(bit_1);
flagAlarm[i][bit_1] = 0;
flagReset[i][bit_1] = 1;
}
else if (flagAlarm[i][bit_1] == 0 && flagReset[i][bit_1] == 1)
{
Serial.print("Reset Alarm at bit ");
Serial.println(bit_1);
flagReset[i][bit_1] = 0;
}
else if (flagAlarm[i][bit_1] == 1 && flagReset[i][bit_1] == 1)
{
Serial.print("Alarm still active at bit ");
Serial.println(bit_1);
flagAlarm[i][bit_1] = 0;
flagReset[i][bit_1] = 1;
}
else
{
}
}
Could it be that your bit_1 variable is modified from some other code not mentioned here, or get optimized at all? Also, is it necessary to make a loop counter a global variable? Can you declare it inside the Findbit function?

Getting segmentation fault (or bad access) for some inputs and the program halts

#include <iostream>
#include <vector>
#include <string>
using namespace std;
void step_selection_sort(vector <int> &a, int size, int idx){
int i,j,min,temp;
i = idx;
min = i;
for (j=i+1;j<size;j++)
{
if (a[min]>a[j])
min=j;
}
if (min!=i)
{
temp = a[i];
a[i] = a[min];
a[min] = temp;
}
idx++;
}
void selection_sort(vector <int> &a, int size, int idx){
int i;
for(i=0;i<size;i++)
{
step_selection_sort(a,size,idx);
}
}
void step_desc_sort(vector <int>& a, int size, int idx){
int i,j,max,temp;
i = idx;
max = i;
for (j=i+1;j<size;j++)
{
if (a[max]<a[j])
max=j;
}
if (max!=i)
{
temp = a[i];
a[i] = a[max];
a[max] = temp;
}
idx++;
}
void desc_sort(vector <int>& a, int size, int idx){
int i;
for(i=0;i<size;i++)
{
step_desc_sort(a,size,idx);
}
}
void swap (int & a, int & b)
{
int t = a;
a = b;
b = t;
}
int findCeil (vector <int>& nums, int first, int begin, int end)
{
int ceilIndex = begin;
for (int i = begin+1; i <= end; i++)
if (nums[i] > first && nums[i] < nums[ceilIndex])
ceilIndex = i;
return ceilIndex;
}
int findBottom(vector <int>& nums,int first,int begin,int end)
{
int bottomIndex = begin;
for (int i = begin+1; i <= end; i++)
if (nums[i] < first && nums[i] > nums[bottomIndex])
bottomIndex = i;
return bottomIndex;
}
void sortedPermutations_ASC (vector <int> nums,int num)
{
bool isfinished=false;
if(isfinished==false)
for(int i=0;i<num;i++)
cout << nums[i]; //bad access when giving inputs bigger than 8
cout << endl;
int k;
for ( k = num - 2; k >= 0; --k )
if (nums[k] < nums[k+1])
break;
if ( k == -1 )
isfinished=true;
else
{
int ceilIndex = findCeil( nums, nums[k], k + 1, num - 1 );
swap( nums[k], nums[ceilIndex] );
selection_sort(nums,num,k+1);
sortedPermutations_ASC(nums,num);
}
}
void sortedPermutations_DESC (vector <int> nums,int num)
{
int i;
bool isfinished=false;
if(isfinished==false)
for(i=0;i<num;i++)
cout << nums[i];
cout << endl;
int k;
for ( k = num - 2; k >= 0; --k )
if (nums[k] > nums[k+1])
break;
if ( k == -1 )
isfinished=true;
else
{
int bottomIndex = findBottom( nums, nums[k], k + 1, num - 1 );
swap( nums[k], nums[bottomIndex] );
desc_sort(nums,num,k+1);
sortedPermutations_DESC(nums,num);
}
return;
}
int main(){
vector <int> nums;
string line,temp;
int num,j,k;
getline(cin,line);
while(j<line.size() && line[j]!=' ')
j++;
num=stoi(line.substr(0,j));
string kind;
j++;
kind=line.substr(j);
if(kind=="ASC"){
for(k=0;k<num;k++)
nums.push_back(k+1);
sortedPermutations_ASC(nums,num);
}
if(kind=="DESC"){
for(k=0;k<num;k++)
nums.push_back(num-k);
sortedPermutations_DESC(nums,num);
}
return 0;
}
here's is my code. it gives the permutations of a number.It works properly when inputs are between 1 and 8 .But it doesn't work with numbers bigger than 8 .
for example if I give
9 ASC (it means in Ascending order)
to the program , I get "Segmentation Fault:11" in terminal (mac) after printing some of the permutations .
I tried running it in Xcode . with the same input it says :
Thread 1:EXC_BAD_ACCESS(code=2,address=0x7ffff5f3fffc8)
for the line that I put comment in front of it .
I don't know what to do anymore ...
Any help would be appreciated - thanks in advance

Resources