text:
Conditional randomization gets stuck
First-time poster here...
I have the following code to randomize note values and store them in an array loop1[i], where i is a specific step in the loop:
nextNote = random(-2, 3);
note = note + nextNote;

loop1[i] = note;

while (loop1[i] == loop1[i - 1] ||
       loop1[i] == loop1[i - 2] ||
       note > 6 ||
       note < 0) {
  nextNote = random(-2, 3);
  note = note + nextNote;
  loop1[i] = note;
}

(I hope this is clear enough).
Now, it usually works to a certain point until the sketch loops forever in order to randomize an allowed number. Therefore, my questions are:
Running an ATmega 2560, is this actually a task too demanding for the processor or should I suspect that it's not working properly?
How can I optimize the code, but retain the conditions above in order to avoid the loop getting stuck?

if note is bigger that 6 before the while, and your random value for nextNote has a higher chance of being positive rather than negative, the most likely scenario is that note will gradually keep increasing, and increasing, and increasing. So your while loop will get "stuck" gradually increasing note, and not doing anything else. Are you sure you don't mean note>0 and note<6 to limit the note values to between -1 and 9.

Thanks for your reply. Short answer to your last question: my intention was to limit the number range from 0 to 6. I fixed that using constrain().

Well, constrain isn't used inside this while loop, so it will still give the problem I described above. I think you'd need something like if(note>6)nextNote=random(-2,-1);else nextNote=random(1,3); in order to ensure it goes back into range again. That should fix the "infinite-loop" problem you are now having.

Now i understand what you're getting at. I've rewritten the code to make it entirely conditional instead of re-randomize prohibited values. Appreciate the input.

I think you have a problem with your math here, not with your code. What
you are simulating is very similar to a 1-dimensional random
walk.
According to the linked MathWorld page, for such a process “the most
probable number of sign changes in a walk is 0”.
If, at some point in your program, the loop starts with note == 6, and
then it starts randomly going up, there is a sizable probability for it
to never go back to values below 7.

Edit: One possible solution could be to avoid the random-walk notion
and instead repeat the random choice always from the same starting
point.
int oldNote = note;  // starting point
do
    note = oldNote + random(-2, 3);
while (
    note == loop1[i - 1] ||
    note == loop1[i - 2] ||
    note > 6 ||
    note < 0);
loop1[i] = note;

Yes, i think you have a point. Earlier i used a model for statistically distributing the probability, in order to restrain the randomization within range. It became a bit overdone, so i was aiming for an easier solution. Now i have new problems, haha... Care to elaborate on a solution? Math is definitely not one of my strengths.

@Erik: I edited the answer with a suggested solution. Not the most effective, by far, but close enough to the code you posted.

Some reasons why it will not work:

My feeling is that i gets too big, i.e. it is higher than the length of the array you are using. That can cause crashes, or at least unpredicted results. You can easily check this by printing the value of i (and check against the maximum value).
I don't see problems with the while loop (although I would use brackets around note > 6 and around note < 0, but I don't think this is really needed.
If the value gets below 0 or higher than 6, still random values are added, assume the value is +10... then it might take a lot of time (if ever) for that value to reach max 6 again. The same is true for values < 0. Maybe you should never allow values of less than 0 and higher than 6 anyway, or making the random values in such a way they tend to go towards the average (3).

Tip to debug:
However, the easiest way to debug this is to print all relevant variables (e.g. nextNote, note, i, the last two notes loop[i-2], loop[i-1] and the current note loop[i]... Also print a line inside the while loop so you know when you skip it or not. This probably will give you enough information to see what is wrong.

Thanks for your quick feedback, i should probably have included the code for the entire for-loop as it loops OK. However, i did a bit of optimization using constraint() and do/while conditions instead.

The line loop1[i] = note doesn't belong in the loop (or above it); you're not changing i in the loop, so you're just rewriting the same location over and over again.
As for the loop itself, what sort of use case do you have for this, and what sort of distribution do you want? Waiting until it's between 0 and 6 is horribly inefficient. You need to decide what sort of distribution you want and implement it more directly. For instance, you could have a piecewise quadratic distribution by getting a random number between zero and sqrt(3), then squaring the result, and then randomly choosing whether to subtract the result from 6.


text:
Very Basic Arduino Uno Serial.readString() operation
I am very new to Arduino Programming.
I am trying to identify the input string from serial monitor and printing the output to the console accordingly
Code is :
void setup() {
       Serial.begin(9600);
}

void loop() {

   while (Serial.available() > 0 ) {

     String str = Serial.readString();

     if (str.equals("send")) {
        Serial.println("identified");
     } else {
        Serial.println("unknown");
     }

   }

}

Whenever i put send string it is showing "unknown" as the output, which is wrong, and i should get "identified" as the output.
Can anyone guide me here to achieve the result.
Note : I am getting output as i wanted by using readStringUntil function but the strings has a lot of "." in it, hence not useful.

what is your line end setting in Serial Monitor?

both NL and CR.

then check for "send/r/n"

send/r/n not working.

then print it to see. with print, not println

and the baud rate setting in Serial Monitor is 9600 baud?

i added Serial.print(str); below readString , in serial monitor it is showing the propper string whatever i am typing , but still no results.

Let us continue this discussion in chat.

You mean \r\n not /r/n...

@Majenko : tried that too. no result though.

The problem with relying on things like readString is you really don't know what they are doing or how they work. Parse the incoming data manually so you know what it is you are working with.

If you set your Serial Monitor's line ending to "Both NL & CR", then this code will find the word "send". It will NOT find the word "send" in this string, "ssend" or in this string, "sendd".
void setup(){
  Serial.begin(9600);
}

void loop(){
  while(Serial.available() > 0 ){
    String str = Serial.readString();
    if(str.substring(0) == "send\r\n"){
      Serial.println("identified");}
    else{
      Serial.println("unknown");
    }
  }
}

If you want to find the string "send" in "1234send" or "send1234" or "1234send5678" then use indexOf();
void setup(){
  Serial.begin(9600);
}

void loop(){
  while(Serial.available() > 0 ){
    String str = Serial.readString();
    if(str.indexOf("send") > -1){
      Serial.println("identified");}
    else{
      Serial.println("unknown");
    }
  }
}

There are any number of reasons the *.equals test is false. Consider case difference or extra characters introduced from the source of your communications.  Even non printable characters may pose a problem and cause the test to fail.
Consider using *.substring() instead.  This method will return true if the substring is found.  For example:
  String stringOne = "12345 send 1234";

  // substring(index) looks for the substring from the index position to the end:
  if (stringOne.substring(0) == "send")
  {
    Serial.println("identified");
  }
  else
  {
    Serial.println("unknown");
  }

...should always return "identified" because the characters 's', 'e', 'n' and 'd' are found in the correct sequence within the string stringOne.

String str = Serial.readString();
if (str.substring(0) == "send")
  Serial.println("identified");
else
  Serial.println("unknown");

this did not work even.

Odd.  Did you look at the linked to web page to make sure you were using substring correctly?  (This web page?).  Also, I see from the comments that you did print it out the received string and you did see "send" in the received message, correct?  You may just want to comment out the serial read line and try using "String str = "12345 send 1234";" to test if everything is working. Judging for other comments you might quickly try sending (typing in) "space"+"send"+"space" (" send ") to see if that works.

That won't work.  substring(n) just returns the portion of the string starting at position n.  So substring(0) just returns a copy of the string. str.substring(0,4) will return the frist 4 characters of the string  (assuming there at lest 4 chars to return - I'm not familiar enough with this implementation to know what it does for a shorter string - C# would throw an exception).

void setup() {
       Serial.begin(9600);
}

void loop() {
   char inChar[5];

   if(Serial.available() > 0 )
   {
     for (int i=0; i<5; i++)
     {
      inChar[i] = Serial.read();
      delay(10);
     }

     if (inChar[0] == 's' && inChar[1] == 'e' \
                          && inChar[2] == 'n' \
                          && inChar[3] == 'd')
         {
          Serial.println("identified");
         }

     else
     {
       Serial.println("unknown");
     }
  }
}

Reading the String "send" using Serial.readString() command is fine. But somehow it will not work if you use the result for comparing ( e.g data == "send" ...). A possible solution is to use character array (e.g inChar[5]). The size of the array is 1 more than the maximum characters needed.

source: Stack Exchange

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

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

sort: votes


text:
Arduino keypad and RF 433MHz transmitter problem
So, the basic idea is that user presses a key on keypad, and key that is pressed is sent with RF transmitter.
I got individual parts to work(keypad and transmitter), but can't send the actual key. When I try to send it, I get a strange string on the other end. I am convinced its simple issue with my syntax, so if anyone could help me, that would be great. Code is below:
#include <RH_ASK.h>
#include <SPI.h> // Not actually used but needed to compile
RH_ASK driver; //use this driver for transmitter

#include <Keypad.h>
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte rowPins[ROWS] = {10, 9, 8, 7}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {6, 5, 4, 3}; //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup()
{
    Serial.begin(9600);   // Debugging only
    if (!driver.init())
         Serial.println("init failed");
}

void loop()
{

    char key = keypad.getKey();

    if (key){
      Serial.println(key);//outputs correct key
      //transmitter part
//      const char *msg = "Hello World!";
      const char *msg = key;//here is the problem, when i send the string above, it works okay, when I send this, i get strange string on other end
      driver.send((uint8_t *)msg, strlen(msg));
      driver.waitPacketSent();
      Serial.println(key);//outputs correct key
      Serial.println("packet_sent");
    }
}

With the VirtualWire library, the (unused) pins are assigned to certain pins. You could check the source code of the RadioHead library which pins are used by default or you can set every possible pin that RadioHead can control to unused pins.

Sir, can you please share the receiver's side program?

The problem is you send a character of type char, thus exactly one byte.
However, when you send it you have to give the length and you use strlen. However, msg is an array (at least that is what you want), but that array contains only the character to sent. What you want is to send only 1 character, so use 1 instead of strlen.
Also, you can get rid of the special msg pointer and instead of
  const char *msg = key;//here is the problem, when i send the string above, it works okay, when I send this, i get strange string on other end
  driver.send((uint8_t *)msg, strlen(msg

use
  driver.send(&key, 1);

Where &key defines the address (pointer to) key, and since there is always exactly 1 byte in key (the key itself), 1 can be used. To be more safe, you can use sizeof(key) thus
  driver.send(&key, sizeof(key));

What you also can do is create a string that ends with \0, so the first is the character to send, and strlen can be used, but the easiest way is to set the length to exactly 1.
Actually, using strlen on a string that does not end with \0 can result in strange behavior, because maybe there is no \0 in memory.

Thanks for your answer, I tried both solutions (just "1" and sizeof), and it got me closer to the solution. On the other side I get "1k⸮⸮⸮******8" when the key value is 1, "2k⸮⸮⸮******8" for 2, and so on.
Again sorry for needing to be handheld, but as PHP programmer, this is whole new world for me :)

No problem, I think the writing is ok, but maybe where you read it (where you get the package) you have to do the same... If the other side expect a null terminated string, than try to send a string of 2 characters, first is the keypad value, second is a null string, and send length 2.
However, since the first character is correct, I think, you can just do a read of exactly 1 character (which is the character you want). The k⸮⸮⸮*****8 part is just some random memory that is not written since the buffer is only 1 byte.

You were right, I updated receiver code and it works correctly now. Thanks for your help!

You're welcome, good luck with your project

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


text:
Arduino reads hc-05 device connecting status
Hello I want to get an arduino get status of bluetooth hc 05 if connect with device or not . I'm trying by myself and search on internet website but I can't find useful things.

Can you show us the code you have written so far?

if (Serial1.available()) {   Serial1.print("AT+BIND");  Serial.println(Serial1.print("AT+BIND"));  }

This's one code of codes who I tryed .  The other codes mybe the same but with some differents order...

In hc05 there is led that shows you Bluetooth is paired or not. In datasheet it says that connected the PIO9 pin. You can connect this pin to arduino's digitial input pin. After that you can understand is it paired or not.
AT+BIND? gives you which device you currently paired.

If I connect PIO9 pin maybe it's get write in serial.read()  if it's connect or not ...?

No its not like that. When you paired this led turns on so if you make a little bit solder and you can get a wire from there and put this wire to arduino's digitial input pin. When Bluetooth paired this pin goes HIGH and if its not connected this pin goes LOW

Ok I edited the post check it again

Different Bluetooth adapters (using the HC-05 module) provide different signals, besides its Rx and Tx. Most bring out a "key" input that puts the module into command mode where serial communication is between the external pins and the module itself - 'AT' commands & queries to the module's firmware. When the module is not in command mode, the firmware just passes serial data through the Bluetooth radio, ignoring the content. Some provide an LED- or State signal that you can read (or observe on an LED) to know whether the devices is paired (communicating) or unpaired (in command mode).
On some, this is a simple logic signal; on others it is a square wave of 1/2 to 1 Hz which means your code has to track the signal to know whether it is static (typically High when paired) or toggling (for unpaired/waiting to pair).
You need to read your module's datasheet to find out the behavior of this signal on your particular module. If you connect an LED to this signal, or your module has one on the board, you can often make a good enough guess by observing it with a stopwatch. Either way, you then need an Arduino function that samples the LED periodically, remembering what state it saw and for how long, to decide whether the LED is blinking or is steady.


text:
How to make a button work a second time in my code?
I am making a security system, and the alarm starts when the button gets pressed. If i turn the alarm off by the serial communication, and want to turn it on again using the button, it will only let the alarm go on for about 0.5 seconds. Does someone see the mistake i'm making, and can help me? Thanks in advance!
const int ledrood = 11;
const int ledgroen = 12;
const int buttonPin = 2;
int buttonState = LOW;

int statePin = LOW;
const int trigPin = 9;
const int echoPin = 10;
long duration;
int distance;
bool alarm = false;
int speakerPin = 8;
String Message = "";
String NMessage = "";
String Command = "";
int index = 0;
bool Bericht = true;

void PlaySong()
{
  tone(speakerPin, 4699, 500);
  delay(1000);
  tone(speakerPin, 4699, 500);
  delay(1000);
  tone(speakerPin, 4699, 500);
  delay(1000);
  tone(speakerPin, 4699, 500);
  delay(1000);
  tone(speakerPin, 4699, 500);
  delay(1000);
  tone(speakerPin, 4699, 500);
  delay(1000);
  tone(speakerPin, 4699, 500);
  delay(1000);
}
void alarmaan()
{
 alarm = true;

  digitalWrite(ledrood, HIGH);
  digitalWrite(ledgroen, LOW);
  digitalWrite(trigPin, LOW);

 }

void AlarmUit() {
  Serial.println("alarm uit");
  alarm = false;
  digitalWrite(ledgroen, HIGH);
  digitalWrite(ledrood, LOW);
  digitalWrite(trigPin, LOW);

 }
void setup() {
  pinMode(ledrood, OUTPUT);
  pinMode(ledgroen, OUTPUT);
  pinMode(buttonPin, INPUT);
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  Serial.begin(9600);
 }
String Doorsturen() //Methode om te communiceren via de serial monitor
{
 if (Serial.available() > 0)
  {
   char readChar = (char) Serial.read();
   NMessage = NMessage + readChar;
  }
  if (NMessage.startsWith("#") && NMessage.endsWith("%"))
  {
   index = NMessage.indexOf("%");
   NMessage = NMessage.substring(1, index);
   Serial.println(NMessage);
   Command = NMessage;
   NMessage = "";
   Bericht = true;
  }
  else if (NMessage.endsWith("%"))
 {
   NMessage = "";
 }
 return Command;
}
void loop() {
 Message = Doorsturen();
 int buttonState = digitalRead(buttonPin);
 digitalWrite(trigPin, HIGH);
 digitalWrite(trigPin, LOW);
 duration = pulseIn(echoPin, HIGH);
 distance = duration * 0.034 / 2;
 Serial.print("Distance: ");
 Serial.println(distance);

 if (alarm == false) {
   digitalWrite(ledgroen, HIGH);
 }

 if (Message == "alarm_off")
 {
   AlarmUit();
   Message = "";
 }
  if (Message == "1234")
  {
   AlarmUit();
   Message = "";
  }
  if (Message == "aan") {
   alarmaan();
   Message = "";
   }

  if (alarm == false) {
   if (buttonState == HIGH) {
    delay(50);
    while (digitalRead(buttonPin) == HIGH) {}
    alarmaan();
    Serial.println("fout");
   }
  }

  if (distance < 10 && alarm == true) {
   PlaySong();
  }

 if (alarm == true) {
   if (buttonState == HIGH) {
    delay(50);
    while (digitalRead(buttonPin) == HIGH) {}
    alarmaan();
    Serial.println("Test");
   }

 }
}

Please create a minimal, complete, verifiable example of the problem. Strip out all the extraneous stuff, tune playing and so on, and include only the code required to demonstrate the problem. You'll probably fix it yourself in the process, and if not, someone will have an easier time helping, and hence you're more likely to get useful help.

Could you provide the serial output you are getting? How can you see that the alarm is only on for half a second?

@Gerben Serial output is 'Distance: ...' + 'alarm uit', this keeps looping. I know the alarm is on for short because i see 'alarm on' (test in this case) only once and the red led (meaning the alarm is on) only flashes once, then goes back to green led (alarm off)

The problem is that Message = ""; doesn't actually do anything, because the next time doorsturen is called, it will just load the previous command from the command variable. I'd suggest having the doorsturen function only return the command once, and not on consecutive calls.
String Doorsturen() //Methode om te communiceren via de serial monitor
{
  Command = "";
  if (Serial.available() > 0)
  {
    char readChar = (char) Serial.read();
    NMessage = NMessage + readChar;

    if (NMessage.startsWith("#") && NMessage.endsWith("%"))
    {
      index = NMessage.indexOf("%");
      NMessage = NMessage.substring(1, index);
      Serial.println(NMessage);
      Command = NMessage;
      NMessage = "";
      Bericht = true;
    }
    else if (NMessage.endsWith("%"))
    {
      NMessage = "";
    }
  }
  return Command;
}

see comment in the code
if (alarm == false) {
  if (buttonState == HIGH) {
    //here you set alarm to true
  }
}

...

if (alarm == true) { //now this if statement is true
  if (buttonState == HIGH) {//also buttonState is still high, because it's never updated after you set alarm to true

  }

to fix do this
if (alarm == false) {
   if (buttonState == HIGH) {
    delay(50);
    while (digitalRead(buttonPin) == HIGH) {}
    delay(50);// this is to negate switch bounce, on release, from interfering
    buttonState = false;// add this line
    alarmaan();
    Serial.println("fout");
   }
  }

This does not seem to work, the alarm 'on' only still works for about half a second, then it switches off again...

I think I found the problem. See my edited answer.

It works! Thank you very much for the help, i really appreciate it. Have a nice day :)


text:
Basic Arduino Question. Trying to turn off leds turned on through the serial monitor by using a push button
I'm new to using the serial monitor. I have a code set up so that LEDs turn on when I type an input on the keyboard. I know how to turn them off using a keyboard but I and can't figure out why the leds won't turn off when I press a push button.
    #define led1 10 //10th,
    #define led2 11 //11th
    #define led3 12 //12th
    #define led4 13 //13th
    #define ButtonA 9

    int ButtonState;
    int ButtonState2;
    int state;
    int StateNow;
    int PreviousState = HIGH;

    void setup(){
      pinMode(led1,OUTPUT);
      pinMode(led2,OUTPUT);
      pinMode(led3,OUTPUT);
      pinMode(led4,OUTPUT);
      pinMode(ButtonA,INPUT_PULLUP);
      Serial.begin(9600);
      Serial.println("Enter ch a, b, c, or d:");
    }

    void loop() {
    if (Serial.available())
    {
      ButtonState = digitalRead(ButtonA);
      delay(10);
      ButtonState2 = digitalRead(ButtonA);  //debounce
      if (ButtonState != ButtonState2)
      {
        StateNow = ButtonState2;
      }
      else
      {
        StateNow = ButtonState;
      }
      if(StateNow == LOW && PreviousState == HIGH)
  {
    digitalWrite(led1,LOW);
    digitalWrite(led2,LOW);
    digitalWrite(led3,LOW);
    digitalWrite(led4,LOW);
    Serial.println("Turned off all LEDs");
    PreviousState = LOW;
  }
  else if(StateNow == HIGH && PreviousState == LOW)
  {
    PreviousState = HIGH;
  }
  state = Serial.read();
  if (state == 'a' || state == 'A')
  {
    digitalWrite(led1,HIGH);
    Serial.println("Turned on led 1");
  }
  else if (state == 'b' || state == 'B')
  {
    digitalWrite(led2,HIGH);
    Serial.println("Turned on led 2");
  }
  else if (state == 'c' || state == 'C')
  {
    digitalWrite(led3,HIGH);
    Serial.println("Turned on led 3");
  }
  else if (state == 'd' || state == 'D')
  {
    digitalWrite(led4,HIGH);
    Serial.println("Turned on led 4");
  }
}

}

The LEDs turn on properly and I know the circuit is wired correctly so it's definitely something I'm missing in the software

you check the button only when serial is connected

So should I check the button outside of serial being connected?

why would you even ask? just try it.

To turn off all leds when button is pressed, you must detect a rising or falling in the button signal.

In your code you detect the change only if serial is available, but you should do it in the loop.
The simple way to detect the change is doing this in every loop:
if (StateNow != PreviousState) {
  if (StateNow == LOW && PreviousState == HIGH) //button pushed
  {
    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);
    digitalWrite(led3, LOW);
    digitalWrite(led4, LOW);
    Serial.println("Turned off all LEDs");
  }
  PreviousState = StateNow;
}

I simplify your code and add some comments:
#define led1 10 //10th,
#define led2 11 //11th
#define led3 12 //12th
#define led4 13 //13th
#define ButtonA 9

int state;
int StateNow;
int PreviousState;

void setup() {
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(ButtonA, INPUT_PULLUP);
  Serial.begin(9600);
  Serial.println("Enter ch a, b, c, or d:");
  PreviousState = digitalRead(ButtonA);
}

void loop() {
  //detect changes in button signal to turn off leds
  StateNow = digitalRead(ButtonA);
  if (StateNow != PreviousState) {
    if (StateNow == LOW && PreviousState == HIGH) //button pushed
    {
      digitalWrite(led1, LOW);
      digitalWrite(led2, LOW);
      digitalWrite(led3, LOW);
      digitalWrite(led4, LOW);
      Serial.println("Turned off all LEDs");
    }
    PreviousState = StateNow;
  }

  //check serial biffer to turn on leds
  if (Serial.available())
  {
    state = Serial.read();
    if (state == 'a' || state == 'A')
    {
      digitalWrite(led1, HIGH);
      Serial.println("Turned on led 1");
    }
    else if (state == 'b' || state == 'B')
    {
      digitalWrite(led2, HIGH);
      Serial.println("Turned on led 2");
    }
    else if (state == 'c' || state == 'C')
    {
      digitalWrite(led3, HIGH);
      Serial.println("Turned on led 3");
    }
    else if (state == 'd' || state == 'D')
    {
      digitalWrite(led4, HIGH);
      Serial.println("Turned on led 4");
    }
  }
}


text:
ATMega328p (Arduino) Timer1 set-up
I am trying to measure AC power using an Arduino with an Atmega328p.
In summary, I want to use timer1 to make an interrupt every 400us where I measure two ADC channels (A0 and A1) and put them into an array. The problem is that instead of measuring five mains periods (mains frequency = 50Hz so 20ms * 5), I get instead 13 of these periods (260ms). What am I doing wrong?
volatile int sample_incremental = 0;

void setup() {
      Serial.begin(115200);
      pinMode(voltagePin, INPUT);
      pinMode(currentPin, INPUT);
      set_sample_interrupt();
      sei();
    }

void set_sample_interrupt() {
  //Count to 400us
  OCR1A = 99;
  //Mode 4, CTC
  TCCR1B |= (1 << WGM12);
  //Enable interrupt
  TIMSK1 |= (1 << OCIE1A);
  //Prescaler 64
  TCCR1B |= (1 << CS11) | (1 << CS10);
}

ISR (TIMER1_COMPA_vect) {
  // action to be done every 400 usec
  current_sample[sample_incremental] = analogRead(currentPin) - 504;
  voltage_sample[sample_incremental] = analogRead(voltagePin) - 512;
  if (sample_incremental < (SAMPLES * PERIODREADS))
    sample_incremental++;
  else {
    //Disable interrupt
    TIMSK1 &= ~(1 << OCIE1A);
    sample_incremental = 0;
    finishedReading = true;
  }
}

Where after I do one reading, I stop the interrupt, and SAMPLES * PERIODREADS = 250.

Since you've omitted extremely much of your code, I'll guess that you have not declared the variable "sample_incremental" as volatile.

Sorry about that, is has a large portion for computing RMS and real power that is not relevant to the question. Unfortunately that is not the problem as I have declared sample_incremental as volatile.

please post a graph of what you expect and what you actually get

The Arduino core library configures the Timer 1 for phase-correct PWM at
about 490 Hz. Then you are setting some configuration bits in the
timer's control registers without clearing the bits that had previously
been set by the Arduino core. If you want to use the timer for your own
purposes, and configure it by yourself, you should completely overwrite
the core's configuration with your own. For that, use the = operator
rather than |=, as in:
OCR1A  = 99;                         //Count to 400us
TIMSK1 = (1 << OCIE1A);              //Enable interrupt
TCCR1A = 0;
TCCR1B = (1 << WGM12)                //Mode 4, CTC
       | (1 << CS11) | (1 << CS10);  //Prescaler 64

This is the right answer, I fixed it using "  TCCR1A = 0;
TCCR1B = 0;
TCNT1  = 0;" as a "hack" but your reply goes to the problem. Thank you!


text:
Why does void loop() stop after some samples?
I am not getting any compile time error. After some samples of data void loop() stops executing. Please let know what the problem is. Below is my code.
Thanks and regards
Thippeswamy
#include<SPI.h>
float amplitude=1.5;
int freq1=20; int freq2=12;
int k=20;float A= amplitude*k;
int Fs=10550; float sine[5000]; float Fs1=3000;
int i=0;int reg1=1; int reg2=0;
int sample1=Fs/freq1; float sample2=Fs1/freq2;

void setup() {
  int SS=10;
  pinMode(SS, OUTPUT);
  SPI.begin();
}

void data(int reg, int data) {
  digitalWrite(SS,LOW);
  SPI.transfer(reg);
  SPI.transfer(data);
  digitalWrite(SS,HIGH);
}

void loop() {
  for(int j=0;j<sample1||i<sample2||i>=sample2);j++) {
    float s=A*sin((2*3.14*freq1*j)/Fs);
    sine[j]=s+190;
    data(reg1,sine[j]);
    if(i<=sample2) {
      float s=A*sin((2*3.14*freq2*i)/Fs1);
      sine[i]=s+190;
      data(reg2,sine[i]);
      i++;
    } else if(i>sample2) {
      float s=A*sin((2*3.14*freq2*i)/Fs1);
      sine[i]=s+190;
      data(reg2,sine[i]);
      i++;
    }
  }
}

please format your code properly (indent at least 4 spaces)

how do you know that the code stops?

I find it hard to believe you are not getting a compiler error because this line for(int j=0;j<sample1||i<sample2||i>=sample2);j++) has a bracket too many.

Also I really don't like the conditions used in that if... It looks like it's likely to end up with j being more than the size of your sine[] array since you have no absolute bounds checking...

Your huge sine[] array serves no useful purpose. Get rid of it and just data(reg2, s + 190);.

float sine[5000]
...
sine[j]=s+190;

A float takes 4 bytes. You are allocating 5000 of them which is 20000 bytes. The Uno has 2048 bytes of RAM. Thus you are running out of RAM and overwriting something you shouldn't be.

As pointed out on the Arduino forum, your for loop which tests for:
i < sample2 || i >= sample2

will always be true. Of course i will be either less than or greater than or equal to sample2.

Hi, Now i have chanced the data type to int and reduced the value to 1000, even now also same thing is happened

1000 x 5 = 5000 which is still more than 2048.

On arduino.cc forum OP has the same question, only there he mentions Arduino Due http://forum.arduino.cc/index.php?topic=520194

See amended answer. Your for loop will never end.


text:
What's the difference between DDRB and pinMode?
It's my understanding that the following lines are equivalent. They seem to be interchangeable in my sketch:
DDRB = 1<<DDB0;

and
pinMode(0, OUTPUT);

Is the first form (DDRB...) setting a micro-controller address directly? Is that assembler?
And is the second form (pinMode) using an included library? Maybe the avr/io.h library?
On a Digispark ATTiny85.

They are not interchangeable. DDRB = 1<<DDB0; sets PB0 to output, and it also sets every other I/O pin to input. It's not assembler, no. In assembler you would write sbi _SFR_IO_ADDR(DDRB), 0.

DDRB |= 1<<DDB0; would be equivalent to pinMode(0, OUTPUT);. The latter has the side-effect of being slower though.

@EdgarBonet if not assembler, what is it? C? Is it really the same language as pinMode(), just setting lower-level bits directly? thx

It is C (or C++, they are the same for this statement). The pinMode() form invokes a library function which does the same thing as the other form.

@EdgarBonet Did you mean to say,'......sets every other I/O pin of Port B to input"?

@MarsSojourner: Yes, indeed. DDRB only controls port B.

@EdgarBonet What if you want to set only bit 5 of Port B as an input? Would the programming syntax then be DDRB = 1<<DDB5; ?

@MarsSojourner: That would set PB5 as output and all the other PBn as inputs. To set PB5 as output without touching the other pins, use DDRB |= 1<<DDB5. To set it as input without touching the other pins, DDRB &= ~(1<<DDB5).

Yes, on a simple microcontroller like the ATTiny the two lines of code are equivalent.  The function pinMode(...) just looks up what pins relate to what ports in a table and set the right registers.
Using DDRB instead of pinMode(...) is fine as long as you are never going to run your code on anything else (or give it to anyone else to run), since you have now hard coded into your sketch what pins are to be used. It is more efficient to use DDRB though. You sacrifice portability for efficiency.
However, for more complex microcontrollers that have many many functions on a single pin, just manipulating DDRB (or the equivalent on the target microcontroller) may not be enough. You may need to switch the pin into GPIO mode, disable analog inputs on the pin, or other operations as well. All that will be wrapped up in the pinMode(...) function for you by the Arduino API so you don't need to worry about it.
So, in short, if you don't care about portability, and you do care about efficiency and code size (which may well be the case on an ATTiny) then yes use DDRB and its friends.

i understand that analogWrite() eliminates the need to enable output-mode completely -- neither DDRB nor pinMode() statements are needed. Is analogWrite() even less efficient than pinMode() + analogWrite()? -thx

The pinMode is redundant. PWM is a special mode that is not controlled by GPIO but a signal from a timer.

"as long as you are never going to run your code on anything else" --I assume the DDRB syntax is valid at least for the entire ATTiny line, if not beyond. No?

@johnywhy: It even works on the ATmegas. Note, however, that for setting pin 0 to output on an Arduino Uno you would use DDRD instead of DDRB, because pin 0 on the Uno is on port D rather than port B. With the pinMode() function you use the pin numbers that are printed on the silkscreen of the board, and you don't have to worry about the pin to port mapping, because the function takes care of this for you. You sacrifice efficiency for convenience.

@EdgarBonet yep, i understand the efficiency vs convenience tradeoff. Just confirming that the registers are, or are not, the same across the ATTiny family.

@johnywhy Have you heard of "datasheets"? All the registers and what they mean are in them...

I'm asking about your answer. You said "as long as you are never going to run your code on anything else", implying that no, the addresses are different even between different ATTiny's. Is that your intended meaning? thx

@johnywhy "anything else" even includes the same chip in a different board with different pins being needed to be manipulated. If you need to use pin B3 instead of pin B0 on a different board with the same chip you will have to change your code. Using pinMode, as long as both pins are numbered the same in the IDE, there will be nothing you need to change.

DDRB

is a register. Exactly: Port B Data Direction Register. See datasheet for ATtiny, chapter 10.4. Register Description and 10.2.1 Configuring the Pin. This part will explain why

DDB0

value was used.
Using this way of setting direction of a pin is much faster than  pinMode(0, OUTPUT);
The possible problem is when you want to use same code to program different Arduino. In this case you have to remember to check all direct registers operations.


text:
Can't stop my variable value at zero?
In my recent project, I want to set my time according to the requirement. And somehow I'm able to manage that. But when I'm decreasing my time value then one weird problem happens. When decreasing my time value, when I reach ZERO (0) and when I again decrease value then it shows the maximum range of that data type even if I put the condition for stop value at ZERO(0).
My code is below:
const int kPinSw1 = 2;
const int kPinSw2 = 3;

int plusBtnIncState = 0;
int lastPlusBtnIncState = 0;

int minusBtnDecState = 0;
int lastMinusBtnDecState = 0;

unsigned long currentMillis;
unsigned long previousMillis;
unsigned long interval = 0UL;

void setup() {
  Serial.begin(9600);
  pinMode(kPinSw1, INPUT_PULLUP);
  pinMode(kPinSw2, INPUT_PULLUP);
}

void loop() {
  //---------------INC_TIMER---------------//
  plusBtnIncState = digitalRead(kPinSw1);
  if(plusBtnIncState != lastPlusBtnIncState) {
    if(plusBtnIncState == HIGH) {
      interval = interval + 1000;
    }
    delay(50);
  }
  lastPlusBtnIncState = plusBtnIncState;

  //---------------DEC_TIMER---------------//
  minusBtnDecState = digitalRead(kPinSw2);
  if(minusBtnDecState != lastMinusBtnDecState) {
    if(minusBtnDecState == HIGH) {
      interval = interval - 1000;
      if(interval <= 0) {
        interval = 0;
      }
    }
    delay(50);
  }
  lastMinusBtnDecState = minusBtnDecState;

  //---------------------------------------//
  Serial.print("Int:");
  Serial.print(interval);
  Serial.print("\n");
}

And output:
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:4294966296
Int:4294966296
Int:4294966296
Int:4294966296
Int:4294966296
Int:4294966296
Int:4294966296
Int:4294966296

As you can see in output when I reach ZERO and then again decrease the value then the value is like 4294966296 instead of ZERO. I put the logic for that if we reached ZERO or less ZERO then it must stay at ZERO. I don't understand why this happens. Please suggest me something.

do not decrement once you reach zero

The interval variable is unsigned long.
In this example, we are using int that are 4 bits long (just to keep thing short) just to subtract 1 from 0:
    0b0000
   -0b0001
    ------
    0b1111

That is normal arithmetic, but in binary.
The result 0b1111 can read as a signed int, in which case we read the value '-1', or you can read as unsigned, and you read it as '15'.
The same thing is working in your case, only that your int are 32 bits long.
The unsigned keyword is not a promise that "0-1" will produce "0". It only indicates that whatever bit configuration is inside that variable, it will be treat as a positive value.

That is probably because I advised to use unsigned long for the interval here: https://arduino.stackexchange.com/questions/47996/how-to-start-particular-event-for-particular-time-using-millis I didn't know that it was going to be lowered and could become negative.

The variable "interval" is an unsigned long.  This means it can not go negative.  It also means that it is made up of a 32 bits.
Instead of going negative, an unsigned variable will cycle to its most maximum value by following a modulo 2 math behavior.  So a 32 bit value will become 2^32 or 4294967296 if, for example, decremented 1 past 0.
In the above program the 32 bit value was decremented by 1000 past 0 resulting in 4294967296 - 1000 or 4294966296.
Testing if an unsigned number is negative is futile.  So this code:
  if(interval <= 0)
  {
    interval = 0;
  }

...does nothing.  Instead, test if "interval" is larger than 1000 before subtracting 1000.

As already mentioned in previous answers, the issue is that an unsigned
number wraps modulo MAX+1. The obvious fix would be to make interval a
signed number.
Another option would be to avoid subtracting from interval anything
larger that interval itself. You could do this by replacing
interval = interval - 1000;
if(interval <= 0) {
  interval = 0;
}

by
if (interval >= 1000)
  interval -= 1000;
else
  interval = 0;

Note that the else clause could be dropped if you can guarantee that
interval is always a multiple of 1000.


text:
Digispark ATtiny85 keyboard
I have a small project that I have in mind and I'm pretty new with Arduino.
I want to make a small device that if a key was pressed it would do something.
Now I know I could use a button with the device but I want to specifically use a Cherry MX Blue Switch.
So I wanted to know if the test code I wrote up would get me in the right stating place and I want to know where I would wire the key switch onto the board.
From how I have the code written I'm guessing I connect the positive pin from the switch to P0 on the board and the other pin to ground on the board, is this correct?
#include "DigiKeyboard.h"

void setup() {
    pinMode(0, INPUT);
}

void loop() {
    // put your main code here, to run repeatedly:
    if(digitalRead(0)==HIGH){
        DigiKeyboard.sendKeyStroke(MOD_GUI_LEFT,KEY_R);
        DigiKeyboard.print("test");
    }
}

Try Googling: "Arduino INPUT_PULLUP", "Arduino button edge detection" and "Arduino button debounce".

is there something special about cherry mx blue switch? ... i thought that it is just a SPST switch

I just really like cherry mix blue switches tbh

I would suggest to connect one pin of the with to 5v and the other to ground. The Arduino will be able to detect 5v as logic HIGH.
The code looks correct except for better programming technique I would suggest to indent you code, this make debugging easier for longer programs:
#include "DigiKeyboard.h"

void setup() {

   pinMode(0, INPUT);

}

void loop() {
  // put your main code here, to run repeatedly:

  if(digitalRead(0)==HIGH){

    DigiKeyboard.sendKeyStroke(MOD_GUI_LEFT,KEY_R);
    DigiKeyboard.print("test");

  }
}

so should i connect it to pin 0 and 5v?
since in the code its telling it to look at pin 0.

The pin which you originally connected to gnd connect to 5v

So so the switch would be connected to 5v & p0?

Yes, this means when the switch is closed p0 will be able to detect 5v as login high

This wont' work unless you add an external pulldown resistor to GND. Connecting the switch between the digital input and GND has the advantage that you don't need an external resistor, as you can use the internal pullup by setting the pin mode toINPUT_PULLUP. This was already suggested by @tttapa in his comment.

When the switch is connected the pin will go high, and when disconnected the pin will be floating but will never reach 5v which still reliablly work

Do you want the absolute lowest power consumption? If yes then instead of using a microcontroller, use a dual D type latch. The circuit below will take the first break of the optical beam, turn on the output for that latch, and will block the other latch from turning on.
When the clock input goes high (beam broken) the high on the D input is transferred to Q and -Q will go low. That low will force the output of the other latch to stay low.
To reset the light the push button switch is used to clear the Q output. It is then ready again.
I didn't show the power supply (bypass cap). The chip is a CD74HC74. 14 pins containing two latches.The only current drawn is the LED current and the current of the opto-transistors.


text:
Uploading code to Mega 2560 is stuck
I'm trying to upload code from a Mac (online Arduino editor) onto an Arduino Mega2560, to connect a motor to pin 52 and Ground to get it to move. But at the top it says busy (like it does when it uploads) and doesn't do anything else. Refreshing the page doesn't work. The code is verified, and here's the code:
void setup() {
}

void loop() {
  digitalWrite(52,HIGH);
}

The Arduino application (with same code copied in) comes up with this error:
Arduino: 1.8.4 (Mac OS X), Board: "Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)" Sketch uses 1190 bytes (0%) of program storage space. Maximum is 253952 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 8183 bytes for local variables. Maximum is 8192 bytes.
avrdude: ser_open(): can't open device "COM1": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device
ioctl("TIOCMGET"): Inappropriate ioctl for device
avrdude: ser_send(): write error: Bad file descriptor
avrdude: stk500_send(): failed to send command to serial port
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer
the selected serial port avrdude: stk500v2_getsync(): timeout communicating with programmer does not exist or your board is not connected

I hope someone can work out why it doesn't upload!

What specific online Arduino editor? There are more than one. Also, the Arduino pin cannot supply enough power to drive a motor.

It's https://create.arduino.cc/editor. The motor works when I connect it to the power section GND and 5/3.3v pins. Because of the error codes, have I damaged the port?

The power pins are can supply much more energy than the IO pins.  Your error text notes COM1, but Macs don’t call ports COM1. You need to set the port correctly to upload. But you won’t get the motor to work on a data pin anyway.

Ok I'm new to Arduino so that really helps thanks. But still why won't the code upload?

You have to figure out the right serial port. I’m not familiar enough with the online editor to help you on that. I just know COM1 is wrong on a Mac.

I would suggest to download the Arduino app (https://www.arduino.cc/en/Main/Software).
Download both the latest version and an a legacy build (https://www.arduino.cc/en/Main/OldSoftwareReleases#00xx). Within the DMG for the legacy you'll need to install the FTDI drivers to allow Arduino app to see the Arduino in ports.

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


text:
Why is my DS18B20-PAR not picked up?
I have had a DS18B20-PAR for some time and have often used it without a problem until now. Yesterday it just suddenly stopped working. I was trying to use it along with two i2C sensors at the time. I don't really know of anything which could have fried it, though.
Edit: It is turning out much more complicated than I thought. I can't ever get it to work on pin 10. The sensor sometimes works on other pins (3, 9 and 11), but it often does not. I can still use pin 10 to blink and fade an LED, and receive input from a button, but it never picks up my DS18B20-PAR. What is happening here?
My setup:
I have just one DS18B20-PAR connected to my Arduino Uno look-alike as shown in the following image:

Please note that on the DS18B20-PAR the third pin is internally not connected.
The code:
My Arduino is running this code (a OneWire example sketch which has always worked before):
#include <OneWire.h>

// OneWire DS18S20, DS18B20, DS1822 Temperature Example
//
// http://www.pjrc.com/teensy/td_libs_OneWire.html
//
// The DallasTemperature library can do all this work for you!
// http://milesburton.com/Dallas_Temperature_Control_Library

OneWire  ds(10);  // on pin 10 (a 4.7K resistor is necessary)

void setup(void) {
  Serial.begin(9600);
}

void loop(void) {
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float celsius, fahrenheit;

  if ( !ds.search(addr)) {
    Serial.println("No more addresses.");
    Serial.println();
    ds.reset_search();
    delay(250);
    return;
  }

  Serial.print("ROM =");
  for( i = 0; i < 8; i++) {
    Serial.write(' ');
    Serial.print(addr[i], HEX);
  }

  if (OneWire::crc8(addr, 7) != addr[7]) {
      Serial.println("CRC is not valid!");
      return;
  }
  Serial.println();

  // the first ROM byte indicates which chip
  switch (addr[0]) {
    case 0x10:
      Serial.println("  Chip = DS18S20");  // or old DS1820
      type_s = 1;
      break;
    case 0x28:
      Serial.println("  Chip = DS18B20");
      type_s = 0;
      break;
    case 0x22:
      Serial.println("  Chip = DS1822");
      type_s = 0;
      break;
    default:
      Serial.println("Device is not a DS18x20 family device.");
      return;
  }

  ds.reset();
  ds.select(addr);
  ds.write(0x44, 1);        // start conversion, with parasite power on at the end

  delay(1000);     // maybe 750ms is enough, maybe not
  // we might do a ds.depower() here, but the reset will take care of it.

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE);         // Read Scratchpad

  Serial.print("  Data = ");
  Serial.print(present, HEX);
  Serial.print(" ");
  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
    Serial.print(data[i], HEX);
    Serial.print(" ");
  }
  Serial.print(" CRC=");
  Serial.print(OneWire::crc8(data, 8), HEX);
  Serial.println();

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {
      // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
  } else {
    byte cfg = (data[4] & 0x60);
    // at lower res, the low bits are undefined, so let's zero them
    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    //// default is 12 bit resolution, 750 ms conversion time
  }
  celsius = (float)raw / 16.0;
  fahrenheit = celsius * 1.8 + 32.0;
  Serial.print("  Temperature = ");
  Serial.print(celsius);
  Serial.print(" Celsius, ");
  Serial.print(fahrenheit);
  Serial.println(" Fahrenheit");
}

On the serial monitor is just prints "No more addresses." every 250 milliseconds.

If the setup worked fine and then stopped, you must examine what changed. If your code is unchanged then it could be your sensor or your Arduino.
You can try putting the sensor on a different input pin and update the code accordingly.
You can try the sensor on a different Arduino or a new sensor if the same type on your Arduino.
These are the first steps to troubleshooting.

I don't have another Arduino or another sensor unfortunately.


text:
Using a pushbutton to power Arduino on and off
I need help adding a pushbutton to provide power to an Arduino to save power, as I am using a battery and the same button to power it off. This is the circuit I wish to implement.

Thanks.

Not exactly what you are asking, but useful: http://www.zolalab.com.br/eletronica_projetos/auto_shutdown_enus.php.

Use a toggle button. Mechanical. No fancy electronics needed and 100% efficient.

you posted a useless picture of a bunch of components that have absolutely nothing to do with powering the Arduino, and you did not include the battery, which does.

If you want advice on how to power an Arduino circuit, then the circuit diagram you provide should SHOW THE POWER SOURCE!

Also, you need a flyback diode to protect your transistor from back EMF from the motor.

You can use the button as a switcher for the Arduino power. Just wire up the button between the battery + out and the Arduino's Vin port.

This would totally work for a high-power toggle button or switch, as opposed to a momentary push button. It is a simple solution, so I give it an upvote. For a solution which could use a low-power momentary push-button plus a transistor or relay, see my answer here: https://arduino.stackexchange.com/a/77428/7727.

You can attach an interrupt and just turn the arduino in sleep mode. If one of your mudules drain power while beeng inactive and drains less than 20mah while working than connect the VCC to one of the digital pins and when the arduino wakes up just turn the pin to HIGH.

This is a hardware/software "bootstrapping" problem: you need a power switch to be controlled by an Arduino, but the power switch also feeds power to, or turns ON the Arduino, which means the Arduino can't control the power switch until the Arduino is ON, and the Arduino can't be ON until the power switch is ON. Each relies on the other, so you must "bootstrap" it to turn it on and get the cycle started.
The process will look like this: you mechanically press a button with your finger, which controls either the Gate of a MOSFET transistor or the Base of a BJT transistor (or it could even power ON a normally-off relay), momentarily turning it ON. This split-second of ON time is just enough to turn on the Arduino, which now commands a signal to the Gate or Base to keep the transistor ON. Now, the Arduino maintains its own power, continually sending the necessary signal to the transistor to keep the transistor ON, which in turn powers the Arduino to keep the Arduino ON. Now, you can press another button to turn the Arduino OFF. This other button press will be read simply as a button press and the Arduino will then command the digital output pin to stop sending the signal which keeps the transistor ON, thereby turning the transistor OFF, which then turns the Arduino OFF. Now, the whole system is 100% OFF. The Arduino isn't even in sleep mode, it's just 100% not powered anymore. You use your finger press on the ON button again to bootstrap the whole system and start the process over again.
As for all of the details, this is an interesting problem I've been wanting to implement for years. I suspect it could be done with a single button, but haven't gone through the design to prove it yet. Meanwhile, for simplicity's sake, just use two separate buttons: one for ON and one for OFF, as I describe above.


text:
Convert String data To char Array in Arduino
I'm able to get json data and storing in String object, now i want to convert string into Char Array for parsing json data
I'm tried with this code, but it is not responding
      String data = http.getString();   //Get the request response payload
      Serial.println(data);                     //Print the response payload
      int len=data.length();
      Serial.println(len);

      char  buf[len + 1];
      data.toCharArray(buf, len + 1);
      int bufLength = sizeof(buf);
      Serial.println(bufLength);   //Printing nothing

Tried c_str()?

No, can you tell me how it converts String JSON data to char Array

Your code does work when I try it: all the Serial.println() do print their stuff. 2) It converts the String to a char array by giving you “direct access to the internal String buffer”. It's written in the doc I linked to.

for me, it is printing like this
Exception (9):
epc1=0x40203d9e epc2=0x00000000 epc3=0x00000000 excvaddr=0x64522072 depc=0x00000000
after len

There is no need for char array. It's possible to access elements inside of String by data[index]. Or you can use ArduinoJson library

One of your problems is you don't know what sizeof does. I think you wanted to use strlen.


text:
Weird Voltage Noise
I'm new to this forum, so hello to everyone out there.
So I have an Uno with A0 connected to the positive end of a chain of LEDs (they light up when a motion sensor goes off, clunky, but it works), and the negative end is hooked up to the GND of the analog side of the Uno. It runs the following code:
void setup()
{
  Serial.begin(115200);
  pinMode(A0, INPUT);
  pinMode(A1, INPUT);
}

void loop()
{

  Serial.println(printVals(A0));
}

float printVals(uint8_t pin)
{
  int sensorValue = analogRead(pin);
  float voltage = sensorValue * (5.00 / 1023.00);
  return voltage;
}

And when I open the Serial Plotter, I get a weird square wave for the voltage (when there is 0V on the LEDs, I used a volt meter).
Out of curiosity, I added a jumper cable from A2 to +5V (the red wire in the diagram) and added plotting for A2, and this solved the problem - except now, the read on A0 is about 0.53.
Now, I'm more of a software guy, so I figure just subtract 0.53 and move on (varies only +- 0.03V), but I want to know: What in the world did that jumper cable do?

There is a tiny capacitance in the ADC sampler, and if the signal you are measuring is weak, the stored charge in the ADC can affect the reading, depending on what else is going on.  Like multiplexing readings from A0 and A2.

A0 connected to the positive end of a chain of LEDs - you did what? Can you sketch up a schematic?

A square wave of what values?

The square wave is between 0 and roughly 0.5, and when I added the jumper, it was a mostly straight line at about 0.5V.

And this is a driveway motion sensor, so sense I don't have direct access to the trigger wires, I am connected to the indicator LEDs of the system, they have about 2-2.5V on them when lit, and they are only lit when motion is detected.

Just realized that the analog port being read from (intended to have the jumper on it) was A1, even though the jumper cable was connected to A2. Either that, or I was reading A2, but initialized A1 instead.

It is better to use an optocoupler. This will give the galvanic isolation between the devices. And use a digital input instead of an analog. Since the indicator has only two states.

I give you +1 for posting a minimal/complete code that show your problem.

@Ferba, my chain of LEDs is actually part of a circuit board for a driveway monitor receiver. When it detects motion, the LEDs light up and the voltage measured by analogRead increases by about a volt.
Also, as it turns out, the jumper to +5v was functioning as a pull-up wire... not a good idea. It burned out the chip in the driveway monitor by backfeeding an output.
In the end, I added an "_PULLUP" after the INPUT in setup and that solved the problem.

Why are you connecting a chain of leds to a pin setted as an input and then connected to GND? I think that is like connect the pin to nothing.
in the documentation of arduino they have a note about the funcion analogRead() and a fluctuation of data.
https://www.arduino.cc/reference/en/language/functions/analog-io/analogread/
i think if you need to read an input put a button (or maybe i didnt understand you scheme)


text:
Alternative to UART/I2C LCD displays?
I'm building a MIDI synthesizer on Arduino Uno, and am considering user interface options.
I see on Adafruit and Sparkfun there are 16x2 LCD panels available that interface via I2C serial or by UART, but I think neither of those will work in my application:

The UART is clocked at 31250 baud to receive MIDI, and that's not a supported baud rate for these LCD devices;
I'm producing audio by driving an external DAC (MCP4725) over full-speed I2C; any transmission to another device would audibly jitter the DAC output;
SoftwareSerial would get around the UART clocking problem, but I believe it would stall the main loop while driving the output.

One option might be to roll my own software serial routine, carefully clocking it on the main loop, which (I believe) reliably runs at either 14.8KHz or 22.2KHz depending on the DAC protocol in use. I could set a SparkFun SerLCD into a slow data rate (2400 baud) and count passes through the main loop to time the data output.
Another option would be to use a secondary MCU -- I have a surplus Trinket M0 on hand -- and define a custom synchronous serial protocol between the two MCUs, and have the secondary relay commands to the LCD but that's getting into Rube Goldberg territory.
Any obvious options I'm overlooking?

Old 16x2 LCDs doesn't have an interface really, just a bunch of cables to connect to some unused pins. Modern OLED comes in I2C and SPI versions.

Also consider using an Arduino Mega, which has 4 UARTs.

@LookAlterno: IIRC, it's a sort of synchronous, either 8-bits or 4-bits, parallel interface.

There are a few interrupt-based SoftwareSerial alternatives floating around that will not stall your loop.

The standard HD44780 LCD interface is defined as a "6800 CPU bus interface" with optional 4-bit mode. That is not "sort of synchronous" nor "not an interface really" but rigidly defined in operation. The I2C and UART LCDs just provide a third party interface (IO expander, small MCU, etc) to that 6800 CPU bus interface.

UART is considered "point-to-point", so as a rule of thumb you shouldn't attach more than two devices. Usually serial LCDs come with a I2C or SPI interface, or you can use any parallel LCD connecting the required 7 pins (4 data, 3 control). Or you can use a shift register to control it (there are plenty of schematics on the internet and I think all the libraries support these modes). In any case, high-speed I2C (the 3.4Mbps one)? Are you sure the arduino uno supports this? Did you already try it? If, as I think, the uno is capped to 400kbps, I suggest you to switch to an SPI ADC (a bit faster)

@frarugi87 I meant full-speed I2C (400k) for the DAC, not high-speed - will edit. I'm only using the input side of the UART currently for MIDI, so I figured the output side would be available. Parallel LCD seems like the best solution, but I'm running short of pins, so I may have to lose some indicator LEDs if I go that route.

@RussellBorogove ok, then if you use the I2C only to communicate with the DAC (and never release it - this means you will have to write your library, since you need to never send the stop byte and the address) you will be able to continuously feed the DAC with two bytes for each sample, which are roughly 19 bits. At 400kbps, the sample rate of the signal can be at most 21 kHz. Is it enough? In my opinion it is better to switch to a SPI DAC (e.g. from the same supplier the MCP4921, or lower resolution variants MCP4911 or 4901), which is much faster to control

Yep, the requirements for a grungy bass synth are different from those for a symphony ;) I was actually using the sample-at-a-time mode of the 4725, so getting ~14khz from it — and putting it directly through a fixed lowpass at ~4500. In any case I’m probably switching to PWM output.

One obvious option would be to get a display with SPI interface, since you have it available. Another option is to get a DAC running on SPI, and use the I2C for the display.
If you insist on using one of these 16x2 LCDs, there are SPI adapters for them as well. Example


text:
How to post JSON data from Arduino?
I want to post data that I'm getting from the sensor every 5 seconds to my application in JSON format. Initially, I'm getting data as int and converting into String.
For example:
if data=15, it is converting into string.
String st=String(data);

Now I want to post st every 5 seconds.
    int S2 = http.sendRequest("PUT", "{\"itemId\":\"64006A962B71A1E7B3A0428637DA997C.327681\",\"item\":{\"Properties\":{\"AssetSensorDistance\":\"+st+\"}},\"operationType\":\"Update\",\"originalItem\":{\"Work_Order\":{\"ItemId\":\"64006A962B71A1E7B3A0428637DA997C.327681\"},\"Properties\":{\"AssetSensorDistance\":\"+st1+\"}}}");
    Serial.print("Sensor Status: ");
    Serial.println(S2);

st1 is the previous value, it is printing httpcode -2(invalid Syntax).
Can anyone help me with this issue?
Thanks in advance.

I take it, at some other point in your program, you are telling it where to post the data to?

To My Application

please provide detailed information in your question about what you are observing. ... there appears to be a contradiction in your statements

The string
"{\"AssetSensorDistance\":\"+st+\"}"

contains a literal "+st+". If you want to do string concatenation, you
should terminate the string with a double quote character, then add st,
then use another double quote to start the second part of the string:
"{\"AssetSensorDistance\":\""+st+"\"}"

it displaying as +st+ in my application instead of value

@AnneLingesh: That's what I wrote in my answer: you have a literal “+st+” in your string.

I didn't understand @Edgar Bonet 2

it displaying as +st+ in my application instead of value ... your post says that it does not work, that you are getting invalid Syntax ... which is it? you are either getting some data to your application, or you are not getting data to your application.  .... update your question with more information

Getting data but which I'm not expected, I want to display value in my application not st(text)

@AnneLingesh: Please, read my answer again slowly, paying attention to each word and punctuation. If there is still something you do not understand, tell us what exactly you do not understand.


text:
LED Programme where it delays the amount written in the Serial Monitor
I have written a simple code to delay the blinking of LED 13, the delay time is set by us.I have incurred a problem when I enter a 2 digit value in the serial monitor.There is some problem with the ASCII. Is there a way to solve this problem without using Serial.parseInt().
void setup()
{
  Serial.begin(9600);
  Serial.println("Programming is starting");
  pinMode(13,OUTPUT);
}

void loop()
{
  if(Serial.available())
  {
    int val=Serial.read();
    int val1=val-'0';
    Serial.println(val1);
    digitalWrite(13,HIGH);
    delay(val1*1000);
    digitalWrite(13,LOW);
  }
}

Blink without delay.

I know this .But i want to use ascii for 2 digit.

It does not use serial monitor.

Here you have.
No error checking. Anything not digit produce zero as output.
void setup()
{
    Serial.begin(9600);
    Serial.println("Programming is starting");
    pinMode(13,OUTPUT);
}

void loop()
{
    static int value = 0;

    while(Serial.available() > 0) {
        int c = Serial.read();

        if(isDigit(c)) {
            value = value * 10 + (c - '0');
        } else {
            Serial.println(value);
            digitalWrite(13,HIGH);
            delay(value*1000);
            digitalWrite(13,LOW);
            value = 0;
        }
    }

It convert chars to values as they are being readed, one by one. There are no size limit for the input string, other that final value must fit in an int
You write a value in the Serial Monitor and end it with return, space bar or whatever non digit key you want.


text:
How to prevent optocoupler to activate when resetting the arduino?
From various example on how to use optocouplers ( eg 4N25)  I gathered that they
work in inverted way meaning that for the optocoupler to output a signal,
the input LED must be OFF.
This is very easy to process by code as I just need to use digitalWrite LOW
instead of digitalWrite HIGH to activate the output of the optocoupler.
My problem is that when I reboot the arduino, the optocupler LED goes OFF and thus activate the ouput of the optocoupler for a few seconds until the code is loaded on the arduino.
How can I prevent this behavior ? Should I connect the optocoupler in a non inverted way ? ( And if so how ? ). Should I use an inverter ?

An optocoupler has no "default" way of working - inverted or non-inverted. It all depends on how it is wired up.

Thanks for the answer Majenko. It seemed to me that most of the time they were presented as inverted though. Is there a reason for this ? Practicability ? Performance ? Or maybe I got the wrong impression.

What controls optocoupler in your case? https://electronics.stackexchange.com/a/219882/141930

Show your circuit or we cannot help you.

The Fairchild datasheet for 4N25 shows this diagram:

describing the (or 'an') operation of the device. If this is how yours is operating, and if the input side is connected between an output pin and ground, then yes, on reset, the LED will go out and the switched output will go high. If you connect the device's input between the pin and +5v, the LED will light on reset, taking the switched output low. Plus, the switched output will now have the same sense as the Arduino output pin: i.e., digitalWrite(PIN, HIGH) will turn the switched output on, and vice-versa.


text:
Arduino hardwareSerial Bluetooth.println not sending string over 310 chars
Hey all I am wondering if my code below can be modified in order for the Arduino to send more than 300 chars to a HM-10 bluetooth 4.0 le module?
#include <SoftwareSerial.h>
#define SERIAL_BUFFER_SIZE 512

SoftwareSerial bluetooth(8,9); // RX, TX
String btString;
String comString;
int isVS;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {;}

  Serial.println("PC Side Connected");

  bluetooth.begin(115200);
  while (!bluetooth) {;}

  bluetooth.println("Bluetooth Side Connected");
}

void loop() {
  if (Serial.available() > 0) {
    //The IDE Sends and the phone receives
    comString = Serial.readString();

    //Check to see if this request is coming from Visual Studio
    isVS = comString.indexOf("_VS");

    if (isVS > -1) {
      //Is coming from Visual Studio so display it over serial port
    } else {
      //Not coming from VS so send it to the bluetooth phone
      //bluetooth.write(comString);
      bluetooth.println(comString);
    }
  }

  if (bluetooth.available() > 0) {
    //The phone sends and the IDE receives
    btString = bluetooth.readStringUntil('\n');
    Serial.println(btString);
  }
}

As in my code above, I've already tried to add the #define SERIAL_BUFFER_SIZE 512 to the top to give the software serial more buffers but that does not allow me to send more than ~310 chars.
So sending this string:

{MAC:'00-14-22-01-23-45',settings:{rgb:true,quotes:true,sleep:false,timeFrame:{on:'05:30:00',off:'22:30:00'},reset:false,weatherZip:'57104',userInfo:{left:'John
  Rambo',right:'T100'}},wifiInfo:{Name:'ItBurnsWhenIP',Pwd:'AwHk6gKnsMdxw3boWWAhus5NNCV304YQb/2287QqzH0WnS5W59vCzzW2pR8kgHI79hAUglQOCcBiEKiNWRBQ3oyvyJ0/fDfM1aKa9gfoy3kGHA=='}}

works just fine but if i send out a little more information:

{MAC:'00-14-22-01-23-45',settings:{rgb:true,quotes:true,sleep:false,timeFrame:{on:'05:30:00',off:'22:30:00'},reset:false,weatherZip:'57104',userInfo:{left:'JohnRambo',right:'T100'}},wifiInfo:{Name:'ItBurnsWhenIP',Pwd:'AwHk6gKnsMdxw3boWWAhus5NNCV304YQb/2287QqzH0WnS5W59vCzzW2pR8kgHI79hAUglQOCcBiEKiNWRBQ3oyvyJ0/fDfM1aKa9gfoy3kGHA==','testing
  out some more strings'}}

It shows everything but the gs'}} at the end on the iphone.
How would i go about fixing this so i can send much more than this?

Re work it to not use String. The problem isn't serial, it's how you're storing the data.

Alright mind showing me an example?

You need to understand both these blog posts: https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/ and https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/


text:
rev id and read_rev_id() function
What is a rev id? I have looked everywhere for a proper definition but I haven't found anything. I am trying to understand the code below. I don't understand why this read_rev_id function is necessary and yes, I tried to look in the user manual for the IMU I am using but it is practically none-existent. I am using the myAHRS IMU and the only manual I could find, on GitHub, didn't even show a register by this name.
void setup()
{
  //Initialization
  Wire.begin();
  Serial.begin(115200);
  who_am_i();
  read_rev_id();
  delay(1000); //Wait for 1second.
}

somebody named one of their functions read_rev_id.  ... look to where you got the program.

You haven't provided enough information for anyone to easily help you. Assuming that you took your code from GitHub myAHRS_plus_i2c.ino you can look further down the file to find the definition of read_rev_id(). It simply reads the revision number from the AHRS chip and displays it on the console. Since this is all that it does you could leave out the call to read_rev_id(). But if you are going to use it then be aware that it contains an obvious bug. The second read() should be to I2C_SLAVE_REG_REV_ID_MINOR.
//READ REVISION ID
int read_rev_id()
{
    uint8_t id_1 = 0;
    uint8_t id_2 = 0;
    read(I2C_SLAVE_REG_REV_ID_MAJOR, &id_1, 1);
    read(I2C_SLAVE_REG_REV_ID_MAJOR, &id_2, 1);
    Serial.print("READ REVISION ID= "); Serial.print(id_1); Serial.println(id_2);
}


text:
Unable to use Keyboard library with Arduino UNO even after changing the firmware
So I'm trying to use my UNO as an HID device. I followed this tutorial, flashed the firmware and got the UNO to be detected as an HID device.
However, I am still getting the error

'Keyboard' not found. Does your sketch include the line '#include '?

Here's the code -
/*
Copyright (c) 2014 NicoHood
 See the readme for credit to other people.

 Keyboard example
 Press a button to write some text to your pc.
 See official documentation for more infos
 */

// include HID library
#include <HID.h>

const int pinLed = 13;
const int pinButton = 8;

void setup() {
  pinMode(pinLed, OUTPUT);
  pinMode(pinButton, INPUT_PULLUP);

  // Starts Serial at baud 115200 otherwise HID wont work on Uno/Mega.
  // This is not needed for Leonado/(Pro)Micro but make sure to activate desired USB functions in HID.h
  Serial.begin(115200);

  // Sends a clean report to the host. This is important because
  // the 16u2 of the Uno/Mega is not turned off while programming
  // so you want to start with a clean report to avoid strange bugs after reset.
  Keyboard.begin();
}

void loop() {
  if (!digitalRead(pinButton)) {
    digitalWrite(pinLed, HIGH);

    // Same use as the official library, pretty much self explaining
    Keyboard.println("This message was sent with my Arduino.");
    Serial.println("Serial port is still working and not glitching out");

    // simple debounce
    delay(300);
    digitalWrite(pinLed, LOW);
  }
}

/*
Definitions:

 KEY_LEFT_CTRL
 KEY_LEFT_SHIFT
 KEY_LEFT_ALT
 KEY_LEFT_GUI
 KEY_RIGHT_CTRL
 KEY_RIGHT_SHIFT
 KEY_RIGHT_ALT
 KEY_RIGHT_GUI

 KEY_UP_ARROW
 KEY_DOWN_ARROW
 KEY_LEFT_ARROW
 KEY_RIGHT_ARROW
 KEY_BACKSPACE
 KEY_TAB
 KEY_RETURN
 KEY_ESC
 KEY_INSERT
 KEY_DELETE
 KEY_PAGE_UP
 KEY_PAGE_DOWN
 KEY_HOME
 KEY_END
 KEY_CAPS_LOCK
 KEY_F1
 KEY_F2
 KEY_F3
 KEY_F4
 KEY_F5
 KEY_F6
 KEY_F7
 KEY_F8
 KEY_F9
 KEY_F10
 KEY_F11
 KEY_F12

 KEY_PRINT
 KEY_SCROLL_LOCK
 KEY_PAUSE
 */

Can anyone point out what I'm doing wrong here?

Okay, so the problem was that the added HID library was conflicting with the core Keyboard/Mouse library. I replaced the core library with the new one and it worked without any problems.
Well one problem actually, it would ask for a platform.h. To solve this download the Arduino v1.5.7 BETA zip and find the platform.h file in it and paste it in your current Arduino directory.

If I open the rar library file, than I see a file called Keyboard.h. I'm sure you need to include Keyboard.h, than the class Keyboard is known and you can use it in your sketch.

I've tried doing that... It doesn't work. Still gives the same error


text:
Make Arduino send and receive at the same time
I am working on a project where I connect a GPS module and GPRS SIM900 shield. The location will be sent when it recives a certain character.
Now my question is, can the Arduino receive from GPRS and GPS module data at the same time? The GPS is not given coordinates, however it works properly without receiving a message from the GPRS.
I am using softwareserial  for both. Should/can I use hardware serial and softwareserial?

You cannot receive from two softwareserial devices at the same time.

I am using SoftwareSerial for both.

As others have said, you cannot listen to 2 SoftwareSerial ports at the same time.

Should/can I use HardwareSerial and SoftwareSerial?
... can the Arduino receive from GPRS and GPS module data at the same time?

Yes, but...
This answer provides full details on choosing "good" combinations of hardware and software serial ports.  To summarize:

Use the HardwareSerial port (i.e., Serial) for one of the devices.  You can still use it for debug prints, as long as the device has some kind of command "format".  For example, if commands start with "AT", just make sure that none of your debug prints start with "AT".  It is the absolute best choice.  You would have to disconnect RX pin 0 from the device in order to upload new sketches over USB.
Use AltSoftSerial for the other device.  It is the most efficient software serial port, and it can be used at the same time as Serial.  It only works on two specific pins.
NeoSWSerial is the next best choice, at limited baud rates.  It can be used with the above choices, but transmitting on NeoSWSerial prevents them from receiving.
SoftwareSerial is the worst choice.  Receiving or transmitting on SoftwareSerial prevents all of the above from receiving anything.  It disables interrupts for long periods of time.

Probably you don't need to use both GPS and GPRS in same time. Just check for a certain character from GPRS in the loop and when it comes check the GPS data.
Why not connect GPS module to hardware serial?

you can connect gps to hardware serial port rx and gsm to software serial.  in similar way,  I solve the problem


text:
Send and receive text between Arduino Mega 2560 and C# via ENC28J60
I'm working on an Arduino project that sends and receives text to/from a C# application via ENC28J60 in a LAN network. Whenever C# sends a request to Arduino (In text), Arduino responds to it by sending also a text. What is the best way to do this? I'm newbie in network programming (Or whatever it's called). Thanls in advance :)

Use a TCP socket. Give the Arduino a static IP address, run a TCP server, and have the C# application open the connection as a TCP client.

@tttapa: you mean ENC28J60 is useless here ?

No, you need the ENC28J60 to connect the Arduino to the LAN. TCP is a network protocol that works on top of the physical connection that's established by the ENC.
This could be useful (it was written for the ESP8266, a WiFi chip for Arduino, but the principle is the same.

https://github.com/ntruchsess/arduino_uip/tree/master/examples       found this on github. I think its what youre talking about.

You can use TCP or UDP protocols.
https://www.arduino.cc/en/Tutorial/UDPSendReceiveString
https://www.arduino.cc/en/Tutorial/DhcpChatServer
You can use free UDP, TCP port listener sofwares for Windows, Linux etc.. for testing your setup.
For C# development:
https://stackoverflow.com/questions/20038943/simple-udp-example-to-send-and-receive-data-from-same-socket
and
https://stackoverflow.com/questions/10182751/server-client-send-receive-simple-text

The netcat/ncat/nmap familiy of tools is also handy for those tests. They run in Linux and Windows.


text:
SSID was not declared in this scope
so I am new to arduino and coding in general, I am trying to use the arduino to remotely survey plants, I am using this guide: https://create.arduino.cc/projecthub/arduino/plant-communicator-7ea06f. The entire code is:
#include <WiFi101.h>
#include<WiFiSSLClient.h>
const char* ssid = SKY1C9D0;    //  your network SSID (name)
const char* password = SYDTSTQR;  // your network password
String httpsRequest = https://hooks.zapier.com/hooks/catch/2821422/84ehn1/;
// your Zapier URL
   const char* host = "hooks.zapier.com";
WiFiSSLClient client;
void setup() {
  Serial.begin(9600);
  while (!Serial);
  delay(2000);
  Serial.print("Connecting Wifi: ");
  Serial.println(ssid);
  while (WiFi.begin(ssid, password) != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println("");
  Serial.println("WiFi connected");
}
void loop() {
  float temperature = 22;
  int moisture = 150;
  int light = 40;
  String warning = "This is a warning message";
  warning.replace(" ", "%20");
  send_email(temperature, moistue, light, warning );
  delay(20000)
}
void send_email(float temperature, int moisture, int light, String warning)     {
  // convert values to String
  String _temperature = String(temperature);
  String _moisture = String(moisture);
  String _light = String(light);
  String _warning = warning;
  if (client.connect(host, 443)) {
    client.println("POST " + httpsRequest + "temperature=" + _temperature +                 "&moisture=" + _moisture + "&light=" + _light + "&warning=" + _warning + "     HTTP/1.1");
    client.println("Host: " + String(host));
    client.println("Connection: close");
    client.println();
    delay(1000);
    while (client.available()) { // Print on the console the answer of the server
      char c = client.read();
      Serial.write(c);
    }
    client.stop();  // Disconnect from the server
  }
  else {
    Serial.println("Failed to connect to client");
 }
}

The error is specifically highlighted here:
    const char* ssid = SECRET_SSID;    //  your network SSID (name). The error is that the ssid has not been declared.
I am unsure of what to do to fix this and any other possible errors that have gone unnoticed. I would highly appreciate any help or guidance.
Thank you

const char* ssid = "myAP"; and  const char* password = "myAP passworld"; is not working? You have to REPLACE it with correct credentials.

I have tried using correct credentials, still does not work, I removed credentials only so I could post the code online

Also the httpsRequest have to be a string, you can't just put the https address like this.

have you replaced SECRET_SSID with the actual SSID or defined a value for a variable SECRET_SSID? The error seems to be saying that SECRET_SSID is not defined or declared so the compiler doesn't know what that text is. This looks like C so is there a #define missing?

I have now edited it with the actual ssid and password, it still does not work

@KIIV how would I include the https address then?

String httpsRequest = "https://hooks.zapier.com/hooks/catch/2821422/84ehn1/";. However HTTP request should be GET, as you are not posting anything and Requested path should be without protocol and without host

A problem in the include file on the line previous could cause the following line to be misinterpreted. To test that try moving the ssid after the password and see if the error changes. Obviously make sure all strings are properly quoted.
#include <WiFi101.h>
#include <WiFiSSLClient.h>

const char* password = "SYDTSTQR";  // your network password
const char* ssid = "SKY1C9D0";    //  your network SSID (name)
String httpsRequest = "https://hooks.zapier.com/hooks/catch/2821422/84ehn1/";

You need quotes around literal string values.
const char* ssid = "SKY1C9D0" ; // your network SSID (name)
const char* password = "SYDTSTQR" ;


text:
ledkeypad shield not responsive
I recently purchased several of the DFRobot ledkeypad shields: https://www.dfrobot.com/product-1407.html
I have Arduino Leonardo (which also had some problems in the beginning, being recognized as modems).
My OS is Linux Mint, and I'm using the last Arduino IDE.
The library I use is the one recommended on the website of the vendor, LedKeypad.h, and works fine with the other shields of the same model from the same batch.
Some shields worked fine but I am now having trouble with one of them, which seems unresponsive. I can load for instance the blink program in the arduino, and it works, but the shield does not work. When it is plugged in, the fours dots are slightly red, and I cannot turn them off.
I tried displaying something on the serial monitor when the buttons are pushed, and only one of the 5 buttons works (the KEY_DOWN one).
Is there anything I can attempt to fix the problem ? Or should I just give up on this shield ?

the information that you have posted is incomplete. ... there is no mention of software ... please include all info in the question ... do not use comments to add info

@jsotola added software info, is all the relevant information there ?

what i am talking about is that you made no mention of any libraries for the arduino. there is no way to tell if you downloaded the correct libraries.

@jsotola oh sorry I added info about the library

... and works fine with the other shields of the same model from the same batch.

So had you considered that the shield might be faulty? Have you contacted the manufacturer or vendor for support?

The schematic seems to show that it uses the actual SDA/SCL pins on the digital header (next to Aref) instead of A4/A5, so it should be compatible with other boards as well. The buttons are just a voltage divider connected to an analog input, so that should work with the Leonardo as well.

I had not seen that.


text:
Arduino UNO - analogRead() returning mixed results
I have created a small circuit with a 220 Ohm resistor and a LED connected to PIN9 for power.
I want to measure the Voltage of the current flowing through the circuit. In order to do that I connected a bridge from between the resistor and the LED to the A3 PIN and used this code:
int ledPin=9;
int inPin=A3;
long int in=0;
float V_in=0;
int val;

void setup() {
  analogReference(DEFAULT);
  pinMode(ledPin, OUTPUT);
  pinMode(inPin, INPUT);
  Serial.begin(9600);
  }

  void loop() {
    if (Serial.available() > 0) {
      val = Serial.parseInt();

      if (val>=0 && val<=155) {
        analogWrite(ledPin, val);
        //Serial.println(val);

        for (int i=0; i<10; i++) {
          val+=5;
          analogWrite(ledPin, val);
          //Serial.println(val);

          delay(1000);
          in = analogRead(inPin);
          V_in=float(5.0)*(float(in)/float(1023));
          Serial.println(V_in);
          delay(1000);
          }

        }
        else {
          Serial.println("Dio è morto.");
          }
      }
    }

The problem is that when I run it, with an Input of 55, I get what seams to be a random arrangement of 0s and 2.56s. While I expect a increasing sequence of numbers between 0 and 2.5.
What am I doing wrong?
I measured the Voltage on the A3 Pin using a voltimeter, and it increases every step by 0.2, exactly as expected.
This is an output example:

That's to be expected. The analogWrite function doesn't output an analog voltage. It can only output 5V or 0V, nothing in between. It's called PWM.

It's strange your observation seams to make sense if considering the output data. The officiial Arduino documentation states that the return value for this function is an int(0 to 1023). Why should it return either 0 or 5V? https://www.arduino.cc/reference/en/language/functions/analog-io/analogread/

Note that @tttapa is referring to analogWrite, not analogRead.

It returns either 0v or Vf of the LED since that is where you have it connected.

@EdgarBonet The LED is being driven with analogWrite, so the signal being sampled is PWM.

Also, "Measure the voltage of the current flowing through..." makes no sense whatsoever.

The analogWrite function, despite its name, outputs PWM (pulse width modulation) which is either fully on or fully off, with varying duty cycles. If you run that through a RC network (eg. 4.7k in series and 10 µF to ground), it will smooth out the pulses and you will actually get a varying voltage.
So in your case you are measuring on or off depending on the timing. However since you are measuring between the resistor and the LED, you won't get 5V because of the voltage drop over the resistor. An LED, depending on the colour, might have a voltage drop of around 2.2V, and thus you might expect 2.8V at that junction. This is approximately what you got.

I want to measure the Voltage of the current ...

This doesn't make any sense electrically. You are either measuring the voltage (in volts) or the current (in amps). You don't measure the "voltage of the current". I suppose you mean "the voltage at that point".

Reference
Arduino functions reference:
Reference > Language > Functions > Analog io > Analogwrite

Measuring the voltage of the current does make sense if you measure the voltage across a known, fixed resistor. You can then use Ohm's law to determine the current through that resistor (and through the LED).

Thank you for the grat and detailed answer. I am quite new to arduino, but this answer clarified the doubts I had


text:
Arduino extended database library data type. Is char str[] in Arduino the equivalent of VARCHAR in SQL?
I am new to Arduino and I am currently working with an Arduino Uno and SD card module - SD/MMC for database storage using the Arduino database library from https://github.com/jwhiddon/EDB.
My question is, is the char str[] type the equivalent of VARCHAR?
Here is my arbitrary record definition for my table:
struct LogEvent {
  int logId;
  int unumber;
  char username[10];
  char fname[15];
  char lname[15];
  char role[6];
  char boxid[10];
  char userStatus[2];
} logEvent;

What's VARCHAR? Where is the definition of that? Are you referring to the SQL type?

I am referring to SQL type

You are asking if a SQL data type VARCHAR is "equivalent" to char str[]? What do you mean by the word "equivalent"? For one thing, SQL VARCHAR has a size associated with it: VARCHAR(size). So no, they are not equivalent.

If you mean, are these equivalent:
foo VARCHAR(100);

and:
char foo [100];

No, they are not equivalent, really. In the case of SQL you can put 100 characters into foo. In the case of C++ you would (generally speaking) put up to 99 characters into foo, with the final character being 0x00 which indicates the length of the string.
You could conceivably put 100 characters into foo but then you would have to store the size of foo in another variable.

If you're referring to the SQL type VARCHAR, then, vaguely. char username[10]; for instance will define a char array of 10 bytes. A char being the equivalent of a byte. That's about it for the type. This is C++, so you're pretty close to the iron, and a char array is about as basic as it gets. No collation, no encoding (remember that a character is not always a single byte!), no indexing. Just a bunch of bytes put together.


text:
ENC28J60 is not getting ping
I bought a new ENC28J60 module and I tried to communicate with the PC through Arduino Uno board.
When I tried to ping the address that I gave in the program it's not getting the ping. Give me some solution.
I used the web server example that is in the example section of Arduino. I even turned off my firewall setting.
The code that I used is:
/*
  Web Server

 A simple web server that shows the value of the analog input pins.
 using an Arduino Wiznet Ethernet shield.

 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13
 * Analog inputs attached to pins A0 through A5 (optional)

 created 18 Dec 2009
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe
 modified 02 Sept 2015
 by Arturo Guadalupi

 */

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 20);

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);

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

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
          client.println("Refresh: 5");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("");
          // output the value of each analog input pin
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            int sensorReading = analogRead(analogChannel);
            client.print("analog input ");
            client.print(analogChannel);
            client.print(" is ");
            client.print(sensorReading);
            client.println("
");
          }
          client.println("");
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disconnected");
  }
}

"Give me some solution." Say please.

Use EtherCard library

since 2020 you can use my EthernetENC library

You have an ENC28J60 based module. Your code is for the Wiznet-based module. The two are not interchangeable.
See this: http://nathanhein.com/2013/02/getting-arduino-online-with-an-enc28j60/
Good luck.


text:
Code that worked in Uno/Nano is not working in Mega - help me port the code to Mega
I used the code from this project... to build an oscilloscope-like project. It worked fine with Uno and Nano.
Later I tried to do the same with a Mega, but I don't know what's wrong. It's not working! Maybe due to some pin or port number mismatch (I think so...). Because it has some low level code like:
------------------------------------------------------
// set up 8 MHz timer on pin 9
pinMode (9, OUTPUT);
// set up Timer 1
TCCR1A = _BV (COM1A0);  // toggle OC1A on Compare Match
TCCR1B = _BV(WGM12) | _BV(CS10);   // CTC, no prescaling
OCR1A =  0;       // output every cycle
---------------------------------------------------------

And like:
Data.Values[i]=PINC;

I have very little knowledge about these registers.
Please help me port this code to Mega and make it work...

There is some concept you would have to learn before you can go from Arduino Uno to Mega.
Because your project is designed to operate on Arduino Uno R3, the registers operations like below are specific to the microcontroller in Arduino Uno - in this case ATmega328P-PU - datasheet here
TCCR1A = _BV (COM1A0);  // toggle OC1A on Compare Match
 TCCR1B = _BV(WGM12) | _BV(CS10);   // CTC, no prescaling
 OCR1A =  0;
You can find description of registers in mentioned datasheet in chapter 19. TC0 - 8-bit Timer/Counter0 with PWM
Now, you grab another datasheet - one which describes ATmega2560 (yes, this is microcontroller which is sitting in Arduino Mega), find corresponding pin (like OC1 in Uno - check the drawing below):

and find proper pin and corresponding register from ATmega2560 datasheet.
Take a look at the schematic picture first, select one of OCx pins and configure what is needed.
Pins from Aruino Mega with OCR functionality:

and

You need to learn what registers are, and what they can do. Can be a little demanding task, but believe me - this will give you supernatural powers in microcontrollers world ;)

Thank you very much for giving some idea about the origin of the problem, and definitely I will work on that. But, time being, I have some time constraints on the project. So, can anybody tell me how to set that 8MHz timer on any of mega pins... Also please give me some information on 'PINC'

@Thirumalesh Please realize that this is not a free design house, homework-answering service or an on-line technical encyclopedia, copied out to you on demand. People will help you take the next step if your question shows that you've done as much as you possibly could on your own - which your post doesn't.


text:
Finding ESP8266 in a network
I am connecting an ESP8266 to my home network (WiFi). After successful connection, an IP is assigned to it. I am sending commands to the ESP8266 from an Android app.
What can I do to find the ESP8266 on any network where my Android app is also connected? I ask this because whenever I change the network, a new IP is assigned to the ESP8266 and I have to manually change the IP in the Android app.
I just need to find the ESP8266 on the network, get its IP address and send commands to it.
Thanks in advance.

This question may have an answer that helps: https://arduino.stackexchange.com/questions/38092/how-do-i-know-ip-of-assigned-ip-address-to-esp8266

That's what mDNS is for. The ESP866 API has examples that show you how to use it.

@Majenko : Usefull thing mDNS is, but i am having a lot of issues , to use it in my product. I will give a try to post a new issue regarding that.
Btw thanks for the response, i really appreciate the help each time u contribute.

i am using socket to communicate with the esp8266. hence needed the ip address.

@Majenko : i have tried using mDNS but it doesn't work when the esp is in STA mode.

Did you found any solution to this ?

The best way to do this if you are doing it for product is using SSDP protocol.
It's Simple service discovery protocol which allows you to search for device in a network. It's implemented in many smart devices now a days with dlna or upnp.
Implement a SSDP server on esp8266 and
Implement a SSDP client on Android device.
You can find many devices with this approach, using simple filter to result with your specific information you want from SSDP packet can allow you to only get desired devices from network.
All the documentation about SSDP is given on Arduino esp8266 GitHub page.
You can broadcast your IP in your SSDP packet and then use it in your app, But still your most imp problem of dynamic IP remains unsolved as your IP will always be changing and using IP for accessing a hardware like home automation is not proper way.
You can either use.
1) Static IP for this if you want offline access or
2) Use cloud based solutions, such as mqtt to access device anywhere without the worries of NAT, IP or anything.
But second option is more of commercial kind, you need multiple resources to implement it.

@KarmaCoding If you think I have answered your question then upvoting or marking it as accepted answer is good idea. I can add more info to it if you want.

Some solutions that have worked for me:

Reserved IP - use the router's DHCP reservation to give the same ESP the same IP each time.
Static IP - Set the ESP to use the same IP each time, bypassing the DHCP feature altogether. This also boots the ESP slightly faster. WiFi.config(ip, gateway, subnet);
Dump the IP address to Serial on boot, so that you can at least see what's assigned: Serial.println(WiFi.localIP());
Give the STA a unique name that you can find in the router's DCHP clients page: WiFi.hostname("look_here");
use mDNS to assign a domain-like local URL to the device: MDNS.begin("esp8266");// default to "http://esp8266.local/"

useful answer too. but i am finding something to implement on a product level with different custom working protocols for multiple devices to search them in a network , where only my devices will get listed, also it must be the fastest way. i am using socket to communicate with the esp8266. hence needed the ip address.