body:
    #include <LiquidCrystal.h>
    #include <Wire.h>

    LiquidCrystal lcd(2, 3, 4, 5, 11, 12);// initialize the library with the numbers of the interface pins

    int pirPin = 7; //Variable that will receive the digital signal from the sensor
    int LEDgreen = 6; //LED addressed to the digital pin 6
    int speaker = 8; //speaker addressed to the digital pin 7
    int buttonPin = 9; // the pin that the pushbutton is attached to

    void setup(){
      pinMode(buttonPin, INPUT);// Initialize the button pin as an input:
      pinMode(pirPin, INPUT);  // declares variable pirPin as an input
      pinMode(LEDgreen, OUTPUT); // declares variable LEDgreen as an output
      pinMode(speaker, OUTPUT); // declares variable speaker as an output
      lcd.begin(16, 2);
      // turn on the cursor:
      lcd.cursor();
      Serial.begin(9600);
    }

    void loop(){
      int buttonState = digitalRead(buttonPin);// Read the pushbutton input pin:
      int pirVal = digitalRead(pirPin); //read the digital value from the pirPin and store the value in the local variable pirVal
      if(buttonState == LOW){
        if(digitalRead(pirPin) == LOW){
          /*The LED Blinks once with the command digitalWrite
          the LED keeps turned on after blink during the motion cycle*/
          digitalWrite(LEDgreen, HIGH);
          delay(1000);
          digitalWrite(LEDgreen, LOW);
          delay(500);
          digitalWrite(LEDgreen, HIGH);
          /*speaker plays frequency, the number 7 is the digital pin,
          the second number is the frequency played and the third number is the sound duration
          we repeated this command with different frequency and varying the time in order to create a
          pleasant sound */
          tone(4,261,300);
          delay(200);
          tone(4,329,300);
          delay(200);
          tone(4,392,600);
          delay(200);
          tone(4,329,300);
          delay(200);
          tone(4,392,300);
          delay(200);
          tone(4,493,600);
          delay(200);
          tone(4,392,300);
          delay(200);
          tone(4,493,300);
          delay(200);
          tone(4,294,600);
          delay(200);
          lcd.setCursor(0,0);
          lcd.print("  Motion  ");  // Print a message to the LCD.
          lcd.setCursor(0,1);
          lcd.print(" Detected ");
        } else if(digitalRead(pirPin) ==  HIGH) {
           digitalWrite(LEDgreen, LOW); // Turn off the LED in the case where no motion is detected
           lcd.setCursor(0,0);
           lcd.print("No Motion  ");
           lcd.setCursor(0,1);
           lcd.print(" Detected ");
         }
       } else if(buttonState == HIGH) {
         if(digitalRead(pirPin) == LOW) {
           digitalWrite(LEDgreen, HIGH);
           delay(1000);
           digitalWrite(LEDgreen, LOW);
           delay(500);
           digitalWrite(LEDgreen, HIGH);
           tone(4,261,300);
           delay(200);
           tone(4,329,300);
           delay(200);
           tone(4,392,600);
           delay(200);
           tone(4,329,300);
           delay(200);
           tone(4,392,300);
           delay(200);
           tone(4,493,600);
           delay(200);
           tone(4,392,300);
           lcd.setCursor(0,0);
           lcd.print("  Motion  ");
           lcd.setCursor(0,1);
           lcd.print(" Detected & door ");
         } else if(digitalRead(pirPin) ==  HIGH) {
           digitalWrite(LEDgreen, LOW);
           // Turn off the LED in the case where no motion is detected
           tone(4,329,300);
           delay(200);
           tone(4,392,300);
           delay(200);
           tone(4,493,600);
           delay(200);
           tone(4,392,300);
           lcd.setCursor(0,0);
           lcd.print("No Motion  ");
           lcd.setCursor(0,1);
           lcd.print(" Detected but door ");
         }
       }
       delay(2000); // wait for 1 seconds before compare again
     }

title: LCD does not work with if condition

Answers: 1

body:
This is a summary of your basic loop logic:

    void loop() {
      int buttonState = digitalRead(buttonPin);// Read the pushbutton input pin:
      int pirVal = digitalRead(pirPin); //read the digital value from the pirPin and store the value in the local variable pirVal
      if (buttonState == LOW) {
        if (digitalRead(pirPin) == LOW) {
            // buttonState is LOW
            // pirPin is recently read as LOW
            // ... Motion Detected ...
        }
        else if (digitalRead(pirPin) ==  HIGH) {
            // buttonState is LOW
            // pirPin is recently read as HIGH
            // ... No Motion Detected ...
        }
      }
      else if (buttonState == HIGH) {
        if (digitalRead(pirPin) == LOW) {
            // buttonState is HIGH
            // pirPin is recently read as LOW
            // ... Motion Detected & Door ...
        }
        else if (digitalRead(pirPin) ==  HIGH) {
            // buttonState is HIGH
            // pirPin is recently read as HIGH
            // ... No Motion Detected but Door ...
        }
      }
      delay(2000); // wait for 1 seconds before compare again
    }

However, this is bad code:

    if (digitalRead(pirPin) == LOW) {
        // ... Motion Detected ...
    }
    else if (digitalRead(pirPin) ==  HIGH) {
        // ... No Motion Detected ...
    }

because each time the digitalRead(..) function is called, it can give a different value. So even though your intention is clear, this code won't work the way you expect. Consider what happens if the first digitalRead(pirPin) is high, so digitalRead(pirPin)==LOW is false, but then the second digitalRead(pirPin) is low, so digitalRead(pirPin)==HIGH is also false. Then neither block of code runs. Instead, use:

    if (digitalRead(pirPin) == LOW) {
        // ... Motion Detected ...
    }
    else {
        // ... No Motion Detected ...
    }

Or since you already sampled it at the start of the loop with `int pirVal = digitalRead(pirPin);`, simplify the logic as:

    void loop() {
      int buttonState = digitalRead(buttonPin);// Read the pushbutton input pin:
      int pirVal = digitalRead(pirPin); //read the digital value from the pirPin and store the value in the local variable pirVal

      if (buttonState == LOW) {
        if (pirVal == LOW) {
            // buttonState is LOW
            // pirPin is LOW
            // ... Motion Detected ...
        }
        else {
            // buttonState is LOW
            // pirPin is HIGH
            // ... No Motion Detected ...
        }
      }
      else {
        // buttonState is HIGH
        if (pirVal == LOW) {
            // buttonState is HIGH
            // pirPin is LOW
            // ... Motion Detected & Door ...
        }
        else {
            // buttonState is HIGH
            // pirPin is HIGH
            // ... No Motion Detected but Door ...
        }
      }
      delay(2000); // wait for 1 seconds before compare again
    }

By the way, if you're using the Arduino IDE, you can easily clean up the indentation to make these control structures easier to see, by using Tools | Auto Format.


body:
I'm writing a little API for processing email messages in Arduinos. Obviously, I need to keep memory use down, but I also want to allow the end user to use the String functions (like indexOf) to search for particular content in emails.

My logic uses char arrays (so that memory is statically allocated). If my end user converts a char array to a String (so that they can easily see if an email subject startsWith() a particular word) will this result in doubling the character memory used? .. or will the String class simply include a pointer to the original char array (and just add some cruft)?

What would be the best-practice in this kind of situation?

title: What is the memory expense of creating a String from a char array?

Answers: 2

body:
> What would be the best-practice in this kind of situation?

To not use `String`.

> I also want to allow the end user to use the String functions (like indexOf) to search for particular content in emails.

There's nothing wrong with providing an `indexOf` function in your API.  But you don't have to use `String` to implement that function when called.  You can just use the `strstr` function on char arrays (reference [here](http://www.cplusplus.com/reference/cstring/strstr/)).

I should also point out that most Arduinos do not have enough RAM for storing an email.

### UPDATE 07-01-2016:
To answer the titular question, the fixed cost of using `String` is at least 1600 bytes of program space, more if you use more than a few methods.  The linker can throw out methods you don't use.

Then for each `String` variable you declare, the recurring cost is 8 bytes for the variable itself, plus the variable-size memory chunk for your character data.  This chunk is allocated from the heap, and is the size of your string plus 4 more bytes to manage the chunk within the heap.  That's a total of 12 extra bytes per `String` instance.

However, I did not originally answer that question because you explicitly asked about the *memory* expense.  This ignores other expenses that should not be ignored:

* execution time - Allocating memory from the heap is really a search for a chunk of the requested size.  At the beginning it can be quick, but as the heap gets fragmented (small chunks build up) it takes longer to find a chunk.  And when the `String` is emptied or destroyed, the memory chunk gets put back into the heap and (possibly) merged with adjacent chunks.  Reducing the size of a `String` does not free up any memory.  The `String` maintains its maximum size until it is emptied or destroyed.
* long-term stability - Embedded Systems are supposed run *forever*.  A primary characteristic of a system that can run forever is "deterministic."  For whatever inputs it receives, it has a predictable response and end state.  When you use the heap via `String`, the heap gets fragmented according to the data it handles.  This is not predictable, and it may get into a state where no memory chunk of the requested size is available.  Choke.
* maintenance - because the heap state depends on the processed `String` data, finding the cause of the failure can be difficult.  It can fail at different times because the input data is different, and it can fail at different places in the program.

Because of *these* expenses, `String` is rarely used by an experienced developer.  Unfortunately, `String` is tempting to the beginner because it is easy to understand.  What is difficult to understand is the complicated, non-deterministic behaviour under the hood that **inevitably** leads to system failure, rending of garments and gnashing of teeth.

body:
[I'm a year late but this or a related question gets asked often enough, I think it's worth another answer.]

With a Mega, there's enough memory to *consider* doing what you propose ***if*** we make some assumptions and modifications:

1. We know or can accept a maximum size of a string, above which, memory allocation will fail, detectably (the allocator returns a NULL pointer and the object handles the failure gracefully);

2. We use a non-fragmenting allocation method - statically allocated buffer pools of one or more fixed sizes - that are allocated and returned intact. No splitting or merging will take place. A given request will be filled with a buffer of the requested size or larger, if one is available.

3. Either the String object is modified to only use the new allocator or the system '_new()_' is replaced by it.

The obvious disadvantages are:

 - The entire heap will not be eaten up by a fragmented memory pool. ("Heap" is that space between the statically allocated memory and dynamically growing and shrinking stack. When the stack and heap meet, your application fails).
 - You'll need to know something about your application's memory needs to plan the buffer pools.
 - You'll have to plan to prevent or handle allocation failure.

In exchange, you get:

 - The allocator won't crash your system.
 - The String object's programming advantages become available.
 - You'll write better code since you had to think about and plan for its needs rather than let a dumb and fragmenting allocator blindly consume the heap.


body:
I'm using a Yún shield from Dragino with an Arduino Uno, but the default wifi password for the shield (which should be "dragino") isn't working.

I tried the wifi reset (holding down the reset button for 5 seconds) and a factory reset (holding down the reset button for 30 seconds) but the password still seems to be incorrect.

Is there any way I can reset the password?

title: Arduino Yún shield password reset

Answers: 2

body:
Try connecting via ethernet to 192.168.255.1 with root/root

The SSH access for Dragrove is:
IP: 192.168.255.1 on LAN port. If you want to connect to the Dragrove via WiFi, the IP should be 192.168.1.108.
Username: root
Password: root

http://www.seeedstudio.com/wiki/Dragrove_-_Generic_gateway_for_internet_of_things

body: Dragino is just the password for the first initial setup. You probably set a new password. Even if you reset the shield, it keeps your password. This happened to me to and then I put in my password and it worked.


body:
Assuming I have all the necessary hardware...
I want to develop a system where you type in an email address and the Arduino will send hourly updates on attached sensors to the provided email address.

I can only get this to work if I enter my email account's username and password and send the email from the authenticated account. There's tons of examples online of this. However, I want to share it with others and I do not want my email authentication to be accessible or be attached with sending the emails.
For example, I want the email to be from a generic service like email@web-mail.com that no one can sign into and not my personal email or a Gmail account I made for the project.

Anonymous email senders have the right method, but they require human interaction to bypass Captcha or similar.

Does anyone have an idea of how to do this? Or should I make a separate webserver that handles the requests made by the Arduino and send emails through a Gmail account I made for the project?

title: How to send an email via Arduino without an email account?

Answers: 2

body:
You may be able to do this by running the [SMTP][1] transaction yourself. You don't actually need a valid from address (though I probably shouldn't be saying that). There are a number of resouces for how to do this, here's a quick list:

* [Arduino Playground Email Client page][2]
* [Adafruit][3]
* [How to send an email with Arduino and a WiFi shield?][4]

If you read an article telling you how to do SMTP in a generic sense (not using a particular provider's infrastructure) and it looks like they want a "real" e-mail address, you can try with a fake one. Chances are decent that it may work.

There are some fine points that may cause you grief if you go for the most simple of implementation (for example, just because my e-mail address is foo@bar.org doesn't mean that bar.org will accept an SMTP connection, the "right" way to do it is to check DNS for an MX record for bar.org).

It would be best to do (and log) any errors that you encounter. There are plenty of things that can go wrong, so tracking where it blows up will help you – or anybody who's trying to help you debug.

If you don't want to roll your own [SMTPClient][5] and [FullIP][6] look worth checking out.

[1]: https://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol
[2]: http://playground.arduino.cc/Code/Email
[3]: https://learn.adafruit.com/downloads/pdf/arduino-lesson-17-email-sending-movement-detector.pdf
[4]: https://arduino.stackexchange.com/questions/1114/how-to-send-an-email-with-arduino-and-a-wifi-shield
[5]: https://github.com/gregington/SMTPClient
[6]: https://github.com/bibi21000/arduino-fullip

body:
I am thinking that you will have a few issues in doing this,

If you wish to, as mentioned by _dlu_, run the SMTP Transaction from the device yourself, you are free to do that, however, most SMTP Relays will require some sort of authentication; this is to prevent me from using a random relay to send out millions of messages.

Another issue may be that if you do setup a local relay, your ISP will block traffic on port 25, which is common; this means your mail can never be delivered to an external server.

My thoughts on the _simplest_ way to do this would be getting a Virtual Private Server that will run the mail service and a webserver; you could then make a simple PHP script that will accept a few parameters, and send an email.

Following the above, you would only need to make an HTTP request to your server for the mail to be sent,

    http://web-mail.com/sendmail.php/?to=someone@somewhereelse.com&subject=Wooo&Message=This is a message.


body:
I want to use attiny13 in my project but this program is going over 1KB

<!-- language: lang-C -->

    void setup()
    {
      Serial.begin(9600);
      delay(2000);
      Serial.println("AT+CMGF=1");
      delay;
    }
    void loop()
    {
      for (int i=0 ;i < 1 ;i++)
      {
        delay(1500);

        Serial.print("AT+CMGS=\"");
        Serial.print("+918269394684");
        Serial.println("\"");
        while(Serial.read()!='>');
        {
          Serial.print("22.7010709,75.9372517");
          delay(500);
          Serial.write(0x1A);
          Serial.write(0x0D);
          Serial.write(0x0A);
          delay(5000);
        }
      }
    }

title: Is it possible to reduce the size of this program to 1KB

Answers: 1

body:
There are several problems with your program as shown that make a good answer impossible.  After I list those problems, I'll then proceed to give an answer, partly good, partly bad.  The good part is that the 432-bytes-of-code program shown below should send all the indicated text strings, in the proper order and separated by appropriate delays.  The bad part is that it sends at 115200 bps instead of 9600.  Depending on point of view, it may be good or may be bad that the code doesn't look for absence of `'>'` on Serial input; as I note in discussion of problems, the original code's unclear.

As promised, here are several problems with your program as shown, and how to fix them:

-  The statement `delay;` is a constant expression [address of the `delay()` function rather than a call to `delay()`] so take it out.

-  The statement `for (int i=0 ;i < 1 ;i++)` is a do-nothing so take it out.

- The sequence `while(Serial.read()!='>'); {` is confusing – it compiles but isn't something a rational programmer would write – so take it out.  (As written, with a semicolon directly between the right parenthesis and the left brace, it busy-waits until it reads `'>'` on Serial input.  Then the unnecessarily-blocked block of statements within the matched braces executes one time and `loop()` exits its current pass.  If the semicolon weren't there, the statements within the braces would execute repeatedly until a `'>'` appears on Serial input.)

Anyhow, with the minor fixes outlined above, and using the `BasicSerial` library from nerdralph's [writing AVR assembler code with Arduino](http://nerdralph.blogspot.ca/2013/12/writing-avr-assembler-code-with-arduino.html) page, we get the following message for the program shown below.
>Sketch uses 432 bytes (42%) of program storage space. Maximum is 1,024 bytes.  Global variables use 68 bytes of dynamic memory.

<!-- language: lang-C -->

    #include <BasicSerial.h>
    char *text = "AT+CMGF=1\n\0"    "AT+CMGS=\"+918269394684\"\0"
      "22.7010709,75.9372517\0" "\033\r\n";
    #define send(item) while (*item) TxByte (*item++)
    void setup() {
      //Serial.begin(9600);
      delay(2000);
      //Serial.write("AT+CMGF=1\n");
      send(text);
      //delay;
    }
    void loop() {
      char *msg = text;
      delay(1500);   // took out `for`
      //Serial.write("AT+CMGS=\"+918269394684\"");
      send(msg);
      //while(Serial.read()!='>'); {
      //Serial.write("22.7010709,75.9372517");
      send(msg);
      delay(500);
      //Serial.write("\033\r\n");
      send(msg);
      delay(5000);
      //}
    }

*Program Notes:*

1. The string `text` contains all the text from your original `Serial` prints and writes.  With the text organized as a single string, the program only needs to set its character pointer `msg` once per loop, saving perhaps half a dozen bytes of code.

2. The commented-out `Serial.write` statements are equivalents of your various `Serial.println`, `Serial.print`, and `Serial.write` statements, with adjacent strings lumped into single writes, thus for example using one write instead of three to write the Esc, CR, LF sequence just before `delay(5000)`.  Just changing those printlns, prints and writes all to writes reduces code size  by about 150 bytes, which might be enough of a reduction to get you by, depending where you start from.  But in my tests, substituting `BasicSerial` in place of `Serial` saves over a thousand bytes so is likely to be a requirement.

3.  You probably can modify the code in `BasicSerial.S` for other data rates, or perhaps can substitute one or another of the small `Serial` replacements listed in ernstc's [Serial communication with the Tiny's](http://www.ernstc.dk/arduino/tinycom.html) webpage, to get different data rates and/or receive as well as transmit.

*Edit:*  As Edgar Bonet noted in a comment, an ATtiny13 has 64 bytes of RAM, so the above program (using 68 bytes of RAM) will fail.  RAM usage can be reduced by copying string characters individually from program memory, instead of copying the string into RAM (per Arduino default).  See the following revision of the program, which also corrects a problem (leaving `msg` pointed at a null byte) that would keep the former program from working.  Note, with these changes, we have:

>Sketch uses 456 bytes (44%) of program storage space. Maximum is 1,024 bytes.     Global variables use 6 bytes of dynamic memory.

<!-- language: lang-c -->

    #include <BasicSerial.h>
    #include <avr/pgmspace.h>
    const char text[] PROGMEM = "AT+CMGF=1\n\0"
      "AT+CMGS=\"+918269394684\"\0"
      "22.7010709,75.9372517\0" "\033\r\n";
    char *front = (char*)text;
    #define send(item) while (pgm_read_byte(item)) TxByte (pgm_read_byte(item++))

    void setup() {
      delay(2000);
      send(front);  ++front;
    }
    void loop() {
      char *msg = front;
      delay(1500);
      send(msg);   ++msg;
      send(msg);   ++msg;
      delay(500);
      send(msg);
      delay(5000);
    }


body:
I'm trying to track down a clearly/simply articulated piece of code to take a reading from the [ACS712 current sensor][1] (link to download PDF data sheet).

I understand that these sensors are noisy, and that reading AC current is quite different to DC current.

After looking at a range of examples in a variety of forums etc., I've based the following on http://henrysbench.capnfatz.com/henrys-bench/acs712-arduino-ac-current-tutorial/

    void ac_read() {
      int rVal = 0;
      int maxVal = 0;
      int minVal = 1023;
      int sampleDuration = 100; // 100ms

      uint32_t startTime = millis();
      // take samples for 100ms
      while((millis()-startTime) < sampleDuration)
      {
        rVal = analogRead(A0);
        if (rVal > maxVal)
          maxVal = rVal;

        if (rVal < minVal)
          minVal = rVal;
      }

      // Subtract min from max to determine the peak to peak range
      // 1023 = the max value we'll get on the input (1024, zero indexed)
      // 5.0 = 5v total on adc input
      double volt = ((maxVal - minVal) * (5.0/1023.0));

      // div by 2 is to calculate RMS from peak to peak
      // 0.35355 is factor to calculate RMS from peak to peak
      // see http://www.learningaboutelectronics.com/Articles/Voltage-rms-calculator.php
      double voltRMS = volt * 0.35355;

      // x 1000 to convert volts to millivolts
      // divide by the number of millivolts per amp to determine amps measured
      // the 20A module 100 mv/A (so in this case ampsRMS = voltRMS
      double ampsRMS = (voltRMS * 1000)/100;
      Serial.println(ampsRMS);
    }

I unfortunately don't have sufficient test equipment at present to validate this, but I'm getting a value of around 8.9 for a 2300W device, which afaict is roughly accurate (based on this calculator http://www.rapidtables.com/calc/electric/Watt_to_Amp_Calculator.htm).

Is anyone able to confirm the above makes sense/is logical/sane?  Is there anything obviously incorrect?

[1]: http://www.allegromicro.com/~/media/Files/Datasheets/ACS712-Datasheet.ashx?la=en

title: ACS712 sensor reading for AC current

Answers: 1

body:
Measuring the peak-to-peak current and scaling the result will get you an answer which will at least go up and down with the magnitude of your average AC current, so yes it is NOT incorrect.  As you suggested it will be sensitive to noise from the sensor - in fact as you are taking the highest and lowest single readings the noise will always cause the measurement to be higher than actual.

However, I think you could do better.  Given that the code is already having to take many samples (basically as fast as it can) for 100mS (which will sample 5 cycles of the waveform if it is 50Hz and 6 if it is 60Hz, depending on where you are in the world), then you could actually do the maths to measure the RMS value and by basing this on all of the signal the effect of the noise will be reduced.

You need to know the ADC reading when there is no current `rZero` (which should be around 511 but could be off a bit due to offset errors) - you could measure this with nothing connected to calibrate the sensor, or take a long term average even with the AC signal present.

As the henrysbench tutorial points out it is important that the Arduino samples the signal at a high enough frequency (say 1000Hz - hence 100 samples for your 100mS sample duration)- the count of the number of times that the while loop executes `sampleCount` will confirm if this still the case even with the extra computation time of this code.

Also if you increase the sample time please be careful that the `unsigned long rSquaredSum` can't overflow, but I would avoid use of doubles within the while loop as they will definitely slow it down a LOT.

    void ac_read() {
      int rVal = 0;
      int sampleDuration = 100;       // 100ms
      int sampleCount = 0;
      unsigned long rSquaredSum = 0;
      int rZero = 511;                // For illustrative purposes only - should be measured to calibrate sensor.

      uint32_t startTime = millis();  // take samples for 100ms
      while((millis()-startTime) < sampleDuration)
      {
        rVal = analogRead(A0) - rZero;
        rSquaredSum += rVal * rVal;
        sampleCount++;
      }

      double voltRMS = 5.0 * sqrt(rSquaredSum / sampleCount) / 1024.0;

      // x 1000 to convert volts to millivolts
      // divide by the number of millivolts per amp to determine amps measured
      // the 20A module 100 mv/A (so in this case ampsRMS = 10 * voltRMS
      double ampsRMS = voltRMS * 10.0;
      Serial.println(ampsRMS);
    }


body:
I would like to make an arduino board that is capable of handling 24V i/o.

Powering the Arduino would be done through either a linear or switching regulator of some sort. Low amperages, so efficiency isn't the main problem.

For input:
24v to 5v input scaling could be created with a voltage divider.

As far as I know, there will never run a high current into the arduino? So the power loss is minimal?

For output:
5v to 24v can be easily achieved using a MOSFET? Since this will ramp up the possible load (higher amperages) given that I'm using a 24v supply/separate line.

So I could choose to make half the I/O only input and half only output.

1. Could I combine the MOSFET and voltage divider, and in what way?
2. Are my "assumptions" about the I/O correct, or are there beter ways of handling it?
3. What other things should I think of? Over voltage protection? Polarity inversion? Protection against too high currents?

title: Industrializing Arduino - 24V io? (Electronics)

Answers: 3

body:
You mentioned 2 items: the supply voltage to the Arduino and scaling up to 24V output.

If the supply voltage you have available is 24V, then I would suggest you look for a DC-DC converter that scales down to 12V. Or, if you are looking to design your own PCB then perhaps use a 78xx voltage regulator. The 78xx are 3 pin devices and only require 2 caps to operate - I suppose a heat sink will not be needed.

To scale up the outputs to 24V I would suggest one of the following options:

a) Relay board /
These will take the 5V from your Arduino and close a mechanical switch. If the relays are good quality they will go on for ages. And you can switch loads from 0 to 240V and more, DC or AC.
Plus of the relays are sturdiness and that they are quite forgiving for short current overloads. Minus are that relays are " slow" when compared to semiconductors and they can arce when the contacts open - especially when driving inductive loads and that. Arcing will wear down your contacts and in extreme cases generate EMI that might interfere with your electronics. Arcing can be remediated in AC with a capacitor accross the contacts or in DC with a flyback diode.

If you will make your own PCB don't forget the flyback diode on pins connecting to the relay coils or you will possibly fry the Arduino due to a voltage spike!

Many of these boards are available on the web, so it's a quick solution.

b) Optocouplers /
Also a good option. Functionally they act as a relay. They are a bit less forgiving to current overloads, so chose them wisely.
They are silent and fast acting. Available for AC or DC and up to 600V.
Minus side is that the tend to be a bit more expensive than relay boards. I'm talking about industrial grade devices and not some el-cheapo web site :-)

c) MOSFETS or Bipolar transistors /
If you are designing your PCB then this could be an option.
Here you can use a MOSFET or a PNP transistor of the adequate ratings and you would be done. Though maybe considering yur time investment the options above could be less expensive in the end.
I this case you get complete control of PCB layout which might be a consideration.
If you go this way, don't forget to add a flyback diode to the output of these devices to protect from spikes when switching inductive loads (= motors, solenoids).

A big advantage of Relays and Optocouplers is the galvanic isolation they provide, both from the load to the board as between the loads themselves.

If you could supply more detailed specs of the loads, environments etc I can help you narrow down your choices.

body:
24 VDC industrial circuits are typically based around 4-20mA measurement (AI) transmitters and outputs (AO) to valves and other actuators. There are also 24 VDC DI & DO's. I believe that you should investigate Analog Devices and Texas Instruments chips for 4-20 mA interfacing.  They have a number of chips for reading in and outputting 4-20 mA.  You can get started if you Google "analog devices 4-20ma application note" or "texas instruments 4-20ma application note." If you Google "4-20mA application note," you will find that there are any number of people that make these chips and lots of people that provide application notes for 4-20mA loops.

Any information provided here is on a Caveat Emptor basis.

body:
This is a pretty old post but I'm sure people still search this topic from time to time. If what you are after is making an arduino into the plc replacement of sorts, look at these links. I've done these tasks and they worked pretty easyily for me. When you compare the cost of a plc to these alternatives, you won't find a new plc for the same price:

https://www.universal-solder.ca/product/canaduino-plc-mega328-programmable-logic-controller-electronics-diy-kit-for-arduino-nano-included/

and

https://www.visuino.com/ - A visual ide


body:
Is it possible to directly set the registers that control the ADC in an Arduino Yun (micro-controller side is essentially a Arduino Leonardo) from a sketch or is there a specific file somewhere you must edit?

I am working on a project that collects a signal digitizes it and sends it through a digital filter. I looked up the Datasheet for the micro-controller on the Yun and wrote the code setting the registers associated with the ADC portion of the micro controller. The code setting the registers was something like `REGNAME = 0x01;`. Yet when tested several of the associated registers were unaffected. Pointers on the process to set the ADC manually without using the `analogRead()` function would be appreciated.

Edit:
My original code looked something like this:

<!-- language: lang-c++ -->

    void setup(){
        // register to turn on ADC
        REG1 = REG1 | 0x01;

        //register to set sample rate and set ADC to Free Running Mode
        REG2 = REG2 & 0x30;

        // register to set other settings
        REG3 = REG3 | 0xF1;
    }

    void loop(){
        // code to take samples from ADC
        // and send them through a digital filter here.
    }

title: Is it possible to directly set the registers that control the ADC clock on the Arduino?

Answers: 2

body:
Since your project is about acquiring signals I guess that the sample frequency is important for you. In fact you need to know exactly how much time passes from one sample to another. This cannot be achieved by simple reading the ADC in your loop(). The easiest implementation is to use an interrupt that occurs every n seconds (e.g. every overflow of timerX).

I'm going to write a pseudo-code for this:

    void SetTimer()
    {  TISREG |= 1<<Prescaler_bit   //set the prescaler
       TICNT = 0   //sdt the tarting value
       TIINT |= 1<<OVF_Interrupt_enable
       sei() //enable global interrupt
    }

    ISR(TIM1_OVF_vect)   //happens every [prescaler*2^bit_timer/F_CPU] seconds
    {
       while( !(ADCSREG &= (1<<bit_is_ready)) ) ; //usually there is a bit that is 1 while the ADC has read the data, and 0 while it is doing the conversions

    //imagine the ADC stores the 3 MSBits in the ADCHI
    //and the LSBits in the  ADCLO

    value_high = (ADCHI & 0b00000111);
    value_low = ADCLO;

    value = (value_high << 7) | value_low;

    }

body:
I can see no problem with your pseudo-code. You should probably post a
complete testable code in order to get better feedback.

That being said, here are a few suggestions:

1. You should _completely set_ the ADC registers to the values that suit
   your application, instead of just changing a few bits here and there.
   This is because you should not care about how the Arduino core
   library initializes those registers, especially if this is a
   prototype for a final product that will not use Arduino core. For
   example, instead of

<!-- language-all: lang-c++ -->

    REG1 = REG1 | 0x01;

   you can write something like this:

    REG1 = _BV(FOO)   // use foo mode...
         | _BV(BAR);  // ...in the bar setting

   where `_BV(x)` is a macro from avr-libc that expands to `(1<<(x))`,
   and the bit names are those of the datasheet, for better readability.

2. You may want to run the digital filter in the ADC interrupt service
   routine. If you can split your processing into a fast filter
   (processing every sample) and a slow filter (running on decimated
   samples), then do only the fast one in the ISR and leave the slow one
   to the main loop. I say this from experience: when I tried to do
   all the processing in `loop()` I always lost samples, which did not
   happen when I moved the filter to the ISR.

3. But then, make sure your filter is optimized to be _fast_. Avoid
   floating point operations in the ISR if at all possible.

I have written a program that looks very similar to what you are trying
to do: it samples an analog input at 9.6 kS/s and runs an
[homodyne detection](https://en.wikipedia.org/wiki/Homodyne_detection)
filter in order to extract the signal power in a very narrow band around
1 kHz. The ADC is set to free running mode. In the ADC ISR, I
retrieve the sample, run it through the filter, and store the result
into volatile variables. In `loop()`, I read these back from time to
time. Here is how I set the ADC:

    static void configure_adc()
    {
        ADMUX  = _BV(REFS0)  // ref = AVCC
               | _BV(ADLAR)  // left adjust result
               | analog_in;  // input channel
        ADCSRB = 0;          // free running mode
        ADCSRA = _BV(ADEN)   // enable
               | _BV(ADSC)   // start conversion
               | _BV(ADATE)  // auto trigger enable
               | _BV(ADIF)   // clear interrupt flag
               | _BV(ADIE)   // interrupt enable
               | 7;          // prescaler = 128
    }

The complete program is available here:
[homodyne.ino](https://gist.github.com/edgar-bonet/0b03735d70366bc05fc6).
It was initially intended for an Arduino Uno, but it runs unmodified on
a Leonardo clone.


body:
I am making a system of regulation of the temperature using PID.
I want to keep my temperature in 37 celsius.
in order to understand the stability of my system easily, I want to see the fuction of temperature in terms of time.
I found a function pulseIn() who Read a pulse (either HIGH or LOW) on a pin.
But I don't know how to do it into my program.
this is the program of my PID system:

<!-- language: c -->

    #include <PID_v1.h>
    #include "math.h"
    int c=0;
    int  i=0, output2 = 0, output3 = 0;
    double val=0.0;
    double val2 = 0.0;
    //Define Variables we'll be connecting to
    double Setpoint, Input, Input2, Output=0;
    double tOnMax = 50.0;

    //Specify the links and initial tuning parameters
    PID myPID( &Input, &Output, &Setpoint,10,20,20, DIRECT);

    void setup()
    {
      //initialize the variables we're linked to
      Setpoint = 37; //temperature a reguler

      //turn the PID on
      pinMode(9, OUTPUT);
      myPID.SetOutputLimits(-100, 100);
      myPID.SetMode(AUTOMATIC);
      Serial.begin(19200);
      while (!Serial);
    }

    void loop()
    {
      // phase haute
      digitalWrite(9,HIGH);
      delay(output2);
      // phase basse
      digitalWrite(9,LOW);

      for (i = 0; i < 64;i++)
          val += analogRead(0);
      val /= 64.;

     for (i = 0; i < 64;i++)
          val2 += analogRead(1);
      val2 /=64.;

      float mv = round (( val/1024.0)*5000);
      float mv2 = round (( val2/1024.0)*5000);
      Input = mv/10;
      Input2 = mv2/10;
    //  Serial.println(Input);
      myPID.Compute();
      output2 = map(Output, -100, 100, 0, tOnMax);
      output3 = map(Output, -100, 100, 0, tOnMax);
    //  Serial.print("output is :");
    //  Serial.println(output2);
    //  Serial.print("Input: ");
    for (c=0; c < 500; c++) {}
    Serial.println(Input);

    }

thnak you in advance

title: PID and pulseIn()

Answers: 2

body:
> I want to see the evolution of the function tempertaure (t), in other words, i want to see in my screen for exemple: 24.1C -> 20ms ; 25C-> 200ms; 26 -> 500ms

Quite apart from managing the heater, it sounds as if you need to sample the temperature at a constant rate, compare its value to any of several temperature-intervals, and, when it moves out of one interval into another, report the time it spent within the previous one. This will require saving which interval the temperature was last observed in, and the time it entered that interval, re-saving both when it moves into a new one. You may need to apply some smoothing to the temperature data to if there is any noise in the temperature data to prevent it appearing to jitter back and forth between intervals during interval edge crossings.

body:
OK, with such a slow heater as compared to the calculation time of the arduino, you likely want to use a much longer sampling time. One could disconnect the PWM time and the sampling time from the loop() time by replacing the delay() with millis() as in https://arduino.stackexchange.com/questions/17918/using-arduino-for-simultaneous-lighting-effects/17929#17929 and below, and with a sampling time of 1s, 10s or 60s, the parameters of the PID and the integral and derivative terms could start making sense. i.e. the D term would conform to watts/(degreeError/minute), the I term to Watts/(degreeError*minutes) and P to watts/degreeError.

One nice way to think of a PID controller is that it converts process errors into a control variable.  If you want to convert "degrees below setpoint" into "milliseconds of heat per tOnMax second cycle", set that directly:

    // Tuned for full power (1000ms/sec) up to 35C: P=1000/2
    PID myPID( &Degrees, &millisecondsOn, &Setpoint,500,0,0, DIRECT);
    myPID.SetOutputLimits(0, tOnMax);
    ...

Or "duty cycle of heater"

    // Tuned for full power (100%) up to 35C: P=1.0/2
    PID myPID( &Degrees, &millisecondsOn, &Setpoint,0.5,0,0, DIRECT);
    myPID.SetOutputLimits(0, 1.0);
    ...

I didn't want to edit your code too much, but went for a 1s PWM frequency, 10s sampling or PID cycle time.   The 1sec PWM/cycle time is the minimum most commercial PID controllers work with (typically 1s-999s to handle a range from solid-state-relay controlled resistive heating elements to relay controlled mechanical systems like pilot light heaters or fan/pump systems) and should be plenty fast enough for your system.  Slower PWM times are better for mechanical systems, and faster times are better for thermal cycling of resistive elements.

The 10s cycle time is ~200x slower than your initial code looks like it is sampling, but the 10s time might be more in keeping with the physical changes in your system as compared to your resolution.  I can't tell the temperature resolution of your sensor for your code, but assuming it is 0.1C, taken with a (37C-20C)/30m=0.0094C/s rate of change, it would take about 10s to make 1 bit of  detectable change.  If you sample faster than that, all you will be getting is noise or no change.  Sampling significantly faster than the physical process changes can serve to confuse a PID in the integral and derivative terms--Derivative because the derivative of error is mostly zeros or noise, and Integral because the integral accumulator can wind up before the system even begins to move.  Looking at the Arduino PID library code at https://github.com/br3ttb/Arduino-PID-Library/blob/master/PID_v1.cpp#L57 with a I=20, output limits of (-100,100), a t0=20C, a setpoint of 37, sampling time of 50ms, and a temperature rate of change of 0.0094C/s, the Iterm accumulator would be wound up to 100 in just 0.300 seconds.  The wound-up integral would guarantee an overshoot until the integral accumulator erodes afterwards (For example: 37.5C for 10s? 37.1C for 100s? ???)

With a 1000ms PWM and 10s sampling time base, you would need to reconsider your PID settings.   In particular, the I and D terms strongly sensitive to the sampling time and the output range.  As a start, PID myPID( &Input, &Output, &Setpoint,500,0,0, DIRECT); would start to proportionally turn the heater off at 37-1000/500)=35C, which might be good enough for your needs.  If that isn't close enough, you could increase P more to tighten the proportional band.  ("Proportional band" is error band where the P*error term of the PID doesn't saturate the output limits, i.e., PropBand = +/-(tOnMax/P) )   Alternately, you could fiddle with the I term to completely eliminate the droop.

<!-- language: c -->

    #include <PID_v1.h>
    #include "math.h"
    int c=0;
    int  i=0, output2 = 0, output3 = 0;
    double val=0.0;
    double val2 = 0.0;
    //Define Variables we'll be connecting to
    double Setpoint, Input, Input2, Output=0;
    double tOnMax = 1000.0; // 1 second PWM controlling 10w heater
    unsigned long sampleTime, heaterTime;

    //Specify the links and initial tuning parameters
    // Process takes 30m to come to 37C from 17C at 10W
    // Proportional: Full power to setpoint-2C, then proportional taper: P= tOnMax/2
    // Integral: 30m = 300 samples, so area under curve = 20*300/2=3000
    // so for integral to roll up to 50% power (1/2 tOnMax) in 30m:
    // I = tOnMax/2/3000 = 1000/2/3000 = 0.15
    // Derivative: Max slew rate of 20C/30m = 20C/300 10sSamples = 0.067C/sample
    // Ignore the derivative for now to avoid potential noise problems,
    // but D=tOnMax/0.067=15000 would anticipate and counteract the maximum slewing rate
    PID myPID( &Input, &Output, &Setpoint,tOnMax/2,0.15,0, DIRECT);

    void setup()
    {
      //initialize the variables we're linked to
      Setpoint = 37; //temperature a reguler

      //turn the PID on
      pinMode(9, OUTPUT);
      myPID.SetOutputLimits(0, tOnMax);
      myPID.SetMode(AUTOMATIC);
      Serial.begin(19200);
      while (!Serial);
      heaterTime=sampletime=millis();
    }

    void loop()
    {
      unsigned long now = millis();
      if(heaterTime < now){
         if(digitalRead(9)) {// phase haute -> basse
            heaterTime += tOnMax-output2; // schedule on
            digitalWrite(9,LOW);}
         } else {  // phase basse -> haute
           heaterTime += output2);  // schedule off
           digitalWrite(9,HIGH);
         }
      if (sampleTime < now ) {
          sampleTime = sampleTime + 10000;  // every 10 seconds
          val=0=val2=0;
          for (i = 0; i < 64;i++)
              val += analogRead(0);
          val /= 64.;

          float mv = round (( val/1024.0)*5000); // convert to degrees*10?
          Input = mv/10;        // degrees
          myPID.Compute();
          output2 = Output;
          Serial.print(Input);
          Serial.print("C -> ");
          Serial.print(output2);
          Serial.print("ms / ");
          Serial.println(tOnMax);
       } // end sample
    }


body:
This going to be a difficult to debug problem but I hope some ppl here have C knowledge and idea what's going on. Given an arduino nano which is controlled by a C program from WRT54G.

Here is the relevant part of the arduino code:

<!-- language: c -->

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

     int integerValue=0;

                                  // Max value is 65535
    char incomingByte;

    void loop() {
      if (Serial.available() > 0) {   // something came across serial
        integerValue = 0;         // throw away previous integerValue
        while(1) {            // force into a loop until 'n' is received
          incomingByte = Serial.read();
          if (incomingByte == '\n') break;   // exit the while(1), we're done receiving
          if (incomingByte == -1) continue;  // if no characters are in the buffer read() returns -1
          integerValue *= 10;  // shift left 1 decimal place
          // convert ASCII to integer, add, and shift left 1 decimal place
          integerValue = ((incomingByte - 48) + integerValue);

        }
       Serial.print("Command: ");
       Serial.println(integerValue);

      }
    }

Pretty straight forward (it converts serial received ascii chars to numeric format), arduino receives a simple integer and it runs a function. For example 1-> turn on relay1. This work's reliably for sure because I can just do:

    echo "1" > /dev/tts/1

from the terminal.

Now here is the relevant part of the C code:

<!-- language: c -->

        int serialport_read_until(int fd, char* buf, char until, int buf_max, int timeout)
        {
            char b[1];  // read expects an array, so we give it a 1-byte array
            int i=0;
            do {
                int n = read(fd, b, 1);  // read a char at a time
                if( n==-1) return -1;    // couldn't read
                if( n==0 ) {
                    usleep( 1 * 1000 );  // wait 1 msec try again
                    timeout--;
                    continue;
                }
        #ifdef SERIALPORTDEBUG
                printf("serialport_read_until: i=%d, n=%d b='%c'\n",i,n,b[0]); // debug
        #endif
                buf[i] = b[0];
                i++;
            } while( b[0] != until && i < buf_max && timeout>0 );

            buf[i] = 0;  // null terminate the string
            return 0;
        }

        /* Only use integer commands */
        int serialport_write(int fd, int comm_no)
        {
            char command[6];

            sprintf(command,"%d\n",comm_no);
            printf("Sending Command:%s",command);

            int len = strlen(command);
            int n = write(fd, command, len);
            if( n!=len )
                return -1;
            return 0;
        }

    void *ardu_handler(void *fdfd)
    {
      int fd = *(int*)fdfd;
      char buf[256];
      char getback[10];

      while (1)
       {
        memset(buf, 0, sizeof(buf));
         serialport_read_until(fd, buf, '\n', 256, 5);
        fprintf(stderr, "Received: %s\n", buf);
       }
    }

Then a C thread will be started with the ardu_handler which in this case doesn't do anything else just print's back the response from the ardu.

What's happening is when I send a command I start getting back infinite amount of commands (up until I close the C app and start it again) and to make it worse it is even inconsistent.

For example:

    Command: 62143
    Command: 7891
    Command: 3216
    Command: 11287
    ...
    runs forever.

What I asking myself is whether these *responses* coming out from the arduino or they are just coming out from the bogous C program...
It's not possible to connect to see what's coming out on the serial port unfortunately until this program holds the port open.

Although I run the C code on mips this was doing the same thing back on x86 PC with an arduino uno (sometimes it is stable but then it falls into this unstable state and floods the serial port). It was unreliable and I would like to make it reliable.

title: C Serial Communication Code is unreliable

Answers: 1

body: I recommend you change the type of `incomingByte` to `int`, like was advised in the comments. Also, your null-termination is occurring past the end of `buf`; change the condition in the `while` statement to `i < buf_max - 1`, so that one byte is left for the `null`. Also use parentheses to separate those conditions, in the unlikely event there's some issue of precedence.


body:
I have just installed the arduino IDE on my gentoo laptop. I then installed the toolchain with the following command:

    crossdev -s4 avr

This does a stage 4 install of the toolchain, with all its dependecies etc.

I am following a tutorial, with my arduino uno, which I am assuming is using the Amtel ATmega328 chipset. This tutorial is simply going to turn an led on and off.

I click the verify button and I get the following errors:

    /usr/libexec/gcc/avr/ld: cannot find crtatmega328p.o: No such file or directory

    /usr/libexec/gcc/avr/ld: cannot find -latmega328p

    collect2: error: ld returned 1 exit status

I downloaded the source files "avr-libc" compiled them and noticed inside the directory

    /avr-libc-1.8.1/avr/lib/avr5/atmega328p

That the compiled module is named crtm328p.o which is available on my pc under the directory:

    /usr/avr/lib/

I dont understand what is wrong and why this is not working. The only posts relating to missing files are over 5 years old and those solutions are not working.

title: Cannot find crtatmega328p

Answers: 2

body:
I do not use Gentoo, but I can tell you how things work on Ubuntu 14.04,
which also installs Arduino 1.0.5. I assume Gentoo should not be that
different... The dependency tree is like this:

* The package named "arduino", version 1.0.5, contains the IDE. It
  depends on Java and on arduino-core.
* arduino-core, version 1.0.5 also, has the Arduino core libraries. It
  depends on gcc-avr, avrdude and avr-libc.
* gcc-avr comes as version 4.8, avr-libc is version 1.8.0.

When you compile a program for an Uno, on the link stage avr-g++ gets
called, and it is asked to link your object files with libcore.a (the
Arduino core) and -lm (the math library). avr-g++ in turn calls the
linker (collect2) and asks it to link together
/usr/lib/avr/lib/avr5/crtm328p.o (the C runtime), your object files,
libcore.a, -lgcc (the GCC support libraries), -lm and -lc (avr-libc).
Notice that there is no crtatmega328p.o, it's called crtm328p.o instead.
And there is no -latmega328p.

For diagnosing your problem, you can set an IDE preference so that it
shows you the exact command lines it runs for compiling your program.
You can then copy and paste the last command (link stage) on a terminal.
If you add the `-v` option (meaning “verbose”), you will see what gcc is
asking the linker to put together.

You may be able to fix your problem with a simple symlink from
crtm328p.o to crtm328p.o. If you are using vanilla Gentoo packages, you
should then file a bug to the packager. On Ubuntu, you type
`sudo apt-get install arduino` and it just works.

body:
I had the same error, but I did everything as says in arduino wiki: https://wiki.gentoo.org/wiki/Arduino#Install_the_toolchain_using_crossdev

and solved it, after read this discussion: https://wiki.gentoo.org/wiki/Talk:Arduino

**helped**: build the avr toolchain without '--stable' part of crossdev command line :

USE="-openmp -hardened -sanitize -vtv" crossdev -s4 --portage --verbose --target avr


body:
I am getting constant values and I need to know the amplification of the circuit. I believe that amplification = R8/R6 though I am not sure.[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/pL7jh.jpg

title: Amplification of microphone circuit

Answers: 1

body:
You are mostly correct Diana.  The gain of an OP-Amp would normally be R8 divided by R6.

However, what needs to be recognized is that in your circuit, the resistance of R3 and the microphone get entangled with your R6.

The resistance (impedance of your microphone) is in series with R6. R3 also comes into play, but I will ignore it here (subject of another question on amplifiers).

So, since R of microphone is in series with your R6, your gain (amplification) will be slightly less than you have calculated.

The old 741 Op-Amp won't work very well (probably not at all) with a single ended power supply of 5 volts.  Although you have done a good job of biasing the non-inverting input (+) at 2.5 volts.

The 741 output can't get near the +5 volts, nor can it get near ground.  Try a better Op-Amp such as MCP6002. Look at how the output of the MCP6002 can approach the rails (your power supply and ground).


body:
I have a Servo Motor and an Arduino Uno.

I used the Arduino to run a servo motor. The code was very simple. It was to just Turn it 90 Deg Anti-Clockwise when a switch is pressed and Turn back to its original position (90 Deg Clockwise).

The servo had 3 pins.
 1. V+
 2. Ground
 3. Data

I connected the V+ to the Arduino's 5v Output. And the Ground to the Arduino's GND pin. I connected the Data to Digital Pin 3.

When ever this script runs, The servo turns a little and then stops. It stops because the arduino froze and It wont do anything. I pressed the Reset button and it does nothing. I plugged off the Servo and the Power Supply and replugged the Power and it works.

The power source was a battery pack with 4x 1.5 Volts batteries in it. Maybe there was a problem with this?

Do anyone know what might be the problem here? Any Answer will be Appriciated. Thanks.

title: Why does my Arduino freezes when i turn a servo

Answers: 3

body: Connect your servo V+ to your battery stack and the servo data input to your Arduino. I suspect that the servo is causing the Arduino to reset when the servo draws too much current through the Arduino's voltage supply circuitry.

body:
My first response would be a brown out reset. Because of the load the voltage will sag and drop below a certain voltage so the microcontroller will reset. Try to put a big buffer capacitor on the power supply.

Other possible cause could be inductive spiking, but I dont expect this to be the cause of your problem.

body:
You said that you were using 4x 1.5v batteries. That would make a total of 6 volts. The current that those batteries can supply is also little.

The Recommended Input Range is 7-12 volts. And the Limit is 6-20 volts.

You were supplying it with 6 Volts which is at the very limit of the Input Voltage Range. When the motor runs, the Voltage might have dropped and made the arduino freeze.

The fix is to supply the arduino with another source such as a benchtop supply that can supply more than 8 volts.


body:
I want to use an Arduino Uno, a seven segment LED display (four digits) and the [SevSeg library][1], to see temperature and humidity (alternatively).

First of all I try this code:

      #define COMMON_ANODE 1
      #define COMMON_CATODE 0
      #include "DHT.h"
      #define DHTPIN A5     // pin analogico che legge i dati
      #define DHTTYPE DHT22   // DHT 22  (AM2302)
      #include "SevSeg.h"

      // Crea un'istanza dell'oggetto
      SevSeg sevseg;
      DHT dht(DHTPIN, DHTTYPE);
      unsigned long timer; // the timer
      unsigned long INTERVAL = 5000; // the repeat interval (30 seconds)

      int segA = 6;   // Undicesimo PIN del display 7Segment x 4
      int segB = 2;   // Settimo PIN del display 7Segment x 4
      int segC = 10;  // Quarto PIN del display 7Segment x 4
      int segD = 12;  // Secondo PIN del display 7Segment x 4
      int segE = 13;  // Primo PIN del display 7Segment x 4
      int segF = 5;   // Decimo PIN del display 7Segment x 4
      int segG = 9;   // Quinto PIN del display 7Segment x 4
      int segDP = 11; // Terzo PIN del display 7Segment x 4

      int digit1 = 7; // Dodicesimo PIN - PWM che Accende il primo digit
      int digit2 = 4; // Nono PIN - PWM che Accende il secondo digit
      int digit3 = 3; // Ottavo PIN - PWM che Accende il terzo digit
      int digit4 = 8; // Sesto PIN - PWM che Accende il quarto digit

      void setup()
      {
        dht.begin();
        int numberOfDigits = 4; //Numero di cifre del display

        // Inizializzo i PIN
        sevseg.Begin(COMMON_CATODE,digit1,digit2,digit3,digit4,segA,segB,segC,segD,segE,segF,segG,segDP);
        // Imposto la luminosità (valore da 0 a 100)
        sevseg.Brightness(90);
        timer = millis(); // start timer
      }

      void loop()
      {
        if ((millis()-timer) > INTERVAL) {
          // Reset the timer and get/display the current temperature
          timer += INTERVAL;
          // Leggo dal sensore la temperatura
          float t = dht.readTemperature();
          float h = dht.readHumidity();
          //La converto in un numero intero a 4 cifre
          int a=t*100;
          sevseg.NewNum(a,2);
        }
            sevseg.PrintOutput();
      }

And it works very well!

But I cant see temperature (first) AND humidity (after) and again temperature (first) AND humidity (after)...

I have tried many ways but... nothing!! Can you help me?

  [1]: http://playground.arduino.cc/Main/SevenSegmentLibrary

title: Arduino thermometer and humidity display with 7 segment LED display

Answers: 1

body:
You need to maintain a *state* which tells your program whether you are displaying the temperature or the humidity.  Every time the timer expires you need to change from one state to the other, and then display the relevant value depending on what the state is.

Something like:

    bool displaying = false; // false = temperature, true = humidity

    void loop() {
        if ((millis()-timer) >= INTERVAL) {
            timer = millis();
            display = !display; // Switch between display values

            if (display) {
                float h = dht.readHumidity();
                sevseg.NewNum(h * 100, 2);
            } else {
                float t = dht.readTemperature();
                sevseg.NewNum(t * 100, 2);
            }
        }
        sevseg.PrintOutput();
    }


body:
I am trying to get the string ("Enter an Integer : ") to print to the serial, then have the user enter a string of numbers which is then converted to an array of chars then ints.

The problem is the string will not display on the serial monitor when opened, and when the numbers are entered by the user, and  the conversion is done I need the string to be displayed again. So when the user inputs a number and presses enter it should be the end of that conversion, and prompt a new one.

Code below:

    int convert(void) {
      while (Serial.available() > 0) {
        char ch = Serial.read();
        if (ch >= '0' && ch <= '9' || ch == '-') {
          // Collect digits, only works if minus is first.
          strValue[index] = ch;
          index++;
        } else {
          strValue[index] = '\0';
          blinkRate = atoi(strValue);
          Serial.println(blinkRate);
          Serial.print("Enter integer : ");
          index = 0;
        }
      }
    }

title: Print to console

Answers: 3

body: The problem is, the Arduino serial monitor is way too crude to understand what you're trying to do.  Using a real terminal emulator (Teraterm for example) will probably give you better results (but you will also need to echo back the characters typed so you can see what you're typing) - either that or don't try and do things "in-line" like a prompt, instead print a message including the line feed (i.e., use `println()` instead of `print()`) so that the serial monitor can output a new line with the message text in it.

body:
It seems likely to me that you have not configured your serial monitor to send a newline. See the bottom line of the Serial Monitor.

[![Serial monitor configuration][1]][1]

If it is set to "no line ending" then when you send the line, you get the line only and no newline.

  [1]: https://i.stack.imgur.com/44gPd.png

body:
The biggest problem I see is that when your `convert()` function is called, if the user hasn't already typed something, then `Serial.available()` is going to return 0 (zero) and the `while` statement will never get executed.

Second, your `print` statement that prints the prompt to the console will only get called *after* you have already read a string from the user.

Third, you're trying to reinvent the wheel by writing your own function to read a string from the serial input. I suggest you use [`ReadStringUntil()`][1].

  [1]: https://www.arduino.cc/en/Serial/ReadStringUntil


body:
I am not sure if this question has been asked before but here's what I wanted to do.

I have a Arduino Nano, which I need to update with a new sketch. The plan is to be able to use another Arduino (maybe a Nano again), with an SD card reader and a sketch loaded as HEX file on it. Then connect both using a 4 pin RX/TX/5V/GND and upload the sketch from the transmitter to the receiver. Is it possible?

I am not sure how to do this; I know I can use one Arduino as an ISP to update other, but I am thinking of streaming the hex file to the other. Has anyone done this, any hints would be extremely helpful.

title: Field Programming a Arduino with another Arduino with SD card over RX/TX lines

Answers: 2

body:
See https://arduino.stackexchange.com/questions/15936/what-happens-when-code-is-uploaded-using-the-bootloader

There is a graphic on that page (reproduced below) which shows the general idea of what happens when you program using Tx/Rx after reset.

[![Optiboot programming][1]][1]

You could delve into the specs for the STK500 protocol (see linked page) and make your second Arduino follow that, to program from the SD card file.

  [1]: https://i.stack.imgur.com/14Whw.png

body:
There's actually a library for that as well! See [here][1] and [here][2].

  [1]: https://github.com/osbock/Baldwisdom/tree/master/BootDrive
  [2]: http://baldwisdom.com/bootdrive/


body:
I'm new to the Arduino and do not quite understand the `F()` macro yet.

 In my code, I have a `String`, and as I want to transfer it via WebServer, I need to write it to the answer.

Somehow I need to convert the `String`, to fit it into the `fastrprintln()` function.

    String weather_json = getWeatherData();
    char weather[2048];
    weather_json.toCharArray(weather,2048);
    client.fastrprintln(F(weather));

Do you have any idea for me?

title: Store String using F() Macro

Answers: 1

body:
The Arduino core macro [F()][1] takes a string literal and forces the compiler to put it in program memory. This reduces the amount of SRAM needed as the string is not copied to a data memory buffer. Special functions are required to access the data stored in program memory. The Arduino core hides a lot of the typical usages such as:

    Serial.println(F("Hello world"));

Further details of the low level access program memory access may be found in the [AVR GCC libc][2] documentation. The F() macro is [defined][3] as:

    class __FlashStringHelper;
    #define F(string_literal) (reinterpret_cast<const __FlashStringHelper*>(PSTR(string_literal)))

The FlashStringHelper class is used to help the compiler recognize this type of string literal when passed to Arduino functions. Below are some examples:

    // String constructor with program memory string literal
    String::String(const __FlashStringHelper *str);

    // Print (Serial, etc) of program memory string literal
    size_t Print::print(const __FlashStringHelper *);
    size_t Print::println(const __FlashStringHelper *);

You should not use the Arduino core F() macro with anything other than a string literal.

  [1]: http://playground.arduino.cc/Learning/Memory
  [2]: http://www.nongnu.org/avr-libc/user-manual/pgmspace.html
  [3]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/WString.h#L38


body:
I was wondering how much my Arduino I/O pin can output when it is set at **Output** and is at **High**.

I am using an **Arduino Uno R3**.

Thanks in Advanced.

title: What is the Maximum Current an Arduino can Supply?

Answers: 1

body:
40.0mA.

The Arduino UNO Digital IO pins are connected directly to the IO pins on the ATMEGA328P processor.

From page 299 of the [data sheet][1] for that processor...

[![enter image description here][2]][2]

Note that there is also a total current limit for all output pins combined, and that the voltage starts to drop as the current goes up.

  [1]: https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwi3p_GkrpnKAhWEQyYKHVBiCJUQFggjMAA&url=http://www.atmel.com/images/atmel-8271-8-bit-avr-microcontroller-atmega48a-48pa-88a-88pa-168a-168pa-328-328p_datasheet_complete.pdf&usg=AFQjCNEfBUXFG85G6huz6IpUbv0LQqhvGQ&sig2=9zwktRebt6GXlhApMf7Zzg
  [2]: https://i.stack.imgur.com/Brff1.jpg


body:
Consider:

[![Enter image description here][1]][1]

I having a problem in compiling in extern "C" code in the Arduino IDE 1.6.7 which I don't have on version 1.6.5.

The error is:

> error: conflicts with new declaration with 'C' linkage

It is complaining about the lines containing `loop()` and `start_timer(void);`.

This is my code:

    #ifdef __cplusplus
    extern "C" {
    #endif

    void start_timer(void);

    #ifdef __cplusplus
    }
    #endif

    void start_timer(void)
    {
        Serial.println("2");
        Serial.begin(9600);
        delay(2000);
    }

    void setup()
    {
        start_timer();
        Serial.println("4");
    }

    void loop()
    {
        Serial.println("1");
        delay(2000);
    }

  [1]: https://i.stack.imgur.com/UNzrv.png

title: Why can't the new Arduino IDE 1.6.7 compile extern "C"?

Answers: 2

body:
The compiler is telling you that there is a conflict between the *two* definitions of start_timer().

The normal usage of extern "C" is in a header file for functions that are accessed from both C and C++. This actually has to do with how C++ handles names and overloading. Using extern "C" will use normal C name handling and C++ name mangling is turned off (together with overloading, etc).

Please see https://stackoverflow.com/questions/31349865/compiler-error-for-conflicting-variable-declarations-conflicts-with-new-declar.

body:
I can't reproduce your problem still. See this:

[![Compiler output][1]][1]

---

However if you are having problems (and frankly I expected you to) then you should read this:

[How to avoid the quirks of the IDE sketch file pre-preprocessing](http://www.gammon.com.au/forum/?id=12625)

[How the IDE organizes things](https://arduino.stackexchange.com/questions/13178/classes-and-objects-how-many-and-which-file-types-i-actually-need-to-use-them)

---

I can reproduce your problem in IDE 1.6.5 (not 1.6.7). The code generated by the IDE preprocessor is this:

    #line 1 "sketch_jan11a.ino"
    #ifdef __cplusplus
    #include "Arduino.h"
    void start_timer(void);
    void setup();
    void loop();
    #line 2
    extern "C" {
    #endif

    void start_timer(void);

    #ifdef __cplusplus
    }
    #endif

    void start_timer(void)
    {
        Serial.println("2");
        Serial.begin(9600);
        delay(2000);
    }

    void setup()
    {
        start_timer();
        Serial.println("4");
    }

    void loop()
    {
        Serial.println("1");
        delay(2000);
    }

You can see that in the automatic function prototype generation that the IDE "helpfully" generates for you, it puts the prototype for `start_timer` outside the extern "C" declaration. Thus one function prototype has a declaration in C++ format, and the other in C format.

Why are you even doing this? I presume this is a small example of a larger problem.

If you follow the suggestions in my link [How to avoid the quirks of the IDE sketch file pre-preprocessing](http://www.gammon.com.au/forum/?id=12625) - *did you read that?* - the problem goes away, because .cpp files in IDE tabs are not subjected to this extra processing.

  [1]: https://i.stack.imgur.com/noxJR.png


body:
I am using the following https://code.google.com/p/simple-modbus/ arduino master library code. In order to communicate with my industrial drive.

All seems right but I am getting some weird errors. I am using the arduino master code as it is. With just the difference in modbus_construct.

Here is the error I am getting

     This report would have more information with
     "Show verbose output during compilation"

    enabled in File > Preferences.
    Arduino: 1.0.6 (Windows 7), Board: "Arduino Uno"
    In file included from SimpleModbusMasterArduino.ino:29:

    C:\Program Files\Arduino\hardware\arduino\cores\arduino/Arduino.h:131: error: expected ',' or '...' before numeric constant
    In file included from C:\Program Files\Arduino\hardware\arduino\cores\arduino/HardwareSerial.h:28,
                     from C:\Program Files\Arduino\hardware\arduino\cores\arduino/Arduino.h:215,
                     from SimpleModbusMasterArduino.ino:29:
    C:\Program Files\Arduino\hardware\arduino\cores\arduino/Stream.h:57: error: expected ',' or '...' before numeric constant
    In file included from SimpleModbusMasterArduino.ino:29:
    C:\Program Files\Arduino\hardware\arduino\cores\arduino/Arduino.h:222: error: expected ',' or '...' before numeric constant
    SimpleModbusMasterArduino:37: error: 'Packet' does not name a type
    SimpleModbusMasterArduino.ino: In function 'void setup()':
    SimpleModbusMasterArduino:45: error: 'packets' was not declared in this scope
    SimpleModbusMasterArduino:45: error: 'READ_HOLDING_REGISTERS' was not declared in this scope
    SimpleModbusMasterArduino:45: error: 'modbus_construct' was not declared in this scope

SimpleModbusMasterArduino:49: error: 'modbus_configure' was not declared in this scope SimpleModbusMasterArduino.ino: In function 'void loop()': SimpleModbusMasterArduino:56: error: 'modbus_update' was not declared in this scope

Here is my code:

    #include <SimpleModbusMaster.h>

    /*
       The example will use packet1 to read a register from address 0 (the adc ch0 value)
       from the arduino slave (id=1). It will then use this value to adjust the brightness
       of an led on pin 9 using PWM.
       It will then use packet2 to write a register (its own adc ch0 value) to address 1
       on the arduino slave (id=1) adjusting the brightness of an led on pin 9 using PWM.
    */

    //////////////////// Port information ///////////////////
    #define baud 115200
    #define timeout 1000
    #define polling 200 // the scan rate
    #define retry_count 10

    // used to toggle the receive/transmit pin on the driver
    #define TxEnablePin 2
    #define LED 13

    // The total amount of available memory on the master to store data
    #define TOTAL_NO_OF_REGISTERS 8
    #define TOTAL_NO_OF_CONSTANTS 1

    // This is the easiest way to create new packets
    // Add as many as you want. TOTAL_NO_OF_PACKETS
    // is automatically updated.
    enum
    {
      PACKET1,
      //PACKET2,
      TOTAL_NO_OF_PACKETS // leave this last entry
    };

    // Create an array of Packets to be configured
    Packet packets[TOTAL_NO_OF_PACKETS];

    // Masters register array
    unsigned int regs[TOTAL_NO_OF_REGISTERS];

    void setup()
    {
      // Initialize each packet
      modbus_construct(&packets[PACKET1], 1, READ_HOLDING_REGISTERS, 0x3000, 8, 0);
      //modbus_construct(&packets[PACKET2], 2, READ_HOLDING_REGISTERS, 0x3000, 8, 16);

      // Initialize the Modbus Finite State Machine
      modbus_configure(&Serial, baud, SERIAL_8N2, timeout, polling, retry_count, TxEnablePin, packets, TOTAL_NO_OF_PACKETS, regs);

      pinMode(LED, OUTPUT);
    }

    void loop()
    {
      modbus_update();
      Serial.println(regs[0]);
      //regs[0] = analogRead(0); // update data to be written to arduino slave

      //analogWrite(LED, regs[0]>>2); // constrain adc value from the arduino slave to 255
    }

title: Modbus master arduino code is throwing weird errors on upload

Answers: 1

body:
Your issue is that you define constants, such as `timeout`, which are [widely used][1] in Arduino library as parameter names. After preprocessing your definitions, correct code in "Arduino.h" such as

    unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout);

becomes

    unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long 1000);

No wonder the latter line fails to compile.

You will need to find unique names for your defines, or use constant variables instead.

  [1]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Arduino.h


body:
we are using Arduino W5100 Ethernet shield. The code is to try DHCP first and if that fails, then try the static IP. we do the Ethernet Initialization and stop every time.  The library is Arduino Ethernet library.

 1. when we try with a wireless router, everything works and we are able to contact our web server.
 2. Now the wireless router is connected to a switch.
switch <======> router <=====> W5100

if we try to send data using the switch directly, DHCP fails, whereas a laptop using the same cable works.

Question is, even Arduino Library has DHCP functionality, why should a laptop work where the shield is failing? The network and topology and rules should be same for both the laptop and W5100 shield. Anything we can do to debug this issue more?

Edit1 : -  Switch which we are using is [L3 in nature][1].

Below is the code which we are using at present.

        while(1) {

      KDEBUG("wait 10 seconds...\r\n");
      // wait 10 seconds
      for(loop = 10; loop > 0 ; loop--) {
       wait_millis(1000);
      }

      KDEBUG("Try transmitting data on ethernet...\r\n");
      transmit_data();

     }

     return 0 ;

    }

    void wait_millis(uint16_t num) {

     for(; num > 0 ; num-- ) {
      _delay_ms(1) ;
     }

    }

    // transmit data using Ethernet
    static uint8_t transmit_data() {

     char request[256];
     uint8_t status = 0  ;

     // reset counter
     counter = (counter > 254) ? 0 : counter ;

     memset(&request[0], 0 , sizeof(request));
     memset(&bencode[0], 0 , sizeof(bencode));

     wait_millis(5000);
     // try DHCP
     if (Ethernet.begin(mac_address) == 0) {
      KDEBUG("Failed to configure Ethernet using DHCP \r\n");
      // use static IP. no return code.
      Ethernet.begin(mac_address, ip_address);

     } else {
      KDEBUG(" Got lease from DHCP \r\n");
     }

     // wait for ethernet to initialize:
     wait_millis(5000);

     // we got a connection?
     status = client.connect(server, port) ;
     KDEBUGF("ethernet client  status= %d \r\n", status);
     if(!status) {
      goto quit ;
     }

            KDEBUG("connected \n");
     // create an HTTP request
     strcat(request, "GET /api/gl868.php?data=");
     strcat(request,bencode);
     // 12 chars
     strcat(request," HTTP/1.1 \r\n");
     // 25 chars
     strcat(request,"Host: ");
     strcat(request,server);
     strcat(request," \r\n");

     // send GET request
     client.println(request);
     _delay_ms(1);
     client.println() ;

     wait_millis(1000);
     client.stop();
     wait_millis(1000);

     if(client.connected()) {
      client.stop();
     }

     return 1 ;

    quit:

     wait_millis(100);
     if(client.connected()) {
      client.stop();
     }

     return 0 ;

    }

  [1]: http://searchnetworking.techtarget.com/tip/Layer-3-switches-explained

title: W5100 Ethernet shield DHCP fails with a Switch

Answers: 2

body:
A certain way to debug this is to use [`tcpdump`](http://www.tcpdump.org/tcpdump_man.html) to capture network packets from both Arduino and your laptop and check the differences. I would start by looking for `DHCPDISCOVER` packet that Arduino should be sending.

A simpler way would be to check DHCP server logs to see how the communication looks like from server's perspective. Here, you should be looking for lines which have the MAC address of your Arduino shield. The success of this approach will depend of the verbosity of the DHCP server you're using.

body:
If I understand your connection...

 - Device over wifi to router works.
 - Wired, via a switch to router does not?

DHCP is clearly switched on for WLAN, is it switched on for LAN?

Personally I always use fixed IP for such projects, with a default value that can be reset so that I can always find my device. I change the IP (and/or MAC) via a serial monitor.


body:
I want to use an Arduino Yún as a kind of outdoor weather station. I want to supply the power for the Yún with a 5V USB-Charger. Using a normal USB cable everything works fine. But as the weather station shall be far from the next power socket, I made the USB cable about 10 meters longer. Now the Yún does not power up any more.

Has anybody an idea why?

Should I use a 12 V power supply and a 7805 power converter instead?

title: Power Supply Problem with Arduino Yún: Using a long USB cable

Answers: 1

body:
The USB specification limits the length of a cable between two devices to 5 meters. When you make a longer cable, you're going out of spec, which means it is not guaranteed to work anymore.

Since you're only supplying power, the issue is (as you have guessed) the voltage drop in the cable. However, the voltage drop will depend on how much current Arduino is consuming at any given moment. Supplying it with a higher voltage without a converter is dangerous, because it will lead to overvoltage you won't be able to control.

I'd suggest trying [better cables][1] first: thicker and stiffer cables have thicker wires, and may have less voltage drop. You can also make your own cable (provided you can solder) using only two thick wires for power.

The ultimate solution, like you said yourself, is to deliver higher voltage over the wire (12V would do) and install a power converted (12V to 5V) near your Arduino. That way, the voltage drop in 5V line will be small, and the voltage drop in 10m 12V line will be compensated by the converter. Actually, the intermediate voltage may be higher: you can simply drop a mains line (220V or whatever you have) to your weather station and place the same USB charger near the Arduino.

  [1]: https://raspberrypi.stackexchange.com/questions/39066/usb-cables-why-are-some-of-them-bad-for-raspberry-pi/39080


body:
I have to build a wireless sensor network with arduinos on my project. It does not need to be a mesh network, but it needs to have self healing capabilities.

I would like to use something cheaper than XBees. I tried the NRF24L01 with maniacbug's, TMRh20's and MySensors' libraries. However they aren't solving the problem and I'm wasting a ton of time trying to figure out how to make them work.

Another thing, I need a lot of repeater nodes between the base and the sensors because the office is 2 km far from the monitoring area and some of these libraries have a limitation of 5 level deep network, so I'd have max 4 repeaters between the base and sensor, which is bad.

And the last, my project is going to be fine with 15 sensors for now, but it'll have 500-1000 nodes in a couple of months and most of these libraries assign 8 bit addresses (256 nodes), which does not cover that amount of nodes.

What do you suggest?

title: Module and library for self healing large sensor network

Answers: 1

body:
A few thoughts:

1. For ~$20 per unit, the 1mW Digimesh modules will take care of reliable mesh networking plus provide a high degree of configurability and scalability. Depending on the budget for your sensor nodes this might be better than "wasting a ton of time" messing with bare-bones hardware and third party code.

2. Constrain the mesh network within the "monitoring area" and set up dedicated point-to-point links (with higher power and directional antennae) between it and your office. Set up two or three if you want redundancy.

3. If you can't afford better hardware but have time to spare, consider reading up on mesh protocols and implementing one you think best fits your project. Many of them are reasonably simple if you are not pushing for maximum efficiency or performance.


body:
I know it's pretty standard to set up an Arduino system as a BLE client, and use something like an app running on a smartphone as the GATT server, which receives the data and does something with it.

In my scenario I have a BLE sensor that is not connected directly to the Arduino system, and I want the Arduino to be able to respond to the sensor output (a wearable accelerometer) and, for example, initiate various lighting sequences depending on the data being received.

I would prefer not to introduce a third component (ie: mobile device as GATT server) into the equation. I'd like for the Arduino to listen to the remote device's services and characteristics, analyze the incoming data and then make some decisions about what LEDs to illuminate based on that analysis.

Can an Arduino run as a GATT server?

title: Can an Arduino act as a GATT Server (Bluetooth LE)

Answers: 2

body:
I got this link here that could be helpful - link at the bottom. It is a tutorial that shows you how to control your Arduino with a custom app on an Android. It uses the MIT app creator, an app that lets you create an app. You program it with there IDE in some Java I believe. You can add button to your app so that is sends a message to your Arduino then program the Arduino to do something when it receives that message. For the Arduino side, you could buy an HC-05 Bluetooth module. It is both an transmitter and receiver. It is quite cheap and very popular so there is many libraries out there. I think this is a good module you should get and I recommend to get them in pairs so you can connect them together with 2 Arduinos.

https://www.youtube.com/watch?v=E-1w7dL3Cps

body: An ESP32 module (Arduino IDE compatible) can act as both a GATT Client and Server, and there are module examples for each of these, as well as github projects.


body:
I get a compile error when I try to set a different font in Adafruit GFX on a TFT display on my Arduino Uno.

I'm testing a new TFT shield for Arduino equipped with an ILI9341 by using the Adafuit GFX libraries and examples. The test program supplied with the library works fine out of the box displaying text and all kind of drawings on the screen.

However, the standard font built into the Adafruit GFX library is "blocky" to save memory space. They do provide other fonts, but I get an error when I try to invoke them.

The segment of code that throws the compile error is this one:

    unsigned long testText1() {
      tft.setFont();    // When I remove this line the sketch compiles OK
      tft.fillScreen(BLACK);
      tft.setCursor(0, 50);
      tft.setTextColor(RED);
      tft.setTextSize(13);
      tft.println("1234");
    }
When compiling I get this error:

> "error: ‘class Adafruit_ILI9341_8bit_AS’ has no member named ‘setFont’"

According to Adafruit's GFX manual, the `setFont()` procedure allows to define a new font or revert to the standard one.

I examined the libraries and nowhere could I find a procedure to select a font, yet the example has declarations like these below, so changing fonts should be possible:

    #include <Adafruit_GFX_AS.h>
    #include <Adafruit_ILI9341_8bit_AS.h>
    #include <Font16.h>
    // #include <Font32.h>
    // #include <Font64.h>
    // #include <Font72.h>
    #include <Font7s.h>
    #include <Load_fonts.h>

I would like to load the 7segment font with:

    tft.setFont(&Font7s);

Does anybody have experience to share loading these fonts?

title: How can I load fonts into Adafruit GFX for TFT display (ILI9341)

Answers: 3

body:
Looking further into documentation on the Adafruit website they indicate that indeed, their GFX library published on GitHub does not handle different fornts.

Case closed :-)

body:
Newer versions of the library CAN use fonts.

    #include <Fonts/FreeSerifBold12pt7b.h>

and then...

 matrix.setFont(&FreeSerifBold12pt7b);

Whether they work or not, I dunno. ***Case closed, lol!***

body:
Tested on Windows, with newest libraries **Adafruit-GFX** and  **Adafruit_PCD8544** (Nokia5110 LCD connected to Arduino Nano).

    #include <Fonts/FreeSerifBold12pt7b.h>

and then

    matrix.setFont(&FreeSerifBold12pt7b);

Then there is one very important difference how to use function `drawChar(...)`. Coordinates of character (x,y) begins in left-bottom corner of character instead of top-left corner so this will not work (you will see only about 1 px of character):

    matrix.drawChar(0,0,'1', 1, 0, 6),

**Use this to show all pixels of character:**

    matrix.drawChar(20,20,'1', 1, 0, 6),

Full manual for using fonts here: [Adafruit GFX Graphics Library - Using Fonts][1]

  [1]: https://learn.adafruit.com/adafruit-gfx-graphics-library/using-fonts


body: I was wondering if Arduino digital pin can receive binary data. For example, I might want one Arduino to send another Arduino a binary code. If the code is `01` it would turn a red led on, if it was `11` it would turn green on, etc. I would like to do this so that I don't have to use a lot of digital pins. Is this possible with Arduino or not?

title: Arduino recieving binary

Answers: 2

body:
Pretty much anything is possible.

There is a method known as *bit banging* which toggles a generic IO pin to create a protocol, and read changes on another generic IO pin to read in the data of a protocol.

The trick is in creating a protocol.

Fortunately that has all been done for you - the SoftwareSerial library. It will create a bit banged version of the RS232 serial protocol using any combination of IO pins to transfer data between devices.

body:
As Majenko says, it is easily possible to implement using bit banging.  Assuming that you want to write your own protocol, you need to distinguish between the end of one data packet and the start of another.  This could be done by having all of the packets the same length (as in your example with length 2) or using a form of [Huffman coding][1] where only the external nodes of the state tree are results so you know when a full packet has been received.

Using a standard serial or I2C protocol would also work.  With serial you would be able to communicate via a serial emulator on a USB port so you could test with a computer.

  [1]: https://en.wikipedia.org/wiki/Huffman_coding


body:
 This code is used for communication between the Glediator interface and a NeoPixel Matrix, but I receive an error saying 'UCSR0A' is not defined within the scope.

    UCSR0A |= (1<<U2X0);
    UCSR0B |= (1<<RXEN0)  | (1<<TXEN0) | (1<<RXCIE0);
    UCSR0C |= (1<<UCSZ01) | (1<<UCSZ00)             ;
    UBRR0H = 0;
    UBRR0L = 1; //Baud Rate 1 MBit (at F_CPU = 16MHz)

Any feedback is appreciated.

title: UART error can not compile on Arduino Yun (ATmega32u4)

Answers: 3

body:
Those register names are for a different chip (maybe the ATMega328P of the Uno).

Instead you need to use the *right* register names.  Start by reading the datasheet for the ATMega32U4.  You might find that the register names are UCSR1A etc, or UCSRA or something like that instead of UCSR0A.

body:
You should be able to use Serial1 to access the USART. But...

> Note that on the Yún, the Serial class refers to USB (CDC)
> communication; for TTL serial on pins 0 and 1, use the Serial1 class.
> The hardware serials of the ATmega32U4 and the AR9331 on the Yún are
> connected together and are used to communicate between the two
> processors. As is common in Linux systems, on the serial port of the
> AR9331 is exposed the console for access to the system, this means
> that you can access to the programs and tools offered by Linux from
> your sketch[1].

Please see below references for further details:

 1. https://www.arduino.cc/en/Main/ArduinoBoardYun
 2. https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/variants/yun/pins_arduino.h#L40
 3. https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/variants/leonardo/pins_arduino.h#L363

body:
So what I did was changing the codes by replacing the '0' from the other chipset to the '1' on the Atmega32u4

    UCSR1A |= (1<<U2X1);
    UCSR1B |= (1<<RXEN1)  | (1<<TXEN1) | (1<<RXCIE1);
    UCSR1C |= (1<<UCSZ11) | (1<<UCSZ10)             ;
    UBRR1H = 0;
    UBRR1L = 1; //Baud Rate 1 MBit (at F_CPU = 16MHz)

    ISR(USART_RX_vect)
    {
      unsigned char b;
      b=UDR1;
    ...

I think that this is the problem that causes freeze when I Open Serial.
Any advice? Thanks In advance


body:
I'm building an automatic door lock, which is moved by a servo ( [this one][1] ). However, I want to still make it possible to open the lock manually, but it's not possible if the servo is attached to the lock mechanism.

Do you have ideas on how to go around this problem?

Here's a diagram of the lock mechanism

[![Lock mechanism diagram][2]][2]

  [1]: http://www.amazon.com/Rage-RC-S142-16-6VM-Standard-Analog/dp/B00MPW2N6K "this one"
  [2]: https://i.stack.imgur.com/HlkLP.png

title: Automatic/manual door lock with servo

Answers: 1

body:
So it's actually the worm gear that is causing your problem, since that can't be reverse driven by the cogs.

The simplest option, I think, would be to have the middle cog normally separated from the worm gear and only re-engage it when you need to drive the mechanism with the servo.  You could maybe use a second servo to move it into the right place, or maybe a solenoid, or something along those lines. Have it slide along a short track or slot with a spring to ensure it disengages when the solenoid is released.


body:
I use an Arduino and a 9 DOF sensor (gyroscope, accelerometer and magnetometer) and I'm trying to use the pitch, roll and yaw that the sensor gives me to rotate an object in unity.

I managed to correctly compute pitch and roll (the z and x axis in unity) from the accelerometer but it seems that I can't get the Yaw right. By that I mean that when I rotate my sensor pitch or roll it rotates my yaw too, in a weird way.

----------

*Code in the arduino to get the heading*

    void getHeading(void)
    {
      heading=180*atan2(Mxyz[0],Mxyz[1])/PI;
      if(heading <0) heading +=360;
    }

    void getTiltHeading(void)
    {
      //float pitch = asin(-Axyz[0]);
      //float roll = asin(Axyz[1]/cos(pitch));
      float pitch = atan( Axyz[0] / sqrt( Axyz[1] * Axyz[1] + Axyz[2] * Axyz[2] ) );
      float roll = atan( Axyz[1] / sqrt(Axyz[0] * Axyz[0] + Axyz[2] * Axyz[2]));

      float xh = Mxyz[0] * cos(pitch) + Mxyz[2] * sin(pitch);
      float yh = Mxyz[0] * sin(roll) * sin(pitch) + Mxyz[1] * cos(roll) - Mxyz[2] * sin(roll) * cos(pitch);
      float zh = -Mxyz[0] * cos(roll) * sin(pitch) + Mxyz[1] * sin(roll) + Mxyz[2] * cos(roll) * cos(pitch);
      tiltheading = 180 * atan2(yh, xh)/PI;
      if(yh<0)    tiltheading +=360;
    }

*Pitch and roll*

        float _Pitch  = (float)(180 / Math.PI * Math.Atan( m_ResultX / Math.Sqrt( m_ResultY * m_ResultY + m_ResultZ * m_ResultZ ) ) );
        float _Roll = (float)(180 / Math.PI * Math.Atan(m_ResultY / Math.Sqrt(m_ResultX * m_ResultX + m_ResultZ * m_ResultZ)));
        float _Yaw = (float)(m_TiltHeadingResult);

Don't hesitate to ask for details.

title: Compute yaw from magnetometer and accelerometer

Answers: 1

body:
I don't know how all your sensor's axis are lined up, but it looks like you should level the magnetometer readings by rotating them by `-pitch` and `-roll` to get back to the global reference frame, instead of rotating the magnetometer readings by the positive angles.

However, The pitch and roll angles in the code are both relative the horizon, not a set of euler angles that define a rotation between two states; because of this, they do not compose to rotate the magnetometer back into the global xy frame like I assume the equations are trying to do. The code is also only using `atan` for pitch and roll instead of `atan2`, so their range is only 180 degrees.

You need to make sure the rotation matrix you multiply your magnetometer reading by is based on the same conventions as the equations you use to get pitch and roll from the accelerometer, and that it cancels the observed rotation.

To do this correctly, I recommend you read into [euler angles][1]. You might also try searching around for a good library that handles 9-DOF sensor fusion for you.

  [1]: https://en.wikipedia.org/wiki/Euler_angles