text:
How to save a state - make an arduino run a code only once/make aruduino bahave differently the next time he is on
Im building a arduino based bicycle speedometer. When the code starts the user picks his bike size (which I need to calculate the radius). Then I have a state finite machine where the user taps the button between speed, time and temperature. I need to put this circuit on a battery and it needs to be mounted on a bike. But every time you plug and unplug the battery, the code runs from the beginning again, which I don't want. So every time the user turns the speedometer off then on, he needs to pick his bike size again. Is it possible to save the size he has picked so that the next time he turns it on, it doesn't come across.
So - user has his speedometer, turns it on, picks the bike size, turns it off, then sometime later turns it back on and the part for picking the bike size doesn't show up, it simply "knows" remembers what the user picked last time.
I don't know how could that work, would the Arduino run the certain code only once or is there a function for "the next time Arduino has electricity behave like this".

use the EEPROM library

As one of the comments said, you will need to use the EEPROM library. When you save a variable in your code (e.g. int test = 10;) the variable along with its value gets stored in the RAM. The EEPROM is a piece of harddisk on your arduino that will remember its value when you power off your arduino.
If you implement a power-off button, simply save the state (or in your case, the wheel size) in EEPROM whenever the user inputs it. The next time you power up, you can check if there is a previous value in EEPROM and continue with that value if it exists. Otherwise ask the user for their wheel size.
You might want to implement a reset-button as well, to reset whenever you change bike or wheels. Look up a code example of EEPROM, as there are a lot online.

Alright, thanks. I will look it up, this part "the next time you power up, you can check if there is a previsus value" - that is what I need. And yeah I will implement a reset button, good idea.
Cheers man :)

@MarinFilipovic don’t forget to read eeprom, it will not be in the variable you stored previously

ahaa okay, I get it, thanks

On boot/reset, read the configs from EEPROM. You can keep them in RAM except for when they change. It may help to store distance, calories, and everything else in there too. Don't forget to add some sort of magic number and version so that if it is fresh and not formatted (or you change the data structure) that you can format or convert it. Another possible thing you may want is a variation of wear-leveling, since EEPROM writes aren't free and it gradually wears out. It's good for a guaranteed 100,000 cycles, and usually much further, but if that won't be enough, wear-leveling is a good idea.


text:
How to combine this two sensor code
I have a problem. I don’t know how to combine this two codes & the diagram. My project is about automatic water storage door that using water sensor & rain sensor. The rain sensor will function when rain while the water sensor will control the open/close door. The door will open when it rain but it will remain close when the volume in the water storage is full.the volume of water in tank was controlled by flood sensor(water sensor). Here is the code for two sensor.
rain sensor
const int senmin = 0;
const int senmax = 1024;
int led = 13;
int sensory = A0;
int i;
void setup() {
Serial.begin (9600);
pinMode(led, OUTPUT);
}
void loop() {
int sensor = analogRead(sensory);
int range = map(sensor, senmin, senmax, 0, 3);
switch (range)
{
case 0:
Serial.println("raining");
digitalWrite(led, HIGH);
  break;

case 1:
  Serial.println("not raining");
  digitalWrite(led,LOW);

}
delay(500);
}
water sensor
const int waterSens = A0; //define water sensor
const int led = 9;//define led to pin 9
int waterVal; //define the water sensor value
void setup() {
pinMode(led, OUTPUT); //set led as an output
pinMode(waterSens, INPUT);//set water sensor as an input
Serial.begin(9600);  //start the serial port at 9600 bauds
}
void loop() {
waterVal = analogRead(waterSens); //read the water sensor
Serial.println(waterVal); //print the value of the water sensor to the serial monitor
if (waterVal <= 0){
digitalWrite(led, HIGH);//if the water sensor senses water turn the led on
}
else{
digitalWrite(led, LOW);//if it doesn't sense anything turn the led off
}
}

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
I cannot upload any code to my arduino nano
Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "Arduino Nano, ATmega328P"
Sketch uses 934 bytes (3%) of program storage space. Maximum is 30720 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x49
An error occurred while uploading the sketch
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x49
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x49
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Do you have the right COM port selected? Is your Nano a cheap chinese clone that may not even have the bootloader installed (I have had that before...)? Has it ever worked, or is this your first attempt with this board?

Does this answer your question? "avrdude: stk500_getsync(): not in sync: resp=0x00," aka Some Dude Named Avr Won't Let Me Upload My Program

First try the "Old bootloader" answer

The old boot loader fixed it for me. A lot of the Chinese boards I used have that issue.

For me selecting the ATmega328P (Old Bootloader) from the Tools --> Processor menu in the Arduino IDE solved the problem.
See: https://gyorgybalassy.wordpress.com/2020/10/16/arduino-programmer-is-not-responding-not-in-sync-error/

I had the same problem with an Arduino Micro. When the upload starts, press once the reset button.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Convert character to Integer while leaving encoded

I have two characters, that I get by Bluetooth.
char a = SerialBT.read();
char b = SerialBT.read();

According to the Arduino Reference, decoded data stored in a char gets encoded to ASCII text.
I want to combine them in an Intenger, but the following methods don't work:
int c = a + b;

int c = (int)a + (int)b;

int c = (a - 48) + (b - 48);

and

String c;
c.setCharAt(0, a);
c.setCharAt(1, b);

Thank you

The sentence “decoded data stored in a char gets encoded to ASCII text” makes no sense: a and b contain the received data as is, with no encoding/decoding whatsoever applied. All the methods you show should work, but do different things. What exactly are you trying to achieve by “combining” the characters? Please, show an example of the data you have and the result you want.

@Edgar Bonet, first thank you for the answer. Here is the example: I get the decimal numbers 49 and 50. I save them to two seperate characters, a and b. Now I want to make one number (c) out of two characters (a and b). When I try the methods shown in my post, it don't work.

What do you mean by “it don't work”? What numeric value would you expect c to have?

I expect it to be in ASCII value.

"What do you mean by “it don't work”?" - I get a decimal value, not a ASCII one. Sorry, I didn't write it clearly.

The ASCII value of what? Please, answer my question: if a is 49 and b is 50, what should be the value of c?

@PythonSchlange You still didn't really explain, what you receive and what you want. Are you receiving ASCII encoded data (like the Serial Monitor does)? Or are you receiving simple integers? And what value in what type do you expect as output? The string "4950"? An integer with value 4950? Or are 49 and 50 the decimal values of the two bytes of an integer value?

a is in the example '49', which is 1 in ASCII, and b '50', which is 2. I expect c to be 12 in the end.

You mean something like c = 10*(a-48) + b-48; ?

@StarCat Thank you!

OK, so after the lengthy requests for clarifications, it appears that
you are receiving a number in ASCII decimal ("12") and want to parse
it into an integer.
You may use the parseInt() method of the serial object, like:
int c = SerialBT.parseInt();

This can however make you program quite slow, as parseInt() uses a
timeout to know when to stop expecting more digits.
If you already have read the bytes, you can combine them with simple
arithmetics:
int c = 10 * (a - '0') + (b - '0');

Note that '0' is the same as 48, only it makes more explicit the
intent of your code.

Thank you so much! It's working now. But I recieve a decimal number, just for clearance.

Use an AND mask to convert the character to a digit:
int c = 10 * (a & 0x0F) + (b & 0x0F);

When ASCII was invented, the digits 0 to 9 were encoded in hexadecimal as 30 to 39 to enable easy conversion to/from digits and characters.
To convert a digit to ASCII, OR the byte with 0x30:
byte digit = 5;
char character = digit | 0x30;

To convert a character to a digit, AND it with 0x0F:
char character = '5';
byte digit = character & 0x0F;

These logical operators are faster and more efficient than mathematical operations + and -.

In what way are these operators faster and more efficient? A binary & and a subtraction both take a single clock cycle for an AVR. I.m.o this will only make your code less readable (make it less clear what it is actually doing).

Note also that the byte() conversion has no effect, as it is undone by the subsequent integral promotion. You can simply write character & 0x0f.

@starcat, Regarding readability: yes I agree, but those are the standard transforms since the inception of ASCII and are very well known so are recognised at a glance. Many people write their own macros or inline functions to make them more readable. Regarding speed and efficiency: the & and | circuits in the processor are simpler and use less power, and complete within a smaller fraction of the clock cycle. Regarding the AVR: it's but one of many that may use more clock cycles.

@edgar-bonet, it's for packing the byte into the assembly instruction along with the opcode, as many processors do.

@EdgarBonet, ANDI - Logical AND with Immediate from AVR Instruction Set Manual, Page 36

Re “speed and efficiency”: I doubt you will save a mere picojoule by replacing a subtraction by a bitwise and. You must provide actual measurement data if you want to argue that the difference in energy consumption between subi and andi is at least measurable, let alone relevant in real life. Re “packing the byte into the assembly instruction”: this makes no sense. Semantically, character & byte(0x0F) means int(character) & int(byte(0x0F)), per the rules of the language. Practically, you get the same generated assembly whether you cast or not.

Packing the byte into the instruction is standard practice. For the AVR ANDI instruction, the immediate Konstant byte is split into two nibbles labelled KKKK...KKKK.

What's your point? How is this relevant to the discussion? The same “packing” (called an “immediate” operand) applies to the subtraction instruction subi. And you get the same assembly instruction whether you use a cast to byte or not.

I just compiled a test using bitwise OR | for uint_8 and another for int in VS for x86. It honoured the typecasts, i.e. movzx eax,byte ptr [digit] and mov eax,dword ptr [int_digit], but this is not conclusive because it's a 32-bit processor, so it used a 32-bit | for both, which is still more efficient than using an adder or subtractor circuit. For the 8-bit AVR processor it should use the ANDI instruction. What compiler are you using that doesn't honour the typecasts?

And the power savings are important for extending battery life, for example.

@EdgarBonet, I just compiled the test in AVR gcc 9.2.0. It used lds r24,digit, ori r24,lo8(48) for the byte while it uses lds r24,int_digit, lds r25,int_digit+1, ori r25,3 for the int. So it, too, honours the typecasts. What compiler are you using that doesn't honour the typecasts?

-1 for turning a perfectly good, 5 paragraph answer into a school book report.

Sorry @VE7JRO. It was in response to EdgarBonet's comments.

@VE7JRO, On reflection, I might revert to the previous version because I think StarCat and EdgarBonet were simply trolling. We'll see how it goes for now. I was going to add a section about logic gate efficiency as well... a thesis!

@tim - Why don't you add the max number of chars to your answer to make it even better!!! I think the limit is 30,000 chars per post (HINT: "per post"). Everyone on the planet knows that the longer the answer, the better :)

BTW @VE7JRO, if you thought it was a perfectly good answer why didn't you up-vote it before I added to it? :) And I have a Quartus synthesizer to hand to prove the point about efficiency of a 2-input OR gate versus a full-adder circuit. LOL

@tim - The Arduino Stack Exchange network only gives each user a limited number of votes per day (24 maybe?). I didn't think your answer was worth an up vote when you first posted it, so I didn't up vote it. You've been a member of SO - Stack Exchange for six and one half years, so the up vote / down vote process should not be a surprise to you.

@tim, Trolling? No, it was meant as a genuine comment. I didn’t (and still don’t) see the point of this kind of optimization as an answer to this particular question. It can be useful in other situations where a high level of optimization is essential. Just not here. I just don’t believe this is a useful answer.

I tried with both avr-g++ 5.4.0 (as shipped with Ubuntu 18.04) and avr-g++ 7.3.0 (from Arduino 1.8.13). Both ignore the typecast, as they should per the language rules (read about “C++ integral promotion”). Note that your test is flawed: not only are you changing the typecasts, but also the types and values of the data: the generated assembly obviously has to be different. Read my first comment: I just wrote that character & byte(0x0f) is equivalent to character & 0x0f. That's all there is to compare. PS: it looks like you compiled at optimization level 0. Nobody would ever do that.

Thank you @tim for another soulution, but StarCat's and Edgar Bonet's way is just easier. I don't need the faster soulution in this project as it won't give me any advantage. But anyway, thanks.

@EdgarBonet, I tried int i1 = c1 & char(0x0f); and int i1 = c1 & char(0x0f0f); Both gave andi r24,15 so it honoured the typecast. I also tried int i1 = c1 & int(0x0f); and int i1 = c1 & int(0x0f0f); The former gave andi r24,15 optimised because 15 fits in a byte; the latter gave andi r24,15, andi r25,15.

@PythonSchlange, thanks for the compliment. While it may not be necessary in your particular project, it's essential for battery powered products and low power products in general because it's easier on the power consumption. It's nothing new, & and | have been the efficient method for the last 60 years. The mathematical operators are a degradation of the original design intent of ASCII 30 to 39 hex.

@StarCat, OK you weren't trolling, and I did give you a genuine answer at the time. The OP didn't specify what level of optimisation they wanted, so I simply gave the 60-year-old industry standard method. However, due to compiler optimisations, it's possible to remove the typecasts to make it more readable.

Re “industry standard method”: it was indeed standard in the times when you would do it with dedicated circuitry. If you believe it is still “industry standard” when done today, on a contemporary CPU, please provide some reference. Otherwise I would say it's no more than cargo cult.

Re “it's essential for battery powered products”: Essential? Really? You are visibly not afraid of hyperboles... I performed some actual measurements to see the difference. I invite you to take a look. Spoiler: its far from “essential”.

@EdgarBonet, What is the value of the pull-up resistor inside your Arduino on PD2 for SUBI? And what is the the value your pull-down resistor on PD2 for ANDI? What is the energy consumption of this internal pull-up resistor when shorted to ground via PD2 for the ANDI test?

@EdgarBonet, Rather than being "somewhat surprising", it's highly predictable and obvious to a professional design engineer and hobbyist alike. Although you 'concluded' that a 1% difference (in favour of SUBI) was negligible, you need to consider the bigger picture of the real world. How many ASCII 30 to 39characters are sent across the internet and transposed to/from 0 to 9? What is the energy consumption of that multitude? A 1% fraction of a huge number is still a lot of energy.

The internal (and only) pull-up is about 30 kΩ. There is no pull-down. Note that, for the andi test, I disconnected PD2 before making the measurement in order to not be affected by the pull-up current. Your remark about the energy consumption of the whole Internet is completely out of topic in this Arduino-centric site.

Some (at least) of the current difference looks like that from the internal pull-up resistor left shorted to ground via PD2 throughout the ANDI test. Regarding this site's context, it's completely on-topic to highlight energy reduction especially as it relates to IoT for which Arduinos are used extensively. Besides, you broadened the topic by mentioning "real world applications" on your GitHub link. The principle of using | and &  were sound in 1960 and remain sound to this day - even more so with today's scale of usage.

As I already said, the internal pull-up was disconnected from ground while I was measuring the consumption. 2. I do not intend to broaden the context. IoT, microcontrollers, and even Arduinos are seen in real world applications. 3. I do not dispute that & is a sound option. I dispute that it is “essential” (your word) to choose it over a subtraction. 4. This discussion has drifted way too far. Followup on stackoverflow.

@VE7JRO, I've reverted to the "perfectly good answer". Could you un-down-vote it please?

@tim - No problemo :)  Now we just need a moderator to move these comments to chat where they belong. The SE robot generates a "flag" for the mod's at 20 comments, yet we are now up to 32 comments.


text:
Several lines of code stop program from running?
After a lot of help from you guys (huge thanks) Ive completed my code and gone to test it. unfortunately though one line of code weight = (tip_read.get_units()); stops anything from happening and on the mode one, two or three sub programs it freezes somewhere in there. Any and all help and advice is welcome as Ive been trying to fix this all day and got literly nowhere.
#include <HX711.h>

#include <Wire.h>  // IC2 communication

#include <LiquidCrystal_I2C.h>  //LCD
LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 20, 4); // Change to (0x27,16,2) for 16x2 LCD.

int max_load;
int interval;
int max_load_prev;
int interval_prev;
int mode;
float handle_weight;
float tip_weight;
int stop1;
int mode_previous;
int interval_sum;

int mode1 = 53;
int mode2 = 51;
int mode3 = 49;
int start1 = 39;
int start2 = 37;
int increment = 47;
float potentiometer1 = A0;
float potentiometer2 = A1;
int tare_1 = 45;
int tare_2 = 43;

//stepper motor controller
int stepPin = 12;
int dirPin = 13;

#
//sensor readings
  HX711 tip_read;
  HX711 handle_read;
  #define DOUT_tip  4
  #define DOUT_handle  6
  #define CLK_tip  3
  #define CLK_handle  5

  //saving to array//
  float data_storage_array[400][3];

void setup() {
  // put your setup code here, to run once:

  lcd.init();
  lcd.backlight();

  pinMode(mode1, INPUT);
  pinMode(mode2, INPUT);
  pinMode(mode3, INPUT);
  pinMode(start1, INPUT);
  pinMode(start2, INPUT);
  pinMode(increment, INPUT);
  pinMode(stop1, INPUT);
  pinMode(potentiometer1, INPUT);
  pinMode(potentiometer2, INPUT);

  //sesnor readings

  tip_read.begin(DOUT_tip, CLK_tip);
  tip_read.set_scale(194);// change to calibration factor

  handle_read.begin(CLK_tip,CLK_handle);
  handle_read.set_scale(43.5);// change to calibration factor

  pinMode(tare_1, INPUT);
  pinMode(tare_2, INPUT);

  Serial.begin(9600);

  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);

}

void loop() {
  // put your main code here, to run repeatedly:
  mode_previous = 0;
  interval = 25;
  max_load_prev = 0;
  interval_prev = 0;
  interval_sum = 0;
  while (digitalRead(start1) == 0){
    if (digitalRead(mode1) == 1){
      mode = 1;
    }
    if (digitalRead(mode2) == 1){
      mode = 2;
    }
    if (digitalRead(mode3) == 1){
      mode = 3;
    }
    if (mode_previous != mode){
      Display_mode_set_up(mode);
      mode_previous = mode;
    }
    if (digitalRead(increment) == 1){
      delay(500);
      if (interval >= 1000){
         interval = 25;
      }
      else if (interval < 1000){
        interval = interval + 25;
      }
    }
    max_load = max_load_reading();
    if (max_load_prev != max_load or interval_prev != interval){
      Display_value_set_up(max_load, interval, mode);
      max_load_prev = max_load;
      interval_prev = interval;
    }
   Display_output(handle_weight, tip_weight);
   tare_one();
  }
  if (mode == 1){
    mode_one(max_load, tip_weight);
  }
  else if (mode == 2){
    mode_two(max_load, interval, handle_weight);
  }
  else if (mode ==3){
    mode_three(max_load, interval, handle_weight);
  }
  Pause_stop();

}

//---SUB ROUTINES---

void mode_one(int max_load, float tip_weight){
  tip_weight = read_tip();
  while (tip_weight < max_load){
    tip_weight = read_tip();
    turn_motor();
    Pause_stop();
    Display_output(handle_weight, tip_weight);
  }
}

void mode_two(int max_load, int interval, float handle_weight){
  int aim_value;
  aim_value = 0 + interval;
  tip_weight = read_tip();
  while (tip_weight < max_load){
    while (tip_weight < aim_value){
      turn_motor();
      Pause_stop();
      Display_output(handle_weight, tip_weight);
      tip_weight = read_tip();
    }
    save_to_array(interval_sum);
    aim_value = aim_value + interval;
    while (digitalRead(start2) == 0){
      delay(1);
    }
  }
}

void mode_three(int max_load, int interval, float handle_weight){
  int aim_value;
  aim_value = 0 + interval;
  tip_weight = read_tip();
  while (tip_weight < max_load){
    while (tip_weight < aim_value){
      turn_motor();
      Pause_stop();
      Display_output(handle_weight, tip_weight);
      tip_weight = read_tip();
    }
    save_to_array(interval_sum);
    aim_value = aim_value + interval;
    delay(1000);
  }
}

void tare_one(){
  if (tare_1 == HIGH) {
    tip_read.tare();
  }
  if (tare_2 == HIGH) {
    handle_read.tare();
  }
}

void turn_motor(){
  digitalWrite(dirPin, HIGH);
  digitalWrite(stepPin, HIGH);
  delayMicroseconds(500);
  digitalWrite(stepPin, LOW);
  delayMicroseconds(500);
}

float read_tip(){
  float weight;
  weight = (tip_read.get_units());
  return weight;
}
float read_handle(){
  float weight;
  weight = (handle_read.get_units());
  return weight;
}

void save_to_array(int interval_sum){
  data_storage_array[interval_sum][0] = interval_sum;
  data_storage_array[interval_sum][1] = tip_read.get_units();
  data_storage_array[interval_sum][2] = handle_read.get_units();
  interval_sum = interval_sum + 1;
}

int max_load_reading(){
  int KG_value;
  int g_value;
  int load_max;
  KG_value = analogRead(potentiometer1);
  g_value = analogRead(potentiometer2);
  KG_value = KG_value * 2;
  KG_value = KG_value/ 100;
  KG_value = round(KG_value);
  KG_value = KG_value* 100;
  g_value = g_value/ 10;
  g_value = round(g_value);
  if (g_value >= 100){
    g_value = 99;
  }
  load_max = KG_value + g_value;
  return load_max;
}

void Pause_stop(){
  if (digitalRead(stop1) == 1){
    delay(1000);
    while (digitalRead(start1) == 0){
      if (digitalRead(stop1) == 1){
        motor_unwind();
      }
      else{
        delay(100);
        lcd.setCursor(0, 2);
        lcd.print("Program Paused");
      }
    }
    lcd.setCursor(0, 2);
    lcd.print("                    ");
  }

}

void motor_unwind(){
  tip_weight = read_tip();
  while (tip_weight < 100){
    digitalWrite(dirPin, LOW);
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(500);
  }
  int count = 100;
  while (count > 0){
    digitalWrite(dirPin, LOW);
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(500);
    count = count -1;
  }
}

void Display_mode_set_up(int mode){
  lcd.setCursor(0, 0);
  if (mode == 1){
    lcd.print("Mode: Max           ");
    lcd.setCursor(0, 1);
    lcd.print("MLoad:");
    lcd.setCursor(12, 1);
    lcd.print("inti:---");
  }
  if (mode == 2){
    lcd.print("Mode: Incrimental    ");
    lcd.setCursor(0, 1);
    lcd.print("MLoad:");
    lcd.setCursor(12, 1);
    lcd.print("inti:   ");
  }
  if (mode == 3){
    lcd.print("Mode: Automatic      ");
    lcd.setCursor(0, 1);
    lcd.print("MLoad:");
    lcd.setCursor(12, 1);
    lcd.print("inti:   ");
  }
  lcd.setCursor(0, 3);
  lcd.print("Tp:");
  lcd.setCursor(9, 3);
  lcd.print("Hdle:");
}

void Display_value_set_up(int max_load, int interval, int mode){
  if (mode == 1){
    lcd.setCursor(6, 1);
    lcd.print("      ");
    lcd.setCursor(6, 1);
    lcd.print(max_load);
  }
  if (mode == 2 or mode == 3){

    lcd.setCursor(6, 1);
    lcd.print("      ");
    lcd.setCursor(6, 1);
    lcd.print(max_load);

    lcd.setCursor(17, 1);
    lcd.print("   ");
    lcd.setCursor(17, 1);
    lcd.print(interval);
  }
}

void Display_output(float handle_weight, float tip_weight){
  tip_weight = read_tip();
  handle_weight = read_handle();
  lcd.setCursor(3, 3);
  lcd.print("   ");
  lcd.setCursor(3, 3);
  lcd.print(tip_weight);
  lcd.setCursor(14, 3);
  lcd.print("    ");
  lcd.setCursor(14, 3);
  lcd.print(handle_weight);
}

What's in the function get_units()? In the mode_* subroutines, there are several while loops. Are you sure the conditions are being met for the loops to exit?


text:
MD_Parola display issue when constructing test
I'm using ESP8266 and 4 dot Matrix Tiles, to display clock ( updates using NTP and WiFi ).
Everything is working well, but only when I'm constructing text using a const char* type.
But, since I wish to construct text as sprintf(temp, "12:00"); or char temp[20]="12:00\n; creates gibberish text.
MD_Parola dotMatrix = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);

void updateTime()
{
  char clk[10];
  char dat[10];
  char temp[10];
  sprintf(temp, "12:00"); // <---- this ways failes
  const char *t = "12:00"; // <---- this way succeeds
  dotMatrix.displayText(t, PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);
}

link to library
Appreciate explanation how to construct text not as const char*

You haven't written, how you supply temp to the dotMatrix.displayText() function. Are you just writing temp where now t is written? Have you tried providing a pointer to temp? I'm not sure here about the implicit handling of arrays as pointers, but you might try something like &temp or &temp[0] to get the pointer as parameter of the display function. That's what I would try in this case

@chrisl - t replaces temp as you asked. &temp fails compilation and &temp[0] yields same result as temp

Mhh, the library documentation states, that the library doesn't use an internal buffer, but points to the buffer, that you provide a pointer to. I haven't looked into the library closer, but the problem might be, that the temp buffer goes out of scope after the function exits, which means, that the library uses then a pointer to an invalid location. Please try moving the declaration of the temp buffer to the global scope.

@chrisl - I've read also what you;ve stated but I didn't understand that it should be external. it is correct! please  post as an aunswer

The library documentation states:

The library does not allocate any memory for the text message

That suggests, that the buffer has to be valid beyond the execution of the displayText() function. But as you declare it inside of your updateTime() function, it the buffer gets out of scope, when exiting that function. The memory space can then be reused by the rest of the program. At that point the library will still have the pointer to the old location, though that pointer can now be considered invalid. Thus you are just reading, what the compiler decided to place in that memory location.
To solve that, you need to keep the buffer variable in scope. You can do this by moving the declaration to the global scope.


text:
The analog read is not giving the correct waveform as that of an oscilloscope
I have code that fetches analog input values from terminals A0, A1 and A2 of an Arduino Mega 2560. When I plot the data, it does not give the desired waveform.
The desired waveform is also measured with a the digital storage oscilloscope.
I was thinking to make use of an Arduino Mega 2560 as an oscilloscope that can have 16 channels, because the DSO has only 4 and for a project, I urgently need 16 channels. Would be great if the community people suggest something.

Below is the desired data from the oscilloscope that is measured in parallel to avoid any confusion about the circuit.

%This is a script that will plot Arduino analogRead values in real time
%Modified from http://billwaa.wordpress.com/2013/07/10/matlab-real-time-serial-data-logger/
%The code from that site takes data from Serial

clear all
close all
clc

%User Defined Properties
a = arduino('Com5')             % define the Arduino Communication port
arduino=serial('COM5','BaudRate',9600);
s1 = serial('COM5');                                                       % Define here YOUR serial port
s1.BaudRate=9600;

plotTitle = 'Arduino Data Log';  % plot title
xLabel = 'Time (s)';     % x-axis label
yLabel = 'Voltage (V)';      % y-axis label
legend1 = 'Voltage 1'
legend2 = 'Voltage 2'
legend3 = 'Voltage 3'
yMax  = 5                           %y Maximum Value
yMin  = 0                       %y minimum Value
plotGrid = 'on';                 % 'off' to turn off grid
min = 0;                         % set y-min
max = 5;                        % set y-max
delay = .01;                     % make sure sample faster than resolution

%Define Function Variables
time = 0;
data = 0;
data1 = 0;
data2 = 0;
count = 0;

%Set up Plot
plotGraph = plot(time,data,'-r' )  % every AnalogRead needs to be on its own Plotgraph
hold on                            %hold on makes sure all of the channels are plotted
plotGraph1 = plot(time,data1,'-b')
plotGraph2 = plot(time, data2,'-g' )
title(plotTitle,'FontSize',15);
xlabel(xLabel,'FontSize',15);
ylabel(yLabel,'FontSize',15);
legend(legend1,legend2,legend3)
axis([yMin yMax min max]);
grid(plotGrid);

tic

while ishandle(plotGraph) %Loop when Plot is Active will run until plot is closed

%          dat = readVoltage(a,'A0')* 0.48875855327; %Data from the arduino
%          dat1 = readVoltage(a,'A1')* 0.48875855327;
%          dat2 = readVoltage(a,'A2')* 0.48875855327;

         dat = readVoltage(a,'A0')* 1; %Data from the arduino
         dat1 = readVoltage(a,'A1')* 1;
         dat2 = readVoltage(a,'A2')*1;

         count = count + 1;
         time(count) = toc;

         data(count) = dat(1);
         data1(count) = dat1(1)
         data2(count) = dat2(1)

         %This is the magic code
         %Using plot will slow down the sampling time.. At times to over 20
         %seconds per sample!
         set(plotGraph,'XData',time,'YData',data);
         set(plotGraph1,'XData',time,'YData',data1);
         set(plotGraph2,'XData',time,'YData',data2);

          axis([0 time(count) min max]);

          %Update the graph
          %pause(delay);
  end

delete(a);

disp('Plot Closed and arduino object has been deleted');`

What sketch are you using on the Arduino? Are you using something like Firmata? Where does the readVoltage() function come from? It isn't anywhere in the link, where you modified the code from. From your images it is obvious, that you are sampling way too slow for seeing the wave form.

You are trying to sample at ≈ 12 samp/s a waveform that is around 3 kHz. You must read about the Nyquist–Shannon sampling theorem.

why are you sampling 3 channels?  ... first determine if one channel can capture the data, then try two channels, etc.

Your sampling rate is far too low for the signals you are looking at; you're not getting enough data points for drawing something that looks like the original signal.
The Arduino library's analogRead(), while slow, can do better, up to about 9000 samples/s; the ADC in the atmega2560 in free-running mode can do about 75000 samples/s at 8 bits resolution. This would require programming it at the register level.
There is only one ADC, so if you want 16 channels, this leaves about 4700 samples/s for each channel. In that configuration, however, the first measurements aren't valid and the second ones should be used, further reducing the sample rate per channel to about 2300 samples/s.
With a perfect reconstruction filter, this would limit you to measuring signals up to only 1150 Hz.
All this doesn't even consider the time it takes to store or transmit the results.
So, an Arduino Mega 2560 will not do for making a usable 16-channel oscilloscope for your signals; it's not even close.


text:
CC2541 Bluetooth AT Commands not work for any Commands sended from Serial
i bought the HM 10 Bluetooth controller (CC2541), i got connect on this device through Serial Bluetooth Terminal (Android App) with Serial BLE menu this method not requires any pass and "Connected" state is showed and the led on CC2541 is always HIGH now, but... any command sended from terminal or sended from serial arduino is not show and "AT+NAME" or "AT+NAME?" returns null everytimes, this is my code to run Bluetooth on Arduino Mega2560:
#include <SoftwareSerial.h>

SoftwareSerial mySerial(26, 27); // RX, TX

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.println("Goodnight moon!");

  delay(500);

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  mySerial.print("Wake up wake up wake up wake up wake up! Wake up wake up wake up wake up wake up!");
}

void loop() // run over and over
{
  if (mySerial.available()) {
    String s = "";
    char c;
    while((c = mySerial.read()) != -1) {
      s += c;
      delay(10);
    }

    Serial.println("Received: " + s);
  }

  if (Serial.available()) {
    String s = "";
    char c;
    while((c = Serial.read()) != -1) {
      s += c;
      delay(10);
    }

    delay(10);

    Serial.println("Sent: " + s);

    mySerial.print(s);
  }
}

Example of output serial monitor:
Sent: AT+DEFAULT

Sent: AT+BAUD9600

Sent: AT+HELP

I never receive "Received" status...

Your serial code is really weird. Maybe you should instead directly use the typical Serial Passthrough Sketch, just with mySerial instead of Serial1 (and of course the initialization stuff of SoftwareSerial). Also: Are you sure, that the HM-10 module listens for AT commands at 9600 baud? Have you tried other baudrates?

I'm not sure about my CC2541's BAUD rate, why doesn't it accept AT + BAUD?
So I can't know what your BAUD RATE would be

For just accepting that command every time, it would have to read at every baudrate simultaneously. That's a bit too much to ask. The seller, where you have bought the module, should know the baudrate, that it is configured to. Look at the documentation of it. Or (in the case, that there is no documentation) you can test yourself and go through the list of common baudrates (the ones listed in the Serial Monitor). Though I think you could start above 9600 and go up, before trying others. Also SoftwareSerial has problems with the high baudrates (for example 115200), so you can stop there

I tried all BaudRates (But Serial Arduino is always 9600) and the response is equal... null

I tried change mySerial.begin to 9600
19200
38400
57600
115200
4800
2400
1200
230400


text:
Wrong documentation for Mega2560 SPI Pins?
This page https://store.arduino.cc/usa/mega-2560-r3 contains an image under the Documentation section which shows digital pins 10 to 13 with labels SS, MOSI, MISO, and SCK.
EDIT: The documentation page has since been updated with the correct pin assignment as discussed below. The image has been removed to stop it from showing up in "mega SPI pinout" searches and continuing to spread wrong information.
However, this page says that those are at pins 50 to 53 https://www.arduino.cc/en/reference/SPI.

Which page is correct?

check the schematic ... the top picture is incorrect ... PB4 to PB7 are not SPI pins  ... ATmega2560 datasheet confirms that PB0 to PB3 are SPI pins ... these are pins 50 to 53 on the Arduino board

https://store.arduino.cc/store-support

I have asked Arduino store tech support to check on it - "        Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us."

Got reply from Arduino Store as well. " it is being taken care"

The image is incorrect, unfortunately.
The SPI pins are below:
PB0 - #SS
PB1 - SCK
PB2 - MOSI
PB3 - MISO


text:
1.7 MHz generator for a water atomizer
I'm creating a  controller for a small greenhouse, I have a DHT22 for measuring and two relay module that controls heating and cooling systems, and I will use a piezo to produce humidity when it goes below X amount. This piezo works at 1.7 MHz and I know that Arduino can provide 1.779Mhz, I think It's close enough. After that I'll place a MOSFET at the output and then connect the piezo.
I'm quite new so I'm trying copy-paste some codes and this is what I've done:
I don't know how to turn on and off the frequency generator, I would like to know the code for that
           #include <DHT.h>
            #include <DHT_U.h>

            #define DHTPIN 6
            #define DHTTYPE DHT11 //Define sensor as DHT11

            #define RELAY1  4  // Relay heating
            #define RELAY2  5  // Relay cooling

            int red = 8; // red LED heating
            int blue = 9; // blue LED cooling

            DHT dht(DHTPIN, DHTTYPE);

            float temperature;
            float humidity;

            // Frequency Generator code
            const uint8_t OUTPUT_PIN = 3;  // = OC2B pin inamovible
            const uint8_t PERIOD = 9;      // 9 CPU cycles ~ 1.778 MHz

            void setup()
            {

              pinMode(red, OUTPUT);
              pinMode(blue, OUTPUT);
              pinMode(RELAY1, OUTPUT);
              pinMode(RELAY2, OUTPUT);

              // Freq generator code
                pinMode(OUTPUT_PIN, OUTPUT);
                TCCR2B = 0;           // stop timer
                TCNT2  = 0;           // reset timer
                TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
                       | _BV(WGM20)   // fast PWM mode, TOP = OCR2A
                       | _BV(WGM21);  // ...ditto
                TCCR2B = _BV(WGM22);  // ...ditto
                OCR2A = PERIOD - 1;
                OCR2B = PERIOD/2 - 1;
            }

            void soundBuzzer() {
                TCCR2B |= _BV(CS20);  // F_CPU / 1
            }

            void silenceBuzzer() {
                TCCR2B &= ~_BV(CS20);
                TCNT2 = 0;
            }
              //End of freq generator code
            void loop()
            {
              delay(1000); //delay time between measurements. 1 sec for DHT11

              temperature = dht.readTemperature(); //Reads temperature
              humidity = dht.readHumidity(); //Reads humidity

             if(temperature < 25)
                {
            digitalWrite(red,HIGH);
            digitalWrite(blue,LOW);

            digitalWrite(RELAY1,0);
            digitalWrite(RELAY2,1);
                 }
             else if(temperature > 25)
                {
            digitalWrite(RELAY1,1);
            digitalWrite(RELAY2,0);
            digitalWrite(red,LOW);
            digitalWrite(blue,HIGH);

            }

        if(humidity < 30)
         {
   TCCR2A |= _BV(COM2B1);
    }
        else if(humidity > 35)
                {
          TCCR2A &= ~_BV(COM2B1);

            }
        }

I don't even know if i'm doing it right, please let me know and thanks

Your code doesn't compile: humidity should be humedad, and turn on frequency does not mean anything in C++. Other than that, it looks fine. You should test it!

You should consider replacing your MOSFET with a suitable H-bridge driver and feed an RF transformer to drive the transducer with matched impedance. Just a simple MOSFET will give very poor results. At the absolute minimum you need a resistance across the transducer to bleed the charge, otherwise it won't do much. Medium, drive it with an H-bridge for a full swing signal. Best is to add a transformer as well. Alternatively a half-bridge and center-tapped transformer will reduce component count at the cost of a more complex transformer.

Code was fixed, So if you are telling me that mosfet isn't the best for this task I should consider simply turning ON another relay and adding a different circuit for the piezo then
I was planning to simply put a MP2565 on the output of the Arduino
As I told you before i'm pretty new at this so I don't know if it's good or not


text:
Modbus TCP/IP using Arduino uno and ENC28J60 module
I have this project where I need a modbus tcp server that will host a series of sensor data for other modbus client devices to read. I use this Library by Andresoarmento
This is the code i am using from the library example:
#include <EtherCard.h>
#include <Modbus.h>
#include <ModbusIP_ENC28J60.h>

//Modbus Registers Offsets (0-9999)
const int SENSOR_IREG = 100;
//Used Pins
//const int sensorPin = A0;

//ModbusIP object
ModbusIP mb;

long ts;

void setup() {
    // The media access control (ethernet hardware) address for the shield
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    // The IP address for the shield
    byte ip[] = { 192, 168, 1, 120 };
    //Config Modbus IP
    mb.config(mac, ip);

    // Add SENSOR_IREG register - Use addIreg() for analog Inputs
    int i = 2200;
    mb.addIreg(SENSOR_IREG,i);

    ts = millis();
}

void loop() {
   //Call once inside loop() - all magic here
   mb.task();

   //Read each two seconds
   if (millis() > ts + 2000) {
       ts = millis();
       //Setting raw value (0-1024)
       int i = 0;
       i++;
       mb.Ireg(SENSOR_IREG, i);
   }

The enj28j60 module is working as i tested it. So, I used a modbus scanner(CAS SCANNER) which was unable to detect it. Can anyone tell me how to get this all working and test it?
Thank you in advance.


text:
i am working on rfid module and the module is not detecting sny of the cards
i am working on uno.
i am using mfrc522.
the module is not detecting aby of the cards. nothing is poping up on the screen.
this is the code-
#include <deprecated.h>
#include <MFRC522.h>
#include <MFRC522Extended.h>
#include <require_cpp11.h>

// RFID door access system.

#include <SPI.h>
#include <MFRC522.h>
#include <Servo.h>

#define SS_PIN 10
#define RST_PIN 9
#define LED_G 5 //define green LED pin
#define LED_R 4 //define red LED
#define BUZZER 2 //buzzer pin
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
Servo myServo; //define servo name

void setup()
{
  Serial.begin(9600);   // Initiate a serial communication
  SPI.begin();      // Initiate  SPI bus
  mfrc522.PCD_Init();   // Initiate MFRC522
  myServo.attach(3); //servo pin
  myServo.write(0); //servo start position
  pinMode(LED_G, OUTPUT);
  pinMode(LED_R, OUTPUT);
  pinMode(BUZZER, OUTPUT);
  noTone(BUZZER);
  Serial.println("Put your card to the reader...");
  Serial.println();

}
void loop()
{
  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    return;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())
  {
    return;
  }
  //Show UID on serial monitor
  Serial.print("UID tag :");
  String content= "";
  byte letter;
  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
     Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     Serial.print(mfrc522.uid.uidByte[i], HEX);
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "76 2B E3 93") //change here the UID of the card/cards that you want to give access
  {
    Serial.println("Authorized access");
    Serial.println();
    delay(500);
    digitalWrite(LED_G, HIGH);
    tone(BUZZER, 500);
    delay(300);
    noTone(BUZZER);
    myServo.write(180);
    delay(5000);
    myServo.write(0);
    digitalWrite(LED_G, LOW);
  }

 else   {
    Serial.println(" Access denied");
    digitalWrite(LED_R, HIGH);
    tone(BUZZER, 300);
    delay(1000);
    digitalWrite(LED_R, LOW);
    noTone(BUZZER);
  }
}

please help me

have you tried the example codes of the mfrc522 library? Are they working?


text:
What is the proper wiring for relay module?
I want to know the recommended wiring for relay. I am setting it up as NO.

Where should I connect the relay, the hot wire or the ground wire?
Where should I connect the wire going to bulb, NO or C pins of relay? Where should I connect the wire going to AC, NO or C?

For that setup it doesn't matter in the slightest.

ALWAYS switch the hot wire with the relay (or any switch), never the neutral wire. This prevents a hazardous voltage being present at the bulb, when the switch/relay is turned off. Important safety measure for electricians.

@chrisl good point. I added that bit to my answer. It's an important safety measure for non-electricians as well. (Electricians should know better)

@chrisl While that may be good in principle, in practice it's generally irrelevant. At least in countries with non-polarized sockets, like the USA and most of Europe and Asia. That is, pretty much anywhere except the UK and India...  There's no "Hot" (I HATE that word!) or neutral wire in an appliance.

A relay is a simple switch controlled by an electromagnet coil. The "NO" (normally open) side is off until you apply power to the coil. The "NC" (Normally closed) side is on until you supply power to the coil, at which point it turns off. Switches don't have polarity. If you connect the common into one part of a circuit and the "NO" side into the other, it doesn't matter which goes where.
Edit:
As another poster pointed out, you should wire the relay so it switches the hot leg from the plug, not the neutral (Assuming you're in the US or another country with polarized plugs.) That is much safer, since it means when the relay is off, the lamp is only connected to the neutral line. If, instead, you wire the relay to switch the neutral leg then the lamp will ALWAYS be connected to hot, and if somebody touches the wires they could get a shock.
Important:
What does matter is how you power the relay. If you try to drive a simple relay directly from a logic pin, it will likely damage or destroy the Arduino.
If you're using a "digital" relay that takes a constant 5V source, and a logic level control, such relays have built in transistors and protection diodes that prevent the relay coil from destroying solid state electronics.
If you're using a simple relay, you'll need an appropriate transistor to boost the current to the coil, as well as a "flyback diode" to protect the transistor from back-EMF when the coil is disconnected.

Connect the bulb to the NO pin of the relay.
Image source from: https://ncd.io/relay-logic/

One point: In the US, polarized AC plugs are almost universal. The smaller blade is connected to the black, hot wire, and the wider blade is connected to the white, neutral wire. It's the convention to connect the outer threaded part of an Edison lightbulb socket to the neutral and the inner "tab" on the socket to the hot.

That's because users are more likely to accidentally touch the outer part of the socket while screwing in bulbs, and if your house is wired correctly you shouldn't get a shock from the neutral wire (where you will get a shock from the hot wire if you touch it, or touch metal that's in contact with it.)

@DuncanC - Regarding this part of your comment: "..you will get a shock from the hot wire if you touch it...". That is not always true. The only time you could get a shock is if another part of your body is touching the neutral or ground potential at the same time. I just did a simple experiment before posting this. While standing on a dry, hardwood floor with shoes on, I took a pair of stainless steel nail clippers and inserted the "nail file part of it" into the hot 120VAC side of the receptacle. Nothing happened. I didn't feel anything. Nothing happened in the neutral side either.

Fair enough. I should have said "You CAN get a shock..." You have to be at least partially grounded. If you're isolated from ground you won't pass any current. Note that if you're standing on a damp concrete floor, or have your other hand on a grounded metal object, you could be killed.


text:
I want a bar type display for my Arduino Project
I am trying to make a smart table project. But I have stumbled upon one problem, that is I don't know which display should I use. I need a display that has roughly aspect ratio of 2:1 but also has a relatively high pixel density. I have purchased a 2.42 inch display based on SSD1309 but the display is way too pixelated for my use. Do you have any display recommendations for me?
This is the display that I have bought:

The display I am trying to achieve is like this:

It looked like the display that I'm trying to achieve uses a custom made display. Is there anyway I can achieve that kind of look (at least similar in quality) with displays on the market?

Yes, that is a custom display. No, not without a really high res screen, and those are really expensive and hard to drive from an Arduino. You could always use a mobile phone...

As Majenko already stated, the second image shows a custom display. It is not pixelated, because each shown element/symbol has it's own element in the LCD. When you have one of these displays, you might be able to reuse it for your project, but that is advanced.
In the case of pixel based displays with a significantly higher resolution than the standard SSD1309 driven LCD or OLED displays, you are mostly out of luck. There might be fitting products, though they most likely will be expensive and are not as easy to drive, as the standard ones. AVR based Arduinos, like Uno, Nano or Mega, are also not really good for driving high res displays.
The way to go depends on your exact requirements.

You could - as Majenko suggested - ditch the Arduino and use an old smartphone. If you need more control over the smartphone for your project, than the standard Andriod gives you, you could install an open source OS on the phone.

You could move to a Single Board Computer, like the Raspberry Pi Zero, and buy a display for it. There are many displays for Raspberry Pis, that should have enough resolution. Though most of them are larger than a normal smartphone display.


text:
What's wrong with my codes/
My teacher gave us a performance output about doing a dancing christmas lights in tinkercad. But I don't know what to do about the codes. He left  an instruction to us about what to do. I follow it but the tinkercad keep telling that...
Sorry, it seems like your code has some errors.
Close
 In function 'void setup()':
13:5: error: a function-definition is not allowed here before '{' token
21:7: error: a function-definition is not allowed here before '{' token
41:61: error: expected '}' at end of input
41:61: error: expected '}' at end of input
41:61: error: expected '}' at end of input
 exit status 1

And here's the code that I've entered...
int ledPins[]={3,4,5,6,7,8,9,10,11,12};
void setup()
{
  for(int i =0; i <11; i++)
  {
    pinMode(ledPins[i],OUTPUT);
}
  {
  void setup()
    {
     for (int i=0; i <11; i++)
     {
       pinMode(ledPins[i],OUTPUT);
     }
  }
    {
      void loop()
      {
        int i = 0;
        while (i<10)

        {
          {
            digitalWrite(ledPins{i],HIGH);
            delay(100);
            digitalWrite(ledPins[i],LOW);
            i++;
                                }
                         }
                         i = 10;
                         while (i >0
                                {
                                  digitalWrite(ledPins[i],HIGH;
                                               delay(100);
                                               digitalWrite(ledPins[i],LOW;
                                                            i--;
                                                            }
                                                            }

And here's the instruction of my teaher for the codes...
6. Initialize variables
Use array to initialize variables.
Set ledPin as the name of the variable and initialize the Arduino pins that you’re going to use.
Never forget to end each statement with semicolon
7. Set all pin to output
Use function void setup ()
Create a for () loop for array manipulation.
Initialize the for loop with i=0; since we will start the dancing lights with all LEDs turned off.
Initialize the condition i<11; since we need to turn on the 10 LEDs.
Set the increment to i++ because we need to iterate until it reaches the last LED.
Configure pin using pinMode().
Place a curly bracket before and after the for loop and pinMode().
8. Create a loop
Use function void loop().
Create a variable, i = 0.
Use while() for continuous looping
First while() is used to run your light from right to left.
Second while() is used to run your light from left to right.
Place a curly bracket before and after your statement block
Never forget to end each statement with semicolon

You seem to have brackets-tourettes. You really need to look at those brackets. Examine the shape of them, and the order of them. Hint: for every opening { there must be a closing }. For every opening ( there must be a closing ). For every opening [ there must be a closing ].

Are those the only codes that I need to change?

I don't know. Your code is such a mess I have no clue what it's intending to do.

You need to get the brackets right. Though that is not about Arduino, thus off topic here. You can search for C/C++ tutorials on the web to get the syntax right. Also you should use an autoformatting function (don't know, if Tinkercad has one, but the Arduino IDE has it) to get the indenting right. Otherwise you have to do it manually. Once the code is correctly indented, it is way easier to see the bracket problems.

you really need to look at the example code in the Arduino IDE ... see how the code is formatted, which means how it is indented ... indent levels are like paragraphs in writing ... your code has indentation, but it is all over the place without reason

Does this answer your question? What's wrong with my codes?

Duplicate of https://arduino.stackexchange.com/questions/77967/whats-wrong-with-my-codes

I changed it, so it at least compiles.
int ledPins[]={3,4,5,6,7,8,9,10,11,12};
void setup()
{
  for(int i=0; i < 11; i++)
  {
    pinMode(ledPins[i],OUTPUT);
  }
}

void loop()
{
  int i = 0;
  while (i < 10)
  {
    digitalWrite(ledPins[i],HIGH);
    delay(100);
    digitalWrite(ledPins[i],LOW);
    i++;
  }
  i = 10;
  while (i > 0)
  {
    digitalWrite(ledPins[i],HIGH);
    delay(100);
    digitalWrite(ledPins[i],LOW);
    i--;
  }
}


text:
Use the stepper motor library with the A4988 driver?
I want to use this library: https://www.arduino.cc/en/Reference/Stepper
#include <Stepper.h>

The wiring for my driver is shown here:

https://www.pololu.com/product/1182
From the library, I'm stuck at the motor pins:
#define motorSteps 200
#define motorPin1 2    // STEP pin
#define motorPin2 3    // DIR pin

Stepper myStepper(motorSteps, motorPin1, motorPin2);

Is this library not compatible with this stepper motor driver? Or what needs to be defined for it to work?
More details on the library are here: http://www.tigoe.com/pcomp/code/circuits/motors/stepper-motors
The basic section of my code that works without the library is this:
digitalWrite(stepPin, HIGH);
delay(wait);
digitalWrite(stepPin, LOW);
delay(wait);

Yet, the two-wire circuit part of the library uses motorPin1 and motorPin2 in a way I don't understand:
switch (thisStep) {
  case 0:  // 01
    digitalWrite(motor_pin_1, LOW);
    digitalWrite(motor_pin_2, HIGH);
  break;
  case 1:  // 11
    digitalWrite(motor_pin_1, HIGH);
    digitalWrite(motor_pin_2, HIGH);
  break;
  case 2:  // 10
    digitalWrite(motor_pin_1, HIGH);
    digitalWrite(motor_pin_2, LOW);
  break;
  case 3:  // 00
    digitalWrite(motor_pin_1, LOW);
    digitalWrite(motor_pin_2, LOW);
  break;
}

https://github.com/arduino-libraries/Stepper/blob/master/src/Stepper.cpp
How should motorPin1 and motorPin2 be defined?

That library is not compatible with the A4988. It is intended to do the same job that the A4988 does. You provide a step direction and an instruction to step, and it does the stepping for you.
To use the A4988 you just set a pin HIGH or LOW for the direction, then toggle another pin to make it step. You don't really need a library for that.
However if you do want to abstract it with a library and add lots of cool extra features then you should look at AccelStepper which supports 2-wire drivers like the A4988.


text:
Need help: Cast from 'char*' to 'uint8_t {aka unsigned char}' loses precision [-fpermissive]
I'm trying to convert the string that I receive from the Websocket to uint8_t that I can copy to the data bytes of CAN protocol frame. I'm using an ESP32 chip and programming it on an Arduino IDE. The string that it receives from the websocket is "0322F12155555555".
#include <WiFi.h>
#include <SPIFFS.h>
#include <ESPAsyncWebServer.h>
#include <WebSocketsServer.h>
#include <esp32_can.h>
#include <SPI.h>
#include <string.h>

uint8_t payload1;
char payload2[100];
...
AsyncWebServer server(80);
WebSocketsServer webSocket = WebSocketsServer(1337);
...
// Callback: receiving any WebSocket message
void onWebSocketEvent(uint8_t client_num,
                      WStype_t type,
                      uint8_t * payload,
                      size_t length) {
...
      Serial.printf("[%u] Received text: %s\n", client_num, payload);
      strcpy(payload2, (const char*)payload);
      payload1 = (uint8_t)(payload2);
...

Error:
error: cast from 'char*' to 'uint8_t {aka unsigned char}' loses precision [-fpermissive]
       payload1 = (uint8_t)(payload2);
                                    ^

I'm segmenting the data into an array later, but I'm not confident that my cast is correct. Can someone please help with this? Thanks
-- Keith

It should be uint8_t * not uint8_t.

@Majenko, I have to finally segment the data and copy it into an array that accepts uint8_t. How do I do that?

I think it sounds like you need to do a lot more than just casting. You need to interpret the content of the string.

You can't just cast a string to a numeric type - C just doesn't work that way. What you're actually casting is the address in memory that the string resides at.
Instead you need to take the content of the string and interpret it.
For instance, you might take each pair of characters and combine them into a HEX value in a string that you then interpret as a number. That could be done a number of ways.
For example:
char temp[3]; // Temporary space for the conversion string
// Copy two characters into the temporary string
temp[0] = payload[0];
temp[1] = payload[1];
// and terminate the string properly
temp[2] = 0;
// Convert the string using base 16
uint8_t val = strtol(temp, NULL, 16);

In your example string you have 16 characters, which would be 8 bytes of data. So you could put it in a loop:
char temp[3]; // Temporary space for the conversion string
uint8_t vals[8]; // Array to store your values

// Iterate over the values
for (int i = 0; i < 8; i++) {
    // Copy two characters into the temporary string
    temp[0] = payload[i * 2];
    temp[1] = payload[i * 2 + 1];
    // and terminate the string properly
    temp[2] = 0;
    // Convert the string using base 16
    vals[i] = strtol(temp, NULL, 16);
}

Of course there are "lighter" ways of doing it that don't involve an intermediate string or the strtol() function.  For example I often use this little function:
uint8_t h2d(char hex) {
    if(hex > 0x39) hex -= 7; // adjust for hex letters upper or lower case
    return(hex & 0xf);
}

That takes a single character and converts it from hex to decimal. So you can combine that with bit shifting and OR to create a byte from two characters:
val = h2d(payload[0]) << 4 | h2d(payload[1]);

In your loop that would look like:
for (int i = 0; i < 8; i++) {
    // Convert the string using base 16
    vals[i] = h2d(payload[i * 2]) << 4 | h2d(payload[i * 2 + 1]);
}


text:
Interrupts Within Critical Statements
I've redone a previous Arduino sketch I posted in which I was having trouble capturing encoder counts within critical statements, having no luck properly attaching and detaching interrupts.  I've studied various ISR sketches but haven't been able to produce anything that caters to my needs.
I now have a switch case in which a DC motor with CPR encoder correctly rotates back and forth between specified boundaries if it alone is in the void loop.  However, once enclosed within a critical statement (I want this action to occur only if a button is pressed), the DC motor continues to rotate only one direction.
I need assistance in where to properly attach and detach these interrupts and how to correctly pass the encoder value to the next action.  Below is what I've done so far and any help would greatly be appreciated.
#define enA 9
#define in1 6
#define in2 7

const int button1Pin = 8;

int button1State = 0;

volatile long temp, counter = 0;

long local_counter=counter;

enum {IdleState, ForwardState, BackwardState} State;

void setup() {

  Serial.begin(9600);

  pinMode(enA, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);

  Serial.begin (9600);
  pinMode(2, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);

  attachInterrupt(0, ai0, RISING);
  attachInterrupt(1, ai1, RISING);

  pinMode(button1Pin, INPUT);

  State = IdleState;
}

void loop() {

  button1State = digitalRead(button1Pin);

   if( counter != temp ){
   Serial.print("counter = ");
   Serial.print (counter);
   Serial.print("     local counter = ");
   Serial.println(local_counter);
   temp = counter;
   }

   //if (button1State == HIGH) {

          switch (State) {

              case IdleState:
                halt ();

              if (counter<2000)
                State = ForwardState;
              break;

              case ForwardState:
                clockwise();

              if (counter>=2000)
                State = BackwardState;
              break;

              case BackwardState:
                counterclockwise();

              if (counter <=0)
                State = ForwardState;
              break;

          } // end switch
   //  }

}

void ai0() {
  if(digitalRead(3)==LOW) {
  counter++;
  }else{
  counter--;
  }
  }

void ai1() {
  if(digitalRead(2)==LOW) {
  counter--;
  }else{
  counter++;
  }
  }

void clockwise (){
    analogWrite(enA, 255);
    digitalWrite(in1, HIGH);
    digitalWrite(in2, LOW);
  }

void counterclockwise () {
    analogWrite(enA, 255);
    digitalWrite(in1, LOW);
    digitalWrite(in2, HIGH);
  }

void halt () {
    digitalWrite(in1, LOW);
    digitalWrite(in2, HIGH);
}

An explanation of my setup is as follows:
My button is a tactile button on breadboard (connected to pin 8 of an Arduino Uno),  with 5V supply from Arduino. Pins 6 of the Arduino is connected input 1 of the L298N motor driver, pin 7 of Arduino connected to input 2 of the motor driver, and pin 9 of the Adruino connected to the enable of the motor driver.  Them motor driver is being supplied by an external 12V supply which is also power the 12V DC geared motor with encoder.  The encoder outputs are connected to pin 2 and 3 of the Arduino.

what is a critical statement?

For halt shouldn’t you turn that Enable pin back off?

Setting in1 LOW and on2 HIGH in halt() doesn't seem to be correct

The way I see it, the state should go back to IdleState if the button is not pressed. Just putting the switch-case inside the if-statement will result in the motor continue rotating the way it was rotating when the button is released.
if (button1State == LOW ) {
  State = IdleState;
  counter=2000;
}
else if(button1State==HIGH && State==IdleState ) {
  counter = 0;
}

switch(State) {
  ...

Depending on what it is you want to do, you might want to add another state (say StoppedState), where the motors are halted, just like IdleState, but you don't get a state change if counter<2000. Then you don't have to change the counter variable.
if (button1State == LOW ) {
  State = StoppedState;
}
else if(button1State==HIGH && State==StoppedState ) {
  State = IdleState;
}

switch(State) {
  case StoppedState:
    halt ();
    break;
  case IdleState:
    ...

PS please indent the if statements inside you cases.

I actually want it to continuously rotate back and forth, even after the button is depressed.  Later, I plan to add buttons to stop and to rotate in one designated direction. So if  I want this continuous back and forth motion to continue after the button is depressed, should the first IF statement (button == LOW) be altered?  I've tried removing it but that doesn't do the trick.

What part of your code would make it stop and go the other way?  Is that inside an if statement that only executes if the button is pressed?  Then it will only happen if button isn’t pressed.  Let button press choose a state.  Let the switch run all the time.

I suppose it would have to be the first part of the IF statement for when the button is LOW, being that "counter=2000", the condition for counterclockwise motion. I've tried changing or removing that condition without any success. Should I be focusing more on Gerben's second suggestion?  It seems to have a similar behavior as the first in my attempts.

I'm confused. Do you want to motor to do nothing, until the button is pressed? And then go back and forth no matter whether the button is pressed or not? If that's the case, go with the second solution, but leave out the State = StoppedState; in the if statement, and put that in the setup (instead of State = IdleState).

Will you marry me Gerben???!!! That's exactly what I wanted and it worked!!!  But the honeymoon is short lived  I added a second button to stop, but all it does is rotate counterclockwise when pressed:
      if(button2State==HIGH){
          State = StoppedState;
      }

Will the switch case not work with this setup?

The code you've provided looks okay, so I'm not sure what the problem is. Please post your code, as I'm still a bit confused. And you marriage proposal makes me even more confused q-;.  I think it would be best to create a new question.

Sorry, I'm a confusing person by nature, but there was also a problem with my code for halt (), which I corrected and now my second button correctly stops the motor.  But I've added a third button, when pressed, I want the motor to move continuously clockwise, so I added this:  if(button3State==HIGH){clockwise();} but it doesn't do anything.  Should I create another state or void function? <-- but that seems necessary to me.  I can indeed post this as another question if you feel it best.

Seems like you fixed our honeymoon issue. For the third problem use while(button3State==HIGH){clockwise();} instead. That way the switch statement isn't called right after it, and negate the clockwise rotation. Adding a separate state would also work, and will probably result in nicer and easier to read code.

That did work; however, it doesn't break from button 3 action when button 1 or 2 is pressed.  I also tried this:  while(button3State==HIGH&&button1State==LOW&&button2State==LOW){
clockwise();} but this really doesn't change anything.  We're so close!!!

I added another state, and button 3 works, but then button 1 no longer works AFTER button 3 is pressed (button 2 works at anytime).

Nevermind, I figured it out....and by "I" I mean 99% StackExchange and 1% me.  I had an issue with the counter value, it needed to be reset to 0 before button 1 could properly work.  I can't thank you all enough, for now we can go our separate ways...I guess we're getting divorced :(

It was 100% that searched SE. So "You" solved it 100% yourself. I guess it wasn't meant to be ;-p


text:
Input Capture with Sleep Enabled on ATM32u4 board only works every second reading in SLEEP mode
In short: I have an Input Capture code and a Power-Saving code combined into one program.  Both are adapted from Nick Gammon's examples that work fine independently.  When I combined them into one code it only reads the data every other time a single pulse is sent to be captured every 20 seconds. The board sleeps during one idle cycle between the 20 second readings, then wakes up but misses the first reading, and then it stays awake during the next idle cycle and reads the pulse correctly at the 40 second mark for the second reading.  And repeats.  The references of these two Nick Gammon codes are listed in the program.
Details: Adafruit BlueFruit Feather 32u4 w/nrf51 in the Arduino 1.8.10 IDE.  Using Nick Gammon's example for Input Capture an external incoming pulse of around 800 us (micro sec) long pulse is being measured by (ICP3) Input Capture #3 (rewritten from ICP1) on Pin D13 (PC7) (removed the LED). Works good.
Then I had a separate program that puts the board into deep-sleep and using INT0 (D3) to wake it up with an external interrupt signal.    Since I was not able to figure out how to use the Input Capture as an ISR Interrupt to wake up the board, I ran the same external pulse signal also to the D3 (INT0) pin. So when the pulse hits both D3 (INT0) and D13 (ICP3) at the same time, and D3 wakes up the board via INT0 and then the ICP3 can capture the pulse and measure it.  Then right after that, or several seconds later, can go back to sleep until the next pulse arrives on D13 (ICP3).  I spaced the external 800us single pulses 20 seconds apart to make it easier to diagnose.  If I remove the line that places the board into sleep "sleep_cpu ();" I get a nice single-shot signal pulse measurement every 20 seconds.   Since I am not using the USB-detach and reconnect feature, after the board goes to sleep it disconnects, but I am monitoring the power usage  via a Fluke mA meter and I can see when it sleep and when it wakes up, and also monitoring the external pulse going to D13 (ICP3) and D3 (INT0) on the Oscope.
Notes: The Input Capture is listed under the Interrupts, but at a much lower priority then INTo or INT1.
I do not need an active USB during the readings or sleep, because using  BLE to send the data.  The code I posted has the BLE portion removed the make it simpler to troubleshoot. The 800us external single-shot pulse is rock solid I have it showing on the Oscope, at the proper magnitude (0 to 3.3V) and intervals. I am trying to have the CPU sleep between readings.  Can be right after the reading or a few seconds later. Interrupts have to be alive and ready to capture in case the 20 seconds becomes 1 or 2 seconds intervals (in real life).
// Time the interval between two consecutive pulses.Frequency timer using input //capture unit #3 on 32u4
// Author: Nick Gammon
// Date: 31 August 2013  http://www.gammon.com.au/timers
//  References: here:  http://www.gammon.com.au/forum/?id=11504&reply=12#reply12    //and  here:  https://www.gammon.com.au/power Sketch J
// Info here: http://gammon.com.au/interrupts
//Freq (Hz)     Per (µs)
// 8,000,000*   0.125us  or 125ns per clock tick at 8mghz

#include "LowPower.h"
//part of work around for BOSD missing functionality in 32u4.
//Not needed for 328p MCUs for sleep.

#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/interrupt.h>
#include "avr/io.h"
#include <math.h>
#include <Arduino.h>

// Input: Pin D13 (PC7, ICP3) adafruit 32u  which is Timer3 Capture Input pin ,   //removed D13 LED by cutting trace or by removing resistor before LED13

const int wakeUpPin = 3;
volatile boolean first;
volatile boolean triggered;
volatile unsigned long overflowCount;
volatile unsigned long startTime;
volatile unsigned long finishTime;
volatile unsigned long elapsedTime;

//////START: ISR TIMER/COUNTER PULSE ROUTINE ON D13 INPUT-CAPTURE #3 on 32u4 ////
//https://www.nongnu.org/avr-libc/user-manual/group__avr__interrupts.html   //http://medesign.seas.upenn.edu/index.php/Guides/MaEvArM-timer3

// timer overflows (every 65536 counts)
ISR (TIMER3_OVF_vect) //1 3

{
        overflowCount++;
}  // end of TIMER3_OVF_vect

ISR (TIMER3_CAPT_vect)   // 1 3
  {
       // cancel sleep as a precaution  (added here from Power Save)
      sleep_disable();

   // grab counter value before it changes any more
  unsigned int timer3CounterValue;
  timer3CounterValue = ICR3;
// see datasheet, page 117 (accessing 16-bit registers)
  unsigned long overflowCopy = overflowCount;

  // if just missed an overflow
  if ((TIFR3 & bit (TOV3)) && timer3CounterValue < 0x7FFF)  // 1 3     //http://medesign.seas.upenn.edu/index.php/Guides/MaEvArM-timer3
    overflowCopy++;

  // wait until we noticed last one
  if (triggered)
    return;

  if (first)
    {
    startTime = (overflowCopy << 16) + timer3CounterValue;
    first = false;
    return;
    }

  finishTime = (overflowCopy << 16) + timer3CounterValue;
  triggered = true;
  TIMSK3 = 0;    // no more interrupts for now   // 1 3    //http://medesign.seas.upenn.edu/index.php/Guides/MaEvArM-timer3
  }  // end of TIMER3_CAPT_vect

/////////////////////////ENF OF: TIMER/COUNTER PULSE MEASURE ROUTINE////////////

////////PREPARE FOR INTERRUPTS ROUTINE FOR TIMER/COUNTER CAPTURE////////////////

void prepareForInterrupts ()
  {

  noInterrupts ();  // protected code
  first = true;
  triggered = false;  // re-arm for next time
  // reset Timer 1
  TCCR3A = 0;   // 1 3
  TCCR3B = 0;    // 1 3

  TIFR3 = bit (ICF3) | bit (TOV3);  // clear flags so we don't get a bogus interrupt    // 1 3
  TCNT3 = 0;          // Counter to zero   // 1 3
  overflowCount = 0;  // Therefore no overflows yet

  // Timer 3 - counts clock pulses
  TIMSK3 = bit (TOIE3) | bit (ICIE3);   // interrupt on Timer 3 overflow and input capture
  // start Timer 1, no prescaler
  TCCR3B =  bit (CS30) | bit (ICES3);

// plus Input Capture Edge Select (rising on D13)
//TCCR1B &= ~(1<<ICES1);
//ICP set to trigger on falling/rising edge
//   Bit 6 - ICES1: Input Capture Edge select    Select edge detection for //input capture function.          0 = Capture on falling edge  1 = Capture on //rising edge

  interrupts ();
  }  // end of prepare For Interrupts

///END OF:   PREPARE FOR INTERRUPTS ROUTINE FOR TIMER/COUNTER////////////

///POWER SAVING -SIGNAL INTERRUPT WAKEUP ISR ON D3 on 32u4 or D2 on 328p///

void wakeUp ()
 {
  // cancel sleep as a precaution
     sleep_disable();
  // precautionary while we do other stuff
   detachInterrupt(digitalPinToInterrupt(wakeUpPin));
//D3 for 32u4 and D2 for 328p (INT0)
 }  // end of wakeUp
////POWER SAVING ROUTINE - WAKEUP ISR-END/////////////////

////////SET UP VOID ///////////////////////////////////////////

void setup(void)
{
 pinMode(wakeUpPin, INPUT); //this is pin D3 (INT0) on 32u4 and D2 (INT0) on 328p
digitalWrite (wakeUpPin, LOW);
// enable pull-down on D3 (on 32u4 D3 is INT0) for Wake INTERRUPT   - PART OF //POWER SAVING ROUTINE WITH INT0 SIGNAL on D3 on 32u4 (or D2 on 328p)

 Serial.begin(115200);

  pinMode(13, INPUT);
//This is the input/measure pin (LED taken off or LED13 resistor removed)
   analogWrite(13, LOW);  //must pull up or down to stop noise and floating

  // set up for interrupts
  prepareForInterrupts ();

}   // <= this is for the SET UP () ///////

////////////////////////END OF SETUP SEGMENT/////////////////

//////START OF MAIN LOOP/////////////

void loop(void)
{

   // wait till we have a reading
if (!triggered) //if "triggered" is NOT TRUE  (i.e. NOT TRIGGERED) then STOP HERE
 return;

unsigned long  elapsedTime = (finishTime - startTime);
//period count between start and stop times

Serial.print ("Start time: ");
Serial.print(startTime);
Serial.print (" counts.  ");
Serial.print ("Finish time: ");
Serial.print(finishTime );
Serial.print (" counts.  ");
Serial.print ("Elapsed time: ");
Serial.print (elapsedTime);
Serial.println (" counts.   ");

 // Delay before next measurement update
 delayMicroseconds(1000) ;

 prepareForInterrupts ();
//  goes back up outside LOOP to RESET conditions for next INPUT CAPTURE ISR AND //OVERFLOW ISR TIMER/COUNTER reading, clear registers, etc

///START: POWER SAVING ROUTINE USING D3 (INT0) on 32u4  (D2 is INT0 on 328p) //INTERRUPT FROM PULSE OR USER SWITCH////////////

//delayMicroseconds(3000000) ;
// DELAY SO SLEEP ONLY CAN HAPPEN EVERY 3 sec =>  3000000 us (micro sec)

 delay(500);// MUST have delay to allow power down process to proceed

      // disable ADC
      ADCSRA = 0;

      set_sleep_mode (SLEEP_MODE_PWR_DOWN);
      sleep_enable();

  // Do not interrupt before we go to sleep, or the ISR will detach interrupts and we won't wake.
      noInterrupts ();

  // will be called when INT0 (pin D2 for 328p) or D3 for 32u4 goes HIGH//
     attachInterrupt(digitalPinToInterrupt(wakeUpPin), wakeUp, RISING);

// [External Interrupts] //3 for 32u4 and 2 for 328p (INT0)  Use RISING as //trigger for (INT0 on D2 for 328p and) INT0 on D3 on 32u4 from op AMP.  Same //signal as the D13 INPUT CAPTURE TIMER from op Amp OUT
     EIFR = bit (INTF0);  // clear flag for interrupt 0
     EIFR = bit (INTF1);  // clear flag for interrupt 1
//  added just for good measure to cover both D2 and D3 INT pins

// turn off brown-out enable in software, BODS does not work with 32u4, only //328p.  Work around is to use "low-power.h" library, not implemented here
// BODS must be set to one and BODSE must be set to zero within four clock cycles
       // MCUCR = bit (BODS) | bit (BODSE);
       // The BODS bit is automatically cleared after three clock cycles
       // MCUCR = bit (BODS);

//We are guaranteed that the sleep_cpu call will be done as the processor //executes the next instruction after interrupts are turned on.
        interrupts ();  // one cycle
     // sleep_cpu ();   // one cycle    //*****DISABLED BECAUSE KEEPS DOUBLING
                                        //DATA SEND TIME, AND ONLY WAKES UP HALF
                                        //THE TIME

///////END OF POWER SAVING ROUTINE///////////////////////////////////////////////

}
///////////////////////END OF MAIN LOOP///////////////////

It seems to me your problem lies here:

set_sleep_mode (SLEEP_MODE_PWR_DOWN);

In this mode, all the synchronous peripherals are turned off, including
your timer. However, you need this timer for generating the input
capture interrupt. You also want it to be running in order to count the
overflows, otherwise the values captured would be meaningless.
In order to keep the timer running, you have to use SLEEP_MODE_IDLE,
which is the default sleep mode anyway. This mode puts the CPU to sleep
while keeping the peripherals running. If you are afraid this may have
too high a power consumption, you can selectively turn off all the
peripherals you do not need. Note that you cannot selectively
enable peripherals in other sleep modes.

Thank you for the suggestion & link. Saw an example for IDLE mode. Will check if shutting down unused peripherals lowers close to same as consumption as in SLEEP_MODE_POWERDOWN.  My assumption was that using an INT0-type interrupt would wake up the CPU so the INPUT CAPTURE TIMER would be fully ready. Works half of the time, on every 2nd external pulse, so I thought that  there is some sort of an interrupt-sequence/priority conflict in my code, or some of the flags (which are still murky for me) are not set properly as a result of the two combined codes. I suspect "if !triggered" and "return".

Edgar Bonet. Implemented & worked w/IDLE! Much lower mA. However, there maybe a coding solution to the problem outlined in my post.Convinced that when I combined Mr. Nick Gammon's two examples "InputCaptureCounter/Timer" & "Deep Sleep" the issue is in Void Loop=> if (!triggered) return;  This stops the program until a flag inside the ISR Capture is "true". When the attacheInterrupt on INT0/D3 fires same time as the ISR Capture reads on D13, the program may not make past WakeUp ISR, added by me. As a consequence the ISRs Capture & Overflow cannot read the pulse on D13 (PC7 on 32u4).


text:
is it necessary to include libraries that are specified in the header file already?
I am using the Adafruit BME280 library in my sketch. In the example sketches, they have included the Wire, SPI and the Adafruit_Sensor library. However, I see that in the Adafruit_BME280 library header file, these libraries are already included. So I tried commenting out them in my sketch and it still works. So I wonder if there are still cases or any specific reason to include them twice?
Additionally, if a library is included/referenced twice like mentioned above, wouldn't it increase the size of the sketch unnecessarily?

Example Sketch that comes with the library
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

#define BME_SCK 13
#define BME_MISO 12
#define BME_MOSI 11
#define BME_CS 10

#define SEALEVELPRESSURE_HPA (1013.25)

Adafruit_BME280 bme; // I2C
//Adafruit_BME280 bme(BME_CS); // hardware SPI
//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI

unsigned long delayTime;

void setup() {
    Serial.begin(9600);
    while(!Serial);    // time to get serial running
    Serial.println(F("BME280 test"));

    unsigned status;

    // default settings
    status = bme.begin();
    // You can also pass in a Wire library object like &Wire2
    // status = bme.begin(0x76, &Wire2)
    if (!status) {
        Serial.println("Could not find a valid BME280 sensor, check wiring, address, sensor ID!");
        Serial.print("SensorID was: 0x"); Serial.println(bme.sensorID(),16);
        Serial.print("        ID of 0xFF probably means a bad address, a BMP 180 or BMP 085\n");
        Serial.print("   ID of 0x56-0x58 represents a BMP 280,\n");
        Serial.print("        ID of 0x60 represents a BME 280.\n");
        Serial.print("        ID of 0x61 represents a BME 680.\n");
        while (1) delay(10);
    }

    Serial.println("-- Default Test --");
    delayTime = 1000;

    Serial.println();
}

void loop() {
    printValues();
    delay(delayTime);
}

void printValues() {
    Serial.print("Temperature = ");
    Serial.print(bme.readTemperature());
    Serial.println(" *C");

    Serial.print("Pressure = ");

    Serial.print(bme.readPressure() / 100.0F);
    Serial.println(" hPa");

    Serial.print("Approx. Altitude = ");
    Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
    Serial.println(" m");

    Serial.print("Humidity = ");
    Serial.print(bme.readHumidity());
    Serial.println(" %");

    Serial.println();
}

it is not necessary now. in the past it was necessary to include all used libraries in the main sketch file.

It doesn’t use any extra code space.  There is an include guard on any decent library that stops it actually being included twice.

Actually, the first two lines in the include file (#ifndef __BME280_H__,  #define __BME280_H__ .... and the #endif on the last line of the file prevent it from being processed twice, so it doesn't matter how many times your code tries to #include it. All or most include files from libraries work the same way.

Historically it was necessary, yes. In times past the IDE would look only in your sketch to find the list of libraries to compile and link. However much progress has been made in recursive library searching, whereby the IDE can now find libraries that are included by other libraries.
I am not sure when that change was implemented, but it was a long time coming and is only recently that it's worked.
So if you are distributing code for other people to use then it's a good idea to still add the libraries in the sketch - just in case they're using an older version of the IDE that can't find the libraries included by other libraries.

Thanks for the answer. But what about the memory usage if libraries are added twice?

I don't understand what you're asking. You mean the memory usage of your computer?

I meant size of the sketch and required memory (SRAM and/or Flash) on the MCU if the library is added once in the sketch and once called by another library. Usually when libraries are included the sketch size increases. But I suppose the compiler would be smart enough to see the duplication.

Oh, I see. The compiler doesn't need to be "smart enough" to "see" the duplication. There is no duplication. Added is added. You can't add the same apple to a bowl twice - no matter how many times you put it in the bowl it's the same apple. A library is a library. It's a single item. Referencing it multiple times in multiple places is still just the one library.

@Zaffresky, the library is not the .h file. the library is added to build because the include is detected in the source code. this is what the Arduino builder does for you. In normal C++ tools you must list the libraries in the makefile.

@Zaffresky: "But what about the memory usage if libraries are added twice?" If a global is defined (not just declared) in a .h file and the .h file lacks include-guards, then that global would be multiply-defined. But the .h file doesn't actually pull in the library code and data; the linker does that in order to satisfy references to definitions the library contains. When the library has been added, all program references to anything in it are now satisfied, so the linker never needs to pull it in a second time.

@JRobert Thanks for clarifying. Makes sense :)


text:
ArduinoJson is not adding string to JsonObject. ArduinoJson broken?
So I've got this code

String GetTimeString(){
    strftime(dateArray, 100, dateFormat, getTimeInfo());
    dateString = String(dateArray);
    Serial.println(dateString);
    return dateString;
}

Being called later like this:
document["Time"] = GetTimeString();

But the resulting object looks like this:

September 12 2020 09:49:04
{"DryBulbTemp":80.762,"WetBulbTemp":72.74606,"Pressure":398.9942,"Humidity":68.32129,"Time":null}

So it behaves this way no matter if I print what comes out of the function immediately before the assignment to the "Time" property.  Is ArduinoJson just broken?

https://arduinojson.org/v6/faq/why-is-the-output-incomplete/

ArduinoJson 6 works with fixed memory allocation.
When you create a JsonDocument, you must specify its memory capacity.
If the capacity is too small, some parts will be missing.
The solution is to increase the capacity of the JsonDocument.
Use the ArduinoJson Assistant to know the memory requirements for your project.

It is not at all logical that the 'Time' Property would persist but not the value.  Nor is the requirement for the allocation to be N+2 whats actually in there.  But sure, downvote my question.

I didn't downvote your question. If you believe ArduinoJson is broken, please open an issue on GitHub. If you want to learn how the library works, please read the documentation.


text:
Timers, PWM pins and digital outputs on Arduino Mega
I'm using an Arduino Mega to control motors via PWM and Adafruit DRV8871 motor drivers.  I also use TIMER1 for a timed interrupt.  After adding the TIMER1 interrupt I discovered I had problems with motor control, which I finally tracked down to using pins 11 & 12 for PWM simultaneously with using TIMER1 for timed interrupts.
My initial thought was to change the timer used for the ISR to avoid the pin 11/12 conflict, but now I'm uncertain as to what the restrictions are for using pins associated with timers.  I now realize that pins associated with a timer interrupt can't be used for PWM using analogWrite(int val), but can they be used as general purpose digital outputs?
For instance, if I change from TIMER1 to TIMER0 for my timer interrupt, that appears to change the pin dependency from 11/12 to 4/13.  I don't use pin 13, but I do use pin 4 as a digital output.  Will using pin 4 as a digital output still work properly?
TIA,
Frank

Are you sure you are using an Arduino Mega? pins 11 and 12 aren't PWM pins on the mega. Only on the UNO. The Mega has like 6 timers, so you'd have plenty to choose from, to avoid conflicts.

You can use them for any purpose other than PWM.  You can even use them for PWM as long as the settings for the timer allow you to produce the waveform you want.
The reason PWM broke was that you had changed the settings for the timer.  The timer is what controls the PWM.  When you changed those settings you either turned the PWM function off or set some setting where it wouldn't work.  Then the pins associated with that timer didn't get PWM anymore.  You can do anything else you want that doesn't involve the timer including use the pin for input or output or any other special function it has not related to the timer.
If you change the timer interrupt to TIMER0, then you run the risk of delay, millis, and micros stop working right.  They depend on the TIMER0 overflow interrupt running at a set interval to count time.  It depends on how you set the timer up.
I would suggest you do some reading on how these timers work.  The Datasheet for the ATMega328P chip is a great place to start.


text:
How to rotate servo every 12 hours using RTC module?
I am trying to make a auto fish feeder to feed my fish every 6hours. I want to implement RTC module to my code. So far I've been using only an arduino and a servo using this as a code:
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  myservo.write(15);
}

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
      // Wait for 12h
    delay(6 * 3600000);
}

The RTC module I have is the DS1302. It's library cn be downloaded here
The code for the clock is this:
// DS1302_Serial_Hard
// Copyright (C)2015 Rinky-Dink Electronics, Henning Karlsen. All right reserved
// web: http://www.RinkyDinkElectronics.com/
//
// A quick demo of how to use my DS1302-library to
// retrieve time- and date-date for you to manipulate.
//
// I assume you know how to connect the DS1302.
// DS1302:  CE pin    -> Arduino Digital 2
//          I/O pin   -> Arduino Digital 3
//          SCLK pin  -> Arduino Digital 4

#include <DS1302.h>

// Init the DS1302
DS1302 rtc(2, 3, 4);

// Init a Time-data structure
Time t;

void setup()
{
  // Set the clock to run-mode, and disable the write protection
  rtc.halt(false);
  rtc.writeProtect(false);

  // Setup Serial connection
  Serial.begin(9600);

  // The following lines can be commented out to use the values already stored in the DS1302
  rtc.setDOW(FRIDAY);        // Set Day-of-Week to FRIDAY
  rtc.setTime(12, 0, 0);     // Set the time to 12:00:00 (24hr format)
  rtc.setDate(6, 8, 2010);   // Set the date to August 6th, 2010
}

void loop()
{
  // Get data from the DS1302
  t = rtc.getTime();

  // Send date over serial connection
  Serial.print("Today is the ");
  Serial.print(t.date, DEC);
  Serial.print(". day of ");
  Serial.print(rtc.getMonthStr());
  Serial.print(" in the year ");
  Serial.print(t.year, DEC);
  Serial.println(".");

  // Send Day-of-Week and time
  Serial.print("It is the ");
  Serial.print(t.dow, DEC);
  Serial.print(". day of the week (counting monday as the 1th), and it has passed ");
  Serial.print(t.hour, DEC);
  Serial.print(" hour(s), ");
  Serial.print(t.min, DEC);
  Serial.print(" minute(s) and ");
  Serial.print(t.sec, DEC);
  Serial.println(" second(s) since midnight.");

  // Send a divider for readability
  Serial.println("  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -");

  // Wait one second before repeating :)
  delay (1000);
}

So the question here is, how can I set up my code to work with RTC, in order to move the servo every 6 hours?

if you can print the time, then you can operate a servo when the time is equal to a predetermined value ... it is unclear what is giving you trouble

I have trouble coding, to be honest. Do you think you could help me with that?

start with the bottom code ... insert a line that prints "hello" when seconds is equal to 10

Thanks for your help, I'll try to figure it out with your tips...

stary by doing the simplest modification to existing code ... printing a message when second is at particular value teaches you how to run a command when a variable contains a specific value ... choosing seconds means that you do not have to wait very long for results ... next, you add code that moves a servo ... that will also move every 60 seconds ... when it works correctly, then change the watched variable to hours

This is my first time trying to code, those codes you see are found open source hahaha... What you said, sounds hard for me. But I guess this would be my best shot if no one else shows up to help me out of that hahaha. Thanks buddy.

If you think you can help me further by modifying this code for me, it would be really appreciated! By me and my fish! hahaha

start by trying out the example codes that are included with the arduino IDE ... learn how conditional code works using if statements

Does this answer your question? How do you combine 2 different sketches together

Does this answer your question? Code for fish auto feeder not working

You have to spend some time and practice coding, it does not come over night. As far as your timing look up for an alarm clock sketch that will do what you want.  Once you understand that you should only have to add a few lines of code. As far as open source the tools you are using are open source. Remember there are people out there that are expertes and there people just starting so expect what you find to fall some in that range of quality.