Arduino Ethernet Client crashes after obtaining values from string My Ethernet server keeps crashing after pulling the RGB values from the string. It remains connected if I'm just toggling a pin, but whenever the string has the rgb values in it, the RGB values are pulled, the LED changes but then the server crashes and won't take any more requests. Do I need to restart the server after it plucks the RGB values for another read? If so, how would I go about doing this?

Thanks, James :)

Example HTTP request that causes the crash: /?LED=B233+G011+R133&t=T HTTP/1.1

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

    byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    byte ip[] = {192, 168, 0, 102 };
    byte gateway[] = {192, 168, 0, 1 };
    byte subnet[] = {255, 255, 255, 0 };
    EthernetServer server(84);
    ;

    char* redstring={0};
    String blue1;
    String green1;
    String red1;
    String testString = "0123456789";

    int blue;
    int green;
    int red;
    int been=0;
    int b=0;
    int g=0;
    int r=0;
    //////////////////////

    void setup(){

    pinMode(11, OUTPUT);
    pinMode(9, OUTPUT);
    pinMode(7, OUTPUT);
    pinMode(6, OUTPUT);

    //start Ethernet
    Ethernet.begin(mac, ip, gateway, subnet);
    server.begin();

    //enable serial data print
    Serial.begin(9600);
    Serial.println("SERVER RUNNING HTTP / GET");
    }

    void loop(){
     ////////////////////////////////////////
     EthernetClient client = server.available();
if (client) {
while (client.connected()) {
  if (client.available()) {
    char c = client.read();

    //read char by char HTTP request
    if (sizeof(redstring) < 100) {

      //store characters to string
      redstring += c;
      //Serial.print(c);
    }

    //if HTTP request has ended
    if (c == '\n') {

      ///////////////////////////////////////////

      Serial.println(redstring);

      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/html");
      client.println();
      client.println("");
      client.println("<link rel=\"shortcut icon\" href=\"data:image/x-icon;,\" type=\"image/x-icon\">");
      client.println("");
      client.println("<TITLE>Arduino GET</TITLE>");
      client.println("");
      client.println("");

      client.println("
HTML GET
");
      //change ip back if not local
      client.println("<FORM ACTION=\"http://192.168.0.102:84\" method=get >");

      client.println("JQUERY: <INPUT TYPE=TEXT NAME=\"LED\" VALUE=\"\" SIZE=\"25\" MAXLENGTH=\"50\">
");

      client.println("<INPUT TYPE=SUBMIT NAME=\"t\" VALUE=\"T\">");

      client.println("</FORM>");

      client.println("
");

      client.println("");
      client.println("");

      delay(1);
      //stopping client
      client.stop();
      /////////////////////
      //readString = Character.toUpperCase(readString);
      for (int i = 1; i < sizeof(redstring); i++) {
        if (strchr(redstring, 'B') && && redstring[i+1] > -1) {
          blue=redstring[i+1, i+4];
          analogWrite(11, blue);
          delay(1000);
                      }

        if (strchr(redstring, 'G') && redstring[i+1] > -1) {
          green=redstring[i+1, i+4];
          analogWrite(9, green);
          delay(1000);
                      }

        if (strchr(redstring, 'R')&& redstring[i+1] > -1) {
          red=redstring[i+1, i+4];
          analogWrite(7, red);
          delay(1000);
                      }

      }

      //clearing string for next read
           redstring="";
          (redstring, "0", sizeof(redstring));
        }
      }
    }
  }
}

Using String, which uses dynamic allocation/deallocation on the heap is not advised in embedded platforms, as this can quickly lead to heap fragmentation, eventually leading to memory exhaustion, heap/stack collision...

First off, you should try to replace all String usage, everywhere in your program, with C-tyle strings, i.e. char* or char xxx[...] along with dedicated C functions to deal with them: strchr, strstr, strcpy, strcat, strtok, atoi...

Second, you can avoid using global variables and use the stack for many of them.

void loop() {
    ...
    if (client) {
        char readString[101];
        const int READ_STRING_SIZE = sizeof(readString) - 1;
        int readIndex = 0;
        while (client.connected()) {
            if (client.available()) {
                char c = client.read();
                if (readIndex < READ_STRING_SIZE) {
                    readString[readIndex++] = c;
                }

                if (c == '\n') {
                    // Terminate the read string
                    readString[readIndex] = 0;
                    Serial.println(readString);

                    // Prepare for next reeading
                    readIndex = 0;

                    client.println("HTTP/1.1 200 OK");
                    ...
                    client.stop();

                    // convert readString to all uppercase
                    for (i = 0; i < strlen(readString); i++)
                        readString[i] = toupper(readString[i]);

                    bool b = false;
                    bool r = false;
                    bool g = false;
                    int blue, red, green;

                    // Look for 'B' value
                    char* bb = strchr(readString, 'B');
                    if (bb != 0 && isdigit(bb[1]) {
                        blue = atoi(&bb[1]);
                        analogWrite(11, blue);
                        delay(500);
                        b = true;
                    }
                    // Same for 'G' and 'R' value
                    ...
                    if (b && r && g) {
                        Serial.print("CHANGING RED TO: ");
                        Serial.println(red);
                        Serial.print("CHANGING GREEN TO: ");
                        Serial.println(green);
                        Serial.print("CHANGING BLUE TO: ");
                        Serial.println(blue);
                    }
                }

                if (strstr(readString, "PIN6") != 0) {
                    digitalWrite(6, !digitalRead(6));
                    ...
                }
            }
        }
    }
}

In this sample code, we have completely removed dynamic memory allocation.


Run Stepper with A4988 driver in highest resolution I have a Bipolar Stepper Motor (12V, 350mA, 28oz-in NEMA-17) and would like to run it in the highest resolution (Sixteenth Step) with the A4988 Driver. According to multiple sources I read I need to "put 5V" to the MS 1,2,3 pins. What does this mean/How can I achieve this ?

Do I need to hook up the MS 1,2,3 to the digital pins of the Arduino and write Digital High. Or do I need to hook all of them to 5V together ? And should the code look like this ? Is this safe/good pratice ?

int MS1Pin = 8;                 // Set MS Pins
int MS2Pin = 9;
int MS3Pin = 10;

void setup()
{
  pinMode(MS1Pin, OUTPUT);      // sets the digital pin as output
  pinMode(MS2Pin, OUTPUT);      // sets the digital pin as output
  pinMode(MS3Pin, OUTPUT);      // sets the digital pin as output
}

void loop()
{
  digitalWrite(MS3Pin, HIGH);
  digitalWrite(MS2Pin, HIGH);
  digitalWrite(MS1Pin, HIGH);
<<MY CODE here>>

}

Sorry for these beginner questions, I just don't want to fry the Chip and this to work.

Thank you.

You can drive the MS pins from the Arduino if you want, but there is no need.  You can just hook them all up to 5V.

Have you seen this page, there seems to be load of details that you might find relevant.
https://www.pololu.com/product/1182


esp2866 powered externally not working I got a beginner level problem.
I got two esp2866 nodeMCU, they both work with the usb cable and I can get the blink program to run though it.
Running them with external power doesn't seem to work though. I expect the blink program to run when I plug them in but I get no led light signal at all. My power source looks identical to this. I got jumpers set on 5V. I don't have a voltage meter but I've tested against my Arduino Uno and it runs as expected when connected to the same wires.

Shouldn't I get the blink signal or any other led signal if the nodeMCU got power?
Any clue to how I could fail to provide power?

thank you!
edit: picture and jack barrel power input: 5V 3A

Linear Regulator Dropouts
The linear voltage regulators found on that board are going to expect more than 5V at the barrel jack, because they require a minimum "drop out" voltage.  The AMS1117 that is on that board, so far as I can tell, has a drop out voltage up to 1.3V.  So you would want at least 6.3V (perhaps better 7V) at the barrel jack in order to get 5V out of it.
So the NodeMCU board may be seeing 5 - 1.3 or 3.7V at the input to its 3.3V regulator, which also requires its own drop out.  The output of that 3.3V regulator may then be significantly below what the esp8266 specified operating voltage range.
UPDATE
So I did the tests mentioned in the comments, just to illustrate the problem.  And the results are about as expected.
I altered the stock blink sketch that comes with IDE version 1.8.13 to use LED_BUILTIN (as opposed to 9) in the pinMode and digitalWrite calls.
I changed the LOW period, which is LED ON for my board, to 10000ms so that my voltmeter would have time to settle on a voltage test across the LED.
And I uploaded to the board, a NodeMCU 1.0 clone by Hitletgo.
When powered on its USB micro b jack, 3.3V labeled pin of the broad measuring 3.30 V.  The LED color is blue, it is bright and it is dropping 2.66V.
Then I switched to powering the NodeMCU board by via of VIN pins from the YwRobot regulator board.  I provided 5.05V to the barrel jack.  To not great surprise, it does not blink.
The voltage out of regulator board was 3.26V.  To be clear, I have this jumper for 5V.  As a sanity check, I jumpered it for 3.3V and got about 2.5V out of it.  Again, this is unsurprising because it also needs a dropout voltage.
I then measured the "3.3V" header line on the NodeMCU itself to be 2.14 V.  Without sufficient voltage into the 3.3V regulator, it is not providing 3.3V out.  And what it is producing is below that LED forward voltage when lit.  So it is not surprising that it is not lit.
The ESP8266 technical specifications suggest that it can run down to 1.8V.  So just for the hell of it I connected the board back to USB and updated the blink sketch to "blink" D8 (or GPIO15) 4 seconds on, 4 seconds off.  I did not attach anything to this pin except the voltmeter.
I then reconnected the board to the test rig and found with a meter that it is "blinking" D8 just fine with a logic level consistent with the voltage the ESP8266 is actually receiving.
So in summary, the arrangement here is running the ESP8266 but there is not enough available voltage for it to light the LED.  And it is very likely the exact same thing is happening for you.


Latest news about alternative Arduino IDEs I simply hate the default Arduino "IDE".
On Windows I use Visual Studio Code with the related plugin.

Now I have a Ubuntu machine and I'm looking for the definitive IDE.
Questions:

I'm not sure whether to use VSC I need to install the default IDE as well
is there something better?

By the way, I also have QtCreator, PHPStorm, MPLAB X, STM32Cube (Eclipse based).

I use the Arduino IDE to 'build' everything.

However, in case of a bigger project, I use a 'decent' code editor (Visual Studio in my case) to edit, and the Arduino IDE to build.

Also, because I prefer testing all non-Arduino related code on the PC (not on the Arduino), the Visual Studio (C++) project uses some stub classes I created (specifically for my project), and I can run the application on my PC.

When some part is finished, I can build the same code in Arduino IDE, but without the stubs (because these are acquired from Arduino.h and related Arduino files).

What IDE is best to 'edit' code is very subjective I think. But in the above way I can see many classes/files at a glance on the left side (and not in the top like Arduino IDE where only like 5 tabs fit on a screen), and to test lots of code on the PC already before sending it to an Arduino.

The GitHub repository can be found here: https://github.com/michelkeijzers/Mestra

Project inside is DmxLightShow.


how much current does Arduino Nano draw when only using 8 digital pins? I want to connect an Arduino Nano to an Intel Minnowboard Max (it's like a Raspberry Pi). I know Arduino can draw up to 500 mA current through the USB connection. Since I already need the USB to communicate the Arduino with the Minnowboard, it would be nice to not power the Arduino separately as well. However, I wouldn't want the current the Arduino draws from the Minnowboard to overheat Minnowboard's 2.5A 12V power supply.
I only have 8 buttons connected to the digital pins of the Arduino Nano. Nano sends the state of the buttons to the Minnowboard via USB (serial). How much current is Arduino drawing in this case?

I would guess around 50 mA, to power the processor and the USB converter. I notice that this question suggests more like 20 mA.

To be certain, you could measure it, but probably 20 to 50 mA would be a ball-park figure.


Tile NeoPixel NeoMatrix 8x8 As a programmer I am new and lack some knowledge in electronic and I will appreciate the help.

I wish to connect 3 Adafruit NeoPixel NeoMatrix 8x8 - 64 RGB LED Pixel Matrix (https://www.adafruit.com/products/1487) can some one please provide me a scheme how to connect/tile 3 these NeoMatrix 8x8 to one Arduino Uno.

Thanks a lot

On the page that you cite they say

If, say, you need MORE blinky, you can chain these together.

For the second shield, connect the DIN connection to the first panel's DOUT.
Also connect a ground pin together
and power with 5V.
There you go!

You can chain as many as you'd like although after 4 or more panels you may run low on RAM if you're using an UNO. Watch your power usage too, you may need a 5V 10A power supply for so many of these!

Related:

They also say:

There is a single data line with a very timing-specific protocol. Since the protocol is very sensitive to timing, it requires a real-time microconroller such as an AVR, Arduino, PIC, mbed, etc. It cannot be used with a Linux-based microcomputer or interpreted microcontroller such as the netduino or Basic Stamp.

Our wonderfully-written Neopixel library for Arduino supports these pixels! As it requires hand-tuned assembly it is only for AVR cores but others may have ported this chip driver code so please google around.

An 8MHz or faster processor is required.


Arduino serial monitor first message I'm connect arduino to my PC through serial monitor. Very common situation:

Serial.begin(9600);
delay(100);
Serial.print("Hello, World!");

But I always get an ¤ello, World!. How can I get the first symbol straight? I've tried on both unix & windows, mega & uno. I've also tried println, but with no happiness

This is more a wild guess than a real answer... Assuming your terminal
is using a character set more or less like ISO-8859-1 or Windows-1252,
then you are receiving 0xA4 when you expect 0x48. My guess is that the
very first start bit got lost somehow.

Here are the serial port waveforms corresponding to the expected and
received bytes. ‘S’ and ‘T’ are the start bit and stop bit respectively.
The data bits are sent least-significant first. The idle state is HIGH:

• ‘H’ = 0x48 = 0b01001000

────┐               ┌───┐       ┌───┐   ┌──────
    │ S   0   0   0 │ 1 │ 0   0 │ 1 │ 0 │ T
    └───────────────┘   └───────┘   └───┘

• ‘¤’ = 0xA4 = 0b10100100

────┐           ┌───┐       ┌───┐   ┌──────────
    │ S   0   0 │ 1 │ 0   0 │ 1 │ 0 │ 1   T
    └───────────┘   └───────┘   └───┘

You can see that, if you remove the start bit from the first waveform,
you get exactly the second one. I do not know what may be the cause of
this though.


Trouble with sleep mode and interrupts Context

I am building a small battery powered counting device. As with many other projects like this, saving power is critical. I am therefore trying to utilise the sleep mode wherever possible. This is using a 328P as a standalone MCU running on the 1MHz internal clock

The Hall Effect sensor I am using outputs Vcc when nothing is detected, and Ground when something is detected. It therefore seems well suited to being used as a trigger for an interrupt to wake up the 328P from sleep (so that I don't even need to use a watchdog timer.)

Below is an excerpt from my code. This code does put the processor into sleep as desired. However, from testing I have discovered that the device will not sleep when the magnet is left near the sensor, as its output stays LOW. As I only want to detect pulses of a moving piece of metal, this is wasting power. I only want to wake up when it is initially detected on each cycle.

void sleepLoop()
{
  Serial.print("S");

  delay(5);   //scales to 40ms

  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  noInterrupts();

  attachInterrupt(digitalPinToInterrupt(countInterruptPin), sleepInterrupt, LOW);

  interrupts();
  sleep_cpu();

  //The program will continue from here.

  //First thing to do is disable sleep.
  sleep_disable();
}

I therefore changed

attachInterrupt(digitalPinToInterrupt(countInterruptPin), sleepInterrupt, LOW);

to

attachInterrupt(digitalPinToInterrupt(countInterruptPin), sleepInterrupt, FALLING);

PROBLEM

Now my processor never goes to sleep. For debugging I have put in a serial print at the start of the loop so that I know it has entered this loop of code. Whether LOW or FALLING is used the 'S' is printed. I only know it is not sleeping because I am measuring the current flow.

I thought the sensor may be going LOW long enough to keep the device awake, but not long enough to register as a count (as I have a debounce in there) so I have checked the output from the sensor with an oscilloscope in case it was momentarily going LOW, but I couldn't see any sign of this.

The findings from the oscilloscope make me feel like there is something about the interrupt function that I am overlooking. Any help would be greatly appreciated!

Only low level detect is possible with external interrupt pins (INT0/D2 and INT1/D3) in power down sleep mode. The signal must be low for a number of clock cycles to be detected and the interrupt will detected while the signal is low (and the interrupt is enabled). It is not a transition.

A pin change interrupt could be used instead.

For more details please see chap. 9.5 Power-down Mode and chap. 12. External Interrupts.

Cheers!


Interrupt triggering using DHT-11 I am new at arduino.
I want to write a sketch that would print the message if the temperature grows greater than 30 C.
Here is my sketch can you please tell me what's wrong with it

#include "DHT.h"
#define DHTTYPE DHT11
#define dht_dpin D3

DHT dht(dht_dpin, DHTTYPE);

void setup()
{
 Serial.begin(9600);
 }
void loop()
{
 float t = dht.readTemperature();
 Serial.print("temp=");
 Serial.println(t);
 attachInterrupt(dht_dpin, IntCallback, CHANGE);
}
void IntCallback()
{
  float t = dht.readTemperature();
  if(t>30)
  {
    Serial.print("Alert");
  }
}

You can't use an interrupt the way you are attempting to. Attaching an interrupt to a pin like that will cause the interrupt to trigger any time the digital pin's value changes. The DHT11 uses serial communication to send temp values to the Arduino. Serial communication uses lots and lots of on/off pulses on the signal line to send characters of data. Your interrupt will fire every time the DHT11 toggles the signal line.

You need to read the temp from the DHT11 in your loop, and then add an if statement that does what you want when the temp exceeds your threshold. (It looks like you just need to get rid of the attachInterrupt() call, and instead call IntCallback() every couple of seconds.


Digispark uploading not working in KDE Neon (Linux) I am using KDE Neon and have downloaded the Arduino IDE via the Snap store. It worked well with the ESP8266 and other Arduions. But when I tried to upload a simple sketch or an example sketch to my Digispark, I get an error message. I have selected the right Board and the micronucleus programmer. I have also installed libusb. But I always get the following error message:
/home/myusername/snap/arduino/41/.arduino15/packages/digistump/tools/micronucleus/2.0a4/micronucleus: error while loading shared libraries: libusb-0.1.so.4: cannot open shared object file: No such file or directory

I had the same problem when using the snap package of the Arduino IDE. I solved the problem by installing the Arduino IDE from the official web page: https://www.arduino.cc/en/software
You might have to run the Arduino IDE with sudo or better add a custom udev rule in case you now get following assertion error:

'micronucleus_connect: Assertion `res >= 4' failed.'

Solving the assertion error is further described in following post: https://digistump.com/board/index.php?topic=106.0


Arduino Esp8266 Signal(TIMER0_COMPA_vect) can’t compile Trying to compile a program containing the statement SIGNAL(TIMER0_COMPA_vect) written for arduino. But I want to use it on an esp8266 board. The code will compile  for Arduino uno. But I get an error “expected constructor, destructor, or type conversion before ‘(‘ token when I try to compile for a Wemos D1 board. Can anyone help me convert the statement to pass the compile test. Thank you

That instruction is for setting up an interrupt handler for the timer. It is very much specific to the AVR.
There's a lot more to do that just adjust that one statememt - you have to completely rewrite the whole of the timer code that you're using to operate with the ESP8266 SDK calls.
Without knowing what your code intends to achieve it's impossible to help you further, but this library may be of help to you.


Lolin NodeMCU V3 and 5V sensors I am new to Arduino and electronics so please correct me if I made a mistake.

Many sensors and actuators require 5V. The Lolin NodeMCU V3 has outputs of 3.3V. I want to have them working together.

I have read that the VIN pin outputs the voltage of the USB power source, which is around 5V. I bet that many sensors and actuators can be connected to VIN.

I guess that the main difference with the VCC pin of other boards is the accuracy and stability of the potential.

1) What about the amperage? (I guess that the max amperage of the USB power supply is divided between the board and sensors/actuators connected). How does it compare with the VCC output of, let say, an Arduino UNO?

2) How important is in most practical cases not having exactly 5V? (clearly, I am not considering using the sensors for extremely accurate measurements). I am interested in things like movements/distance/light/accelerometers/humidity etc. sensors and LCD displays, relays, small motors, etc..

I have seen that many sensors have a not so narrow range of working voltages. That makes me think that small oscillations in the USB voltage may not be significant.

3) Is there a better yet simple way to connect 5V devices to this board?

Thank you in advance.

What about the amperage? (I guess that the max amperage of the USB power supply is divided between the board and sensors/actuators connected). How does it compare with the VCC output of, let say, an Arduino UNO?

The 5V pin is connected directly to the 5V of the USB. Whatever your USB port can provide the 5V can provide, minus the current used by the ESP8266.

  How important is in most practical cases not having exactly 5V? (clearly, I am not considering using the sensors for extremely accurate measurements). I am interested in things like movements/distance/light/accelerometers/humidity etc. sensors and LCD displays, relays, small motors, etc..

That all depends on the device. Read the datasheet. Look at the Electrical Characteristics. It will tell you the recommended (and the absolute maximum) voltage range.

  Is there a better yet simple way to connect 5V devices to this board?

Again, it all depends on the devices. Many many devices that are marketed as 5V are in fact "anything from 2.8V to 5.5V" or something like that. Read the datasheets!

The NodeMCU is a tricky board to use with 5V because there is no isolation between the USB power and the 5V pin's power. You can't power the board through the 5V pin and still be able to use the USB port or you risk destroying the USB port or computer that the NodeMCU is plugged into.  If possible you really want to be running as many 3.3V devices as you can, or to keep any external 5V supplies completely separate (except ground, of course) from the 5V of the NodeMCU.


Using a scrolling text in OLED Adafruit_SSD1305 I have been in internet for the past week looking for a way of programming a scrolling text (either left or right) using Adafruit_SSD1305 but I only find scrolling commands for Adafruit_SSD1306. Has anyone tried this before? I really need help on this

The SSD1305 hardware apparently does include scrolling support (SDD1305 datasheet - see section 10) but apparently the Adafruit driver didn't implement it. But The SSD1306 looks so similar to the SSD1305, that if the SSD1306 software driver won't work with it "out of the box" (worth a try!), you could probably compare the two software drivers and back-implement that feature into the the 1305 driver yourself.


How to share a library on Arduino Playground? I have written an ISR-based timer library for Arduino Uno and I would like to share it on the website and get it reviewed.

But I am stuck on how to post it to playground.

The Arduino Playground library list is a wiki page (like everything on the playground). That means anyone can log in to edit it and add links to their own libraries. The "Log In" and "Sign Up" links are at the top right of the Arduino site. When you first go to edit a Playground page you'll be taken to a "Password required" page but don't worry, this is only to prevent spam and the password is pre-filled. You only need to click the "I'm not a robot" checkbox, wait for the green checkmark to appear, then click "Submit".

There are a couple of important things to note though. Firstly, the Playground library list isn't there for getting your work reviewed. It's a place to post things that are functional and ready to be used by other people. If you need someone to help with your project then you can maybe post on the Arduino forums. Alternatively, if you have specific questions, you can post here on Arduino SE.

If you're ready to post your library online, you also have to be aware that the Playground itself won't host your code. You can put a link there and maybe some documentation. However, you'll need to host your code somewhere else, such as Github.


Pointer memory allocation in function I would like to know how Arduino allocate memory for pointers in function arguments.

For instance. I have this code that use 192 bytes (Arduino IDE compiler:
Global variables use 192 bytes (9%) of dynamic memory).

char alph [] = {'a', 'b', 'c','\0'}; // 4 bytes
int numb [] = {1, 2, 3, 4}; // 8 bytes
float flo [] = {1.1, 2.2, 3.3}; // 12 bytes

void fn(){
  Serial.println(alph);
  Serial.println(numb[1]);
  Serial.println(flo[1]);
}

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

void loop(){}

The following code is the same of above, but I'm using pointer to variables in arguments, that use 234 bytes (Arduino IDE compiller: Global variables use 234 bytes (11%) of dynamic memory).

char alph [] = {'a', 'b', 'c','\0'}; // 4 bytes
int numb [] = {1, 2, 3, 4}; // 8 bytes
float flo [] = {1.1, 2.2, 3.3}; // 12 bytes

void fn(char * _alph, int * _numb, float * _flo){
  Serial.println(_alph);
  Serial.println(_numb[1]);
  Serial.println(_flo[1]);
}

void setup()
  Serial.begin(9600);
  fn(alph, numb, flo);
}

void loop(){}

There is a difference of 42 bytes to use three pointers. Why? A char pointer is 1 byte, a int pointer is 2 bytes and a float pointer is 4 byte length. Do the difference must be 7 bytes?

When you ask: "why?". The cheapest answer is: "why not?".

The compiler can do clever optimizations as @Majenko wrote. That is what this is about.

Even for such a small sketch, the compiler has many optimization methods to choose from. Changing a single line or adding a variable can make the compiler to choose other optimizations. It is therefor impossible to link the increased number of bytes to those extra pointers.

Sometimes the compiler can decide to keep a variable in a register instead of storing it in a memory location. Sometimes the compiler understands that a variable has a constant value and is used only once, then the compiler might not even use dynamic ram for it.

The used dynamic ram by the sketch is even more trivial, since Arduino sets the compiler to use the minimal size for the code.

Optimizing a sketch is best done with a large sketch. Your small sketch uses the Serial library, and that is the main part of the compiled code. Your own functions and pointers is just some code on the side.

For beginners, the compiler optimizations can be magical Abracadabra. However, using arrays will prevent the compiler to do extreme optimizations. There might even be a logical explanation for the number of increased bytes if the assembly code is studied as @Gerben wrote.


What is the proper way to make library pin mappings configurable? I am working with some libraries that provide APIs for interacting with specific hardware chips (that makes these drivers?).  However, different custom boards or shields will have the chip mapped to different pins meaning the library needs to be modified for each case.  Needing to modify the library does not work well with the Arduino IDE Library Manager.

Are there preferred/recommended patterns for exposing this configuration so that the library itself does not need to be modified every time?

Here is an example where it is documented which part needs to be changed to match the pin layout of your board.

The method I use is to provide the pins as parameters to the constructor. Those pin numbers are stored in variables to use later in the .begin() function and elsewhere.

Most of the time I use initialization lists to keep things simple. For example:

class Something {
    uint8_t _cs;
    uint8_t _dc;

    Something(uint8_t cs, uint8_t dc) : _cs(cs), _dc(dc) {}
    void begin();
};

void Something::begin() {
    pinMode(_cs, OUTPUT);
    pinMode(_dc, OUTPUT);
}

Something mySomething(10, 8);


Get image from Fingerprint module I want to get the image from the fingerprint module (https://makeradvisor.com/tools/fingerprint-sensor-module/) as a result of scanning. It is enough to have a single frame image. it would be good if the computer can get image the output image from the serial port (as in linescan camera example: https://www.youtube.com/watch?v=welv4w8B88g   https://www.tindie.com/products/ap_tech/tsl1401cl-linescan-camera/)

I am open to your suggestions if it can be done in another module.

Since all of these cheap fingerprint readers are similar you can find a compatible datasheet and just find the commands and descriptions there. However, I couldn't find a datasheet that would include a good description of the protocol. So the other option is to look at the protocot through the software SFGDemo which is apparently capable of getting an image of a fingerprint. Or to use this python package which apparently also can download the image.


Powering a system using batteries I made an arduino nano IR sensor based auto liquid dispenser. Currently it is being powered by a 12V 2 amps adapter. The 12v adapter is connected to a LM2596 DC to DC buck converter which converts the 12V to 5V and powers the arduino, IR sensor and a regular green LED. Also I am using a RO valve solenoid (rated upto 24V DC) which is being powered by the 12V adapter. So whenever the IR sensor is triggered, the DC motor (5V 200mA) and solenoid (12V 300-500mA) are turned on for 3 seconds.

Now, I intend to power this system via batteries. I am considering the following 3 options.

a.) Lithium batteries in series (4 of 3.7V batteries). But again here I believe things would be complex as I have to make a BMS and charger for this. Is anything available off the shelf so that I can directly integrate the battery and charger with my existing system ?

b.) Connect 8 AAA batteries in series to get 12V. But how long would these batteries last for my application ?

c.) Connect 2 9V batteries in series. Again, can you guys please tell me how long these may last in the system.

Arduino nano I believe consumes 20mA and the IR sensor probably around another 10- 20mA.
If it wasnt for the solenoid, I was considering connecting a mobile power bank to power the system.

I think you should go with 3 lithium batteries in series and for proper balance charging of batteries, you can use an off the shell 3s lithium charging circuit like this here.So you will get 4.2*3 = 12.6V on full charge and on full discharge you will get 3.7*3=11.1v out of the battery.

So still I think your pump motor would work on 11v and ther are chances that your solanoid also work on 11v it will just draw more current then usual.


How to send and receive hex or binary numbers via BLE UART? I am trying to send hex or binary numbers through BLE UART, but it is taking only char value which is converted into ASCII value.

I am using Adafruit's Bluefruit micro device and Bluefruit LE apps.

https://github.com/adafruit/Bluefruit_LE_Connect_Android
https://github.com/adafruit/Adafruit_BluefruitLE_nRF51

Serial.print(F("[Recv] "));
Serial.println(ble.buffer);
BluetoothData=ble.buffer[0];
Serial.println(BluetoothData);

In the UART box I want to type only a hex number and receive it in the Ble.buffer of the Arduino only.

ASCII is just a pattern of 0s and 1s, and can therefore be represented in binary, hex, octal, or decimal. The interpretation is entirely up to you in your code.


board stops working when writing serial i just started using Arduino IDE for my XMC1100XMC2Go. Information about the microcontroller can be found here: https://github.com/Infineon/XMC-for-Arduino/wiki/XMC-2Go
I now started with my first codes and want to print things on the serial monitor with this code:
*/
/* For on board LEDs */
#include <LED.h>

/* Create an LED object */
LED Led;

//#define SERIAL_DEBUG 1

int p_LED = 5;
int p_Button = 4;
int i_stateButton = 0;

void setup()
{
  Led.Add(LED1);            // Configure the LEDs
  Led.Add(LED2);
  pinMode(p_LED, OUTPUT);
  pinMode(p_Button, INPUT);

  // Set default state of LEDs
  Led.On(LED2);
  Led.Off(LED1);

  digitalWrite(p_LED, LOW);
  Serial.print("Hello World!");

  Serial.begin(9600);
}

void loop()
{
  Serial.write("Hello World!");
  Serial.println(i_stateButton);
  delay(200);
  Led.Toggle (LED2);
  Led.Toggle(LED1);

  i_stateButton = digitalRead(p_Button);
  //digitalToggle(p_LED);
  digitalWrite(p_LED, i_stateButton);
}

I checked under tools that SerialOutput is set to PC (https://github.com/Infineon/XMC-for-Arduino/blob/master/variants/XMC1100/config/XMC1100_XMC2GO/pins_arduino.h#L54)
There are two Ports, COM1 and COM3. I can send new sketches to the microcontroller using COM3. I checked my Serial Monitor and it is set to COM3, too.
Baudrate is for both the same (code and monitor)
Now that i send the above sketch to the microcontroller it stops working. one LED is on and the other is off. But they do no longer change the state. Nothing appears on the monitor.
When i remove the both lines Serial.write("Hello World!");  Serial.println(i_stateButton); and send the sketch, the LEDs start flashing again.
I'm pretty sure it's a kind of configuration problem, but i cannot find out what it is. Does anyone have an idea?

In the setup(), you have:
Serial.print("Hello World!");
Serial.begin(9600);

One should avoid printing to the serial port before enabling it with
Serial.begin().


Why can't I use an optocoupler to drive an AC circuit using the arduino digital pins? So, when I searched for ways to drive AC circuits from Arduino, everyone suggested relays with a transistor switching circuit to channel an external 5V. I was wondering what would happen if I used an optocoupler like 4n35 to drive an AC circuit. Will the phototransistor inside the chip burn out?

Use it with Triac.  I use MOC3020 + BT138 + 330 and 510 Ohm resistors.
It works good as relay and in dimmer scheme.
Scheme is here
http://cyber-place.ru/attachment.php?attachmentid=1030&d=1370462030


Start/Stop/Reset the melody using buttons I have 2 buttons.  Button 1 will start/stop the melody while the button 2 will reset the melody. My melody is "Happy Birthday".

How am I going to use the buttons to start/stop/reset the melody?

Here's the code:

#include "pitches.h"

int melody[] = {
    NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, NOTE_C4, NOTE_B3,
    NOTE_G3,NOTE_G3, NOTE_A3,NOTE_G3, NOTE_D4, NOTE_C4,
    NOTE_G3, NOTE_G3, NOTE_G4,NOTE_E4,NOTE_C4, NOTE_B3, NOTE_A3,
    NOTE_F4, NOTE_F4, NOTE_E4, NOTE_C4, NOTE_D4, NOTE_C4
};

int noteDurations[] = {
    8,8,4,4,4,2,8,8,4,4,4,2,8,8,4,4,4,4,3,8,8,4,4,4,2
};

boolean needtoPlay;

void setup() {
    pinMode(4, OUTPUT);
    pinMode(2, INPUT); //START/STOP
    pinMode(3, INPUT); //PAUSE
}

void loop() {
    for (int thisNote = 0; thisNote < 26; thisNote++) {
        int noteDuration = 1000 / noteDurations[thisNote];
        tone(4, melody[thisNote], noteDuration);
        int pauseBetweenNotes = noteDuration * 1.60;
        delay(pauseBetweenNotes);
        noTone(4);

        if (needToPlay == true) {
        }
    }
}

Modify your code so notes will play using timer interrupts instead of delay(). Once your program is inside delay(), no button will be responded. Done that, you just have to read buttons either by polling them with digitalRead or using interrupts.


How to control nokia 5110 display using esp-01 I am working on a smart device using esp-01 to pull data from internet and display on Nokia 5110 LCD display, and send back the resistive touch inputs to my server and display those on my lcd I am using an Arduino UNO as a secondary device that talks to esp-01, my display and the resistive touch panel. As the esp-01 has got a system on chip, I can program it and do most of the thing my UNO is doing, but because of lack of ports I am using UNO (as far as i know that's the only limitation.. I dont exactly know how is the analog pins on UNO different from the gpio pins on esp) is there any ways if I can do the whole task using only my esp-01 by eliminating UNO. If its only about the less gpio pins on esp-01, will I be able to eliminate UNO by using higher esp such as esp-07 or esp-12E? if not, could you suggest a best way of bi-directional communication between esp and UNO? (so that esp can sent the display info to uno and based on that info, uno can send the resistive touch inputs to esp)

Yes, you can use a NodeMCU ESP12E board for example as a standalone microcontroller, you actually don't need an Arduino in your case.


How to burn arduino bootloader on SAMD21 chips using J-Link mini I am planning on making my own custom PCB of a SAMD21 board. I would like to ask if anyone has experience uploading arduino bootloader on a J-link Mini although adafruit has a guide on this device, its not uploading a arduino bootloader.

On a related note which pins should I connect it to my SAMD21 chip ?

The Atmel EDBG would work for Arduino Zero since that has the EDBG chip. With Jlink, you can use Atmel Studio. Once the Jlink is connected to the chip via the 10 pin SWD header, goto the programmer option in Atmel Studio, select the chip and programmer and burn your firmware with the selected programmer. You can follow a tutorial here which walks through it.


Understanding the meaning of '[](){ /* Code */ }' in an argument I have this piece of code from a library and im trying to understand the 3rd argument, I've searched google to the best of my abilities and could not find any tutorials or references in in the C/C++ language about it.
timeOutTask.set(NODE_TIMEOUT, TASK_ONCE, [self = this->shared_from_this()]() {
    Log(CONNECTION, "Time out reached\n");
    self->close();
  });

Specificly im trying to undestand this piece of code that utilizes the above mentioned method.
blinkNoNodes.set(BLINK_PERIOD, (mesh.getNodeList().size() + 1) * 2, []() {
  // If on, switch off, else switch on
  if (onFlag)
    onFlag = false;
  else
    onFlag = true;
  blinkNoNodes.delay(BLINK_DURATION);

  if (blinkNoNodes.isLastIteration()) {
    // Finished blinking. Reset task for next run
    // blink number of nodes (including this node) times
    blinkNoNodes.setIterations((mesh.getNodeList().size() + 1) * 2);
    // Calculate delay based on current mesh time and BLINK_PERIOD
    // This results in blinks between nodes being synced
    blinkNoNodes.enableDelayed(BLINK_PERIOD -
        (mesh.getNodeTime() % (BLINK_PERIOD*1000))/1000);
  }
});

My question comes down to what the [](){ /*Code*/ } actually do in an argument of a function?

As KIIV kindly pointed out, it has to do with lambda functions


Is there a color LCD display for an arduino? I currently have a Mega2560 with the LCD4884 Shield. The Shield is good for putting out text and simple pixel images. But I am wondering if there is something that has a full range of colours that would work with the Arduino? The screen size would only have to be a few inches in size.

There are actually several shields that have color screens on them. Many of the shields are just regular mini TFT displays, however there are also touch screen ones.

Here is one from Adafruit that includes a MicroSD holder and a Joystick.

Here is one from Radio Shack that features a 2.8 inch screen with touch capabilities

As far as screen size, many of the screens are only about an 1 inch across, however the biggest I have ever been able to find are 2.8 in.


Find Elapsed Time on Serial Plotter How do I find out the elapsed time from the serial Plotter graph? I am plotting sensor values from the Arduino Nano and would like to know the time scale on the x-axis in order to calculate settling time of oscillations.
I have tried the suggestions here but they do not seem to work in my case.

For example, in the graph below I would like to find out the time it took for the sensors to record their first movement at around point 190.

I am doing the following to print two values:

   //printData1();
   Serial.print(roll_err);
   Serial.print(" ");
   Serial.println(pitch_err);
   Serial.print(" ");

Baud Rate: 9600
Loop Time: 40ms

If my loop time is 40ms then I was thinking that the total time would be 180*40ms. Is this reasoning correct?

Is there a better way to read the time elapsed in the serial plotter?

EDIT: Trying to get a 10ms 'grid'

As per the suggestion in the answer below I have tried running something similar to the following but the loop does not run at a constant time.

I tried to add Serial.print(((millis()/10)%2)*50); but as can be seen, the loop time is not constant.

It depends on how precise you want your time-base to be. The plotter's x-axis is in sample-count, not time, so you have to emit samples at a fixed rate for it to have time-significance.

Your

loop(){
   yadda();
   zadda();
}

may or may not run at a constant rate, depending on what takes place in each iteration of the loop, as well as on your definition of "constant" (I don't believe I just said that...)

Even if none of your code is conditional, binary to ASCII conversion, clock and Serial interrupts, and other low-level code we don't see, may run slightly differently from iteration to iteration; e.g. the number of interrupts during any given iteration may well vary.

If you need to hold a tighter timebase, stalling at the bottom of the loop until millis() reaches (the previous millis() + an interval constant) will at least get you to within a millisecond of a fixed loop-rate. You could, of course, do the same thing with micros(), as long as you know for a fact that the loop can never take longer to execute than 1/frequency you need it to run at, and even then, it should take a fair slop-factor (that's a technical term! :) less than that, "just in case".

Update:

Though I wrote "stalling" at the end of the loop, a better technique is to call every job (in your case, 1 of them - for now ? ) as frequently as possible and let each job decide whether it needs to execute. So in your case:

loop {
  maybeSampleAndPlot();
  // maybeDoSomeOtherThing();  // not implemented yet...
}

maybeSampleAndPlot(){
  time = millis();
  if time - previousSampleTime >= MSEC_040
    save (time + MSEC_040) as nextSampleTime;
    sample the data;
    plot the data;
  endif
}


Temperature sensor and LCD I have a project which uses a DS18B20 temperature sensor and an LCD with an I2C interface on it. I have connected the sensor to my micro-controller (the DS18B20 has a 12-bit digital output) to the ATmega16 PD17, but as I try to print my values on the terminal the sensor output a really high value in decimal. Here is part of the code (and yes everything is working fine, this is a home-made Arduino):

DDRD &= 0x00;
PORTD |=  0x00;
ds18b20_init(&PORTD, 20, 30, DS18B20_12BIT_RES);
int temperature_sensor_output =  (float)ds18b20_temperature(&PORTD);
printf("Temperature: %d  ", temperature_sensor_output);
delay_ms(500);

ds18b20_init is the Dallas function for initializing the module. ds18b20_temperature returns a float value of the temperature

From this code it just prints:

  Temperature: 51603

If I change %d to %f it prints:

  Temperature: without any value

I do not understand where I may have missed some things.

Without more detail about the system, I won't understand what printf() does; in non-embedded systems,  printf() writes to stdout by default, but Arduino systems typically don't use such a device.

That aside, %d is the proper format code for printing an integer value, and %f is proper for a float or double.  If you attempt to print an integer value like temperature_sensor_output under a %f format code, either the compiler will complain or the integer pattern of bits (plus perhaps two additional random bytes) will be interpreted as if it is a float or double pattern of bits.  No type cast occurs within printf().  If you want to use a %f format code, pair it up with a float-type variable.

If, as you say, ds18b20_temperature() returns a float, then the type cast  (float)ds18b20_temperature(&PORTD) will have no effect.  Generally, casts convert data from one form to another, or in some cases declare that data has a given form.  Going from float to float doesn't change anything.

In a C statement like a=b, if b has a type that's different from that of a, the b value will be cast to the type of a.  Thus, the float value on the right hand side of

int temperature_sensor_output =  (float)ds18b20_temperature(&PORTD);

will be converted to an integer value and stored into the integer variable temperature_sensor_output.


Make a PC graphical interface for Arduino - Any easy software? What's the best/easiest software to make a PC-Arduino interface? Ideally, I need to create a .exe that shows up a simple graphic interface, where the user can display data acquired from sensors connected to the Arduino (eg. Voltage, current etc.) and from there he should be able to control Arduino outputs through graphical buttons/switches.

To say that I am not a programmer, so if there's some sort of 'graphical coding' or 'non coding' software to make such things it'd be great!

Thanks for your help!!!

UPDATE:

Image of how the user interface should look like:

The "best" software for me is the free Visual Studio Express for Desktops.

Using C#, I would add a SerialPort component to the form, configure it for the same COM port as the Arduino/FTDI, then send commands to it.

Visual Studio is "stupid simple" (I'm not implying anything :D). Double-click Button in the toolbox(1) and it creates one. Double click the button(2), and it outlines the code and attaches the Click event to it for you. Double click Components>SerialPort(3) to create one. My code is highlighted in blue to the right and this took all of 1 minute to create.

To point you in the right direction on the Arduino side, here is the structure of the "command" I sent in the screenshot:

XXXYYYZZ
Where:
XXX = 000b for "turn off", 001b for "turn on", 010b for "toggle", 011b for "read pin"
YYY = Pin number //Max = 111b = 7 (+ 0) = 8 uniquely addressable pins (using 3 bits)
//Pin number does not have to match the MCU port/pin designations
//MCU will convert logical pin #'s 0-7 into the correct physical port+pin
//For more pins, steal another bit from ZZ; Max for YYYY = 1111b = 15
ZZ = Spare bits //Tell the Arduino whether to acknowledge or not, etc.

00100100b = "Set pin 1 high"
01001000b = "Toggle pin 2"
10000000b + 0xAA (two byte command) = "Reply with contents of register 0xAA"

Additional commands can be created to tell the Arduino to reply with a specific variable or status.

bool isRegisterRead = false;
bool isMultiByte = false;
while (true)
 if (wasByteReceived) //This flag is set in the RX interrupt and the byte is saved to byteReceived
  if (isMultiByte) //Second byte received
  {
    if (isRegisterRead)
    {
      //We need to read and send the value of the register at the address in byteReceived
      ReadAndSendRegisterValueAtAddress(byteReceived);
      isRegisterRead = false;
    }
    else DoSomethingWith(byteReceived);
    isMultiByte = false; //Start over
  }
  else //First or only byte received
  {
    //Consider using a ZZ bit to indicate more data instead of listing them explicitly
    if (byteReceived == 0x80) //A multi-byte "read register" command
    {
      isMultiByte = true; //Next byte received is money
      //For my example we need to set a flag somewhere to indicate that we are reading a register
      //isRegisterRead should be set to true by DoSomethingWith
    }
    //Is there any processing for the "command" byte? (i.e. extract and save the pin number)
    DoSomethingWith(byteReceived); //Process one-byte command or first of two-byte command
  }


Are there any GPS data pusher for Arduino? I plan to build a GPS logger for my car using a GPS device, an Arduino board and a SD Card. The plan is that the GPS device forwards the position to the Arduino which is responsible for storing the data on the SD card. However, I would like to regularly (say every hour) send my current position to a server at home.

For that you can use GPS pusher or puller, but I couldn't find any such devices on the Internet. Do these devices exist? What are my (other) options?

Check this shield out, it sounds almost exactly like what you need, plus it has OBD2 (CAN) access to log RPM, indicated speed, steering wheel angle, and whatever else your car exposes. You can get a GPS module from Sparkfun as well. Matter of fact, I'm using it in a very similar project, but development is paused until I upgrade to a Mega, since I've run out of RAM.

The shield comes with example code that's hacked together from other sources but it serves the demo purpose well.

As for pushing to a server--that'd be tougher. I would go the route of a Bluetooth shield and make a corresponding app for the phone that pushes the data.


How to burn bootloader/program an ATMega 328P with an external crystal 8 MHz oscilator? I need to program a ATMega328P on a breadboard, running on an external crystal at 8 MHz.

All of the guides I can find either use the arduino environment and describe a 16 MHz config, or using the 8 MHz internal oscillator - which is too inaccurate for this project.

How do I do this?  Configure the chip to run at 8 MHz and upload the program?

myself as of 3 hours ago.

Get an arduino or similar, install the ArduinoISP sketch
Connect the two as described here.
Change the board to Arduino Pro or Pro Mini, Processor to 3.3V, 8Mhz, Programmer: Arduino as ISP
Hit burn bootloader button
Load up the sketch that you want on the device
Without changing anything, use "Upload using programmer"
Remove arduino, fix wiring changes required to use as programmer

Committed to Electronics Stackexchange  for posterity.  Or so I can find it when I forget next time...


Problems with Serial.read() void loop()
{
  if (sensor.begin() == true)
  {
    Serial.print("Current Conversion Mode: ");
    Serial.println(sensor.getConversionMode());
    Serial.println("Enter your mode of Conversion (number 0 - 3): ");
    while (Serial.available() == 0); // Waits for the user input
    mode = Serial.read(); // Reads the input string from serial port
    Serial.print("Number recieved: ");
    Serial.println(mode);
    delay(500);
    if (mode == '0' | mode == '1' | mode == '2' | mode == '3')
    {
      sensor.setConversionMode(mode);
      Serial.println();
      delay(500);
    }
    else
    {
      Serial.println("Conversion mode unsuccessfully set - Please enter a number 0 - 3");
    }
    delay(1000);
  }
  else // Runs when the device was unable to setup properly
  {
    Serial.println("Device failed to setup");
  }
}

I'm currently using the SparkFun red board to run this code on. I have been trying to get this to read from the serial monitor to take an input to send to the library I wrote to change the value of the conversion mode register of a temperature sensor. When I run the code, I can only have it run once correctly, then it jumps directly to the else statement for the inputs, saying that 0-3 was not an input. I tried the other methods that people have suggested  from this website and the Arduino forums but none of them have worked for me yet. I'm not sure if adding more delays would help - that was one of the most common suggestion I found for this specific issue and it wasn't that consistent. Please help! Thanks.

Using a slightly modified version of your sketch, I receive the following output in the serial monitor when I enter the number 2.

  Current Conversion Mode: Enter your mode of Conversion (number 0 - 3):
  Number recieved: 2

  Current Conversion Mode: Enter your mode of Conversion (number 0 - 3):
  Number recieved:

  Conversion mode unsuccessfully set - Please enter a number 0 - 3
  Current Conversion Mode: Enter your mode of Conversion (number 0 - 3):
  Number recieved:

  Conversion mode unsuccessfully set - Please enter a number 0 - 3
  Current Conversion Mode: Enter your mode of Conversion (number 0 - 3):

If you change mode to an int then retest, you'll see the second and third "Number recieved" are 10 and 13. That would be the New Line and Carriage Return characters. When you send data via the serial monitor, do you have "No Line Ending" selected or something else?

Here is a test sketch:

char mode;

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

void loop()
{
  if (true)
  {
    Serial.print("Current Conversion Mode: ");
    //Serial.println(sensor.getConversionMode());
    Serial.println("Enter your mode of Conversion (number 0 - 3): ");
    while (Serial.available() == 0); // Waits for the user input
    mode = Serial.read(); // Reads the input string from serial port
    Serial.print("Number recieved: ");
    Serial.println(mode);
    delay(500);
    if (mode == '0' | mode == '1' | mode == '2' | mode == '3')
    {
      //sensor.setConversionMode(mode);
      Serial.println();
      delay(500);
    }
    else
    {
      Serial.println("Conversion mode unsuccessfully set - Please enter a number 0 - 3");
    }
    delay(1000);
  }
  else // Runs when the device was unable to setup properly
  {
    Serial.println("Device failed to setup");
  }
}


Need Help in circuit diagram of 8*8 reed switch matrix I am designing 8*8 reed switch matrix which will be connected to Arduino. I am using Arduino Duemilanove. I have completed the matrix portion but don't know how to connect and where to connect the other elements.

I decided to use the following items:

Arduino (Duemilanove)
64x Reed Switch
64x Diode (1N4148)
20x Resistors (10K)
1x 74HC595
1x 74HC165

I don't know where to place the Resistors and shift Registers and connection from shift registers to arduino. I need help in the circuit diagram. Please help me out with the circuit diagram.

Reference: https://mtifall10.wordpress.com/2010/12/10/magnetic-sensing-chessboard/

This answer is based on a previous version of the question

Not necessarily. You can use the internal pullups of the arduino if you're willing to accept that reading a "1" means that no piece is there and reading a "0" means a piece is there.
Connect each wire up to a pin on the arduino. If you do it wisely, step 3 becomes fairly easy.
You need to configure the pins connected to the letter wires as inputs with their pullups enabled. Set the number pins to inputs as well, but without the pullup enabled so that they are floating. The number pins will be each set as an output in sequence with the value being low (non-active number pins are set back to inputs). As you do so, you can read the pins on the letter wires and build a picture of the board.

Example

This is how I would do it just taking a naive stab at it. I'm sure there are more effective ways to do this.

Wiring:

Configure the outputs and inputs in setup:

pinMode(2, INPUT_PULLUP);
pinMode(3, INPUT_PULLUP);
pinMode(4, INPUT_PULLUP);
pinMode(5, INPUT_PULLUP);
pinMode(6, INPUT_PULLUP);
pinMode(7, INPUT_PULLUP);
pinMode(8, INPUT_PULLUP);
pinMode(9, INPUT_PULLUP);
pinMode(10, INPUT);
pinMode(11, INPUT);
pinMode(12, INPUT);
pinMode(13, INPUT);
pinMode(14, INPUT); //A0
pinMode(15, INPUT); //A1
pinMode(16, INPUT); //A2
pinMode(17, INPUT); //A3
pinMode(18, INPUT); //A4

Make a function to scan the rows into an array of bytes:

void scan_rows(uint8_t *rows)
{
    uint8_t i, j;

    for (i = 0; i < 8; i++)
    {
        if (i)
        {
            pinMode(i+9, INPUT);
        }
        pinMode(i+10, OUTPUT);
        digitalWrite(i+10, LOW);
        for (j = 2; j <= 9; j++)
        {
            rows[i] <<= 1;
            if (digitalRead(j))
                rows[i] |= 1;
        }
    }
    pinMode(18, INPUT);
}

Now, just call that function with a pointer to an array with 8 bytes in it whenever you need to scan the board. Each byte in the array represents one of the rows and each bit represents a column.

[moderator note: This answer appears in this thread as a result of a merge]


Problems with Ultrasonic Sensor I want to check my understanding on how to use digitalWrite for 5V and Grd and why this code isn't working.
This is for the Makeblock sensor
Consider the image here which says to plugin a wire to 5V, Grd and a signal pin.
My code does the following
#define h  22
#define l  24
#define sig 26

void setup() {
   Serial.begin(9600);
   pinModde(h, OUTPUT);
   pindMode(l, OUPUT);
   pinMode(sig, OUPUT);

   digitalWrite(h, HIGH);
   digitalWrite(l, LOW);
}

void loop() {
   digitalWrite(sig, LOW);
   delayMicroseconds(2);
   digitalWrite(sig, HIGH);
   delayMicroseconds(10);
   digitalWrite(sig, LOW);
   pinMode(sig, INPUT);
   long duration = pulseIn(sig, HIGH, 38000);
   delay(2500);
}

When I run this code duration is always 0.  If I unplug 22 and 24 and use the board's 5V and Grd I get duration is 30001 no matter how far away an object is from the sensor.  Meaning it's not sensing anything, just returning this number.
Full disclosure that I'm using solder-less wires but I don't that would make this much of a difference?
So to summarize: why are 22 and 24 resulting in a 0 readout and not acting as 5V and Grd?  My only thought is maybe too much voltage and a resister is needed?
Secondly: why is the sensor not working even when using 5V and Grd pins?

You've set pinMode(sig,INPUT); and never changed this back to OUTPUT before triggering next measure:

void loop() {
   pinMode(sig, OUTPUT);    // ensure sig is configured as an output
   digitalWrite(sig, LOW);
   delayMicroseconds(2);
   digitalWrite(sig, HIGH);
   delayMicroseconds(10);
   digitalWrite(sig, LOW);
   pinMode(sig, INPUT);
   long duration = pulseIn(sig, HIGH, 38000);
   delay(2500);
}

And for example PING))) (which is basically the same module) has power consumption about 30mA-35mA in datasheet. Output pin might be strong enough to power it, but I'd recommend at least GND connect directly to arduino GND. And using transistor for powering it up would be even better


Breaking up for loop with ISR I am curious if the following scenario is possible.

EICRB |= (0<<ISC60)|(0<<ISC61);
EIMSK |= (1<<INT6);

ISR(INT6_vect) {
  myISR();
}

void myISR() {
     digitalWrite(led_off, OFF);
     // Please break my main for loop :)
}

void loop()
{
      for (i=100; i>=0; i--)
             {

            /* STOP button */
              if (read_switch() == 1) {
                      break;
               }
           .. delays and other logic ...
}

As you see the following code is not complete but quite understandable. I have a heating process done in the main program, each loop temp adjustments, printing, delay etc takes about 2-3 seconds to complete. When somebody pushes a switch read_switch will return 1 and that breaks up this function ending the heating process.
This works just fine except the user have to hold the button for the time it finishes looping and get to this point again.
I have fortunately realized that the switch pin (Arduino promicro pin7) also an interrupt pin so I could do interrupt in real time, as I doing it in other code already.

However what you can do in this ISR routine is limited (eg you cannot print to serial etc). I could setup a global volatile bool variable here of course which would immediately get flipped as the interrupt triggered but it would not solve anything since in the main loop I would have to wait for the next round again.

So is it possible with some hack to tell the ISR to break that for loop (not the whole program with an exit(0)) and continue execution afterwards?

No, it's not possible, nor desirable. It's complicated and unnecessary.

What you have to do is:

Declare a volatile global variable (a switch).
Inside ISR, change that switch to signal that a break is needed.
Inside your loop (for, while, ...) test for that global variable and proceed.

This example print "This is the end" each time a button connected to pin 2 is pressed.

volatile bool fin = false; // The switch for ISR-loop communication.

void setup()
{
    Serial.begin(9600);
    pinMode(2, INPUT);  // Read a button or other signal.
    attachInterrupt(0, buttonISR, RISING);
}

void loop()
{
    if(fin) {
        Serial.println("This is the end");
        fin = false; // Reset the switch.
    }
}

void buttonISR()
{
    fin = true;  // Just raise the signal for the main loop.
}

This method keeps ISR ultra-short and there is no mixing between ISR's instructions and loop's instructions. All of your logic reside in the main loop.


Will a genuine Arduino board have the same issues with High Sierra as other non genuine ones? I think my question is quite specific to High Sierra. I am very new and have bought a starter Elegoo kit to learn the basics. I did not realise that their boards are not the real thing.

I have an iMac running High Sierra and although the Mac recognises the board (I checked this through the apple menu) every time i try to upload code i get the error message:

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

I have watched several videos on line that have taken me through installing drivers including one specific to High Sierra. However the problem continues.

Does anyone know if i buy a genuine Arduino board, will i have the issues? Will Arduino just not work with High Sierra.

Any help or advice would be so appreciated by someone very new and trying to learn!

Thank you

Paddy

As long as the firmware on the ATMega16U2 chip is the same as on a Genuine Arduino and the bootloader on the ATMega2560 chip is the same as on a Genuine Arduino then your boards should function exactly the same as a Genuine Arduino.

If you find a Genuine Arduino works but your boards don't then there must be a difference, and that can really only be in the software on the chips - so reprogramming the chips to match a Genuine Arduino would probably help.

I haven't heard reports of High Sierra not working with Genuine Arduino boards, but given the severity of some of the bugs that have crept in recently, it seems likely that more problems are hidden away under the hood that no one really knows about yet.


How to connect mini jack output to arduino mini pro and send sound to it? I would like to connect arduino mini pro to mini jack output and send sound through it.

What would I need here, how can I connect the mini jack to arduino and how to send data of sounds (any library?) to that connected output?

EDIT

The sound source will be a music file ( streamed via bluetooth). I would like to be able to connect this output to a speaker and play (stream) music via bluetooth.

EDIT

Either mono or stereo will be good for me. My plan is to: stream the music via bluetooth to bluetooth module (for now I think about HC-06), send that data stream through arduino mini pro to the output mini jack.

Do I need in that case some kind of mp3/other format decoder module like VS1003B on ebay ?

The Arduino Uno / Mini Pro is not really the right tool for the job. It has no native audio output such as a 3.5mm jack.

Having said that I am sure it can be done - but it won't be the best quality sound. I have no doubt that it can be achieved with one of the following methods:

using the tone() function.
by using a R-2R resistor ladder network and some sort of amplification circuit.

The Arduino Due and the Arduino M0 / M0 Pro both have inbuilt DAC's, meaning that they can output analog signals which can be used to drive a speaker circuit.

Another option is to use a Raspberry Pi which has a native 3.5mm audio jack.


How to protect my arduino, while hotplugging its power supply and other related electronics The unsolved: when I connect power and signal lines to my Arduino - while power is on - I potentially kill it. I have fried 2 so far.

Situation:

I have build an DMX-controlled lighting fixture, which consists of the fixture and a Controller Box.
The fixture houses 2 Arduino's (5V), 2 steppers, 2 drives (36V), 2 fans (24V) and some temperature sensors.
The controller box houses 1 Arduino, amongst other electronics.

The controller box receives DMX and does calculations an send controls via I2C to the fixture.

There is a 8 pole connector between fixture and controller box.

1 - GND
2 - 5v
3 - 24v
4 - 36v
5 - CLK (i2c)
6 - SDA (i2c)
7 - signal line (used as charge pump)
8 - reset

All wires are shielded(but the shield is only connected AFTER the initial pins make contact)

When the power on the controller box is ON and i connect the light Fixture with the 8-pole connector my arduino goes to heaven.

My own idea's so far:

Voltage spike, because the connection wires is grounded after it connects the pins.
Some strange flyback? via the Arduinos in the light fixture? I connected everything straight to the 5v pins, not using the regulator.
no idea

Any help on a way to search for the most likely cause of the problem would be greatly appreciated.

There's usually a number of scenarios that can cause hardware to go poof when you plug it in to a live system.  Most of them you have managed to identify, so I won't go into detail here.

Suffice it to say that creating hot-pluggable devices isn't as straight forward as you would at first guess.

There are two main critical things to consider when designing your system:

Suppression

Invest in TVS diodes to suppress ESD.  All the IO pins that connect to the outside world that will be liable to be disconnected or connected at any time should be protected by adequate suppression.  Any inputs should also ideally be tied to a default state with pullup or pulldown resistors so they aren't left floating.

Connector

The connector itself is pretty critical.  Hot-plug connectors typically have different pins of different lengths so that they connect in a specific pre-determined order.  Normally you want your ground and shield to connect first.  Then your power supplies, and finally your IO pins.  Doing it in any other order is asking for trouble - such things as back-powering through the IO pins if the supply hasn't been connected.

If you can't use a proper hot-plug connector then there are ways you can simulate it internally.  You can add hardware (buffers, reed relays, FETs, whatever, depending on your signals) which normally isolate the signals from the MCU, and only when the MCU is powered up and ready does it then activate the buffers to allow the signals through.  Of course, the buffers themselves have to be able to withstand any possible back-powering etc while the plug is being inserted.

One other small trick is to ensure that all your IO lines have a series resistor in them.  This limits the maximum current that can ever go in or out of a pin (at a specific voltage of course) to a level that is safe for the hardware.  470Ω - 1KΩ are good values.


How to write to the second line of a display? I got this 4 line display from Mouser: https://www.gravitech.us/20chbllcd.html, and I get it to work fine for lines 1 and 3 (as line 3 is just the 21st character of line 1). But I am struggling to get lines 2 and 4 working. If I understand correctly, these are "line 2" for the HD44780 controller, and I should set the DDRAM address to 0x40 before I write there.

But, when I try that, nothing happens.

I tried writing 0x04 to the DDRAM address counter, and I can see the cursor jumping there, but when I write to that address, no text shows up. If I omit the command, text pops up correctly.

Also, when changing the contrast of the display (using the potentiometer on the Vdd and Vo pins), only lines 1 and 3 change contrast.

My code:

This method I use for convenience:

void set(int _rs, int _rw, int _d7, int _d6, int _d5, int _d4, int _d3, int _d2, int _d1, int _d0) { ... }

To set the DDRAM address to 0x40:

set(0,0,1,1,0,0,0,0,0,0);

The general timing and control is correct, as I can get text on the display, and also a function like "shift" works fine.

Line 1 starts at address 0x00 | 0x80 0b10000000 and ends at 0x13 | 0x80 0b10010011
Line 2 starts at address 0x40 | 0x80 0b11000000 and ends at 0x53 | 0x80 0b11010011
Line 3 starts at address 0x14 | 0x80 0b10010100 and ends at 0x27 | 0x80 0b10100111
Line 4 starts at address 0x54 | 0x80 0b11010100 and ends at 0x67 | 0x80 0b11100111

That 0x80 0b10000000  is the HD44780 command for set DDRAM address. The other bits 0b1xxxxxx define the address.

You'll find more details at Arduino with HD44780 based Character LCDs


Common button on two Arduinos and two computers We have two computers giving two presentations that need to    be triggered in sync. I know how to send the space button via Arduino, but I want to check it will be safe for the computers. If each Arduino is connected to their computer via USB, both data pins togeather and both grounds togeather (not sure if I can find a dt momentarily push button in two days). Is there anything I should keep in mind incase both sides are not at the same voltage as eachother?

The ground of both computers are connected also via their power lines. You get a ground loop that might result in malfunctions and/or defects.

Think about using a galvanically separated connection, for example via an optocouple.


User callback functions I want to write a class that allows the user to attach his own function to a member function that listens for messages coming from a wireless module, so that the user's function can be called depending on the message.

I am thinking about using function pointers but I don't know how it will work since I don't know the user's function parameters, return type and number of functions that will be added.

//sketch.ino

<unknown> (*funcPtr)(<unknown>)[<unknown>];

void receive() {
  message.type = 'o';
  if (message.available()) {
    message.receive();
  }
  switch (message.type) {
    case 'p': {
      Serial.println(p);
      break;
    }
    case 'f': {
      funcPtr[message.funcID](message.parameter1, message.parameter2);
      break;
    }
    default: break;
}

void userFunction1() {
  Serial.println("User function 1");
}

int userFunction2(int x) {
  return x * 2;
}

funcPtr[0] = &userFunction1;
funcPtr[1] = &userFunction2;

void setup() {}

void loop() {
  receive();
}

Is this kind of thing possible?

I don't know the user's function parameters,

A common way for dealing with this issue is to pass a generic pointer to
arbitrary data. See below.

  return type

It makes little sense to allow for arbitrary return types, as your
library would have no way of knowing what to do with the returned value.

  and number of functions that will be added.

Either you allocate the callback array statically with a fixed size, or
you use dynamic allocation. In the first case, the array size could be
decided by the user if it is a template parameter. In the second case,
you risk memory fragmentation unless all the callbacks are registered
once and for all at program startup, which is a common scenario anyway.

About the generic pointer technique

This is a very common way of defining callbacks in C: a callback
contains both a function and a void * pointer to arbitrary data, which
will be given as a parameter to the function. It is up to the user to
decide if and how he will use this pointer: he could completely ignore
it, like he could make it point to the root of a complex data tree.

Here is a simple example:

// A callback contains both a function and a pointer to arbitrary data
// that will be passed as argument to the function.
struct Callback {
    Callback(void (*f)(void *) = 0, void *d = 0)
        : function(f), data(d) {}
    void (*function)(void *);
    void *data;
};

Callback callbacks[3];

// This callback expects an int.
void print_int(void *data)
{
    int parameter = * (int *) data;
    Serial.println(parameter);
}

// This one expects a C string.
void print_string(void *data)
{
    char * parameter = (char *) data;
    Serial.println(parameter);
}

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

    // Register callbacks.
    static int seventeen = 17;
    static int forty_two = 42;
    static char hello[] = "Hello, World!";
    callbacks[0] = Callback(print_int, &seventeen);
    callbacks[1] = Callback(print_int, &forty_two);
    callbacks[2] = Callback(print_string, hello);
}

void loop()
{
    // Test all the callbacks.
    for (size_t i = 0; i < 3; i++)
        callbacks[i].function(callbacks[i].data);
    delay(500);
}

Notice that the two callback functions take different types of
parameters, only disguised into the same generic pointer. Notice also
that print_int is used in two different callbacks with different data.
In this example, the data does not change, but this need not be the
case: both the callbacks and the rest of the user code could change the
data pointed to by the generic pointers. Again, it is up to the user to
decide how he will use this facility to communicate between his
callbacks and the rest of his code.


Get more PCINT capable pins on Mega 2560 I'm building kinda "ball game" for a total of 6 players based on these per-player specs:

1 stepper motor with 4 pins
2 end stops (start & finish) per motor
1 finish LED
3 holes to score, resulting in slow, medium or fast motor movement

Additionally, there's a "master reset" to move all motors back to their starting end stops.
Because of my initial assumption, 54 pins would be enough, I didn't realize actually requiring 60 pins (24 for motors, 12 for end stops, 6 for LED, 18 for holes). I'm also neither an expert at microelectronics nor C programming language, but my understanding of the Mega's pins is that I need 12 + 18 PCINT capable pins (end stops + holes) while only 16 pins are available.
So far, the only information I could find suggests buying an Arduino Shield to resolve this by providing additional 16 PCINT pins. But being connected via I2C, I suspect delays resulting in unequal treatment of player scores.
How to get at least 30 PCINT capable pins, treated equally by Arduino? In case there's no need for the PCINT requirement, which pins can be used as an alternative?

The Atmega2560 has a total of 24 pins associated to the PinChange interrupt. You cannot change that. It is an internal property of the microcontroller.
As you already have seen yourself, you need to use extra chips to extent the available IO pins. There are different options to consider:

IO-Port-Expanders (available for I2C or SPI) (for example the PCF8574. Don't know, if that is the best, just the port expander, that I also used myself)
Shift-In (for inputs) or Shift-Out (for outputs) registers (often used are the 74HC595 (Shift-out register) and the 75HC165 (Shift-In register). I often used this tutorial as reference)

As you don't want to poll these chips all the time, I suggest, that you use one, which provides an additional interrupt pin. That pin will change its value, when one of the input changes. You could then connect this pin to one of the interrupt pins of the Atmega2560. When the interrupt triggers, you can read the states of the input pins.

But being connected via I2C, I suspect delays resulting in unequal treatment of player scores.

Indeed that wouldn't be good. So you should divide the pins up by their purpose, not by their association to a player. For example all end stop inputs, or all outputs for the stepper motors. Then you need to access, what timing requirements each group has. Then you can take the group with the lowest requirements and check, if and which chip would be able to handle the data fast enough. For example the "finish LED". You didn't specify, what exactly it does, but I guess, that it is not really time critical. So you could handle all finish LEDs via a single shift-out register.
Or take the inputs for the holes: I guess here you have some sensor, that triggers, when a ball passes it. Check how long the sensor get's triggered. Most likely (depending on the type of sensor) this depends on the speed of the ball. Take a speed, that you want to consider maximum (for example the pitching speed of a good baseball player, as these are really high), and calculate, how long the resulting pulse will be. The chip, that you choose, might be fast enough for this. So you could handle all ball hole inputs over extra chips (meaning chips providing extra input chips, like a Shift-In register or a port expander).

In case there's no need for the PCINT requirement, which pins can be used as an alternative?

Every pin capable of digital IO. That's nearly every pin on the Arduino Mega. Though that means, that you cannot use interrupts for them and you have to poll then constantly. That might be ok for you. It really depends on your exact timing requirements.

I thought polling was a "avoid where possible"-area?!

Yes and no. First you asked for the possibility of using other pins, so I mentioned that above. Though doing that means using no PinChange interrupt. Generally polling is bad, when

you spend too much time on it, leaving no time for other functions of the code, or
if the events, that you are polling, are too short for your polling code.

That can happen in the cases, that

you use blocking code to poll (like waiting with a while loop for a button press), which blocks all other functions from executing.
your code needs a long enough event to register it (for example the signal from your hole sensors might be very short. If your polling interval is bigger than that, you will loose some events)

If you stay inside of the confinements and use non-blocking code, there is nothing bad with polling.
Let's take the often used Bounce2 library for Arduino. It helps you with reading buttons and handles the debouncing for you. It does not use any interrupts. You are expected to call Bounce.update() often enough to catch all button presses, which is typically a few ms at max. But since the Arduino Mega runs on 16MHz, it is capable of way faster speeds than the few ms. Calling Bounce.update() often enough is easy, when you don't write code, that stays a long time to execute. So no delays, except for maybe very short ones. Instead you can use the coding style of the BlinkWithoutDelay example, that comes with the Arduino IDE. It uses the millis() function as a time base to check repeatedly, if it is time to do something, and only do so, if it really is time for it. Much like you are baking a pizza by putting it into the oven and then regularly watch at your clock, if it is time to get the pizza out of the oven. You don't want to sit in front of the oven waiting for pizza. The analog of doing that is writing blocking code with delay().
So all in all about polling vs interrupts: It depends on your requirements. Fast response times or short events often need interrupts, though you need to cope with limited usable pin numbers and different interrupts (which is a bit more complex to code). Polling - when done right - can give you big freedom and rather easy handling, while saving interrupt sources for more important functions. Though it poses bigger limits on response times and the duration of events. Also it depends strictly on the rest of your code.

Note, that in the above, terms like "time critical", "fast response times" and such are more meant for the region of a low number of microseconds. Timings in the millisecond range can easily be done by using the mentioned non-blocking coding style (either with millis(), or for greater resolution and accuracy at low numbers of milliseconds micros()). The principle is always the same and there are tons of tutorials about it on the web and even many questions and answers on this site. So you can google for this, to get a more detailed tutorial.


Arduino does not make any sound when connected to laptop? When I connect my Arduino through USB to my laptop, it does not make any sound like something is connected but green light is on. And port option in the Arduino IDE remains grayed out. I might have burned my Arduino, maybe? Please help.

The Arduino will not make a sound, but probably you refer to the sound Windows makes when a USB device is connected?

Try (except for the tips already given by JRobert)

different USB port
reinstall Arduino IDE
disable/enable or reinstall driver in Control panel/hardware/system/USB devices


Why is the stack pointer out of range? I have a function that dumps the contents of the arduino's ram, and it works, but I still dont understand why it says my stack pointer is at 0x08C9 If the ram of the arduino is 2kb, or 2048 bytes, shouldent the max addressable size be 0x0800?

RAM: SP->0x08C9 HP->0x0371 FREE:1368

And the code:

void printAddress(uint16_t val)
{
  Serial.print(F("0x"));
  if(val < 16)
{
 Serial.print(F("0"));
}
if(val < 256)
 {
  Serial.print(F("0"));
}
if(val < 4096)
{
  Serial.print(F("0"));
}
Serial.print(val,HEX);
}

void setup(){
Serial.begin(115200);
//0x0800 2048
uint8_t *heapptr, *stackptr;
stackptr = (uint8_t *)malloc(4);        // use stackptr temporarily
heapptr = stackptr;                     // save value of heap pointer
free(stackptr);                         // free up the memory again (sets stackptr to 0)
stackptr =  (uint8_t *)(SP);            // save value of stack pointer

Serial.print(F("RAM: SP->"));
printAddress(stackptr);
Serial.print(F(" HP->"));
printAddress(heapptr);//(int)&__heap_start);
Serial.print(F(" FREE:"));
Serial.print(stackptr - heapptr);
Serial.println();
}

As a note, Comments are not mine.

Sure... if the RAM started at address 0, which it doesn't.

According to the datasheet the RAM starts at address 0x0100, below which are all the SFRs:


Collection of functions for arduino IDE I am having troubles creating a collection of functions to be used in Arduino sketches and libraries. What I want is not a class, but simply a group of functions which do not require an object to be called; general utilities that can be helpful in any Arduino sketch, like an average of analog reads, or a little statistical tool.

Suppose I write a file called Utilities.h    (I am not sure .h is the right extension to use in this case):

Utilities.h

#ifndef Utilities_h
#define Utilities_h
#include <Arduino.h>

void utility1(...){
...
}

float utility2(...){
...
}

//and so on

#endif

I then save this file in ../Arduino/libraries/Utilities. Whenever I want to use my utilities from this file directly in a sketch I type #includethe full path to the file (#include <Utilities.h>  won't work).

The real problem is if I want to use this collection of functions in a library, like in the following example.

myClass.h

#ifndef myClass_h
#define myClass_h
#include "full path to Utilities.h"

class myClass{
 private:
  int a;
 public:
  myClass();
};

#endif

myClass.cpp

#include "myClass.h"

myClass::myClass(){
 a = utility2(...);
}

Whenever I try to #include <myClass.h>  in my sketches and compile, I get 'multiple definition' error messages for the functions on my  Utilities.h.

So to summarize, my question is: how can I create a collection of functions that can be used both in a sketch and in a library for Arduino?

You need to "split" your library.

Placing full functions inside a header file (.h) is bad form and causes the exact problem you are seeing. Every time you include the header file you create an entirely new copy of the function. This can only work if the functions are static, which means that they exist, and are contained entirely within, the function in which the header is included in. All outside access to them is completely cut off and they become "local" to the file. That means you can have multiple copies of them in one program. However that is wasteful of space since you are duplicating your code.

Instead you need to have the code itself in a .cpp file, which gets compiled separately and then linked with your sketch at the end of compilation, and just pointers to the functions you have written in your .h file.

Utilities.h:

extern void myFunction();

Utilities.cpp:

void myFunction() {
    blah blah
}

The .h file just contains a prototype for the functions which tells the compiler that "This function is defined elsewhere. Find it later on when you link."

It's only the .h file that is included in libraries and sketches, etc, so only the prototype that is duplicated between files. The .cpp is compiled separately and thus only compiled the once, so you don't get the code duplicated.

One caveat with this is that your sketch must include the library you have written so that the IDE knows to look for .cpp files within it to compile. And you must use #include <Utilities.h> for it to be able to work that out. Using a full path rather than just <Utilities.h> means that you break all portability and the IDE may not know to look for .cpp files in there, or even where to actually find it when compiling.  Note as well that the IDE needs to be restarted after creating a new library, which is why it may not be able to find it in your experiments.


Auto detecting Baud Rate of Arduino I'm trying to detect baud rate of Arduino Mega2560 by using C#. My code is below:

SerialPort SP=new SerialPort();
SP.BaudRate = 115200;

BaudRate is specified as a constant like this, but I would like to automatically detect it.

For instance, if Arduino code includes Serial.begin(xxxx), program should declare SP.BaudRate = xxxx.

How can I do it?

I'm not a C# programmer but this StackOverflow answer might be what you're looking for.


Switch Case Return , Return not printing I am trying to get the value of a key pressed and set it to return a value to use in a loop.  In the code below the Print(t) does not show anything

#include <Keypad.h>

const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char hexaKeys[ROWS][COLS] = {
    {'1', '2', '3', 'A'},
    {'4', '5', '6', 'B'},
    {'7', '8', '9', 'C'},
    {'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {9, 8, 7, 6};
byte colPins[ROWS] = {5, 4, 3, 2};
Keypad customKeypad = Keypad(makeKeymap(hexaKeys),rowPins,colPins,ROWS,COLS;

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

void loop()
{
    int t;
    switch (customKeypad.getKey())
    {
    case 'A':
        t = 8;
        break;
    case '2':
        t = 9;
        break;
    }
    return t;
    Serial.print(t);
}

You misunderstand the use of return.  The loop function is declared void.  That means it doesn't return anything.  If you simply remove that return statement completely then your code will do what you want.

The return stops the loop.  It throws away the value since the loop is defined as returning void, and code execution never reaches the print statement.  Writing anything in a function after a return statement is useless.


Arduino UNO doesn't produce expected square waveform I want to produce quick square waveform for testing purposes. If I will use this code:

void setup()
{
 pinMode(2, OUTPUT);
}

void loop()
{
 bitSet(PORTD, 2);
 bitClear(PORTD, 2);
}

I will get expected pulses but I also will get these 6.25 us dips in waveform roughly every 1 ms.

I use latest Arduino 1.6.9 environment.

Whole loop cycle take 1 us which mean 16 instructions (62.5 ns per instruction). So I will get 125 ns high and rest of the time low signal.

Any idea what I'm doing wrong?

Same results if I use asm sbi and sci instead of macros bitSet/bitClear.

Thank you!

/*

So after yours advices and little bit further searching I came up with solution to produce clean square waveform. It make 2.66 Mhz and it's probably fastest what you can get:

void setup()
{
 pinMode(2, OUTPUT);
 noInterrupts();
}

void loop()
{
 while(true)
 {
 bitSet(PORTD, 2);
 bitClear(PORTD, 2);
 }
}

As I explained in my comment, the reason for this glitch is the Timer 0
overflow interrupt kicking in every 1024 µs. This interrupt is used
by the Arduino core library for timekeeping. It is the basis of
millis(), micros() and delay(). The interrupt is enabled by the
init() function in
wiring.c.
There are several approaches to avoid that:

Avoid the Arduino core initialization

This may be overkill, but since it seems you are already familiar with
directly accessing the IO ports of the ATmega chip, it may well suit
you. You can use the Arduino IDE without the Arduino core initialization
simply by defining your own main():

#include <util/delay.h>

int main(void)
{
    DDRD |= _BV(PD2);        // PD2 as output
    for (;;) {
        PORTD |= _BV(PD2);   // PD2 high
        PORTD &= ~_BV(PD2);  // PD2 low
        _delay_us(0.625);    // 10 CPU cycles, loop time = 16 cycles
    }
}

Notice the extra delay: without it, the loop would complete in 6 CPU
cycles (2 per port access, 2 more to loop back). Not doing the Arduino
core initialization means you have no timekeeping and no analogRead()
or analogWrite(). Other Arduino functions should work normally but
some, like Serial.begin() will bring their own interrupts.

Disable interrupts

As suggested by Majenko, this may be the simplest way to have a steady
waveform:

void setup()
{
    pinMode(2, OUTPUT);
    noInterrupts();
}

void loop()
{
    PORTD |= _BV(PD2);   // PD2 high
    PORTD &= ~_BV(PD2);  // PD2 low
}

Without interrupts, you have no timekeeping, no serial communications
and, obviously, no attachInterrupt(). Most other Arduino functions
should work.

Use a hardware timer

This allows you to generate the signal without relying on the CPU. You
can keep interrupts enabled and do other work in the program while the
waveform goes undisturbed. The simplest way to generate such a waveform
is with analogWrite(). The resulting frequency is quite low though,
like 0.5 to 1 kHz. If you want 1 MHz, you will have to
configure the timer the hard way. For example:

void setup()
{
    DDRD |= _BV(PD3);     // OC2B = PD3 as output
    OCR2A = 15;           // period = 16 clock cycles
    OCR2B = 1;            // high during 2 clock cycles
    TCCR2A = _BV(COM2B1)  // non-inverting PWM
           | _BV(WGM20)   // fast PWM, TOP = OCR2A
           | _BV(WGM21);  // ditto
    TCCR2B = _BV(WGM22)   // ditto
           | _BV(CS20);   // clock at f_CPU
}

void loop() { }

The output is on pin PD3 = digital 3. This configuration will disable
analogWrite() on pins 3 (PD3) and 11 (PB3).


Nothing is working even though every thing is right & it is new? I have bought a new 'SunFounder Arduino uno R3' and started learning, the first lesson was 'Blinking LED' of course.

I have done it all, connected Jumper-Wires and the Sensor and the LED light, I wrote the code:

const int ledPin = 9;
void setup()
{
   pinMode(ledPin,OUTPUT);
}
void loop()
{
   digitalWrite(ledPin,HIGH);
   delay(500);
   digitalWrite(ledPin,LOW);
   delay(500);
}

BUT NOTHING HAPPENS !!!, I checked out every thing over and over, it just does not work ???
Every thing is well about the board and the UNO R3 it is new.
I have checked the code and the connections and checked the Device Manager to know that the serial port of the arduino is 'COM3'...
I dont know what is wrong with it ?!!

In these cases it helps to break down the problem in pieces.

If the internal LED on pin 13 blinks with your code it means that the software side is OK so far (code, Arduino type, compiling, uploading etc), so I suggest looking at the physical side of things.

Do you have a multimeter available? If so, connect it between pin 13 and ground and it should show you if the output works.

Finally, is the LED working? When you connect it between 5V and GND (with a resistor!) it should light up.


How to wire Christmas lights with LEDs to use for Arduino Project? First things first, I am new here and this is my first post. So if this is in the wrong place I apologize and please just let me know.

I am a programmer that is getting into working with an Arduino compatible board, so my questions are 99% of the time with the hardware side and not the software side.

I just went through a tutorial on how to connect LEDs in parallel to a shift register so that I can control each LED individually.

My project goal is to make a Christmas house for a family member that will use some predefined songs to blink the lights to. So what I am actually looking for suggestions for is how to make a string of LEDs (5mm) that I can hook up to a small house without it looking messy. I was thinking I could maybe use 2 wires to run along the + and - of all the LEDs and then maybe there is some kind of connector I can use to split the 8 LEDs off to their respected hookups on the shift register.

Any good ways of doing this and keeping the metal unexposed?

I thank you in advance for your answers and your time!

Here is a string of Stripleds operated from a CPU 12V supply with built-in double-sided tape under the hand rail in one of my homes. Red downstairs and blue upstairs.

Now define your input and output attributes to modulate the current.


lcd has no contrast pin i just bought this lcd. I connected all pins as discripted on this datasheet (Page 8). However i noticed that there is no pin to control the contrast. I also didin't get the display to run yet.

Might that be a problem?

edit: here is the code...

#define RST 3
#define CE 2
#define DC 4
#define DIN 6
#define CLK 5

void LcdWriteCmd(byte cmd)
{
digitalWrite(DC, HIGH); //DC pin is low for commands
digitalWrite(CE, HIGH);
shiftOut(DIN, CLK, MSBFIRST, cmd); //transmit serial data
digitalWrite(CE, LOW);
}

void setup()
{
pinMode(RST, OUTPUT);
pinMode(CE, OUTPUT);
pinMode(DC, OUTPUT);
pinMode(DIN, OUTPUT);
pinMode(CLK, OUTPUT);
digitalWrite(RST, LOW);
digitalWrite(RST, HIGH);
LcdWriteCmd(0xAE); // LCD set display enabled
LcdWriteCmd(0x21); // LCD set power COntrol
LcdWriteCmd(0x14); // LCD bias mode 1:40
LcdWriteCmd(0xA2); // LCD basic commands
// LcdWriteCmd(0xA9); // LCD all segments on
}

void loop()
{
}

I think your commands are a little wrong. Let's look at them:

LcdWriteCmd(0xAE); // LCD set display enabled

0xAE is 0b10101110. In the datasheet the matching command is 1010111# where # is display on (1) or off (0), so 0xAE is actually display disabled. Changing it to 0xAF instead, so bit 0 is 1, should enable the display.

LcdWriteCmd(0x21); // LCD set power COntrol

0x21 is 0b00100001. That command is 00100### where ### is the VLCD resistor ratio. That is being set to 2/8. ((# + 1) / 8).

LcdWriteCmd(0x14); // LCD bias mode 1:40

0x14 is 0b00010100, which is command 0001#### which sets the column address MSB. Quite why you're doing that I don't know, but that command has nothing to do with bias mode...

LcdWriteCmd(0xA2); // LCD basic commands

No, 0xA2 / 0xA3 sets the bias ratio set, which selects the bias from one of two groups of biases depending on the current duty. This is the default value.

So not only are you not configuring the screen correctly, but you aren't even then trying to put anything on the screen to see if it's working or not.

I suggest you work from the provided example code:

http://www.buydisplay.com/download/democode/ERC12864-655_DemoCode.txt

The "Initial" function sets the sequence of operations:

SET_ADC();
CLEAR_SHL();
CLEAR_BIAS();
Power_Control(0x07);
Regulor_Resistor_Select(0x06);
Set_Contrast_Control_Register(Contrast_level);
Initial_Dispay_Line(0x00);
DISPLAY_ON();

The main commands are defined at the top of the file:

#define DISPLAY_ON()           Write_Instruction(0xaf)   //  Display on
#define DISPLAY_OFF()          Write_Instruction(0xae)   //  Display off
#define SET_ADC()              Write_Instruction(0xa1)   //  Reverse disrect (SEG131-SEG0)
#define CLEAR_ADC()            Write_Instruction(0xa0)   //  Normal disrect (SEG0-SEG131)
#define REVERSE_DISPLAY_ON()   Write_Instruction(0xa7)   //  Reverse display : 0 illuminated
#define REVERSE_DISPLAY_OFF()  Write_Instruction(0xa6)   //  Normal display : 1 illuminated
#define ENTIRE_DISPLAY_ON()    Write_Instruction(0xa5)   //  Entire dislay   Force whole LCD point
#define ENTIRE_DISPLAY_OFF()   Write_Instruction(0xa4)   //  Normal display
#define SET_BIAS()             Write_Instruction(0xa3)   //  bias 1   1/7 bais
#define CLEAR_BIAS()           Write_Instruction(0xa2)   //  bias 0   1/9 bais
#define RESET()                Write_Instruction(0xe2)  //   system reset
#define SET_SHL()              Write_Instruction(0xc8)   // SHL 1,COM63-COM0
#define CLEAR_SHL()            Write_Instruction(0xc0)   // SHL 0,COM0-COM63

The more complex ones are simple enough - just ORing the provided parameter with the base command. For example Power_Control() just does:

Write_Instruction((0x28|vol));

I am sure you can find (and decipher) the rest of the commands to initialize the screen properly.