Arduino 'for' error - arduino

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

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.

C++ Vector understanding

I am currently using codewars.com to practice my coding skills. I finished one of the problems and wanted to check what other people's solutions were and I found one I couldn't understand. It's much better than my solution and I would like to understand it more. such what does "*std" do exactly. what is the +=i doing to the min_elements and what is happening to the min elements?
long queueTime(std::vector<int> customers,int n){
std::vector<long> queues(n, 0);
for (int i : customers)
*std::min_element(queues.begin(), queues.end()) += i;
return *std::max_element(queues.cbegin(), queues.cend());
}
This was my solution:
#include <iostream>
#include <vector>
#include <array>
using namespace std;
long queueTime(std::vector<int> customers,int n){
int i = 0; //start of Queue
int count = 0; //keeps track of how many items has been
processed
int biggest = 0; //Last/largest ending item size, add to count at end
int list [n]; //Declared number of registers by size n
for(int k = 0;k<n;k++) //sets each existing register to have 0
items
{
list[k] = 0;
}
//Start of processing customers, ends when last customer is at register.
for (auto i = customers.begin(); i!=customers.end();)
{
//checks if there are free registers.
for(int index = 0; index<n && i!=customers.end();index++)
{
if(list[index]==0)
{
list[index] = *i;
i++;
}
}
//Subtract 1 from every register
int temp=0;
for (int k =0;k<n;k++)
{
if(list[k]!= 0)
{
temp = list[k];
temp = temp-1;
list[k] = temp;
}
}
//increase count of items processed
count++;
}
//calculates the largest number of items a customer has amungst the last few
customers.
for(int j=0;j<n;j++)
{
if(list[j]>biggest)
{
biggest = list[j];
}
}
//end first part
cout<<"\nCount: "<<count<<" Biggest: "<<biggest<<endl;
cout<<"End Function:"
<<"\n************************\n***************************
*******************\n"<<endl;
//answer if number of items processed + last biggest number of items.
return count+biggest;
}
The code is mapping a set of integers to n buckets and minimizing the sum of the elements assigned to a given bucket.
For each customer int i , the smallest element of the queue is incremented by i. Then the largest resulting queue value is returned.
std::vector is a qualified name lookup of an identifier within the std namespace.
min_element returns an iterator. The dereference operator (*) produces an lvalue that is incremented by a compound assignment operator (+=).

Game of Life Processing

import processing.core.PApplet;
public class gl extends PApplet {
static int neighborCount;
static int screenRows;
int tNC; // Temporary Neighbor Count
int newState;
int columns = 960;
int rows = 477;
int[][] cells = new int[columns][rows];
int[][] newGen = new int[columns][rows];
public static void main(String[] args) {
PApplet.main("gl");
}
public void settings() {
size(1920, 955);
}
public void setup() {
// Set background white and all of cells[][] to 0 or 1
screenRows = 0;
background(255);
for (int j = 0; j < (rows / 2); j++) {
for (int i = 0; i < (columns / 2); i++) {
cells[i][j] = (int) random(0, 2);
}
}
}
public void draw() {
// If program has finished generating this frame, reset everything and set cells[][] equal to newGen[][]
if (screenRows > (height / 2)) {
screenRows = 0;
System.out.println("End of generation reached");
background(255);
cells = newGen.clone();
for (int i = 0; i < columns; i++) {
for (int j = 0; j < rows; j++) {
newGen[i][j] = 0;
}
}
}
// Go through every element in cells[][], determine it's value, and display it
for (int x = 1; x < (width / 2) - 1; x++) {
for (int y = 1; y < (height / 2) - 1; y++) {
printCell(x, y);
}
}
screenRows++;
}
public void printCell(int x, int y) {
setCellState(x, y);
if (newGen[x][y] == 0) {
stroke(255);
fill(255);
} else if (newGen[x][y] == 1) {
stroke(0);
fill(0);
}
System.out.println(x + ", " + y);
rect(x, y, 2, 2);
}
public void setCellState(int x, int y) {
tNC = getNeighborCount(x, y);
neighborCount = 0;
System.out.println(tNC);
if (tNC < 2) { // If less than 2 neighbors, cell dead
newGen[x][y] = 0;
} else if (tNC > 3) { // If more than 3 neighbors, cell dead
newGen[x][y] = 0;
} else if ((tNC == 2 || tNC == 3) && cells[x][y] == 1) { // If 2 or 3 neighbors and cell is alive, do nothing (unnecessary statement but makes visualizing easier)
} else if (tNC == 3 && cells[x][y] == 0) { // If 3 neighbors and cell is dead, cell is alive
newGen[x][y] = 1;
} else if (tNC == 2 && cells[x][y] == 0) { // If 2 neighbors and cel is dead, do nothing (also unnecessary)
} else {
System.out.println("Error in setCellState(int, int);"); // In event of none of the conditions being met
}
tNC = 0; // Reset variable (probably unnecessary but might as well)
}
public int getNeighborCount(int x, int y) {
// Go through each cell adjacent or diagonal to the cell and add it's value (0 or 1) to neighborCount
for (int i = -1; i < 2; i++) {
for (int j = -1; j < 2; j++) {
neighborCount += cells[i + x][j + y];
}
}
// Subtract the value of the cell being evaluated from neighborCount as that is not a factor in the sum of the neighbors
neighborCount -= cells[x][y];
return neighborCount;
}
}
Pastebin
I am just going for functionality over speed, for now.
I am attempting to code Conway's Game of Life using Processing in Eclipse. The above code is dysfunctional in multiple ways:
The generation displayed appears much smaller in the window than I want to be. It only takes up a fraction of the window despite my efforts to counterbalance this by making each cell 2x2 pixels and half as many rows and columns as the window is tall and wide.
Also, the generation does not appear to update in the window after the first generation is displayed after a few seconds.
I noticed that the variable tNC is often equal to 0 when it should be equal to any number from 0 to 7.
You've got three main problems.
Problem 1: You seem to be generating the next generation as you render cells, which might be okay... but then what are you doing with the screenRows logic (the if statement in your draw() function)?
If I were you, I would split your logic up into two sections: write one function that draws your board, and another function that returns a new board based on the current one. Stop trying to calculate the next generation as you're drawing the current generation, as that's just going to give you a ton of headaches.
I also don't think your logic for switching between the arrays is correct. Which array holds the current generation, and which holds the next generation? Are you sure?
Problem 2: You seem to be switching between pixel sizes and array coordinates. For example, you're drawing each cell at its array index coordinate, but you're drawing them as 2x2 rectangles. This doesn't make a ton of sense, since you're just going to draw over top of it with the next cell anyway. Again, separate your logic: create a function that draws a cell based on the window width and height, an array position, and an array length.
Problem 3: Your print statements are killing your framerate. Print statements are notoriously slow. Your framerate is already pretty slow because of all of the calculations you're doing, but it gets even slower when you print out (960*477*2) things every single frame. This isn't really a logic error, but it makes it harder to see exactly what your program is doing.
The Solution: To fix your problems, I'd recommend refactoring your code quite a bit. If I were you, I would start over with a new program. Then:
Step 1: Separate your drawing logic from your logic for calculating the next generation. Create two functions: one for drawing, and another one that returns a new array based on the current one.
Step 2: In your drawing code, make sure you separate your array indexes and your pixel positions. Maybe write another function that takes a cell position and draws a rectangle based on the window size and the array size.
PS: Are you in the same class as this person? Are you using Daniel Shiffman's code too?

Arduino Uno - EEPROM locations not consistant

I was trying to write items to the EEPROM and later read them out. I was finding the reading back I was not getting the same as I put in at times. I narrow down to an example I can show you. Below I read into variables 2 address.
const int start_add_type = (EEPROM.length() - 10);
const int start_add_id = (EEPROM.length() - 4);
I then look at the value (via RS232)
Serial.begin(9600);
Serial.println(start_add_type);
Serial.println(start_add_id);
of them at the start of the setup() and see I get
1014
1020
I then look again at the end
Serial.println(start_add_type);
Serial.println(start_add_id);
and I get
1014
818
I cannot see why this should change. I did try calling them const e.g. const
const int start_add_type = (EEPROM.length() - 10);
const int start_add_id = (EEPROM.length() - 4);
but this gave the same result. So here I sit very puzzled at what I must have missed. Anyone got any idea?
#include "EEPROM.h"
int start_add_type = (EEPROM.length() - 10);
int start_add_id = (EEPROM.length() - 4);
char ID[7] = "ENCPG2";
char Stored_ID[5];
char Input[10];
//String Type;
void setup()
{
Serial.begin(9600);
Serial.println(start_add_type);
Serial.println(start_add_id);
// start_add = (EEPROM.length() - 10); // use this method to be PCB independent.
for (int i = 0; i < 6; i++)
{
Stored_ID[i] = EEPROM.read(start_add_type + i); // Read the ID into the EEPROM.
}
if (Stored_ID != ID) // Check if the one we have got is the same as the one in this code ID[7]
{
for (int i = 0; i < 6; i++)
{
EEPROM.write(start_add_type + i, ID[i]); // Write the ID into the EEPROM.
}
}
Serial.println(start_add_type);
Serial.println(start_add_id);
}
void loop()
{
}
You are overwriting your memory in this loop:
for (int i = 0; i < 6; i++)
{
Stored_ID[i] = EEPROM.read(start_add_type + i);
}
Stored_ID array is 5 bytes long, so writing to Stored_ID[5] will rewrite also the start_add_id variable, thus the weird value 818, which equals to 0x0332 HEX and 0x32 is the '2' character of your ID
For fixing this issue, declare Stored_ID in this way:
char Stored_ID[6];
if (Stored_ID != ID)
This is nonsense: You compare two different addresses, which are never equal. If you want to compare the content, you should do it in a loop. (e.g. directly when reading the EEPROM value into Stored_ID[i] )
Alternatively, Stored_ID could be a 0-terminated text as well and you might use
if (strcmp(Stored_ID, ID) != 0)

Base case condition in quick sort algorithm

For the quick sort algorithm(recursive), every time when it calls itself, it have the condition if(p < r). Please correct me if I am wrong: as far as I know, for every recursive algorithm, it has a condition as the time when it entered the routine, and this condition is used to get the base case. But I still cannot understand how to correctly set and test this condition ?
void quickSort(int* arr, int p, int r)
{
if(p < r)
{
int q = partition(arr,p,r);
quickSort(arr,p,q-1);
quickSort(arr,q+1,r);
}
}
For my entire code, please refer to the following:
/*
filename : main.c
description: quickSort algorithm
*/
#include<iostream>
using namespace std;
void exchange(int* val1, int* val2)
{
int temp = *val1;
*val1 = *val2;
*val2 = temp;
}
int partition(int* arr, int p, int r)
{
int x = arr[r];
int j = p;
int i = j-1;
while(j<=r-1)
{
if(arr[j] <= x)
{
i++;
// exchange arr[r] with arr[j]
exchange(&arr[i],&arr[j]);
}
j++;
}
exchange(&arr[i+1],&arr[r]);
return i+1;
}
void quickSort(int* arr, int p, int r)
{
if(p < r)
{
int q = partition(arr,p,r);
quickSort(arr,p,q-1);
quickSort(arr,q+1,r);
}
}
// driver program to test the quick sort algorithm
int main(int argc, const char* argv[])
{
int arr1[] = {13,19,9,5,12,8,7,4,21,2,6,11};
cout <<"The original array is: ";
for(int i=0; i<12; i++)
{
cout << arr1[i] << " ";
}
cout << "\n";
quickSort(arr1,0,11);
//print out the sorted array
cout <<"The sorted array is: ";
for(int i=0; i<12; i++)
{
cout << arr1[i] << " ";
}
cout << "\n";
cin.get();
return 0;
}
Your question is not quite clear, but I will try to answer.
Quicksort works by sorting smaller and smaller arrays. The base case is an array with less than 2 elements because no sorting would be required.
At each step it finds a partition value and makes it true that all the values to the left of the partition value are smaller and all values to the right of the partition value are larger. In other words, it puts the partition value in the correct place. Then it recursively sorts the array to the left of the partition and the array to right of the partition.
The base case of quicksort is an array with one element because a one element array requires no sorting. In your code, p is the index of the first element and r is the index of the last element. The predicate p < r is only true for an array of at least size 2. In other words, if p >= r then you have an array of size 1 (or zero, or nonsense) and there is no work to do.

Resources